问:
Javascript and CSS not loading into partial from asset manager
I have a partial "menu-2" in which there are clickable images that light up when they are clicked. I wrote a js script (first one ever woo) to add an "active" class onclick, and remove the class from all the other menu items. The problem I am facing is that the script only works if I embed it within

-->

    <video loop muted autoplay playsinline poster="{{ 'assets/images/vid-bg-placeholder.tif'|theme }}">
        <source src="{{ 'assets/vid/vid-bg-dark.mp4'|theme }}" type="video/mp4">
    </video>

   {% partial "homepage" %}

   {% partial "menu-2" %}

<script>
//check what type of animation depending on which menu item is chosen

//Particle js settings
particlesJS("particles-js",

 {
  "particles": {
    "number": {
      "value": 140,
      "density": {
        "enable": true,
        "value_area": 800
      }
    },
    "color": {
      "value": "#ffffff"
    },
    "shape": {
      "type": "circle",
      "stroke": {
        "width": 0,
        "color": "#000000"
      },
      "polygon": {
        "nb_sides": 5
      },
      "image": {
        "src": "img/github.svg",
        "width": 100,
        "height": 100
      }
    },
    "opacity": {
      "value": 0.2,
      "random": false,
      "anim": {
        "enable": false,
        "speed": 1,
        "opacity_min": 0.1,
        "sync": false
      }
    },
    "size": {
      "value": 3,
      "random": true,
      "anim": {
        "enable": false,
        "speed": 9.589796456570207,
        "size_min": 0.1,
        "sync": false
      }
    },
    "line_linked": {
      "enable": true,
      "distance": 142.0488174435947,
      "color": "#ffffff",
      "opacity": 0.4,
      "width": 1
    },
    "move": {
      "enable": true,
      "speed": .78,
      "direction": "none",
      "random": true,
      "straight": false,
      "out_mode": "out",
      "bounce": false,
      "attract": {
        "enable": true,
        "rotateX": 1815.0682228903763,
        "rotateY": 1200
      }
    }
  },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": true,
        "mode": "bubble"
      },
      "onclick": {
        "enable": true,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 400,
        "line_linked": {
          "opacity": 1
        }
      },
      "bubble": {
        "distance": 400,
        "size": 3.99574852357092,
        "duration": 0.7991497047141839,
        "opacity": 0.5114558110170777,
        "speed": 3
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      },
      "push": {
        "particles_nb": 4
      },
      "remove": {
        "particles_nb": 2
      }
    }
  },
  "retina_detect": true

});
</script>
```

<p><strong>menu-2.htm (partial)</strong></p>

```layout = "menu"
==
function onInit()
{
$this->addJs('assets/javascript/menu-selection.js');
}
==

```

<p><strong>default.htm</strong></p>

```<!doctype html>

    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="{{ this.page.meta_description }}">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="shortcut icon" type="image/png" href="{{ 'assets/favicon.png'|theme }}">

    <script src="{{ 'assets/javascript/jquery-2.1.0.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/bootstrap.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/blocs.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/particles.js'|theme }}"></script>

    <script src="{{ 'assets/javascript/pagetransitions.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/modernizr.custom.js'|theme }}"></script>

    <script src="{{ 'assets/javascript/menu-selection.js'|theme }}"></script>

    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/bootstrap.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/style.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/font-awesome.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/css.css'|theme }}">

    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/animations.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/component.css'|theme }}">

    <title>{{ this.page.title }}</title>

     {% page %}

    {% framework extra %}
    {% framework %}
    {% scripts %}
    {%styles%}

```

I'm not sure what the error might be. Any ideas?

答:
I fixed the problem. There were 2 main issues

1) I had the default layout set to "menu" layout instead of "default"

2) I had onInit() instead of onStart().

Below is the code I had wrong:

menu-2.htm (partial)

```<code>layout = "menu"
==
function onInit()
{
$this->addJs('assets/javascript/menu-selection.js');
}
==
</code>```

Here are the updated default.htm and menu-2.htm:

default.htm

```<code><!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="{{ this.page.meta_description }}">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="shortcut icon" type="image/png" href="{{ 'assets/favicon.png'|theme }}">

    <script src="{{ 'assets/javascript/jquery-2.1.0.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/bootstrap.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/blocs.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/particles.js'|theme }}"></script>
    <!--page transitions-->
    <script src="{{ 'assets/javascript/pagetransitions.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/modernizr.custom.js'|theme }}"></script>
    <!--menu selection-->
    <script src="{{ 'assets/javascript/menu-selection.js'|theme }}"></script>

    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/bootstrap.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/style.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/font-awesome.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/css.css'|theme }}">

    <!--page transitions-->
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/animations.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/component.css'|theme }}">

    {%styles%}

    <title>{{ this.page.title }}</title>

</head>
<body style="height:100vh;overflow:hidden!important">

<!-- Main container -->

     {% page %}

<!-- Main container END -->

{% framework extra %}
    {% framework %}
    {% scripts %}
</body>
</html>
</code>```

menu-2.htm

```<code>==
function onStart()
{
    $this->addCss('assets/css/menu.css');
    $this->addJs('assets/javascript/menuselection.js');
}
==
<div class="menu-2" onload="default_active()">

    <!--Home Icon-->
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="home-icon"  src="{{ 'assets/images/menu/home-3.png'| theme }}"/>
    </div>
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="my-story"  src="{{ 'assets/images/menu/story-2.png'| theme }}"/>
    </div>
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="soundcloud" src="{{ 'assets/images/menu/music-2.png'| theme }}"/>
    </div>
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="store"  src="{{ 'assets/images/menu/store-2.png'| theme }}"/>
    </div>

</div>
</code>```

Body:
I have a partial "menu-2" in which there are clickable images that light up when they are clicked. I wrote a js script (first one ever woo) to add an "active" class onclick, and remove the class from all the other menu items. The problem I am facing is that the script only works if I embed it within

-->

    <video loop muted autoplay playsinline poster="{{ 'assets/images/vid-bg-placeholder.tif'|theme }}">
        <source src="{{ 'assets/vid/vid-bg-dark.mp4'|theme }}" type="video/mp4">
    </video>

   {% partial "homepage" %}

   {% partial "menu-2" %}

menu-2.htm (partial)

layout = "menu"
==
function onInit()
{
$this->addJs('assets/javascript/menu-selection.js');
}
==

default.htm

<!doctype html>

    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="{{ this.page.meta_description }}">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="shortcut icon" type="image/png" href="{{ 'assets/favicon.png'|theme }}">

    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/bootstrap.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/style.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/font-awesome.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/css.css'|theme }}">

    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/animations.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/component.css'|theme }}">

    <title>{{ this.page.title }}</title>

     {% page %}

    {% framework extra %}
    {% framework %}
    {% scripts %}
    {%styles%}

I'm not sure what the error might be. Any ideas?

Body:
I fixed the problem. There were 2 main issues

1) I had the default layout set to "menu" layout instead of "default"

2) I had onInit() instead of onStart().

Below is the code I had wrong:

menu-2.htm (partial)

layout = "menu"
==
function onInit()
{
$this->addJs('assets/javascript/menu-selection.js');
}
==

Here are the updated default.htm and menu-2.htm:

default.htm

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="keywords" content="">
    <meta name="description" content="{{ this.page.meta_description }}">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
    <link rel="shortcut icon" type="image/png" href="{{ 'assets/favicon.png'|theme }}">

    <script src="{{ 'assets/javascript/jquery-2.1.0.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/bootstrap.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/blocs.min.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/particles.js'|theme }}"></script>
    <!--page transitions-->
    <script src="{{ 'assets/javascript/pagetransitions.js'|theme }}"></script>
    <script src="{{ 'assets/javascript/modernizr.custom.js'|theme }}"></script>
    <!--menu selection-->
    <script src="{{ 'assets/javascript/menu-selection.js'|theme }}"></script>

    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/bootstrap.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/style.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/font-awesome.min.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/css.css'|theme }}">

    <!--page transitions-->
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/animations.css'|theme }}">
    <link rel="stylesheet" type="text/css" href="{{ 'assets/css/pagetransitions/component.css'|theme }}">

    {%styles%}

    <title>{{ this.page.title }}</title>

</head>
<body style="height:100vh;overflow:hidden!important">

<!-- Main container -->

     {% page %}

<!-- Main container END -->

{% framework extra %}
    {% framework %}
    {% scripts %}
</body>
</html>

menu-2.htm

==
function onStart()
{
    $this->addCss('assets/css/menu.css');
    $this->addJs('assets/javascript/menuselection.js');
}
==
<div class="menu-2" onload="default_active()">

    <!--Home Icon-->
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="home-icon"  src="{{ 'assets/images/menu/home-3.png'| theme }}"/>
    </div>
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="my-story"  src="{{ 'assets/images/menu/story-2.png'| theme }}"/>
    </div>
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="soundcloud" src="{{ 'assets/images/menu/music-2.png'| theme }}"/>
    </div>
    <div class="row" >
        <img class="menu-item-2 shadowfilter" id="store"  src="{{ 'assets/images/menu/store-2.png'| theme }}"/>
    </div>

</div>


来源: stackexchange

问:
How can I identify the images with 'Possibly corrupt EXIF data'
I am working on a image classification Kaggle competition and download some training images from Kaggle.com. Then I am using transfer learning with ResNet50 to work on these images, within Keras 2.0 and Tensorflow as background (and Python 3).

However, 258 out the total 1281 train images are having 'Possibly corrupt EXIF data' and been ignored when loaded to the ResNet model, very likely due to a Pillow issue.

The output messages are like:

```<code>/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 524288 bytes but only got 0. Skipping tag 3
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 393216 bytes but only got 0. Skipping tag 3
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 33554432 bytes but only got 0. Skipping tag 4
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 25165824 bytes but only got 0. Skipping tag 4
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 131072 bytes but only got 0. Skipping tag 3
  "Skipping tag %s" % (size, len(data), tag))
