问:
Question about type classes in Scala
Let there are classes Fruit, Orange, and Apple.

```<code>abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit</code>```

Now I want to add write functionality to both types Orange and Apple. Using the type class pattern I can do the following:

```<code>trait Writer[T] {def write(t:T)}

implicit object AppleWriter extends Writer[Apple] {
   def write(a:Apple) {println("I am an apple!")}
}

implicit object OrangeWriter extends Writer[Orange] {
   def write(o:Orange) {println("I am an orange!")}
}

def write[T](t:T)(implicit w:Writer[T]){w.write(t)}</code>```

So for, so good but what if I want to define writeFruits ?

```<code>def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}</code>```

I would like writeFruits to call either write[Apple] or write[Orange] for each fruit. I see that it does not work (and I know why) but maybe I can implement the writeFruits anyway.

Can I implement writeFruits somehow ?

答:
You need to pick out only those Fruit for which a Writer exists.  Unfortunately, once you've cast to Fruit you've lost the ability to automatically figure out which is which.  If you must set up the problem this way--rather than assembling a list of writable fruit or somesuch--then one reasonable option is to split out the types again with a FruitWriter:

```<code>def writeOne[T](t:T)(implicit w:Writer[T]){w.write(t)}  // New name to avoid shadowing

implicit object FruitWriter extends Writer[Fruit] {
  def write(f: Fruit) { f match {
    case o: Orange => writeOne(o)
    case a: Apple => writeOne(a)
  }}
}

scala> val fruits = List(new Apple, new Orange)
fruits: List[Fruit] = List(Apple@1148ab5c, Orange@39ea2de1)

scala> for (fruit <- fruits) writeOne(fruit)
I am an apple!
I am an orange!
</code>```

Title: Question about type classes in Scala

Body:
Let there are classes Fruit, Orange, and Apple.

abstract class Fruit
class Orange extends Fruit
class Apple extends Fruit

Now I want to add write functionality to both types Orange and Apple. Using the type class pattern I can do the following:

trait Writer[T] {def write(t:T)}

implicit object AppleWriter extends Writer[Apple] {
   def write(a:Apple) {println("I am an apple!")}
}

implicit object OrangeWriter extends Writer[Orange] {
   def write(o:Orange) {println("I am an orange!")}
}

def write[T](t:T)(implicit w:Writer[T]){w.write(t)}

So for, so good but what if I want to define writeFruits ?

def writeFruits(fruits:List[Fruit]) {for (fruit <- fruits) write(fruit)}

I would like writeFruits to call either write[Apple] or write[Orange] for each fruit. I see that it does not work (and I know why) but maybe I can implement the writeFruits anyway.

Can I implement writeFruits somehow ?

Body:
You need to pick out only those Fruit for which a Writer exists.  Unfortunately, once you've cast to Fruit you've lost the ability to automatically figure out which is which.  If you must set up the problem this way--rather than assembling a list of writable fruit or somesuch--then one reasonable option is to split out the types again with a FruitWriter:

def writeOne[T](t:T)(implicit w:Writer[T]){w.write(t)}  // New name to avoid shadowing

implicit object FruitWriter extends Writer[Fruit] {
  def write(f: Fruit) { f match {
    case o: Orange => writeOne(o)
    case a: Apple => writeOne(a)
  }}
}

scala> val fruits = List(new Apple, new Orange)
fruits: List[Fruit] = List(Apple@1148ab5c, Orange@39ea2de1)

scala> for (fruit <- fruits) writeOne(fruit)
I am an apple!
I am an orange!


来源: stackexchange

问:
How to use group by on 2 different columns and use SUM function in mysql
I have this table:

and I want records like this:

```<code>Leave_detail_id   emp_id  leave_count
-------------------------------------
  1                 22       3
  3                 22       2
  2                 30       4
</code>```

Please help me how to use multiple GROUP BY with SUM

答:
I think they want the fields in the select as well, </p>

```<code>SELECT leave_detail_id, emp_id, SUM(leave_count) FROM table GROUP BY leave_detail_id, emp_id;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this table:

and I want records like this:

Leave_detail_id   emp_id  leave_count
-------------------------------------
  1                 22       3
  3                 22       2
  2                 30       4

Please help me how to use multiple GROUP BY with SUM

Body:
I think they want the fields in the select as well,

SELECT leave_detail_id, emp_id, SUM(leave_count) FROM table GROUP BY leave_detail_id, emp_id;


问:
how to make app full screen when a FragmentDialog is showing
i make my app Full Screen but when i create and show a Fragment Dialog it'll exit from Full Screen

i try two way but none working for me , check out code 1 and code 2

code 1 :
add
adding <item name="android:windowFullscreen">true</item>
to my style.xml
code 2 :
override onShow in Fragment Dialog

```<code>    @Override
    public void show(FragmentManager manager, String tag)
    {
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show(manager, tag);
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }
</code>```

nothing happened and my app exit from Full Screen again

答:
Try this   </p>

```<code>@Override
    public void show(FragmentManager manager, String tag)
    {
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show(manager, tag);
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

        // add these two line
        getDialog().requestWindowFeature(1);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0));
    }
</code>```

Body:
i make my app Full Screen but when i create and show a Fragment Dialog it'll exit from Full Screen

i try two way but none working for me , check out code 1 and code 2

code 1 :
add
adding <item name="android:windowFullscreen">true</item>
to my style.xml
code 2 :
override onShow in Fragment Dialog

    @Override
    public void show(FragmentManager manager, String tag)
    {
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show(manager, tag);
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
    }

nothing happened and my app exit from Full Screen again

Body:
Try this

@Override
    public void show(FragmentManager manager, String tag)
    {
        getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
        super.show(manager, tag);
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        getDialog().getWindow().getDecorView().setSystemUiVisibility(uiOptions);
        getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);

        // add these two line
        getDialog().requestWindowFeature(1);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0));
    }


问:
Fastest way to get all values from a Map where the key starts with a certain expression
Consider you have a map<String, Object> myMap.

Given the expression "some.string.*", I have to retrieve all the values from myMap whose keys starts with this expression.

I am trying to avoid for loops because myMap will be given a set of expressions not only one and using for loop for each expression becomes cumbersome performance wise.

What is the fastest way to do this?

答:
Remove all keys which does not start with your desired prefix:</p>

```<code>yourMap.keySet().removeIf(key -> !key.startsWith(keyPrefix));
</code>```

Body:
Remove all keys which does not start with your desired prefix:

yourMap.keySet().removeIf(key -> !key.startsWith(keyPrefix));


问:
How to get Excel to recognise dates without a manual find and replace "/" for "/"?
How do I get excel to recognize timestamps as timestamps rather than strings?

If I do a find and replace on "/" with "/" it fixes it on most files:

```<code>Cells.Replace What:="/", Replacement:="/", LookAt:=xlPart, SearchOrder :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
</code>```

I have a chunk of code that checks if it's still in the wrong format by converting to "Comma" format and checking if the cell contains any "/" characters, then a break line that triggers in that instance to alert me that I need to manually do the find and replace on this file. If I stop the Macro when it fails and run it manually (Crtl+h, Enter), then it works and I can restart the macro to finish the standardisation. I need a way of automating this.

I have >2000 .csv files of a similar but not identical format. Each one contains ~350 variables, each with it's own timestamp and data column. I've written some code that formats it into a usable format. The original csv has the timestamps in "DD/MM/YYYY hh:mm:ss" format as is my computer and Excel default.

Excel seemingly randomly decides it can't recognise around a quarter of the files timestamps and instead interprets them as strings. This can be corrected by clicking into the cell and then clicking out of the cell, then excel recognises it as a timestamp. I need the timestamps recognised so that I can interpolate values into a standard sampling frequency as Excel can't interpolate using values it interprets as strings.

There are often well over 100k timestamps per file, so doing this manually isn't an option.

I've tried using SendKeys. The problem with that seems to be that it opens the find and replace dialogue for the VBA script editor, not for the excel sheet.
I've tried shifting focus before by calling:

```<code>Windows(windowname).Activate
ActiveWorkbook.Application.SendKeys("^h")
</code>```

I've also tried:

```<code>Windows(windowname).Application.SendKeys("^h")
</code>```

Which both result in the find and replace being called on the VBA script editor.

I have no shortcut to start the Macro.

I've tried Matlab, but it can't deal with the header on the file or the columns populated with text. I'd like to retain all the data.

I have used the Macro recorder to record me doing the find and replace which results in:

```<code>Sub Fixer()
'
' Fixer Macro
'

'
    Selection.Replace What:="/", Replacement:="/", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub
