问:
Python filter list to remove certain links from html source code
I have html source code which I want to filter out one or more links and keep the others.

I have set up my filter with "*" as the wildcard:

```<code><a*>Link1</a>‚ <a*>Link2</a>‚ or <a*>Link3</a>
<a*>A bad link*</a>
some text* <a*>update*</a>
other text right before link <a*>click here</a>
</code>```

I would like to filter out every instance of the link from the html source code using python. I'm ok with loading the list into an array.  I need some help with the filter.  Each line break would signify a separate filter and I only want to remove the link(s) and not the text

I am still very new to python and regex/beautifulsoup.  Even if you could point me in the right direction, it would be greatly appreciated.

答:
To remove  tags and keep only the text not contained within those tags:

```<code>>>> from BeautifulSoup import BeautifulSoup as bs
>>> markup = """<a*>Link1</a> <a*>Link2</a> or <a*>Link3</a>
... <a*>A bad link*</a>
... some text* <a*>update*</a>
... other text right before link <a*>click here</a>"""
>>> soup = bs(markup)
>>> TAGS_TO_EXTRACT = ('a',)
>>> for tag in soup.findAll():
...   if tag.name in TAGS_TO_EXTRACT:
...     tag.extract()
...
>>> soup
  or

some text*
other text right before link
</code>```

It's not clear to me if you want the text within the tags or not.  If you want the text contained within the tags do something like this instead:

```<code>>>> for tag in soup.findAll():
...   if tag.name in TAGS_TO_EXTRACT:
...     tag.replaceWith(tag.text)
...
>>> soup
Link1 Link2 or Link3
A bad link*
some text* update*
other text right before link click here
</code>```

Body:
I have html source code which I want to filter out one or more links and keep the others.

I have set up my filter with "*" as the wildcard:

Link1‚ Link2‚ or Link3
A bad link*
some text* update*
other text right before link click here

I would like to filter out every instance of the link from the html source code using python. I'm ok with loading the list into an array.  I need some help with the filter.  Each line break would signify a separate filter and I only want to remove the link(s) and not the text

I am still very new to python and regex/beautifulsoup.  Even if you could point me in the right direction, it would be greatly appreciated.

Body:
To remove <a> tags and keep only the text not contained within those tags:

>>> from BeautifulSoup import BeautifulSoup as bs
>>> markup = """<a*>Link1</a> <a*>Link2</a> or <a*>Link3</a>
... <a*>A bad link*</a>
... some text* <a*>update*</a>
... other text right before link <a*>click here</a>"""
>>> soup = bs(markup)
>>> TAGS_TO_EXTRACT = ('a',)
>>> for tag in soup.findAll():
...   if tag.name in TAGS_TO_EXTRACT:
...     tag.extract()
...
>>> soup
  or

some text*
other text right before link

It's not clear to me if you want the text within the tags or not.  If you want the text contained within the tags do something like this instead:

>>> for tag in soup.findAll():
...   if tag.name in TAGS_TO_EXTRACT:
...     tag.replaceWith(tag.text)
...
>>> soup
Link1 Link2 or Link3
A bad link*
some text* update*
other text right before link click here


来源: stackexchange

问:
Can git tell me if a rebase will conflict without actually rebasing?
I would like to programmatically determine with of my feature branches would have rebase conflicts if I tried to rebase them.  Is there a way I can get git to tell me this information without actually performing the rebase?

Failing that, what is the simplest way to detect if a rebase failed before git rebase --aborting it?

My question is similar to these two, which are the same but for merge instead of rebase

Can git tell me if a merge will conflict without actually merging?

Is there a git-merge --dry-run option?

答:
You could use a custom pre-rebase hook to do any checks that you need before the rebase begins. There's a sample pre-rebase hook here: https://github.com/git/git/blob/master/templates/hooks--pre-rebase.sample

In the pre-rebase hook code, you could diff the changed files and check for conflicts and stop the rebase.

ContentLicense: CC BY-SA 3.0


问:
Return more than 1 types from a table using SQL
I have a table like this

```<code>Type <- c("TEN_02","TEN_04","TEN_05",
          "JOS_01","JOS_02","JOS_03",
          "VIT_06","VIT_11","VIT_08")
Value <- c(5,8,9,11,8,4,6,6,7)
df <- data.frame(Type,Value)
</code>```

I am trying to use an sql statement to extract any types with TEN & VIT from this table.

I am able to return for one type using sqldf

```<code>library(sqldf)
df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE 'TEN%'")
</code>```

But, if I need to pass in a variable "TYPES" that has more than one type

```<code>TYPES <- 'TEN,VIT'

df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE ('",TYPES,"%')")
</code>```

I get an error

```<code>Error in rsqlite_send_query(conn@ptr, statement) :
  unrecognized token: "'"
</code>```

My desired output is

```<code>    Type Value
  TEN_02     5
  TEN_04     8
  TEN_05     9
  VIT_06     6
  VIT_11     6
  VIT_08     7
</code>```

Could someone point me in the right direction? I would like to use SQL for this instead of dplyr or data.table since I would want to apply the logic to query databases.

答:
Well you can use a compound condition (an OR condition) like

```<code>SELECT * FROM df
WHERE Type LIKE 'TEN%'
OR Type LIKE 'VIT%'
</code>```

have no idea about sqldf but think you can do it like below per this blog https://codywu2010.wordpress.com/2015/08/08/r-sqldf-select-with-condition-of-one-column-like-another-column/

```<code>df1 <- sqldf("SELECT * FROM df WHERE Type LIKE TYPES || '%' ")
</code>```

Body:
I have a table like this

Type <- c("TEN_02","TEN_04","TEN_05",
          "JOS_01","JOS_02","JOS_03",
          "VIT_06","VIT_11","VIT_08")
Value <- c(5,8,9,11,8,4,6,6,7)
df <- data.frame(Type,Value)

I am trying to use an sql statement to extract any types with TEN & VIT from this table.

I am able to return for one type using sqldf

library(sqldf)
df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE 'TEN%'")

But, if I need to pass in a variable "TYPES" that has more than one type

TYPES <- 'TEN,VIT'

df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE ('",TYPES,"%')")

I get an error

Error in rsqlite_send_query(conn@ptr, statement) :
  unrecognized token: "'"

My desired output is

    Type Value
  TEN_02     5
  TEN_04     8
  TEN_05     9
  VIT_06     6
  VIT_11     6
  VIT_08     7

Could someone point me in the right direction? I would like to use SQL for this instead of dplyr or data.table since I would want to apply the logic to query databases.

Body:
Well you can use a compound condition (an OR condition) like

SELECT * FROM df
WHERE Type LIKE 'TEN%'
OR Type LIKE 'VIT%'

have no idea about sqldf but think you can do it like below per this blog https://codywu2010.wordpress.com/2015/08/08/r-sqldf-select-with-condition-of-one-column-like-another-column/

df1 <- sqldf("SELECT * FROM df WHERE Type LIKE TYPES || '%' ")


问:
Good way to insert html atributes in blade template based on conditions in Laravel 5.3
I know that there are other question addressing this issue but they mostly cover adding a value to an attribute based on a variable.  I want to include several attributes and their values based on a condition.

My first attempt, as you can see below, besides not working is not very readable:

```<code><input
type="text"
{{ $errors->has('bedrooms') ? "data-toggle='tooltip' data-placement='right'
title='please, enter a value between 1 and 9.'" : "" }}

/>
</code>```

Produces the html:

```<code><input type="text"
data-toggle="tooltip" data-placement="right"
title="please, enter a value between 1 and 9.&quot />
</code>```

答:
Change your blade syntax to {!! !!}

```<code><input type="text"
  {!! $errors->has('bedrooms') ? "data-toggle='tooltip' data-placement='right' title='please, enter a value between 1 and 9.'" : "" !!}
/>
</code>```

By default, Blade escape Html - See the documentation

Body:
I know that there are other question addressing this issue but they mostly cover adding a value to an attribute based on a variable.  I want to include several attributes and their values based on a condition.

My first attempt, as you can see below, besides not working is not very readable:

<input
type="text"
{{ $errors->has('bedrooms') ? "data-toggle='tooltip' data-placement='right'
title='please, enter a value between 1 and 9.'" : "" }}

/>

Produces the html:

<input type="text"
data-toggle="tooltip" data-placement="right"
title="please, enter a value between 1 and 9.&quot />

Body:
Change your blade syntax to {!! !!}

<input type="text"
  {!! $errors->has('bedrooms') ? "data-toggle='tooltip' data-placement='right' title='please, enter a value between 1 and 9.'" : "" !!}
/>

By default, Blade escape Html - See the documentation


问:
Use Selenium Driver to load page, dismiss/dispose it and keep browser active
I am using Selenium Webdriver to load a specific feature from an application, a rich text editor (actually a custom release of CKEditor) and the code below works perfectly for that... except that I would like to release Selenium objects (and geckodriver.exe/marionnette black cmd window) since the desired page was loaded. But either .Close(), .Quit() or .Dispose() methods will wipe out the Firefox window as well...

Is there a way to dismiss Selenium Webdriver and keep Firefox running by its own?

Thank you very much

```<code>Private Sub LoadResource()
    Dim FFD As New OpenQA.Selenium.Firefox.FirefoxDriver()

    'Set timeout of 60 seconds for steps to complete successfully
    Dim WDW As New OpenQA.Selenium.Support.UI.WebDriverWait(FFD, TimeSpan.FromSeconds(60))

    'navigate to login page
    FFD.Navigate.GoToUrl("https://www.myapplication.com/login")

    'Wait until application loads main page (this means login was successful)
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/")

    'Load built-in rich text editor Rich text
    FFD.Navigate.GoToUrl("https://www.myapplication.com/editor?document=1080199")

    'Wait for successful loading of the editor page
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/editor?document=1080199")

     'That's all.
     'here I'd like to release Firefox to keep running and get rid  of WebDriver's objects and resources, if possible.

End Sub
</code>```

答:
This is based on Kirhgoph's comment and seems to work well:</p>

```<code>Private Sub LoadResource()
    Dim FFD As New OpenQA.Selenium.Firefox.FirefoxDriver()
    Dim GDP As Process = Process.GetProcessesByName("geckodriver").Last
    Dim WDW As New OpenQA.Selenium.Support.UI.WebDriverWait(FFD, TimeSpan.FromSeconds(60))
    FFD.Navigate.GoToUrl("https://www.myapplication.com/login")
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/")
    FFD.Navigate.GoToUrl("https://my.application.com/editor?document=1080199")
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/editor?document=1080199")
    GDP.CloseMainWindow()
    GDP.WaitForExit()
    FFD.Quit()
End Sub
</code>```

Body:
I am using Selenium Webdriver to load a specific feature from an application, a rich text editor (actually a custom release of CKEditor) and the code below works perfectly for that... except that I would like to release Selenium objects (and geckodriver.exe/marionnette black cmd window) since the desired page was loaded. But either .Close(), .Quit() or .Dispose() methods will wipe out the Firefox window as well...

Is there a way to dismiss Selenium Webdriver and keep Firefox running by its own?

Thank you very much

Private Sub LoadResource()
    Dim FFD As New OpenQA.Selenium.Firefox.FirefoxDriver()

    'Set timeout of 60 seconds for steps to complete successfully
    Dim WDW As New OpenQA.Selenium.Support.UI.WebDriverWait(FFD, TimeSpan.FromSeconds(60))

    'navigate to login page
    FFD.Navigate.GoToUrl("https://www.myapplication.com/login")

    'Wait until application loads main page (this means login was successful)
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/")

    'Load built-in rich text editor Rich text
    FFD.Navigate.GoToUrl("https://www.myapplication.com/editor?document=1080199")

    'Wait for successful loading of the editor page
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/editor?document=1080199")

     'That's all.
     'here I'd like to release Firefox to keep running and get rid  of WebDriver's objects and resources, if possible.

End Sub

Body:
This is based on Kirhgoph's comment and seems to work well:

Private Sub LoadResource()
    Dim FFD As New OpenQA.Selenium.Firefox.FirefoxDriver()
    Dim GDP As Process = Process.GetProcessesByName("geckodriver").Last
    Dim WDW As New OpenQA.Selenium.Support.UI.WebDriverWait(FFD, TimeSpan.FromSeconds(60))
    FFD.Navigate.GoToUrl("https://www.myapplication.com/login")
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/")
    FFD.Navigate.GoToUrl("https://my.application.com/editor?document=1080199")
    WDW.Until(Function() FFD.Url = "https://www.myapplication.com/editor?document=1080199")
    GDP.CloseMainWindow()
    GDP.WaitForExit()
    FFD.Quit()
End Sub


问:
How can I call a method in a base Frame Renderer from the iOS Custom renderer?
I have this code:

```<code>public partial class PhrasesFrameRenderer : Frame
{
    Random rand = new Random();
    private int answeredPhraseCount;
    private int correctAns;

    public PhrasesFrameRenderer()
    {
        InitializeComponent();
        App.PhrasesFrameRenderer = this;

        public void abc()
        {

            ....
        };
</code>```

and the custom Renderer

```<code>[assembly: ExportRenderer(typeof(PhrasesFrameRenderer), typeof(PhrasesFrameCustomRenderer))]
namespace Japanese.iOS
{
    public class PhrasesFrameCustomRenderer : FrameRenderer
    {
        UISwipeGestureRecognizer leftSwipeGestureRecognizer;
        UISwipeGestureRecognizer rightSwipeGestureRecognizer;
        PhrasesFrameRenderer frame;
        bool rightSwipeEnabled = false;
</code>```

Can someone explain to me how I can call the ABC function in the Phrases FrameRenderer from the custom Renderer code.

答:
So the 'ExportRenderer' flag basically tells the native project that if it is trying to display that type of control, override where necessary anything used in the native code (I.E. the overriden methods in your class 'PhrasesFrameCustomRenderer').

What this means is that your custom renderer doesn't technically derive from your custom frame, it derives from a special xamarin forms class, in this case the class called 'FrameRenderer'. So it doesn't have access to any of the methods in your derived control in your forms project ('PhrasesFrameRenderer').

So the solution to your answer depends entirely on what you're trying to achieve.

If you simply want to invoke that method at a certain time, then you could look into subscribing to the messagingcenter, if you want access to variables/data that the method may create, then that could be done by a generic static dictionary for setting and getting objects.

EDIT MessagingCenter Example:

```<code>public partial class PhrasesFrameRenderer : Frame
{
    Random rand = new Random();
    private int answeredPhraseCount;
    private int correctAns;

    public PhrasesFrameRenderer()
    {
        InitializeComponent();
        App.PhrasesFrameRenderer = this;
        MessagingCenter.Subscribe<App>(App, "invokeABC", abc);
    }

    public void abc(App obj)
    {

    };
}
</code>```

and in your custom renderer you need the following wherever you want to invoke that method:

```<code>MessagingCenter.Send((App)Xamarin.Forms.Application.Current, "invokeABC");
</code>```

This all assumes that you do not need to pass any data between the two classes.

EDIT Static pointer

Taking a closer look at your code you place a pointer to your custom frame in a variable in your App class. so in theory you could call

```<code>App.PhrasesFrameRenderer.abc();
</code>```

Body:
I have this code:

public partial class PhrasesFrameRenderer : Frame
{
    Random rand = new Random();
    private int answeredPhraseCount;
    private int correctAns;

    public PhrasesFrameRenderer()
    {
        InitializeComponent();
        App.PhrasesFrameRenderer = this;

        public void abc()
        {

            ....
        };

and the custom Renderer

[assembly: ExportRenderer(typeof(PhrasesFrameRenderer), typeof(PhrasesFrameCustomRenderer))]
namespace Japanese.iOS
{
    public class PhrasesFrameCustomRenderer : FrameRenderer
    {
        UISwipeGestureRecognizer leftSwipeGestureRecognizer;
        UISwipeGestureRecognizer rightSwipeGestureRecognizer;
        PhrasesFrameRenderer frame;
        bool rightSwipeEnabled = false;

Can someone explain to me how I can call the ABC function in the Phrases FrameRenderer from the custom Renderer code.

Body:
So the 'ExportRenderer' flag basically tells the native project that if it is trying to display that type of control, override where necessary anything used in the native code (I.E. the overriden methods in your class 'PhrasesFrameCustomRenderer').

What this means is that your custom renderer doesn't technically derive from your custom frame, it derives from a special xamarin forms class, in this case the class called 'FrameRenderer'. So it doesn't have access to any of the methods in your derived control in your forms project ('PhrasesFrameRenderer').

So the solution to your answer depends entirely on what you're trying to achieve.

If you simply want to invoke that method at a certain time, then you could look into subscribing to the messagingcenter, if you want access to variables/data that the method may create, then that could be done by a generic static dictionary for setting and getting objects.

EDIT MessagingCenter Example:

public partial class PhrasesFrameRenderer : Frame
{
    Random rand = new Random();
    private int answeredPhraseCount;
    private int correctAns;

    public PhrasesFrameRenderer()
    {
        InitializeComponent();
        App.PhrasesFrameRenderer = this;
        MessagingCenter.Subscribe<App>(App, "invokeABC", abc);
    }

    public void abc(App obj)
    {

    };
}

and in your custom renderer you need the following wherever you want to invoke that method:

MessagingCenter.Send((App)Xamarin.Forms.Application.Current, "invokeABC");

This all assumes that you do not need to pass any data between the two classes.

EDIT Static pointer

Taking a closer look at your code you place a pointer to your custom frame in a variable in your App class. so in theory you could call

App.PhrasesFrameRenderer.abc();


问:
How can I run cargo tests on another machine without the Rust compiler?
I know that the compiler can run directly on arm-linux-androideabi, but the Android emulator (I mean emulation of ARM on x86/amd64) is slow,
so I don't want to use cargo and rustc on the emulator, I only want to run tests on it.

I want to cross-compile tests on my PC (cargo test --target=arm-linux-androideabi --no-run?), and then upload and run them on emulator,
hoping to catch bugs like this.

How can I run cargo test without running cargo test? Is it as simple as running all binaries that were built with cargo test --no-run?

答:
There are two kinds of tests supported by cargo test, one is the normal tests (#[test] fns and files inside tests/), the other is the doc tests.

The normal tests are as simple as running all binaries. The test is considered successful if it exits with error code 0.

Doc tests cannot be cross-tested. Doc tests are compiled and executed directly by rustdoc using the compiler libraries, so the compiler must be installed on the ARM machine to run the doc tests. In fact, running cargo test --doc when HOST ≠ TARGET will do nothing.

So, the answer to your last question is yes as long as you don't rely on doc-tests for coverage.

Starting from Rust 1.19, cargo supports target specific runners, which allows you to  specify a script to upload and execute the test program on the ARM machine.

#!/bin/sh
set -e
adb push "$1" "/sdcard/somewhere/$1"
adb shell "chmod 755 /sdcard/somewhere/$1 && /sdcard/somewhere/$1"
# ^ note: may need to change this line, see https://stackoverflow.com/q/9379400
```

<p>Put this to your <code>.cargo/config</code>:</p>

<pre class="lang-ini prettyprint-override"><code>[target.arm-linux-androideabi]
runner = ["/path/to/your/run/script.sh"]
</code>```

then cargo test --target=arm-linux-androideabi should Just Work™.

If your project is hosted on GitHub and uses Travis CI, you may also want to check out trust. It provides a pre-packaged solution for testing on many architectures including ARMv7 Linux on the CI (no Android unfortunately).

Body:
There are two kinds of tests supported by cargo test, one is the normal tests (#[test] fns and files inside tests/), the other is the doc tests.

The normal tests are as simple as running all binaries. The test is considered successful if it exits with error code 0.

Doc tests cannot be cross-tested. Doc tests are compiled and executed directly by rustdoc using the compiler libraries, so the compiler must be installed on the ARM machine to run the doc tests. In fact, running cargo test --doc when HOST ≠ TARGET will do nothing.

So, the answer to your last question is yes as long as you don't rely on doc-tests for coverage.

Starting from Rust 1.19, cargo supports target specific runners, which allows you to  specify a script to upload and execute the test program on the ARM machine.

#!/bin/sh
set -e
adb push "$1" "/sdcard/somewhere/$1"
adb shell "chmod 755 /sdcard/somewhere/$1 && /sdcard/somewhere/$1"
# ^ note: may need to change this line, see https://stackoverflow.com/q/9379400

Put this to your .cargo/config:

[target.arm-linux-androideabi]
runner = ["/path/to/your/run/script.sh"]

then cargo test --target=arm-linux-androideabi should Just Work™.

If your project is hosted on GitHub and uses Travis CI, you may also want to check out trust. It provides a pre-packaged solution for testing on many architectures including ARMv7 Linux on the CI (no Android unfortunately).

ContentLicense: CC BY-SA 4.0


问:
Reducing code duplication while defining a commutative operation
I have a a set of overloads of a commutative binary function named overlap, which accepts two distinct types:

```<code>class A a; class B b;
bool overlap(A, B);
bool overlap(B, A);
</code>```

My function overlap returns true if and only if one shape overlaps the other - this is one common example used when discussing multimethods.

Because overlap(a, b) is equivalent to overlap(b, a), I only need to implement one "side" of the relation.  One repetitive solution is to write something like this:

```<code>bool overlap(A a, B b) { /* check for overlap */ }
bool overlap(B b, A a) { return overlap(a, b);   }
</code>```

But I would prefer not to write an extra N! / 2 trivial versions of the same function by allowing them to be generated instead, using a template.

```<code>template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap(std::forward<U>(u), std::forward<T>(t)); }
</code>```

Unfortuately, this is prone to recurse infinitely, which is not acceptable: see
http://coliru.stacked-crooked.com/a/20851835593bd557

How can I prevent such infinite recursion?  Am I approaching the problem correctly?

答:
As a wise man once said, there is no problem you cannot solve with an additional layer of indirection, except too many layers of indirection.

So, use SFINAE and some indirection to get it done:

```<code>template<class A, class B>
auto overlap(A&& a, B&& b)
-> decltype(overlap_impl('\0', std::forward<A>(a), std::forward<B>(b)))
{ return overlap_impl('\0', std::forward<A>(a), std::forward<B>(b)); }

template<class A, class B>
auto overlap_impl(int, A&& a, B&& b)
-> decltype(do_overlap(std::forward<A>(a), std::forward<B>(b)))
{ return do_overlap(std::forward<A>(a), std::forward<B>(b)); }

template<class A, class B>
auto overlap_impl(long, B&& b, A&& a)
-> decltype(do_overlap(std::forward<A>(a), std::forward<B>(b)))
{ return do_overlap(std::forward<A>(a), std::forward<B>(b)); }

// You can provide more choices if you want, for example to use member-functions.

// Implement `do_overlap(A, B)`, maybe with references, in at least one direction.
</code>```

Body:
I have a a set of overloads of a commutative binary function named overlap, which accepts two distinct types:

class A a; class B b;
bool overlap(A, B);
bool overlap(B, A);

My function overlap returns true if and only if one shape overlaps the other - this is one common example used when discussing multimethods.

Because overlap(a, b) is equivalent to overlap(b, a), I only need to implement one "side" of the relation.  One repetitive solution is to write something like this:

bool overlap(A a, B b) { /* check for overlap */ }
bool overlap(B b, A a) { return overlap(a, b);   }

But I would prefer not to write an extra N! / 2 trivial versions of the same function by allowing them to be generated instead, using a template.

template <typename T, typename U>
bool overlap(T&& t, U&& u)
{ return overlap(std::forward(u), std::forward<T>(t)); }

Unfortuately, this is prone to recurse infinitely, which is not acceptable: see
http://coliru.stacked-crooked.com/a/20851835593bd557

How can I prevent such infinite recursion?  Am I approaching the problem correctly?

Body:
As a wise man once said, there is no problem you cannot solve with an additional layer of indirection, except too many layers of indirection.

So, use SFINAE and some indirection to get it done:

template<class A, class B>
auto overlap(A&& a, B&& b)
-> decltype(overlap_impl('\0', std::forward<A>(a), std::forward<B>(b)))
{ return overlap_impl('\0', std::forward<A>(a), std::forward<B>(b)); }

template<class A, class B>
auto overlap_impl(int, A&& a, B&& b)
-> decltype(do_overlap(std::forward<A>(a), std::forward<B>(b)))
{ return do_overlap(std::forward<A>(a), std::forward<B>(b)); }

template<class A, class B>
auto overlap_impl(long, B&& b, A&& a)
-> decltype(do_overlap(std::forward<A>(a), std::forward<B>(b)))
{ return do_overlap(std::forward<A>(a), std::forward<B>(b)); }

// You can provide more choices if you want, for example to use member-functions.

// Implement `do_overlap(A, B)`, maybe with references, in at least one direction.


问:
How to add new element to existing 2d string array?
How to add new element to 2d string array in c#?
Ex. I have a array

```<code>string [,] x = new string[,]{{"1","a"},{"2","b"}};
</code>```

Now I want to increase the length array and add "3" and "c" to the top.

答:
You cannot resize Arrays in C#.
But there are 2 solutions for you:

Using List<T> https://msdn.microsoft.com/en-gb/library/6sh2ey19(v=vs.110).aspx

Recreate array everytime after add or remove operations(bad way).

P.S. It looks like you need a Dictionary<K,V> for your work(with unic 1st field, called Key).
https://msdn.microsoft.com/en-gb/library/xfhwa508(v=vs.110).aspx

```<code>var x = new List<List<string>>();
x.Add(new List<string>()
{
    "1", "a"
});
// so on.
</code>```

Body:
How to add new element to 2d string array in c#?
Ex. I have a array

string [,] x = new string[,]{{"1","a"},{"2","b"}};

Now I want to increase the length array and add "3" and "c" to the top.

Body:
You cannot resize Arrays in C#.
But there are 2 solutions for you:

Using List<T> https://msdn.microsoft.com/en-gb/library/6sh2ey19(v=vs.110).aspx

Recreate array everytime after add or remove operations(bad way).

P.S. It looks like you need a Dictionary<K,V> for your work(with unic 1st field, called Key).
https://msdn.microsoft.com/en-gb/library/xfhwa508(v=vs.110).aspx

var x = new List<List<string>>();
x.Add(new List<string>()
{
    "1", "a"
});
// so on.


问:
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value
I'm implementing full calendar API into my project .I have a problem when I try to save an event , I keep on getting the following error:

```<code>SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2017-07-1415:41:03' for column 'start' at row 1 (SQL: insert into `event3s` (`title`, `start`, `end`, `color`) values (New event, 2017-07-1415:41:03, , #9e1515))
</code>```

I have changed to the right time(time zone) in phpmyadmin but I still got the same error.

This is my table in phpmyadmin :
[![enter image description here][1]][1]

This is the calendar.blade.php class :

```<code><!doctype html>
<html lang="{{ config('calendar.locale') }}">
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <title>Full Calendar</title>

    {!! Html::style('vendor2/seguce92/bootstrap/css/bootstrap.min.css') !!}
    {!! Html::style('vendor2/seguce92/fullcalendar/fullcalendar.min.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-datetimepicker/css/bootstrap-material-datetimepicker.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css') !!}

</head>
<div id='app'></div>
<div class='container'></div>

{{ Form::open(['route' => 'user.events.store', 'method' => 'post', 'role' => 'form']) }}
<div id="responsive-modal" class="modal fade" tabindex="-1" data-backdrop="static"->

    <div class="modal-dialog">
        <div class="modal-content">

        <div class="modal-header">
        <h4>Registration of new Event</h4>

        </div>

        <div class="modal-body">

            <div class="form-group">
                {{Form::label('title','Date Start') }}
                {{Form::text('title',old('title'),['class' => 'form-control'])}}
            </div>

        <div class="form-group">
            {{Form::label('date_start','Date Start') }}
            {{Form::text('date_start',old('date_start'),['class' => 'form-control','readonly'=>'true'])}}
        </div>

            <div class="form-group">
                {{Form::label('time_start','Time Start') }}
                {{Form::text('time_start',old('time_start'),['class' => 'form-control'])}}
            </div>

            <div class="form-group">
                {{Form::label('date_end','Time Finish') }}
                {{Form::text('date_end',old('date_end'),['class' => 'form-control'])}}
            </div>

            <div class="form-group">
                {{Form::label('color','COLOR') }}
                <div class="input-group colorpicker">
                    {{ Form::text('color',old('color'),['class' => 'form-control']) }}
                    <span class ="input-group-addon">

                        <i></i>
                    </span>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            {!! Form::submit('Save',['class' => 'btn-btn-success'])!!}

        </div>
    </div>
    </div>

</div>
{{Form::close()}}
<div id='calendar'></div>

</body>

{!! Html::script('vendor2/seguce92/jquery.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap/js/bootstrap.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/lib/moment.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/fullcalendar.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-datetimepicker/js/bootstrap-material-datetimepicker.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js') !!}
    <script type="text/javascript">
    var BASEURL="{{url('/')}}";
        $(document).ready(function() {

            $('#calendar').fullCalendar({
                header: {
                    left: 'prev,next today',
                    center: 'title',
                    right: 'month,basicWeek,basicDay'
                },

                navLinks: true, // can click day/week names to navigate views
                editable: true,
                selectable:true,
                selectHelper:true,

                select:function(start){
                    start = moment(start.format());

                    $('#date_start').val(start.format('YYYY-MM-DD'));
                    $('#responsive-modal').modal('show');
                },
                events: BASEURL+'/events'

            });

        });

        $('.colorpicker').colorpicker();

        $('#time_start').bootstrapMaterialDatePicker({

                date:false,
                shortTime: false,
                format: 'HH:mm:ss'
        });

    $('#date_end').bootstrapMaterialDatePicker({

        date:true,
        shortTime: false,
        format: 'YYYY-MM-DD'
    });
</code>```

One thing to note is that I had to create the table through phpmyadmin ,I was not able to migrate table from my code .

Also I have tried to change YYYY-MM-DD to Y-m-d H:i:s

This is my migration class:

```<code>class CreateEvent3sTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('event3s', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->datetime('start');
            $table->datetime('end');
            $table->string('color', 7);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('event3s');
    }
}
</code>```

This is my controller where the saving process is meant to happen:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Event3;
class EventsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Event3::get(['title','start','end','color']);

       return Response()->json($data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       $event = new Event3();
       $event->title = $request->title;
       $event->start = $request->date_start .''. $request->time_start;
       $event->end = $request->data_end;
       $event->color = $request->color;
        $event->save();

        return redirect('/');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
</code>```

答:
The problem lies within your store() method:

```<code>$event->start = $request->date_start .''. $request->time_start;
</code>```

As you can see there is no whitespace in between the date_start and time_start. Simply change it to

```<code>$event->start = $request->date_start .' '. $request->time_start;
</code>```

There is also an issue with the date_end. Change this line:

```<code>$event->end = $request->data_end;
</code>```

to

```<code>$event->end = $request->date_end;
</code>```

And it should enter into your database without an error!

Body:
I'm implementing full calendar API into my project .I have a problem when I try to save an event , I keep on getting the following error:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2017-07-1415:41:03' for column 'start' at row 1 (SQL: insert into `event3s` (`title`, `start`, `end`, `color`) values (New event, 2017-07-1415:41:03, , #9e1515))

I have changed to the right time(time zone) in phpmyadmin but I still got the same error.

This is my table in phpmyadmin :
[![enter image description here][1]][1]

This is the calendar.blade.php class :

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>Full Calendar</title>

    {!! Html::style('vendor2/seguce92/bootstrap/css/bootstrap.min.css') !!}
    {!! Html::style('vendor2/seguce92/fullcalendar/fullcalendar.min.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-datetimepicker/css/bootstrap-material-datetimepicker.css') !!}
    {!! Html::style('vendor2/seguce92/bootstrap-colorpicker/css/bootstrap-colorpicker.min.css') !!}

{{ Form::open(['route' => 'user.events.store', 'method' => 'post', 'role' => 'form']) }}

Registration of new Event

                {{Form::label('title','Date Start') }}
                {{Form::text('title',old('title'),['class' => 'form-control'])}}

            {{Form::label('date_start','Date Start') }}
            {{Form::text('date_start',old('date_start'),['class' => 'form-control','readonly'=>'true'])}}

                {{Form::label('time_start','Time Start') }}
                {{Form::text('time_start',old('time_start'),['class' => 'form-control'])}}

                {{Form::label('date_end','Time Finish') }}
                {{Form::text('date_end',old('date_end'),['class' => 'form-control'])}}

                {{Form::label('color','COLOR') }}

                    {{ Form::text('color',old('color'),['class' => 'form-control']) }}

            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            {!! Form::submit('Save',['class' => 'btn-btn-success'])!!}

{{Form::close()}}

{!! Html::script('vendor2/seguce92/jquery.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap/js/bootstrap.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/lib/moment.min.js') !!}
{!! Html::script('vendor2/seguce92/fullcalendar/fullcalendar.min.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-datetimepicker/js/bootstrap-material-datetimepicker.js') !!}
{!! Html::script('vendor2/seguce92/bootstrap-colorpicker/js/bootstrap-colorpicker.min.js') !!}

Body:
The problem lies within your store() method:

$event->start = $request->date_start .''. $request->time_start;

As you can see there is no whitespace in between the date_start and time_start. Simply change it to

$event->start = $request->date_start .' '. $request->time_start;

There is also an issue with the date_end. Change this line:

$event->end = $request->data_end;

to

$event->end = $request->date_end;

And it should enter into your database without an error!


问:
Woocommerce cart notice showing multiple times
I have a function that's working properly except for it displays the notice twice in the cart instead of once. The function applies a discount and also shows a notice.  The function looks for items of a particular category adds the total and if it meets the discount amount it applies the discount and shows a notice. Right now, even if there's only one item in the cart, it's showing the notice twice.

I've tried adding wc_clear_notices() but that will clear other notices I need like min max notices for minimum order amounts on categories. If I add in wc_clear_notices() at the beginning of the function or in any of the foreach statements it will clear the other min/max notice before it even shows.

Here are some questions I've already looked at but just say to use wc_clear_notices() which isn't working because other notices get cleared:

WooCommerce Notice, run only once

Show wc_add_notice only one time

Here's the code I currently have that correctly discounts items and displays notices but displays the notices twice instead of once:

```<code>//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'cart_count_foil_seal_items',10,1);

function cart_count_foil_seal_items( $cart_object ) {
$seal_prod_tally = 0;
$foil_prod_tally = 0;
// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {
    //  Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //tally total
    if (in_array('seal-stickers', $prod_cat)){
        $seal_prod_tally += $item_qty;
    }else if(in_array('foil-badges', $prod_cat)){
        $foil_prod_tally += $item_qty;
    }
}

 foreach ( $cart_object->get_cart() as $item_values ) {

    //Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat2 = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //apply discount to each item within category

      if (in_array('seal-stickers',$prod_cat2)){

        switch ($seal_prod_tally){
            case 20000:
                $item_values['data']->set_price(1327.01/20000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 20,000 at $1327.01.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 30000:
                $item_values['data']->set_price(1578.65/30000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 30,000 at $1578.65.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 40000:
                $item_values['data']->set_price(1853.05/40000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 40,000 at $1853.05.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 50000:
                $item_values['data']->set_price(2126.76/50000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 50,000 at $2126.76.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 60000:
                $item_values['data']->set_price(2405.98/60000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 60,000 at $2405.98.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            default:
                break;
        }
    }else if (in_array( 'foil-badges',$prod_cat2)){
        switch ($foil_prod_tally){
            case 25000:
                $item_values['data']->set_price(5872.63/25000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 25,000 at $5872.63.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 50000:
                $item_values['data']->set_price(10815.47/50000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 50,000 at $10815.47.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            default:
                break;
        }
    }
 }

}
</code>```

答:
The multiple notices were caused when the customer updated the cart with the Update Cart button so a quick fix was simply clearing notices every time the customer clicked the Update Cart button.

It would be better to solve the problem at its source which would be finding a different way to display notices without duplication but until then this gets the desired effect.

```<code>//clear notices on cart update
function clear_notices_on_cart_update() {
    wc_clear_notices();
};

// add the filter
add_filter( 'woocommerce_update_cart_action_cart_updated', 'clear_notices_on_cart_update', 10, 1 );
</code>```

Body:
I have a function that's working properly except for it displays the notice twice in the cart instead of once. The function applies a discount and also shows a notice.  The function looks for items of a particular category adds the total and if it meets the discount amount it applies the discount and shows a notice. Right now, even if there's only one item in the cart, it's showing the notice twice.

I've tried adding wc_clear_notices() but that will clear other notices I need like min max notices for minimum order amounts on categories. If I add in wc_clear_notices() at the beginning of the function or in any of the foreach statements it will clear the other min/max notice before it even shows.

Here are some questions I've already looked at but just say to use wc_clear_notices() which isn't working because other notices get cleared:

WooCommerce Notice, run only once

Show wc_add_notice only one time

Here's the code I currently have that correctly discounts items and displays notices but displays the notices twice instead of once:

//apply discounts to foil and seal product categories
add_action( 'woocommerce_before_calculate_totals', 'cart_count_foil_seal_items',10,1);

function cart_count_foil_seal_items( $cart_object ) {
$seal_prod_tally = 0;
$foil_prod_tally = 0;
// Iterating through each item in cart
foreach ( $cart_object->get_cart() as $item_values ) {
    //  Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //tally total
    if (in_array('seal-stickers', $prod_cat)){
        $seal_prod_tally += $item_qty;
    }else if(in_array('foil-badges', $prod_cat)){
        $foil_prod_tally += $item_qty;
    }
}

 foreach ( $cart_object->get_cart() as $item_values ) {

    //Get cart item data
    $item_id = $item_values['data']->get_id(); // Product ID
    $item_qty = $item_values['quantity']; // Item quantity

    // Getting the object
    $product = new WC_Product( $item_id );
    $prod_cat2 = wp_get_post_terms($product->get_id(),'product_cat',array('fields'=>'slugs'));

    //apply discount to each item within category

      if (in_array('seal-stickers',$prod_cat2)){

        switch ($seal_prod_tally){
            case 20000:
                $item_values['data']->set_price(1327.01/20000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 20,000 at $1327.01.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 30000:
                $item_values['data']->set_price(1578.65/30000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 30,000 at $1578.65.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 40000:
                $item_values['data']->set_price(1853.05/40000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 40,000 at $1853.05.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 50000:
                $item_values['data']->set_price(2126.76/50000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 50,000 at $2126.76.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 60000:
                $item_values['data']->set_price(2405.98/60000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 60,000 at $2405.98.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            default:
                break;
        }
    }else if (in_array( 'foil-badges',$prod_cat2)){
        switch ($foil_prod_tally){
            case 25000:
                $item_values['data']->set_price(5872.63/25000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 25,000 at $5872.63.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            case 50000:
                $item_values['data']->set_price(10815.47/50000);
                if(!is_checkout()){
                    wc_add_notice(
                            sprintf( 'Quantity discount has been applied to item %s: 50,000 at $10815.47.', $item_values['data']->get_title()
                            ), 'notice'
                    );
                }
                break;
            default:
                break;
        }
    }
 }

}

Body:
The multiple notices were caused when the customer updated the cart with the Update Cart button so a quick fix was simply clearing notices every time the customer clicked the Update Cart button.

It would be better to solve the problem at its source which would be finding a different way to display notices without duplication but until then this gets the desired effect.

//clear notices on cart update
function clear_notices_on_cart_update() {
    wc_clear_notices();
};

// add the filter
add_filter( 'woocommerce_update_cart_action_cart_updated', 'clear_notices_on_cart_update', 10, 1 );


问:
activity crash with YouTubePlayerView when app is minimize
I have integrated YouTubePlayerView library into our app and its working perfectly but whenever I minimize the app it crashes or you can say whenever the app goes in the background it crashes.

Here is the crash log:

```<code>    java.lang.NoClassDefFoundError: rt
        at rs.<clinit>(SourceFile:17)
        at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
        at android.view.View.dispatchSaveInstanceState(View.java:12985)
        at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2643)
        at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.View.saveHierarchyState(View.java:12968)
        at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1705)
        at android.app.Activity.onSaveInstanceState(Activity.java:1277)
        at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
        at android.app.Activity.performSaveInstanceState(Activity.java:1226)
        at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3342)
        at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3401)
        at android.app.ActivityThread.access$1100(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1320)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:149)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(Native Method)
07-03 13:02:44.608 31106-31174/com.seeken D/FA: Logging event (FE): _ae, Bundle[{_o=crash, timestamp=1499067164609, fatal=1}]
07-03 13:02:44.808 31106-31106/com.seeken I/dalvikvm: Could not find method java.util.Locale.toLanguageTag, referenced from method bme.a
07-03 13:02:44.808 31106-31106/com.seeken W/dalvikvm: VFY: unable to resolve virtual method 10275: Ljava/util/Locale;.toLanguageTag ()Ljava/lang/String;
07-03 13:02:44.808 31106-31106/com.seeken D/dalvikvm: VFY: replacing opcode 0x6e at 0x00e4
07-03 13:02:44.848 31106-31106/com.seeken D/dalvikvm: GC_FOR_ALLOC freed 3454K, 15% free 20646K/24152K, paused 25ms, total 25ms
07-03 13:02:44.868 31106-31106/com.seeken E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.seeken, PID: 31106
java.lang.NoClassDefFoundError: rt
    at rs.<clinit>(SourceFile:17)
    at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
    at android.view.View.dispatchSaveInstanceState(View.java:12985)
    at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2643)
    at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.View.saveHierarchyState(View.java:12968)
    at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1705)
    at android.app.Activity.onSaveInstanceState(Activity.java:1277)
    at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
    at android.app.Activity.performSaveInstanceState(Activity.java:1226)
    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
    at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3342)
    at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3401)
    at android.app.ActivityThread.access$1100(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1320)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)
</code>```

Here is my manifest:

```<code><activity android:name=".activities.VideoActivity"
            android:configChanges="orientation|screenLayout|screenSize"/>
</code>```

答:
You may refer with this SO post that suggested some workaround which might help:

Release YouTubePlayer at onSavedInstanceState and onStop.

```<code>@Nullable
protected YouTubePlayer mUtPlayer;

@Override
public void onSaveInstanceState(Bundle outState) {
    /* release ut when home button pressed. */
    if (mUtPlayer != null) {
        mUtPlayer.release();
    }
    mUtPlayer = null;
    super.onSaveInstanceState(outState);
}

@Override
public void onStop() {
    /* release ut when go to other fragment or back pressed */
    if (mUtPlayer != null) {
        mUtPlayer.release();
    }
    mUtPlayer = null;
    super.onStop();
}
</code>```

If it doesn't work, just add the same lines in onPause instead of in onSaveInstanceState and onStop, and initialize the YouTubePlayerFragment in onResume instead of in onCreate so it'll be available every time the activity is in foreground and released when the app goes to the background.

Additional reference:

NoClassDefFoundError Crash on Minimizing Youtube Player on Android 4.0, 4.2, 4.4

Body:
I have integrated YouTubePlayerView library into our app and its working perfectly but whenever I minimize the app it crashes or you can say whenever the app goes in the background it crashes.

Here is the crash log:

    java.lang.NoClassDefFoundError: rt
        at rs.<clinit>(SourceFile:17)
        at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
        at android.view.View.dispatchSaveInstanceState(View.java:12985)
        at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2643)
        at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
        at android.view.View.saveHierarchyState(View.java:12968)
        at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1705)
        at android.app.Activity.onSaveInstanceState(Activity.java:1277)
        at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
        at android.app.Activity.performSaveInstanceState(Activity.java:1226)
        at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3342)
        at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3401)
        at android.app.ActivityThread.access$1100(ActivityThread.java:139)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1320)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:149)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(Native Method)
07-03 13:02:44.608 31106-31174/com.seeken D/FA: Logging event (FE): _ae, Bundle[{_o=crash, timestamp=1499067164609, fatal=1}]
07-03 13:02:44.808 31106-31106/com.seeken I/dalvikvm: Could not find method java.util.Locale.toLanguageTag, referenced from method bme.a
07-03 13:02:44.808 31106-31106/com.seeken W/dalvikvm: VFY: unable to resolve virtual method 10275: Ljava/util/Locale;.toLanguageTag ()Ljava/lang/String;
07-03 13:02:44.808 31106-31106/com.seeken D/dalvikvm: VFY: replacing opcode 0x6e at 0x00e4
07-03 13:02:44.848 31106-31106/com.seeken D/dalvikvm: GC_FOR_ALLOC freed 3454K, 15% free 20646K/24152K, paused 25ms, total 25ms
07-03 13:02:44.868 31106-31106/com.seeken E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.seeken, PID: 31106
java.lang.NoClassDefFoundError: rt
    at rs.<clinit>(SourceFile:17)
    at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
    at android.view.View.dispatchSaveInstanceState(View.java:12985)
    at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2643)
    at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2629)
    at android.view.View.saveHierarchyState(View.java:12968)
    at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1705)
    at android.app.Activity.onSaveInstanceState(Activity.java:1277)
    at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
    at android.app.Activity.performSaveInstanceState(Activity.java:1226)
    at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1223)
    at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3342)
    at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3401)
    at android.app.ActivityThread.access$1100(ActivityThread.java:139)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1320)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)

Here is my manifest:

<activity android:name=".activities.VideoActivity"
            android:configChanges="orientation|screenLayout|screenSize"/>

Body:
You may refer with this SO post that suggested some workaround which might help:

Release YouTubePlayer at onSavedInstanceState and onStop.

@Nullable
protected YouTubePlayer mUtPlayer;

@Override
public void onSaveInstanceState(Bundle outState) {
    /* release ut when home button pressed. */
    if (mUtPlayer != null) {
        mUtPlayer.release();
    }
    mUtPlayer = null;
    super.onSaveInstanceState(outState);
}

@Override
public void onStop() {
    /* release ut when go to other fragment or back pressed */
    if (mUtPlayer != null) {
        mUtPlayer.release();
    }
    mUtPlayer = null;
    super.onStop();
}

If it doesn't work, just add the same lines in onPause instead of in onSaveInstanceState and onStop, and initialize the YouTubePlayerFragment in onResume instead of in onCreate so it'll be available every time the activity is in foreground and released when the app goes to the background.

Additional reference:

NoClassDefFoundError Crash on Minimizing Youtube Player on Android 4.0, 4.2, 4.4


问:
How to remove rows from a data frame when a % of columns have a value less than specified?
I have some data that I want to filter. I want to be able to say, "If a specified percentage of each row contains a value less than indicated, remove that row from the data frame.

Here is some sample data.

```<code>       Sample1, Sample2, Sample3, Sample4, Sample5, Sample6
Item1   0   0   0   0   0   0
Item2   478 440 522 578 1066 1045
Item3   16  14  9   6   6   20
</code>```

Let's say I want rows with 50% of columns with a value of less than 10 to be removed.  So in that scenario Item1 row is removed, and Item3 row is removed.

If I change the criteria to be 50% of columns with a value of less than 7, then only Item1 goes, and Item2 and Item3 remain.

What's a neat way to accomplish this in R?  This is a simple issue and I want to avoid writing messy code to accomplish it.  From what I've read so far I should be doing this with lapply() maybe?  I appreciate any insight.

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

dat <- fread("Item Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
              Item1   0   0   0   0   0   0
              Item2   478 440 522 578 1066 1045
              Item3   16  14  9   6   6   20")

slice_val <- 10
dat[apply(dat[, !"Item"], 1, function(x) sum(x > slice_val)/length(x)) > 0.5]

    Item Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
1: Item2     478     440     522     578    1066    1045

slice_val <- 7
dat[apply(dat[, !"Item"], 1, function(x) sum(x > slice_val)/length(x)) > 0.5]

    Item Sample1 Sample2 Sample3 Sample4 Sample5 Sample6
1: Item2     478     440     522     578    1066    1045
2: Item3      16      14       9       6       6      20
</code>```

Body:
I have some data that I want to filter. I want to be able to say, "If a specified percentage of each row contains a value less than indicated, remove that row from the data frame.

Here is some sample data.

       Sample1, Sample2, Sample3, Sample4, Sample5, Sample6
Item1   0   0   0   0   0   0
Item2   478 440 522 578 1066 1045
Item3   16  14  9   6   6   20

Let's say I want rows with 50% of columns with a value of less than 10 to be removed.  So in that scenario Item1 row is removed, and Item3 row is removed.

If I change the criteria to be 50% of columns with a value of less than 7, then only Item1 goes, and Item2 and Item3 remain.

What's a neat way to accomplish this in R?  This is a simple issue and I want to avoid writing messy code to accomplish it.  From what I've read so far I should be doing this with lapply() maybe?  I appreciate any insight.


问:
Call a function on elements with specific css class angular2 equivalent of jquery
so I have two components which are a Parent and a Child Component. The Parent Component references the child component with this below code and also has this constructor.

```<code>@ViewChild('nouislider') nouislider: any;

constructor(private util: UtilService, private elementRef: ElementRef) {
}

ngAfterViewInit() {
    console.log(this.nouislider.el);
    this.nouislider.slider.on('start', function(){
        console.log("hello");
    });
}
</code>```

So my question is: how can I do the equivalent of the following jquery code using only angular2? Basically, using angular to select a class and call a function on elements with that class?

```<code>$('#slider-tooltip').noUiSlider_pips({
    mode: 'values',
    values: [500000,1000000,3000000,5000000,10000000],
    density: 4
});

$('.noUi-value.noUi-value-horizontal.noUi-value-large').each(function(){
    var val = $(this).html();
    val = recountVal(parseInt(val));
    $(this).html(val);
});

function recountVal(val){
    switch(val){
        case 500000: return '< $500 K'; break;
        case 1000000:return '$1 M';break;
        case 3000000:return '$3 M';break;
        case 5000000:return '$5 M';break;
        default :return '$10 M';break;
    }
}
</code>```

Here is the nouislider component

```<code><div class="container">
<div class="row">
    <div class="col-md-8">
        <nouislider #nouislider [step]="step" [format]="format" [tooltips]="[ true , true ]" [connect]="true" [min]="minValue" [max]="maxValue" [(ngModel)]="someRange" (change)="onSlide()"></nouislider>
        <div class="alert alert-danger" *ngIf="ninetyDaysError">Dates must be within 90 days of each other.</div>
    </div>
    <div class="col-md-4">
        <h4><div class="label label-primary">{{days}}</div></h4>
    </div>
</div>
</code>```

答:
So the nouislider variable is of type NouisliderComponent.  This means that you can call any methods on that component that you wish.

Additionally, you can pass in a formatter of type NouiFormatter which implements the following methods: to(value: number): string; from(value: string): number;

So you can make a custom formatter which you pass to your component via [format]="myCustomFormatter".  Your format would take in 500000 and return '< $500 K' and so on for your specific values.

Body:
so I have two components which are a Parent and a Child Component. The Parent Component references the child component with this below code and also has this constructor.

@ViewChild('nouislider') nouislider: any;

constructor(private util: UtilService, private elementRef: ElementRef) {
}

ngAfterViewInit() {
    console.log(this.nouislider.el);
    this.nouislider.slider.on('start', function(){
        console.log("hello");
    });
}

So my question is: how can I do the equivalent of the following jquery code using only angular2? Basically, using angular to select a class and call a function on elements with that class?

$('#slider-tooltip').noUiSlider_pips({
    mode: 'values',
    values: [500000,1000000,3000000,5000000,10000000],
    density: 4
});

$('.noUi-value.noUi-value-horizontal.noUi-value-large').each(function(){
    var val = $(this).html();
    val = recountVal(parseInt(val));
    $(this).html(val);
});

function recountVal(val){
    switch(val){
        case 500000: return '< $500 K'; break;
        case 1000000:return '$1 M';break;
        case 3000000:return '$3 M';break;
        case 5000000:return '$5 M';break;
        default :return '$10 M';break;
    }
}

Here is the nouislider component

        <nouislider #nouislider [step]="step" [format]="format" [tooltips]="[ true , true ]" [connect]="true" [min]="minValue" [max]="maxValue" [(ngModel)]="someRange" (change)="onSlide()"></nouislider>

Dates must be within 90 days of each other.

{{days}}


问:
OpenSTF API POST remoteConnect
OpenSTf has API POST /api/v1/user/devices/{serial}/remoteConnect

I need with Apache http POST send request and pass serial.

```<code>      HttpPost request = new HttpPost("/api/v1/user/devices/"+ serial +"/remoteConnect");
HttpPost request1 = new HttpPost("/api/v1/user/devices/remoteConnect");

 request.setConfig(config);

                ArrayList<BasicNameValuePair> postParameters = new ArrayList<>();
                postParameters.add(new BasicNameValuePair("serial", serial));

                request.setEntity(new UrlEncodedFormEntity(postParameters));
</code>```

request  and request1 does not work, I do not understand how to write
API URL in new HttpPost ?

答:
I don't see you sending the access token? Might be the reason why your requests are failing. The access token can be created in the setting section in OpenSTF.

Another issue that might be causing the request to fail is that you don't set the device to a user first.

Note this is my solution and I'm using RestAssured Library to do the POST request.

```<code> String AccessToken = "Bearer e334457w44423e2342b6e5b8e5e0e723423488487b5cfe3";
 String BaseUrl = "http://myopenstfapiurl.com/api/v1";
 String deviceserial = "0123456789ABCDEF";

public void SetADeviceToUser() {
    RestAssured.baseURI = BaseUrl;
    RestAssured.given().contentType(ContentType.JSON).header("Authorization", AccessToken)
        .body("{\"serial\": \"" + deviceserial + "\",\"timeout\": 0}").post("/user/devices")
        .asString();
  }

  public String GetRemoteUrlForDevice() {
    RestAssured.baseURI = BaseUrl;
    String response = RestAssured.given().contentType(ContentType.JSON)
        .header("Authorization", AccessToken)
        .post("/user/devices/" + deviceserial + "/remoteConnect").asString();

    System.out.println(response);
    //Return the remoteConnectURL which will be used to connect to the device.
    return JsonPath.parse(response).read("$.remoteConnectUrl");
  }
</code>```

Title: OpenSTF API POST remoteConnect

Body:
OpenSTf has API POST /api/v1/user/devices/{serial}/remoteConnect

I need with Apache http POST send request and pass serial.

      HttpPost request = new HttpPost("/api/v1/user/devices/"+ serial +"/remoteConnect");
HttpPost request1 = new HttpPost("/api/v1/user/devices/remoteConnect");

 request.setConfig(config);

                ArrayList<BasicNameValuePair> postParameters = new ArrayList<>();
                postParameters.add(new BasicNameValuePair("serial", serial));

                request.setEntity(new UrlEncodedFormEntity(postParameters));

request  and request1 does not work, I do not understand how to write
API URL in new HttpPost ?

Body:
I don't see you sending the access token? Might be the reason why your requests are failing. The access token can be created in the setting section in OpenSTF.

Another issue that might be causing the request to fail is that you don't set the device to a user first.

Note this is my solution and I'm using RestAssured Library to do the POST request.

 String AccessToken = "Bearer e334457w44423e2342b6e5b8e5e0e723423488487b5cfe3";
 String BaseUrl = "http://myopenstfapiurl.com/api/v1";
 String deviceserial = "0123456789ABCDEF";

public void SetADeviceToUser() {
    RestAssured.baseURI = BaseUrl;
    RestAssured.given().contentType(ContentType.JSON).header("Authorization", AccessToken)
        .body("{\"serial\": \"" + deviceserial + "\",\"timeout\": 0}").post("/user/devices")
        .asString();
  }

  public String GetRemoteUrlForDevice() {
    RestAssured.baseURI = BaseUrl;
    String response = RestAssured.given().contentType(ContentType.JSON)
        .header("Authorization", AccessToken)
        .post("/user/devices/" + deviceserial + "/remoteConnect").asString();

    System.out.println(response);
    //Return the remoteConnectURL which will be used to connect to the device.
    return JsonPath.parse(response).read("$.remoteConnectUrl");
  }


问:
Django error while creating superuser, AttributeError: 'Manager' object has no attribute 'get_by_natural_key'
I am using Django version 1.11.3 and djangorestframework version 3.6.3. At the stage of creating the superuser with the following command:

```<code>python manage.py createsuperuser
</code>```

This command was supposed to ask me about my Email and Password, though it does ask me the Email but after entering my Email, I got an error:

```<code>Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 121, in handle
    self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'
</code>```

My models.py is this:

```<code>from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager

class UserProfileManager(object):
    """helps django work with our custom user model"""
    def create_user(self,email,name,password=None):
        if not email:
            raise ValueError('User must have email')
        email = self.normalize_email(email)
        user = self.model(email=email, name=name)

        user.set_password(password)
        user.save(using=self._db)

        return user
    def create_superuser(self,email,name,password):
        """creates and saves a new superuser with given details"""
        user = self.create_user(email,name,password)
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)

class UserProfile(AbstractBaseUser, PermissionsMixin):

    """docstring for UserProfile"""
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserProfileManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        """used to get a user full name"""
        return self.name

    def get_short_name():
        """used to get a users short name"""
        return self.name

    def __str__(self):
        """Django uses this when it needs to convert the object into string"""
        return self.email
</code>```

And I also updated the Application Definition in settings.py:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'profiles_api',
]
AUTH_USER_MODEL = 'profiles_api.UserProfile'
</code>```

I have tried to do this with both python2 and python3 but the error is same.

答:
UserProfileManager should be inherited from BaseUserManager class, not from object:

```<code>class UserProfileManager(BaseUserManager):
...
</code>```

You can find example of implementation custom user model here

Body:
I am using Django version 1.11.3 and djangorestframework version 3.6.3. At the stage of creating the superuser with the following command:

python manage.py createsuperuser

This command was supposed to ask me about my Email and Password, though it does ask me the Email but after entering my Email, I got an error:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute
    return super(Command, self).execute(*args, **options)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/shivams334/myapp2/lib/python3.5/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 121, in handle
    self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'

My models.py is this:

from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager

class UserProfileManager(object):
    """helps django work with our custom user model"""
    def create_user(self,email,name,password=None):
        if not email:
            raise ValueError('User must have email')
        email = self.normalize_email(email)
        user = self.model(email=email, name=name)

        user.set_password(password)
        user.save(using=self._db)

        return user
    def create_superuser(self,email,name,password):
        """creates and saves a new superuser with given details"""
        user = self.create_user(email,name,password)
        user.is_superuser = True
        user.is_staff = True
        user.save(using=self._db)

class UserProfile(AbstractBaseUser, PermissionsMixin):

    """docstring for UserProfile"""
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserProfileManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        """used to get a user full name"""
        return self.name

    def get_short_name():
        """used to get a users short name"""
        return self.name

    def __str__(self):
        """Django uses this when it needs to convert the object into string"""
        return self.email

And I also updated the Application Definition in settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'profiles_api',
]
AUTH_USER_MODEL = 'profiles_api.UserProfile'

I have tried to do this with both python2 and python3 but the error is same.

Body:
UserProfileManager should be inherited from BaseUserManager class, not from object:

class UserProfileManager(BaseUserManager):
...

You can find example of implementation custom user model here


问:
Android get TabView from TabLayout after using setupWithViewPager
I am lazy so I use this instead of creating different TabView

```<code>    v = new myTabContent(c);//my custom viewpager
    t = new TabLayout(c);
    t.setupWithViewPager(v);
</code>```

I wonder if there is any ways to get all the TabView from the TabLayout, because I want to set longclicklistener to each TabView.

答:
```<code>            TabLayout.Tab tab =  tabLayout.newTab();

            LinearLayout linearLayout = (LinearLayout) LayoutInflater.from(TagsManagerActivity.this).inflate(R.layout.item_tab, null);
            ((TextView)linearLayout.findViewById(R.id.text1)).setText(tagsManagerTab.getTagNameRes());
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                ((ImageView)linearLayout.findViewById(R.id.icon)).setImageDrawable(getResources().getDrawable(tagsManagerTab.getIconRes(),TagsManagerActivity.this.getTheme()));
            else
                ((ImageView)linearLayout.findViewById(R.id.icon)).setImageDrawable(getResources().getDrawable(tagsManagerTab.getIconRes()));

            tab.setCustomView(linearLayout);
            tabLayout.addTab(tab);
</code>```

Body:
I am lazy so I use this instead of creating different TabView

    v = new myTabContent(c);//my custom viewpager
    t = new TabLayout(c);
    t.setupWithViewPager(v);

I wonder if there is any ways to get all the TabView from the TabLayout, because I want to set longclicklistener to each TabView.


问:
How to bind a click event to the document so that it fires only when no object is clicked
I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked.

Right now I have:

```<code>$( document ).click( function() { /*do whatev*/ } );
</code>```

and in another place:

```<code>$( "img" ).click( function( e ) {
  e.stopPropagation();
  /*do whatev*/
} );
</code>```

it does not work. both events are fired. any other ideas?

答:
If you want an event to fire when the html and/or body is clicked or an img is clicked something like this should work: Live Example

```<code>$(document).click(function(e) {
  if($(e.target).is('html')){
    alert('this is the html element');
  }else if($(e.target).is('body')){
    alert('this is the body element');
  }
});
$("img").click(function(e) {
    e.stopPropagation();
    alert('img')
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would like an event to fire whenever something other than a DOM element is clicked, and a separate event when an image is clicked.

Right now I have:

$( document ).click( function() { /*do whatev*/ } );

and in another place:

$( "img" ).click( function( e ) {
  e.stopPropagation();
  /*do whatev*/
} );

it does not work. both events are fired. any other ideas?

Body:
If you want an event to fire when the html and/or body is clicked or an img is clicked something like this should work: Live Example

$(document).click(function(e) {
  if($(e.target).is('html')){
    alert('this is the html element');
  }else if($(e.target).is('body')){
    alert('this is the body element');
  }
});
$("img").click(function(e) {
    e.stopPropagation();
    alert('img')
});


问:
How to take screenshot of game div in phaser
I am using this code now, but it returns a blank transparent image:

```<code>$(document).ready(function(){
    $("#t").click(function() {
        html2canvas(document.querySelector("#bracelet_maker"),
         { onrendered: function(canvas){
            src = canvas.toDataURL();
            window.open(src); } });
    });
});
</code>```

If I use game.canvas.toDataUrl(); it returns a black image.

This is how the game is started in #bracelet_maker div

```<code>var game = new Phaser.Game(width,height,Phaser.AUTO,"bracelte_canvas",{
    preload:preload,
    create:create,
    update:update  });
</code>```

答:
Using Phaser.AUTO will allow either Phaser.WEBGL or Phaser.CANVAS be used, depending upon what your browser supports.

If you switch over to Phaser.CANVAS when creating your new Phaser.Game you should be able to use access the canvas.

For example, within Phaser by binding off the S key:

```<code>function create() {
    // ...
    var screenshotKey = game.input.keyboard.addKey(Phaser.Keyboard.S);
    screenshotKey.onDown.add(function () { window.open(game.canvas.toDataURL());
}
</code>```

There's also preserveDrawingBuffer which should allow you capture from WebGL as well, but it needs to be set early on in the process.

```<code>var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
    preload: preload, create: create, update: update
});
game.preserveDrawingBuffer = true;
</code>```

Body:
I am using this code now, but it returns a blank transparent image:

$(document).ready(function(){
    $("#t").click(function() {
        html2canvas(document.querySelector("#bracelet_maker"),
         { onrendered: function(canvas){
            src = canvas.toDataURL();
            window.open(src); } });
    });
});

If I use game.canvas.toDataUrl(); it returns a black image.

This is how the game is started in #bracelet_maker div

var game = new Phaser.Game(width,height,Phaser.AUTO,"bracelte_canvas",{
    preload:preload,
    create:create,
    update:update  });

Body:
Using Phaser.AUTO will allow either Phaser.WEBGL or Phaser.CANVAS be used, depending upon what your browser supports.

If you switch over to Phaser.CANVAS when creating your new Phaser.Game you should be able to use access the canvas.

For example, within Phaser by binding off the S key:

function create() {
    // ...
    var screenshotKey = game.input.keyboard.addKey(Phaser.Keyboard.S);
    screenshotKey.onDown.add(function () { window.open(game.canvas.toDataURL());
}

There's also preserveDrawingBuffer which should allow you capture from WebGL as well, but it needs to be set early on in the process.

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
    preload: preload, create: create, update: update
});
game.preserveDrawingBuffer = true;


问:
How to pass an std::vector with custom allocator to a function that expects one with std::allocator?
I am working with an external library (pcl) so I need a solution that does not change the existing function prototypes.

One function that I am using generates an std::vector<int, Eigen::aligned_allocator<int>>. The function that I want to call next expects a const boost::shared_ptr<std::vector<int, std::allocator<int>>>. I do not want to copy the elements because it is in an already slow critical part of my code. If not for the allocator mismatch, I would get around the shared_ptr requirement by simply doing:

```<code>// code that generates std::vector<int, Eigen::aligned_allocator<int>> source
boost::shared_ptr<std::vector<int>> indices(new std::vector<int>);
indices->swap(source);
// use indices as intended
</code>```

This does not compile with the MSVC compiler because it cannot convert between these two vector types. The only solution I have thought of so far that does not copy the contents is:

```<code>// code that generates std::vector<int, Eigen::aligned_allocator<int>> source
boost::shared_ptr<std::vector<int>> indices(new std::vector<int>);
indices->swap(reinterpret_cast<std::vector<int>&>(source));
// use indices as intended
indices->swap(reinterpret_cast<std::vector<int>&>(pcout.points));
</code>```

Note how I need to use indices as as a const shared_ptr. I believe that the allocator will not play a role in the swap operation. The ints should also not need any padding to be aligned as they are already of size 32-bit. The std::allocator version should be able to read from the aligned version because it can only allocate in memory addresses that the std::allocator could have used anyway. Finally, I swap back because the aligned allocator might crash if it tries to delete a non-aligned reserved space.

I tried it and it didn't crash but that is not enought to convince me that it is actually correct. Is it safe? If not, is it conditionally safe if certain reasonable assumptions are made concerning the compiler? Is there a safer alternative that does not noticeably impact performance?

Please do not reply with "profile your code", "not worth it" or similar answers. Even if they are applicable here, there is theoretically a scenario where copying is not a viable solution, and this thread should address that.

Similar question is talking about copying the data in a clean way as was clarified in the comments.

EDIT: it seems that despite Eigen::aligned_allocator being designed for 16-bit alignment, no extra padding is added to the ints. Comparing the address of the first and last element on the list gives the size one would expect from the number of elements and the sizeof(int). This means that the ints are stored in a way that should be compatible with the std::allocator version. I hope I'll have time later today or in the coming days to make a more complete test.

答:
If you have the ability to change the function prototype to another vector type, then there is an entirely new namespace (namespace pmr) in the standard library that uses type erasure for allocators to ensure compatibility between containers that use different allocators.

For more see polymorphic_allocator: when and why should I use it?

With that change you can simply do

```<code>void foo(std::pmr::vector<int>& vec);
</code>```

and pass in a vector type with any allocator you want (as long as it is also a std::pmr::vector) you want.

If you are not able to change the type of vector the function expects than I don't think you can do much better than copying/moving the elements one by one.

reinterpret_casting two different vector instances to different types and then using methods on them is very dangerous.

Body:
I am working with an external library (pcl) so I need a solution that does not change the existing function prototypes.

One function that I am using generates an std::vector<int, Eigen::aligned_allocator<int>>. The function that I want to call next expects a const boost::shared_ptr<std::vector<int, std::allocator<int>>>. I do not want to copy the elements because it is in an already slow critical part of my code. If not for the allocator mismatch, I would get around the shared_ptr requirement by simply doing:

// code that generates std::vector<int, Eigen::aligned_allocator<int>> source
boost::shared_ptr<std::vector<int>> indices(new std::vector<int>);
indices->swap(source);
// use indices as intended

This does not compile with the MSVC compiler because it cannot convert between these two vector types. The only solution I have thought of so far that does not copy the contents is:

// code that generates std::vector<int, Eigen::aligned_allocator<int>> source
boost::shared_ptr<std::vector<int>> indices(new std::vector<int>);
indices->swap(reinterpret_cast<std::vector<int>&>(source));
// use indices as intended
indices->swap(reinterpret_cast<std::vector<int>&>(pcout.points));

Note how I need to use indices as as a const shared_ptr. I believe that the allocator will not play a role in the swap operation. The ints should also not need any padding to be aligned as they are already of size 32-bit. The std::allocator version should be able to read from the aligned version because it can only allocate in memory addresses that the std::allocator could have used anyway. Finally, I swap back because the aligned allocator might crash if it tries to delete a non-aligned reserved space.

I tried it and it didn't crash but that is not enought to convince me that it is actually correct. Is it safe? If not, is it conditionally safe if certain reasonable assumptions are made concerning the compiler? Is there a safer alternative that does not noticeably impact performance?

Please do not reply with "profile your code", "not worth it" or similar answers. Even if they are applicable here, there is theoretically a scenario where copying is not a viable solution, and this thread should address that.

Similar question is talking about copying the data in a clean way as was clarified in the comments.

EDIT: it seems that despite Eigen::aligned_allocator being designed for 16-bit alignment, no extra padding is added to the ints. Comparing the address of the first and last element on the list gives the size one would expect from the number of elements and the sizeof(int). This means that the ints are stored in a way that should be compatible with the std::allocator version. I hope I'll have time later today or in the coming days to make a more complete test.

Body:
If you have the ability to change the function prototype to another vector type, then there is an entirely new namespace (namespace pmr) in the standard library that uses type erasure for allocators to ensure compatibility between containers that use different allocators.

For more see polymorphic_allocator: when and why should I use it?

With that change you can simply do

void foo(std::pmr::vector<int>& vec);

and pass in a vector type with any allocator you want (as long as it is also a std::pmr::vector) you want.

If you are not able to change the type of vector the function expects than I don't think you can do much better than copying/moving the elements one by one.

reinterpret_casting two different vector instances to different types and then using methods on them is very dangerous.


问:
how to make the screen command console open after showing output mine is closing very fastly . but without using Console.ReadLine();
how to make the screen command console open after showing output
mine is closing very fastly .
but without using Console.ReadLine();</p>

答:
If you  don't want to use Console.ReadLine() for some reason, you can use Console.ReadKey() or perhaps Thread.Sleep(10000).
The screen stays for 10 seconds