问:
how to use tsfresh python package to extract features from time series data?
I have a list of lists where each list represents a time series :

```<code>tsli=[[43,65,23,765,233,455,7,32,57,78,4,32],[34,32,565,87,23,86,32,56,32,57,78,32],[87,43,12,46,32,46,13,23,6,90,67,8],[1,2,3,3,4,5,6,7,8,9,0,9],[12,34,56,76,34,12,45,67,34,21,12,22]]
</code>```

i want to extract feature from this dataset with tsfresh package using code:

```<code>import tsfresh
tf=tsfresh.extract_features(tsli)
</code>```

When i'm running it i'm getting Value error which is:

```<code>> ValueError: You have to set the column_id which contains the ids of the different time series
But i don't know how to deal with this and how to define column id for this problem.
</code>```

EDIT 1:
As suggested i had tried by converting the dataset into data and then tried :

```<code>import tsfresh
df=pd.DataFrame(tsli)
tf=tsfresh.extract_features(df)
</code>```

but the Value error is same

```<code>> ValueError: You have to set the column_id which contains the ids of the different time series
</code>```

Any resource or reference will be helpful.

Thanks

答:
First you have to convert your list to a dataframe, where every time-series has an unique id, e.g.

```<code>df = pd.DataFrame()
for i, ts in enumerate(tsli):
    data = [[x, i] for x in ts]
    df = df.append(data, ignore_index=True)
df.columns = ['value', 'id']
</code>```

 ...

Now you can use tsfresh with column_id argument on the created column:

```<code>tf=tsfresh.extract_features(df, column_id='id')

>> Feature Extraction: 100%|██████████| 5/5 [00:00<00:00, 36.83it/s]
</code>```

Another example: tsfresh Quick Start

Body:
I have a list of lists where each list represents a time series :

tsli=[[43,65,23,765,233,455,7,32,57,78,4,32],[34,32,565,87,23,86,32,56,32,57,78,32],[87,43,12,46,32,46,13,23,6,90,67,8],[1,2,3,3,4,5,6,7,8,9,0,9],[12,34,56,76,34,12,45,67,34,21,12,22]]

i want to extract feature from this dataset with tsfresh package using code:

import tsfresh
tf=tsfresh.extract_features(tsli)

When i'm running it i'm getting Value error which is:

> ValueError: You have to set the column_id which contains the ids of the different time series
But i don't know how to deal with this and how to define column id for this problem.

EDIT 1:
As suggested i had tried by converting the dataset into data and then tried :

import tsfresh
df=pd.DataFrame(tsli)
tf=tsfresh.extract_features(df)

but the Value error is same

> ValueError: You have to set the column_id which contains the ids of the different time series

Any resource or reference will be helpful.

Thanks

Body:
First you have to convert your list to a dataframe, where every time-series has an unique id, e.g.

df = pd.DataFrame()
for i, ts in enumerate(tsli):
    data = [[x, i] for x in ts]
    df = df.append(data, ignore_index=True)
df.columns = ['value', 'id']

 ...

Now you can use tsfresh with column_id argument on the created column:

tf=tsfresh.extract_features(df, column_id='id')

>> Feature Extraction: 100%|██████████| 5/5 [00:00<00:00, 36.83it/s]

Another example: tsfresh Quick Start


来源: stackexchange

问:
Why Am I getting extra messages when sending keystroke to an application?
I am sending CTRL+A and CTRL+C to an application ( in order to copy the content obviously ).
For this I wrote some C++ code which seems to be ok.

Indeed I see on spy++ that the messages produced and sent to the application by my code are exactly the same ( expect frepeat value ) than the messages received by the application when CTRL+A and CTRL+C are inputed ,manually on the keyboard... except that with my code, the application receive at the end two extra WM_CHAR messages for 'A' and 'B'.

since I do not send these WM_CHAR messages but only WM_KEYDOWN and WM_KEYUP I am slightly puzzled. Incidentally nothing is selected and nothing is copied ( even if selected before )

here is my C++ code:

```<code>HWND hTargetWindow=(HWND) 0x280908;

LPARAM lparam1 = 0x00000001 | (LPARAM)(0x1D << 16);
LPARAM lparam2 = 0x00000001 | (LPARAM)(0x1E << 16);
LPARAM lparam3 = 0x00000001 | (LPARAM)(0x2E << 16);

LPARAM lparam1_ = lparam1 | (LPARAM)(0x1 << 31);
LPARAM lparam2_ = lparam2 | (LPARAM)(0x1 << 31);
LPARAM lparam3_ = lparam3 | (LPARAM)(0x1 << 31);

PostMessage(hTargetWindow, WM_KEYDOWN, VK_CONTROL, lparam1);
PostMessage(hTargetWindow, WM_KEYDOWN, VK_A, lparam2);

PostMessage(hTargetWindow, WM_KEYUP, VK_CONTROL, lparam1_);
PostMessage(hTargetWindow, WM_KEYUP, VK_A, lparam2_);

PostMessage(hTargetWindow, WM_KEYDOWN, VK_CONTROL, lparam1);
PostMessage(hTargetWindow, WM_KEYDOWN, VK_C, lparam3);

PostMessage(hTargetWindow, WM_KEYUP, VK_C, lparam3_);
PostMessage(hTargetWindow, WM_KEYUP, VK_CONTROL, lparam1_);
</code>```

and here respectively

a) the messages received when CTRL+A CTRL+C are inputed manually

b) here the messages received when when CTRL+A CTRL+C are sent by my C+ code

I will put frepeat to 1 for KEYUP events  but I doubt this will change anything so I post the question anyway.

so why are these two extra messages sent by my code ?

thanks in advance for any hint.

added 7:09:05 p.m.(GMT + 2:00):

the KEYUP and KEYDOWN for CTRL+A are reversed ( CTRL+C sequence is the same )  but this is because I have also tried this to solve the problem.  I have also tried many times the right combination.

this is spy++ when the keydown and keyup dequence is exactly the same , that does not change anything:

答:
```<code>// Send [CTRL-A] to select the entire text in a Notepad window, even if Notepad is out of focus,
// without bringing the Notepad window into focus.
// Works with Notepad, but not with Command Prompt window.
BYTE gucKeybStateCur [256] = {'\0'};
// hwN = Find Notepad HWND
AttachThreadInput (GetWindowThreadProcessId (hwN, NULL), GetCurrentThreadId (), TRUE);
GetKeyboardState ((PBYTE) &gucKeybStateCur);
gucKeybStateCur [VK_CONTROL] |= 0x80;
SetKeyboardState ((LPBYTE) &gucKeybStateCur);
PostMessage (hwN, WM_KEYDOWN, (WPARAM) 0x00000041, (LPARAM) 0x001E0001);
PostMessage (hwN, WM_KEYUP, (WPARAM) 0x00000041, (LPARAM) 0xC01E0001);
GetKeyboardState ((PBYTE) &gucKeybStateCur);
gucKeybStateCur [VK_CONTROL] &= 0x0F;
SetKeyboardState ((LPBYTE) &gucKeybStateCur);
AttachThreadInput (GetWindowThreadProcessId (hwN, NULL), GetCurrentThreadId (), FALSE);

// Send [CTRL-C] to interrupt a batch file running in a Command Prompt window, even if the Command Prompt window is not visible,
// without bringing the Command Prompt window into focus.
// [CTRL-C] will have an effect on the batch file, but not on the Command Prompt  window itself -- in other words,
// [CTRL-C] will not have the same visible effect on a Command Prompt window that isn't running a batch file at the moment
// as bringing a Command Prompt window that isn't running a batch file into focus and pressing [CTRL-C] on the keyboard.
ulong ulProcessId = 0UL;
// hwC = Find Command Prompt window HWND
GetWindowThreadProcessId (hwC, (LPDWORD) &ulProcessId);
AttachConsole ((DWORD) ulProcessId);
SetConsoleCtrlHandler (NULL, TRUE);
GenerateConsoleCtrlEvent (CTRL_C_EVENT, 0UL);
SetConsoleCtrlHandler (NULL, FALSE);
FreeConsole ();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am sending CTRL+A and CTRL+C to an application ( in order to copy the content obviously ).
For this I wrote some C++ code which seems to be ok.

Indeed I see on spy++ that the messages produced and sent to the application by my code are exactly the same ( expect frepeat value ) than the messages received by the application when CTRL+A and CTRL+C are inputed ,manually on the keyboard... except that with my code, the application receive at the end two extra WM_CHAR messages for 'A' and 'B'.

since I do not send these WM_CHAR messages but only WM_KEYDOWN and WM_KEYUP I am slightly puzzled. Incidentally nothing is selected and nothing is copied ( even if selected before )

here is my C++ code:

HWND hTargetWindow=(HWND) 0x280908;

LPARAM lparam1 = 0x00000001 | (LPARAM)(0x1D << 16);
LPARAM lparam2 = 0x00000001 | (LPARAM)(0x1E << 16);
LPARAM lparam3 = 0x00000001 | (LPARAM)(0x2E << 16);

LPARAM lparam1_ = lparam1 | (LPARAM)(0x1 << 31);
LPARAM lparam2_ = lparam2 | (LPARAM)(0x1 << 31);
LPARAM lparam3_ = lparam3 | (LPARAM)(0x1 << 31);

PostMessage(hTargetWindow, WM_KEYDOWN, VK_CONTROL, lparam1);
PostMessage(hTargetWindow, WM_KEYDOWN, VK_A, lparam2);

PostMessage(hTargetWindow, WM_KEYUP, VK_CONTROL, lparam1_);
PostMessage(hTargetWindow, WM_KEYUP, VK_A, lparam2_);

PostMessage(hTargetWindow, WM_KEYDOWN, VK_CONTROL, lparam1);
PostMessage(hTargetWindow, WM_KEYDOWN, VK_C, lparam3);

PostMessage(hTargetWindow, WM_KEYUP, VK_C, lparam3_);
PostMessage(hTargetWindow, WM_KEYUP, VK_CONTROL, lparam1_);

and here respectively

a) the messages received when CTRL+A CTRL+C are inputed manually

b) here the messages received when when CTRL+A CTRL+C are sent by my C+ code

I will put frepeat to 1 for KEYUP events  but I doubt this will change anything so I post the question anyway.

so why are these two extra messages sent by my code ?

thanks in advance for any hint.

added 7:09:05 p.m.(GMT + 2:00):

the KEYUP and KEYDOWN for CTRL+A are reversed ( CTRL+C sequence is the same )  but this is because I have also tried this to solve the problem.  I have also tried many times the right combination.

this is spy++ when the keydown and keyup dequence is exactly the same , that does not change anything:

ContentLicense: CC BY-SA 4.0


问:
Is it possible to declare and run a lambda function in an expression?
Given a very simple expression like:

```<code>var x = new Thing();
</code>```

I was thinking, can you encapsulate new Thing as a lambda like () => new Thing() inline, along the lines of:

```<code>var x = () => new Thing();
</code>```

This doesn't compile because I'm trying to assign a delegate to x, not the result of calling it.

But when I try:

```<code>var x = (() => new Thing())(); //call my lambda in-line
</code>```

This also doesn't compile with eror "Method name expected".

So does this imply I cannot declare and use a lambda inline, or just that I don't understand the syntax?

(Note: this is a question about understanding the language, I'm not asking if it's a good idea to do it, only if I can. My example is clearly over-simplified from any real-world use!)

答:
using gives you a boundary around IDisposable objects. Once you leave that boundary, the object is destroyed.

For example, take this line

```<code>using (var connection = new SqlConnection(connectionString))
</code>```

SqlConnection implements IDisposable, so once the end of the using block is reached, the disposal method is called.

Now let's look at your example with the lambda -

```<code>using (var conn = (() => new SqlConnection(ConnectionString)))
</code>```

In this case, your variable conn is not a connection, instead it is an anonymous method, which of course does not implement IDisposable. The type of the anonymous method is dependent on the initializer expression, and you don't have one of those. More on that in a moment.

For your second example,

```<code>using (var conn = (() => new SqlConnection(ConnectionString))())
</code>```

This is where I start to get confused about what you are trying to accomplish. I can't tell how you intend this to be different than

```<code>using (var conn = new SqlConnection(ConnectionString))
</code>```

If you absolutely must do that, you would probably need to wrap it in a Func

```<code>using (var conn = new Func<SqlConnection>(() => new SqlConnection(ConnectionString)).Invoke())
</code>```

But, again, I'm not sure why you would want to do this.

Body:
Given a very simple expression like:

var x = new Thing();

I was thinking, can you encapsulate new Thing as a lambda like () => new Thing() inline, along the lines of:

var x = () => new Thing();

This doesn't compile because I'm trying to assign a delegate to x, not the result of calling it.

But when I try:

var x = (() => new Thing())(); //call my lambda in-line

This also doesn't compile with eror "Method name expected".

So does this imply I cannot declare and use a lambda inline, or just that I don't understand the syntax?

(Note: this is a question about understanding the language, I'm not asking if it's a good idea to do it, only if I can. My example is clearly over-simplified from any real-world use!)

Body:
using gives you a boundary around IDisposable objects. Once you leave that boundary, the object is destroyed.

For example, take this line

using (var connection = new SqlConnection(connectionString))

SqlConnection implements IDisposable, so once the end of the using block is reached, the disposal method is called.

Now let's look at your example with the lambda -

using (var conn = (() => new SqlConnection(ConnectionString)))

In this case, your variable conn is not a connection, instead it is an anonymous method, which of course does not implement IDisposable. The type of the anonymous method is dependent on the initializer expression, and you don't have one of those. More on that in a moment.

For your second example,

using (var conn = (() => new SqlConnection(ConnectionString))())

This is where I start to get confused about what you are trying to accomplish. I can't tell how you intend this to be different than

using (var conn = new SqlConnection(ConnectionString))

If you absolutely must do that, you would probably need to wrap it in a Func

using (var conn = new Func<SqlConnection>(() => new SqlConnection(ConnectionString)).Invoke())

But, again, I'm not sure why you would want to do this.


问:
Simple addClass on mouseover problem
I'm trying to set a class for a li item, with no luck. I have tried many things (to much to post) but I can't figure it out:

```<code>$("li").live("mouseover",function(){
    $(this).addClass('current');
});
</code>```

The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.

Hope it makes some sense..This is the fiddle jsfiddle

答:
Just remove the class from its siblings:</p>

```<code>$("li").live("mouseover",function(){
    $(this).addClass('current');
    $(this).siblings().removeClass("current");
  });
</code>```

Title: Simple addClass on mouseover problem

Body:
I'm trying to set a class for a li item, with no luck. I have tried many things (to much to post) but I can't figure it out:

$("li").live("mouseover",function(){
    $(this).addClass('current');
});

The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.

Hope it makes some sense..This is the fiddle jsfiddle

Body:
Just remove the class from its siblings:

$("li").live("mouseover",function(){
    $(this).addClass('current');
    $(this).siblings().removeClass("current");
  });


问:
How to compare elements in a list without for loop?
I have a list: R = ['123', '1854', '000'] and I want to make sure that all the elements on it have the same length, but I don't want to use a for loop.

I tried this:

```<code>if R[::] !== R[::]:
   print('false')
</code>```

Obviously it does not work.

It's possible to do it without a for loop?

And How to put it as an AssertError like: assert ..., 'False'? if the list elements are length different then raise an AssertError.

答:
```<code>result = any(map(lambda x: len(x) != len(R[0]), R))
</code>```

Body:
I have a list: R = ['123', '1854', '000'] and I want to make sure that all the elements on it have the same length, but I don't want to use a for loop.

I tried this:

if R[::] !== R[::]:
   print('false')

Obviously it does not work.

It's possible to do it without a for loop?

And How to put it as an AssertError like: assert ..., 'False'? if the list elements are length different then raise an AssertError.


问:
Xcode indexing takes ages and uses gigabytes of memory
I have a small project that takes ages to get indexed and uses ridiculous amounts of memory while indexing. In the screenshot you can see two Swift processes using 160+ GB of memory. I have this problem only in one project. btw the project uses CocoaPods.

Now if I keep an eye on the Activity monitor and keep kill the processes in time (before they take up too much memory to freeze the Mac), eventually the project is indexed and I can work on it.

What could be the cause of this memory behavior and how can I prevent it?

[Xcode Version 11.2.1 (11B500) on Catalina 10.15.1 (19B88), CocoaPods 1.8.4]

P.S. Doing the usual clean and delete derived data doesn't help at all.

答:
Xcode 11.5 and building project in SwiftUI

Seems like it could be an Xcode bug, basically building/ indexing gets stuck on a particular file and memory gets eaten up.

Option 1

If you are in the project and it gets stuck building go to the Report Navigator select the build that is currently running and you can see which file Xcode is currently building. Stop the build and check code in that file, if you spot the error and fix it your build will proceed.

Option 2

If Xcode gets stuck on launch so it starts indexing the moment you open the project:
Open up Activity Monitor and Force quit the swift process as it builds up. You need to keep quitting the process until indexing perceives itself to be complete. You'll know when Xcode has stopped indexing when the indexing label in Xcode disappears. Once you are in your project and memory is not being eaten up, refer to Option 1 above to fix the issue.


答: I've fixed it for you in the fiddle fiddle if you remove the current class from all the li elements and then apply it, you'll have better luck.</p>

Title: Simple addClass on mouseover problem


问:
Updating a single ObservableCollection but show in 2 different ListViews
Suppose I have one ObservableCollection that I insert, update and delete from.

```<code>public ObservableCollection<Item> AllItems {get;set;}
</code>```

The Item class (which implements INotifyPropertyChanged) looks like this:

```<code>public class Item
{
  public int Id {get;set;}
  public int Kind {get;set;}
  public string Text {get;set;}
}
</code>```

I have this bound in my View in one ListView. Everything works, meaning if I delete or add or updates Items in the ObservableCollection from my ViewModel, they are updating in my ListView as expected.

But now I need to split the ListView in 2 ListViews in my View. The first ListView must display all items where Item.Kind=1. And the other ListView must have all items where Item.Kind=2.

I don't mind binding to two different ObservableCollections from my ViewModel, but I would really like a solution where I can just do:

```<code>var item = new Item { Id=22, Kind=1, Text="SomeText" };
AllItems.Add(item);
AllItems.First(x => x.Id==22).Text = "SomeOtherText";
AllItems.Remove(item);
</code>```

And then these operations are automatically reflected in the 2 ListViews. So in the above example, the new Item is only viewed, updated and removed from the first ListView (where Item.Kind=1).

Is that possible?

EDIT: I should say that I have tried to use two CollectionViewSources with the same ObservableCollection as source. But that fails and does not seem to be the correct solution.

答:
create two ListCollectionViews with different filters - one for each ListView

```<code>public ICollectionView Items_1 { get; private set; }
public ICollectionView Items_2 { get; private set; }

public ViewModel
{
    Items_1 = new ListCollectionView(AllItems);
    Items_1.Filter = o => (o as Item).Kind == 1;

    Items_2 = new ListCollectionView(AllItems);
    Items_2.Filter = o => (o as Item).Kind == 2;
}
</code>```

Body:
Suppose I have one ObservableCollection that I insert, update and delete from.

public ObservableCollection<Item> AllItems {get;set;}

The Item class (which implements INotifyPropertyChanged) looks like this:

public class Item
{
  public int Id {get;set;}
  public int Kind {get;set;}
  public string Text {get;set;}
}

I have this bound in my View in one ListView. Everything works, meaning if I delete or add or updates Items in the ObservableCollection from my ViewModel, they are updating in my ListView as expected.

But now I need to split the ListView in 2 ListViews in my View. The first ListView must display all items where Item.Kind=1. And the other ListView must have all items where Item.Kind=2.

I don't mind binding to two different ObservableCollections from my ViewModel, but I would really like a solution where I can just do:

var item = new Item { Id=22, Kind=1, Text="SomeText" };
AllItems.Add(item);
AllItems.First(x => x.Id==22).Text = "SomeOtherText";
AllItems.Remove(item);

And then these operations are automatically reflected in the 2 ListViews. So in the above example, the new Item is only viewed, updated and removed from the first ListView (where Item.Kind=1).

Is that possible?

EDIT: I should say that I have tried to use two CollectionViewSources with the same ObservableCollection as source. But that fails and does not seem to be the correct solution.

Body:
create two ListCollectionViews with different filters - one for each ListView

public ICollectionView Items_1 { get; private set; }
public ICollectionView Items_2 { get; private set; }

public ViewModel
{
    Items_1 = new ListCollectionView(AllItems);
    Items_1.Filter = o => (o as Item).Kind == 1;

    Items_2 = new ListCollectionView(AllItems);
    Items_2.Filter = o => (o as Item).Kind == 2;
}


问:
MongoDB aggregation lookup additional field from localField to result
I have the following collections in MongoDB (mongoplayground) [characters,guilds]

I want to make a $lookup, that will add rank field to the resulting document, like that:

```<code>    "members_t": [
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "level": 20,
        "name": "test1",
        "rank": 1
      },
      {
        "_id": ObjectId("5a934e000102030405000001"),
        "level": 40,
        "name": "test2",
        "rank": 2
      }
    ]