</code>```

But this doesn't work when you run it on the same file.

I expect it to convert the string "DD/MM/YYYY hh:mm:ss" format into a date-time format that I can then convert into decimal format which I can then use for interpolating the values into a usable format. Instead I get no error message, and nothing happens.

An example line of date timestamps from the raw CSV is:
"31/03/2019 14:55:57,1.0000000149,31/03/2019 14:55:57,14.6,31/03/2019 14:55:57,57.86,31/03/2019 14:55:57,0.175000000000068"

So the timestamp "31/03/2019 14:55:57" I want converting into "43555.62218750000"

I could use a script to deconstruct the string, calculate the decimal equivalent, and overwrite the cell, but this will take a prohibitively long time.

答:
You need to back up a step.

Your problem is common and is caused by OPENing a csv file where the date format (DMY) in this case is in a different format than your Windows Regional Setting on the your computer.

So even the input that appears to convert properly, will not be as the Day and Month will be exchanged from what you might expect.

Arguably the "best" fix for this issue, assuming you cannot alter the csv file, will be to IMPORT the file instead.

Depending on how you do the IMPORT, and that is Excel version dependent, you will have the opportunity, at the time of import, to define the date format of the incoming data, so it will be properly converted by Excel.

In Power Query you can specify to have PQ do the date conversion according to a specified locale.  In earlier versions of Excel, a Text-to-columns wizard will open allowing you to specify DMY for the format of the csv file.  I would suggest using PQ as it can easily handle the time portion, whereas with the older wizard you'll need to split the two, and then add them back together.

Body:
How do I get excel to recognize timestamps as timestamps rather than strings?

If I do a find and replace on "/" with "/" it fixes it on most files:

Cells.Replace What:="/", Replacement:="/", LookAt:=xlPart, SearchOrder :=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

I have a chunk of code that checks if it's still in the wrong format by converting to "Comma" format and checking if the cell contains any "/" characters, then a break line that triggers in that instance to alert me that I need to manually do the find and replace on this file. If I stop the Macro when it fails and run it manually (Crtl+h, Enter), then it works and I can restart the macro to finish the standardisation. I need a way of automating this.

I have >2000 .csv files of a similar but not identical format. Each one contains ~350 variables, each with it's own timestamp and data column. I've written some code that formats it into a usable format. The original csv has the timestamps in "DD/MM/YYYY hh:mm:ss" format as is my computer and Excel default.

Excel seemingly randomly decides it can't recognise around a quarter of the files timestamps and instead interprets them as strings. This can be corrected by clicking into the cell and then clicking out of the cell, then excel recognises it as a timestamp. I need the timestamps recognised so that I can interpolate values into a standard sampling frequency as Excel can't interpolate using values it interprets as strings.

There are often well over 100k timestamps per file, so doing this manually isn't an option.

I've tried using SendKeys. The problem with that seems to be that it opens the find and replace dialogue for the VBA script editor, not for the excel sheet.
I've tried shifting focus before by calling:

Windows(windowname).Activate
ActiveWorkbook.Application.SendKeys("^h")

I've also tried:

Windows(windowname).Application.SendKeys("^h")

Which both result in the find and replace being called on the VBA script editor.

I have no shortcut to start the Macro.

I've tried Matlab, but it can't deal with the header on the file or the columns populated with text. I'd like to retain all the data.

I have used the Macro recorder to record me doing the find and replace which results in:

Sub Fixer()
'
' Fixer Macro
'

'
    Selection.Replace What:="/", Replacement:="/", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

But this doesn't work when you run it on the same file.

I expect it to convert the string "DD/MM/YYYY hh:mm:ss" format into a date-time format that I can then convert into decimal format which I can then use for interpolating the values into a usable format. Instead I get no error message, and nothing happens.

An example line of date timestamps from the raw CSV is:
"31/03/2019 14:55:57,1.0000000149,31/03/2019 14:55:57,14.6,31/03/2019 14:55:57,57.86,31/03/2019 14:55:57,0.175000000000068"

So the timestamp "31/03/2019 14:55:57" I want converting into "43555.62218750000"

I could use a script to deconstruct the string, calculate the decimal equivalent, and overwrite the cell, but this will take a prohibitively long time.


问:
asyncio: running task only if all other tasks are awaiting
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

```<code>import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())
</code>```

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)

答:
Why not use a semaphore

```<code>async def do_stuff(semaphore):
    async with semaphore:
      await getting_stuff_done()

async def wait_til_everyone_is_busy(semaphore):
    while not semaphore.locked():
      await asyncio.sleep(1)
    do_other_stuff()
</code>```

To better illustrate my point, take this trivial example:

```<code>import asyncio
import time

async def process(semaphore, i):
    while True:
        print(f"{i} I'm gonna await")
        await asyncio.sleep(1)
        async with semaphore:
            print(f'{i} sleeping')
            await asyncio.sleep(3)
        print(f'{i} done sleeping')
        print(f"{i} I'm gonna await again")
        await asyncio.sleep(1)

async def other_process(semaphore):
    while True:
        while not semaphore.locked():
            print("Everyone is awaiting... but I'm not startingr")
            await asyncio.sleep(1)
        print("Everyone is busy, let's do this!")
        time.sleep(5)
        print('5 seconds are up, let everyone else play again')
        await asyncio.sleep(1)

semaphore = asyncio.Semaphore(10)
dataset = [i for i in range(10)]
loop = asyncio.new_event_loop()
tasks = [loop.create_task(process(semaphore, i)) for i in dataset]
tasks.append(loop.create_task(other_process(semaphore)))
loop.run_until_complete(asyncio.wait(tasks))

</code>```

We create 10 tasks that use the "process" function, and one that uses the "other_process". The one that performs "other_process" can only run while all the others are holding the semaphore, and because of the way Asyncio context-switching works, only the "other_process" function will be performed while the others are in an await status, up until "other_process" hits its own "await".

```<code>$ python3 tmp
0 I'm gonna await
1 I'm gonna await
2 I'm gonna await
3 I'm gonna await
4 I'm gonna await
5 I'm gonna await
6 I'm gonna await
7 I'm gonna await
8 I'm gonna await
9 I'm gonna await
Everyone is awaiting... but I'm not startingr
0 sleeping
1 sleeping
2 sleeping
3 sleeping
4 sleeping
5 sleeping
6 sleeping
7 sleeping
8 sleeping
9 sleeping
Everyone is busy, let's do this!
5 seconds are up, let everyone else play again
0 done sleeping
0 I'm gonna await again
1 done sleeping
1 I'm gonna await again
2 done sleeping
2 I'm gonna await again
3 done sleeping
3 I'm gonna await again
4 done sleeping
4 I'm gonna await again
5 done sleeping
5 I'm gonna await again
6 done sleeping
6 I'm gonna await again
7 done sleeping
7 I'm gonna await again
8 done sleeping
8 I'm gonna await again
9 done sleeping
9 I'm gonna await again
Everyone is awaiting... but I'm not startingr
0 I'm gonna await
1 I'm gonna await
2 I'm gonna await
3 I'm gonna await
4 I'm gonna await
5 I'm gonna await
6 I'm gonna await
7 I'm gonna await
8 I'm gonna await
9 I'm gonna await
Everyone is awaiting... but I'm not startingr
0 sleeping
1 sleeping
2 sleeping
3 sleeping
4 sleeping
5 sleeping
6 sleeping
7 sleeping
8 sleeping
9 sleeping
Everyone is busy, let's do this!
</code>```

Body:
I am currently running some endless tasks using asyncio.wait

I need a special function to run when all the others are on await

import asyncio

async def special_function():
    while True:
        # does some work,
        # Passes control back to controller to run main_tasks
        # if they are no longer waiting.
        await asyncio.sleep(0)

async def handler():
    tasks = [task() for task in main_tasks]

    # Adding the task that I want to run when all main_tasks are awaiting:
    tasks.append(special_function())

    await asyncio.wait(tasks)

asyncio.get_event_loop().run_until_complete(handler())

How can I get  the special_function to only be run when all main_tasks are on await?

Edit:

What I mean by "all main_tasks are on await": all main_tasks are not ready to continue, e.g. are in asyncio.sleep(100) or I/O bound and still waiting for data.

Therefore the main_tasks cannot continue and the event loop runs the special_function while the tasks are in this state, NOT every iteration of the event loop.

Edit 2:

My use case:

The main_tasks are updating a data structure with new data from web-sockets.

The special_function transfers that data to another process upon an update signal from that process. (multiprocessing with shared variables and data structures)

It needs to be the most up to date data it can be when it transfers, there cannot be pending updates from main_tasks.

This is why I only want to run special_function when there are no main_tasks with new data available to be processed. (i.e. all waiting on await)

Body:
Why not use a semaphore

async def do_stuff(semaphore):
    async with semaphore:
      await getting_stuff_done()

async def wait_til_everyone_is_busy(semaphore):
    while not semaphore.locked():
      await asyncio.sleep(1)
    do_other_stuff()

To better illustrate my point, take this trivial example:

import asyncio
import time

async def process(semaphore, i):
    while True:
        print(f"{i} I'm gonna await")
        await asyncio.sleep(1)
        async with semaphore:
            print(f'{i} sleeping')
            await asyncio.sleep(3)
        print(f'{i} done sleeping')
        print(f"{i} I'm gonna await again")
        await asyncio.sleep(1)

async def other_process(semaphore):
    while True:
        while not semaphore.locked():
            print("Everyone is awaiting... but I'm not startingr")
            await asyncio.sleep(1)
        print("Everyone is busy, let's do this!")
        time.sleep(5)
        print('5 seconds are up, let everyone else play again')
        await asyncio.sleep(1)

semaphore = asyncio.Semaphore(10)
dataset = [i for i in range(10)]
loop = asyncio.new_event_loop()
tasks = [loop.create_task(process(semaphore, i)) for i in dataset]
tasks.append(loop.create_task(other_process(semaphore)))
loop.run_until_complete(asyncio.wait(tasks))

We create 10 tasks that use the "process" function, and one that uses the "other_process". The one that performs "other_process" can only run while all the others are holding the semaphore, and because of the way Asyncio context-switching works, only the "other_process" function will be performed while the others are in an await status, up until "other_process" hits its own "await".

$ python3 tmp
0 I'm gonna await
1 I'm gonna await
2 I'm gonna await
3 I'm gonna await
4 I'm gonna await
5 I'm gonna await
6 I'm gonna await
7 I'm gonna await
8 I'm gonna await
9 I'm gonna await
Everyone is awaiting... but I'm not startingr
0 sleeping
1 sleeping
2 sleeping
3 sleeping
4 sleeping
5 sleeping
6 sleeping
7 sleeping
8 sleeping
9 sleeping
Everyone is busy, let's do this!
5 seconds are up, let everyone else play again
0 done sleeping
0 I'm gonna await again
1 done sleeping
1 I'm gonna await again
2 done sleeping
2 I'm gonna await again
3 done sleeping
3 I'm gonna await again
4 done sleeping
4 I'm gonna await again
5 done sleeping
5 I'm gonna await again
6 done sleeping
6 I'm gonna await again
7 done sleeping
7 I'm gonna await again
8 done sleeping
8 I'm gonna await again
9 done sleeping
9 I'm gonna await again
Everyone is awaiting... but I'm not startingr
0 I'm gonna await
1 I'm gonna await
2 I'm gonna await
3 I'm gonna await
4 I'm gonna await
5 I'm gonna await
6 I'm gonna await
7 I'm gonna await
8 I'm gonna await
9 I'm gonna await
Everyone is awaiting... but I'm not startingr
0 sleeping
1 sleeping
2 sleeping
3 sleeping
4 sleeping
5 sleeping
6 sleeping
7 sleeping
8 sleeping
9 sleeping
Everyone is busy, let's do this!


问:
pandas: taking the diff of every second row
I have a dataframe that looks like this

```<code>                       price    signal
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell
</code>```

I want to create a profit column populated with the difference of the previous buy/sell pair

```<code>                       price    signal   profit
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell     -7.88
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell      7.99
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell      2.29
</code>```

How might I best go about this?

Alternative or more efficient approaches to calculating profit also welcome

答:
I would probably do:

```<code>    df['profit'] = df.price - df.price.shift()
</code>```

Do you always close out your position before taking another though?

I would suggest a trade_id column, to use to marry up trades.

Body:
I have a dataframe that looks like this

                       price    signal
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell

I want to create a profit column populated with the difference of the previous buy/sell pair

                       price    signal   profit
time
2017-10-28 13:54:00   293.18    buy
2017-11-02 17:13:04   285.30    sell     -7.88
2017-11-02 18:40:04   283.24    buy
2017-11-03 08:40:06   291.23    sell      7.99
2017-11-03 12:38:06   294.26    buy
2017-11-05 13:33:06   296.52    sell      2.29

How might I best go about this?

Alternative or more efficient approaches to calculating profit also welcome

Body:
I would probably do:

    df['profit'] = df.price - df.price.shift()

Do you always close out your position before taking another though?

I would suggest a trade_id column, to use to marry up trades.


问:
How can I copy a pseudo variable in CMD? I'm trying to automate the copying of part of the date into the clipboard
What I want to have happen is when I open a batch file, the date will automatically be copied into the clipboard in the format of month.day.

In cmd, when I type in %date:~4,2%.%date:~7,2% it outputs the date perfectly, but I can't seem to get it to automatically add it to the clipboard.  Do you guys have any ideas?

Here's the code that I've tried to get to work:

start cmd.exe /c "%date:~4,2%.%date:~7,2% /t | clip"

When I try this, the console outputs the following: '05.26' is not recognized as an internal or external command, operable program or batch file.

答:
You forgot echo to display the time which will be captured by clip.

Try with this:

```<code>start "" cmd /c "echo %date:~4,2%.%date:~7,2% | clip"
</code>```

Body:
You forgot echo to display the time which will be captured by clip.

Try with this:

start "" cmd /c "echo %date:~4,2%.%date:~7,2% | clip"


问:
Visualising static log files on Kibana
I have a couple of Apache Server logs that I want to parse into Kibana for visualisation. Right now, I have tried setting up Elasticsearch + Kibana + Filebeat to ingest these server logs. However, Filebeat seems to be taking up quite a lot of CPU usage.

These logs are static, ie old logs that I collected. Therefore, I do not need Filebeat active monitoring capabilities. In this case, are there any other alternative methods for me to import my Apache Server logs into Kibana only once?

Also, as a side note, what are the differences between filebeat and logstash? I read that logstash is able to parse more info out of the logs such as geo location. However, while trying out my method, it seems that filebeat's apache module is capable of doing so as well.

答:
Filebeat will monitor the logs in the given directory for changes.  You can control that by either moving the processed files to an unwatched directory, or setting the ignore_older option.  Also look at the options that start with close_ for more optimizations in this area.

Filebeat is a lighter-weight local agent that can do some processing and ship the logs to logstash or elasticsearch.  Some local processing (e.g. multiline and ignore) are very powerful.

Logstash can also be used as a shipper, but it's typically used to turn unstructured logs into structured data for insertion into elasticsearch.  Processing options are basically unlimited through the use of built-in filters and you can drop into ruby to do really custom stuff.

Title: Visualising static log files on Kibana


问:
Moving up a directory
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

```<code>chdir("../");
chdir("..")
system("cd ..");
</code>```

none of the above have any effect on the present working directory

答:
you can create a directory on the upper level like this

```<code><?
   mkdir('../newdir/', 0755);
