问:
How do I get rental users in SQL without displaying what has already been returned
I have a 3 tables database. This is a DVD rental database.

I would like to know what DVDs are currently rented to users. I use PL/SQL.

What I can't resolve is to keep the returned DVDs from showing up, especially if the same user has taken out the same DVD again.

```<code>  User Table:      DVD Table:                            Rent table:
| ID | Name  |   | ID | Name  |   | ID | USER_ID | DVD_ID | RENT_RETURN | Rent_RETURN_DATE |
| -- | ----- |   | -- | ----- |   | -- | ------- | ------ | ----------- | ---------------- |
| 1  | USER1 |   | 1  | DVD1  |   | 1  |    1    |    1   |      -1     |     2020.01.01   |
| 2  | USER2 |   | 2  | DVD2  |   | 2  |    1    |    1   |       1     |     2020.02.01   |
| 3  | USER3 |   | 3  | DVD3  |   | 3  |    1    |    1   |      -1     |     2020.03.01   |
| 4  | USER4 |   | 4  | DVD4  |   | 4  |    1    |    2   |      -1     |     2020.04.01   |
                                  | 5  |    2    |    3   |      -1     |     2020.05.01   |
                                  | 6  |    3    |    4   |      -1     |     2020.06.01   |
                                  | 7  |    3    |    2   |      -1     |     2020.07.01   |
                                  | 8  |    3    |    4   |       1     |     2020.08.01   |
</code>```

What I want to reach:

```<code>| USER_NAME | DVD_NAME |  RENT_DATE |
| --------- | -------- | ---------- |
|     1     |    1     | 2020.03.01 |
|     1     |    2     | 2020.04.01 |
|     2     |    3     | 2020.05.01 |
|     3     |    2     | 2020.07.01 |
</code>```

I tried this but yes it's not enough:

```<code>SELECT U.NAME, D.NAME, R.RENT_RETURN_DATE
FROM USER U, DVD D, RENT R
WHERE U.ID = R.USER_ID
AND D.ID = R.DVD_ID
AND R.RENT_RETURN = 1;
</code>```

Thanks in advance for your help!

答:
SELECT user_name, dvd_name, rent_return_date
FROM (SELECT ROW_NUMBER() OVER
(PARTITION BY user_id, dvd_id
ORDER BY rent_return_date DESC) AS rn,
u.name AS user_name, d.name AS dvd_name, r.*
FROM rent r
JOIN "user" u
ON r.user_id = u.id
JOIN dvd d
ON r.dvd_id = d.id
WHERE rent_return = -1)
WHERE rn = 1</p>

Body:
I have a 3 tables database. This is a DVD rental database.

I would like to know what DVDs are currently rented to users. I use PL/SQL.

What I can't resolve is to keep the returned DVDs from showing up, especially if the same user has taken out the same DVD again.

  User Table:      DVD Table:                            Rent table:
| ID | Name  |   | ID | Name  |   | ID | USER_ID | DVD_ID | RENT_RETURN | Rent_RETURN_DATE |
| -- | ----- |   | -- | ----- |   | -- | ------- | ------ | ----------- | ---------------- |
| 1  | USER1 |   | 1  | DVD1  |   | 1  |    1    |    1   |      -1     |     2020.01.01   |
| 2  | USER2 |   | 2  | DVD2  |   | 2  |    1    |    1   |       1     |     2020.02.01   |
| 3  | USER3 |   | 3  | DVD3  |   | 3  |    1    |    1   |      -1     |     2020.03.01   |
| 4  | USER4 |   | 4  | DVD4  |   | 4  |    1    |    2   |      -1     |     2020.04.01   |
                                  | 5  |    2    |    3   |      -1     |     2020.05.01   |
                                  | 6  |    3    |    4   |      -1     |     2020.06.01   |
                                  | 7  |    3    |    2   |      -1     |     2020.07.01   |
                                  | 8  |    3    |    4   |       1     |     2020.08.01   |

What I want to reach:

| USER_NAME | DVD_NAME |  RENT_DATE |
| --------- | -------- | ---------- |
|     1     |    1     | 2020.03.01 |
|     1     |    2     | 2020.04.01 |
|     2     |    3     | 2020.05.01 |
|     3     |    2     | 2020.07.01 |

I tried this but yes it's not enough:

SELECT U.NAME, D.NAME, R.RENT_RETURN_DATE
FROM USER U, DVD D, RENT R
WHERE U.ID = R.USER_ID
AND D.ID = R.DVD_ID
AND R.RENT_RETURN = 1;

Thanks in advance for your help!


来源: stackexchange

问:
Difference between await Task and await Func<Task>()
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

```<code>static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}
</code>```

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10
```
<p>The output of <code>Task2()</code>:</p>
<pre class="lang-none prettyprint-override"><code>-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------
</code>```

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

```<code>static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}
</code>```

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------
```
<p>UPDATE2:
I tried to minimal the example but the following code does not have this problem.</p>
<pre class="lang-c# prettyprint-override"><code>var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);
</code>```

答:
This question essentially boils down to the difference between calling

```<code>public Task MyMethod();
</code>```

and calling

```<code>public void MyMethod()
</code>```

using Task.Run. The essential difference is that the second example will explicitly be run on a background thread. The first example will run on the current thread up until the first await. At this point it may continue, or may schedule a 'continuation' at a later time. This continuation will be run on the same synchronization context as the calling thread, this means that in UI programs it will run on the UI thread if called from a UI thread.

For a console program like yours, it will be little practical difference since one of the first operations will be a Task.Delay, and since you do not have a UI, it will run the continuation on a thread pool thread.

ContentLicense: CC BY-SA 4.0

Body:
I have a program which needs to run a number of async tasks in parallel. The main difference between two implements, Task1() and Task2():

Task1() saves the FTask of type Func<Task> and later await Task.WhenAny(FTask()),

Task2() saves the Task produced by Task.Run() and later await Task.WhenAny(Task).

I think they should be equivalent, but Task1() does not work properly, however Task2() does work.

The flow of this program is:
If there are available task contexts in the free queue, dequeue one and setup it up with an async task; when async task finished put the context back to the free queue.

The problem is Task1() which saves Func<Task> does not work, it seems the async task has more than one instances running.

The complete code is:

static async Task Task1()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task1 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.FTask = async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            };

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.FTask()));
    }

    await Task.WhenAll(taskPool.Select(x => x.FTask()));
    Console.WriteLine($"-------- Task1 finished --------");
}

static async Task Task2()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    int ticket = 0;

    Console.WriteLine($"-------- Task2 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = Task.Run(async () =>
            {
                Console.WriteLine($"[{x.Token}] start");
                await Task.Delay(x.Delay1);

                Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
                while (ticket != x.Token)
                {
                    await Task.Yield(); // yield and wait other task increases the ticket
                }

                Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
                await Task.Delay(x.Delay2);
                Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
                ticket++;

                qFree.Enqueue(x);
            });

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task2 finished --------");
}

public class TaskCtx
{
    public int Token;
    public int Delay1;
    public int Delay2;
    public Func<Task> FTask;
    public Task Task;

    public TaskCtx()
    {
        FTask = async () => await Task.CompletedTask;
        Task = Task.CompletedTask;
    }
}

The output of Task1():

-------- Task1 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[0] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1   <-- [1] is running and got the ticket
[4] submit
[4] start
[1] start               <-- another [1] starts ???
[2] start
[3] start
[2] wait ticket: 1
[1] wait ticket: 1
[1] acquire ticket: 1
[4] wait ticket: 1
[3] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[2] acquire ticket: 2
[1] release ticket: 2
[3] acquire ticket: 3
[3] acquire ticket: 3
[5] submit
[6] submit
[4] start
[6] start
[2] start
[3] start
[2] wait ticket: 3
[4] wait ticket: 3
[6] wait ticket: 3
[3] wait ticket: 3
[3] acquire ticket: 3
[2] release ticket: 3
[4] acquire ticket: 4
[2] release ticket: 3
[4] acquire ticket: 4
[3] release ticket: 5
[6] acquire ticket: 6
[3] release ticket: 5
[3] release ticket: 7
[4] release ticket: 8
[4] release ticket: 8
[6] release ticket: 10

The output of Task2():

-------- Task2 start --------
[0] submit
[1] submit
[2] submit
[3] submit
[0] start
[1] start
[2] start
[3] start
[2] wait ticket: 0
[1] wait ticket: 0
[3] wait ticket: 0
[0] wait ticket: 0
[0] acquire ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] submit
[4] start
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] submit
[5] start
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task2 finished --------

UPDATE:
I make another implement, by use a normal async function, not anonymous function:

static async Task Task3()
{
    int qd = 4;
    var taskPool = Enumerable.Range(0, qd).Select(n => new TaskCtx()).ToArray();
    Queue<TaskCtx> qFree = new Queue<TaskCtx>(taskPool);
    Random r = new Random();

    long segs = 7, submit = 0;
    int token = 0;
    Ticket ticket = new Ticket(0);

    Console.WriteLine($"-------- Task3 start --------");

    while (submit < segs)
    {
        if (qFree.Count > 0)
        {
            var x = qFree.Dequeue();
            x.Token = token++;
            x.Delay1 = r.Next(10, 20);
            x.Delay2 = r.Next(30, 50);

            x.Task = RunTask3Async(x, ticket, qFree);

            Console.WriteLine($"[{x.Token}] submit");
            submit++;
        }
        else await Task.WhenAny(taskPool.Select(x => x.Task));
    }

    await Task.WhenAll(taskPool.Select(x => x.Task));
    Console.WriteLine($"-------- Task3 finished --------");
}