</code>```

old $lookup syntax can't help me with that, but the following query with the new syntax returns me an empty array in tested field (even without $addFields stage):

```<code>  {
    $lookup: {
      from: "characters",
      let: {
        members_name: "$members.name",
        rank: "$members.rank"
      },
      pipeline: [
        {
          $match: {
            name: "$$members_name"
          }
        }
      ],
      as: "tested"
    }
  }
</code>```

So, is there any option to add an additional field after $lookup stage or not?

(Mongo -v 4.2.3, so the problem is not related with new syntax support)

答:
You were almost close to solving it. Since the members are an array, you need to pass it through $lookup and then conditionally join it per each character with $reduce (You can do this with $filter as well, but then we need aditional stages).

Note: Explanation why we need to use $expr inside $lookup pipeline.

Try this one:

```<code>db.guilds.aggregate([
  {
    $lookup: {
      from: "characters",
      let: {
        members: "$members"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$name",
                "$$members.name"
              ]
            }
          }
        },
        {
          $addFields: {
            rank: {
              $reduce: {
                input: "$$members",
                initialValue: null,
                in: {
                  $cond: [
                    {
                      $eq: [
                        "$$this.name",
                        "$name"
                      ]
                    },
                    "$$this.rank",
                    "$$value"
                  ]
                }
              }
            }
          }
        }
      ],
      as: "members_t"
    }
  }
])
</code>```

MongoPlayground

Body:
I have the following collections in MongoDB (mongoplayground) [characters,guilds]

I want to make a $lookup, that will add rank field to the resulting document, like that:

    "members_t": [
      {
        "_id": ObjectId("5a934e000102030405000000"),
        "level": 20,
        "name": "test1",
        "rank": 1
      },
      {
        "_id": ObjectId("5a934e000102030405000001"),
        "level": 40,
        "name": "test2",
        "rank": 2
      }
    ]

old $lookup syntax can't help me with that, but the following query with the new syntax returns me an empty array in tested field (even without $addFields stage):

  {
    $lookup: {
      from: "characters",
      let: {
        members_name: "$members.name",
        rank: "$members.rank"
      },
      pipeline: [
        {
          $match: {
            name: "$$members_name"
          }
        }
      ],
      as: "tested"
    }
  }

So, is there any option to add an additional field after $lookup stage or not?

(Mongo -v 4.2.3, so the problem is not related with new syntax support)

Body:
You were almost close to solving it. Since the members are an array, you need to pass it through $lookup and then conditionally join it per each character with $reduce (You can do this with $filter as well, but then we need aditional stages).

Note: Explanation why we need to use $expr inside $lookup pipeline.

Try this one:

db.guilds.aggregate([
  {
    $lookup: {
      from: "characters",
      let: {
        members: "$members"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $in: [
                "$name",
                "$$members.name"
              ]
            }
          }
        },
        {
          $addFields: {
            rank: {
              $reduce: {
                input: "$$members",
                initialValue: null,
                in: {
                  $cond: [
                    {
                      $eq: [
                        "$$this.name",
                        "$name"
                      ]
                    },
                    "$$this.rank",
                    "$$value"
                  ]
                }
              }
            }
          }
        }
      ],
      as: "members_t"
    }
  }
])

MongoPlayground


问:
How could I turn this PineScript input into a usable function?
I have written an input variable to define what type of moving average I'd like to use in my strategy. I have a significant amount of other code in the script so I have tried to choose only what is relevant. The input variable:

```<code>MA1Type = input(title="MA1 Type", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA", "VWMA"])
</code>```

And the function that I'm trying to use the input for, is the "sma" function here:

```<code>MovAv1 = sma(close, MA1Period)
</code>```

This is my working MA function below

```<code>ma(MAType, MASource, MAPeriod) =>
if MAType == "SMA"
    sma(MASource, MAPeriod)
else
    if MAType == "EMA"
        ema(MASource, MAPeriod)
    else
        if MAType == "WMA"
            wma(MASource, MAPeriod)
        else
            if MAType == "RMA"
                rma(MASource, MAPeriod)
            else
                if MAType == "HMA"
                    wma(2*wma(MASource, MAPeriod/2)-wma(MASource, MAPeriod), round(sqrt(MAPeriod)))
                else
                    if MAType == "DEMA"
                        e = ema(MASource, MAPeriod)
                        2 * e - ema(e, MAPeriod)
                    else
                        if MAType == "TEMA"
                            e = ema(MASource, MAPeriod)
                            3 * (e - ema(e, MAPeriod)) + ema(ema(e, MAPeriod), MAPeriod)
                        else
                            if MAType == "VWMA"
                                vwma(MASource, MAPeriod)
</code>```

The error message I get, when I try to use my ma function instead of one of the built-in functions; is here:

cannot call 'anonym_function_0' with arguments (series[float], input integer);

答:
See the Moving Averages, input with options sample script.

It contains an example of what you're looking for.

Body:
I have written an input variable to define what type of moving average I'd like to use in my strategy. I have a significant amount of other code in the script so I have tried to choose only what is relevant. The input variable:

MA1Type = input(title="MA1 Type", defval="SMA", options=["RMA", "SMA", "EMA", "WMA", "HMA", "DEMA", "TEMA", "VWMA"])

And the function that I'm trying to use the input for, is the "sma" function here:

MovAv1 = sma(close, MA1Period)

This is my working MA function below

ma(MAType, MASource, MAPeriod) =>
if MAType == "SMA"
    sma(MASource, MAPeriod)
else
    if MAType == "EMA"
        ema(MASource, MAPeriod)
    else
        if MAType == "WMA"
            wma(MASource, MAPeriod)
        else
            if MAType == "RMA"
                rma(MASource, MAPeriod)
            else
                if MAType == "HMA"
                    wma(2*wma(MASource, MAPeriod/2)-wma(MASource, MAPeriod), round(sqrt(MAPeriod)))
                else
                    if MAType == "DEMA"
                        e = ema(MASource, MAPeriod)
                        2 * e - ema(e, MAPeriod)
                    else
                        if MAType == "TEMA"
                            e = ema(MASource, MAPeriod)
                            3 * (e - ema(e, MAPeriod)) + ema(ema(e, MAPeriod), MAPeriod)
                        else
                            if MAType == "VWMA"
                                vwma(MASource, MAPeriod)

The error message I get, when I try to use my ma function instead of one of the built-in functions; is here:

cannot call 'anonym_function_0' with arguments (series[float], input integer);


问:
Relying on the (copy) attribute to copy NSMutableDictionary causes crash
The following program relies on the copy

attribute to copy a NSMutableDictionary.

The copy is apparently ok, but, if I try

to add a new element to the copy, the program crashes.

Is it some kind of bug?

PS. If it matters it's NON ARC

```<code>#import <Foundation/Foundation.h>

@interface Dog: NSObject
@property (copy) NSMutableDictionary *dict;
@end

@implementation Dog
@synthesize dict;

- (id) init
{
    if ( (self = [super init]) ) {
    dict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) print {
    for (id key in dict) {
    printf("%s --> %s\n", [key UTF8String], [dict[key] UTF8String] );
    }
}

@end

//------------------------------------------------------

int main() {
    Dog *dog1 = [[Dog alloc] init];
    Dog *dog2 = [[Dog alloc] init];

    dog1.dict[@"color"] = @"black";
    dog2.dict = dog1.dict;
    [dog2 print];
    // the print shows that dog2.dict is indeed a copy of dog1.dict
    // lldb shows that it is a shallow copy, which I guess is ok
    // since values are immutable.
    // ... so far so good.
    dog1.dict[@"tail"] = @"long";   // This goes smoothly
    //
    // But...
    dog2.dict[@"tail"] = @"long";
    // here program crashes with the following message
    //
    // -[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0
    //*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0'
    return(0);
}
</code>```

EDIT:
If I replace the line

```<code>dog2.dict = dog1.dict;
</code>```

with

```<code>[dog2.dict addEntriesFromDictionary: dog1.dict];
</code>```

then it works. There is no crash.

So, OK, this is the correct way of doing it.

But my point is: don't I deserve at least a warning

from the compiler?

答:
You've broken some rules here, which is why it's going badly for you. As a rule, you should not return or accept NSMutableDictionary as a property. There are exceptions (and you have to code around that), but generally you should not. To code this correctly, you need to separate your interface from your implementation.

The correct interface is:

```<code>@interface Dog: NSObject
@property (copy) NSDictionary *dict;
@end
</code>```

This object promises to accept and return NSDictionary, and it promises that the accepted and returned NSDictionaries will be independent copies, so the caller doesn't need to worry about mutability issues. We then need to implement those promises:

```<code>@implementation Dog {
    NSMutableDictionary *mutableDict;
}

- (id) init
{
    if ( (self = [super init]) ) {
        mutableDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) print {
    for (id key in mutableDict) {
        printf("%s --> %s\n", [key UTF8String], [mutableDict[key] UTF8String] );
    }
}

- (NSDictionary *)dict {
    return [mutableDict copy]; // Add an -autorelease if this is MRC
}

- (void)setDict: (NSDictionary *)newValue {
    // I'm going to pretend this is ARC; for MRC, code this in your style.
    mutableDict = [newValue mutableCopy];
}

@end
</code>```

On the other hand, if you really do want to share state with an NSMutableDictionary, you should not copy it, you should retain it to make clear the semantics.

```<code>@interface Dog: NSObject
@property (retain) NSMutableDictionary *dict;
@end
</code>```

And this makes it (hopefully) clear to the caller that this is shared state and should be treated as such, and the caller should make copies if they so desire. But you generally should avoid this. And if you do go this way, I would call the property mutableDict or something like that to make it clear that this is unusual. For an example, see -[NSAttributedString mutableString].

There's not really a "mutable, but independent copy" semantic in ObjC property annotations, and I wouldn't create one unless you have a very strong need (generally performance related). I would generally just return an immutable copy and let the caller make their own mutable copy.

One more side note: Sometimes Cocoa implements "returns an immutable copy" as "just return the mutable one, cast to an immutable type." This improves performance by avoiding the copy, at the cost of sometimes the data changing behind your back. As an example, look at the docs for -[NSView subviews]. In my opinion you should avoid this pattern unless it is critical for performance (and even then, I'd make a special method like -subviewsBackingStore or something silly like that to make it clear "this is weird."

Body:
The following program relies on the copy

attribute to copy a NSMutableDictionary.

The copy is apparently ok, but, if I try

to add a new element to the copy, the program crashes.

Is it some kind of bug?

PS. If it matters it's NON ARC

#import <Foundation/Foundation.h>

@interface Dog: NSObject
@property (copy) NSMutableDictionary *dict;
@end

@implementation Dog
@synthesize dict;

- (id) init
{
    if ( (self = [super init]) ) {
    dict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) print {
    for (id key in dict) {
    printf("%s --> %s\n", [key UTF8String], [dict[key] UTF8String] );
    }
}

@end

//------------------------------------------------------

int main() {
    Dog *dog1 = [[Dog alloc] init];
    Dog *dog2 = [[Dog alloc] init];

    dog1.dict[@"color"] = @"black";
    dog2.dict = dog1.dict;
    [dog2 print];
    // the print shows that dog2.dict is indeed a copy of dog1.dict
    // lldb shows that it is a shallow copy, which I guess is ok
    // since values are immutable.
    // ... so far so good.
    dog1.dict[@"tail"] = @"long";   // This goes smoothly
    //
    // But...
    dog2.dict[@"tail"] = @"long";
    // here program crashes with the following message
    //
    // -[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0
    //*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI setObject:forKeyedSubscript:]: unrecognized selector sent to instance 0x100108ee0'
    return(0);
}

EDIT:
If I replace the line

dog2.dict = dog1.dict;

with

[dog2.dict addEntriesFromDictionary: dog1.dict];

then it works. There is no crash.

So, OK, this is the correct way of doing it.

But my point is: don't I deserve at least a warning

from the compiler?

Body:
You've broken some rules here, which is why it's going badly for you. As a rule, you should not return or accept NSMutableDictionary as a property. There are exceptions (and you have to code around that), but generally you should not. To code this correctly, you need to separate your interface from your implementation.

The correct interface is:

@interface Dog: NSObject
@property (copy) NSDictionary *dict;
@end

This object promises to accept and return NSDictionary, and it promises that the accepted and returned NSDictionaries will be independent copies, so the caller doesn't need to worry about mutability issues. We then need to implement those promises:

@implementation Dog {
    NSMutableDictionary *mutableDict;
}

- (id) init
{
    if ( (self = [super init]) ) {
        mutableDict = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) print {
    for (id key in mutableDict) {
        printf("%s --> %s\n", [key UTF8String], [mutableDict[key] UTF8String] );
    }
}

- (NSDictionary *)dict {
    return [mutableDict copy]; // Add an -autorelease if this is MRC
}

- (void)setDict: (NSDictionary *)newValue {
    // I'm going to pretend this is ARC; for MRC, code this in your style.
    mutableDict = [newValue mutableCopy];
}

@end

On the other hand, if you really do want to share state with an NSMutableDictionary, you should not copy it, you should retain it to make clear the semantics.

@interface Dog: NSObject
@property (retain) NSMutableDictionary *dict;
@end

And this makes it (hopefully) clear to the caller that this is shared state and should be treated as such, and the caller should make copies if they so desire. But you generally should avoid this. And if you do go this way, I would call the property mutableDict or something like that to make it clear that this is unusual. For an example, see -[NSAttributedString mutableString].

There's not really a "mutable, but independent copy" semantic in ObjC property annotations, and I wouldn't create one unless you have a very strong need (generally performance related). I would generally just return an immutable copy and let the caller make their own mutable copy.

One more side note: Sometimes Cocoa implements "returns an immutable copy" as "just return the mutable one, cast to an immutable type." This improves performance by avoiding the copy, at the cost of sometimes the data changing behind your back. As an example, look at the docs for -[NSView subviews]. In my opinion you should avoid this pattern unless it is critical for performance (and even then, I'd make a special method like -subviewsBackingStore or something silly like that to make it clear "this is weird."


问:
How to get the document total number of pages and current page numeric index in epubjs library?
I'm working on an app that is a book-reader and it is developed using epubjs-rn. I want to know how I Can get the book total number of pages and the numeric index of the current page. I will be grateful if somebody teach me this. </p>

答:
This is not super clear cut, the concept of "page numbers" in the tradition sense does not really work. But what we do have is the total number of locations.

For the prop onLocationsReady record the total number of locations.

onLocationsReady={(locations) => {
  this.setState({totalNumberOfLocations: locations.total});
})
```

<p>Then looking at the <code>onLocationChange</code> prop</p>

<pre class="lang-js prettyprint-override"><code>onLocationChange={(visibleLocation) => {
  this.setState({visibleLocation});
});
</code>```

Then what you can do is have all the necessary information to computes the rough "page" or location number and percentage:

  // give the current "page" or location
  _formatCurrentPosition(){
    return Math.floor(this.state.totalNumberOfLocations * (this.state.visibleLocation.start.percentage.toFixed(4)));
  }

  // formats the percentage since this can be very long
  _formatProgressPercentage(){
    return Math.floor(this.state.visibleLocation.start.percentage.toFixed(4) * 100);
  }
```

Note

On mount visibleLocation will be unknown so you will need to make sure the visible location and total number of locations is available prior to rendering

Body:
This is not super clear cut, the concept of "page numbers" in the tradition sense does not really work. But what we do have is the total number of locations.

For the prop onLocationsReady record the total number of locations.

onLocationsReady={(locations) => {
  this.setState({totalNumberOfLocations: locations.total});
})

Then looking at the onLocationChange prop

onLocationChange={(visibleLocation) => {
  this.setState({visibleLocation});
});

Then what you can do is have all the necessary information to computes the rough "page" or location number and percentage:

  // give the current "page" or location
  _formatCurrentPosition(){
    return Math.floor(this.state.totalNumberOfLocations * (this.state.visibleLocation.start.percentage.toFixed(4)));
  }

  // formats the percentage since this can be very long
  _formatProgressPercentage(){
    return Math.floor(this.state.visibleLocation.start.percentage.toFixed(4) * 100);
  }

Note

On mount visibleLocation will be unknown so you will need to make sure the visible location and total number of locations is available prior to rendering


问:
Efficient way to check if 2 columns of DataFrame are subsets of each other
I have 2 DataFrames which has a column whose value is of type set containing 8 digit integers.

df1 (contains around 200k rows)

```<code>    id  s1
0   0   {43649632, 95799329, 40649644, 23335890, 81779...
1   1   {69900026, 74441229}
2   2   {85195648, 55750338, 98936902, 82000264, 43544...
3   3   {21916700, 13627806}
4   4   {62929026, 38592365, 44179790, 38355127}
</code>```

df2 (contains around 900k rows)

```<code>    id  s1
0   0   {58209736, 25405713, 28691898, 94682562}
1   1   {81089732, 82343077}
2   2   {59692896, 33234306, 40445479, 18728345, 24464...
3   3   {71406042, 69900026, 74441229}
4   4   {62929026}
</code>```

I want to know the FASTEST way to find the pair of ids from df2 and df2 that match ONE OF THIS condition:

df1.s1 is a subset of d2.s1

OR

df2.s1 is a subset of d1.s1

For example,

id=1 of df1 is a subset of id=3 of df2, so (1, 3) is a valid pair

id=4 of df2 is a subset of id=4 of df1, so (1, 4) is a valid pair

I have tried this code below but it's going to take about 20 hours:

```<code>id_pairs = []

for i in tqdm(list(df2.itertuples(index=False))):
    for j in df1.itertuples(index=False):
        if i.s1.issubset(j.s1) or j.s1.issubset(i.s1):
            id_pairs.append((i.id, j.id))
</code>```

Is there a faster or more efficient way to do this?

答:
You could do a cartesian join and then apply the condition</p>

```<code>df1["key"] = 0
df2["key"] = 0

merged = df1.merge(df2, how="outer", on="key")

def subset(row):
    if (row.s1.issubset(row.s2)) or (row.s2.issubset(row.s1)):
        return (row.id1, row.id2)
    else:
        return None

merged.apply(lambda row: subset(row), axis=1).dropna()
</code>```

Body:
I have 2 DataFrames which has a column whose value is of type set containing 8 digit integers.

df1 (contains around 200k rows)

    id  s1
0   0   {43649632, 95799329, 40649644, 23335890, 81779...
1   1   {69900026, 74441229}
2   2   {85195648, 55750338, 98936902, 82000264, 43544...
3   3   {21916700, 13627806}
4   4   {62929026, 38592365, 44179790, 38355127}

df2 (contains around 900k rows)

    id  s1
0   0   {58209736, 25405713, 28691898, 94682562}
1   1   {81089732, 82343077}
2   2   {59692896, 33234306, 40445479, 18728345, 24464...
3   3   {71406042, 69900026, 74441229}
4   4   {62929026}

I want to know the FASTEST way to find the pair of ids from df2 and df2 that match ONE OF THIS condition:

df1.s1 is a subset of d2.s1

OR

df2.s1 is a subset of d1.s1

For example,

id=1 of df1 is a subset of id=3 of df2, so (1, 3) is a valid pair

id=4 of df2 is a subset of id=4 of df1, so (1, 4) is a valid pair

I have tried this code below but it's going to take about 20 hours:

id_pairs = []

for i in tqdm(list(df2.itertuples(index=False))):
    for j in df1.itertuples(index=False):
        if i.s1.issubset(j.s1) or j.s1.issubset(i.s1):
            id_pairs.append((i.id, j.id))

Is there a faster or more efficient way to do this?

Body:
You could do a cartesian join and then apply the condition

df1["key"] = 0
df2["key"] = 0

merged = df1.merge(df2, how="outer", on="key")

def subset(row):
    if (row.s1.issubset(row.s2)) or (row.s2.issubset(row.s1)):
        return (row.id1, row.id2)
    else:
        return None

merged.apply(lambda row: subset(row), axis=1).dropna()


问:
Input to reshape is a tensor with 128 values, but the requested shape has 32 [Op:Reshape]
This has stumped me a bit. I have tried several options but cannot get it to work right.
What I am doing is using TF2.0 triple loss function with my own data, but it is not working correctly.
I used the example from TF for an initial test and that works.

function link for reference: https://www.tensorflow.org/addons/tutorials/losses_triplet

With one small difference I am on windows so I cannot download and install tensorflow-addons so I grabbed what I needed to make the code work.
I am using the same model and compile it the same way, but still have issues.
Here is the code:

```<code>augment = True
if augment:
    train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0,
        rotation_range=20,
        zoom_range=0.15,
        width_shift_range=0.2,
        height_shift_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest',
        validation_split=0.20)  # set validation split
else:
    train_datagen = ImageDataGenerator(
        horizontal_flip=True,
        rescale=1. / 255,
        fill_mode='nearest',
        validation_split=0.20)  # set validation split

train_generator = train_datagen.flow_from_directory(
    DATA_PATH,
    target_size=(28,28),
    color_mode='grayscale',
    batch_size=BATCH_SIZE,
    class_mode='categorical',
    subset='training')  # set as training data

validation_generator = train_datagen.flow_from_directory(
    DATA_PATH,  # same directory as training data
    target_size=(28,28),
    color_mode='grayscale',
    batch_size=BATCH_SIZE,
    class_mode='categorical',
    subset='validation')  # set as validation data

# Build the network

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='valid', activation='relu', input_shape=(28,28, 1)))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='valid', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(256, activation=None))  # No activation on final dense layer
model.add(tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1)))  # L2 normalize embeddings

# Compile the model
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
          loss=triplet_semihard_loss)
</code>```

Its all the same just not the data. I even resize and grayscale the data so it is the same shape as the other input data.

Here is the whole error:

File "C:\Users\matthew.millar\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 128 values, but the requested shape has 32 [Op:Reshape]```
</div>
</div>
</p>

<p>EDIT</p>

```def triplet_semihard_loss(y_true, y_pred, margin=1.0):
    labels, embeddings = y_true, y_pred
    # Reshape label tensor to [batch_size, 1].
    lshape = tf.shape(labels)
    labels = tf.reshape(labels, [lshape[0], 1])

    # Build pairwise squared distance matrix.
    pdist_matrix = pairwise_distance(embeddings, squared=True)
    # Build pairwise binary adjacency matrix.
    adjacency = tf.math.equal(labels, tf.transpose(labels))
    # Invert so we can select negatives only.
    adjacency_not = tf.math.logical_not(adjacency)

    batch_size = tf.size(labels)

    # Compute the mask.
    pdist_matrix_tile = tf.tile(pdist_matrix, [batch_size, 1])
    mask = tf.math.logical_and(
        tf.tile(adjacency_not, [batch_size, 1]),
        tf.math.greater(pdist_matrix_tile,
                    tf.reshape(tf.transpose(pdist_matrix), [-1, 1])))
    mask_final = tf.reshape(
        tf.math.greater(
            tf.math.reduce_sum(
                tf.cast(mask, dtype=tf.dtypes.float32), 1, keepdims=True),
        0.0), [batch_size, batch_size])
    mask_final = tf.transpose(mask_final)

    adjacency_not = tf.cast(adjacency_not, dtype=tf.dtypes.float32)
    mask = tf.cast(mask, dtype=tf.dtypes.float32)

    # negatives_outside: smallest D_an where D_an > D_ap.
    negatives_outside = tf.reshape(
        _masked_minimum(pdist_matrix_tile, mask), [batch_size, batch_size])
    negatives_outside = tf.transpose(negatives_outside)

    # negatives_inside: largest D_an.
    negatives_inside = tf.tile(
        _masked_maximum(pdist_matrix, adjacency_not), [1, batch_size])
    semi_hard_negatives = tf.where(mask_final, negatives_outside,
                               negatives_inside)

    loss_mat = tf.math.add(margin, pdist_matrix - semi_hard_negatives)

    mask_positives = tf.cast(
        adjacency, dtype=tf.dtypes.float32) - tf.linalg.diag(
            tf.ones([batch_size]))

    # In lifted-struct, the authors multiply 0.5 for upper triangular
    #   in semihard, they take all positive pairs except the diagonal.
    num_positives = tf.math.reduce_sum(mask_positives)

    triplet_loss = tf.math.truediv(
        tf.math.reduce_sum(
        tf.math.maximum(tf.math.multiply(loss_mat, mask_positives), 0.0)),num_positives)

    return triplet_loss
```

<p>And this is the whole stack trace:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Traceback (most recent call last):
  File "C:/Users/gus/Documents/ImageSimularity/FoodTrainer.py", line 79, in <module>
    callbacks=callbacks_list)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 1297, in fit_generator
    steps_name='steps_per_epoch')
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_generator.py", line 265, in model_iteration
    batch_outs = batch_function(*batch_data)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 973, in train_on_batch
    class_weight=class_weight, reset_metrics=reset_metrics)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py", line 264, in train_on_batch
    output_loss_metrics=model._output_loss_metrics)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_eager.py", line 311, in train_on_batch
    output_loss_metrics=output_loss_metrics))
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_eager.py", line 252, in _process_single_batch
    training=training))
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_eager.py", line 166, in _model_loss
    per_sample_losses = loss_fn.call(targets[i], outs[i])
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\losses.py", line 221, in call
    return self.fn(y_true, y_pred, **self._fn_kwargs)
  File "C:\Users\gus\Documents\ImageSimularity\Tripleloss.py", line 75, in triplet_semihard_loss
    labels = tf.reshape(labels, [lshape[0], 1])
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\ops\array_ops.py", line 131, in reshape
    result = gen_array_ops.reshape(tensor, shape, name)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\ops\gen_array_ops.py", line 8105, in reshape
    tensor, shape, name=name, ctx=_ctx)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\ops\gen_array_ops.py", line 8143, in reshape_eager_fallback
    ctx=_ctx, name=name)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 128 values, but the requested shape has 32 [Op:Reshape]