(more to come ...)
</code>```

Based on the output messages, I only know they are there, but don't know which ones they are...

My question is: how can I identify these 258 images so that I can manually remove them out of the data set?

答: The easiest way that comes to mind is to modify your code to handle one image at a time, then iterate over each images and check which one generates the warning.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am working on a image classification Kaggle competition and download some training images from Kaggle.com. Then I am using transfer learning with ResNet50 to work on these images, within Keras 2.0 and Tensorflow as background (and Python 3).

However, 258 out the total 1281 train images are having 'Possibly corrupt EXIF data' and been ignored when loaded to the ResNet model, very likely due to a Pillow issue.

The output messages are like:

/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 524288 bytes but only got 0. Skipping tag 3
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 393216 bytes but only got 0. Skipping tag 3
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 33554432 bytes but only got 0. Skipping tag 4
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 25165824 bytes but only got 0. Skipping tag 4
  "Skipping tag %s" % (size, len(data), tag))
/home/shi/anaconda3/lib/python3.6/site-packages/PIL/TiffImagePlugin.py:692: UserWarning: Possibly corrupt EXIF data.  Expecting to read 131072 bytes but only got 0. Skipping tag 3
  "Skipping tag %s" % (size, len(data), tag))
(more to come ...)

Based on the output messages, I only know they are there, but don't know which ones they are...

My question is: how can I identify these 258 images so that I can manually remove them out of the data set?


问:
What is the best way to get up to speed on BizTalk?
How should an experienced .NET & SQL developer go about becoming a BizTalk expert for a project starting in 1 month? How should I spend my limited time to gain some practical skill & knowledge in BizTalk so I can "walk the talk"?

I am self employed, and would not be willing to spend more than USD300. I have the book "Professional BizTalk Server 2006" by Wrox, but have not found it to be a particularly good learning resource (very dry, needs more real world examples).

答: The BizTalk Virtual Labs in MSDN are a pretty good place to start with. Pluralsight also has several good BizTalk courses, and their online subscription isn't too expensive; would likely be a good option.</p>

ContentLicense: CC BY-SA 2.5


问:
If database autocommit mode is enabled, why should I care about transaction.on_commit()?
I've read that Django > 1.9 introduces transaction.on_commit in order to avoid race conditions. I know that Django sets database autocommit to true by default, so each query becomes a transaction at db level.

However, take this example,

```<code>from django.db import transaction

def some_view(request):
    obj = SomeModel.objects.create(field=value)
    transaction.on_commit(lambda: some_async_task(obj.pk))
</code>```

Why should I wrap some_async_task(obj.pk) inside transaction.on_commit? I'm not sure how transactions work behind the scenes. All this time I've been thinking that as autocommit is enabled, create or save method should be a transaction itself, and then, in the next statement that object should exist in database.

答:
Ok. I've found the issue. I actually haven't explained the whole thing. Autocommit mode works right. It commits instantly, except when there's an active transaction.

I've realized I only expirienced this in Django's admin. The add/change views are wrapped inside a transaction. SO, my code inside post_save signal was triggered inside and the admin's save transaction wasn't finished yet.

That's why it makes sense to use transaction.on_commit anyway (added in Django > 1.9), because in this case its argument function would be triggered after outer transaction ends.

I'm using Django 1.6.5 but this also happens in 1.11

Hope this helps someone else.

Body:
I've read that Django > 1.9 introduces transaction.on_commit in order to avoid race conditions. I know that Django sets database autocommit to true by default, so each query becomes a transaction at db level.

However, take this example,

from django.db import transaction

def some_view(request):
    obj = SomeModel.objects.create(field=value)
    transaction.on_commit(lambda: some_async_task(obj.pk))

Why should I wrap some_async_task(obj.pk) inside transaction.on_commit? I'm not sure how transactions work behind the scenes. All this time I've been thinking that as autocommit is enabled, create or save method should be a transaction itself, and then, in the next statement that object should exist in database.


问:
How to close ContentDialog on "Enter" in UWP
I've been trying to get a simple ContentDialog with a TextBox to close when the user hits Enter while still in the TextBox. Sadly it doesn't even work without a TextBox, even though the ContentDialog responds to Esc.

I was hoping there was a way to set a Result from inside the KeyDown Handler of the TextBox, but it seems ContentDialog lacks this?!

答:
The short answer is that it isn't (cleanly) possible without workarounds and hacks that will preserve the functionality of identifying which button was pressed. The long answer is that it's fortunately very clean and easy to subclass ContentDialog to do exactly what we want:

```<code>using System;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace NeoSmart.Dialogs
{
    class HotkeyContentDialog : ContentDialog
    {
        public new event TypedEventHandler<ContentDialog, ContentDialogButtonClickEventArgs> PrimaryButtonClick;
        public new event TypedEventHandler<ContentDialog, ContentDialogButtonClickEventArgs> SecondaryButtonClick;

        public ContentDialogResult Result { get; set; }
        public new async Task<ContentDialogResult> ShowAsync()
        {
            var baseResult = await base.ShowAsync();
            if (baseResult == ContentDialogResult.None)
            {
                return Result;
            }
            return baseResult;
        }

        protected override void OnKeyUp(KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                Result = ContentDialogResult.Primary;
                PrimaryButtonClick?.Invoke(this, default(ContentDialogButtonClickEventArgs));
                Hide();
            }
            else if (e.Key == Windows.System.VirtualKey.Escape)
            {
                Result = ContentDialogResult.Secondary;
                SecondaryButtonClick?.Invoke(this, default(ContentDialogButtonClickEventArgs));
                Hide();
            }
            else
            {
                base.OnKeyUp(e);
            }
        }
    }
}
</code>```

Just use HotkeyContentDialog instead of ContentDialog and all will be well.

Body:
The short answer is that it isn't (cleanly) possible without workarounds and hacks that will preserve the functionality of identifying which button was pressed. The long answer is that it's fortunately very clean and easy to subclass ContentDialog to do exactly what we want:

using System;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace NeoSmart.Dialogs
{
    class HotkeyContentDialog : ContentDialog
    {
        public new event TypedEventHandler<ContentDialog, ContentDialogButtonClickEventArgs> PrimaryButtonClick;
        public new event TypedEventHandler<ContentDialog, ContentDialogButtonClickEventArgs> SecondaryButtonClick;

        public ContentDialogResult Result { get; set; }
        public new async Task<ContentDialogResult> ShowAsync()
        {
            var baseResult = await base.ShowAsync();
            if (baseResult == ContentDialogResult.None)
            {
                return Result;
            }
            return baseResult;
        }

        protected override void OnKeyUp(KeyRoutedEventArgs e)
        {
            if (e.Key == Windows.System.VirtualKey.Enter)
            {
                Result = ContentDialogResult.Primary;
                PrimaryButtonClick?.Invoke(this, default(ContentDialogButtonClickEventArgs));
                Hide();
            }
            else if (e.Key == Windows.System.VirtualKey.Escape)
            {
                Result = ContentDialogResult.Secondary;
                SecondaryButtonClick?.Invoke(this, default(ContentDialogButtonClickEventArgs));
                Hide();
            }
            else
            {
                base.OnKeyUp(e);
            }
        }
    }
}

Just use HotkeyContentDialog instead of ContentDialog and all will be well.


问:
Does filter() work in-place in python?
If I call filter() on a list, say:

```<code>>>> filter(lambda x: x > 1, [1,2,3,4])
[2, 3, 4]
</code>```

Is this:

a) creating a totally new list in memory with the results

or

b) is it just pop()-ing items from the existing list and returning the same list?

答:
Python 2

In Python2, filter() returns a new list object. The list passed into the function is unaffected. This can be observed using a very simple example:

```<code>>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda element: element < 4, lst)
[1, 2, 3]
>>> lst # lst is unaffected
[1, 2, 3, 4, 5]
>>>
</code>```

Python 3

In Python3, filter() also does not affect the list passed in. However, it does not return a new list object. Rather, it returns a filter object:

```<code>>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda element: element < 4, lst)
<filter object at 0x7fb69fef1b00>
>>> lst
[1, 2, 3, 4, 5]
>>>
</code>```

If you want a list object, you need to explicitly cast the return value of filter() to a list:

```<code>>>> lst = [1, 2, 3, 4, 5]
>>> list(filter(lambda element: element < 4, lst))
[1, 2, 3]
>>>
</code>```

In both cases though, your first hypothesis is correct. filter() does not do its work in place, it returns a new object.

Title: Does filter() work in-place in python?

Body:
If I call filter() on a list, say:

>>> filter(lambda x: x > 1, [1,2,3,4])
[2, 3, 4]

Is this:

a) creating a totally new list in memory with the results

or

b) is it just pop()-ing items from the existing list and returning the same list?

Body:
Python 2

In Python2, filter() returns a new list object. The list passed into the function is unaffected. This can be observed using a very simple example:

>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda element: element < 4, lst)
[1, 2, 3]
>>> lst # lst is unaffected
[1, 2, 3, 4, 5]
>>>

Python 3

In Python3, filter() also does not affect the list passed in. However, it does not return a new list object. Rather, it returns a filter object:

>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda element: element < 4, lst)
<filter object at 0x7fb69fef1b00>
>>> lst
[1, 2, 3, 4, 5]
>>>

If you want a list object, you need to explicitly cast the return value of filter() to a list:

>>> lst = [1, 2, 3, 4, 5]
>>> list(filter(lambda element: element < 4, lst))
[1, 2, 3]
>>>

In both cases though, your first hypothesis is correct. filter() does not do its work in place, it returns a new object.


问:
Get String Between 2 Strings with Arduino
I am looking for a way to get a String between 2 Strings using Arduino. This is the source String:

```<code>Hello, my name is John Doe# and my favourite number is 32#.
</code>```

The output has to be:

```<code>String name = "John Doe"; //Between "name is " and "#"
String favouriteNumber = "32"; //Between "number is " and "#"
</code>```

How can this be achieved with Arduino?

I am not able to find any information online about this. Those examples for C are not working anyway. I understand that using String is not recommended in Arduino, but I have to do it this way to make things simpler.

By the way, this method of using a '#' to indicate the end of the data is not an ideal way to do it as I would like the input to be more human readable and more natural. Would anyone please suggest another way to do this as well?

Thanks in advance!

答:
just searched for this and saw no answer so i cooked one up.
i prefer working with String as well because of code readability and simplicity.
for me its more important than squeezing every last drop of juice out of my arduino.

```<code>String name = GetStringBetweenStrings("Hello, my name is John Doe# and my favourite number is 32#." ,"name is ","#");