static async Task RunTask3Async(TaskCtx x, Ticket ticket, Queue<TaskCtx> qFree)
{
    Console.WriteLine($"[{x.Token}] start");
    await Task.Delay(x.Delay1);

    Console.WriteLine($"[{x.Token}] wait ticket: {ticket}");
    while (ticket.ticket != x.Token)
    {
        await Task.Yield(); // yield and wait other task increases the ticket
    }

    Console.WriteLine($"[{x.Token}] acquire ticket: {ticket}");
    await Task.Delay(x.Delay2);
    Console.WriteLine($"[{x.Token}] release ticket: {ticket}");
    ticket.ticket++;

    qFree.Enqueue(x);
}

public class Ticket
{
    public int ticket;

    public Ticket(int t)
    {
        ticket = t;
    }

    public override string ToString()
    {
        return $"{ticket}";
    }
}

Task3() also works, the output is:

-------- Task3 start --------
[0] start
[0] submit
[1] start
[1] submit
[2] start
[2] submit
[3] start
[3] submit
[0] wait ticket: 0
[3] wait ticket: 0
[0] acquire ticket: 0
[2] wait ticket: 0
[1] wait ticket: 0
[0] release ticket: 0
[1] acquire ticket: 1
[4] start
[4] submit
[4] wait ticket: 1
[1] release ticket: 1
[2] acquire ticket: 2
[5] start
[5] submit
[5] wait ticket: 2
[2] release ticket: 2
[3] acquire ticket: 3
[6] start
[6] submit
[6] wait ticket: 3
[3] release ticket: 3
[4] acquire ticket: 4
[4] release ticket: 4
[5] acquire ticket: 5
[5] release ticket: 5
[6] acquire ticket: 6
[6] release ticket: 6
-------- Task3 finished --------

UPDATE2:
I tried to minimal the example but the following code does not have this problem.

var FTasks = Enumerable.Range(0, 8).Select(i => async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
}).ToArray();

await Task.WhenAll(FTasks.Select(x => x()));

Console.WriteLine("----------------");

var Tasks = Enumerable.Range(0, 8).Select(i => Task.Run(async () =>
{
    Console.WriteLine($"[{i}] start");
    await Task.Delay(i);
    Console.WriteLine($"[{i}] end");
})).ToArray();

await Task.WhenAll(Tasks);

Body:
This question essentially boils down to the difference between calling

public Task MyMethod();

and calling

public void MyMethod()

using Task.Run. The essential difference is that the second example will explicitly be run on a background thread. The first example will run on the current thread up until the first await. At this point it may continue, or may schedule a 'continuation' at a later time. This continuation will be run on the same synchronization context as the calling thread, this means that in UI programs it will run on the UI thread if called from a UI thread.

For a console program like yours, it will be little practical difference since one of the first operations will be a Task.Delay, and since you do not have a UI, it will run the continuation on a thread pool thread.


问:
Javascript Textbox "Scrubber"
I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.

I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be entered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.

答:
Use regular expressions.

html:

```<code><input type="text" id="code" />
<input type="button" value="test" onclick="alert(checkCode())" />
</code>```

javascript:

```<code>function checkCode(){
var code = document.getElementById('code').value;
return code.match(/\d+ \w+ \w+ \[\d+ \w+\]/)!=null ? true : false;
}
</code>```

http://gskinner.com/RegExr/ is very helpful with regular expressions.

When you say "exactly this format", you have to understand that we have no clue what you mean. There are an infinite number of patterns that could be used to describe your example. The regular expression above will match if the code has a string of numbers, then a word, then another word, then an opening bracket, then a string of numbers, then a word, then a closing bracket.

ContentLicense: CC BY-SA 3.0

Title: Javascript Textbox "Scrubber"

Body:
Use regular expressions.

html:

<input type="text" id="code" />
<input type="button" value="test" onclick="alert(checkCode())" />

javascript:

function checkCode(){
var code = document.getElementById('code').value;
return code.match(/\d+ \w+ \w+ \[\d+ \w+\]/)!=null ? true : false;
}

http://gskinner.com/RegExr/ is very helpful with regular expressions.

When you say "exactly this format", you have to understand that we have no clue what you mean. There are an infinite number of patterns that could be used to describe your example. The regular expression above will match if the code has a string of numbers, then a word, then another word, then an opening bracket, then a string of numbers, then a word, then a closing bracket.


问:
Add Extra Text to Barcode Using Treepoem and BWIPP (Python)
I am generating barcodes using treepoem (and thus BWIPP), I want to have barcodes with their number below and other additional text above. I am trying to keep this all in the eps file generation rather than converting/editing in any other form as this is important for what I am doing with them after generating.

Below is my code as it stands (I have tried a variety of different options from the docs including alttext, but have been unsuccessful). I am using Python 3.8.2 and Treepoem 3.10.0.

```<code>import treepoem # for barcode generation

def generate_rlb_barcode(barcode_type, barcode_data, image_name):

    eps_image = treepoem.generate_barcode(barcode_type, barcode_data, options={'includetext': True})
    print("image generation complete.")
    eps_image.convert('L')
    print("image converted to monochrome.")
    eps_image.save(image_name)
    print("image saved as " + str(image_name))

def main():
    barcode_image_name = 'test_img'
    generate_rlb_barcode('upca', '123456059973', (barcode_image_name + ".eps"))

main()
</code>```

答:
Install treepoem package:

```<code>pip install treepoem
# or
python -m pip install treepoem
</code>```

Run this code

```<code>import treepoem
image = treepoem.generate_barcode(
    barcode_type="code128",  # One of the BWIPP supported codes.
    data="Yout text-978316148fsd4100",
    options= {"includetext": True}
)
image.convert("1").save("output_qrcode_or_barcode.png")
</code>```

Body:
I am generating barcodes using treepoem (and thus BWIPP), I want to have barcodes with their number below and other additional text above. I am trying to keep this all in the eps file generation rather than converting/editing in any other form as this is important for what I am doing with them after generating.

Below is my code as it stands (I have tried a variety of different options from the docs including alttext, but have been unsuccessful). I am using Python 3.8.2 and Treepoem 3.10.0.

import treepoem # for barcode generation

def generate_rlb_barcode(barcode_type, barcode_data, image_name):

    eps_image = treepoem.generate_barcode(barcode_type, barcode_data, options={'includetext': True})
    print("image generation complete.")
    eps_image.convert('L')
    print("image converted to monochrome.")
    eps_image.save(image_name)
    print("image saved as " + str(image_name))

def main():
    barcode_image_name = 'test_img'
    generate_rlb_barcode('upca', '123456059973', (barcode_image_name + ".eps"))

main()

Body:
Install treepoem package:

pip install treepoem
# or
python -m pip install treepoem

Run this code

import treepoem
image = treepoem.generate_barcode(
    barcode_type="code128",  # One of the BWIPP supported codes.
    data="Yout text-978316148fsd4100",
    options= {"includetext": True}
)
image.convert("1").save("output_qrcode_or_barcode.png")


问:
Flutter hide keyboard when icon keyboard is shown
When I click the emoji icon, the emoji keyboard is shown. But then I click on the textfield without closing the emoji keyboard, the text keyboard is displayed on the bottom of the emoji keyboard like the picture above:

What I want is whenever the emoji keyboard is shown, then the text keyboard is hidden. And when the text keyboard is shown, then the emoji keyboard is hidden.

Here is my code :

```<code>bool emojiShowing = false;

  _onEmojiSelected(Emoji emoji) {
    inputTextController
      ..text += emoji.emoji
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: inputTextController.text.length));
  }

  _onBackspacePressed() {
    inputTextController
      ..text = inputTextController.text.characters.skipLast(1).toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: inputTextController.text.length));
  }

   final _focusNode = FocusNode();
   final _textFieldKey = UniqueKey();
</code>```

The textfield controller:

```<code>TextEditingController inputTextController = new TextEditingController();
</code>```

The icon button code:

```<code>                 IconButton(
                        onPressed: () {
                          setState(() {
                            emojiShowing = !emojiShowing;
                            if (emojiShowing) {
                              _focusNode.unfocus();
                            }
                            else {
                              FocusScope.of(context).requestFocus(_focusNode);
                            }
                          });
                        },
                        icon: Icon(
                          Icons.tag_faces,
                          color: Colors.grey,
                        ),
                      ),
</code>```

And the emoji code:

```<code>      Offstage(
          offstage: !emojiShowing,
          child: SizedBox(
            height: 250,
            child: EmojiPicker(
                onEmojiSelected: (Category category, Emoji emoji) {
                  _onEmojiSelected(emoji);
                },
                onBackspacePressed: _onBackspacePressed,
                config: Config(
                    columns: 7,
                    // Issue: https://github.com/flutter/flutter/issues/28894
                    emojiSizeMax: 32 * (Platform.isIOS ? 1.30 : 1.0),
                    verticalSpacing: 0,
                    horizontalSpacing: 0,
                    initCategory: Category.SMILEYS,
                    bgColor: Colors.white,
                    indicatorColor: Colors.blue,
                    iconColor: Colors.grey,
                    iconColorSelected: Colors.blue,
                    progressIndicatorColor: Colors.blue,
                    backspaceColor: Colors.blue,
                    skinToneDialogBgColor: Colors.white,
                    skinToneIndicatorColor: Colors.grey,
                    enableSkinTones: true,
                    showRecentsTab: true,
                    recentsLimit: 28,
                    noRecentsText: 'No Recents',
                    noRecentsStyle: const TextStyle(
                        fontSize: 20, color: Colors.black26),
                    tabIndicatorAnimDuration: kTabScrollDuration,
                    categoryIcons: const CategoryIcons(),
                    buttonMode: ButtonMode.MATERIAL)),
          ),
        ),
</code>```

Added key: _textFieldKey, to the TextField too.

Is there any solution?

答:
You can use
final _focusNode = FocusNode();

set the focus node to the Textfield widget focusNode: _focusNode, and you can use _focusNode.unfocus() to loose focus when the EmojiPicker is open and FocusScope.of(context).requestFocus(_focusNode); to regain focus to the TextInput

Body:
When I click the emoji icon, the emoji keyboard is shown. But then I click on the textfield without closing the emoji keyboard, the text keyboard is displayed on the bottom of the emoji keyboard like the picture above:

What I want is whenever the emoji keyboard is shown, then the text keyboard is hidden. And when the text keyboard is shown, then the emoji keyboard is hidden.

Here is my code :

bool emojiShowing = false;

  _onEmojiSelected(Emoji emoji) {
    inputTextController
      ..text += emoji.emoji
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: inputTextController.text.length));
  }

  _onBackspacePressed() {
    inputTextController
      ..text = inputTextController.text.characters.skipLast(1).toString()
      ..selection = TextSelection.fromPosition(
          TextPosition(offset: inputTextController.text.length));
  }

   final _focusNode = FocusNode();
   final _textFieldKey = UniqueKey();

The textfield controller:

TextEditingController inputTextController = new TextEditingController();

The icon button code:

                 IconButton(
                        onPressed: () {
                          setState(() {
                            emojiShowing = !emojiShowing;
                            if (emojiShowing) {
                              _focusNode.unfocus();
                            }
                            else {
                              FocusScope.of(context).requestFocus(_focusNode);
                            }
                          });
                        },
                        icon: Icon(
                          Icons.tag_faces,
                          color: Colors.grey,
                        ),
                      ),

And the emoji code:

      Offstage(
          offstage: !emojiShowing,
          child: SizedBox(
            height: 250,
            child: EmojiPicker(
                onEmojiSelected: (Category category, Emoji emoji) {
                  _onEmojiSelected(emoji);
                },
                onBackspacePressed: _onBackspacePressed,
                config: Config(
                    columns: 7,
                    // Issue: https://github.com/flutter/flutter/issues/28894
                    emojiSizeMax: 32 * (Platform.isIOS ? 1.30 : 1.0),
                    verticalSpacing: 0,
                    horizontalSpacing: 0,
                    initCategory: Category.SMILEYS,
                    bgColor: Colors.white,
                    indicatorColor: Colors.blue,
                    iconColor: Colors.grey,
                    iconColorSelected: Colors.blue,
                    progressIndicatorColor: Colors.blue,
                    backspaceColor: Colors.blue,
                    skinToneDialogBgColor: Colors.white,
                    skinToneIndicatorColor: Colors.grey,
                    enableSkinTones: true,
                    showRecentsTab: true,
                    recentsLimit: 28,
                    noRecentsText: 'No Recents',
                    noRecentsStyle: const TextStyle(
                        fontSize: 20, color: Colors.black26),
                    tabIndicatorAnimDuration: kTabScrollDuration,
                    categoryIcons: const CategoryIcons(),
                    buttonMode: ButtonMode.MATERIAL)),
          ),
        ),

Added key: _textFieldKey, to the TextField too.

Is there any solution?


问:
What Gitlab tool used for code coverage reports?
Instead of using JaCoCo, I was told, that there would be an internal Gitlab tool, where I can create test coverage reports?

I do not want to use JaCoCo.

I am not interessted in any vizualization plugin within Gitlab.

I would like to generate a xml/html file(s) with e.g. bar graphs, what can be emailed and opened externally.

I couldn't find anything in the Gitlab dashboard menu. The project is a Android App Kotlin project.

答:
Our approach is the following.
have to tell Gitlab where your coverage report is, for example we have this setup for a java unit test report "jacoco.xml":

```<code> Unit Test:
      stage: pruebas
      script:
        - echo "Iniciar Pruebas"
        - mvn $MAVEN_CLI_OPTS test
      artifacts:
        when: always
        reports:
          junit:
            - target/surefire-reports/*Test.xml
            - target/failsafe-reports/*Test.xml
          cobertura: target/site/jacoco/jacoco.xml
</code>```

Our summary in Gitlab :

Unit Test Detaills:

The key is your "jacoco.xml".