?>
</code>```

without move in it

ContentLicense: CC BY-SA 3.0

Title: Moving up a directory

Body:
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

chdir("../");
chdir("..")
system("cd ..");

none of the above have any effect on the present working directory

Body:
you can create a directory on the upper level like this

<?
   mkdir('../newdir/', 0755);
?>

without move in it


问:
Spring 5 WebClient- retrieve method not getting recognized with groovy but works with java
I am using groovy, spring5, springboot2 and i was trying to  replace Resttemplate with WebClient inorder to makes some synchronous HTTP(REST) calls. Retrieve() in webClient.get().uri("").retrieve() is not getting recognized(compilation error) in .groovy while the same code works in .java

WebClientJava.java

```<code>
import org.springframework.web.reactive.function.client.WebClient;

public class WebClientJava {

    String retriever(){

        WebClient webClient = WebClient.create();

       String responsess =  webClient.get().uri("").retrieve().bodyToMono(String.class).block();

        return responsess;
    }
}
</code>```

WebClientGroovy.groovy

```<code>import org.springframework.web.reactive.function.client.WebClient

class WebClientGroovy {

    String retriever(){

        WebClient webClient = WebClient.create()

        WebClient.RequestHeadersSpec responsess = webClient.get().uri("").retrieve().bodyToMono(String.class).block()

        return responsess
    }
}

</code>```

i expect it work with groovy as it is working with java. Does any one encounter or has any thoughts?

答:
Your problem appears to be caused by a bug in IntelliJ IDEA as the sample project builds successfully on the command line with Maven.

The uri method returns S with S being defined as S extends RequestHeadersSpec<?>. The IDE appears to be unable to cope with this and believes it's dealing with a ? which it treats as java.lang.Object. I would recommend reporting the problem to JetBrains.

In the meantime, you can work around the problem by casting the return from uri:

```<code>String responses = ((WebClient.RequestHeadersSpec)webClient.get().uri(""))
        .retrieve().bodyToMono(String.class).block()
</code>```

Body:
I am using groovy, spring5, springboot2 and i was trying to  replace Resttemplate with WebClient inorder to makes some synchronous HTTP(REST) calls. Retrieve() in webClient.get().uri("").retrieve() is not getting recognized(compilation error) in .groovy while the same code works in .java

WebClientJava.java

import org.springframework.web.reactive.function.client.WebClient;

public class WebClientJava {

    String retriever(){

        WebClient webClient = WebClient.create();

       String responsess =  webClient.get().uri("").retrieve().bodyToMono(String.class).block();

        return responsess;
    }
}

WebClientGroovy.groovy

import org.springframework.web.reactive.function.client.WebClient

class WebClientGroovy {

    String retriever(){

        WebClient webClient = WebClient.create()

        WebClient.RequestHeadersSpec responsess = webClient.get().uri("").retrieve().bodyToMono(String.class).block()

        return responsess
    }
}

i expect it work with groovy as it is working with java. Does any one encounter or has any thoughts?

Body:
Your problem appears to be caused by a bug in IntelliJ IDEA as the sample project builds successfully on the command line with Maven.

The uri method returns S with S being defined as S extends RequestHeadersSpec<?>. The IDE appears to be unable to cope with this and believes it's dealing with a ? which it treats as java.lang.Object. I would recommend reporting the problem to JetBrains.

In the meantime, you can work around the problem by casting the return from uri:

String responses = ((WebClient.RequestHeadersSpec)webClient.get().uri(""))
        .retrieve().bodyToMono(String.class).block()


问:
Custom Loss Function: logits and targets must have the same shape ((?, 1) vs (45000,))
My model predicts everything as 0 in a binary classifier. In total we have 4000 true's and 41000 false's. Therefore we're trying to make a custom loss function.

The error I receive is:

(logits.get_shape(), targets.get_shape()))

ValueError: logits and targets must have the same shape ((?, 1) vs (45000,))

The code looks like this:

```<code>combined = tf.keras.layers.concatenate([modelRNN.output, modelCNN.output])

final_dense = tf.keras.layers.Dense(10, activation='relu')(combined) #ff kijken of dit slim is
final_dense = tf.keras.layers.Dense(1, activation='sigmoid')(final_dense)

final_model = tf.keras.Model(inputs=[modelCNN.input, modelRNN.input], outputs=final_dense)

targets = match_train
logits = final_dense
pos_weight = (45000 - 4539) / 4539

custom_loss = tf.nn.weighted_cross_entropy_with_logits(
    targets,
    logits,
    pos_weight,
    )

final_model.compile(optimizer='adam',
                    loss=custom_loss,
                    metrics=['accuracy'])
</code>```

the shape of the initial arrays are:

```<code>modelCNN = (45000, 28, 28, 1) float64
modelRNN = (45000, 93, 13) float64
labels = (45000,1) boolean
</code>```

The problem was partly solved with the code in the comments.
I now receive an error that I didn't had before. It says:

```<code>TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

  File "<ipython-input-6-42327e5a4b50>", line 3, in <module>
    metrics=['accuracy'])

  File "C:\Users\Tijev\Anaconda3\envs\tfp3.6\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 442, in _method_wrapper
    method(self, *args, **kwargs)

  File "C:\Users\Tijev\Anaconda3\envs\tfp3.6\lib\site-packages\tensorflow\python\keras\engine\training.py", line 215, in compile
    loss = loss or {}