String GetStringBetweenStrings(String input, String firstdel, String enddel){
      int posfrom = input.indexOf(firstdel) + firstdel.length();
      int posto   = input.indexOf(enddel);
      return input.substring(posfrom, posto);
}
</code>```

watch out for the first case its fine, but for the second one you would have to change the second filter sting to "#." so it doesn't use the first occurrence of the #

Body:
I am looking for a way to get a String between 2 Strings using Arduino. This is the source String:

Hello, my name is John Doe# and my favourite number is 32#.

The output has to be:

String name = "John Doe"; //Between "name is " and "#"
String favouriteNumber = "32"; //Between "number is " and "#"

How can this be achieved with Arduino?

I am not able to find any information online about this. Those examples for C are not working anyway. I understand that using String is not recommended in Arduino, but I have to do it this way to make things simpler.

By the way, this method of using a '#' to indicate the end of the data is not an ideal way to do it as I would like the input to be more human readable and more natural. Would anyone please suggest another way to do this as well?

Thanks in advance!

Body:
just searched for this and saw no answer so i cooked one up.
i prefer working with String as well because of code readability and simplicity.
for me its more important than squeezing every last drop of juice out of my arduino.

String name = GetStringBetweenStrings("Hello, my name is John Doe# and my favourite number is 32#." ,"name is ","#");

String GetStringBetweenStrings(String input, String firstdel, String enddel){
      int posfrom = input.indexOf(firstdel) + firstdel.length();
      int posto   = input.indexOf(enddel);
      return input.substring(posfrom, posto);
}

watch out for the first case its fine, but for the second one you would have to change the second filter sting to "#." so it doesn't use the first occurrence of the #


问:
MySql 5.7 json_extract by key
I have a table and it looks like below:

Table data

```<code>id params
1  {"company1X":{"price":"1124.55"},"company2X":{"price":"1,124.55"},"company3X":{"price":""},"company4X":{"price":""},"company5X":{"price":"1528.0"}}
</code>```

I don't know the name of "company" to use in my request.

How can I fetch my data ordered by price?
Thanks!

P.S I have tried select json_extract(params, '$[*].price') from data but it doesn't work (return nulls).

答:
$[*] gets all elements of a JSON array, not an object. This is an object, so you get NULL.

$.* will get you all elements in a JSON object, so $.*.price gets you a JSON array of all prices.

```<code>mysql> select json_extract(params, '$.*.price') from foo;
+-------------------------------------------+
| json_extract(params, '$.*.price')         |
+-------------------------------------------+
| ["1124.55", "1,124.55", "", "", "1528.0"] |
+-------------------------------------------+
</code>```

Now there's a problem. As far as SQL is concerned, this is a single row. It can't be sorted with a normal order by, that works on rows.

MySQL has no function for sorting JSON... so you're stuck. You can return the JSON array and let whatever is receiving the data do the sorting. You might be able to write a stored procedure to sort the array... but that's a lot of work to support a bad table design. Instead, change the table.

The real problem is this is a bad use of a JSON column.

JSON columns defeat most of the point of a SQL database (less so in PostgreSQL which has much better JSON support). SQL databases work with rows and columns, but JSON shoves what would be multiple rows and columns into a single cell.

For this reason, JSON columns should be used sparingly; typically when you're not sure what sort of data you'll be needing to store. Important information like "price" that's going to be searched and sorted should be done as normal columns.

You'll want to change your table to be a normal SQL table with columns for the company name and price. Then you can use normal SQL features like order by and performance will benefit from indexing. There isn't enough information in your question to suggest what that table might look like.

Title: MySql 5.7 json_extract by key

Body:
I have a table and it looks like below:

Table data

id params
1  {"company1X":{"price":"1124.55"},"company2X":{"price":"1,124.55"},"company3X":{"price":""},"company4X":{"price":""},"company5X":{"price":"1528.0"}}

I don't know the name of "company" to use in my request.

How can I fetch my data ordered by price?
Thanks!

P.S I have tried select json_extract(params, '$[*].price') from data but it doesn't work (return nulls).

Body:
$[*] gets all elements of a JSON array, not an object. This is an object, so you get NULL.

$.* will get you all elements in a JSON object, so $.*.price gets you a JSON array of all prices.

mysql> select json_extract(params, '$.*.price') from foo;
+-------------------------------------------+
| json_extract(params, '$.*.price')         |
+-------------------------------------------+
| ["1124.55", "1,124.55", "", "", "1528.0"] |
+-------------------------------------------+

Now there's a problem. As far as SQL is concerned, this is a single row. It can't be sorted with a normal order by, that works on rows.

MySQL has no function for sorting JSON... so you're stuck. You can return the JSON array and let whatever is receiving the data do the sorting. You might be able to write a stored procedure to sort the array... but that's a lot of work to support a bad table design. Instead, change the table.

The real problem is this is a bad use of a JSON column.

JSON columns defeat most of the point of a SQL database (less so in PostgreSQL which has much better JSON support). SQL databases work with rows and columns, but JSON shoves what would be multiple rows and columns into a single cell.

For this reason, JSON columns should be used sparingly; typically when you're not sure what sort of data you'll be needing to store. Important information like "price" that's going to be searched and sorted should be done as normal columns.

You'll want to change your table to be a normal SQL table with columns for the company name and price. Then you can use normal SQL features like order by and performance will benefit from indexing. There isn't enough information in your question to suggest what that table might look like.


问:
read csv file one to many relationship
I have 2 csv files, one looks like this:

```<code>summary, key, pID, Name, ID
xsajssad, abc123, 1234, p1, 12345678
yasdnalskdj, babc123, 234, p1, 312345678
zsadkmas, cabc123, 3234, p1, 212345678
</code>```

My other csv file looks like this:

```<code>link
file://doc/312345678/document1.doc
file://doc/312345678/document2.doc
file://doc/12345678/document3.doc
file://soc/12345678/document1.doc
file://doc/12345678/document2.doc
file://doc/212345678/document112983.doc
</code>```

What I want is to alter my first csv files are placed to the corressponding ID. The ID is embedded in the file link needs to map back to the unique ID in file 1. This is a one to many relationship, but I want to create a new row to match however many matches there are in the first file.

```<code>summary, key, projectID, projectName, ID, link
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document3.doc
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document1.doc
xsajssad, abc123, 1234, p1, 12345678, file://dpc/12345678/document2.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document1.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document2.doc
zsadkmas, cabc123, 3234, p1, 212345678, file://doc/212345678/document112983.doc
</code>```

What is the most efficient way to do this?

答:
Pandas may be the neatest tool for this:

```<code>import pandas as pd
</code>```

Read the first file and declare id the index. Then read the second file:

```<code>df1 = pd.read_csv('1.csv', sep=',\s*').set_index('ID')
df2 = pd.read_csv('2.csv')
</code>```

Extract the numeric id from the file name and set it as the index of the second dataframe:

```<code>df2.index = df2.link.str.split('/').str[3].astype(int)
</code>```

Join the two tables by their indexes and convert the index back to the column:

```<code>result = df1.join(df2).reset_index()
result.to_csv('1.csv') # Once you do this, the original contents of 1.csv is gone!
</code>```

Title: read csv file one to many relationship

Body:
I have 2 csv files, one looks like this:

summary, key, pID, Name, ID
xsajssad, abc123, 1234, p1, 12345678
yasdnalskdj, babc123, 234, p1, 312345678
zsadkmas, cabc123, 3234, p1, 212345678

My other csv file looks like this:

link
file://doc/312345678/document1.doc
file://doc/312345678/document2.doc
file://doc/12345678/document3.doc
file://soc/12345678/document1.doc
file://doc/12345678/document2.doc
file://doc/212345678/document112983.doc

What I want is to alter my first csv files are placed to the corressponding ID. The ID is embedded in the file link needs to map back to the unique ID in file 1. This is a one to many relationship, but I want to create a new row to match however many matches there are in the first file.

summary, key, projectID, projectName, ID, link
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document3.doc
xsajssad, abc123, 1234, p1, 12345678, file://doc/12345678/document1.doc
xsajssad, abc123, 1234, p1, 12345678, file://dpc/12345678/document2.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document1.doc
yasdnalskdj, babc123, 234, p1, 312345678, file://doc/312345678/document2.doc
zsadkmas, cabc123, 3234, p1, 212345678, file://doc/212345678/document112983.doc

What is the most efficient way to do this?

Body:
Pandas may be the neatest tool for this:

import pandas as pd

Read the first file and declare id the index. Then read the second file:

df1 = pd.read_csv('1.csv', sep=',\s*').set_index('ID')
df2 = pd.read_csv('2.csv')

Extract the numeric id from the file name and set it as the index of the second dataframe:

df2.index = df2.link.str.split('/').str[3].astype(int)

Join the two tables by their indexes and convert the index back to the column:

result = df1.join(df2).reset_index()
result.to_csv('1.csv') # Once you do this, the original contents of 1.csv is gone!


问:
Sending URL parameter from Flask to a Bokeh server
I'm trying to integrate a Bokeh "autoloaded" server into a Flask app where the set of data to load would be chosen by the user on another page.

The ID of this set of data is in the URL (get parameter), and I'm not able to send it from the Flask app to the Bokeh server.

Some example code:

```<code># flask_app.py
import subprocess
import atexit
import subprocess, os

