问:
"Module not found error" on running python code with numpy in docker container even after adding numpy in dockerfile /requirements.txt
I am running from a dev container some very basic python code

I wanted to make it work with numpy

Before I tried to make it work with numpy , evrything worked perfectly.

I wrote in my python code this line :import numpy as np

These are the steps I followed to install numpy inside my container:

I added pip install for numpy in the dockerfile :
 pip install numpy==1.14.3 (with and without versions ...)
I got this error :

```<code>import numpy as np
ModuleNotFoundError: No module named 'numpy'
</code>```

I tried adding numpy in the requirements.txt and COPY requirements.txt /tmp/pip-tmp/ in the dockerfile

This is my Dockerfile:

```<code>FROM python:3

# Avoid warnings by switching to noninteractive
ENV DEBIAN_FRONTEND=noninteractive

# This Dockerfile adds a non-root user with sudo access. Use the "remoteUser"
# property in devcontainer.json to use it. On Linux, the container user's GID/UIDs
# will be updated to match your local UID/GID (when using the dockerFile property).
# See https://aka.ms/vscode-remote/containers/non-root-user for details.
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Uncomment the following COPY line and the corresponding lines in the `RUN` command if you wish to
# include your requirements in the image itself. It is suggested that you only do this if your
# requirements rarely (if ever) change.
COPY requirements.txt /tmp/pip-tmp/

# Configure apt and install packages
RUN apt-get update \
    && pip install numpy==1.14.3 \
    && apt-get -y install --no-install-recommends apt-utils dialog 2>&1 \
    #
    # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed
    && apt-get -y install git openssh-client iproute2 procps lsb-release \
    #
    # Install pylint
    && apt-get -y install libc-dev \
    && apt-get -y install build-essential \
    && pip install -U pip \
    && pip --disable-pip-version-check --no-cache-dir install pylint \
    #&& pip install --no-cache-dir numpy scipy pandas matplotlib \
    #
    # Update Python environment based on requirements.txt
    && pip --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
    && rm -rf /tmp/pip-tmp \
    #
    # Create a non-root user to use if preferred - see https://aka.ms/vscode-remote/containers/non-root-user.
    && groupadd --gid $USER_GID $USERNAME \
    && useradd -s /bin/bash --uid $USER_UID --gid $USER_GID -m $USERNAME \
    # [Optional] Add sudo support for the non-root user
    && apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME\
    && chmod 0440 /etc/sudoers.d/$USERNAME \
    #
    # Clean up
    && apt-get autoremove -y \
    && apt-get clean -y \
    && rm -rf /var/lib/apt/lists/*

# Switch back to dialog for any ad-hoc use of apt-get
ENV DEBIAN_FRONTEND=dialog
</code>```

I got the same error

(I built my container and rerun it after each step )

If you know how to help me fixing it please let me know

答: One theory: you're accidentally installing the Python packaged by Debian. So now you have two Pythons, the one from the Docker image (where you're pip installing) and the one you run on the command-line, which is different.</p>

Body:
I am running from a dev container some very basic python code

I wanted to make it work with numpy

Before I tried to make it work with numpy , evrything worked perfectly.

I wrote in my python code this line :import numpy as np

These are the steps I followed to install numpy inside my container:

I added pip install for numpy in the dockerfile :
 pip install numpy==1.14.3 (with and without versions ...)
I got this error :

import numpy as np
ModuleNotFoundError: No module named 'numpy'

I tried adding numpy in the requirements.txt and COPY requirements.txt /tmp/pip-tmp/ in the dockerfile

This is my Dockerfile:

FROM python:3

# Avoid warnings by switching to noninteractive
ENV DEBIAN_FRONTEND=noninteractive

# This Dockerfile adds a non-root user with sudo access. Use the "remoteUser"
# property in devcontainer.json to use it. On Linux, the container user's GID/UIDs
# will be updated to match your local UID/GID (when using the dockerFile property).
# See https://aka.ms/vscode-remote/containers/non-root-user for details.
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Uncomment the following COPY line and the corresponding lines in the `RUN` command if you wish to
# include your requirements in the image itself. It is suggested that you only do this if your
# requirements rarely (if ever) change.
COPY requirements.txt /tmp/pip-tmp/