</code>```

答:
Reshape your labels as a 2D tensor.

```<code>targets = np.asarray(match_train).astype('float32').reshape((-1,1))
</code>```

Source: Tensorflow estimator ValueError: logits and labels must have the same shape ((?, 1) vs (?,))

Body:
My model predicts everything as 0 in a binary classifier. In total we have 4000 true's and 41000 false's. Therefore we're trying to make a custom loss function.

The error I receive is:

(logits.get_shape(), targets.get_shape()))

ValueError: logits and targets must have the same shape ((?, 1) vs (45000,))

The code looks like this:

combined = tf.keras.layers.concatenate([modelRNN.output, modelCNN.output])

final_dense = tf.keras.layers.Dense(10, activation='relu')(combined) #ff kijken of dit slim is
final_dense = tf.keras.layers.Dense(1, activation='sigmoid')(final_dense)

final_model = tf.keras.Model(inputs=[modelCNN.input, modelRNN.input], outputs=final_dense)

targets = match_train
logits = final_dense
pos_weight = (45000 - 4539) / 4539

custom_loss = tf.nn.weighted_cross_entropy_with_logits(
    targets,
    logits,
    pos_weight,
    )

final_model.compile(optimizer='adam',
                    loss=custom_loss,
                    metrics=['accuracy'])

the shape of the initial arrays are:

modelCNN = (45000, 28, 28, 1) float64
modelRNN = (45000, 93, 13) float64
labels = (45000,1) boolean

The problem was partly solved with the code in the comments.
I now receive an error that I didn't had before. It says:

TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.

  File "<ipython-input-6-42327e5a4b50>", line 3, in <module>
    metrics=['accuracy'])

  File "C:\Users\Tijev\Anaconda3\envs\tfp3.6\lib\site-packages\tensorflow\python\training\checkpointable\base.py", line 442, in _method_wrapper
    method(self, *args, **kwargs)

  File "C:\Users\Tijev\Anaconda3\envs\tfp3.6\lib\site-packages\tensorflow\python\keras\engine\training.py", line 215, in compile
    loss = loss or {}

Body:
Reshape your labels as a 2D tensor.

targets = np.asarray(match_train).astype('float32').reshape((-1,1))

Source: Tensorflow estimator ValueError: logits and labels must have the same shape ((?, 1) vs (?,))


问:
React groupBy and print into table
EDITED:
methods groupBy, omit and mapValue are imported from:

```<code>import groupBy from 'lodash/groupBy';
import mapValues from 'lodash/mapValues';
import omit from 'lodash/omit';
</code>```

I have this json

```<code>[{
    "name": "Jitka",
    "orderNumber": "1",
    "order": false
},
{
    "name": "Jitka",
    "orderNumber": "0",
    "order": false
},
{
    "name": "Petr",
    "orderNumber": "6",
    "order": false
}]
</code>```

In react I need group value by name. And after grouping I need data print into table in format

The problem is, how convert this data, which I groupBy name into table in this format.

My code is:

```<code>{
        const ordersByName = groupBy(this.state && this.state.orders, 'name');
        let order = mapValues(ordersByName, x => x.map(y => omit(y, 'name')));
        this.state.sortedOrders.push(order);

    }

    return (
        <div>
            <MyNavbar/>
            <div className="container">
                <table className="table">
                    <tbody>
                    <tr>
                        <th>Name</th>
                        <th>Order number</th>
                        <th>Order</th>
                    </tr>
                    {this.state.sortedOrders.map((offer) => {
                        console.log(offer);

                    })}
                    </tbody>
                </table>
            </div>
        </div>
</code>```

Thank you.

答:
Your data needs to be reduced first since you are essentially grouping on orderNumber. So since you are already using lodash you can try doing this:

```<code>let data = _(this.state.sortedOrders) // <-- chain this array via _.chain
  .groupBy('name')  // <-- group by name first
  .mapValues(arr =>  // <-- map through the values of the object from groupBy
    _.mergeWith(  // <-- merge the grouped by name records
      ..._.sortBy(arr, 'orderNumber'),  // <-- sort the array by `orderNumber`
      (o, s, k) => _.isEqual(k, 'orderNumber') ? o + (s ? ',' + s : '') : o)
  )
  .values() // <-- get the values of the final object
  .value()  // <-- get the final result from the chaining
</code>```

And then your render would be:

```<code><div>
  <MyNavbar/>
  <div className="container">
    <table className="table">
      <tbody>
        <tr>
          <th>Name</th>
          <th>Order number</th>
          <th>Order</th>
        </tr>
        {data.map(offer => (
        <tr>
            <td>{offer.name}</td>
            <td>{offer.orderNumber}</td>
            <td>{offer.order}</td>
        </tr>
        ))}
      </tbody>
    </table>
  </div>
</div>
</code>```

The short story is that you need to get your data to look like the result of this:

let data = [{ "name": "Jitka", "orderNumber": "1", "order": false }, { "name": "Jitka", "orderNumber": "0", "order": false }, { "name": "Petr", "orderNumber": "6", "order": false } ]

let result = _(data)
  .groupBy('name')
  .mapValues(arr =>
    _.mergeWith(
      ..._.sortBy(arr, 'orderNumber'),
      (o, s, k) => _.isEqual(k, 'orderNumber') ? o + (s ? ',' + s : '') : o)
  )
  .values()
  .value()

console.log(result)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

As you can see you have 2 records instead of your initial 3 since we merged two of them by orderNumber.

This can obviously be done with Array.reduce/Array.sort etc but since you already are using lodash you can simply utilize its groupBy/mergeWith etc functions.

Title: React groupBy and print into table

Body:
EDITED:
methods groupBy, omit and mapValue are imported from:

import groupBy from 'lodash/groupBy';
import mapValues from 'lodash/mapValues';
import omit from 'lodash/omit';

I have this json

[{
    "name": "Jitka",
    "orderNumber": "1",
    "order": false
},
{
    "name": "Jitka",
    "orderNumber": "0",
    "order": false
},
{
    "name": "Petr",
    "orderNumber": "6",
    "order": false
}]

In react I need group value by name. And after grouping I need data print into table in format

The problem is, how convert this data, which I groupBy name into table in this format.

My code is:

{
        const ordersByName = groupBy(this.state && this.state.orders, 'name');
        let order = mapValues(ordersByName, x => x.map(y => omit(y, 'name')));
        this.state.sortedOrders.push(order);

    }

    return (

            <MyNavbar/>

                        Name
                        Order number
                        Order

                    {this.state.sortedOrders.map((offer) => {
                        console.log(offer);

                    })}

Thank you.

Body:
Your data needs to be reduced first since you are essentially grouping on orderNumber. So since you are already using lodash you can try doing this:

let data = _(this.state.sortedOrders) // <-- chain this array via _.chain
  .groupBy('name')  // <-- group by name first
  .mapValues(arr =>  // <-- map through the values of the object from groupBy
    _.mergeWith(  // <-- merge the grouped by name records
      ..._.sortBy(arr, 'orderNumber'),  // <-- sort the array by `orderNumber`
      (o, s, k) => _.isEqual(k, 'orderNumber') ? o + (s ? ',' + s : '') : o)
  )
  .values() // <-- get the values of the final object
  .value()  // <-- get the final result from the chaining

And then your render would be:

<div>
  <MyNavbar/>
  <div className="container">
    <table className="table">
      <tbody>
        <tr>
          <th>Name</th>
          <th>Order number</th>
          <th>Order</th>
        </tr>
        {data.map(offer => (
        <tr>
            <td>{offer.name}</td>
            <td>{offer.orderNumber}</td>
            <td>{offer.order}</td>
        </tr>
        ))}
      </tbody>
    </table>
  </div>
</div>

The short story is that you need to get your data to look like the result of this:

let data = [{ "name": "Jitka", "orderNumber": "1", "order": false }, { "name": "Jitka", "orderNumber": "0", "order": false }, { "name": "Petr", "orderNumber": "6", "order": false } ]

let result = _(data)
  .groupBy('name')
  .mapValues(arr =>
    _.mergeWith(
      ..._.sortBy(arr, 'orderNumber'),
      (o, s, k) => _.isEqual(k, 'orderNumber') ? o + (s ? ',' + s : '') : o)
  )
  .values()
  .value()

console.log(result)

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

As you can see you have 2 records instead of your initial 3 since we merged two of them by orderNumber.

This can obviously be done with Array.reduce/Array.sort etc but since you already are using lodash you can simply utilize its groupBy/mergeWith etc functions.


问:
Combining Semaphore to limit async requests and dispatch groups for .notify with defer and App is freezing
I have a backend that can handle maximum 4 simultaneous network connections.  To compensate, I have made an array called urlsQueue that contains all the parameters needed for each network request.  The code below produces the results I want if the urlsQueue contains 4 or less elements.  However, if I enter func downloadBusiness with 5+ elements inside urlsQueue, the app freezes.

```<code>func downloadBusinesses(latitude: Double, longitude: Double){
    if urlsQueue.isEmpty {return}
    let semaphore = DispatchSemaphore(value: 4)
    let dispatchGroup = DispatchGroup()

    for (index, element) in urlsQueue.enumerated(){
        dispatchGroup.enter()
        semaphore.wait()
        _ = Client.getBusinesses(latitude: latitude, longitude: longitude, offset: element.offset ,completion: { [weak self] (yelpDataStruct, result) in
            defer {
                semaphore.signal()
                dispatchGroup.leave()
            }
            self?.handleGetNearbyBusinesses(inputData: yelpDataStruct, result: result)
        })
    }
    dispatchGroup.notify(queue: .main) {[weak self] in
        self?.runDownloadAgain()
    }
}
</code>```

If a network request succeeds, I remove the corresponding value from urlsQueue. If the network request fails, the entry stays inside urlsQueue.  After iterating through every element in urlsQueue, I repeat the process again if the loop is not empty.  That way I can re-do any failed network requests.

```<code>func runDownloadAgain(){
    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] timer in
        self?.downloadBusinesses(latitiude: self!.latitude, longitude: self!.longitude)
    }
    timer.fire()
}
</code>```

I have been able to debug the breaking point in the app is within the for-enumerated loop above.  After the 4th time in the loop, everything just stops.  If I'm stepping through the program, I am unable to move forward.  If I adjust the hard-coded value of 4 to any other integer, the problem repeats with the code block only succeeding if urlsQueue.count  <= x where x is the value in DispatchSemaphore(value: x)

The problem lies in my improper mixing of dispatchGroup/semaphore/defer.  But I'm really struggling to see how I can re-combine these elements successfully to avoid the app freeze while limiting network connections to 4.

答:
As you start always at index zero of the URL queue exit the loop if the index > 3 and drop the semaphore</p>

```<code>func downloadBusinesses(latitiude: Double, longitude: Double){
    if urlsQueue.isEmpty {return}
    let dispatchGroup = DispatchGroup()

    for (index, element) in urlsQueue.enumerated(){
        if index > 3 { break }
        dispatchGroup.enter()
        _ = Client.getBusinesses(latitude: latitude, longitude: longitude, offset: element.offset ,completion: { [weak self] (yelpDataStruct, result) in
            defer {
                dispatchGroup.leave()
            }
            self?.handleGetNearbyBusinesses(inputData: yelpDataStruct, result: result)
        })
    }
    dispatchGroup.notify(queue: .main) { // GCD closures don't cause retain cycles
        self.runDownloadAgain()
    }
}
</code>```

Body:
I have a backend that can handle maximum 4 simultaneous network connections.  To compensate, I have made an array called urlsQueue that contains all the parameters needed for each network request.  The code below produces the results I want if the urlsQueue contains 4 or less elements.  However, if I enter func downloadBusiness with 5+ elements inside urlsQueue, the app freezes.

func downloadBusinesses(latitude: Double, longitude: Double){
    if urlsQueue.isEmpty {return}
    let semaphore = DispatchSemaphore(value: 4)
    let dispatchGroup = DispatchGroup()

    for (index, element) in urlsQueue.enumerated(){
        dispatchGroup.enter()
        semaphore.wait()
        _ = Client.getBusinesses(latitude: latitude, longitude: longitude, offset: element.offset ,completion: { [weak self] (yelpDataStruct, result) in
            defer {
                semaphore.signal()
                dispatchGroup.leave()
            }
            self?.handleGetNearbyBusinesses(inputData: yelpDataStruct, result: result)
        })
    }
    dispatchGroup.notify(queue: .main) {[weak self] in
        self?.runDownloadAgain()
    }
}

If a network request succeeds, I remove the corresponding value from urlsQueue. If the network request fails, the entry stays inside urlsQueue.  After iterating through every element in urlsQueue, I repeat the process again if the loop is not empty.  That way I can re-do any failed network requests.

func runDownloadAgain(){
    let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { [weak self] timer in
        self?.downloadBusinesses(latitiude: self!.latitude, longitude: self!.longitude)
    }
    timer.fire()
}

I have been able to debug the breaking point in the app is within the for-enumerated loop above.  After the 4th time in the loop, everything just stops.  If I'm stepping through the program, I am unable to move forward.  If I adjust the hard-coded value of 4 to any other integer, the problem repeats with the code block only succeeding if urlsQueue.count  <= x where x is the value in DispatchSemaphore(value: x)

The problem lies in my improper mixing of dispatchGroup/semaphore/defer.  But I'm really struggling to see how I can re-combine these elements successfully to avoid the app freeze while limiting network connections to 4.

Body:
As you start always at index zero of the URL queue exit the loop if the index > 3 and drop the semaphore

func downloadBusinesses(latitiude: Double, longitude: Double){
    if urlsQueue.isEmpty {return}
    let dispatchGroup = DispatchGroup()

    for (index, element) in urlsQueue.enumerated(){
        if index > 3 { break }
        dispatchGroup.enter()
        _ = Client.getBusinesses(latitude: latitude, longitude: longitude, offset: element.offset ,completion: { [weak self] (yelpDataStruct, result) in
            defer {
                dispatchGroup.leave()
            }
            self?.handleGetNearbyBusinesses(inputData: yelpDataStruct, result: result)
        })
    }
    dispatchGroup.notify(queue: .main) { // GCD closures don't cause retain cycles
        self.runDownloadAgain()
    }
}


问:
How to access destination service which is behind RabbitMQ using S4 Cloud SDK Connectivity
We are using S4SDK to access destination service. it needs to work in multi-tenancy env. Normally if the app is a frontend app, the request context is triggered by user request. Accessing destination service with multi-tenancy is doable with approuter and XUAA.
In our case, our application is behind RabbitMQ which is not trigger by a user request (e.g. REST API call). Currently we are using the class com.sap.cloud.sdk.cloudplatform.connectivity.DestinationAccessor from cloud SDK. we can retrieve a tenant id out of message (RabbitMQ/AMQP). The issue is that we cannot find a way to inject the tenant id or clone a JWT token into DestinationAccessor from S4SDK. We look for a way/guidance of how to achieve that. We expect this exchange/clone token is provided by the SDK.</p>

答:
You should be able to use the JwtBasedRequestContextExecutor for this purpose.</p>

```<code>new JwtBasedRequestContextExecutor()
    .withJwt(encodedJwt)
    .execute(() -> {
        // code using the SAP Cloud SDK
    });