Process finished with exit code 1</code>```

答:
The tf.reshape does not change the order of or the total number of elements in the tensor. The error as states, you are trying to reduce total number of elements from 128 to 32. You are using tf.reshape in triplet_semihard_loss function.

In below example, I have recreated your scenario where I have the given the shape argument as 2 for tf.reshape which doesn't accommodate all the elements of original tensor, thus throws the error -

Code -

```<code>%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, 2)
</code>```

Output -

```<code>---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-3-0ff1d701ff22> in <module>()
      3 t1 = tf.Variable([1,2,2,4,5,6])
      4
----> 5 t2 = tf.reshape(t1, 2)

3 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Input to reshape is a tensor with 6 values, but the requested shape has 2 [Op:Reshape]
</code>```

tf.reshape should be in such a way that the arrangement of elements can change but total number of elements must remain the same. So the fix would be to change the shape to [2,3] -

Code -

```<code>%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, [2,3])
print(t2)
</code>```

Output -

```<code>tf.Tensor(
[[1 2 2]
 [4 5 6]], shape=(2, 3), dtype=int32)
</code>```

Hope this answers your question. Happy Learning.

Body:
This has stumped me a bit. I have tried several options but cannot get it to work right.
What I am doing is using TF2.0 triple loss function with my own data, but it is not working correctly.
I used the example from TF for an initial test and that works.

function link for reference: https://www.tensorflow.org/addons/tutorials/losses_triplet

With one small difference I am on windows so I cannot download and install tensorflow-addons so I grabbed what I needed to make the code work.
I am using the same model and compile it the same way, but still have issues.
Here is the code:

augment = True
if augment:
    train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0,
        rotation_range=20,
        zoom_range=0.15,
        width_shift_range=0.2,
        height_shift_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest',
        validation_split=0.20)  # set validation split
else:
    train_datagen = ImageDataGenerator(
        horizontal_flip=True,
        rescale=1. / 255,
        fill_mode='nearest',
        validation_split=0.20)  # set validation split

train_generator = train_datagen.flow_from_directory(
    DATA_PATH,
    target_size=(28,28),
    color_mode='grayscale',
    batch_size=BATCH_SIZE,
    class_mode='categorical',
    subset='training')  # set as training data

validation_generator = train_datagen.flow_from_directory(
    DATA_PATH,  # same directory as training data
    target_size=(28,28),
    color_mode='grayscale',
    batch_size=BATCH_SIZE,
    class_mode='categorical',
    subset='validation')  # set as validation data

# Build the network

model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='valid', activation='relu', input_shape=(28,28, 1)))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='valid', activation='relu'))
model.add(tf.keras.layers.MaxPooling2D(pool_size=2))
model.add(tf.keras.layers.Dropout(0.3))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(256, activation=None))  # No activation on final dense layer
model.add(tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1)))  # L2 normalize embeddings

# Compile the model
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
          loss=triplet_semihard_loss)

Its all the same just not the data. I even resize and grayscale the data so it is the same shape as the other input data.

Here is the whole error:

File "C:\Users\matthew.millar\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 128 values, but the requested shape has 32 [Op:Reshape]

EDIT

def triplet_semihard_loss(y_true, y_pred, margin=1.0):
    labels, embeddings = y_true, y_pred
    # Reshape label tensor to [batch_size, 1].
    lshape = tf.shape(labels)
    labels = tf.reshape(labels, [lshape[0], 1])

    # Build pairwise squared distance matrix.
    pdist_matrix = pairwise_distance(embeddings, squared=True)
    # Build pairwise binary adjacency matrix.
    adjacency = tf.math.equal(labels, tf.transpose(labels))
    # Invert so we can select negatives only.
    adjacency_not = tf.math.logical_not(adjacency)

    batch_size = tf.size(labels)

    # Compute the mask.
    pdist_matrix_tile = tf.tile(pdist_matrix, [batch_size, 1])
    mask = tf.math.logical_and(
        tf.tile(adjacency_not, [batch_size, 1]),
        tf.math.greater(pdist_matrix_tile,
                    tf.reshape(tf.transpose(pdist_matrix), [-1, 1])))
    mask_final = tf.reshape(
        tf.math.greater(
            tf.math.reduce_sum(
                tf.cast(mask, dtype=tf.dtypes.float32), 1, keepdims=True),
        0.0), [batch_size, batch_size])
    mask_final = tf.transpose(mask_final)

    adjacency_not = tf.cast(adjacency_not, dtype=tf.dtypes.float32)
    mask = tf.cast(mask, dtype=tf.dtypes.float32)

    # negatives_outside: smallest D_an where D_an > D_ap.
    negatives_outside = tf.reshape(
        _masked_minimum(pdist_matrix_tile, mask), [batch_size, batch_size])
    negatives_outside = tf.transpose(negatives_outside)

    # negatives_inside: largest D_an.
    negatives_inside = tf.tile(
        _masked_maximum(pdist_matrix, adjacency_not), [1, batch_size])
    semi_hard_negatives = tf.where(mask_final, negatives_outside,
                               negatives_inside)

    loss_mat = tf.math.add(margin, pdist_matrix - semi_hard_negatives)

    mask_positives = tf.cast(
        adjacency, dtype=tf.dtypes.float32) - tf.linalg.diag(
            tf.ones([batch_size]))

    # In lifted-struct, the authors multiply 0.5 for upper triangular
    #   in semihard, they take all positive pairs except the diagonal.
    num_positives = tf.math.reduce_sum(mask_positives)

    triplet_loss = tf.math.truediv(
        tf.math.reduce_sum(
        tf.math.maximum(tf.math.multiply(loss_mat, mask_positives), 0.0)),num_positives)

    return triplet_loss

And this is the whole stack trace:

Traceback (most recent call last):
  File "C:/Users/gus/Documents/ImageSimularity/FoodTrainer.py", line 79, in <module>
    callbacks=callbacks_list)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 1297, in fit_generator
    steps_name='steps_per_epoch')
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_generator.py", line 265, in model_iteration
    batch_outs = batch_function(*batch_data)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training.py", line 973, in train_on_batch
    class_weight=class_weight, reset_metrics=reset_metrics)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_v2_utils.py", line 264, in train_on_batch
    output_loss_metrics=model._output_loss_metrics)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_eager.py", line 311, in train_on_batch
    output_loss_metrics=output_loss_metrics))
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_eager.py", line 252, in _process_single_batch
    training=training))
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\engine\training_eager.py", line 166, in _model_loss
    per_sample_losses = loss_fn.call(targets[i], outs[i])
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\keras\losses.py", line 221, in call
    return self.fn(y_true, y_pred, **self._fn_kwargs)
  File "C:\Users\gus\Documents\ImageSimularity\Tripleloss.py", line 75, in triplet_semihard_loss
    labels = tf.reshape(labels, [lshape[0], 1])
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\ops\array_ops.py", line 131, in reshape
    result = gen_array_ops.reshape(tensor, shape, name)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\ops\gen_array_ops.py", line 8105, in reshape
    tensor, shape, name=name, ctx=_ctx)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\ops\gen_array_ops.py", line 8143, in reshape_eager_fallback
    ctx=_ctx, name=name)
  File "C:\Users\gus\Anaconda3\envs\TF2\lib\site-packages\tensorflow_core\python\eager\execute.py", line 67, in quick_execute
    six.raise_from(core._status_to_exception(e.code, message), None)
  File "<string>", line 3, in raise_from
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 128 values, but the requested shape has 32 [Op:Reshape]

Process finished with exit code 1

Body:
The tf.reshape does not change the order of or the total number of elements in the tensor. The error as states, you are trying to reduce total number of elements from 128 to 32. You are using tf.reshape in triplet_semihard_loss function.

In below example, I have recreated your scenario where I have the given the shape argument as 2 for tf.reshape which doesn't accommodate all the elements of original tensor, thus throws the error -

Code -

%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, 2)

Output -

---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-3-0ff1d701ff22> in <module>()
      3 t1 = tf.Variable([1,2,2,4,5,6])
      4
----> 5 t2 = tf.reshape(t1, 2)

3 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: Input to reshape is a tensor with 6 values, but the requested shape has 2 [Op:Reshape]

tf.reshape should be in such a way that the arrangement of elements can change but total number of elements must remain the same. So the fix would be to change the shape to [2,3] -

Code -

%tensorflow_version 2.x
import tensorflow as tf
t1 = tf.Variable([1,2,2,4,5,6])

t2 = tf.reshape(t1, [2,3])
print(t2)

Output -

tf.Tensor(
[[1 2 2]
 [4 5 6]], shape=(2, 3), dtype=int32)

Hope this answers your question. Happy Learning.


问:
Cocoa: programmatically show the main window after closing it with X
I want to programmatically re-open the main window of my Cocoa application after the user closed it with the X button.
I know it's still somewhere in memory but I don't know where.</p>

答:
If you're using the default Cocoa Application template, your app delegate has a reference to the window that's in MainMenu.xib. You can simply call

```<code>[window makeKeyAndOrderFront:self];
</code>```

perhaps in an IBAction triggered by a menu item, to reopen the window. Note: be sure that the "Release when closed" and "One shot" boxes are unchecked in IB.

Body:
If you're using the default Cocoa Application template, your app delegate has a reference to the window that's in MainMenu.xib. You can simply call

[window makeKeyAndOrderFront:self];

perhaps in an IBAction triggered by a menu item, to reopen the window. Note: be sure that the "Release when closed" and "One shot" boxes are unchecked in IB.


问:
python: sendmail program works, if defined as functions it fails
I have a RHEL box with python 2.4.3 and I'm trying to write a python script to send an email.

The problem I have is that the program itself works but when I define the code as function and I call the function, it complaints. How can I fix the function?

Actual error:

No recipient addresses found in header

This is code:

```<code>def send_mail():
   SENDMAIL = "/usr/sbin/sendmail" # sendmail location
   FROM = "sender@domain.ca"
   TO = ["recipient@domain.ca"]
   SUBJECT = "Any subject"
   TEXT = "Any Text."

   # Prepare actual message

   message = """\
   From: %s
   To: %s
   Subject: %s

   %s
   """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

   # Send the mail

   p = os.popen("%s -t -i" % SENDMAIL, "w")
   p.write(message)
   status = p.close()
   if status:
      print "Sendmail exit status", status