# Configure apt and install packages
RUN apt-get update \
    && pip install numpy==1.14.3 \
    && apt-get -y install --no-install-recommends apt-utils dialog 2>&1 \
    #
    # Verify git, process tools, lsb-release (common in install instructions for CLIs) installed
    && apt-get -y install git openssh-client iproute2 procps lsb-release \
    #
    # Install pylint
    && apt-get -y install libc-dev \
    && apt-get -y install build-essential \
    && pip install -U pip \
    && pip --disable-pip-version-check --no-cache-dir install pylint \
    #&& pip install --no-cache-dir numpy scipy pandas matplotlib \
    #
    # Update Python environment based on requirements.txt
    && pip --disable-pip-version-check --no-cache-dir install -r /tmp/pip-tmp/requirements.txt \
    && rm -rf /tmp/pip-tmp \
    #
    # Create a non-root user to use if preferred - see https://aka.ms/vscode-remote/containers/non-root-user.
    && groupadd --gid $USER_GID $USERNAME \
    && useradd -s /bin/bash --uid $USER_UID --gid $USER_GID -m $USERNAME \
    # [Optional] Add sudo support for the non-root user
    && apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME\
    && chmod 0440 /etc/sudoers.d/$USERNAME \
    #
    # Clean up
    && apt-get autoremove -y \
    && apt-get clean -y \
    && rm -rf /var/lib/apt/lists/*

# Switch back to dialog for any ad-hoc use of apt-get
ENV DEBIAN_FRONTEND=dialog

I got the same error

(I built my container and rerun it after each step )

If you know how to help me fixing it please let me know


来源: stackexchange

问:
Connection plugin 'packer' was not found
I am trying to provision an Azure image with Packer and Ansible.

(The same thing with AWS works perfectly)

The Packer .json file has defined Ansible provisioner:

```<code>{
      "type": "ansible",
      "playbook_file": "./gitlab/ansible/install-gitlab.yml",
      "extra_arguments": [
        "-vvvv"
      ]
}
</code>```

I get this output:

    azure-arm: ansible-playbook 2.10.0.dev0
    azure-arm:   config file = None
    azure-arm:   configured module search path = [u'/Users/kdemiris/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
    azure-arm:   ansible python module location = /Library/Python/2.7/site-packages/ansible-2.10.0.dev0-py2.7.egg/ansible
    azure-arm:   executable location = /usr/local/bin/ansible-playbook
    azure-arm:   python version = 2.7.16 (default, Nov  9 2019, 05:55:08) [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s
    azure-arm: No config file found; using defaults
    azure-arm: setting up inventory plugins
    azure-arm: host_list declined parsing /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 as it did not pass its verify_file() method
    azure-arm: script declined parsing /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 as it did not pass its verify_file() method
    azure-arm: auto declined parsing /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 as it did not pass its verify_file() method
    azure-arm: Parsed /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 inventory source with ini plugin
    azure-arm: Loading callback plugin default of type stdout, v2.0 from /Library/Python/2.7/site-packages/ansible-2.10.0.dev0-py2.7.egg/ansible/plugins/callback/default.pyc
    azure-arm:
    azure-arm: PLAYBOOK: install-gitlab.yml ***************************************************
    azure-arm: Positional arguments: /Users/kdemiris/Documents/Projects/packer/gitlab/ansible/install-gitlab.yml
    azure-arm: become_method: sudo
    azure-arm: inventory: (u'/var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129',)
    azure-arm: forks: 5
    azure-arm: tags: (u'all',)
    azure-arm: extra_vars: (u'packer_build_name=azure-arm packer_builder_type=azure-arm -o IdentitiesOnly=yes', u'ansible_ssh_private_key_file=/var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/ansible-key049101946')
    azure-arm: verbosity: 4
    azure-arm: connection: packer
    azure-arm: timeout: 10
    azure-arm: 2 plays in /Users/kdemiris/Documents/Projects/packer/gitlab/ansible/install-gitlab.yml
    azure-arm:
    azure-arm: PLAY [all] *********************************************************************
    azure-arm:
    azure-arm: TASK [Gathering Facts] *********************************************************
    azure-arm: task path: /Users/kdemiris/Documents/Projects/packer/gitlab/ansible/install-gitlab.yml:2
    azure-arm: fatal: [default]: FAILED! => {
    azure-arm:     "msg": "the connection plugin 'packer' was not found"
    azure-arm: }
    azure-arm:
    azure-arm: PLAY RECAP *********************************************************************
    azure-arm: default                    : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
    azure-arm:
==> azure-arm: Provisioning step had errors: Running the cleanup provisioner, if present...
```

Has anyone encountered something like this?

答:
Add a directory adjacent to your playbook named connection_plugins. Add the following packer.py file to that directory.

https://raw.githubusercontent.com/hashicorp/packer/master/examples/ansible/connection-plugin/2.6.x/packer.py

Details can be found here:
https://packer.io/docs/provisioners/ansible.html#winrm-communicator

ContentLicense: CC BY-SA 4.0

Body:
I am trying to provision an Azure image with Packer and Ansible.

(The same thing with AWS works perfectly)

The Packer .json file has defined Ansible provisioner:

{
      "type": "ansible",
      "playbook_file": "./gitlab/ansible/install-gitlab.yml",
      "extra_arguments": [
        "-vvvv"
      ]
}

I get this output:

    azure-arm: ansible-playbook 2.10.0.dev0
    azure-arm:   config file = None
    azure-arm:   configured module search path = [u'/Users/kdemiris/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
    azure-arm:   ansible python module location = /Library/Python/2.7/site-packages/ansible-2.10.0.dev0-py2.7.egg/ansible
    azure-arm:   executable location = /usr/local/bin/ansible-playbook
    azure-arm:   python version = 2.7.16 (default, Nov  9 2019, 05:55:08) [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s
    azure-arm: No config file found; using defaults
    azure-arm: setting up inventory plugins
    azure-arm: host_list declined parsing /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 as it did not pass its verify_file() method
    azure-arm: script declined parsing /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 as it did not pass its verify_file() method
    azure-arm: auto declined parsing /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 as it did not pass its verify_file() method
    azure-arm: Parsed /var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129 inventory source with ini plugin
    azure-arm: Loading callback plugin default of type stdout, v2.0 from /Library/Python/2.7/site-packages/ansible-2.10.0.dev0-py2.7.egg/ansible/plugins/callback/default.pyc
    azure-arm:
    azure-arm: PLAYBOOK: install-gitlab.yml ***************************************************
    azure-arm: Positional arguments: /Users/kdemiris/Documents/Projects/packer/gitlab/ansible/install-gitlab.yml
    azure-arm: become_method: sudo
    azure-arm: inventory: (u'/var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/packer-provisioner-ansible245962129',)
    azure-arm: forks: 5
    azure-arm: tags: (u'all',)
    azure-arm: extra_vars: (u'packer_build_name=azure-arm packer_builder_type=azure-arm -o IdentitiesOnly=yes', u'ansible_ssh_private_key_file=/var/folders/1n/by1psykj793gpv8z6jxw2_n06ngr6v/T/ansible-key049101946')
    azure-arm: verbosity: 4
    azure-arm: connection: packer
    azure-arm: timeout: 10
    azure-arm: 2 plays in /Users/kdemiris/Documents/Projects/packer/gitlab/ansible/install-gitlab.yml
    azure-arm:
    azure-arm: PLAY [all] *********************************************************************
    azure-arm:
    azure-arm: TASK [Gathering Facts] *********************************************************
    azure-arm: task path: /Users/kdemiris/Documents/Projects/packer/gitlab/ansible/install-gitlab.yml:2
    azure-arm: fatal: [default]: FAILED! => {
    azure-arm:     "msg": "the connection plugin 'packer' was not found"
    azure-arm: }
    azure-arm:
    azure-arm: PLAY RECAP *********************************************************************
    azure-arm: default                    : ok=0    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0
    azure-arm:
==> azure-arm: Provisioning step had errors: Running the cleanup provisioner, if present...

Has anyone encountered something like this?


问:
InternetExplorer COMException: System.Runtime.InteropServices.COMexception: The RPC server is unavailable
I'm very new to C# so please excuse me if it's a silly question.

I created a console application that uses the "InternetExplorer" from SHDocVw. This application goes to a website and performs some operations. It works just fine on my computer, but when I try to publish it I just can't to get it to work on my colleagues computers. These other computers don't have dotnet core installed.

So if I publish the app as framework-dependant I get a hostfxr.dll missing library error and it obviously doesn't work at all.

I thought I could fix this by publishing the app as self-dependant. This didn't help either. I always need to paste the "Interop.MSHTML.dll" and "Interop.SHDocVw.dll" manually. When I do, the app at least starts. Internet explorer shows up, the "Navigate" command works. But as soon as I try to hide the window, or try to work with elements in the page, it just crashes.

There are two types of errors I get:

Unhandled Exception: System.Runtime.InteropServices.COMexception: The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
at SHDocVw.IWebBrowser2.set_Visible(Boolean pBool)
at MyWebApp.IEDriver.Visibility(Boolean isVisible)
at MyWebApp.Program.Main(String[] args)

Other times I get a very similar error, but it's even mentions my own user files, even when running on a different machine. Is that normal?

Unhandled exception. System.Runtime.InteropServices.COMException (0x800706BA): The RPC server is unavailable. (0x800706BA)
   at SHDocVw.InternetExplorerClass.get_ReadyState()
   at IEAutomation.IEDriver.WaitForComplete() in C:\Users\St3ve\source\repos\MyWebApp\MyWebApp\IEDriver.cs:line 552
   at TestWeb.Program.Main(String[] args) in C:\Users\St3ve\source\repos\MyWebApp\MyWebApp\Program.cs:line 82

I tried to to google the errors, but can't get it work, I would be really grateful for any hints or help.

答:
The crux of this approach is to make sure we are accessing the right InternetExplorer object that is associated with our process

```<code>private InternetExplorer _IE;

public Process m_Proc = Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "-nomerge www.google.com");

public IEDriver()
{

    Thread.Sleep(5000);
    _IE = null;
    ShellWindows m_IEFoundBrowsers = new ShellWindows();
    foreach (InternetExplorer Browser in m_IEFoundBrowsers)
    {
    if (Browser.HWND == (int)m_Proc.MainWindowHandle)
    {
    _IE = Browser;
    break;
    }
}
</code>```

Then in your methods like WaitForCompleteNew(), Navigate(), etc where ever you attempt to access InternetExplorer's proprties or methods, you can use object _IE.

```<code>_IE.Visible = false;
document = ((HTMLDocument)_IE.Document)
</code>```

Body:
The crux of this approach is to make sure we are accessing the right InternetExplorer object that is associated with our process

private InternetExplorer _IE;

public Process m_Proc = Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "-nomerge www.google.com");

public IEDriver()
{

    Thread.Sleep(5000);
    _IE = null;
    ShellWindows m_IEFoundBrowsers = new ShellWindows();
    foreach (InternetExplorer Browser in m_IEFoundBrowsers)
    {
    if (Browser.HWND == (int)m_Proc.MainWindowHandle)
    {
    _IE = Browser;
    break;
    }
}

Then in your methods like WaitForCompleteNew(), Navigate(), etc where ever you attempt to access InternetExplorer's proprties or methods, you can use object _IE.

_IE.Visible = false;
document = ((HTMLDocument)_IE.Document)


问:
Question about multiple inheritance, dynamic class creating and instantiation
Hello I have the following situation:

A specialized class that inherits from two parent class

The need to define the most specialized class at run time, based on some information that I get only when I start reading data from a database.

I defined the following code to handle the create all the classes in the chain:

class BusinessDocument():
    @staticmethod
    def get_class(doc_type):
        switch = {
            'MasterData': MasterData,
            'Transactional': Transactional
        }
        func = switch.get(doc_type, lambda: "Invalid Noun Type")
        return func()

    def __init__(self, doc_id, location, doc_type):
        self.doc_id = doc_id
        self.location = location
        self.doc_type = doc_type
        pass

    @property
    def get_location(self):
        return self.location

    @property
    def get_doc_id(self):
        return self.doc_id

class MasterData(BusinessDocument):
    def __init__(self, doc_id, location):
        BusinessDocument.__init__(self, doc_id, location, 'MasterData')

class Transactional(BusinessDocument):
    def __init__(self, doc_id, location):
        BusinessDocument.__init__(self, doc_id, location, 'Transactional')

class NounClass():
    @staticmethod
    def get_class(doc_name, doc_type):
        return type(doc_name, (BusinessDocument.get_class(doc_type),
                           BusinessDocument, ),dict.fromkeys(['doc_id', 'location']))
```

<p>Then at run time when I get the doc_name and I try to create a new class. At this point I may not have the required arguments <em>doc_id</em> and <em>location</em> but I need to class type.</p>

<pre class="lang-python prettyprint-override"><code>invoice_cls = NounClass.get_class('Invoice', 'Transactional')
</code>```

I get the following error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-cb774746875a> in <module>
----> 1 invoice_cls = NounClass.get_class('Invoice', 'Transactional')

<ipython-input-9-aa5e0b316ed1> in get_class(doc_name, doc_type)
     35     @staticmethod
     36     def get_class(doc_name, doc_type):
---> 37         return type(doc_name, (BusinessDocument.get_class(doc_type),
     38                            BusinessDocument, ),dict.fromkeys(['doc_id', 'location']))

<ipython-input-9-aa5e0b316ed1> in get_class(doc_type)
      7         }
      8         func = switch.get(doc_type, lambda: "Invalid Noun Type")
----> 9         return func()
     10
     11     def __init__(self, doc_id, location, doc_type):

TypeError: __init__() missing 2 required positional arguments: 'doc_id' and 'location'
</code>```

I understand that the reason for it is because the __init__() will be called during the class instantiation, but I thought that type would be only creating a new type and not instantiate one right away. So my question is if is there a way to defer the instantiation of the instance at this time.

Thank you in advance for any help and tips on this.

--MD.

答:
The initalization occurs on line 9:

```<code>    return func()
</code>```

I assume you want to return a class object, so remove those parantheses.

Also func is misleding, I've changed it to cls:

```<code>def get_class(doc_type):
    switch = {
        'MasterData': MasterData,
        'Transactional': Transactional
    }
    cls = switch.get(doc_type, lambda: "Invalid Noun Type")
    return cls
</code>```

Body:
Hello I have the following situation:

A specialized class that inherits from two parent class

The need to define the most specialized class at run time, based on some information that I get only when I start reading data from a database.

I defined the following code to handle the create all the classes in the chain:

class BusinessDocument():
    @staticmethod
    def get_class(doc_type):
        switch = {
            'MasterData': MasterData,
            'Transactional': Transactional
        }
        func = switch.get(doc_type, lambda: "Invalid Noun Type")
        return func()

    def __init__(self, doc_id, location, doc_type):
        self.doc_id = doc_id
        self.location = location
        self.doc_type = doc_type
        pass

    @property
    def get_location(self):
        return self.location

    @property
    def get_doc_id(self):
        return self.doc_id

class MasterData(BusinessDocument):
    def __init__(self, doc_id, location):
        BusinessDocument.__init__(self, doc_id, location, 'MasterData')

class Transactional(BusinessDocument):
    def __init__(self, doc_id, location):
        BusinessDocument.__init__(self, doc_id, location, 'Transactional')

class NounClass():
    @staticmethod
    def get_class(doc_name, doc_type):
        return type(doc_name, (BusinessDocument.get_class(doc_type),
                           BusinessDocument, ),dict.fromkeys(['doc_id', 'location']))

Then at run time when I get the doc_name and I try to create a new class. At this point I may not have the required arguments doc_id and location but I need to class type.

invoice_cls = NounClass.get_class('Invoice', 'Transactional')

I get the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-cb774746875a> in <module>
----> 1 invoice_cls = NounClass.get_class('Invoice', 'Transactional')

<ipython-input-9-aa5e0b316ed1> in get_class(doc_name, doc_type)
     35     @staticmethod
     36     def get_class(doc_name, doc_type):
---> 37         return type(doc_name, (BusinessDocument.get_class(doc_type),
     38                            BusinessDocument, ),dict.fromkeys(['doc_id', 'location']))

<ipython-input-9-aa5e0b316ed1> in get_class(doc_type)
      7         }
      8         func = switch.get(doc_type, lambda: "Invalid Noun Type")
----> 9         return func()
     10
     11     def __init__(self, doc_id, location, doc_type):

TypeError: __init__() missing 2 required positional arguments: 'doc_id' and 'location'

I understand that the reason for it is because the __init__() will be called during the class instantiation, but I thought that type would be only creating a new type and not instantiate one right away. So my question is if is there a way to defer the instantiation of the instance at this time.

Thank you in advance for any help and tips on this.

--MD.

Body:
The initalization occurs on line 9:

    return func()

I assume you want to return a class object, so remove those parantheses.

Also func is misleding, I've changed it to cls:

def get_class(doc_type):
    switch = {
        'MasterData': MasterData,
        'Transactional': Transactional
    }
    cls = switch.get(doc_type, lambda: "Invalid Noun Type")
    return cls


问:
React native Google Signin Fail When i will build release apk
I will signin with google it's working but whenever I'll create release build it not working</p>

```<code>GoogleErrorcode : DEVELOPERERROR
</code>```

答:
I have got a solution to this problem.
You have to put both SHA key i.e. SHA for debug Keystore file and SHA for release jks file, into the firebase project setting.

Go to: https://console.firebase.google.com/

Now choose your project

Click the setting button near Project Overview

Choose Project Setting

Enter both SHA1 (debug SHA1 and release SHA1) in SHA certificate fingerprint

Save it

Download the google-services.json file

Run npx react-native run-android --variant=release in terminal

It worked for me very well.

Body:
I will signin with google it's working but whenever I'll create release build it not working

GoogleErrorcode : DEVELOPERERROR


问:
add legend and smoothing to a graph
I am going to plot these curves with the legend, however, the legend does not appear. Does anyone know how I can bring it ... also is it possible to make the plots neater and smoother? (the data for each plot is 165, ... is it possible to plot the average of each 16 data (i.e. we do not have 165 data anymore, we will have 10 data?
here is the code:

```<code>ggplot() +
  geom_ribbon(data=file1, aes(x = No., ymax = A1_10 + S1_10, ymin = A1_10 - S1_10),alpha = 0.20, fill=cl[1])+
  geom_line(data = file1, aes(x = No., y = A1_10), colour="red")+
  geom_ribbon(data=file1, aes(x = No., ymax = A2_10 + S2_10, ymin = A2_10 - S2_10),alpha = 0.20, fill=cl[3])+
  geom_line(data = file1, aes(x = No., y = A2_10), colour=cl[3])+
  geom_ribbon(data=file1, aes(x = No., ymax = A3_10 + S3_10, ymin = A3_10 - S3_10),alpha = 0.20, fill=cl[11])+
  geom_line(data = file1, aes(x = No., y = A3_10), colour=cl[11])+
  geom_ribbon(data=file1, aes(x = No., ymax = A5_10 + S5_10, ymin = A5_10 - S5_10),alpha = 0.20, fill=cl[8])+
  geom_line(data = file1, aes(x = No., y = A5_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A6_10 + S6_10, ymin = A6_10 - S6_10),alpha = 0.20, fill=cl[12])+
  geom_line(data = file1, aes(x = No., y = A6_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A7_10 + S7_10, ymin = A7_10 - S7_10),alpha = 0.20, fill=cl[18])+
  geom_line(data = file1, aes(x = No., y = A7_10), colour=cl[8])+
  xlab("Number")+ylab("Value")+
  theme(legend.position="bottom")
</code>```

答:
Hi thanks for your time and kind help.
My file contains 12 columns of 165 data with the names A1, A2, ..., A7 and S1, S2, ..., S7. and this is my code

```<code>graphics.off()
rm(list=ls())

library(ggplot2)
library(dplyr)

setwd("F:/files/")

file1<-read.csv("F:/Self/ave1.csv")
file2<-read.csv("F:/Self/ave2.csv")

pdf("4.pdf",width=10,height=4)
par(mfrow =c(4, 1))
cl<-rainbow(20)

names(file1)
names(file2)

ggplot() +
  geom_ribbon(data=file1, aes(x = No., ymax = A1_10 + S1_10, ymin = A1_10 - S1_10),alpha = 0.20, fill=cl[1])+
  geom_line(data = file1, aes(x = No., y = A1_10), colour="red")+
  geom_ribbon(data=file1, aes(x = No., ymax = A2_10 + S2_10, ymin = A2_10 - S2_10),alpha = 0.20, fill=cl[3])+
  geom_line(data = file1, aes(x = No., y = A2_10), colour=cl[3])+
  geom_ribbon(data=file1, aes(x = No., ymax = A3_10 + S3_10, ymin = A3_10 - S3_10),alpha = 0.20, fill=cl[11])+
  geom_line(data = file1, aes(x = No., y = A3_10), colour=cl[11])+
  geom_ribbon(data=file1, aes(x = No., ymax = A5_10 + S5_10, ymin = A5_10 - S5_10),alpha = 0.20, fill=cl[8])+
  geom_line(data = file1, aes(x = No., y = A5_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A6_10 + S6_10, ymin = A6_10 - S6_10),alpha = 0.20, fill=cl[12])+
  geom_line(data = file1, aes(x = No., y = A6_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A7_10 + S7_10, ymin = A7_10 - S7_10),alpha = 0.20, fill=cl[18])+
  geom_line(data = file1, aes(x = No., y = A7_10), colour=cl[8])+
  xlab("Number")+ylab("Value")+
  theme(legend.position="bottom")

ggplot() +
      geom_ribbon(data=file2, aes(x = No., ymax = A11_10 + S11_10, ymin = A11_10 - S11_10),alpha = 0.20, fill=cl[1])+
      geom_line(data = file2, aes(x = No., y = A11_10), colour="red")+
      geom_ribbon(data=file2, aes(x = No., ymax = A21_10 + S21_10, ymin = A21_10 - S21_10),alpha = 0.20, fill=cl[3])+
      geom_line(data = file2, aes(x = No., y = A21_10), colour=cl[3])+
      geom_ribbon(data=file2, aes(x = No., ymax = A31_10 + S31_10, ymin = A31_10 - S31_10),alpha = 0.20, fill=cl[11])+
      geom_line(data = file2, aes(x = No., y = A31_10), colour=cl[11])+
      geom_ribbon(data=file2, aes(x = No., ymax = A41_10 + S41_10, ymin = A41_10 - S41_10),alpha = 0.20, fill=cl[1])+
      geom_line(data = file2, aes(x = No., y = A41_10), colour="red")+
      geom_ribbon(data=file2, aes(x = No., ymax = A51_10 + S51_10, ymin = A51_10 - S51_10),alpha = 0.20, fill=cl[8])+
      geom_line(data = file2, aes(x = No., y = A51_10), colour=cl[8])+
      geom_ribbon(data=file2, aes(x = No., ymax = A61_10 + S61_10, ymin = A61_10 - S61_10),alpha = 0.20, fill=cl[12])+
      geom_line(data = file2, aes(x = No., y = A61_10), colour=cl[8])+
      geom_ribbon(data=file2, aes(x = No., ymax = A71_10 + S71_10, ymin = A71_10 - S71_10),alpha = 0.20, fill=cl[18])+
      geom_line(data = file2, aes(x = No., y = A71_10), colour=cl[8])+
      xlab("Number")+ylab("Value")+
      theme(legend.position="bottom")

dev.off()
</code>```

I have several files (5 files) that I wanted to bring the shapes on a page to be able to compare them, however, it did not work and still, I have one plot per page. I know also I can use facet grid but I am not familiar with how it works yet especially now when the name of columns of different files are different.
It seems I have a loong looooong way to learn R though.

Title: add legend and smoothing to a graph

Body:
I am going to plot these curves with the legend, however, the legend does not appear. Does anyone know how I can bring it ... also is it possible to make the plots neater and smoother? (the data for each plot is 165, ... is it possible to plot the average of each 16 data (i.e. we do not have 165 data anymore, we will have 10 data?
here is the code:

ggplot() +
  geom_ribbon(data=file1, aes(x = No., ymax = A1_10 + S1_10, ymin = A1_10 - S1_10),alpha = 0.20, fill=cl[1])+
  geom_line(data = file1, aes(x = No., y = A1_10), colour="red")+
  geom_ribbon(data=file1, aes(x = No., ymax = A2_10 + S2_10, ymin = A2_10 - S2_10),alpha = 0.20, fill=cl[3])+
  geom_line(data = file1, aes(x = No., y = A2_10), colour=cl[3])+
  geom_ribbon(data=file1, aes(x = No., ymax = A3_10 + S3_10, ymin = A3_10 - S3_10),alpha = 0.20, fill=cl[11])+
  geom_line(data = file1, aes(x = No., y = A3_10), colour=cl[11])+
  geom_ribbon(data=file1, aes(x = No., ymax = A5_10 + S5_10, ymin = A5_10 - S5_10),alpha = 0.20, fill=cl[8])+
  geom_line(data = file1, aes(x = No., y = A5_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A6_10 + S6_10, ymin = A6_10 - S6_10),alpha = 0.20, fill=cl[12])+
  geom_line(data = file1, aes(x = No., y = A6_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A7_10 + S7_10, ymin = A7_10 - S7_10),alpha = 0.20, fill=cl[18])+
  geom_line(data = file1, aes(x = No., y = A7_10), colour=cl[8])+
  xlab("Number")+ylab("Value")+
  theme(legend.position="bottom")

Body:
Hi thanks for your time and kind help.
My file contains 12 columns of 165 data with the names A1, A2, ..., A7 and S1, S2, ..., S7. and this is my code

graphics.off()
rm(list=ls())

library(ggplot2)
library(dplyr)

setwd("F:/files/")

file1<-read.csv("F:/Self/ave1.csv")
file2<-read.csv("F:/Self/ave2.csv")

pdf("4.pdf",width=10,height=4)
par(mfrow =c(4, 1))
cl<-rainbow(20)

names(file1)
names(file2)

ggplot() +
  geom_ribbon(data=file1, aes(x = No., ymax = A1_10 + S1_10, ymin = A1_10 - S1_10),alpha = 0.20, fill=cl[1])+
  geom_line(data = file1, aes(x = No., y = A1_10), colour="red")+
  geom_ribbon(data=file1, aes(x = No., ymax = A2_10 + S2_10, ymin = A2_10 - S2_10),alpha = 0.20, fill=cl[3])+
  geom_line(data = file1, aes(x = No., y = A2_10), colour=cl[3])+
  geom_ribbon(data=file1, aes(x = No., ymax = A3_10 + S3_10, ymin = A3_10 - S3_10),alpha = 0.20, fill=cl[11])+
  geom_line(data = file1, aes(x = No., y = A3_10), colour=cl[11])+
  geom_ribbon(data=file1, aes(x = No., ymax = A5_10 + S5_10, ymin = A5_10 - S5_10),alpha = 0.20, fill=cl[8])+
  geom_line(data = file1, aes(x = No., y = A5_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A6_10 + S6_10, ymin = A6_10 - S6_10),alpha = 0.20, fill=cl[12])+
  geom_line(data = file1, aes(x = No., y = A6_10), colour=cl[8])+
  geom_ribbon(data=file1, aes(x = No., ymax = A7_10 + S7_10, ymin = A7_10 - S7_10),alpha = 0.20, fill=cl[18])+
  geom_line(data = file1, aes(x = No., y = A7_10), colour=cl[8])+
  xlab("Number")+ylab("Value")+
  theme(legend.position="bottom")

ggplot() +
      geom_ribbon(data=file2, aes(x = No., ymax = A11_10 + S11_10, ymin = A11_10 - S11_10),alpha = 0.20, fill=cl[1])+
      geom_line(data = file2, aes(x = No., y = A11_10), colour="red")+
      geom_ribbon(data=file2, aes(x = No., ymax = A21_10 + S21_10, ymin = A21_10 - S21_10),alpha = 0.20, fill=cl[3])+
      geom_line(data = file2, aes(x = No., y = A21_10), colour=cl[3])+
      geom_ribbon(data=file2, aes(x = No., ymax = A31_10 + S31_10, ymin = A31_10 - S31_10),alpha = 0.20, fill=cl[11])+
      geom_line(data = file2, aes(x = No., y = A31_10), colour=cl[11])+
      geom_ribbon(data=file2, aes(x = No., ymax = A41_10 + S41_10, ymin = A41_10 - S41_10),alpha = 0.20, fill=cl[1])+
      geom_line(data = file2, aes(x = No., y = A41_10), colour="red")+
      geom_ribbon(data=file2, aes(x = No., ymax = A51_10 + S51_10, ymin = A51_10 - S51_10),alpha = 0.20, fill=cl[8])+
      geom_line(data = file2, aes(x = No., y = A51_10), colour=cl[8])+
      geom_ribbon(data=file2, aes(x = No., ymax = A61_10 + S61_10, ymin = A61_10 - S61_10),alpha = 0.20, fill=cl[12])+
      geom_line(data = file2, aes(x = No., y = A61_10), colour=cl[8])+
      geom_ribbon(data=file2, aes(x = No., ymax = A71_10 + S71_10, ymin = A71_10 - S71_10),alpha = 0.20, fill=cl[18])+
      geom_line(data = file2, aes(x = No., y = A71_10), colour=cl[8])+
      xlab("Number")+ylab("Value")+
      theme(legend.position="bottom")

dev.off()

I have several files (5 files) that I wanted to bring the shapes on a page to be able to compare them, however, it did not work and still, I have one plot per page. I know also I can use facet grid but I am not familiar with how it works yet especially now when the name of columns of different files are different.
It seems I have a loong looooong way to learn R though.


问:
Missing Style.Triggers and x:Type. Why?
```<code><TextBlock Text="{Binding MyTextProperty}">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBox}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding MyTextProperty}" Value="{x:Null}">
                    <Setter Property="Text" Value="Hey, the text should not be empty!" />
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
</code>```

Question 1: Why is

答:
It looks like you are trying to use WPF XAML within Silverlight. Silverlight does not support the {x:Type} markup extension. You can instead use TargetType={TextBox}.

Also, Silverlight does not have DataTrigger support!

See:

What is the replacement for DataTrigger in Silverlight

ContentLicense: CC BY-SA 3.0

Title: Missing Style.Triggers and x:Type. Why?

Body:
<TextBlock Text="{Binding MyTextProperty}">
    <TextBlock.Style>

        </Style>
    </TextBlock.Style>
</TextBlock>

Question 1: Why is


问:
How to import CSV data from Google Drive/Google Sheets into BigQuery correctly
I'm trying to import a CSV file placed in Google Drive into BigQuery and fail. I get an error Error while reading table, error message: CSV table encountered too many errors, giving up.

I guess to know, what caused an error. The CSV file contains strings in the columns A, B and D, integer in column C, and float in columns E and F. Delimiter is the tab, \t.

While the CSV file contains data like on the image 1:

If i look at the file preview in Google Drive, i see broken numbers, like on the image 2: However, if i download file directly from the GDrive and open it with Notepad++, the file exactly as expected: numbers with commas as decimal sign and tab as column delimiter...

On creating the BigQuery table i add columns manually and assign to them field types too. For columns containing numbers i tested any combination of integer, float and numeric - always the same error.

Q: how should i format the CSV file to make the import possible?

Here is a sample of the file:

```<code>Domain  Keywords    RP  Brand   SI  SiBerechnet
example.de  accura versicherung 1   accura  293,9   0,00244913
example.de  accura versicherung erfahrung   1   accura  63,9    0,00053249
example.de  accura versicherung für wohnmobile  1   accura  43,9    0,00036583
example.de  accura versicherung keine wohnmobile mehr   1   accura  53,9    0,00044916
example.de  accura versicherungsmakler  1   accura  83,9    0,00069916
example.de  accura versicherung test    1   accura  43,9    0,00036583
example.de  accura versicherung wohnmobil   1   accura  73,9    0,00061582
example.de  accura wohnmobilversicherung erfahrungen    1   accura  73,9    0,00061582
example.de  aufgaben innendienst versicherung   75  non brand   0,133333333 0,00000111
example.de  aufgaben versicherung innendienst   59  non brand   0,169491525 0,00000141
example.de  basler versicherung kfz telefonnummer   98  basler  0,102040816 0,00000085
example.de  basler versicherung kundenservice   96  basler  0,104166667 0,00000087
example.de  basler wohnmobilversicherung    8   basler  3,86    0,00003217
example.de  bergungskosten unfallversicherung   37  non brand   0,810810811 0,00000676
example.de  berufsunfähigkeitsversicherung bei bürojob  84  non brand   0,238095238 0,00000198
example.de  berufsunfähigkeitsversicherung bürojob  83  non brand   1,084337349 0,00000904
example.de  betriebshaftpflicht für hausmeisterservice  87  non brand   0,114942529 0,00000096
example.de  betriebshaftpflicht für hausverwalter   29  non brand   1,034482759 0,00000862
example.de  betriebshaftpflicht hausmeister 87  non brand   0,114942529 0,00000096
example.de  betriebshaftpflicht hausverwalter   26  non brand   0,384615385 0,00000321
example.de  betriebsunterbrechungsversicherung freiberufler 46  non brand   0,217391304 0,00000181
example.de  braucht eine krankenschwester eine diensthaftpflichtversicherung    15  non brand   2,706666667 0,00002256
example.de  campingfahrzeug versicherung    39  non brand   1,025641026 0,00000855
example.de  dienst haftpflicht  99  non brand   0,303030303 0,00000253
example.de  diensthaftpflicht öffentlicher dienst   55  non brand   0,545454545 0,00000455
example.de  diensthaftpflichtversicherung   57  non brand   22,80701754 0,00019006
example.de  dienst haftpflichtversicherung  84  non brand   0,238095238 0,00000198
example.de  diensthaftpflichtversicherung beamte    90  non brand   0,555555556 0,00000463
example.de  diensthaftpflichtversicherung für soldaten  28  non brand   0,357142857 0,00000298
example.de  diensthaftpflichtversicherung kosten    80  non brand   0,5 0,00000417
example.de  diensthaftpflichtversicherung öffentlicher dienst   51  non brand   0,980392157 0,00000817
example.de  diensthaftpflichtversicherung öffentlicher dienst angestellte   63  non brand   0,158730159 0,00000132
example.de  diensthaftpflichtversicherung polizei   69  non brand   0,724637681 0,00000604
example.de  diensthaftpflichtversicherung soldaten  26  non brand   0,769230769 0,00000641
example.de  einbauküche hausrat oder gebäude scheidung  31  non brand   0,64516129  0,00000538
example.de  einbauküche hausratversicherung oder gebäudeversicherung    12  non brand   2,643333333 0,00002203
</code>```

答:
What happens often is that the language settings on the drive sheets are different and are throwing around the "." and ",".

You can see/change this in File -> spreadsheet settings

Body:
I'm trying to import a CSV file placed in Google Drive into BigQuery and fail. I get an error Error while reading table, error message: CSV table encountered too many errors, giving up.

I guess to know, what caused an error. The CSV file contains strings in the columns A, B and D, integer in column C, and float in columns E and F. Delimiter is the tab, \t.

While the CSV file contains data like on the image 1:

If i look at the file preview in Google Drive, i see broken numbers, like on the image 2: However, if i download file directly from the GDrive and open it with Notepad++, the file exactly as expected: numbers with commas as decimal sign and tab as column delimiter...

On creating the BigQuery table i add columns manually and assign to them field types too. For columns containing numbers i tested any combination of integer, float and numeric - always the same error.

Q: how should i format the CSV file to make the import possible?

Here is a sample of the file:

Domain  Keywords    RP  Brand   SI  SiBerechnet
example.de  accura versicherung 1   accura  293,9   0,00244913
example.de  accura versicherung erfahrung   1   accura  63,9    0,00053249
example.de  accura versicherung für wohnmobile  1   accura  43,9    0,00036583
example.de  accura versicherung keine wohnmobile mehr   1   accura  53,9    0,00044916
example.de  accura versicherungsmakler  1   accura  83,9    0,00069916
example.de  accura versicherung test    1   accura  43,9    0,00036583
example.de  accura versicherung wohnmobil   1   accura  73,9    0,00061582
example.de  accura wohnmobilversicherung erfahrungen    1   accura  73,9    0,00061582
example.de  aufgaben innendienst versicherung   75  non brand   0,133333333 0,00000111
example.de  aufgaben versicherung innendienst   59  non brand   0,169491525 0,00000141
example.de  basler versicherung kfz telefonnummer   98  basler  0,102040816 0,00000085
example.de  basler versicherung kundenservice   96  basler  0,104166667 0,00000087
example.de  basler wohnmobilversicherung    8   basler  3,86    0,00003217
example.de  bergungskosten unfallversicherung   37  non brand   0,810810811 0,00000676
example.de  berufsunfähigkeitsversicherung bei bürojob  84  non brand   0,238095238 0,00000198
example.de  berufsunfähigkeitsversicherung bürojob  83  non brand   1,084337349 0,00000904
example.de  betriebshaftpflicht für hausmeisterservice  87  non brand   0,114942529 0,00000096
example.de  betriebshaftpflicht für hausverwalter   29  non brand   1,034482759 0,00000862
example.de  betriebshaftpflicht hausmeister 87  non brand   0,114942529 0,00000096
example.de  betriebshaftpflicht hausverwalter   26  non brand   0,384615385 0,00000321
example.de  betriebsunterbrechungsversicherung freiberufler 46  non brand   0,217391304 0,00000181
example.de  braucht eine krankenschwester eine diensthaftpflichtversicherung    15  non brand   2,706666667 0,00002256
example.de  campingfahrzeug versicherung    39  non brand   1,025641026 0,00000855
example.de  dienst haftpflicht  99  non brand   0,303030303 0,00000253
example.de  diensthaftpflicht öffentlicher dienst   55  non brand   0,545454545 0,00000455
example.de  diensthaftpflichtversicherung   57  non brand   22,80701754 0,00019006
example.de  dienst haftpflichtversicherung  84  non brand   0,238095238 0,00000198
example.de  diensthaftpflichtversicherung beamte    90  non brand   0,555555556 0,00000463
example.de  diensthaftpflichtversicherung für soldaten  28  non brand   0,357142857 0,00000298
example.de  diensthaftpflichtversicherung kosten    80  non brand   0,5 0,00000417
example.de  diensthaftpflichtversicherung öffentlicher dienst   51  non brand   0,980392157 0,00000817
example.de  diensthaftpflichtversicherung öffentlicher dienst angestellte   63  non brand   0,158730159 0,00000132
example.de  diensthaftpflichtversicherung polizei   69  non brand   0,724637681 0,00000604
example.de  diensthaftpflichtversicherung soldaten  26  non brand   0,769230769 0,00000641
example.de  einbauküche hausrat oder gebäude scheidung  31  non brand   0,64516129  0,00000538
example.de  einbauküche hausratversicherung oder gebäudeversicherung    12  non brand   2,643333333 0,00002203


问:
Group Products by Brand then by Category - linq
There is three table:

```<code>Brand                               Category
-----------------------          --------------------------------
BrandID     BrandName             CategoryID        CategoryName
-----------------------          --------------------------------
1           Brand1                    1             cat1
2           Brand2                    2             cat2

Product
------------------------------------------------------------
ProductID       BrandID      CategoryID    ProductName
------------------------------------------------------------
1                 1             1          Product1
2                 1             1          Product2
3                 1             2          Product3
4                 2             1          Product4
</code>```

I want to write Llinq query to get output like below:

```<code>Brand1
|__ cat1
|   |__ Product1
|   |__ Product2
|
|__ Cat2
|   |__ Product3
|
|__ Brand2
|__ cat1
|   |__ Product4
</code>```

I Wrote this query to get Product group by Category:

```<code>    var query2 = db.Brands
        .GroupBy(x => new { x.BrandID, x.BrandName })
                    .Select(x => new
                    {
                        x.Key.BrandID,
                        x.Key.BrandName,
                        ProductsNames = db.Products
                                            .Where(p => p.BrandID == x.Key.BrandID)
                                            .Select(p => p.ProductName).ToList()
                    }).ToList();
</code>```

How can Group Products by Brand then by Category?

答:
I wrote a little console program:

```<code>class Program
{
    static void Main(string[] args)
    {
        var products = new List<Product>{
            new Product { ProductID = 1, BrandID = 1, CategoryID = 1, ProductName = "Product1" },
            new Product { ProductID = 2, BrandID = 1, CategoryID = 1, ProductName = "Product2" },
            new Product { ProductID = 3, BrandID = 1, CategoryID = 2, ProductName = "Product3" },
            new Product { ProductID = 4, BrandID = 2, CategoryID = 1, ProductName = "Product4" }
        };
        var groupedByBrand =
            products
                .GroupBy(p => p.BrandID)
                .Select(g => g.GroupBy(p => p.CategoryID));
        foreach (var groupByBrand in groupedByBrand)
            foreach (var groupByCategory in groupByBrand)
                foreach (var product in groupByCategory)
                    Console.WriteLine($"{product.BrandID} - {product.ProductName}");
    }
}

public class Product
{
    public int ProductID { get; internal set; }
    public int BrandID { get; internal set; }
    public int CategoryID { get; internal set; }
    public string ProductName { get; internal set; }
}
</code>```

I grouped by BrandId and then inside this group grouped by categoryId.

If it is just about the grouping you can use the BrandID and CategoryID and don't even need to join the tables. if you want to sort by name then of course you need to join.

Maybe you wanted to do some sorting on top of / instead of grouping?

Body:
There is three table:

Brand                               Category
-----------------------          --------------------------------
BrandID     BrandName             CategoryID        CategoryName
-----------------------          --------------------------------
1           Brand1                    1             cat1
2           Brand2                    2             cat2

Product
------------------------------------------------------------
ProductID       BrandID      CategoryID    ProductName
------------------------------------------------------------
1                 1             1          Product1
2                 1             1          Product2
3                 1             2          Product3
4                 2             1          Product4

I want to write Llinq query to get output like below:

Brand1
|__ cat1
|   |__ Product1
|   |__ Product2
|
|__ Cat2
|   |__ Product3
|
|__ Brand2
|__ cat1
|   |__ Product4

I Wrote this query to get Product group by Category:

    var query2 = db.Brands
        .GroupBy(x => new { x.BrandID, x.BrandName })
                    .Select(x => new
                    {
                        x.Key.BrandID,
                        x.Key.BrandName,
                        ProductsNames = db.Products
                                            .Where(p => p.BrandID == x.Key.BrandID)
                                            .Select(p => p.ProductName).ToList()
                    }).ToList();

How can Group Products by Brand then by Category?

Body:
I wrote a little console program:

class Program
{
    static void Main(string[] args)
    {
        var products = new List<Product>{
            new Product { ProductID = 1, BrandID = 1, CategoryID = 1, ProductName = "Product1" },
            new Product { ProductID = 2, BrandID = 1, CategoryID = 1, ProductName = "Product2" },
            new Product { ProductID = 3, BrandID = 1, CategoryID = 2, ProductName = "Product3" },
            new Product { ProductID = 4, BrandID = 2, CategoryID = 1, ProductName = "Product4" }
        };
        var groupedByBrand =
            products
                .GroupBy(p => p.BrandID)
                .Select(g => g.GroupBy(p => p.CategoryID));
        foreach (var groupByBrand in groupedByBrand)
            foreach (var groupByCategory in groupByBrand)
                foreach (var product in groupByCategory)
                    Console.WriteLine($"{product.BrandID} - {product.ProductName}");
    }
}

public class Product
{
    public int ProductID { get; internal set; }
    public int BrandID { get; internal set; }
    public int CategoryID { get; internal set; }
    public string ProductName { get; internal set; }
}

I grouped by BrandId and then inside this group grouped by categoryId.

If it is just about the grouping you can use the BrandID and CategoryID and don't even need to join the tables. if you want to sort by name then of course you need to join.

Maybe you wanted to do some sorting on top of / instead of grouping?


问:
Two expressions to get an answer (If X = Y and A = B then the answer is D)
Struggling on what should be a simple expression Google Sheets: Two expressions to get an answer (If X = Y and A = B then the answer is D)

You can see copy of the doc here.
https://docs.google.com/spreadsheets/d/1ufFZfXQb0st4bWP_fcw50FKZSx-tRL58ELTClLsIMQs/edit?usp=sharing

答:
You need to combine an if statement with an and operator, e.g.:

=IF(AND(A13="BMW", B13="SUV"), B17, "Not defined")


问:
How to access storyboard items without @IBOutlets?
I am currently working in a IOS app where I have created a storyboard and some viewControllers.

Because many of the areas are similar I choose to create a generic viewController and then populate it with a controller that extends UIViewController.

Since I cannot add two different classes to a viewController in interface builder, I cannot link the viewController to two different controllers.

What would be the best way to accomplish such task?

Having a  controller linked with the storyboard viewController  and this controller handles every view that needs to be instantiated?

答:
You can always use tags in Interface Builder for your controls.

For instance, let say you set a label with a tag of 100, and a button with a tag of 110.

```<code>var label : UILabel! { view.viewWithTag(100) as? UILabel }
var button : UIButton! { view.viewWithTag(110) as? UIButton }
</code>```

So now, you can do things like:

```<code>label.text = "Yeppee!"
</code>```

Body:
You can always use tags in Interface Builder for your controls.

For instance, let say you set a label with a tag of 100, and a button with a tag of 110.

var label : UILabel! { view.viewWithTag(100) as? UILabel }
var button : UIButton! { view.viewWithTag(110) as? UIButton }

So now, you can do things like:

label.text = "Yeppee!"


问:
Training accuracy is less than validation accuracy
I have created a CNN model for classifying text data. Please help me interpret my result and tell me why is my training accuracy less than validation accuracy?

I have a total of 2619 Data, all of them are text data. There are two different classes. Here is a sample of my dataset.

The validation set has 34 data. Rest of 2619 data are training data.

I have done RepeatedKfold cross-validation. Here is my code.

```<code>from sklearn.model_selection import RepeatedKFold
kf = RepeatedKFold(n_splits=75, n_repeats=1, random_state= 42)

for train_index, test_index in kf.split(X,Y):
      #print("Train:", train_index, "Validation:",test_index)
      x_train, x_test = X.iloc[train_index], X.iloc[test_index]
      y_train, y_test = Y.iloc[train_index], Y.iloc[test_index]
</code>```

I have used CNN. Here is my model.

```<code>model = Sequential()
model.add(Embedding(2900,2 , input_length=1))
model.add(Conv1D(filters=2, kernel_size=3, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), activation='sigmoid'))
model.add(Dropout(0.25))
adam = optimizers.Adam(lr = 0.0005, beta_1 = 0.9, beta_2 = 0.999, epsilon = None, decay = 0.0, amsgrad = False)
model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
print(model.summary())
history = model.fit(x_train, y_train, epochs=300,validation_data=(x_test, y_test), batch_size=128, shuffle=False)
# Final evaluation of the model
scores = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))
</code>```

And here is the result.

```<code>Epoch 295/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6920 - acc: 0.7528 - val_loss: 0.5839 - val_acc: 0.8235
Epoch 296/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6532 - acc: 0.7617 - val_loss: 0.5836 - val_acc: 0.8235
Epoch 297/300
2585/2585 [==============================] - 0s 27us/step - loss: 1.5328 - acc: 0.7551 - val_loss: 0.5954 - val_acc: 0.8235
Epoch 298/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6289 - acc: 0.7524 - val_loss: 0.5897 - val_acc: 0.8235
Epoch 299/300
2585/2585 [==============================] - 0s 21us/step - loss: 1.7000 - acc: 0.7582 - val_loss: 0.5854 - val_acc: 0.8235
Epoch 300/300
2585/2585 [==============================] - 0s 25us/step - loss: 1.5475 - acc: 0.7451 - val_loss: 0.5934 - val_acc: 0.8235
Accuracy: 82.35%
</code>```

Please help me with my problem. Thank you.

答:
You may have too much regularization for your model causing it to underfit your data.

A good way to start is begin with no regularization at all (no Dropout, no weights decay, ..) and look if it's overfitting:

If not, regularization is useless

If it's overfitting, add regularization little by little, start by small dropout / weights decay, and then icrease it if it's continue to overfit

Moroever, don't put Dropout as final layer, and don't put two Dropout layers successively.

Body:
I have created a CNN model for classifying text data. Please help me interpret my result and tell me why is my training accuracy less than validation accuracy?

I have a total of 2619 Data, all of them are text data. There are two different classes. Here is a sample of my dataset.

The validation set has 34 data. Rest of 2619 data are training data.

I have done RepeatedKfold cross-validation. Here is my code.

from sklearn.model_selection import RepeatedKFold
kf = RepeatedKFold(n_splits=75, n_repeats=1, random_state= 42)

for train_index, test_index in kf.split(X,Y):
      #print("Train:", train_index, "Validation:",test_index)
      x_train, x_test = X.iloc[train_index], X.iloc[test_index]
      y_train, y_test = Y.iloc[train_index], Y.iloc[test_index]

I have used CNN. Here is my model.

model = Sequential()
model.add(Embedding(2900,2 , input_length=1))
model.add(Conv1D(filters=2, kernel_size=3, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), padding='same', activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.3))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1, kernel_regularizer=l2(0.0005 ), bias_regularizer=l2(0.0005 ), activation='sigmoid'))
model.add(Dropout(0.25))
adam = optimizers.Adam(lr = 0.0005, beta_1 = 0.9, beta_2 = 0.999, epsilon = None, decay = 0.0, amsgrad = False)
model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy'])
print(model.summary())
history = model.fit(x_train, y_train, epochs=300,validation_data=(x_test, y_test), batch_size=128, shuffle=False)
# Final evaluation of the model
scores = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: %.2f%%" % (scores[1]*100))

And here is the result.

Epoch 295/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6920 - acc: 0.7528 - val_loss: 0.5839 - val_acc: 0.8235
Epoch 296/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6532 - acc: 0.7617 - val_loss: 0.5836 - val_acc: 0.8235
Epoch 297/300
2585/2585 [==============================] - 0s 27us/step - loss: 1.5328 - acc: 0.7551 - val_loss: 0.5954 - val_acc: 0.8235
Epoch 298/300
2585/2585 [==============================] - 0s 20us/step - loss: 1.6289 - acc: 0.7524 - val_loss: 0.5897 - val_acc: 0.8235
Epoch 299/300
2585/2585 [==============================] - 0s 21us/step - loss: 1.7000 - acc: 0.7582 - val_loss: 0.5854 - val_acc: 0.8235
Epoch 300/300
2585/2585 [==============================] - 0s 25us/step - loss: 1.5475 - acc: 0.7451 - val_loss: 0.5934 - val_acc: 0.8235
Accuracy: 82.35%

Please help me with my problem. Thank you.


问:
mongodb schema design for ProductSchema and ReviewSchema
I have two collections: product & review
I initially decided not to nest reviews in product schema because the number of reviews can get quite large. And I also need to query reviews independently for the admins to see.

When a user visits the product page, I can "join" the product and corresponding recent twenty reviews(pagination, 20 per page for example) in the backend server and return it to the client. Now this is an "sql" like method and it works totally fine.

But then I thought, how about only nesting the recent twenty reviews. These nested reviews will also be stored as individual review documents. Now this causes twenty duplications and more updates. But products & reviews are more read intensive, and this way could reduce the read speed almost by half. (Instead of two database requests, we only have single request)

Please share your opinions. Thanks!

答:
Saving review references inside the products collection will cause an update to the product document everytime a new review is made for the that document. Also products will have lots of other fields, so there is no need to make it have more fields.

I would suggest parent referencing here. There will be no reviews references inside the products collection, but we will keep product reference inside the review collection. When a review is made for a product, we just need a simple insert inside the reviews collection.

We also need to think about the user who makes a review for the product. So we need to keep a user reference inside the review collection.

Let me show some sample  documents for these collections:

products:

```<code>{
    "_id" : ObjectId("5e4bdffb09d2675c3cdf8371"),
    "name" : "Product1",
    "price" : 1
}
</code>```

users:

```<code>{
    "_id" : ObjectId("5e4bdfa809d2675c3cdf8370"),
    "username" : "User1",
}
</code>```

reviews: (User1 made a review for Product1)

```<code>{
  "_id": ObjectId("5e4be86809d2675c3cdf8387"),
  "reviewDate": ISODate("2020-02-18T15:51:22.584+03:00"),
  "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
  "user": ObjectId("5e4be85d09d2675c3cdf8386"),
  "score": 5
}
</code>```

And we can read the product info and it's reviews and the user of the review in one db access using mongodb aggregation framework. So it is not a big issue.

For example: Playground

db.products.aggregate([
  {
    $match: {
      _id: ObjectId("5e4bdffb09d2675c3cdf8371")
    }
  },
  {
    $lookup: {
      from: "reviews",
      localField: "_id",
      foreignField: "product",
      as: "reviews"
    }
  },
  {
    $unwind: "$reviews"
  },
  {
    $sort: {
      "reviews.reviewDate": -1
    }
  },
  {
    $lookup: {
      from: "users",
      localField: "reviews.user",
      foreignField: "_id",
      as: "user"
    }
  },
  {
    $addFields: {
      "reviews.user": {
        $arrayElemAt: [
          "$user",
          0
        ]
      }
    }
  },
  {
    $project: {
      user: 0
    }
  },
  {
    $group: {
      _id: "$_id",
      reviews: {
        "$push": "$reviews"
      },
      "doc": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$doc",
          {
            "reviews": "$reviews"
          }
        ]
      }
    }
  }
])
```

<p>This will give a result in the following way:</p>

```[
  {
    "_id": ObjectId("5e4bdffb09d2675c3cdf8371"),
    "name": "Product1",
    "price": 1,
    "reviews": [
      {
        "_id": ObjectId("5e4be83b09d2675c3cdf8381"),
        "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
        "reviewDate": ISODate("2020-02-18T16:15:22.584Z"),
        "score": 2,
        "user": {
          "_id": ObjectId("5e4be83009d2675c3cdf8380"),
          "username": "User8"
        }
      },
      {
        "_id": ObjectId("5e4be09709d2675c3cdf8375"),
        "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
        "reviewDate": ISODate("2020-02-18T15:02:22.584Z"),
        "score": 4,
        "user": {
          "_id": ObjectId("5e4be08b09d2675c3cdf8374"),
          "username": "User2"
        }
      },
      {
        "_id": ObjectId("5e4be84b09d2675c3cdf8383"),
        "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
        "reviewDate": ISODate("2020-02-18T14:08:22.584Z"),
        "score": 3,
        "user": {
          "_id": ObjectId("5e4be84109d2675c3cdf8382"),
          "username": "User9"
        }
      },
    ...
    ]
  }
]
```

With this, when you open a GET api for the product detail page, this will contain all the information you will need.

Body:
Saving review references inside the products collection will cause an update to the product document everytime a new review is made for the that document. Also products will have lots of other fields, so there is no need to make it have more fields.

I would suggest parent referencing here. There will be no reviews references inside the products collection, but we will keep product reference inside the review collection. When a review is made for a product, we just need a simple insert inside the reviews collection.

We also need to think about the user who makes a review for the product. So we need to keep a user reference inside the review collection.

Let me show some sample  documents for these collections:

products:

{
    "_id" : ObjectId("5e4bdffb09d2675c3cdf8371"),
    "name" : "Product1",
    "price" : 1
}

users:

{
    "_id" : ObjectId("5e4bdfa809d2675c3cdf8370"),
    "username" : "User1",
}

reviews: (User1 made a review for Product1)

{
  "_id": ObjectId("5e4be86809d2675c3cdf8387"),
  "reviewDate": ISODate("2020-02-18T15:51:22.584+03:00"),
  "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
  "user": ObjectId("5e4be85d09d2675c3cdf8386"),
  "score": 5
}

And we can read the product info and it's reviews and the user of the review in one db access using mongodb aggregation framework. So it is not a big issue.

For example: Playground

db.products.aggregate([
  {
    $match: {
      _id: ObjectId("5e4bdffb09d2675c3cdf8371")
    }
  },
  {
    $lookup: {
      from: "reviews",
      localField: "_id",
      foreignField: "product",
      as: "reviews"
    }
  },
  {
    $unwind: "$reviews"
  },
  {
    $sort: {
      "reviews.reviewDate": -1
    }
  },
  {
    $lookup: {
      from: "users",
      localField: "reviews.user",
      foreignField: "_id",
      as: "user"
    }
  },
  {
    $addFields: {
      "reviews.user": {
        $arrayElemAt: [
          "$user",
          0
        ]
      }
    }
  },
  {
    $project: {
      user: 0
    }
  },
  {
    $group: {
      _id: "$_id",
      reviews: {
        "$push": "$reviews"
      },
      "doc": {
        "$first": "$$ROOT"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          "$doc",
          {
            "reviews": "$reviews"
          }
        ]
      }
    }
  }
])

This will give a result in the following way:

[
  {
    "_id": ObjectId("5e4bdffb09d2675c3cdf8371"),
    "name": "Product1",
    "price": 1,
    "reviews": [
      {
        "_id": ObjectId("5e4be83b09d2675c3cdf8381"),
        "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
        "reviewDate": ISODate("2020-02-18T16:15:22.584Z"),
        "score": 2,
        "user": {
          "_id": ObjectId("5e4be83009d2675c3cdf8380"),
          "username": "User8"
        }
      },
      {
        "_id": ObjectId("5e4be09709d2675c3cdf8375"),
        "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
        "reviewDate": ISODate("2020-02-18T15:02:22.584Z"),
        "score": 4,
        "user": {
          "_id": ObjectId("5e4be08b09d2675c3cdf8374"),
          "username": "User2"
        }
      },
      {
        "_id": ObjectId("5e4be84b09d2675c3cdf8383"),
        "product": ObjectId("5e4bdffb09d2675c3cdf8371"),
        "reviewDate": ISODate("2020-02-18T14:08:22.584Z"),
        "score": 3,
        "user": {
          "_id": ObjectId("5e4be84109d2675c3cdf8382"),
          "username": "User9"
        }
      },
    ...
    ]
  }
]

With this, when you open a GET api for the product detail page, this will contain all the information you will need.


问:
How can i transpose csv data using java spark
I am using java spark and i want to know if there is anyway i can transform the sample data given below

```<code>Incremental Cost Number | Approver Names
---------------------------------------------------------------------------------
S703401                  |Ryan P Cassidy|Christopher J Mattingly|Frank E
                         LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason Monte
</code>```

into something like this.

```<code>Incremental Cost Number| Approver Names
-------------------------------------------
S703401                | Ryan P Cassidy
S703401                | Christopher J Mattingly
S703401                | Frank E LaSota
S703401                | Ryan P Cassidy
S703401                | Anthony L Locricchio
S703401                | Jason Monte
</code>```

Also the file i am importing is a comma separated csv file, just that a particular column contains multiple values are separated by pipeline symbol. And similarly if i have multiple values of Incremental Cost Number.

答:
I think you need split the second column by "|" and then use explode() function</p>

```<code>df.select(col("id"), explode(split(col("a"), "\\|")).as("a")).show()

+-------+--------------------+
|     id|                   a|
+-------+--------------------+
|S703401|      Ryan P Cassidy|
|S703401|Christopher J Mat...|
|S703401|             Frank E|
</code>```

Body:
I am using java spark and i want to know if there is anyway i can transform the sample data given below

Incremental Cost Number | Approver Names
---------------------------------------------------------------------------------
S703401                  |Ryan P Cassidy|Christopher J Mattingly|Frank E
                         LaSota|Ryan P Cassidy|Anthony L Locricchio|Jason Monte

into something like this.

Incremental Cost Number| Approver Names
-------------------------------------------
S703401                | Ryan P Cassidy
S703401                | Christopher J Mattingly
S703401                | Frank E LaSota
S703401                | Ryan P Cassidy
S703401                | Anthony L Locricchio
S703401                | Jason Monte

Also the file i am importing is a comma separated csv file, just that a particular column contains multiple values are separated by pipeline symbol. And similarly if i have multiple values of Incremental Cost Number.

Body:
I think you need split the second column by "|" and then use explode() function

df.select(col("id"), explode(split(col("a"), "\\|")).as("a")).show()

+-------+--------------------+
|     id|                   a|
+-------+--------------------+
|S703401|      Ryan P Cassidy|
|S703401|Christopher J Mat...|
|S703401|             Frank E|


问:
Attach CSS triangle to MatTooltip depending on actual positioning?
I've been wrecking my brain to figure out a way to attach a little CSS triangle to a MatTooltip in Angular that switches from being at the top when the tooltip is displayed below the host element (default) to being at the bottom when the tooltip is above the host element (e.g. when the host element is too close to the bottom of the viewport).

Am I missing some property that would give me a way to switch the CSS
  class? Or is it simply impossible?

Any help would be highly appreciated.

答:
It is possible.

Since MatTooltip controls its positioning via transform-origin, you can make use of it.

For example, .mat-tooltip[style*="transform-origin: left center"] only selects tooltips shown to the right of its parent, so you can display the triangle on the left side of the tooltip.

Values of transform-origin:

Tooltip to the right of its parent: left center

Tooltip to the left of its parent: right center

Tooltip above its parent: center top

Tooltip below its parent: center bottom


问:
Can AWS Lambda be used as the backend for getstream.io?
I didn't find any posts related to this topic. It seems natural to use Lambda as a getstream backend, but I'm not sure if it heavily depends on persistent connections or other architectural choices that would rule it out. Is it a sensible approach? Has anyone made it work? Any advice?</p>

答:
Yes, you can use AWS Lambda as backend and integrate with Stream API there.

Building an entire application on Lambda directly is going to be very complex and requires writing lot of boiler plate code just to enforce some basic organization and structure to your project.

My recommendation is use a serverless framework to do this that takes care of keeping your application well organized and to deploy new versions (and environments).

Serverless is a good option for that: https://serverless.com/framework/docs/providers/aws/guide/intro/


问:
Accessing $_POST data sent by Jquery/AJAX
I am using this function:

```<code>function end_incident() {
    var dataString = 'name=Daniel&phone=01234123456';
    $.ajax({
        type: "POST",
        url: "http://www.example.co.uk/erc/end_incident.php",
        data: dataString,
        success: function(msg){
            alert('Success!'+dataString);
        }
    });
};
</code>```

to send information to end_incident.php, but I'm not able to access the $_POST variables. I've tried doing it like this:

```<code>$name = $_POST['name'];
$phone = $_POST['phone'];
</code>```

Am I doing something wrong?

Thanks for any help

答:
Make sure the url your requesting for is within the same origin of your site, if it isn't, you've got a cross-site scripting issue. Only way around that:

Getting "higher" access/priveledges within the browser, i.e. create an add-on/extension, or use Greasemonkey

Use a proxy through your own site to get the request for the file:

```<code>var getURL = "http://www.example.co.uk/erc/end_incident.php";
$.ajax({
   type: "POST",
   url: "/get_url.php?url=" + encodeURIComponent(getURL),
   data: { name: "Daniel", phone: "01234123456" },
   success: function(msg){
       alert('Success!');
   }
});
</code>```

I recommend you add a error function to your ajax. It's suprising how many people just focus on success and never process an error!

```<code>error: function()
{
   console.log(arguments);
}
</code>```

Body:
I am using this function:

function end_incident() {
    var dataString = 'name=Daniel&phone=01234123456';
    $.ajax({
        type: "POST",
        url: "http://www.example.co.uk/erc/end_incident.php",
        data: dataString,
        success: function(msg){
            alert('Success!'+dataString);
        }
    });
};

to send information to end_incident.php, but I'm not able to access the $_POST variables. I've tried doing it like this:

$name = $_POST['name'];
$phone = $_POST['phone'];

Am I doing something wrong?

Thanks for any help

Body:
Make sure the url your requesting for is within the same origin of your site, if it isn't, you've got a cross-site scripting issue. Only way around that:

Getting "higher" access/priveledges within the browser, i.e. create an add-on/extension, or use Greasemonkey

Use a proxy through your own site to get the request for the file:

var getURL = "http://www.example.co.uk/erc/end_incident.php";
$.ajax({
   type: "POST",
   url: "/get_url.php?url=" + encodeURIComponent(getURL),
   data: { name: "Daniel", phone: "01234123456" },
   success: function(msg){
       alert('Success!');
   }
});

I recommend you add a error function to your ajax. It's suprising how many people just focus on success and never process an error!

error: function()
{
   console.log(arguments);
}


问:
How to define Opacity by percentage in CSS?
Is it possible to define opacity in CSS by percentage (eg 30%) in CSS? does not seem to be working, right now I can only conduct it by decimal point.

https://css-tricks.com/almanac/properties/o/opacity/

```<code>.test{
   opacity: 0.3;
}
</code>```

Intended Goal:

```<code>.test{
   opacity: 30%;
}
</code>```

答:
Using a percentage is fully valid css, according to the spec:
https://developer.mozilla.org/en-US/docs/Web/CSS/opacity#Values

alpha-value
      A number in the range 0.0 to 1.0, inclusive, or a percentage in the range 0% to 100%, inclusive, representing the opacity of the channel (that is, the value of its alpha channel). Any value outside the interval, though valid, is clamped to the nearest limit in the range.

So, either of these should be okay, according to spec:

.foo {
  opacity: .3;
}

.foo {
  opacity: 30%;
}
```

Keep in mind, though, that if you are using Sass, it will not handle the percentage value, and will compile it to 1%.

Body:
Is it possible to define opacity in CSS by percentage (eg 30%) in CSS? does not seem to be working, right now I can only conduct it by decimal point.

https://css-tricks.com/almanac/properties/o/opacity/

.test{
   opacity: 0.3;
}

Intended Goal:

.test{
   opacity: 30%;
}

Body:
Using a percentage is fully valid css, according to the spec:
https://developer.mozilla.org/en-US/docs/Web/CSS/opacity#Values

alpha-value
      A number in the range 0.0 to 1.0, inclusive, or a percentage in the range 0% to 100%, inclusive, representing the opacity of the channel (that is, the value of its alpha channel). Any value outside the interval, though valid, is clamped to the nearest limit in the range.

So, either of these should be okay, according to spec:

.foo {
  opacity: .3;
}

.foo {
  opacity: 30%;
}

Keep in mind, though, that if you are using Sass, it will not handle the percentage value, and will compile it to 1%.


问:
Func with interface argument not equals to func with string argument. Why?
I cant understand whats the problem.
Here is sample code:

type InterfaceFunction func(i interface{})
func main() {
    var notOk InterfaceFunction = func(s string){}
    var ok InterfaceFunction = func(i interface{}){}
}
```

答:
Because the types aren't the same. Imagine this:

```<code>type InterfaceFunction func(i interface{})

func main() {
    var notOk InterfaceFunction = func(s string){}
    myFunc(InterfaceFunction(notOk))    // This can't possibly work!
}

func myFunc(fn InterfaceFunction) {
    x := 17
    fn(x)   // This is legal, because InterfaceFunction takes an interface{}
}
</code>```

Our myFunc here takes an InterfaceFunction, which, by definition, takes any interface{} as its argument. myFunc can pass it anything it wants. If we were allowed to use a func(string) as a func(interface{}) here, myFunc would no longer have compile-time type-safety: it would be passing an int to a function that takes a string.

Body:
Because the types aren't the same. Imagine this:

type InterfaceFunction func(i interface{})

func main() {
    var notOk InterfaceFunction = func(s string){}
    myFunc(InterfaceFunction(notOk))    // This can't possibly work!
}

func myFunc(fn InterfaceFunction) {
    x := 17
    fn(x)   // This is legal, because InterfaceFunction takes an interface{}
}

Our myFunc here takes an InterfaceFunction, which, by definition, takes any interface{} as its argument. myFunc can pass it anything it wants. If we were allowed to use a func(string) as a func(interface{}) here, myFunc would no longer have compile-time type-safety: it would be passing an int to a function that takes a string.


问:
How to make a countdown timer in Android?
I have two EditTexts in XML. In one EditText, the user can put a number as minutes and in another EditText, a number as seconds. After clicking the finish button, the seconds EditText should start to countdown and update its text every second.

Additionally, how can I keep it updating until it gets to zero minutes and zero seconds?

答:
Output: 01:30</p>
```<code>new CountDownTimer(90000, 1000) {

            public void onTick(long duration) {
                //tTimer.setText("seconds remaining: " + millisUntilFinished / 1000);
                //here you can have your logic to set text to edittext resource id
                // Duration
                long Mmin = (duration / 1000) / 60;
                long Ssec = (duration / 1000) % 60;
                if (Ssec < 10) {
                    tTimer.setText("" + Mmin + ":0" + Ssec);
                } else tTimer.setText("" + Mmin + ":" + Ssec);
            }

            public void onFinish() {
                tTimer.setText("00:00");
            }

        }.start();
</code>```

Body:
Output: 01:30

new CountDownTimer(90000, 1000) {

            public void onTick(long duration) {
                //tTimer.setText("seconds remaining: " + millisUntilFinished / 1000);
                //here you can have your logic to set text to edittext resource id
                // Duration
                long Mmin = (duration / 1000) / 60;
                long Ssec = (duration / 1000) % 60;
                if (Ssec < 10) {
                    tTimer.setText("" + Mmin + ":0" + Ssec);
                } else tTimer.setText("" + Mmin + ":" + Ssec);
            }

            public void onFinish() {
                tTimer.setText("00:00");
            }

        }.start();


问:
IndexError: list index out of range when no argument is supplied
I just want to know why this code is generating IndexError: list index out of range when no argument supplied to it?

script.py

```<code>import sys
a = sys.argv[1]
print(a)
</code>```

Sample output with argument/s

```<code>user@linux:~$ python3 script.py abc
abc
user@linux:~$ python3 script.py abc def
abc
user@linux:~$
</code>```

Sample output without argument/s

```<code>user@linux:~$ python3 script.py
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = sys.argv[1]
IndexError: list index out of range
user@linux:~$
</code>```

My reference: https://www.pythonforbeginners.com/system/python-sys-argv

答:
From the python docs sys.argv returns:

The list of command line arguments passed to a Python script. argv[0]
is the script name (it is operating system dependent whether this is a
full pathname or not).

The problem is that when you run your script without arguments like python3 script.py, you are trying to access the element at index 1 by using sys.argv[1] but in fact this element doesn't even exists in the list.
Therefore, The python interpreter throws an IndexError.

Body:
I just want to know why this code is generating IndexError: list index out of range when no argument supplied to it?

script.py

import sys
a = sys.argv[1]
print(a)

Sample output with argument/s

user@linux:~$ python3 script.py abc
abc
user@linux:~$ python3 script.py abc def
abc
user@linux:~$

Sample output without argument/s

user@linux:~$ python3 script.py
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = sys.argv[1]
IndexError: list index out of range
user@linux:~$

My reference: https://www.pythonforbeginners.com/system/python-sys-argv


问:
JavaScript array of pointers like in C++
I'm faced with a situation in JavaScript when I need to update an object via its pointer similar to С++ array of pointers to objects

Example code for my issue:

var foo = new Array();
var bar = function(){
    this.test = 1;
    foo.push(this); // push an object (or a copy of object?) but not pointer
};
var barInst = new bar(); // create new instance
// foo[0].test equals 1
barInst.test = 2;
// now barInst.test equals 2 but
// foo[0].test still equals 1 but 2 is needed
```

So, how can I solve this? Should I use a callback or something like this or there is an easy way to help me to avoid copying the object instead pushing the raw pointer into an array?

答:
JS is pass-by-value, so your original assignment was this.test = the value of 1, in my example, it's this.test = the object pointed to by ptr, so when I change ptr this.test changes as well.

```<code>var foo = [],
    ptr = {val: 1},
    bar = function(){
       this.test = ptr;
       foo.push(this); // push an object (or a copy of object?) but not pointer
    },
    barInst = new bar(); // create new instance
    // foo[0].test.val equals 1
    ptr.val = 2;
    // foo[0].test.val equals 2
</code>```

Although if you thought that foo.push(this); was similar, it isn't. Since this is an object, the array will indeed contain "raw pointers" to objects, just like you want. You can prove this simply:

```<code>foo[0].test = 3;
// barInst.test === 3
</code>```

Which shows that it is indeed a pointer to the object that was pushed onto the array

Body:
I'm faced with a situation in JavaScript when I need to update an object via its pointer similar to С++ array of pointers to objects

Example code for my issue:

var foo = new Array();
var bar = function(){
    this.test = 1;
    foo.push(this); // push an object (or a copy of object?) but not pointer
};
var barInst = new bar(); // create new instance
// foo[0].test equals 1
barInst.test = 2;
// now barInst.test equals 2 but
// foo[0].test still equals 1 but 2 is needed

So, how can I solve this? Should I use a callback or something like this or there is an easy way to help me to avoid copying the object instead pushing the raw pointer into an array?

Body:
JS is pass-by-value, so your original assignment was this.test = the value of 1, in my example, it's this.test = the object pointed to by ptr, so when I change ptr this.test changes as well.

var foo = [],
    ptr = {val: 1},
    bar = function(){
       this.test = ptr;
       foo.push(this); // push an object (or a copy of object?) but not pointer
    },
    barInst = new bar(); // create new instance
    // foo[0].test.val equals 1
    ptr.val = 2;
    // foo[0].test.val equals 2

Although if you thought that foo.push(this); was similar, it isn't. Since this is an object, the array will indeed contain "raw pointers" to objects, just like you want. You can prove this simply:

foo[0].test = 3;
// barInst.test === 3

Which shows that it is indeed a pointer to the object that was pushed onto the array


问:
Nativescript: ITMS-90535: Unexpected CFBundleExecutable Key
After I run tns publish ios --release apple connect showed me that my build is invalid. I got a mail with this error:

ITMS-90535: Unexpected CFBundleExecutable Key - The bundle at '/Payload/MyApp.app/app/App_Resources/iOS/Info.plist' does not contain a bundle executable.
  If this bundle intentionally does not contain an executable, consider removing the CFBundleExecutable key from its Info.plist and using a CFBundlePackageType of BNDL.
  If this bundle is part of a third-party framework, consider contacting the developer of the framework for an update to address this issue.

I found a similar post here.
The solution was

```<code>tns platform remove ios
tns platform add ios
</code>```

however, that did not help.

Update:
I updated my Nativescript CLI to 6.4 and run the tns publish ios --release --clean command again. I got the same error mail. But AppStore Connect display a other error message:

ITC.apps.preReleaseBuild.errors.invalidBinary

答: I have experienced that sometimes you must follow up with tns build your_platform, additionally, add --clean if you haven't recently removed/added the platform.

Body:
After I run tns publish ios --release apple connect showed me that my build is invalid. I got a mail with this error:

ITMS-90535: Unexpected CFBundleExecutable Key - The bundle at '/Payload/MyApp.app/app/App_Resources/iOS/Info.plist' does not contain a bundle executable.
  If this bundle intentionally does not contain an executable, consider removing the CFBundleExecutable key from its Info.plist and using a CFBundlePackageType of BNDL.
  If this bundle is part of a third-party framework, consider contacting the developer of the framework for an update to address this issue.

I found a similar post here.
The solution was

tns platform remove ios
tns platform add ios

however, that did not help.

Update:
I updated my Nativescript CLI to 6.4 and run the tns publish ios --release --clean command again. I got the same error mail. But AppStore Connect display a other error message:

ITC.apps.preReleaseBuild.errors.invalidBinary


问:
Problems Installing PostgreSQL 9.2
I've been trying to install the 64bit version of PostgreSQL 9.2 for Windows on my machine (Windows 7 64bit) and get this error:

The environment variable COMPSPEC does not seem to point to the cmd.exe or there is a trailing semi colon present.

I've installed it as Administrator.

I disabled the antivirus (Microsoft Security Essentials) and the firewall.

Running:

```<code>"%COMSPEC%" /C "echo test ok"
</code>```

returned test ok

I've checked my System Environment Variables for trailing semi colon and I couldn't find any.

I then installed the 32bit version and managed to get to the end of the install with a different error message stating: Problem running post-install step. Installation may not complete correctly Error reading the C:\Program Files (x86)\PostgreSQL\9.2\data\postgresql.conf but there is no postgresql.conf file in that directory. It did install the application and when I try to connect the server with the red X on it it says fail at the bottom and it won't connect after I type in my password.

How can I connect to this server connection?

答:
What worked for me after trying to enter the commandline given her in cmd.exe
I found it was named cmd1.exe in system32.. so i copied the file and renamed it as cmd.exe and installation finished</p>

Title: Problems Installing PostgreSQL 9.2

Body:
I've been trying to install the 64bit version of PostgreSQL 9.2 for Windows on my machine (Windows 7 64bit) and get this error:

The environment variable COMPSPEC does not seem to point to the cmd.exe or there is a trailing semi colon present.

I've installed it as Administrator.

I disabled the antivirus (Microsoft Security Essentials) and the firewall.

Running:

"%COMSPEC%" /C "echo test ok"

returned test ok

I've checked my System Environment Variables for trailing semi colon and I couldn't find any.

I then installed the 32bit version and managed to get to the end of the install with a different error message stating: Problem running post-install step. Installation may not complete correctly Error reading the C:\Program Files (x86)\PostgreSQL\9.2\data\postgresql.conf but there is no postgresql.conf file in that directory. It did install the application and when I try to connect the server with the red X on it it says fail at the bottom and it won't connect after I type in my password.

How can I connect to this server connection?


问:
jCarousel - update carousel items without page refresh
I'm using the jCarousel plugin for a small gallery page with the itemloadcallback parameter to dynamically load the items on the carousel.

However, I'm not sure if this is possible, but is there a way by which a carousel instance on a page itself can be removed and recreated with new set of items? I am planning to use a filter (select box) on the page at the onchange of which, I would like to generate a new carousel with the filtered list. Any ideas experts?

Thx in advance.

Za

答: Why don't you put the jCarousel in a div with specific ID (although that's probably how you do it). You only need ajax to load new content. If ajax call succeeds, you can append (or rather just use jquerys' html() function) the necessary structure and invoke jCarousel to that div.</p>


问:
DDD: Lazy loading in aggregates
I've been learning DDD for the past few days and struggling to understand some core concepts of aggregate roots. Maybe somebody could give me push in the right direction and elaborate what's best practice in this scenario:

To make this example less complex, let's say we have a domain of two entities: restaurant and opening time. Restaurant is defined as aggregate root.

From what I understood in all the online examples (correct me if I'm mistaken), the aggregate root is eager loading all sub-entities every time I need an instance of it. So whenever I want to call call a method on the restaurant, all opening times are loaded (no matter if they are used or not).

In this example I want to verify that there is no intersection of opening times when a new time get's added to that restaurant. In this case the eager loading of every other opening time makes sense because I need to compare them with the existing ones.

BUT: this is kind of restricting because I know every time I want to add another collection of something (let's say restaurant images), the SQL load get's heavier and heavier even though most of the methods only require one of the collections.

I could think of two possible solutions:

Lazy loading

Lazy loading opening times / sub entities through entity framework property proxies. So the aggregate root can exist without eager loading them but whenever they are needed they can be accessed.
However everywhere I was searching for an answer I've red that lazy loading in aggregate roots is considered bad practice. Maybe somebody could explain why.

Smaller aggregate roots

Of course I could define the opening time itself as an aggregate root but then I need to take the business logic (in this case the verification of intersections) outside of the model.

In all the examples above I'm only talking about the command side (not querying or serializing).

Maybe I'm missing some fundamental ideas. How should the aggregate roots be organized in this example and why is lazy loading considered bad practice?

EDIT
Not sure why this question was closed because of "opinion based". I'm asking for best practice and why lazy loading is not in this case.

答:
For your question why is lazy loading considered as bad practice:

Some issue I have with lazy loading is that you need to be constantly aware of potential performance issues. On the other hand However LL is a decent default behaviour for ORMs. It is great if you have long term running applications but it is pointless implementing it on top of your services. I think it depends a lot on the data you are using so its neither good or bad.

Title: DDD: Lazy loading in aggregates