from flask import render_template, render_template_string, Flask

from bokeh.embed import autoload_server
from bokeh.client import pull_session, push_session

app_html = """
<!DOCTYPE html>
<html lang="en">
  <body>
    <div class="bk-root">
      {{ bokeh_script|safe }}
    </div>
  </body>
</html>
"""

app = Flask(__name__)

bokeh_process = subprocess.Popen(
    ['bokeh', 'serve', '--allow-websocket-origin=localhost:5000', 'sample.py'], stdout=subprocess.PIPE)

@atexit.register
def kill_server():
    bokeh_process.kill()

@app.route('/visualization/<int:batchid>')
def visualization(batchid):
    session = pull_session(app_path='/sample')

    # I'd love to do something like that... though it doesn't work :
    session.document.batch_id = batchid
    bokeh_script = autoload_server(None, app_path="/sample", session_id=session.id)
    return render_template_string(app_html, bokeh_script=bokeh_script)

if __name__ == '__main__':
    print("STARTED")
    app.run(debug=True)
</code>```

and for the bokeh server:

```<code># sample.py
import pandas as pd
import bokeh

# ... doesn't work
data = pd.read_csv('batch-%i.csv' % (curdoc().batch_id))
</code>```

Since autoload_server creates a Javascript snippet, there is no way to use the URL parameters for the Bokeh server to pass this data (along with curdoc().session_context)

So... is there any way to pass arguments to a Bokeh app that way?
TYA!

Body:
I'm trying to integrate a Bokeh "autoloaded" server into a Flask app where the set of data to load would be chosen by the user on another page.

The ID of this set of data is in the URL (get parameter), and I'm not able to send it from the Flask app to the Bokeh server.

Some example code:

# flask_app.py
import subprocess
import atexit
import subprocess, os

from flask import render_template, render_template_string, Flask

from bokeh.embed import autoload_server
from bokeh.client import pull_session, push_session

app_html = """
<!DOCTYPE html>

      {{ bokeh_script|safe }}

"""

app = Flask(__name__)

bokeh_process = subprocess.Popen(
    ['bokeh', 'serve', '--allow-websocket-origin=localhost:5000', 'sample.py'], stdout=subprocess.PIPE)

@atexit.register
def kill_server():
    bokeh_process.kill()

@app.route('/visualization/<int:batchid>')
def visualization(batchid):
    session = pull_session(app_path='/sample')

    # I'd love to do something like that... though it doesn't work :
    session.document.batch_id = batchid
    bokeh_script = autoload_server(None, app_path="/sample", session_id=session.id)
    return render_template_string(app_html, bokeh_script=bokeh_script)

if __name__ == '__main__':
    print("STARTED")
    app.run(debug=True)

and for the bokeh server:

# sample.py
import pandas as pd
import bokeh

# ... doesn't work
data = pd.read_csv('batch-%i.csv' % (curdoc().batch_id))

Since autoload_server creates a Javascript snippet, there is no way to use the URL parameters for the Bokeh server to pass this data (along with curdoc().session_context)

So... is there any way to pass arguments to a Bokeh app that way?
TYA!

Body:
You can do it by appending to the src attribute of the <script> tag returned from autoload_server. Check out my function appendQuery in the source for this question

def appendQuery( script , key , value) :
    # Pass along the parameter as a query string to the script's src url: TODO this will formally be introduced in next release of Bokeh to avoid this hack
    script_list = script.split("\n")
    idxSrcAttr = 2
    script_list[idxSrcAttr] = script_list[idxSrcAttr][:-1] + "&{}={}\"".format( key , value )
    script = "\n".join(script_list)
    return script

This is methodology is supposed to be formalized in an upcoming Bokeh release according to... https://github.com/bokeh/bokeh/issues/5992#issuecomment-287232101


问:
'You may need an appropriate loader to handle this file type.' in Vue.js project
I am getting the following error when I am trying to run "gulp" in my vue.js project after I have added an image tag in my Home.vue component [  ] :

```<code>stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^
 Error: ModuleParseError: Module parse failed: G:\Projects\Cakes\src\images\logoWhite.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '�' (1:0)
</code>```

I read that this error might be caused by babel and how it is configured in webpack.config.js. After trying some solutions listed, I still haven't managed to get it work. I have also tried to create a '.babelrc' file with the presets conditions for babel, but still it didn't work.

This is how 'webpack.config.js' file looks like:

```<code>var webpack = require('webpack')