send_mail()
</code>```

Thanks
Note: code taken from here: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm

答:
The message shouldn't be indented. Header lines have to be at the beginning of the line; indentation in headers is used to indicate continuation of the previous header.</p>

```<code>   message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)
</code>```

Body:
I have a RHEL box with python 2.4.3 and I'm trying to write a python script to send an email.

The problem I have is that the program itself works but when I define the code as function and I call the function, it complaints. How can I fix the function?

Actual error:

No recipient addresses found in header

This is code:

def send_mail():
   SENDMAIL = "/usr/sbin/sendmail" # sendmail location
   FROM = "sender@domain.ca"
   TO = ["recipient@domain.ca"]
   SUBJECT = "Any subject"
   TEXT = "Any Text."

   # Prepare actual message

   message = """\
   From: %s
   To: %s
   Subject: %s

   %s
   """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

   # Send the mail

   p = os.popen("%s -t -i" % SENDMAIL, "w")
   p.write(message)
   status = p.close()
   if status:
      print "Sendmail exit status", status

send_mail()

Thanks
Note: code taken from here: http://effbot.org/pyfaq/how-do-i-send-mail-from-a-python-script.htm

Body:
The message shouldn't be indented. Header lines have to be at the beginning of the line; indentation in headers is used to indicate continuation of the previous header.

   message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)


问:
Can JQuery do it?
I want to create a div and remove it after 5 seconds, the problem i have is that myscript is removing all the divs at the same time, and I want you to remove the divs in order of creation, one by one.

Here my script until now:

$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  $('.divs').append('
Hello
');
  //HERE FINISH CREATE THE DIVS

  });
});

//HERE I DELETE THE DIVS IF IT EXIST
var $auto_refresh = setInterval(function () {
    var $articleCount = $('.deleteon5seconds').length;

    while ($articleCount > 0) {
        $('.deleteon5seconds:last-child').remove();
        $articleCount = $('.deleteon5seconds').length;
    }

    $autoUpdate();
}, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div></code>```