Body:
Our approach is the following.
have to tell Gitlab where your coverage report is, for example we have this setup for a java unit test report "jacoco.xml":

 Unit Test:
      stage: pruebas
      script:
        - echo "Iniciar Pruebas"
        - mvn $MAVEN_CLI_OPTS test
      artifacts:
        when: always
        reports:
          junit:
            - target/surefire-reports/*Test.xml
            - target/failsafe-reports/*Test.xml
          cobertura: target/site/jacoco/jacoco.xml

Our summary in Gitlab :

Unit Test Detaills:

The key is your "jacoco.xml".


问:
Set up a number of categories to display on a page
I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages

```<code>$categories = get_categories();
foreach($categories as $category) {
   echo '<div class="col-md-4"><a href="' .
    get_category_link($category->term_id) . '">' . $category->name
  . '</a></div>';
}?>
</code>```

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations

答:
```<code>$page=$_GET['page_number'];

$categories = get_categories();

$data=array_chunk($categories ,3);

$paginations=count($data); // use loop for paginations in html page

foreach($data[$page] as $category) {
   echo '<div class="col-md-4"><a href="' .
    get_category_link($category->term_id) . '">' . $category->name
  . '</a></div>';
}
</code>```

Body:
I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages

$categories = get_categories();
foreach($categories as $category) {
   echo '
term_id) . '">' . $category->name
  . '
';
}?>

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations


问:
Setting airplane mode does not completely work
I've written the code below to set the phone into airplane mode to save power. The devices is being used as a WiFi-Hotspot to relay data from some sensors in a village in Indonesia. The sensors send their data at the same time so I just need to come out of airplane mode for five minutes at midnight and then reenter airplane mode.

The problem is the cellular radio is not shut off and the airplane icon does not appear. Though the the phone reports its status as airplane_mode on, it is still possible to call it. Other widgets in the marketplace seem to fare no better. I've tried "Airplane Mode Wi-Fi Tool". It too can not get the airplane icon to appear nor disable cell radio. When watching LogCat while using the device settings to go to Airplane mode, I can see that much more is happening than when trying from the program.

If I load my program on a Droid, this code works as expected. AIRPLANE_MODE_RADIOS is set to cell, bluetooth, wifi.

The offending device is a Samsung Galaxy 5, I5500 tested with:

-Froyo 2.2 build FROYO.UYJP2
-Froyo 2.2.1 build FROYO.UYJPE

One interesting side note: if I programmatically set airplane mode and then power cycle the device, it comes up in full airplane mode, rejects incoming calls etc.

Do others have similar stories with this or other devices? Is there a way to specifically turn off cell only?

```<code>public static void setAirplaneMode(Context context, boolean status) {

    boolean isAM = Settings.System.getInt(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_ON, 0) != 0;

    String radios = Settings.System.getString(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_RADIOS);

    //This line is reporting all radios affected but annunciator does not seem to think so. Does not show airplane
    Wake.logger("Airplane mode is: " + isAM + " changing to " + status + " For radios: " + radios, false);

    // It appears Airplane mode should only be toggled. Don't reset to
    // current state.
    if (isAM && !status) {
        Settings.System.putInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0);
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", 0);
        context.sendBroadcast(intent);
        return;
    }
    if (!isAM && status) {
        Settings.System.putInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 1);
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", 1);
        context.sendBroadcast(intent);
        return;
    }
}
</code>```

答:
Classic bit twister error. The extra data argument in the broadcast intent needed to be true/false, not 1/0. Ugh!!!

```<code>    intent.putExtra("state", true);  //Not 1!!
</code>```

One phone worked another didn't. Now both do.

Body:
I've written the code below to set the phone into airplane mode to save power. The devices is being used as a WiFi-Hotspot to relay data from some sensors in a village in Indonesia. The sensors send their data at the same time so I just need to come out of airplane mode for five minutes at midnight and then reenter airplane mode.

The problem is the cellular radio is not shut off and the airplane icon does not appear. Though the the phone reports its status as airplane_mode on, it is still possible to call it. Other widgets in the marketplace seem to fare no better. I've tried "Airplane Mode Wi-Fi Tool". It too can not get the airplane icon to appear nor disable cell radio. When watching LogCat while using the device settings to go to Airplane mode, I can see that much more is happening than when trying from the program.

If I load my program on a Droid, this code works as expected. AIRPLANE_MODE_RADIOS is set to cell, bluetooth, wifi.

The offending device is a Samsung Galaxy 5, I5500 tested with:

-Froyo 2.2 build FROYO.UYJP2
-Froyo 2.2.1 build FROYO.UYJPE

One interesting side note: if I programmatically set airplane mode and then power cycle the device, it comes up in full airplane mode, rejects incoming calls etc.

Do others have similar stories with this or other devices? Is there a way to specifically turn off cell only?

public static void setAirplaneMode(Context context, boolean status) {

    boolean isAM = Settings.System.getInt(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_ON, 0) != 0;

    String radios = Settings.System.getString(context.getContentResolver(),
            Settings.System.AIRPLANE_MODE_RADIOS);

    //This line is reporting all radios affected but annunciator does not seem to think so. Does not show airplane
    Wake.logger("Airplane mode is: " + isAM + " changing to " + status + " For radios: " + radios, false);

    // It appears Airplane mode should only be toggled. Don't reset to
    // current state.
    if (isAM && !status) {
        Settings.System.putInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0);
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", 0);
        context.sendBroadcast(intent);
        return;
    }
    if (!isAM && status) {
        Settings.System.putInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 1);
        Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
        intent.putExtra("state", 1);
        context.sendBroadcast(intent);
        return;
    }
}

Body:
Classic bit twister error. The extra data argument in the broadcast intent needed to be true/false, not 1/0. Ugh!!!

    intent.putExtra("state", true);  //Not 1!!

One phone worked another didn't. Now both do.


问:
Function argument evaluation and side effects
The C++20 standard says in Function Call, 7.6.1.3/8:

The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.

Indeterminately sequenced (as opposed to unsequenced) ensures that side effects affecting the same memory region are not undefined behavior. Cppreference gives the following examples:

```
f(i = -2, i = -2); // undefined behavior <b>until C++17</b>
f(++i, ++i);       // undefined behavior <b>until C++17,</b> unspecified after C++17
```

The change in C++17 doesn't seem to be in the quoted  section though whose wording essentially stayed the same through the centuries decades. (OK; in n3337 it is only a note.)

And a simple example elicits warnings from both gcc and clang:

```<code>void f(int fa, int fb);

void  m() // contains code calling f()
{
    int a = 11;
    f(++a, ++a);
    cout << "after f(): a=" << a << '\n';
}
</code>```
```<code><source>:6:7: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
    f(++a, ++a);
      ^    ~~
</code>```

gcc also produces unintuitive code, incrementing a twice before moving its value into both parameter registers. That contradicts my understanding of the standard wording.

Fellow stackoverflow user Davis Herring mentioned in a comment that while the initialization is sequenced, the evaluation of the argument expressions is not.

Am I misinterpreting this wording? Is cppreference wrong? Are the compilers wrong, especially gcc? What, if anything, changed in C++17 regarding specifically function parameters?

答:
If your question is whether "initialization of a parameter" involves evaluating the expression(s) that are part of its initializer... of course it does. Initializing a parameter works exactly like initializing any other object ([dcl.init]/1):

The process of initialization described in this subclause applies to all initializations regardless of syntactic context, including the initialization of a function parameter ([expr.call]), the initialization of a return value ([stmt.return]), or when an initializer follows a declarator.

Emphasis added.

The entirety of [dcl.init] describes the process of initializing objects, but in all cases, it involves evaluating the initializer expression(s). That therefore fits under the "every associated value computation and side effect" part of the rule about sequencing.

Any compiler which doesn't do this for the parameter initializer expression(s) is in error.

Compilers can warn about whatever they want. Indeed, compiler warnings are frequently code that is technically valid but unreasonable.

The main point of even changing this part of the standard is not to make trivial nonsense like f(++a, ++a) into semi-reasonable code. It's for dealing with cases where the writer of the code has no idea that the same object is being referenced in multiple places. Consider:

```<code>template<typename ...Args>
void g(Args &&args)
{
  f((++args) ...);
}
</code>```

Pre-C++17, what this code was valid depends entirely on whether the user passed two references to the same object, and a compiler could not reasonably warn about the potential problems. Post-C++17, this code is safe (modulo compiler bugs).

So giving out warnings for easily detectable confusing code is not just valid, but good.

Body:
The C++20 standard says in Function Call, 7.6.1.3/8:

The initialization of a parameter, including every associated value computation and side effect, is indeterminately sequenced with respect to that of any other parameter.

Indeterminately sequenced (as opposed to unsequenced) ensures that side effects affecting the same memory region are not undefined behavior. Cppreference gives the following examples:

f(i = -2, i = -2); // undefined behavior until C++17
f(++i, ++i);       // undefined behavior until C++17, unspecified after C++17

The change in C++17 doesn't seem to be in the quoted  section though whose wording essentially stayed the same through the centuries decades. (OK; in n3337 it is only a note.)

And a simple example elicits warnings from both gcc and clang:

void f(int fa, int fb);

void  m() // contains code calling f()
{
    int a = 11;
    f(++a, ++a);
    cout << "after f(): a=" << a << '\n';
}

<source>:6:7: warning: multiple unsequenced modifications to 'a' [-Wunsequenced]
    f(++a, ++a);
      ^    ~~

gcc also produces unintuitive code, incrementing a twice before moving its value into both parameter registers. That contradicts my understanding of the standard wording.

Fellow stackoverflow user Davis Herring mentioned in a comment that while the initialization is sequenced, the evaluation of the argument expressions is not.

Am I misinterpreting this wording? Is cppreference wrong? Are the compilers wrong, especially gcc? What, if anything, changed in C++17 regarding specifically function parameters?

Body:
If your question is whether "initialization of a parameter" involves evaluating the expression(s) that are part of its initializer... of course it does. Initializing a parameter works exactly like initializing any other object ([dcl.init]/1):

The process of initialization described in this subclause applies to all initializations regardless of syntactic context, including the initialization of a function parameter ([expr.call]), the initialization of a return value ([stmt.return]), or when an initializer follows a declarator.

Emphasis added.

The entirety of [dcl.init] describes the process of initializing objects, but in all cases, it involves evaluating the initializer expression(s). That therefore fits under the "every associated value computation and side effect" part of the rule about sequencing.

Any compiler which doesn't do this for the parameter initializer expression(s) is in error.

Compilers can warn about whatever they want. Indeed, compiler warnings are frequently code that is technically valid but unreasonable.

The main point of even changing this part of the standard is not to make trivial nonsense like f(++a, ++a) into semi-reasonable code. It's for dealing with cases where the writer of the code has no idea that the same object is being referenced in multiple places. Consider:

template<typename ...Args>
void g(Args &&args)
{
  f((++args) ...);
}

Pre-C++17, what this code was valid depends entirely on whether the user passed two references to the same object, and a compiler could not reasonably warn about the potential problems. Post-C++17, this code is safe (modulo compiler bugs).

So giving out warnings for easily detectable confusing code is not just valid, but good.


问:
Consume marvel api with dart/flutter
I'm trying to consume a Marvel API. I'm following the steps given in the Api documentation. I have no idea how to convert what I need to MD5. I know I can use crypto package, but I don't know how to start.

Here is the api documentation= https://developer.marvel.com/documentation/authorization

答:
To encrypt your String data to MD5, follow these steps:

Add this import on top of the file:

import 'package:crypto/crypto.dart';

Use this code to convert any String to MD5:

String MD5 = md5.convert(utf8.encode('your string
data')).toString().toUpperCase();

The .toUpperCase() is optional.

Title: Consume marvel api with dart/flutter


问:
How to mock keypress event on Window object with Enzyme / Jest?
I am looking for a way to test my hook for React components:

```<code>export default function useKeyUp(key: Key, onKeyUp: Function) {
    useEffect(() => {

        const handleUp = (event: KeyboardEvent) => {
            const { key: releasedKey } = event
            if (key === releasedKey) {
                if (onKeyUp) {
                    onKeyUp()
                }
            }
        }

        window.addEventListener('keyup', handleUp)

        return () => {
            window.removeEventListener('keyup', handleUp)
        }
    }, [key, onKeyUp])
}
</code>```

How can I mock / simulate event fired on the Window object in Jest / Enzyme?

答:
Since enzyme can't test react hook directly like react-hooks-testing-library. We can use the hook inside a component. Then, use mount to render the component.

Use keyboardEvent constructor to create a "keyup" event and dispatch the event via dispatchEvent web API.

E.g.

useKeyUp.ts:

```<code>import { useEffect } from 'react';

type Key = string;
export default function useKeyUp(key: Key, onKeyUp: Function) {
  useEffect(() => {
    const handleUp = (event: KeyboardEvent) => {
      const { key: releasedKey } = event;
      if (key === releasedKey) {
        if (onKeyUp) {
          onKeyUp();
        }
      }
    };

    window.addEventListener('keyup', handleUp);

    return () => {
      window.removeEventListener('keyup', handleUp);
    };
  }, [key, onKeyUp]);
}
</code>```

useKeyUp.test.tsx:

```<code>import { mount } from 'enzyme';
import React from 'react';
import useKeyUp from './useKeyUp';

describe('70938281', () => {
  test('should call onKeyUp callback', () => {
    const mOnKeyUp = jest.fn();
    function TestComp() {
      useKeyUp('s', mOnKeyUp);
      return null;
    }
    const wrapper = mount(<TestComp />);
    const keyUpEvent = new KeyboardEvent('keyup', { key: 's' });
    window.dispatchEvent(keyUpEvent);
    expect(mOnKeyUp).toBeCalledTimes(1);
    wrapper.unmount();
    window.dispatchEvent(keyUpEvent);
    expect(mOnKeyUp).toBeCalledTimes(1);
  });

  test('should NOT call onKeyUp callback', () => {
    const mOnKeyUp = jest.fn();
    function TestComp() {
      useKeyUp('s', mOnKeyUp);
      return null;
    }
    mount(<TestComp />);
    const keyUpEvent = new KeyboardEvent('keyup', { key: 'a' });
    window.dispatchEvent(keyUpEvent);
    expect(mOnKeyUp).not.toBeCalled();
  });
});
</code>```

Test result:

 PASS  stackoverflow/70938281/useKeyUp.test.tsx (8.484 s)
  70938281
    ✓ should call onKeyUp callback (29 ms)
    ✓ should NOT call onKeyUp callback (2 ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |       75 |     100 |     100 |
 useKeyUp.ts |     100 |       75 |     100 |     100 | 9
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.937 s
```
<p><code>jest.config.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: ['jest-enzyme', 'jest-extended'],
  setupFiles: ['./jest.setup.js'],
  testEnvironmentOptions: {
    enzymeAdapter: 'react16',
  },
};
</code>```

Body:
I am looking for a way to test my hook for React components:

export default function useKeyUp(key: Key, onKeyUp: Function) {
    useEffect(() => {

        const handleUp = (event: KeyboardEvent) => {
            const { key: releasedKey } = event
            if (key === releasedKey) {
                if (onKeyUp) {
                    onKeyUp()
                }
            }
        }

        window.addEventListener('keyup', handleUp)

        return () => {
            window.removeEventListener('keyup', handleUp)
        }
    }, [key, onKeyUp])
}

How can I mock / simulate event fired on the Window object in Jest / Enzyme?

Body:
Since enzyme can't test react hook directly like react-hooks-testing-library. We can use the hook inside a component. Then, use mount to render the component.

Use keyboardEvent constructor to create a "keyup" event and dispatch the event via dispatchEvent web API.

E.g.

useKeyUp.ts:

import { useEffect } from 'react';

type Key = string;
export default function useKeyUp(key: Key, onKeyUp: Function) {
  useEffect(() => {
    const handleUp = (event: KeyboardEvent) => {
      const { key: releasedKey } = event;
      if (key === releasedKey) {
        if (onKeyUp) {
          onKeyUp();
        }
      }
    };

    window.addEventListener('keyup', handleUp);

    return () => {
      window.removeEventListener('keyup', handleUp);
    };
  }, [key, onKeyUp]);
}

useKeyUp.test.tsx:

import { mount } from 'enzyme';
import React from 'react';
import useKeyUp from './useKeyUp';

describe('70938281', () => {
  test('should call onKeyUp callback', () => {
    const mOnKeyUp = jest.fn();
    function TestComp() {
      useKeyUp('s', mOnKeyUp);
      return null;
    }
    const wrapper = mount(<TestComp />);
    const keyUpEvent = new KeyboardEvent('keyup', { key: 's' });
    window.dispatchEvent(keyUpEvent);
    expect(mOnKeyUp).toBeCalledTimes(1);
    wrapper.unmount();
    window.dispatchEvent(keyUpEvent);
    expect(mOnKeyUp).toBeCalledTimes(1);
  });

  test('should NOT call onKeyUp callback', () => {
    const mOnKeyUp = jest.fn();
    function TestComp() {
      useKeyUp('s', mOnKeyUp);
      return null;
    }
    mount(<TestComp />);
    const keyUpEvent = new KeyboardEvent('keyup', { key: 'a' });
    window.dispatchEvent(keyUpEvent);
    expect(mOnKeyUp).not.toBeCalled();
  });
});

Test result:

 PASS  stackoverflow/70938281/useKeyUp.test.tsx (8.484 s)
  70938281
    ✓ should call onKeyUp callback (29 ms)
    ✓ should NOT call onKeyUp callback (2 ms)

-------------|---------|----------|---------|---------|-------------------
File         | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files    |     100 |       75 |     100 |     100 |
 useKeyUp.ts |     100 |       75 |     100 |     100 | 9
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.937 s

jest.config.js:

module.exports = {
  preset: 'ts-jest/presets/js-with-ts',
  testEnvironment: 'enzyme',
  setupFilesAfterEnv: ['jest-enzyme', 'jest-extended'],
  setupFiles: ['./jest.setup.js'],
  testEnvironmentOptions: {
    enzymeAdapter: 'react16',
  },
};


问:
Create nested object of booleans, arrays and objects from array
I am trying to create an object to satisfy the structure required by json-logic-js. An example of that structure is provided below.

The source array is made up of booleans and strings. Strings can only be OR, AND, NAND or NOR. For now am I working only with OR and AND.

The array of booleans and strings might look like the below. The values are dynamic. So the booleans can be either true or false and strings as mentioned above.

```<code>const source = [false, "OR", false, "OR", false, "AND", false, "AND", false, "OR", true]
</code>```

The grouping of this source array if it were in an if statement would I believe be as follows:

```<code>(false || false || (false && false && false) || true) // true
</code>```

And I would expect to output the following object which satifies the json-logic-js JS package:

```<code>const result = {
    'or': [
        false,
        false,
        {
            'and': [
                false,
                false,
                false,
            ]
        },
        true,
    ]
}
</code>```

I have tried recursive functions and have been playing with the .reduce() method but as have yet been unable to find a solution. I struggle creating the object as I iterate over the source array. I have searched for similar answers here on SO but none seem to want the same result object structure as I do.

答:
Try the following solution. Hopefully the code is more or less self-explanatory:

function process(arr) {
  const isBool = (x) => x === true || x === false;
  const prec = (x) => -["AND", "OR"].indexOf(x);

  // Convert infix -> postfix
  const postfix = [];
  const ops = [];
  for (const x of arr) {
    if (!isBool(x)) {
      const prev = ops[ops.length - 1];
      if (prev === undefined || prec(x) > prec(prev)) {
        ops.push(x);
      } else {
        while (ops.length > 0 && prec(x) < prec(ops[ops.length - 1])) {
          postfix.push(ops.pop());
        }
        ops.push(x);
      }
    } else {
      postfix.push(x);
    }
  }
  postfix.push(...ops.reverse());

  // Convert postfix -> output format
  const stack = [];
  for (const x of postfix) {
    if (!isBool(x)) {
      const op = x.toLowerCase();
      const prevs = [stack.pop(), stack.pop()];
      const obj = prevs.find((y) => !isBool(y) && y.hasOwnProperty(op));
      if (obj !== undefined) {
        const other = prevs.find((y) => y !== obj);
        obj[op].push(other);
        stack.push(obj);
      } else {
        stack.push({
          [op]: prevs,
        });
      }
    } else {
      stack.push(x);
    }
  }
  return stack[0];
}

console.log(JSON.stringify(process([false, "OR", false, "OR", false, "AND", false, "AND", false, "OR", true]), null, 2));```

Body:
I am trying to create an object to satisfy the structure required by json-logic-js. An example of that structure is provided below.

The source array is made up of booleans and strings. Strings can only be OR, AND, NAND or NOR. For now am I working only with OR and AND.

The array of booleans and strings might look like the below. The values are dynamic. So the booleans can be either true or false and strings as mentioned above.

const source = [false, "OR", false, "OR", false, "AND", false, "AND", false, "OR", true]

The grouping of this source array if it were in an if statement would I believe be as follows:

(false || false || (false && false && false) || true) // true

And I would expect to output the following object which satifies the json-logic-js JS package:

const result = {
    'or': [
        false,
        false,
        {
            'and': [
                false,
                false,
                false,
            ]
        },
        true,
    ]
}

I have tried recursive functions and have been playing with the .reduce() method but as have yet been unable to find a solution. I struggle creating the object as I iterate over the source array. I have searched for similar answers here on SO but none seem to want the same result object structure as I do.


问:
How to authenticate and get emails with Microsoft Graph
I am searching for solutions to authenticate with Microsoft Graph and get all my emails in Eclipse IDE. I have used the authentication method of 'Client Credentials Provider'. I am having issues with the SCOPES that need to be defined. Please find the error and my code below:</p>
```<code>package JAVA_MicrosoftGraphAPI;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.logger.DefaultLogger;
import com.microsoft.graph.logger.LoggerLevel;
import com.microsoft.graph.models.User;
import com.microsoft.graph.requests.GraphServiceClient;
import okhttp3.Request;

public class YT_Video{

    private final static String CLIENT_ID = "CLIENT_ID";
    private final static String TENANT_ID = "TENANT_ID";
    private final static String SECRET_ID = "SECRET";

    //Set the scopes for your ms-graph request
    private final static List<String> SCOPES = Arrays.asList("User.Read", "Mail.Read", "openid", "offline_access", "profile");

    public static void main(String[] args) throws Exception {
        // Create the auth provider.
        final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientId(CLIENT_ID)
                .clientSecret(SECRET_ID)
                .tenantId(TENANT_ID)
                .build();

        final TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(SCOPES, clientSecretCredential);
        System.out.println("First Step Reached. ");

        // Create default logger to only log errors
        DefaultLogger logger = new DefaultLogger();
        logger.setLoggingLevel(LoggerLevel.ERROR);

        // Build a Graph client
        GraphServiceClient<Request> graphClient = GraphServiceClient.builder()
                .authenticationProvider(tokenCredAuthProvider)
                .logger(logger)
                .buildClient();
        System.out.println("Second Step Reached. ");

        URL myUrl = new URL("https://graph.microsoft.com/v1.0/me/");
        final String accessToken = tokenCredAuthProvider.getAuthorizationTokenAsync(myUrl).get();
        System.out.println("Access token --> " + accessToken);

        // Just another optional step to get name of signed-in user.
        final User me = ((GraphServiceClient<Request>) graphClient).me().buildRequest().get();
        System.out.println("Hello " + me.displayName +  "( Synced !)");
        System.out.println("Hello " + me.mail +  "( Mail !)");
        System.out.println("Got " + me.messages.getCount() + " messages !");

    }

}

    at JAVA_MicrosoftGraphAPI.YT_Video.main(YT_Video.java:67)
Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS1002012: The provided value for scope User.Read openid profile offline_access Mail.Read is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
</code>```

答:
You need to change the scope to https://graph.microsoft.com/.default.

```<code>//Set the scopes for your ms-graph request
private final static List<String> SCOPES = Arrays.asList("https://graph.microsoft.com/.default");
</code>```

User.Read and Mail.Read permissions must be preconfigured in Azure on the app registration and an administrator must grant consent to those permissions beforehand.

Resources:

Client credentials provider

Body:
I am searching for solutions to authenticate with Microsoft Graph and get all my emails in Eclipse IDE. I have used the authentication method of 'Client Credentials Provider'. I am having issues with the SCOPES that need to be defined. Please find the error and my code below:

package JAVA_MicrosoftGraphAPI;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.logger.DefaultLogger;
import com.microsoft.graph.logger.LoggerLevel;
import com.microsoft.graph.models.User;
import com.microsoft.graph.requests.GraphServiceClient;
import okhttp3.Request;

public class YT_Video{

    private final static String CLIENT_ID = "CLIENT_ID";
    private final static String TENANT_ID = "TENANT_ID";
    private final static String SECRET_ID = "SECRET";

    //Set the scopes for your ms-graph request
    private final static List<String> SCOPES = Arrays.asList("User.Read", "Mail.Read", "openid", "offline_access", "profile");

    public static void main(String[] args) throws Exception {
        // Create the auth provider.
        final ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
                .clientId(CLIENT_ID)
                .clientSecret(SECRET_ID)
                .tenantId(TENANT_ID)
                .build();

        final TokenCredentialAuthProvider tokenCredAuthProvider = new TokenCredentialAuthProvider(SCOPES, clientSecretCredential);
        System.out.println("First Step Reached. ");

        // Create default logger to only log errors
        DefaultLogger logger = new DefaultLogger();
        logger.setLoggingLevel(LoggerLevel.ERROR);

        // Build a Graph client
        GraphServiceClient<Request> graphClient = GraphServiceClient.builder()
                .authenticationProvider(tokenCredAuthProvider)
                .logger(logger)
                .buildClient();
        System.out.println("Second Step Reached. ");

        URL myUrl = new URL("https://graph.microsoft.com/v1.0/me/");
        final String accessToken = tokenCredAuthProvider.getAuthorizationTokenAsync(myUrl).get();
        System.out.println("Access token --> " + accessToken);

        // Just another optional step to get name of signed-in user.
        final User me = ((GraphServiceClient<Request>) graphClient).me().buildRequest().get();
        System.out.println("Hello " + me.displayName +  "( Synced !)");
        System.out.println("Hello " + me.mail +  "( Mail !)");
        System.out.println("Got " + me.messages.getCount() + " messages !");

    }

}

    at JAVA_MicrosoftGraphAPI.YT_Video.main(YT_Video.java:67)
Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS1002012: The provided value for scope User.Read openid profile offline_access Mail.Read is not valid. Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).

Body:
You need to change the scope to https://graph.microsoft.com/.default.

//Set the scopes for your ms-graph request
private final static List<String> SCOPES = Arrays.asList("https://graph.microsoft.com/.default");

User.Read and Mail.Read permissions must be preconfigured in Azure on the app registration and an administrator must grant consent to those permissions beforehand.

Resources:

Client credentials provider


问:
Strange spacing between an inputAccessoryView and a keyboard
I have an InitialView that contains an AccessoryView (blue rectangle at the bottom) as a subview.

When I tap to this AccessoryView, InitialViewController presents OverlayViewController without animation (sounds like a very ugly solution, but in a real project it makes sense):

```<code>let overlayViewController = OverlayViewController()
overlayViewController.modalPresentationStyle = .overFullScreen
present(overlayViewController, animated: false)
</code>```

OverlayViewController has an inputAccessoryView (accessoryViewController.rootView is AccessoryView like on InitialView):

```<code>override var canBecomeFirstResponder: Bool { true }
override var inputAccessoryView: UIView? { accessoryViewController.rootView }
</code>```

This inputAccessoryView presents on viewWillAppear(animated:):

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    becomeFirstResponder()
}
</code>```

After that, TextView becomes the first responder on viewDidAppear(animated:):

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    accessoryViewController.rootView.textView.becomeFirstResponder()
}
</code>```

However, sometimes when the keyboard appears, there is a strange glitch where there is some space between the inputAccessoryView and the keyboard.

Could you help me to remove this spacing? This is my first experience with inputAccessoryView and it is really hard for me to figure out what I am doing wrong.

答:
I realized that the problem was elsewhere. I added a transparent button to my AccessoryView and added target on .touchDown event.

InitialViewController:

```<code>rootView.accessoryView.backgroundButton.addTarget(self, action: #selector(openOverlayScreen), for: .touchDown)
</code>```

When I changed .touchDown to .touchUpInside the problem is went away.

Body:
I have an InitialView that contains an AccessoryView (blue rectangle at the bottom) as a subview.

When I tap to this AccessoryView, InitialViewController presents OverlayViewController without animation (sounds like a very ugly solution, but in a real project it makes sense):

let overlayViewController = OverlayViewController()
overlayViewController.modalPresentationStyle = .overFullScreen
present(overlayViewController, animated: false)

OverlayViewController has an inputAccessoryView (accessoryViewController.rootView is AccessoryView like on InitialView):

override var canBecomeFirstResponder: Bool { true }
override var inputAccessoryView: UIView? { accessoryViewController.rootView }

This inputAccessoryView presents on viewWillAppear(animated:):

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    becomeFirstResponder()
}

After that, TextView becomes the first responder on viewDidAppear(animated:):

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    accessoryViewController.rootView.textView.becomeFirstResponder()
}

However, sometimes when the keyboard appears, there is a strange glitch where there is some space between the inputAccessoryView and the keyboard.

Could you help me to remove this spacing? This is my first experience with inputAccessoryView and it is really hard for me to figure out what I am doing wrong.

Body:
I realized that the problem was elsewhere. I added a transparent button to my AccessoryView and added target on .touchDown event.

InitialViewController:

rootView.accessoryView.backgroundButton.addTarget(self, action: #selector(openOverlayScreen), for: .touchDown)

When I changed .touchDown to .touchUpInside the problem is went away.


问:
MongoDB and geospatial queries: unknown geo specifier: $geometry: null
i'm experimenting with mongodb and geospatial queries. I made the following collection:

```<code>shape> db.shape.find()
[
  {
    _id: ObjectId("61ab50d2056b5357b5e23e56"),
    name: 'Point1',
    structure: { type: 'Point', coordinates: [ 2.5, 2.5 ] }
  },
  {
    _id: ObjectId("61ab5337056b5357b5e23e57"),
    name: 'Point2',
    structure: { type: 'Point', coordinates: [ 5, 5 ] }
  },
  {
    _id: ObjectId("61ab533e056b5357b5e23e58"),
    name: 'Point3',
    structure: { type: 'Point', coordinates: [ 9, 9 ] }
  },
  {
    _id: ObjectId("61ab5b4d056b5357b5e23e64"),
    name: 'square',
    structure: {
      type: 'Polygon',
      coordinates: [ [ [ 0, 0 ], [ 0, 5 ], [ 5, 5 ], [ 5, 0 ], [ 0, 0 ] ] ]
    }
  }
]
</code>```

then i tried the following:

```<code>var square = db.shape.find({name :"square"});
db.shape.find({structure : { $geoWithin : { $geometry : square.structure}}});
</code>```

and i get this error:

```<code>MongoServerError: unknown geo specifier: $geometry: null
</code>```

why is $geometry null?

Thanks in advance

答:
While processing the query, square.structure is getting replaced with null because you are trying to access that variable in wrong way.

In that square variable you are storing results returned by find() method.

find() method returns a cursor and we need to use cursor methods (like forEach) to access the containing documents. Where as findOne() returns a single document which can be accessed directly.

So, you can:

Use findOne() instead of find() or

Use cursor method like square.forEach(function(mydoc){<iterate through cursor here>})

I have copied your data and tested your query with findOne() and it worked well.

Body:
i'm experimenting with mongodb and geospatial queries. I made the following collection:

shape> db.shape.find()
[
  {
    _id: ObjectId("61ab50d2056b5357b5e23e56"),
    name: 'Point1',
    structure: { type: 'Point', coordinates: [ 2.5, 2.5 ] }
  },
  {
    _id: ObjectId("61ab5337056b5357b5e23e57"),
    name: 'Point2',
    structure: { type: 'Point', coordinates: [ 5, 5 ] }
  },
  {
    _id: ObjectId("61ab533e056b5357b5e23e58"),
    name: 'Point3',
    structure: { type: 'Point', coordinates: [ 9, 9 ] }
  },
  {
    _id: ObjectId("61ab5b4d056b5357b5e23e64"),
    name: 'square',
    structure: {
      type: 'Polygon',
      coordinates: [ [ [ 0, 0 ], [ 0, 5 ], [ 5, 5 ], [ 5, 0 ], [ 0, 0 ] ] ]
    }
  }
]

then i tried the following:

var square = db.shape.find({name :"square"});
db.shape.find({structure : { $geoWithin : { $geometry : square.structure}}});

and i get this error:

MongoServerError: unknown geo specifier: $geometry: null

why is $geometry null?

Thanks in advance


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答: What do your Business people say will make you the most money? Do that. Maybe usability is the next thing to do, maybe more features, maybe a different product. It's not something a "geek" will necessarily be able to guess.</p>

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: John Saunders


问:
Docker is not running on Colab
I have tried  to install Docker on google Colab through the following ways:

(1)https://phoenixnap.com/kb/how-to-install-docker-on-ubuntu-18-04

(2)https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-18-04

(3)https://colab.research.google.com/drive/10OinT5ZNGtdLLQ9K399jlKgNgidxUbGP

I started the docker service and saw the status, but it showed 'Docker is not running'. Maybe the docker can not work on the Colab.

I feel confused and want to know the reason.

Thanks

答:
I know, it is an old question, but this an old answer (2020)  by a member of the Google Colaboratory team.

this isn't possible, and we currently have no plans to support this.

Title: Docker is not running on Colab


问:
Google App Engine utf-8 coding problem with Python
I would appreciate your help with a hopefully trivial issue. Recently I've started learning Python for work with Google App Engine environment. Needlessly to say I began with the simplest Hello World app.

The English version of it works just fine

However, when I try to work with the signs in my mother tongue, then the problem starts. Basically when run on local machine it does not display letters properly.

Here's the piece of code that's causing me issues

```<code># -*- coding: utf-8 -*-
import datetime

print 'Content-Type: text/html'
print ''
print '<html>'
print '<head>'
print '<title>Witaj świecie</title>'
print '</head>'
print '<body>'
print '<h1>Witaj świecie</h1>'
print ''
print 'Data logowania to: %s' % (datetime.datetime.now())
print '</body>'
print '</html>'
</code>```

Of course I save all files in utf-8 format. Can anyone tell me how to enable proper display of utf-8 characters here?

答:
Set the encoding when you set the content type:

```<code>print 'Content-Type: text/html; charset=UTF-8'
</code>```

Don't use a meta tag as @bpgergo suggests; it's specific to HTML, and simply overrides the headers. Since you're already setting the headers, it's easier and better to simply set them correctly in the first place.

You really shouldn't be using CGI and outputting your content using print statements, though - it's messy and will be a real pain to maintain as your app gets bigger, as well as making things like internationalization a lot harder. Instead, use WSGI and templating - see the getting started guide for App Engine, specifically this and this.

Body:
I would appreciate your help with a hopefully trivial issue. Recently I've started learning Python for work with Google App Engine environment. Needlessly to say I began with the simplest Hello World app.

The English version of it works just fine

However, when I try to work with the signs in my mother tongue, then the problem starts. Basically when run on local machine it does not display letters properly.

Here's the piece of code that's causing me issues

# -*- coding: utf-8 -*-
import datetime

print 'Content-Type: text/html'
print ''
print ''
print ''
print '<title>Witaj świecie</title>'
print ''
print ''
print '
Witaj świecie
'
print ''
print 'Data logowania to: %s' % (datetime.datetime.now())
print ''
print ''

Of course I save all files in utf-8 format. Can anyone tell me how to enable proper display of utf-8 characters here?

Body:
Set the encoding when you set the content type:

print 'Content-Type: text/html; charset=UTF-8'

Don't use a meta tag as @bpgergo suggests; it's specific to HTML, and simply overrides the headers. Since you're already setting the headers, it's easier and better to simply set them correctly in the first place.

You really shouldn't be using CGI and outputting your content using print statements, though - it's messy and will be a real pain to maintain as your app gets bigger, as well as making things like internationalization a lot harder. Instead, use WSGI and templating - see the getting started guide for App Engine, specifically this and this.


问:
google reset new key certificate for me but certificate not working
i am reset my certificate APK google play console... so google give me information:

the new key will usable from 2022-02-04 17:12:58 UTC

but until now I can't replace my certificate, it says that I entered the old certificate, even though Google has told Google to replace it with a new one, what should I do?
I've contacted the Google developer, but so far they haven't been answered

best regards,

答:
When you reset the upload key, you were given instructions to generate a new keystore. You need to sign your APK or AAB using that new keystore. For that, you will need to update the path to they keystore in your build.gradle file (or signing configuration of whichever build system you use).

If this still doesn't work, go to the "App Integrity" page in the Play Console, and look at the SHA1 of the "Upload certificate", and compare that with the SHA1 of the keystore you sign your APK/AAB with -- see this post for example on how to extract this info off a keystore.

If you see a difference in the SHA1, then either you don't have the right keystore or the reset maybe didn't work and you may need to do it again.


问:
tar: Unrecognized archive format error when trying to unpack flower_photos.tgz, TF tutorials on OSX
I'm trying to unpack the flower_photos.tgz after curling it using

```<code>curl -O http://download.tensorflow.org/example_../images/flower_photos.tgz
tar xzf flower_photos.tgz
</code>```

This is from the image retraining tutorial for TensorFlow

Results from curling

```<code>% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   127  100   127    0     0    255      0 --:--:-- --:--:-- --:--:--   255
</code>```

Then when I try to unpack

```<code>tar xzf flower_photos.tgz
tar: Unrecognized archive format
tar: Error exit delayed from previous errors.
</code>```

答:
I had the same problem

```<code>tar: Error opening archive: Unrecognized archive format
</code>```

In my case the actual file didn't exist anymore (checked by putting the link in the browser), so my tar file was actually an error page (probably 404 page).

Body:
I'm trying to unpack the flower_photos.tgz after curling it using

curl -O http://download.tensorflow.org/example_../images/flower_photos.tgz
tar xzf flower_photos.tgz

This is from the image retraining tutorial for TensorFlow

Results from curling

% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                             Dload  Upload   Total   Spent    Left  Speed
100   127  100   127    0     0    255      0 --:--:-- --:--:-- --:--:--   255

Then when I try to unpack

tar xzf flower_photos.tgz
tar: Unrecognized archive format
tar: Error exit delayed from previous errors.

Body:
I had the same problem

tar: Error opening archive: Unrecognized archive format

In my case the actual file didn't exist anymore (checked by putting the link in the browser), so my tar file was actually an error page (probably 404 page).


问:
Accessing pipeline variables by name in PowerShell
We have a particular scenario where we retrieve secrets from a Key Vault and use it in our release pipeline. This can be easily implemented with the "Azure Key Vault" tasks in Devops which will fetch them and store them as a pipeline variable.

So far so good, easy to do but we have a small issue. The customer insists that the secret's name includes the environment, meaning that we have different secret names depending on the environment (TEST/UAT/PROD/...)

Because we have one pipeline for all environments, we would like to be able to specify which secret to fetch via a pipeline variable, then get the secret and push it into another pipeline variable. We are still using classic pipelines, not YAML.

You can access pipeline variables in Powershell via the macro $(variablename); is there any way how we can access it via a variable name? I tried several things like Get-Variable or "$($(KeyVault.SecretName))", but none of those seem to work.

Anybody has another idea how I can achieve this?

Regards,
Sven

答:
I abondonned the "Azure Key Vault" task and just used an Azure Cli with "az keyvault".
Pretty easy to do in fact and you have full flexibility

(az keyvault secret show --name '$(SecretName)' --vault-name '$(KeyvaultName)' |ConvertFrom-Json).value


问:
How to seed data in .NET Core 6 with Entity Framework?
I know how to seed data to a database with old .NET 5.0 in startup.cs file using my Seeder class with a Seed() method creating some initial data.

```<code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)
{
   seeder.Seed();

   ..............
   // other configurations
}
</code>```

How do I do this in .NET 6.0? There is no place to add my Seeder class as an argument.

答:
I solved a similar problem as follows:

Program.cs (.NET 6)

```<code>...
builder.Services.AddScoped<IDbInitializer, DbInitializer>(); //can be placed among other "AddScoped" - above: var app = builder.Build();

...
SeedDatabase(); //can be placed above app.UseStaticFiles();
...
    void SeedDatabase() //can be placed at the very bottom under app.Run()
    {
        using (var scope = app.Services.CreateScope())
        {
            var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
            dbInitializer.Initialize();
        }
    }
</code>```

Body:
I know how to seed data to a database with old .NET 5.0 in startup.cs file using my Seeder class with a Seed() method creating some initial data.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, Seeder seeder)
{
   seeder.Seed();

   ..............
   // other configurations
}

How do I do this in .NET 6.0? There is no place to add my Seeder class as an argument.

Body:
I solved a similar problem as follows:

Program.cs (.NET 6)

...
builder.Services.AddScoped<IDbInitializer, DbInitializer>(); //can be placed among other "AddScoped" - above: var app = builder.Build();

...
SeedDatabase(); //can be placed above app.UseStaticFiles();
...
    void SeedDatabase() //can be placed at the very bottom under app.Run()
    {
        using (var scope = app.Services.CreateScope())
        {
            var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
            dbInitializer.Initialize();
        }
    }


问:
Java program runtime error
```<code>public class BooksTestDrive {
 public static void main(String[] args) {

  Books [] myBooks = new Books[3];
  int x=0;
  myBooks[0].title = "The Grapes of Jave";
  myBooks[1].title = "The Java Gatsby";
  myBooks[2].title = "The Java Cookbook";
  myBooks[0].author = "bob";
  myBooks[1].author = "sue";
  myBooks[2].author = "ian";

 while (x < 3) {
  System.out.print(myBooks[x].title);
  System.out.print("by");
  System.out.println(myBooks[x].author);
  x = x+1;
  }
 }
}
</code>```

<p>This code compiles but while runtime, its giving nullpointer exception. </p>

答:
You need to add the books to the arrays. This should work:</p>

```<code>class BooksTestDrive {
    public static void main(String [] args) {
        Books [] myBooks = new Books[3];
        int x = 0;
        // THIS IS WHAT WAS MISSING.
        myBooks[0] = new Books();
        myBooks[1] = new Books();
        myBooks[2] = new Books();

        myBooks[0].title = "The Grapes of Java";
        myBooks[1].title = "The Java Gatsby";
        myBooks[2].title = "The Java Cookbook";
        myBooks[0].author = "bob";
        myBooks[1].author = "sue";
        myBooks[2].author = "ian";

        while (x < 3) {
            System.out.print(myBooks[x].title);
            System.out.print(" by ");
            System.out.println(myBooks[x].author) ;
            x = x + 1;
        }
    }
}
</code>```

Title: Java program runtime error

Body:
public class BooksTestDrive {
 public static void main(String[] args) {

  Books [] myBooks = new Books[3];
  int x=0;
  myBooks[0].title = "The Grapes of Jave";
  myBooks[1].title = "The Java Gatsby";
  myBooks[2].title = "The Java Cookbook";
  myBooks[0].author = "bob";
  myBooks[1].author = "sue";
  myBooks[2].author = "ian";

 while (x < 3) {
  System.out.print(myBooks[x].title);
  System.out.print("by");
  System.out.println(myBooks[x].author);
  x = x+1;
  }
 }
}

This code compiles but while runtime, its giving nullpointer exception.

Body:
You need to add the books to the arrays. This should work:

class BooksTestDrive {
    public static void main(String [] args) {
        Books [] myBooks = new Books[3];
        int x = 0;
        // THIS IS WHAT WAS MISSING.
        myBooks[0] = new Books();
        myBooks[1] = new Books();
        myBooks[2] = new Books();

        myBooks[0].title = "The Grapes of Java";
        myBooks[1].title = "The Java Gatsby";
        myBooks[2].title = "The Java Cookbook";
        myBooks[0].author = "bob";
        myBooks[1].author = "sue";
        myBooks[2].author = "ian";

        while (x < 3) {
            System.out.print(myBooks[x].title);
            System.out.print(" by ");
            System.out.println(myBooks[x].author) ;
            x = x + 1;
        }
    }
}


问:
How to take a list of struct value for doing sum
I would like to take all of the initial value from struct to do calculate, but it always show total in 0 to me. It supposed to show me a total value of 21.. Anyone that can help me to fix my program I will be very appreciated. Thank you for reviewing my question.. (Below is my code and text file)

wbz.txt:

```<code>PID00001:Aircon:2
PID00002:Windows:10
PID00003:Pipe:9
</code>```

My Code:

```<code>#define SIZE 100

struct parts
{
    char pid[50], pname[50];
    int initialvalue;
}p[SIZE];

int main()
{
    FILE* f;
    char data[100], pid[50], * s, back;
    int buf = 0, choice, i=0, total=0;
    memset(p, 0, sizeof(p));
    do {
        printf("Which warehouse (1.WBZ | 2.WSL | 3.WAR): ");
        scanf("%d", &choice);

        if (choice == 1)
        {

            f = fopen("wbz.txt", "r");
            while (fgets(data, sizeof data, f))
            {

                s = strtok(data, ":");
                if (s != NULL)
                {
                    strcpy(p[i].pid, s);
                }
                s = strtok(NULL, ":");
                if (s != NULL)
                {
                    strcpy(p[i].pname, s);
                }
                s = strtok(NULL, ":");
                if (s != NULL)
                {

                    p[i].initialvalue = atoi(s);

                }
                printf("\nParts ID: %s\nParts Name: %s\nParts Quantity: %d\n", p[i].pid, p[i].pname, p[i].initialvalue);

                if (p[i].initialvalue < 10)
                {
                    printf("\n---------------------------------------");
                    printf("\n%s unit is not enough, only %d left\n", p[i].pname, p[i].initialvalue);
                    printf("---------------------------------------\n");
                }
                else
                {
                    printf("\n---------------------------------------");
                    printf("\nThis unit is enough\n");
                    printf("---------------------------------------\n");
                }

            }
            if (i > 0)
                p[i].initialvalue += p[i - 1].initialvalue;

            if (++i == SIZE)
            {
                break;
            }
            p[i].initialvalue += p[i].initialvalue;
            printf("\nTotal: %d", p[i].initialvalue);

            fclose(f);
        }

        printf("\nDo you want to continue (y/n): ");
        getchar();
        scanf("%c", &back);

    } while (back != 'n');

    return 0;
}
</code>```

答:
You update p[i].initialVlue using itself after having incremented i = you add 0 to 0 because the value you add is not yet set :

```<code>            // update should  be before the ++i and using previous index
            If (i > 0) {p[i].initialvalue += p[i-1].initialvalue;}

            if (++i == SIZE)
            {
                break;
            }
        } // end of while loop here
        // next line is not good so remove it
        //p[i].initialvalue += p[i].initialvalue;

        // i is SIZE here do decrease it
        // to get the last value
        i—
        printf("\nTotal: %d", p[i].initialvalue);
        }
</code>```

Also you should initialise p with 0 before using it :

```<code>memset(p,0,sizeof(p));
</code>```

Body:
I would like to take all of the initial value from struct to do calculate, but it always show total in 0 to me. It supposed to show me a total value of 21.. Anyone that can help me to fix my program I will be very appreciated. Thank you for reviewing my question.. (Below is my code and text file)

wbz.txt:

PID00001:Aircon:2
PID00002:Windows:10
PID00003:Pipe:9

My Code:

#define SIZE 100

struct parts
{
    char pid[50], pname[50];
    int initialvalue;
}p[SIZE];

int main()
{
    FILE* f;
    char data[100], pid[50], * s, back;
    int buf = 0, choice, i=0, total=0;
    memset(p, 0, sizeof(p));
    do {
        printf("Which warehouse (1.WBZ | 2.WSL | 3.WAR): ");
        scanf("%d", &choice);

        if (choice == 1)
        {

            f = fopen("wbz.txt", "r");
            while (fgets(data, sizeof data, f))
            {

                s = strtok(data, ":");
                if (s != NULL)
                {
                    strcpy(p[i].pid, s);
                }
                s = strtok(NULL, ":");
                if (s != NULL)
                {
                    strcpy(p[i].pname, s);
                }
                s = strtok(NULL, ":");
                if (s != NULL)
                {

                    p[i].initialvalue = atoi(s);

                }
                printf("\nParts ID: %s\nParts Name: %s\nParts Quantity: %d\n", p[i].pid, p[i].pname, p[i].initialvalue);

                if (p[i].initialvalue < 10)
                {
                    printf("\n---------------------------------------");
                    printf("\n%s unit is not enough, only %d left\n", p[i].pname, p[i].initialvalue);
                    printf("---------------------------------------\n");
                }
                else
                {
                    printf("\n---------------------------------------");
                    printf("\nThis unit is enough\n");
                    printf("---------------------------------------\n");
                }

            }
            if (i > 0)
                p[i].initialvalue += p[i - 1].initialvalue;

            if (++i == SIZE)
            {
                break;
            }
            p[i].initialvalue += p[i].initialvalue;
            printf("\nTotal: %d", p[i].initialvalue);

            fclose(f);
        }

        printf("\nDo you want to continue (y/n): ");
        getchar();
        scanf("%c", &back);

    } while (back != 'n');

    return 0;
}

Body:
You update p[i].initialVlue using itself after having incremented i = you add 0 to 0 because the value you add is not yet set :

            // update should  be before the ++i and using previous index
            If (i > 0) {p[i].initialvalue += p[i-1].initialvalue;}

            if (++i == SIZE)
            {
                break;
            }
        } // end of while loop here
        // next line is not good so remove it
        //p[i].initialvalue += p[i].initialvalue;

        // i is SIZE here do decrease it
        // to get the last value
        i—
        printf("\nTotal: %d", p[i].initialvalue);
        }

Also you should initialise p with 0 before using it :

memset(p,0,sizeof(p));