</code>```

Body:
You should be able to use the JwtBasedRequestContextExecutor for this purpose.

new JwtBasedRequestContextExecutor()
    .withJwt(encodedJwt)
    .execute(() -> {
        // code using the SAP Cloud SDK
    });


问:
Subtract a number from a SQL Query in code-igniter framework
I am wondering how I can subtract 1 from a field in my database
i tried the following but it just set it to "-1", did not actually subtract it.</p>

```<code>// update listing status to sold
this->db->update("listings", array("cases" => "cases" - 1,
</code>```

答:
```<code>$this->db->set('cases','`cases`-1',FALSE);
$this->db->where('id', $id);/*whatever condition you want*/
$this->db->update('yourtablename');
</code>```

Heres a link from codeigniter userguide:
https://codeigniter.com/user_guide/database/query_builder.html

Body:
I am wondering how I can subtract 1 from a field in my database
i tried the following but it just set it to "-1", did not actually subtract it.

// update listing status to sold
this->db->update("listings", array("cases" => "cases" - 1,

Body:
$this->db->set('cases','`cases`-1',FALSE);
$this->db->where('id', $id);/*whatever condition you want*/
$this->db->update('yourtablename');

Heres a link from codeigniter userguide:
https://codeigniter.com/user_guide/database/query_builder.html


问:
Comma in return value
I know the desired syntax lies in the first function but I for the life of me can't find where it is.

I've attempted to remove commas and add spaces to each .split() each has yielded an undesired return value.

```<code>def get_country_codes(prices):
    price_list = prices.split(',')
    results = ''
    for price in price_list:
        results += price.split('$')[0]
    return results

def main():
    prices = "US$40, AU$89, JP$200"
    price_result = get_country_codes(prices)
    print(price_result)

if __name__ == "__main__":
    main()
</code>```

The current output:

```<code>US AU JP
</code>```

The desired output:

```<code>US, AU, JP
</code>```

答:
Look at the successive steps:

Your string:

```<code>In [1]: prices = "US$40, AU$89, JP$200"
</code>```

split into a list on comma

```<code>In [2]: alist = prices.split(',')
In [3]: alist
Out[3]: ['US$40', ' AU$89', ' JP$200']
</code>```

split the substrings on $

```<code>In [4]: [price.split('$') for price in alist]
Out[4]: [['US', '40'], [' AU', '89'], [' JP', '200']]
</code>```

select the first element:

```<code>In [5]: [price.split('$')[0] for price in alist]
Out[5]: ['US', ' AU', ' JP']
</code>```

Your += joins the strings as is; same as join with ''.  Note that the substrings still have the initial blank for the original string.

```<code>In [6]: ''.join([price.split('$')[0] for price in alist])
Out[6]: 'US AU JP'
</code>```

Join with comma:

```<code>In [7]: ','.join([price.split('$')[0] for price in alist])
Out[7]: 'US, AU, JP'
</code>```

join is the easiest way of joining a list of strings with a specific delimiter between, in effect reversing a split.  += in a loop is harder to use, since it tends to add an extra delimiter at the start or end.

Title: Comma in return value

Body:
I know the desired syntax lies in the first function but I for the life of me can't find where it is.

I've attempted to remove commas and add spaces to each .split() each has yielded an undesired return value.

def get_country_codes(prices):
    price_list = prices.split(',')
    results = ''
    for price in price_list:
        results += price.split('$')[0]
    return results

def main():
    prices = "US$40, AU$89, JP$200"
    price_result = get_country_codes(prices)
    print(price_result)

if __name__ == "__main__":
    main()

The current output:

US AU JP

The desired output:

US, AU, JP

Body:
Look at the successive steps:

Your string:

In [1]: prices = "US$40, AU$89, JP$200"

split into a list on comma

In [2]: alist = prices.split(',')
In [3]: alist
Out[3]: ['US$40', ' AU$89', ' JP$200']

split the substrings on $

In [4]: [price.split('$') for price in alist]
Out[4]: [['US', '40'], [' AU', '89'], [' JP', '200']]

select the first element:

In [5]: [price.split('$')[0] for price in alist]
Out[5]: ['US', ' AU', ' JP']

Your += joins the strings as is; same as join with ''.  Note that the substrings still have the initial blank for the original string.

In [6]: ''.join([price.split('$')[0] for price in alist])
Out[6]: 'US AU JP'

Join with comma:

In [7]: ','.join([price.split('$')[0] for price in alist])
Out[7]: 'US, AU, JP'

join is the easiest way of joining a list of strings with a specific delimiter between, in effect reversing a split.  += in a loop is harder to use, since it tends to add an extra delimiter at the start or end.


问:
Expand Variadic Template Pack by Pairs
I'm creating a generic collection of Nodes. Each Node has a Start and End type. And the End type of one must match the Start type of the next.

If I were to list each of the types in the collection the constructor would look like this (for four types):

```<code>template <typename Start, typename End>
class Node {
};

template <typename A, typename B, typename C, typename D>
class Collection
{
public:
    Collection(Node<A, B> n1, Node<B, C> n2, Node<C, D> n3) { }
};
</code>```

But when I try to write constuctor as a variadic template to support any number of types, I am stumped.

答:
With some indirection, you might do:

```<code>template <typename Start, typename End>
class Node {
    // ...
};

// Implementation using the Nodes
// You might add typedef in Node to retrieve Start/End if needed (or create traits)
template <typename ... Nodes>
struct CollectionImpl
{
    CollectionImpl(Nodes ... ns) : nodes(ns...){}

    std::tuple<Nodes...> nodes; // You probably want something like that
};

// Helper class to build the type
template <typename Seq, typename Tup> struct CollectionMaker;

template <std::size_t ... Is, typename Tuple>
struct CollectionMaker<std::index_sequence<Is...>, Tuple>
{
    using type = CollectionImpl<Node<std::tuple_element_t<Is, Tuple>,
                                     std::tuple_element_t<Is + 1, Tuple>>...>;
};

// Wanted interface.
template <typename ... Ts>
using Collection = typename CollectionMaker<std::make_index_sequence<sizeof...(Ts) - 1>,
                                            std::tuple<Ts...>>::type;
</code>```

Demo

Title: Expand Variadic Template Pack by Pairs

Body:
I'm creating a generic collection of Nodes. Each Node has a Start and End type. And the End type of one must match the Start type of the next.

If I were to list each of the types in the collection the constructor would look like this (for four types):

template <typename Start, typename End>
class Node {
};

template <typename A, typename B, typename C, typename D>
class Collection
{
public:
    Collection(Node n1, Node n2, Node<C, D> n3) { }
};

But when I try to write constuctor as a variadic template to support any number of types, I am stumped.

Body:
With some indirection, you might do:

template <typename Start, typename End>
class Node {
    // ...
};

// Implementation using the Nodes
// You might add typedef in Node to retrieve Start/End if needed (or create traits)
template <typename ... Nodes>
struct CollectionImpl
{
    CollectionImpl(Nodes ... ns) : nodes(ns...){}

    std::tuple<Nodes...> nodes; // You probably want something like that
};

// Helper class to build the type
template <typename Seq, typename Tup> struct CollectionMaker;

template <std::size_t ... Is, typename Tuple>
struct CollectionMaker<std::index_sequence<Is...>, Tuple>
{
    using type = CollectionImpl<Node<std::tuple_element_t<Is, Tuple>,
                                     std::tuple_element_t<Is + 1, Tuple>>...>;
};

// Wanted interface.
template <typename ... Ts>
using Collection = typename CollectionMaker<std::make_index_sequence<sizeof...(Ts) - 1>,
                                            std::tuple<Ts...>>::type;

Demo


问:
MERN Stack: Using Redux to store whether user is logged in or not
I'm new to backend programming and building my first full stack project and using Express/Mongoose/Mongo and Passport.js for the first time.

I have built "sign in with Github" functionality and have everything with Passport set up. Now I want to use Redux to store whether or not a user is logged in. If the user is logged in I want to change my navigation bar i.e. if the user isn't logged in one link says "log in", but if the user is logged in the "log in" link changes to "profile".

I know I can use the ternary operator in my React component to toggle the link depending on whether the user is logged in.

How do I use Redux to store whether a user is logged in? Here's what I have so far:

Redux action:

```<code>export function loggedIn() {
    return {
      type: "LOGGED_IN",
      loggedIn: false
    }
};
</code>```

Redux reducer:

```<code>export default function reducer(state = {
  loggedIn: false
}, action) {
  switch(action.type) {
    case "LOGGED_IN": {
      return {
        ...state,
        loggedIn: true
      }
    }
    case "LOGGED_OUT": {
      return {
        ...state,
        loggedIn: false
      }
    }
    default: return state;
  }

}
</code>```

I'm my Express route I am using the following middleware:

```<code>// Checks if user is not logged in
const authCheck = (req, res, next) => {
    if(!req.user) {
      // If user is not logged in, redirect them to login page
      res.redirect('/auth/login');
    }
    else {
      // If user is logged in call next in router.get

      // Would this be the proper place to dispatch to the Redux store
      // whether a user is logged in?
      dispatch(loggedIn(true));
      // After updating the Redux store call next()
      next();
    }
};
</code>```

How can I properly store in state whether the user is logged in/out and then access this state in the React component so I can use the ternary operator to choose whether to display "logged in" or "profile" in my navigation bar?

答:
It is advisable not to mix your backend routes with the reducer dispatch. I would suggest sending back a response res.status(200).send({ loggedIn: true }) in your middleware.

```<code>// Checks if user is not logged in
const authCheck = (req, res, next) => {
    if(!req.user) {
      // If user is not logged in, redirect them to login page
      res.redirect('/auth/login');
    }
    else {
      res.status(200).send({ loggedIn: true })
      next();
    }
};
</code>```

The call to this middleware can then dispatch a success based on the response.

```<code> if (res.status === 200) {
  dispatch(loggedIn(res.loggedIn));
 }
 else {
  dispatch({ type: 'LOGIN_FAILED'})
 }
</code>```

Body:
I'm new to backend programming and building my first full stack project and using Express/Mongoose/Mongo and Passport.js for the first time.

I have built "sign in with Github" functionality and have everything with Passport set up. Now I want to use Redux to store whether or not a user is logged in. If the user is logged in I want to change my navigation bar i.e. if the user isn't logged in one link says "log in", but if the user is logged in the "log in" link changes to "profile".

I know I can use the ternary operator in my React component to toggle the link depending on whether the user is logged in.

How do I use Redux to store whether a user is logged in? Here's what I have so far:

Redux action:

export function loggedIn() {
    return {
      type: "LOGGED_IN",
      loggedIn: false
    }
};

Redux reducer:

export default function reducer(state = {
  loggedIn: false
}, action) {
  switch(action.type) {
    case "LOGGED_IN": {
      return {
        ...state,
        loggedIn: true
      }
    }
    case "LOGGED_OUT": {
      return {
        ...state,
        loggedIn: false
      }
    }
    default: return state;
  }

}

I'm my Express route I am using the following middleware:

// Checks if user is not logged in
const authCheck = (req, res, next) => {
    if(!req.user) {
      // If user is not logged in, redirect them to login page
      res.redirect('/auth/login');
    }
    else {
      // If user is logged in call next in router.get

      // Would this be the proper place to dispatch to the Redux store
      // whether a user is logged in?
      dispatch(loggedIn(true));
      // After updating the Redux store call next()
      next();
    }
};

How can I properly store in state whether the user is logged in/out and then access this state in the React component so I can use the ternary operator to choose whether to display "logged in" or "profile" in my navigation bar?

Body:
It is advisable not to mix your backend routes with the reducer dispatch. I would suggest sending back a response res.status(200).send({ loggedIn: true }) in your middleware.

// Checks if user is not logged in
const authCheck = (req, res, next) => {
    if(!req.user) {
      // If user is not logged in, redirect them to login page
      res.redirect('/auth/login');
    }
    else {
      res.status(200).send({ loggedIn: true })
      next();
    }
};

The call to this middleware can then dispatch a success based on the response.

 if (res.status === 200) {
  dispatch(loggedIn(res.loggedIn));
 }
 else {
  dispatch({ type: 'LOGIN_FAILED'})
 }


问:
What is the colon operator doing here?
What are these lines of code doing?

```<code>x0 = rand(n,2)
x0(:,1)=W*x0(:,1)
x0(:,2)=H*x0(:,2)
x0=x0(:)
</code>```

Is this just one big column vector?

答:
I'd encourage you to take a MATLAB Tutorial as indexing arrays is a fundamental skill. Also see Basic Concepts in MATLAB.  Line-by-line descriptions are below to get you started.

What are these lines of code doing?

Let's take this line by line.

1. This line uses rand() to generate an n x 2 matrix of uniform random numbers (~U(0,1)).

x0 = rand(n,2)    % Generate nx2 matrix of U(0,1) random numbers

2. Multiply the first column by W

In this case, x0(:,1) means take all rows of x0 (the colon in the first argument) and the 1st column (the 1). Here, the * operator indicates W is a scalar or an appropriately sized array for feasible matrix multiplication (my guess is a scalar). The notation .* can be used for element-by-element multiplication; see here and here for more details.

x0(:,1)=W*x0(:,1)    % Multiply (all rows) 1st column by W

3. Multiply the first column by H.

Using similar logic as #2.

x0(:,2)=H*x0(:,2)    % Multiply (all rows) 2nd column by H

4. Force column

The x0(:) takes the array x0 and forces all elements into a single column.

From the documentation for colon:

A(:) reshapes all elements of A into a single column vector. This has
no effect if A is already a column vector.

A related operation is forcing a row vector by combining this with the transpose operator.

For example, try the following:  x0(:).'

```<code>x0 = x0(:)       % Force Column
x0 = x0(:).'     % Force Row
</code>```

Related Posts:

What is Matlab's colon operator called?

How does MATLAB's colon operator work?

Combination of colon-operations in MATLAB

Title: What is the colon operator doing here?

Body:
What are these lines of code doing?

x0 = rand(n,2)
x0(:,1)=W*x0(:,1)
x0(:,2)=H*x0(:,2)
x0=x0(:)

Is this just one big column vector?

Body:
I'd encourage you to take a MATLAB Tutorial as indexing arrays is a fundamental skill. Also see Basic Concepts in MATLAB.  Line-by-line descriptions are below to get you started.

What are these lines of code doing?

Let's take this line by line.

1. This line uses rand() to generate an n x 2 matrix of uniform random numbers (~U(0,1)).

x0 = rand(n,2)    % Generate nx2 matrix of U(0,1) random numbers

2. Multiply the first column by W

In this case, x0(:,1) means take all rows of x0 (the colon in the first argument) and the 1st column (the 1). Here, the * operator indicates W is a scalar or an appropriately sized array for feasible matrix multiplication (my guess is a scalar). The notation .* can be used for element-by-element multiplication; see here and here for more details.

x0(:,1)=W*x0(:,1)    % Multiply (all rows) 1st column by W

3. Multiply the first column by H.

Using similar logic as #2.

x0(:,2)=H*x0(:,2)    % Multiply (all rows) 2nd column by H

4. Force column

The x0(:) takes the array x0 and forces all elements into a single column.

From the documentation for colon:

A(:) reshapes all elements of A into a single column vector. This has
no effect if A is already a column vector.

A related operation is forcing a row vector by combining this with the transpose operator.

For example, try the following:  x0(:).'

x0 = x0(:)       % Force Column
x0 = x0(:).'     % Force Row

Related Posts:

What is Matlab's colon operator called?

How does MATLAB's colon operator work?

Combination of colon-operations in MATLAB


问:
Copy & insert row with formulas in protected sheet
I want to insert a row that is copied from above line with formulas in it by double click. and when I turned on protect worksheet macro is not working. I tried the method of ActiveSheet.Unprotect Password:="1" but it is not working. Could any of you guide me what my mistake is and what the solution is?

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect Password:="1"
If [BusinessType] = "Operating Lease (Contract Based)" Then
  Range("hide").EntireRow.Hidden = False
Else
    Range("hide").EntireRow.Hidden = True
End If
ActiveSheet.Protect Password:="1"
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As
Boolean)
ActiveSheet.Unprotect Password:="1"

'Updateby Extendoffice 20160725

    Cancel = True
    Target.Offset(1).EntireRow.Insert
    Target.EntireRow.Copy Target.Offset(1).EntireRow
    On Error Resume Next
    Target.Offset(1).EntireRow.SpecialCells(xlConstants).ClearContents
ActiveSheet.Protect Password:="1"
End Sub
</code>```

答:
One should be always careful when using Worksheet_Change event, because it gets triggered with every worksheet change. In this case, calling Target.Offset(1).EntireRow.Insert triggers the Worksheet_Change event. And the last step in the event is protecting the sheet, which throws an error on the next line Target.EntireRow.Copy Target.Offset(1).EntireRow. When this line of code runs, the sheet is protected, which throws an error.

Possible solutions:

Avoid using Worksheet_Change if possible.

Remove Sheet.protect() from the Worksheet_Change.

Disable events in the Worksheet_BeforeDoubleClick using Application.EnableEvents = False. However, i do not recommend doing this, as you have to make sure that events are enabled again (using proper error handling).

Body:
I want to insert a row that is copied from above line with formulas in it by double click. and when I turned on protect worksheet macro is not working. I tried the method of ActiveSheet.Unprotect Password:="1" but it is not working. Could any of you guide me what my mistake is and what the solution is?

Private Sub Worksheet_Change(ByVal Target As Range)
ActiveSheet.Unprotect Password:="1"
If [BusinessType] = "Operating Lease (Contract Based)" Then
  Range("hide").EntireRow.Hidden = False
Else
    Range("hide").EntireRow.Hidden = True
End If
ActiveSheet.Protect Password:="1"
End Sub

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As
Boolean)
ActiveSheet.Unprotect Password:="1"

'Updateby Extendoffice 20160725

    Cancel = True
    Target.Offset(1).EntireRow.Insert
    Target.EntireRow.Copy Target.Offset(1).EntireRow
    On Error Resume Next
    Target.Offset(1).EntireRow.SpecialCells(xlConstants).ClearContents
ActiveSheet.Protect Password:="1"
End Sub


问:
Which is the best use of discard (or act_as_paranoid) in rails-admin?
I'm using the gem discard and also rails-admin. I would like to know which is the best approach to list my active users in a shop in rails admin, taking into consideration the users kept

I've created a method in the model shop:

```<code>class Shop < ApplicationRecord
  include ShopRailsAdmin

 has_many :users

 def active_users
  users.kept
 end
end
</code>```

In rails admin I'm using:

```<code>field :active_users do
  label 'Users'
end
</code>```

But I'm receiving an AssociationRelation instead of a CollectionProxy so in the view, the association looks like

#<User::ActiveRecord_AssociationRelation:0x00007f9c34c1f8e0>

Is there another way to do this so I can avoid defining the method in the model shop?

PD: the tag should have been also discard but it does not exist and I could not create it.

Thanks!

答:
You need to define it as an scoped association

class Shop < ApplicationRecord
  include ShopRailsAdmin

 has_many :users
 has_many :active_users, -> lambda {
    where(discarded_at: nil)
 }, class_name: 'User'
end
```

I'm assuming you did not personalize the discard_column.

Rails admin should display them right.

Body:
I'm using the gem discard and also rails-admin. I would like to know which is the best approach to list my active users in a shop in rails admin, taking into consideration the users kept

I've created a method in the model shop:

class Shop < ApplicationRecord
  include ShopRailsAdmin

 has_many :users

 def active_users
  users.kept
 end
end

In rails admin I'm using:

field :active_users do
  label 'Users'
end

But I'm receiving an AssociationRelation instead of a CollectionProxy so in the view, the association looks like

#<User::ActiveRecord_AssociationRelation:0x00007f9c34c1f8e0>

Is there another way to do this so I can avoid defining the method in the model shop?

PD: the tag should have been also discard but it does not exist and I could not create it.

Thanks!

Body:
You need to define it as an scoped association

class Shop < ApplicationRecord
  include ShopRailsAdmin

 has_many :users
 has_many :active_users, -> lambda {
    where(discarded_at: nil)
 }, class_name: 'User'
end

I'm assuming you did not personalize the discard_column.

Rails admin should display them right.


问:
Assign nil value to double in Objective-C
In my iOS iPhone app I have this method:

```<code>-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;
</code>```

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

答: You can only assign nil to pointer types. You can assign 0.0 to a double however.

Body:
In my iOS iPhone app I have this method:

-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?


问:
Spring boot: How to convert thymeleaf to jsp
I recently followed a authentication and authorization tutorial using spring boot. It's working fine and I want to integrate it to my existing project. The tutorial I followed is written in thymeleaf and my current project is in jsp. I tried searching online but it's giving me errors.

This is my code:

Controller

```<code>@RequestMapping(value = { "/","/welcome" }, method = RequestMethod.GET)
public ModelAndView test() {
    ModelAndView model = new ModelAndView("welcomePage");
    model.addObject("title","Welcome");
    model.addObject("message","This is welcome page");
    return model;
}
</code>```

Thymeleaf

```<code><a th:if="${#request.userPrincipal != null}" th:href="@{/logout}">Logout</a>
</code>```

JSP

```<code><%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    <div>
        <a href="/">Home</a> |
        <a href="/userInfo">User Info </a> |
        <a href="/admin">Admin</a> |

        <c:if test="${pageContext.request.userPrincipal != null}">
            <h2>Logout</h2>
            <br>
        </c:if>

        ${pageContext.request.userPrincipal}

    </div>

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

pom.xml

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</code>```

application.properties

This is one of the problems that I am encountering. When I tried to run it, it's giving me this error.

```<code>/WEB-INF/jsp/_menu.jsp (line: [18], column: [2]) According to TLD or attribute directive in tag file, attribute [test] does not accept any expressions
</code>```

This is my first time using this. Hope you could help me. Thank you so much!!

答:
Use this in you jsp instead of what you have:

" <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> "

Without the quotation marks

Body:
I recently followed a authentication and authorization tutorial using spring boot. It's working fine and I want to integrate it to my existing project. The tutorial I followed is written in thymeleaf and my current project is in jsp. I tried searching online but it's giving me errors.

This is my code:

Controller

@RequestMapping(value = { "/","/welcome" }, method = RequestMethod.GET)
public ModelAndView test() {
    ModelAndView model = new ModelAndView("welcomePage");
    model.addObject("title","Welcome");
    model.addObject("message","This is welcome page");
    return model;
}

Thymeleaf

Logout

JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<!DOCTYPE html>

<meta charset="ISO-8859-1">
<title>Insert title here</title>

        Home |
        User Info  |
        Admin |

        <c:if test="${pageContext.request.userPrincipal != null}">

Logout

        </c:if>

        ${pageContext.request.userPrincipal}

pom.xml

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>

application.properties

This is one of the problems that I am encountering. When I tried to run it, it's giving me this error.

/WEB-INF/jsp/_menu.jsp (line: [18], column: [2]) According to TLD or attribute directive in tag file, attribute [test] does not accept any expressions

This is my first time using this. Hope you could help me. Thank you so much!!


问:
Is there any scenario where using multithreading on a single core CPU be beneficial?
I know that using multithreading in a single core CPU is possible. But can somebody help me out with a situation or a scenario where it might be useful. I was asked this question in an interview round.</p>

答:
Threads are a model of concurrency: Using threads enables you to write a program in which multiple, stateful activities each progress at their own pace, independently of one another.

Parallel processing is a form of concurrency, and so threads are one way to exploit the resources of a multiprocessor system, but there are other reasons to have concurrent activities in a program.

One classic example is a server that can support arbitrarily many simultaneous, stateful client connections. The server has one thread that awaits new connections, and that thread creates a new client thread each time a new connection is accepted.  Each client thread awaits messages from its client, and advances its state accordingly. The state of each client connection can be partially implicit in local variables on the client thread's stack and, on where the thread is executing in the code at any given moment. This design can be much easier to understand than a single thread that must accept input from every client, and explicitly store and update the state of each client.

A personal preference of mine is to describe every thread I create by first saying what the thread waits for:  The server thread in the example above waits for new clients.  Each client thread waits for commands from its client. In a GUI application, the GUI thread waits for keyboard and mouse events.  In a parallel processing scenario, there are worker threads that wait for tasks (computations) to be performed. etc.


问:
"ModuleNotFoundError", How to fix it?
```<code>from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(receiver, instance, created, **kwargs):
    if created:
        Profile.objects.create(User=instance)

@receiver(post_save, sender=User)
def save_profile(receiver, instance, **kwargs):
    instance.Profile.save()
</code>```

apps.py

```<code>from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'
    def ready(self):
        import users.signals
</code>```

Error in server

File "C:\Users\Mian.G\Desktop\django_admin\users\apps.py", line 7, in
  ready
      import users.signals ModuleNotFoundError: No module named 'users.signals'

答: You've probably already solved this, as I see the post is almost 2 months old. But just in case you haven't.....is it possible you have created the 'signals.py' file in the 'users' sub directory instead of the 'users' root directory? I know from your code snippet that I am following the same tutorial and I was getting the same error because I hadn't created the 'signals.py' file in the 'users' app directory, but rather in the 'users' sub directory. If your 'signals.py' file is in the 'users' folder containing only 4 HTML files (login, logout, profile, register) then it is in the wrong location. Move it to the 'users' app directory and problem solved.</p>

Title: "ModuleNotFoundError", How to fix it?

Body:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender=User)
def create_profile(receiver, instance, created, **kwargs):
    if created:
        Profile.objects.create(User=instance)

@receiver(post_save, sender=User)
def save_profile(receiver, instance, **kwargs):
    instance.Profile.save()

apps.py

from django.apps import AppConfig

class UsersConfig(AppConfig):
    name = 'users'
    def ready(self):
        import users.signals

Error in server

File "C:\Users\Mian.G\Desktop\django_admin\users\apps.py", line 7, in
  ready
      import users.signals ModuleNotFoundError: No module named 'users.signals'


问:
How can I change the color of a textbox based on the cell value in a loop?
On my userform, I have a "next" button which loops through a worksheet.  If cell in column CL = "yes", then change color of textbox10 to Yellow, otherwise leave it white.  Problem is, it will only change to yellow if I don't have an "Else" statement, and  then it won't turn back to white.

I've tried changing Private Sub TextBox10_Change() to Private Sub TextBox10_Enter() and then also added a ...Textbox10_Exit() but still the same results.

```<code>Private Sub TextBox10_change()

Dim i As Integer

Dim Lastrow As Integer

Lastrow = Cells(rows.Count, 1).End(xlUp).Row

For i = 2 To Lastrow

If ActiveSheet.Range("CL" & i) = "yes" Then
    Me.TextBox10.BackColor = vbYellow
Else
    Me.TextBox10.BackColor = vbWhite
End If

Next i

End Sub
</code>```

Basically, nothing happens unless I remove:

```<code>Else

  Me.Textbox10.BackColor = vbWhite
</code>```

and even then it turns yellow but never turns back to white.

答:
Your code will work, but it will be matched to whatever is in the last row (ie yellow if the last row is "yes").

If you want it to be yellow if any of the values are "yes" and white if none are "yes" then

```<code>Me.TextBox10.BackColor = vbWhite
For i = 2 To Lastrow
    If ActiveSheet.Range("CL" & i) = "yes" Then
        Me.TextBox10.BackColor = vbYellow
    End If
Next i
</code>```

Body:
On my userform, I have a "next" button which loops through a worksheet.  If cell in column CL = "yes", then change color of textbox10 to Yellow, otherwise leave it white.  Problem is, it will only change to yellow if I don't have an "Else" statement, and  then it won't turn back to white.

I've tried changing Private Sub TextBox10_Change() to Private Sub TextBox10_Enter() and then also added a ...Textbox10_Exit() but still the same results.

Private Sub TextBox10_change()

Dim i As Integer

Dim Lastrow As Integer

Lastrow = Cells(rows.Count, 1).End(xlUp).Row

For i = 2 To Lastrow

If ActiveSheet.Range("CL" & i) = "yes" Then
    Me.TextBox10.BackColor = vbYellow
Else
    Me.TextBox10.BackColor = vbWhite
End If

Next i

End Sub

Basically, nothing happens unless I remove:

Else

  Me.Textbox10.BackColor = vbWhite

and even then it turns yellow but never turns back to white.

Body:
Your code will work, but it will be matched to whatever is in the last row (ie yellow if the last row is "yes").

If you want it to be yellow if any of the values are "yes" and white if none are "yes" then

Me.TextBox10.BackColor = vbWhite
For i = 2 To Lastrow
    If ActiveSheet.Range("CL" & i) = "yes" Then
        Me.TextBox10.BackColor = vbYellow
    End If
Next i


问:
Creating one hot vector from indices given as a tensor
I have a tensor of size 4 x 6 where 4 is batch size and 6 is sequence length. Every element of the sequence vectors are some index (0 to n). I want to create a 4 x 6 x n tensor where the vectors in 3rd dimension will be one hot encoding of the index which means I want to put 1 in the specified index and rest of the values will be zero.

For example, I have the following tensor:

```<code>[[5, 3, 2, 11, 15, 15],
[1, 4, 6, 7, 3, 3],
[2, 4, 7, 8, 9, 10],
[11, 12, 15, 2, 5, 7]]
</code>```

Here, all the values are in between (0 to n) where n = 15. So, I want to convert the tensor to a 4 X 6 X 16 tensor where the third dimension will represent one hot encoding vector.

How can I do that using PyTorch functionalities? Right now, I am doing this with loop but I want to avoid looping!

答:
The easiest way I found. Where x is a list of numbers and class_count is the amount of classes you have.

```<code>def one_hot(x, class_count):
    return torch.eye(class_count)[x,:]
</code>```

Use it like this:

```<code>x = [0,2,5,4]
class_count = 8
one_hot(x,class_count)
tensor([[1., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 1., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0.],
        [0., 0., 0., 0., 1., 0., 0., 0.]])

</code>```

Body:
I have a tensor of size 4 x 6 where 4 is batch size and 6 is sequence length. Every element of the sequence vectors are some index (0 to n). I want to create a 4 x 6 x n tensor where the vectors in 3rd dimension will be one hot encoding of the index which means I want to put 1 in the specified index and rest of the values will be zero.

For example, I have the following tensor:

[[5, 3, 2, 11, 15, 15],
[1, 4, 6, 7, 3, 3],
[2, 4, 7, 8, 9, 10],
[11, 12, 15, 2, 5, 7]]

Here, all the values are in between (0 to n) where n = 15. So, I want to convert the tensor to a 4 X 6 X 16 tensor where the third dimension will represent one hot encoding vector.

How can I do that using PyTorch functionalities? Right now, I am doing this with loop but I want to avoid looping!

Body:
The easiest way I found. Where x is a list of numbers and class_count is the amount of classes you have.

def one_hot(x, class_count):
    return torch.eye(class_count)[x,:]

Use it like this:

x = [0,2,5,4]
class_count = 8
one_hot(x,class_count)
tensor([[1., 0., 0., 0., 0., 0., 0., 0.],
        [0., 0., 1., 0., 0., 0., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0.],
        [0., 0., 0., 0., 1., 0., 0., 0.]])


问:
How can I redirect after POST in Pyramid?
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.

For example:

User loads the page website.com/post

Form POSTs the data to website.com/post-save

User gets redirected back to website.com/post

Pyramid is giving me some troubles doing this.

Here's my slimmed down views.py

```<code>def _get_link_form(post_data):
    """ Returns the initialised form object """

    return LinkForm(post_data)

def home_page(request):

    form = _get_link_form(request.POST)
    return {'form' : form}

def save_post(request):
    """ form data is submitted here """"

    form = _get_link_form(request.POST)

    if not form.validate():
        return home_page(request, form)
</code>```

This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?

答:
Assuming your homepage is the default view of your pyramid web app, you can do:

```<code>def _get_link_form(post_data):
    """ Returns the initialised form object """

    return LinkForm(post_data)

def home_page(request):

    form = _get_link_form(request.POST)
    return {'form' : form}

def save_post(request):
    form = _get_link_form(request.POST)

    if not form.validate():
        from pyramid.httpexceptions import HTTPFound
        return HTTPFound(location=request.application_url)
</code>```

Basically you need to know how the home_page view was "added" to your Configurator.  If your homepage actually lives at /few/levels/deep/homepage then a redirect might look like this:

```<code>        return HTTPFound(location=request.application_url + '/few/levels/deep/homepage')
</code>```

Body:
I'm trying to have my form submit to a route which will validate the data then redirect back to the original route.

For example:

User loads the page website.com/post

Form POSTs the data to website.com/post-save

User gets redirected back to website.com/post

Pyramid is giving me some troubles doing this.

Here's my slimmed down views.py

def _get_link_form(post_data):
    """ Returns the initialised form object """

    return LinkForm(post_data)

def home_page(request):

    form = _get_link_form(request.POST)
    return {'form' : form}

def save_post(request):
    """ form data is submitted here """"

    form = _get_link_form(request.POST)

    if not form.validate():
        return home_page(request, form)

This is the code I've been playing around with. Not only does it not work, it also feels messy and hacked up. Surely there's a simpler way to 'redirect after-POST' in Pyramid?

Body:
Assuming your homepage is the default view of your pyramid web app, you can do:

def _get_link_form(post_data):
    """ Returns the initialised form object """

    return LinkForm(post_data)

def home_page(request):

    form = _get_link_form(request.POST)
    return {'form' : form}

def save_post(request):
    form = _get_link_form(request.POST)

    if not form.validate():
        from pyramid.httpexceptions import HTTPFound
        return HTTPFound(location=request.application_url)

Basically you need to know how the home_page view was "added" to your Configurator.  If your homepage actually lives at /few/levels/deep/homepage then a redirect might look like this:

        return HTTPFound(location=request.application_url + '/few/levels/deep/homepage')


问:
Docker Network Nginx Resolver
I am trying to get rid of deprecated Docker links in my configuration. What's left is getting rid of those Bad Gateway nginx reverse proxy errors when I recreated a container.

Note: I am using Docker networks in bridge mode. (docker network create nettest)

I am using the following configuration snippet inside nginx:

```<code>location / {
      resolver 127.0.0.1 valid=30s;
      set $backend "http://confluence:8090";
      proxy_pass $backend;
</code>```

I started a container with hostname confluence on my Docker network with name nettest.

Then I started the nginx container on network nettest.

I can ping confluence from inside the nginx container

confluence is listed inside the nginx container's /etc/hosts file

nginx log says send() failed (111: Connection refused) while resolving, resolver: 127.0.0.1:53

I tried the docker network default dns resolver 127.0.0.11 from /etc/resol.conf

nginx log says confluence could not be resolved (3: Host not found)

Anybody knows how to configure nginx resolver with Docker Networks or an alternative on how to force Nginx to correctly resolve the Docker network hostname?

答: We hit this with docker containers on windows trying to lookup host.docker.internal using the docker internal resolver at 127.0.0.11. All queries would resolve correctly except host.docker.internal. Fix was to add the ipv6=off flag to the resolver line in nginx.conf.

Title: Docker Network Nginx Resolver

Body:
I am trying to get rid of deprecated Docker links in my configuration. What's left is getting rid of those Bad Gateway nginx reverse proxy errors when I recreated a container.

Note: I am using Docker networks in bridge mode. (docker network create nettest)

I am using the following configuration snippet inside nginx:

location / {
      resolver 127.0.0.1 valid=30s;
      set $backend "http://confluence:8090";
      proxy_pass $backend;

I started a container with hostname confluence on my Docker network with name nettest.

Then I started the nginx container on network nettest.

I can ping confluence from inside the nginx container

confluence is listed inside the nginx container's /etc/hosts file

nginx log says send() failed (111: Connection refused) while resolving, resolver: 127.0.0.1:53

I tried the docker network default dns resolver 127.0.0.11 from /etc/resol.conf

nginx log says confluence could not be resolved (3: Host not found)

Anybody knows how to configure nginx resolver with Docker Networks or an alternative on how to force Nginx to correctly resolve the Docker network hostname?