All this is an example, the purpose of the code is to show alerts. I need help please!
Advanced thanks!!

答:
You can delete the first created element of that class with $('div.deleteon5seconds').first().remove();

.first()

  Description: Reduce the set of matched
  elements to the first in the set.

The problem here is that you have added while and it deletes them all.
Check my fiddle

$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  $('.divs').append('
Hello
');
  //HERE FINISH CREATE THE DIVS

  });
});

//HERE I DELETE THE DIVS IF IT EXIST
var auto_refresh = setInterval(function () {
    var articleCount = $('.deleteon5seconds').length;

    if (articleCount > 0) {

        $('div.deleteon5seconds:first-of-type').remove();
        articleCount = $('.deleteon5seconds').length;
    }

}, 5000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div></code>```

Title: Can JQuery do it?

Body:
I want to create a div and remove it after 5 seconds, the problem i have is that myscript is removing all the divs at the same time, and I want you to remove the divs in order of creation, one by one.

Here my script until now:

$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  $('.divs').append('
Hello
');
  //HERE FINISH CREATE THE DIVS

  });
});

//HERE I DELETE THE DIVS IF IT EXIST
var $auto_refresh = setInterval(function () {
    var $articleCount = $('.deleteon5seconds').length;

    while ($articleCount > 0) {
        $('.deleteon5seconds:last-child').remove();
        $articleCount = $('.deleteon5seconds').length;
    }

    $autoUpdate();
}, 5000);

<button class="create">Create</button>

All this is an example, the purpose of the code is to show alerts. I need help please!
Advanced thanks!!

Body:
You can delete the first created element of that class with $('div.deleteon5seconds').first().remove();

.first()

  Description: Reduce the set of matched
  elements to the first in the set.

The problem here is that you have added while and it deletes them all.
Check my fiddle

$(document).ready(function(){
  $(".create").click(function(){

  //HERE I CREATE THE DIVS
  $('.divs').append('<div class="deleteon5seconds">Hello</div>');
  //HERE FINISH CREATE THE DIVS

  });
});

//HERE I DELETE THE DIVS IF IT EXIST
var auto_refresh = setInterval(function () {
    var articleCount = $('.deleteon5seconds').length;

    if (articleCount > 0) {

        $('div.deleteon5seconds:first-of-type').remove();
        articleCount = $('.deleteon5seconds').length;
    }

}, 5000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="create">Create</button>
<div class="divs"></div>


问:
rounded corners on html5 video
Is there a way I can cut off the corners of my html5 video element using the CSS3 border-radius attribute?

Check out this example. it's not working.

答: As has been said border-radius does work in Firefox and Chrome depending on video type. I found it necessary to style using video, video::first-child for mp4. There is probably an inner layer(border) to mp4s. I did the first-child bit when I noticed ogg and webm were working whereas mp4 was not.  </p>

Title: rounded corners on html5 video


问:
Why can not Hostname of NiFi Certificate Authority be updated using NIFI-TOOLKIT?
Toolkit to generate keystore and truststore with "-c 'hhh'",but the CN is 'localhost'?Can u get me suggestion?Thanks in  advance!

-c,--certificateAuthorityHostname    Hostname of NiFi Certificate Authority (default: localhost)

答:
If you're running the TLS Toolkit in standalone mode, and this is not the first invocation, you likely already have a nifi-cert.pem and nifi-key.key file in the working directory. These files are the CA public certificate and private key respectively. They will be reused to continue signing newly generated node certificates because this allows for trust across the different nodes of the cluster (which is the intended use case for the toolkit).

If you want to create a new CA certificate and use that to sign the node certificates, you have a few options:

Copy the toolkit build directory to a new location and invoke it there. Ensure that the nifi-cert.pem and nifi-key.key files are not present. On the first invocation, a new CA certificate and key will be generated, with the specified certificate authority hostname.

Delete the nifi-cert.pem and nifi-key.key files from your existing toolkit build directory. Warning: You will no longer be able to sign certificates with the same CA key. For example, if you generated node1 and node2 certificates signed by CA_1, then delete CA_1 and want to add node3, you will not be able to sign node3 with CA_1. You will have to import multiple public CA certificates (CA_1 and the new CA_2, for example) into each node's truststore to allow for cross-trust.


问:
Scroll Event Lag/Delay
I'm having issues when using a scroll jQuery event to apply toggle a class depending on the users scroll position. Unfortunately, it's causing issues on users browsers where it "lags" or there is a huge delay in the script executing.

Is there a more efficient way to do this which wouldn't cause any issues with lag/delay?

```<code><script>
  $(window).scroll(function() {
      var scroll = $(window).scrollTop();

      if (scroll >= 40) {
          $(".main-navigation").addClass("glazeNav");
      } else {
          $(".main-navigation").removeClass("glazeNav");
      }
  });
</script>
</code>```

答:
Tried to run your script when the web page is fully loaded</p>

```<code> <script>
 $(document).ready(function ()
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 40) {
       $(".main-navigation").addClass("glazeNav");
    } else {
       $(".main-navigation").removeClass("glazeNav");
    }`enter code here`
   })
  });