module.exports =  {
  entry: [
    './src/main.js'
  ],
  output: {
    path: "/dist/js",
    publicPath: "/dist/",
    filename: "app.js"
  },
  watch: true,
  module: {
    loaders: [
      {
        test: /\.js$/,
        // excluding some local linked packages.
        // for normal use cases only node_modules is needed.
        exclude: /node_modules|vue\/src|vue-router\//,
        loader: 'babel'
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
      {
        test: /\.vue$/,
        loader: 'vue'
      }
    ]
  },
  babel: {
    presets: ['es2015'],
    plugins: ['transform-runtime']
  },
  resolve: {
    modulesDirectories: ['node_modules']
  }
}
</code>```

In package.json, I have the following packages as my devDependencies for babel:

```<code>"babel-core": "^6.1.21",
"babel-loader": "^6.1.0",
"babel-plugin-transform-runtime": "^6.1.18",
"babel-preset-es2015": "^6.13.2",
"babel-runtime": "^6.3.13"
</code>```

Thanks in advance guys!

答:
I had the same problem and my solution was to use 'file-loader'

Install:

```<code>npm install --save-dev file-loader
</code>```

Add the module rule to your webpack.config.js

```<code>{ test: /\.(png|jpg|gif)$/, loader: 'file-loader?name=./images/[name].[ext]' }
</code>```

CSS file:

```<code>.content {
    background-image: url('./images/background.jpg');
}
</code>```

Body:
I am getting the following error when I am trying to run "gulp" in my vue.js project after I have added an image tag in my Home.vue component [  ] :

stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^
 Error: ModuleParseError: Module parse failed: G:\Projects\Cakes\src\images\logoWhite.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '�' (1:0)

I read that this error might be caused by babel and how it is configured in webpack.config.js. After trying some solutions listed, I still haven't managed to get it work. I have also tried to create a '.babelrc' file with the presets conditions for babel, but still it didn't work.

This is how 'webpack.config.js' file looks like:

var webpack = require('webpack')

module.exports =  {
  entry: [
    './src/main.js'
  ],
  output: {
    path: "/dist/js",
    publicPath: "/dist/",
    filename: "app.js"
  },
  watch: true,
  module: {
    loaders: [
      {
        test: /\.js$/,
        // excluding some local linked packages.
        // for normal use cases only node_modules is needed.
        exclude: /node_modules|vue\/src|vue-router\//,
        loader: 'babel'
      },
      {
        test: /\.scss$/,
        loaders: ['style', 'css', 'sass']
      },
      {
        test: /\.vue$/,
        loader: 'vue'
      }
    ]
  },
  babel: {
    presets: ['es2015'],
    plugins: ['transform-runtime']
  },
  resolve: {
    modulesDirectories: ['node_modules']
  }
}

In package.json, I have the following packages as my devDependencies for babel:

"babel-core": "^6.1.21",
"babel-loader": "^6.1.0",
"babel-plugin-transform-runtime": "^6.1.18",
"babel-preset-es2015": "^6.13.2",
"babel-runtime": "^6.3.13"

Thanks in advance guys!

Body:
I had the same problem and my solution was to use 'file-loader'

Install:

npm install --save-dev file-loader

Add the module rule to your webpack.config.js

{ test: /\.(png|jpg|gif)$/, loader: 'file-loader?name=./images/[name].[ext]' }

CSS file:

.content {
    background-image: url('./images/background.jpg');
}


问:
How to represent multiple types (union types) when targeting JavaScript
What I would like to do is use a generic type that can be one of three other types.

Here's an example with a function:

```<code>fun <T> get(key: String) : T where T: String, T: Number, T: Boolean {}
</code>```

The above code doesn't work, so how should I go about doing this?

答:
For KotlinJS you can use ts2kt to translate your TypeScript definitions to Kotlin.  It does support Union Types but maybe not all cases are perfect.  There are tests for unionTypes in ts2kt that shed light on how they are handled now and you can do something similar for anything you are creating by hand when targetting the JavaScript platform.

Further work is mentioned in comments to issue #41 - to add better Union Type support.  Lastly there is at least one discussion thread on the topic that indicates:

In JS and TS in most cases union types used as the alternative to overloading, so in the near future, we going to use overloading for that when it possible.
  Also, we think about providing the additional way to specify union types for native declarations.

There is another Stack Overflow question talking about this and gives a few current options:  Kotlin and discriminated unions (sum types) which has answers that are valid across all Kotlin target platforms.

Specifically for the JavaScript target you can consider using the dynamic type.  I see at least one test case in ts2kt that is using this type.  This example starts with this TypeScript code:

declare class Foo

type Key = Key2 | number;
type Key2 = string | Foo;
declare var fooKey: Key;

declare function barKey(a: Key|number);
declare function barList(a: List<Key>);
declare function barArray(a: Key[]);

interface Parent {
    (...children: Key[]): Foo;
}
```

<p>And generates this Kotlin using <code>dynamic</code> as a return type in place of the union type; and in other cases overloading the method signature to handle the union type (<em>some comments added by me</em>):</p>

```external open class Foo

// using dynamic in place of union type
external var fooKey: dynamic /* String | Foo | Number */ = definedExternally

// using method overloading in place of union type
external fun barKey(a: String): Unit = definedExternally
external fun barKey(a: Foo): Unit = definedExternally
external fun barKey(a: Number): Unit = definedExternally

// using dynamic in place of union type
external fun barList(a: List<dynamic /* String | Foo | Number */>): Unit = definedExternally
external fun barArray(a: Array<dynamic /* String | Foo | Number */>): Unit = definedExternally

external interface Parent {
    // using method overloading in place of union type
    @nativeInvoke
    fun invoke(vararg children: String): Foo
    @nativeInvoke
    fun invoke(vararg children: Foo): Foo
    @nativeInvoke
    fun invoke(vararg children: Number): Foo
}
```

But again, you should review all of the ts2kt test cases for union types to see other ideas including for handling of undefined.

Body:
What I would like to do is use a generic type that can be one of three other types.

Here's an example with a function:

fun <T> get(key: String) : T where T: String, T: Number, T: Boolean {}

The above code doesn't work, so how should I go about doing this?

Body:
For KotlinJS you can use ts2kt to translate your TypeScript definitions to Kotlin.  It does support Union Types but maybe not all cases are perfect.  There are tests for unionTypes in ts2kt that shed light on how they are handled now and you can do something similar for anything you are creating by hand when targetting the JavaScript platform.

Further work is mentioned in comments to issue #41 - to add better Union Type support.  Lastly there is at least one discussion thread on the topic that indicates:

In JS and TS in most cases union types used as the alternative to overloading, so in the near future, we going to use overloading for that when it possible.
  Also, we think about providing the additional way to specify union types for native declarations.

There is another Stack Overflow question talking about this and gives a few current options:  Kotlin and discriminated unions (sum types) which has answers that are valid across all Kotlin target platforms.

Specifically for the JavaScript target you can consider using the dynamic type.  I see at least one test case in ts2kt that is using this type.  This example starts with this TypeScript code:

declare class Foo

type Key = Key2 | number;
type Key2 = string | Foo;
declare var fooKey: Key;

declare function barKey(a: Key|number);
declare function barList(a: List<Key>);
declare function barArray(a: Key[]);

interface Parent {
    (...children: Key[]): Foo;
}

And generates this Kotlin using dynamic as a return type in place of the union type; and in other cases overloading the method signature to handle the union type (some comments added by me):

external open class Foo

// using dynamic in place of union type
external var fooKey: dynamic /* String | Foo | Number */ = definedExternally

// using method overloading in place of union type
external fun barKey(a: String): Unit = definedExternally
external fun barKey(a: Foo): Unit = definedExternally
external fun barKey(a: Number): Unit = definedExternally

// using dynamic in place of union type
external fun barList(a: List<dynamic /* String | Foo | Number */>): Unit = definedExternally
external fun barArray(a: Array<dynamic /* String | Foo | Number */>): Unit = definedExternally

external interface Parent {
    // using method overloading in place of union type
    @nativeInvoke
    fun invoke(vararg children: String): Foo
    @nativeInvoke
    fun invoke(vararg children: Foo): Foo
    @nativeInvoke
    fun invoke(vararg children: Number): Foo
}

But again, you should review all of the ts2kt test cases for union types to see other ideas including for handling of undefined.


问:
Why wont Mozilla Firefox support third party fonts on my Website?
I have a TTF (True Type Font) which I have used correctly, as it shows up in Safari and Chrome. Is there a way to enable third party fonts on Firefox, or a MAC friendly file extension which is universal across all internet browsers?

I read up about it, and people suggested WOFF files, but they are an executable file on MAC, and Font Book wont open these files. I'm not particularly interested in downloading a third party program to install this third party font.

(In case you are wondering, or it helps, the font is "Top Secret". It's like an ARMY font)

答:
Rather important note: "files" are not "websites". Browsers do not treat file:/// resources the same as actual websites (which use http:// or https://), and will block all kinds of resource loading that websites should be allowed to do, but would open you up to all kinds of exploits if "files on your harddisk" were allowed to do.

So ,if you want to load your "website" as an actual website, load it with a server. You have a mac, so go to the directory with your index.html in the terminal and run:

```<code>python -m SimpleHTTPServer
</code>```

This assumes you have python 2.7, which every mac has, but maybe you have python3 installed and you want to use that. If so, you need to use this instead:

```<code>python3 -m http.server
</code>```

Presto, you can now access http://localhost:8000 and see your file as interpreted as a website, instead of "as a fie".

Body:
Rather important note: "files" are not "websites". Browsers do not treat file:/// resources the same as actual websites (which use http:// or https://), and will block all kinds of resource loading that websites should be allowed to do, but would open you up to all kinds of exploits if "files on your harddisk" were allowed to do.

So ,if you want to load your "website" as an actual website, load it with a server. You have a mac, so go to the directory with your index.html in the terminal and run:

python -m SimpleHTTPServer

This assumes you have python 2.7, which every mac has, but maybe you have python3 installed and you want to use that. If so, you need to use this instead:

python3 -m http.server

Presto, you can now access http://localhost:8000 and see your file as interpreted as a website, instead of "as a fie".


问:
Show a new select for option selected dynamically jquery
```<code><div class="form-group">
   <label for="options">foo</label>
   <select class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
     <option value="opt1">test1</option>
     <option value="opt2">test2</option>
     <option value="opt3">test3</option>
  </select>
</div>
<script type="text/javascript">
  $("#scope_new_system").change(function() {
     var allSelected = new Array();
     $("#scope_new_system option:selected").each(function() {
       allSelected.push(this.value);
     });
  });
</script>
</code>```

I'm trying to dynamically generate a select with different options based on options selected on the multiple select named "options" above. For example if I click on option test 1 then a select element with options shows to select an option. If I select test 2 then another select shows because I now have 2 options selected. Finally if I unclicked test 1 select option goes away and if i do the same with test 2 it also goes away as well and i'm left with nothing selected. Please help!.

答:
Is this what you need?

$('#selectpicker').multiselect();
$('#selectpicker').on('change',function() {
  var val = $(this).val();
  $('.hidden_slc').hide();
  for (x in val) {
    $('#based'+val[x]).show();
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>
  .hidden_slc {
    display: none;
   }
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" rel="stylesheet"/>

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>

<select id="selectpicker" multiple>
  <option value='1'>tes1</option>
  <option value='2'>tes2</option>
  <option value='3'>tes3</option>
</select>

<select id="based1" class='hidden_slc'>
  <option>sample_from_1</option>
  <option>sample</option>
</select>
<select id="based2" class='hidden_slc'>
  <option>sample_from_2</option>
  <option>sample</option>
</select>
<select id="based3" class='hidden_slc'>
  <option>sample_from_3</option>
  <option>sample</option>
</select> </code>```

Body:
   foo
   <select class="form-control"  name="options" multiple>
     <option value="">-- Choice --</option>
     <option value="opt1">test1</option>
     <option value="opt2">test2</option>
     <option value="opt3">test3</option>
  </select>

I'm trying to dynamically generate a select with different options based on options selected on the multiple select named "options" above. For example if I click on option test 1 then a select element with options shows to select an option. If I select test 2 then another select shows because I now have 2 options selected. Finally if I unclicked test 1 select option goes away and if i do the same with test 2 it also goes away as well and i'm left with nothing selected. Please help!.

Body:
Is this what you need?

$('#selectpicker').multiselect();
$('#selectpicker').on('change',function() {
  var val = $(this).val();
  $('.hidden_slc').hide();
  for (x in val) {
    $('#based'+val[x]).show();
  }
})

<style>
  .hidden_slc {
    display: none;
   }
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" rel="stylesheet"/>

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>

<select id="selectpicker" multiple>
  <option value='1'>tes1</option>
  <option value='2'>tes2</option>
  <option value='3'>tes3</option>
</select>

<select id="based1" class='hidden_slc'>
  <option>sample_from_1</option>
  <option>sample</option>
</select>
<select id="based2" class='hidden_slc'>
  <option>sample_from_2</option>
  <option>sample</option>
</select>
<select id="based3" class='hidden_slc'>
  <option>sample_from_3</option>
  <option>sample</option>
</select>


答:
For the sake of completeness, I'll just leave this here.

```<code>>>> a = [i for i in range(10)]
>>> b = list(filter(lambda x: x > 1, a))
>>> id(a)
4510567816
>>> id(b)
4500803808
>>> id(a) == id(b)
False
</code>```

If you know python, you'll know id gives you a unique reference identifier. If they're not equal, it means they're different.

Title: Does filter() work in-place in python?

Body:
If I call filter() on a list, say:

>>> filter(lambda x: x > 1, [1,2,3,4])
[2, 3, 4]

Is this:

a) creating a totally new list in memory with the results

or

b) is it just pop()-ing items from the existing list and returning the same list?

Body:
For the sake of completeness, I'll just leave this here.

>>> a = [i for i in range(10)]
>>> b = list(filter(lambda x: x > 1, a))
>>> id(a)
4510567816
>>> id(b)
4500803808
>>> id(a) == id(b)
False

If you know python, you'll know id gives you a unique reference identifier. If they're not equal, it means they're different.


问:
System.Management.Automation.Powershell.Invoke() claims HadErrors when there were none
I'm having an issue with the following code where it works fine on computers who have Powershell version 1-4 but when ran on a computer with Powershell V5, the test, "posh.HadErrors" is returning true. I tried this on a clean vagrant install so it's not a profile or env var issue. Any git command I try running, powershell claims to have errors when running on a computer with v5 installed. I'm not even sure how to debug this issue.</p>

```<code>using (var posh = PowerShell.Create())
{
    string resultString = "";
    posh.AddScript("git checkout master");
    var results = posh.Invoke();
    foreach (var result in results)
    {
        if (result == null) { continue; }

        if (posh.HadErrors)
        {
            // This is getting hit when it shouldn't when running Powershell V5
            _console.LogError(result.ToString());
        }
        else
        {
            resultString += result + "\r\n";
            _console.LogDebug(result.ToString());
        }
    }

    foreach (var error in posh.Streams.Error)
    {
        _console.LogError(error.ToString());
    }

    return Tuple.Create(!posh.HadErrors, resultString);
}
</code>```

答: Id HadErroes equal true, check PowerShellInstance.InvocationStateInfo.Reason to see the exception

Body:
I'm having an issue with the following code where it works fine on computers who have Powershell version 1-4 but when ran on a computer with Powershell V5, the test, "posh.HadErrors" is returning true. I tried this on a clean vagrant install so it's not a profile or env var issue. Any git command I try running, powershell claims to have errors when running on a computer with v5 installed. I'm not even sure how to debug this issue.

using (var posh = PowerShell.Create())
{
    string resultString = "";
    posh.AddScript("git checkout master");
    var results = posh.Invoke();
    foreach (var result in results)
    {
        if (result == null) { continue; }

        if (posh.HadErrors)
        {
            // This is getting hit when it shouldn't when running Powershell V5
            _console.LogError(result.ToString());
        }
        else
        {
            resultString += result + "\r\n";
            _console.LogDebug(result.ToString());
        }
    }

    foreach (var error in posh.Streams.Error)
    {
        _console.LogError(error.ToString());
    }

    return Tuple.Create(!posh.HadErrors, resultString);
}

ContentLicense: CC BY-SA 4.0


问:
Need help centering div inside bootstrap columns
I need your help
I'm trying to make a page with a 4 equal width bootstrap columns and a content (let's say a rectangle) inside each of the columns. However, I can't seem to find a way to position each rectangle centrally inside the columns. I need your help to find a way to position the rectangles centrally without ruining the responsive layout of the page.</p>

```<code>    <div class="container-fluid">

    <div class="border row">

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    <div class="border col-md-3"><div  class="rectangles"></div></div>

    </div>
    </div>
</code>```

答:
You could try the flex-box vertical align method. And you want to add this to the parent div you want your rect centered in(I.E. the col you made for your rect) </p>

```<code>.aligner{
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}
</code>```

Body:
You could try the flex-box vertical align method. And you want to add this to the parent div you want your rect centered in(I.E. the col you made for your rect)

.aligner{
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;
    align-items: center;
}


问:
Animation to make circles appear in a nice way
I have a div, when i hover into this div three circles should appear, i want an animation to apply it to those circles when they appear like popping or something like that to make the effect look nice when they show up, how can i do it? here is my code:

.circle{
width: 50px;
height: 50px;
border-radius: 50px;
background-color: blue;
}

.circles{
list-style: none;
display: none;
}

.circles li{
margin-top: 10px;
}

.hoverover:hover + .circles{
display: inline-block
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hoverover">Hover Over Me</div>

<ul class="circles">
<li class="circle"></li>
<li class="circle"></li>
<li class="circle"></li>
</ul></code>```

答:
Here's an effect using animation, opacity and transform: scale()

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul></code>```

Body:
I have a div, when i hover into this div three circles should appear, i want an animation to apply it to those circles when they appear like popping or something like that to make the effect look nice when they show up, how can i do it? here is my code:

.circle{
width: 50px;
height: 50px;
border-radius: 50px;
background-color: blue;
}

.circles{
list-style: none;
display: none;
}

.circles li{
margin-top: 10px;
}

.hoverover:hover + .circles{
display: inline-block
}

Hover Over Me

Body:
Here's an effect using animation, opacity and transform: scale()

.circle {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background-color: blue;
  list-style: none;
  opacity: 0;
  transform: scale(0);
}

.circles li {
  margin-top: 10px;
}

.hoverover:hover + .circles .circle {
  animation: popin .25s forwards;
}

@keyframes popin {
  80% {
    transform: scale(1.15);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

<div class="hoverover">Hover Over Me</div>

<ul class="circles">
  <li class="circle"></li>
  <li class="circle"></li>
  <li class="circle"></li>
</ul>


问:
How to write selenium webdriver automation script for Facebook logout?
I tried this code. Its automating the browser, logging in successfully but I'm not able to logout successfully. Please Help.</p>

```<code>public class fb {

    public static void main(String args[])
    {

        WebDriver driver = new FirefoxDriver();

        driver.get("https://facebook.com");

        driver.manage().window().maximize();

        driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("your email");

        driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("your password");

        driver.findElement(By.xpath(".//*[@id='u_0_n']")).click();

        driver.findElement(By.xpath(".//*[@id='userNavigationLabel']")).click();

        driver.findElement(By.id("u_7_2")).click();// for logout-> button.But not working.
</code>```

答:
```<code>**#Working script**
**#firefox can be used too instead of chrome**
**#sleep is necessary to give sufficient loading time**

from selenium import webdriver

from selenium.webdriver.common.keys import Keys

from time import sleep

from selenium.common.exceptions import TimeoutException

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support.ui import Select

from selenium.webdriver.common.by import By

from selenium.webdriver.support import expected_conditions

from selenium.common.exceptions import NoSuchElementException

usr=input('Enter Email Id:')

pwd=input('Enter Password:')

driver = webdriver.Chrome()

driver.get('https://www.facebook.com/')

a = driver.find_element_by_id('email')

a.send_keys(usr)

b = driver.find_element_by_id('pass')

b.send_keys(pwd)

c = driver.find_element_by_id('loginbutton')

c.click()

sleep(20)

d= driver.find_element_by_id("userNavigationLabel")

d.click()

sleep(10)

e=driver.find_element_by_xpath("//a[contains(@data-gt,'menu_logout')]")

e.click()

sleep(5)

driver.quit()
</code>```

Body:
I tried this code. Its automating the browser, logging in successfully but I'm not able to logout successfully. Please Help.

public class fb {

    public static void main(String args[])
    {

        WebDriver driver = new FirefoxDriver();

        driver.get("https://facebook.com");

        driver.manage().window().maximize();

        driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("your email");

        driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("your password");

        driver.findElement(By.xpath(".//*[@id='u_0_n']")).click();

        driver.findElement(By.xpath(".//*[@id='userNavigationLabel']")).click();

        driver.findElement(By.id("u_7_2")).click();// for logout-> button.But not working.


问:
How is creating Firebase audience based on events with parameters?
If I created an audience based on events on Firebase with parameters, it will be the sum the parameters in audiences?

For example,

we have event "A" with parameter "value". Value is sending as integer and receiving in Firebase as a number.

User made 2 action sending us 2 times event "A":

the first time he send us event "A" with value:     "4" and

the second time he sends us event "A" with value "10".

If we have an audience named "X" with rule only users who events "A" and "value" is less than 5, a user from example above will disappear from that audience X after he sends us second event "A" because 10+4>5? Or he will stay on the audience "X" ?

答: Audience membership is permanent.  Once the user has logged the event with A=4, the user will be a member of that audience, and no further event  will remove them from the audience.</p>


问:
Writing Jasmine test for Angular 2 component which uses Observables
I am trying to test an angular 2 component that uses service calls and observable calls to get a list of data. I have imported my main app module into this spec file.

My spec file looks like this:

```<code>import { ComponentFixture, TestBed, fakeAsync, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { AppModule } from '../../../src/app/app.module';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { } from 'jasmine';

import { FirmService } from '../../../src/app/containers/dashboard/services/firm.service';
import { FirmListComponent } from '../../../src/app/containers/dashboard/firm-list/firm-list.component';
import { mockFirm1, mockFirm2, mockFirms } from './firm-list.mocks';
import { Firm } from '../../../src/app/containers/dashboard/models/firm.model';
import { FirmState } from '../../../src/app/containers/dashboard/services/firm.state';

describe('Firm List Component', () => {
    let fixture: ComponentFixture<FirmListComponent>;
    let component: FirmListComponent;
    let element: HTMLElement;
    let debugEl: DebugElement;
    let firmService: FirmService;
    let mockHttp;
    let stateObservable: Observable<FirmState>;
    let store: Store<FirmState>;
    let getFirmsSpy;
    let getObservableSpy;

    // utilizes zone.js in order to mkae function execute syncrhonously although it is asynchrounous
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [MaterialModule, FormsModule, AppModule],
            declarations: [FirmListComponent],
            providers: [FirmService]
        })
            .compileComponents() // compiles the directives template or any external css calls
            .then(() => {
                fixture = TestBed.createComponent(FirmListComponent); // allows us to get change detection, injector
                component = fixture.componentInstance;
                debugEl = fixture.debugElement;
                element = fixture.nativeElement;
                firmService = fixture.debugElement.injector.get(FirmService);

                getObservableSpy = spyOn(firmService, 'stateObservable')
                    .and.returnValue(new FirmState());

                getFirmsSpy = spyOn(firmService, 'getFirms')
                    .and.returnValue(Observable.of(mockFirms));
            });
    }));

    it('should be defined', () => {
        expect(component).toBeDefined();
    });

    describe('initial display', () => {
        it('should not show firms before OnInit', () => {
            debugEl = fixture.debugElement.query(By.css('.animate-repeat'));
            expect(debugEl).toBeNull();
            expect(getObservableSpy.calls.any()).toBe(false, 'ngOnInit not yet called');
            expect(getFirmsSpy.calls.any()).toBe(false, 'getFirms not yet called');
        });

        it('should still not show firms after component initialized', () => {
            fixture.detectChanges();
            debugEl = fixture.debugElement.query(By.css('.animate-repeat'));
            expect(debugEl).toBeNull();
            expect(getFirmsSpy.calls.any()).toBe(true, 'getFirms called');
        });

        it('should show firms after getFirms observable', async(() => {
            fixture.detectChanges();

            fixture.whenStable().then(() => {
                fixture.detectChanges();

                // **I get the correct value here, this is the table headers for the table data below that is showing 0**
                var rowHeaderLength = element.querySelectorAll('th').length;
                expect(rowHeaderLength).toBe(8);

                // **I get 0 for rowDataLength here, test fails**
                var rowDataLength = element.querySelectorAll('.animate-repeat').length;
                console.log(rowDataLength);
            });
        }));

        it('should show the input for searching', () => {
            expect(element.querySelector('input')).toBeDefined();
        });
    });
});
</code>```

The first test above passes but the second one does not, I am currently getting an error that says "Cannot read property 'nativeElement' of null".

My component code looks like this:

```<code> import { NgModule, Component, Input, OnInit, OnChanges } from '@angular/core';
 import { MaterialModule } from '@angular/material';
 import { FlexLayoutModule } from '@angular/flex-layout';
 import { CommonModule } from '@angular/common';
 import { FormsModule } from '@angular/forms';
 import { Firm } from '../models/firm.model';
 import { FirmService } from '../services/firm.service';

 @Component({
   selector: 'firm-list',
   templateUrl: './firm-list.html',
   styles: []
 })

export class FirmListComponent implements OnInit {
   public selectAll: boolean;
   public firms: Array<Firm>;
   public filteredFirms: any;
   public loading: boolean;
   public searchText: string;
   private componetDestroyed = false;

   // @Input() public search: string;

   constructor(public firmService: FirmService) { }

     public ngOnInit() {
       this.firmService.stateObservable.subscribe((state) => {
         this.firms = state.firms;
         this.filteredFirms = this.firms;
       });

      this.getFirms();
   }

    public getFirms(value?: string) {
      this.loading = true;
      this.firmService.getFirms(value).subscribe((response: any) => {
         this.loading = false;
      });
    }
}

 @NgModule({
   declarations: [FirmListComponent],
   exports: [FirmListComponent],
   providers: [FirmService],
   imports: [
       MaterialModule,
       FlexLayoutModule,
       CommonModule,
       FormsModule
     ]
 })

export class FirmListModule { }
</code>```

I'm not sure if I'm missing some code in my spec file to account for the observable or if I'm missing something else?? Any help is appreciated.

Firm Service

```<code>import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { AuthHttp } from 'angular2-jwt';
import { Response } from '@angular/http';
import { Store } from '@ngrx/store';
import { firmActions } from './firm.reducer';
import { FirmState } from './firm.state';

@Injectable()
export class FirmService {
   public stateObservable: Observable<FirmState>;

   constructor(private $http: AuthHttp, private store: Store<FirmState>) {
    // whatever reducer is selected from the store (in line below) is what the "this.store" refers to in our functions below.
    // it calls that specific reducer function
    // how do I define this line in my unit tests?
      this.stateObservable = this.store.select('firmReducer');
  }

public getFirms(value?: string) {
    return this.$http.get('/api/firm').map((response: Response) => {
        this.store.dispatch({
            type: firmActions.GET_FIRMS,
            payload: response.json()
        });
        return;
    });
}

public firmSelected(firms) {
    // takes in an action, all below are actions - type and payload
    // dispatches to the reducer
    this.store.dispatch({
        type: firmActions.UPDATE_FIRMS,
        payload: firms
    });
}

public firmDeleted(firms) {
    this.store.dispatch({
        type: firmActions.DELETE_FIRMS,
        payload: firms
    });
  }
}
</code>```

My firm component html template:

```<code><md-card class="padding-none margin">
  <div class="toolbar" fxLayout="row" fxLayoutAlign="start center">
    <div fxFlex class="padding-lr">
      <div *ngIf="anySelected()">
        <button color="warn" md-raised-button (click)="deleteSelected()">Delete</button>
      </div>
      <div *ngIf="!anySelected()">
        <md-input-container floatPlaceholder="never">
          <input mdInput [(ngModel)]="searchText" (ngModelChange)="onChange($event)" type="text" placeholder="Search" />
        </md-input-container>
      </div>
    </div>
    <div class="label-list" fxFlex fxLayoutAlign="end center">
      <label class="label bg-purple600"></label>
      <span>EDF Model</span>
      <label class="label bg-green600"></label>
      <span>EDF QO</span>
      <label class="label bg-pink800"></label>
      <span>LGD Model</span>
      <label class="label bg-orange300"></label>
      <span>LGD QO</span>
    </div>
  </div>
  <md-card-content>
    <div class="loading-container" fxLayoutAlign="center center" *ngIf="loading">
      <md-spinner></md-spinner>
    </div>
    <div *ngIf="!loading">
      <table class="table">
        <thead>
          <tr>
            <th class="checkbox-col">
              <md-checkbox [(ngModel)]="selectAll" (click)="selectAllChanged()" aria-label="Select All"></md-checkbox>
            </th>
            <th>
              Firm Name
            </th>
            <th>
              Country
            </th>
            <th>
              Industry
            </th>
            <th>
              EDF
            </th>
            <th>
              LGD
            </th>
            <th>
              Modified
            </th>
            <th>
              Modified By
            </th>
          </tr>
        </thead>
        <tbody>
          <tr *ngFor="let firm of filteredFirms; let i = index" class="animate-repeat" [ngClass]="{'active': firm.selected}">
            <td class="checkbox-col">
              <md-checkbox [(ngModel)]="firm.selected" aria-label="firm.name" (change)="selectFirm(i)"></md-checkbox>
            </td>
            <td>{{firm.name}}</td>
            <td>{{firm.country}}</td>
            <td>{{firm.industry}}</td>
            <td>
              <span class="label bg-purple600">US 4.0</span>
              <span class="label bg-green600">US 4.0</span>
            </td>
            <td>
              <span class="label bg-pink800">US 4.0</span>
              <span class="label bg-orange300">US 4.0</span>
            </td>
            <td>{{firm.modifiedOn}}</td>
            <td>{{firm.modifiedBy}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </md-card-content>
</md-card>
</code>```

答:
Hmm I see a couple things here that could be your problem. Just to be clear, your error is coming here:

```<code>de = fixture.debugElement.query(By.css('table'));
</code>```

You try to get the nativeElement of de, which is null. Let's assume you've troubleshot this and there's no reason for it not to exist - you could sanity check yourself and grab some other element that you "know" should exist, but I really think the issue here is trying to grab a reference to something before it exists. In this case, you detect changes AFTER trying to get a reference to a nativeElement. If your table populates the way I think it does, you need to detect changes() first, then grab a reference to what propagates up to the DOM. For sure your ngOnInit could not have occurred yet - it will not trigger when the TestBed creates the component fixture, it occurs on the first detectChanges().

Try this:

```<code>it('should have table headers', () => {
        fixture.detectChanges();
        de = fixture.debugElement.query(By.css('table'));
        el = de.nativeElement;
        expect(el.textContent).toEqual('Firm Name');
    });
</code>```

It goes further - a lot of times with tables or anything using angular's animation under the covers requires you to import either BrowserAnimationsModule or NoopAnimationsModule. Since this is a unit test, I'd just import the NoopAnimationsModule and then grab your reference and perform the test as you like.

Ok, after you pointed out the error you're getting on ngOnInit, I see what your problem is.

So this unit test isn't meant to test that service. In that vein of thought, you have a few options. Intercept the call to the service with a spy, but since it's a property, you'd have to use spyOnProperty. Or, you can just use that stub you were providing anyways. Reviewing your original post, I think that's what you're trying to do. I think this might work if you change it this way:

```<code>beforeEach(async(() => {
     TestBed.configureTestingModule({
        imports: [MaterialModule, FormsModule, AppModule],
        declarations: [FirmListComponent],
        providers: [{provide: FirmService, useClass: FirmStub}]
    })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(FirmListComponent);
            component = fixture.componentInstance;
            firmStub = fixture.debugElement.injector.get(FirmService);
        });
}));
</code>```

On that note, you will also need to provide a stateObservable property on your FirmStub, as that's being accessed in the ngOninit. You can just stub that out relatively straight forward.

```<code>class FirmStub {
   public stateObservable: Observable<FirmState> = new Observable<FirmState>();
   public getFirms(value?: string): Observable<any> {
    return Observable.of(mockFirms);
    }
}
</code>```

Without the html file, I'm not sure if you actually needed that property to be populated in a certain way to test the template, but if not, that stub should work. If you do need it in a certain way, just have the FirmStub provide a more robust property.

You could also just intercept the ngOnInit all together by adding this to the test:

```<code>spyOn(component, 'ngOnInit');// this will basically stop anything from ngOnInit from actually running.
</code>```

Hope this helps!

Body:
I am trying to test an angular 2 component that uses service calls and observable calls to get a list of data. I have imported my main app module into this spec file.

My spec file looks like this:

import { ComponentFixture, TestBed, fakeAsync, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
import { AppModule } from '../../../src/app/app.module';
import { Observable } from 'rxjs/Observable';
import { Store } from '@ngrx/store';
import { } from 'jasmine';

import { FirmService } from '../../../src/app/containers/dashboard/services/firm.service';
import { FirmListComponent } from '../../../src/app/containers/dashboard/firm-list/firm-list.component';
import { mockFirm1, mockFirm2, mockFirms } from './firm-list.mocks';
import { Firm } from '../../../src/app/containers/dashboard/models/firm.model';
import { FirmState } from '../../../src/app/containers/dashboard/services/firm.state';

describe('Firm List Component', () => {
    let fixture: ComponentFixture<FirmListComponent>;
    let component: FirmListComponent;
    let element: HTMLElement;
    let debugEl: DebugElement;
    let firmService: FirmService;
    let mockHttp;
    let stateObservable: Observable<FirmState>;
    let store: Store<FirmState>;
    let getFirmsSpy;
    let getObservableSpy;

    // utilizes zone.js in order to mkae function execute syncrhonously although it is asynchrounous
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [MaterialModule, FormsModule, AppModule],
            declarations: [FirmListComponent],
            providers: [FirmService]
        })
            .compileComponents() // compiles the directives template or any external css calls
            .then(() => {
                fixture = TestBed.createComponent(FirmListComponent); // allows us to get change detection, injector
                component = fixture.componentInstance;
                debugEl = fixture.debugElement;
                element = fixture.nativeElement;
                firmService = fixture.debugElement.injector.get(FirmService);

                getObservableSpy = spyOn(firmService, 'stateObservable')
                    .and.returnValue(new FirmState());

                getFirmsSpy = spyOn(firmService, 'getFirms')
                    .and.returnValue(Observable.of(mockFirms));
            });
    }));

    it('should be defined', () => {
        expect(component).toBeDefined();
    });

    describe('initial display', () => {
        it('should not show firms before OnInit', () => {
            debugEl = fixture.debugElement.query(By.css('.animate-repeat'));
            expect(debugEl).toBeNull();
            expect(getObservableSpy.calls.any()).toBe(false, 'ngOnInit not yet called');
            expect(getFirmsSpy.calls.any()).toBe(false, 'getFirms not yet called');
        });

        it('should still not show firms after component initialized', () => {
            fixture.detectChanges();
            debugEl = fixture.debugElement.query(By.css('.animate-repeat'));
            expect(debugEl).toBeNull();
            expect(getFirmsSpy.calls.any()).toBe(true, 'getFirms called');
        });

        it('should show firms after getFirms observable', async(() => {
            fixture.detectChanges();

            fixture.whenStable().then(() => {
                fixture.detectChanges();

                // **I get the correct value here, this is the table headers for the table data below that is showing 0**
                var rowHeaderLength = element.querySelectorAll('th').length;
                expect(rowHeaderLength).toBe(8);

                // **I get 0 for rowDataLength here, test fails**
                var rowDataLength = element.querySelectorAll('.animate-repeat').length;
                console.log(rowDataLength);
            });
        }));

        it('should show the input for searching', () => {
            expect(element.querySelector('input')).toBeDefined();
        });
    });
});

The first test above passes but the second one does not, I am currently getting an error that says "Cannot read property 'nativeElement' of null".

My component code looks like this:

 import { NgModule, Component, Input, OnInit, OnChanges } from '@angular/core';
 import { MaterialModule } from '@angular/material';
 import { FlexLayoutModule } from '@angular/flex-layout';
 import { CommonModule } from '@angular/common';
 import { FormsModule } from '@angular/forms';
 import { Firm } from '../models/firm.model';
 import { FirmService } from '../services/firm.service';

 @Component({
   selector: 'firm-list',
   templateUrl: './firm-list.html',
   styles: []
 })

export class FirmListComponent implements OnInit {
   public selectAll: boolean;
   public firms: Array<Firm>;
   public filteredFirms: any;
   public loading: boolean;
   public searchText: string;
   private componetDestroyed = false;

   // @Input() public search: string;

   constructor(public firmService: FirmService) { }

     public ngOnInit() {
       this.firmService.stateObservable.subscribe((state) => {
         this.firms = state.firms;
         this.filteredFirms = this.firms;
       });

      this.getFirms();
   }

    public getFirms(value?: string) {
      this.loading = true;
      this.firmService.getFirms(value).subscribe((response: any) => {
         this.loading = false;
      });
    }
}

 @NgModule({
   declarations: [FirmListComponent],
   exports: [FirmListComponent],
   providers: [FirmService],
   imports: [
       MaterialModule,
       FlexLayoutModule,
       CommonModule,
       FormsModule
     ]
 })

export class FirmListModule { }

I'm not sure if I'm missing some code in my spec file to account for the observable or if I'm missing something else?? Any help is appreciated.

Firm Service

import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { AuthHttp } from 'angular2-jwt';
import { Response } from '@angular/http';
import { Store } from '@ngrx/store';
import { firmActions } from './firm.reducer';
import { FirmState } from './firm.state';

@Injectable()
export class FirmService {
   public stateObservable: Observable<FirmState>;

   constructor(private $http: AuthHttp, private store: Store<FirmState>) {
    // whatever reducer is selected from the store (in line below) is what the "this.store" refers to in our functions below.
    // it calls that specific reducer function
    // how do I define this line in my unit tests?
      this.stateObservable = this.store.select('firmReducer');
  }

public getFirms(value?: string) {
    return this.$http.get('/api/firm').map((response: Response) => {
        this.store.dispatch({
            type: firmActions.GET_FIRMS,
            payload: response.json()
        });
        return;
    });
}

public firmSelected(firms) {
    // takes in an action, all below are actions - type and payload
    // dispatches to the reducer
    this.store.dispatch({
        type: firmActions.UPDATE_FIRMS,
        payload: firms
    });
}

public firmDeleted(firms) {
    this.store.dispatch({
        type: firmActions.DELETE_FIRMS,
        payload: firms
    });
  }
}

My firm component html template:

<md-card class="padding-none margin">

        <button color="warn" md-raised-button (click)="deleteSelected()">Delete</button>

        <md-input-container floatPlaceholder="never">
          <input mdInput [(ngModel)]="searchText" (ngModelChange)="onChange($event)" type="text" placeholder="Search" />
        </md-input-container>

      EDF Model

      EDF QO

      LGD Model

      LGD QO

  <md-card-content>

      <md-spinner></md-spinner>

              <md-checkbox [(ngModel)]="selectAll" (click)="selectAllChanged()" aria-label="Select All"></md-checkbox>

              Firm Name

              Country

              Industry

              EDF

              LGD

              Modified

              Modified By

              <md-checkbox [(ngModel)]="firm.selected" aria-label="firm.name" (change)="selectFirm(i)"></md-checkbox>

            {{firm.name}}
            {{firm.country}}
            {{firm.industry}}

              US 4.0
              US 4.0

              US 4.0
              US 4.0

            {{firm.modifiedOn}}
            {{firm.modifiedBy}}

  </md-card-content>
</md-card>

Body:
Hmm I see a couple things here that could be your problem. Just to be clear, your error is coming here:

de = fixture.debugElement.query(By.css('table'));

You try to get the nativeElement of de, which is null. Let's assume you've troubleshot this and there's no reason for it not to exist - you could sanity check yourself and grab some other element that you "know" should exist, but I really think the issue here is trying to grab a reference to something before it exists. In this case, you detect changes AFTER trying to get a reference to a nativeElement. If your table populates the way I think it does, you need to detect changes() first, then grab a reference to what propagates up to the DOM. For sure your ngOnInit could not have occurred yet - it will not trigger when the TestBed creates the component fixture, it occurs on the first detectChanges().

Try this:

it('should have table headers', () => {
        fixture.detectChanges();
        de = fixture.debugElement.query(By.css('table'));
        el = de.nativeElement;
        expect(el.textContent).toEqual('Firm Name');
    });

It goes further - a lot of times with tables or anything using angular's animation under the covers requires you to import either BrowserAnimationsModule or NoopAnimationsModule. Since this is a unit test, I'd just import the NoopAnimationsModule and then grab your reference and perform the test as you like.

Ok, after you pointed out the error you're getting on ngOnInit, I see what your problem is.

So this unit test isn't meant to test that service. In that vein of thought, you have a few options. Intercept the call to the service with a spy, but since it's a property, you'd have to use spyOnProperty. Or, you can just use that stub you were providing anyways. Reviewing your original post, I think that's what you're trying to do. I think this might work if you change it this way:

beforeEach(async(() => {
     TestBed.configureTestingModule({
        imports: [MaterialModule, FormsModule, AppModule],
        declarations: [FirmListComponent],
        providers: [{provide: FirmService, useClass: FirmStub}]
    })
        .compileComponents()
        .then(() => {
            fixture = TestBed.createComponent(FirmListComponent);
            component = fixture.componentInstance;
            firmStub = fixture.debugElement.injector.get(FirmService);
        });
}));

On that note, you will also need to provide a stateObservable property on your FirmStub, as that's being accessed in the ngOninit. You can just stub that out relatively straight forward.

class FirmStub {
   public stateObservable: Observable<FirmState> = new Observable<FirmState>();
   public getFirms(value?: string): Observable<any> {
    return Observable.of(mockFirms);
    }
}

Without the html file, I'm not sure if you actually needed that property to be populated in a certain way to test the template, but if not, that stub should work. If you do need it in a certain way, just have the FirmStub provide a more robust property.

You could also just intercept the ngOnInit all together by adding this to the test:

spyOn(component, 'ngOnInit');// this will basically stop anything from ngOnInit from actually running.

Hope this helps!


问:
Where can I find the status of my OAuth Developer Verification request? (Google)
https://support.google.com/code/contact/oauth_app_verification

Per google's recent security change, I've completed the above OAuth Developer Verification form 7 days ago. However, I received no response or an e-mail to acknowledge receipt of this form from the Google Developers team.

Can anyone direct me to where I can find out the status of my request and/or a contact number or address so I can find out more?

Many, many thanks in advance!

答:
Can you please provide some more information. For e.g. what were the scopes you are going to ask for, and if your application is for personal/public/gsuite use ?

If this is a personal app, you can just join the Google group Risky Access Permissions By Unreviewed Apps.

Also have you verified your domain via the Search Console ?

Additional F.A.Q

Edit #2.

I let the team reviewing the app know and they will reach out to you when the review is done. Currently, there is no place to check for the status of a review.