</script>
</code>```

Title: Scroll Event Lag/Delay

Body:
Tried to run your script when the web page is fully loaded

 <script>
 $(document).ready(function ()
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 40) {
       $(".main-navigation").addClass("glazeNav");
    } else {
       $(".main-navigation").removeClass("glazeNav");
    }`enter code here`
   })
  });
</script>


问:
is JSONDeserializationSchema() deprecated in Flink?
I am new to Flink and doing something very similar to the below link.

Cannot see message while sinking kafka stream and cannot see print message in flink 1.2

I am also trying to add JSONDeserializationSchema() as a deserializer for my Kafka input JSON message which is without a key.

But I found JSONDeserializationSchema() is not present.

Please let me know if I am doing anything wrong.

答:
JSONDeserializationSchema was removed in Flink 1.8, after having been deprecated earlier.

The recommended approach is to write a deserializer that implements DeserializationSchema<T>. Here's an example, which I've copied from the Flink Operations Playground:

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * A Kafka {@link DeserializationSchema} to deserialize {@link ClickEvent}s from JSON.
 *
 */
public class ClickEventDeserializationSchema implements DeserializationSchema<ClickEvent> {

    private static final long serialVersionUID = 1L;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ClickEvent deserialize(byte[] message) throws IOException {
        return objectMapper.readValue(message, ClickEvent.class);
    }

    @Override
    public boolean isEndOfStream(ClickEvent nextElement) {
        return false;
    }

    @Override
    public TypeInformation<ClickEvent> getProducedType() {
        return TypeInformation.of(ClickEvent.class);
    }
}
```

For a Kafka producer you'll want to implement KafkaSerializationSchema<T>, and you'll find examples of that in that same project.

Body:
JSONDeserializationSchema was removed in Flink 1.8, after having been deprecated earlier.

The recommended approach is to write a deserializer that implements DeserializationSchema<T>. Here's an example, which I've copied from the Flink Operations Playground:

import org.apache.flink.api.common.serialization.DeserializationSchema;
import org.apache.flink.api.common.typeinfo.TypeInformation;

import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * A Kafka {@link DeserializationSchema} to deserialize {@link ClickEvent}s from JSON.
 *
 */
public class ClickEventDeserializationSchema implements DeserializationSchema<ClickEvent> {

    private static final long serialVersionUID = 1L;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public ClickEvent deserialize(byte[] message) throws IOException {
        return objectMapper.readValue(message, ClickEvent.class);
    }

    @Override
    public boolean isEndOfStream(ClickEvent nextElement) {
        return false;
    }

    @Override
    public TypeInformation<ClickEvent> getProducedType() {
        return TypeInformation.of(ClickEvent.class);
    }
}

For a Kafka producer you'll want to implement KafkaSerializationSchema<T>, and you'll find examples of that in that same project.


问:
Better frame rate drawing bitmaps in a Canvas (Part 2)?
Here's what I'm trying to do: I'm trying to load a sequence of bitmaps to display an animation. That means that I need to have a descent fps (24 fps). I need to load no more than 10 seconds of animations or about 300 bitmaps. And since it's a live wallpaper I'm limited to manually drawing each frame.

Here's what I tried so far:

The obvious strategy: load each bitmap each frame and draw it. This is slow.

Use caching. I put the bitmap loading in a seperate thread. A cache of about 20 bitmaps   continously load in the background. However, I still get poor performance (about 10 fps). The culprit is  slow bitmap loading.

I was going to try using OpenGL but then I realized that even with OpenGL, the slow bitmap loading will still be a problem. Right? (Or am I wrong?)

So what other strategies can I use?

Here's what I had in mind: if I use openGL, I can use smaller bitmaps (because it gives better scaling). Perhaps then I can have a bigger cache - say perhaps 3 seconds. With a larger cache, the slow bitmap loading will not be a problem, right?

Any other strategies?

Oh and this is my current bitmap loading function:

```<code>void loadNthBitmap(int i, int n) {
    try {
    buf = new
        BufferedInputStream(assets.
                open(folder+"/"
                     +imageList[n])
                );
    tmpBitmap = BitmapFactory.
        decodeStream(buf);
    rbitmap[i] = Bitmap.createBitmap
        (tmpBitmap,
         0,0,imageWidth,imageHeight,
         transMatrix,false);
    }
    catch(IOException e) {}
}
</code>```

where imageList is pre-defined list of assets and transMatrix is a rotation and scaling matrix.

答:
What you're trying to do (i.e. full-frame animation) is not easy.  Almost all Android animation  (from the Lunar Lander example in the SDK to Angry Birds) consists of moving small sprites on a relatively static background.

The "obvious" solution to your problem would be to turn your animation into an mpeg and then decode it as a video live wallpaper, replicating the approach that this guy took here: http://forum.xda-developers.com/showthread.php?t=804720 (alternative link http://android.ccpcreations.com/vlw/)

Body:
Here's what I'm trying to do: I'm trying to load a sequence of bitmaps to display an animation. That means that I need to have a descent fps (24 fps). I need to load no more than 10 seconds of animations or about 300 bitmaps. And since it's a live wallpaper I'm limited to manually drawing each frame.

Here's what I tried so far:

The obvious strategy: load each bitmap each frame and draw it. This is slow.

Use caching. I put the bitmap loading in a seperate thread. A cache of about 20 bitmaps   continously load in the background. However, I still get poor performance (about 10 fps). The culprit is  slow bitmap loading.

I was going to try using OpenGL but then I realized that even with OpenGL, the slow bitmap loading will still be a problem. Right? (Or am I wrong?)

So what other strategies can I use?

Here's what I had in mind: if I use openGL, I can use smaller bitmaps (because it gives better scaling). Perhaps then I can have a bigger cache - say perhaps 3 seconds. With a larger cache, the slow bitmap loading will not be a problem, right?

Any other strategies?

Oh and this is my current bitmap loading function:

void loadNthBitmap(int i, int n) {
    try {
    buf = new
        BufferedInputStream(assets.
                open(folder+"/"
                     +imageList[n])
                );
    tmpBitmap = BitmapFactory.
        decodeStream(buf);
    rbitmap[i] = Bitmap.createBitmap
        (tmpBitmap,
         0,0,imageWidth,imageHeight,
         transMatrix,false);
    }
    catch(IOException e) {}
}

where imageList is pre-defined list of assets and transMatrix is a rotation and scaling matrix.


问:
Mat-datepicker-toggle showing behind modal and not in here position
Helloo, I have a problem on my view using angular 7 and bootstrap 4. When I click on open to show calendar. It's showing behind my modal and show in the left. How can i fix the probleme?

problem

code

答:
Adding this to CSS worked for me. I am using Angular 8 and Angular Material 8.2.3</p>

```<code>.cdk-overlay-container{
  z-index: 2000;
}
</code>```

Body:
Adding this to CSS worked for me. I am using Angular 8 and Angular Material 8.2.3

.cdk-overlay-container{
  z-index: 2000;
}


问:
How to fix IOAF code GPU errors while using ARKit2 & Vision (VNDetectFaceRectanglesRequest) on iPhone XS
While running ARKit on iPhone XS (with iOS 12.1.2 and Xcode 10.1), I'm getting errors and crashes/hangs while running Vision code to detect face bounds.

Errors I'm getting are:

```<code>2019-01-04 03:03:03.155867-0800 ARKit Vision Demo[12969:3307770] Execution of the command buffer was aborted due to an error during execution. Caused GPU Timeout Error (IOAF code 2)
2019-01-04 03:03:03.155786-0800 ARKit Vision Demo[12969:3307850] Execution of the command buffer was aborted due to an error during execution. Discarded (victim of GPU error/recovery) (IOAF code 5)
[SceneKit] Error: display link thread seems stuck
</code>```

This happens on iPhone XS while running the following proof of concept code to reproduce the error (always happens within a few seconds of running the app) - https://github.com/xta/ARKit-Vision-Demo

The relevant ViewController.swift contains the problematic methods:

```<code>func classifyCurrentImage() {
    guard let buffer = currentBuffer else { return }

    let image = CIImage(cvPixelBuffer: buffer)
    let options: [VNImageOption: Any] = [:]
    let imageRequestHandler = VNImageRequestHandler(ciImage: image, orientation: self.imageOrientation, options: options)

    do {
        try imageRequestHandler.perform(self.requests)
    } catch {
        print(error)
    }
}

func handleFaces(request: VNRequest, error: Error?) {
    DispatchQueue.main.async {
        guard let results = request.results as? [VNFaceObservation] else { return }
        // TODO - something here with results
        print(results)

        self.currentBuffer = nil
    }
}
</code>```

What is the correct way to use Apple's ARKit + Vision with VNDetectFaceRectanglesRequest? Getting mysterious IOAF code errors is not correct.

Ideally, I'd also like to use VNTrackObjectRequest & VNSequenceRequestHandler to track requests.

There is decent online documentation for using VNDetectFaceRectanglesRequest with Vision (and without ARKit). Apple has a page here (https://developer.apple.com/documentation/arkit/using_vision_in_real_time_with_arkit) which I've followed, but I'm still getting the errors/crashes.

答:
For anyone else who goes through the pain I just did trying to fix this exact error for VNDetectRectanglesRequest, here was my solution:

It seems that using a CIImage:

```<code>let imageRequestHandler = VNImageRequestHandler(ciImage: image, orientation: self.imageOrientation, options: options)
</code>```

caused Metal to retain a large amount Internal Functions in my memory graph.

I noticed that Apple's example projects all use this instead:

```<code>let handler: VNImageRequestHandler! = VNImageRequestHandler(cvPixelBuffer: pixelBuffer,
                                                                    orientation: orientation,
                                                                    options: requestHandlerOptions)
</code>```

Switching to use cvPixelBuffer instead of a CIImage fixed all of my random GPU timeout errors!

I used these functions to get the orientation (I'm using the back camera. I think you may have to mirror for the front camera depending on what you're trying to do):

```<code>func exifOrientationForDeviceOrientation(_ deviceOrientation: UIDeviceOrientation) -> CGImagePropertyOrientation {

    switch deviceOrientation {
    case .portraitUpsideDown:
        return .right

    case .landscapeLeft:
        return .down

    case .landscapeRight:
        return .up

    default:
        return .left
    }
}

func exifOrientationForCurrentDeviceOrientation() -> CGImagePropertyOrientation {
    return exifOrientationForDeviceOrientation(UIDevice.current.orientation)
}
</code>```

and the following as the options:

```<code>var requestHandlerOptions: [VNImageOption: AnyObject] = [:]
let cameraIntrinsicData = CMGetAttachment(pixelBuffer, key: kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, attachmentModeOut: nil)
if cameraIntrinsicData != nil {
            requestHandlerOptions[VNImageOption.cameraIntrinsics] = cameraIntrinsicData
}
</code>```

Hopefully this saves someone the week that I lost!

Body:
While running ARKit on iPhone XS (with iOS 12.1.2 and Xcode 10.1), I'm getting errors and crashes/hangs while running Vision code to detect face bounds.

Errors I'm getting are:

2019-01-04 03:03:03.155867-0800 ARKit Vision Demo[12969:3307770] Execution of the command buffer was aborted due to an error during execution. Caused GPU Timeout Error (IOAF code 2)
2019-01-04 03:03:03.155786-0800 ARKit Vision Demo[12969:3307850] Execution of the command buffer was aborted due to an error during execution. Discarded (victim of GPU error/recovery) (IOAF code 5)
[SceneKit] Error: display link thread seems stuck

This happens on iPhone XS while running the following proof of concept code to reproduce the error (always happens within a few seconds of running the app) - https://github.com/xta/ARKit-Vision-Demo

The relevant ViewController.swift contains the problematic methods:

func classifyCurrentImage() {
    guard let buffer = currentBuffer else { return }

    let image = CIImage(cvPixelBuffer: buffer)
    let options: [VNImageOption: Any] = [:]
    let imageRequestHandler = VNImageRequestHandler(ciImage: image, orientation: self.imageOrientation, options: options)

    do {
        try imageRequestHandler.perform(self.requests)
    } catch {
        print(error)
    }
}

func handleFaces(request: VNRequest, error: Error?) {
    DispatchQueue.main.async {
        guard let results = request.results as? [VNFaceObservation] else { return }
        // TODO - something here with results
        print(results)

        self.currentBuffer = nil
    }
}

What is the correct way to use Apple's ARKit + Vision with VNDetectFaceRectanglesRequest? Getting mysterious IOAF code errors is not correct.

Ideally, I'd also like to use VNTrackObjectRequest & VNSequenceRequestHandler to track requests.

There is decent online documentation for using VNDetectFaceRectanglesRequest with Vision (and without ARKit). Apple has a page here (https://developer.apple.com/documentation/arkit/using_vision_in_real_time_with_arkit) which I've followed, but I'm still getting the errors/crashes.

Body:
For anyone else who goes through the pain I just did trying to fix this exact error for VNDetectRectanglesRequest, here was my solution:

It seems that using a CIImage:

let imageRequestHandler = VNImageRequestHandler(ciImage: image, orientation: self.imageOrientation, options: options)

caused Metal to retain a large amount Internal Functions in my memory graph.

I noticed that Apple's example projects all use this instead:

let handler: VNImageRequestHandler! = VNImageRequestHandler(cvPixelBuffer: pixelBuffer,
                                                                    orientation: orientation,
                                                                    options: requestHandlerOptions)

Switching to use cvPixelBuffer instead of a CIImage fixed all of my random GPU timeout errors!

I used these functions to get the orientation (I'm using the back camera. I think you may have to mirror for the front camera depending on what you're trying to do):

func exifOrientationForDeviceOrientation(_ deviceOrientation: UIDeviceOrientation) -> CGImagePropertyOrientation {

    switch deviceOrientation {
    case .portraitUpsideDown:
        return .right

    case .landscapeLeft:
        return .down

    case .landscapeRight:
        return .up

    default:
        return .left
    }
}

func exifOrientationForCurrentDeviceOrientation() -> CGImagePropertyOrientation {
    return exifOrientationForDeviceOrientation(UIDevice.current.orientation)
}

and the following as the options:

var requestHandlerOptions: [VNImageOption: AnyObject] = [:]
let cameraIntrinsicData = CMGetAttachment(pixelBuffer, key: kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, attachmentModeOut: nil)
if cameraIntrinsicData != nil {
            requestHandlerOptions[VNImageOption.cameraIntrinsics] = cameraIntrinsicData
}

Hopefully this saves someone the week that I lost!


问:
Is it possible to log all HTTP request headers with Apache?
How to make a record into the logfile the contents of the HTTP request header (all) as received by apache?

Currently my apache combined log format configuration is:

```<code>LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{Cookie}i\"" combined
</code>```

I understand that it is possible to do it so:

```<code>LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{Cookie}i\" \"%{heading name}i\" \"%{heading name}i\" \"%{heading name}i\"" combined
</code>```

but it is not logical and it is not possible to know which headers will be.

答:
In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.</p>
```<code><?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time + "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>
</code>```

Body:
How to make a record into the logfile the contents of the HTTP request header (all) as received by apache?

Currently my apache combined log format configuration is:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{Cookie}i\"" combined

I understand that it is possible to do it so:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{Cookie}i\" \"%{heading name}i\" \"%{heading name}i\" \"%{heading name}i\"" combined

but it is not logical and it is not possible to know which headers will be.

Body:
In my case easiest way to get browser headers was to use php. It appends headers to file and prints them to test page.

<?php
$fp = fopen('m:/temp/requests.txt', 'a');
$time = $_SERVER['REQUEST_TIME'];
fwrite($fp, $time + "\n");
echo "$time.<br>";
foreach (getallheaders() as $name => $value) {
    $cur_hd = "$name: $value\n";
    fwrite($fp, $cur_hd);
    echo "$cur_hd.<br>";
}
fwrite($fp, "***\n");
fclose($fp);
?>