问:
How to maintain same permissions on python dist-package after upgrade?
I am using a python package patroni version 1.0 on Ubuntu 14. On doing ls -lrt /usr/local/lib/python2.7/dist-packages/ I am seeing the permission like below

But once I upgrade the patroni via the command sudo pip install patroni --upgrade I am seeing the permission of the patroni changes after upgrade

The installation output is -

```<code>sudo pip install patroni  --upgrade
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Collecting patroni
Requirement already up-to-date: requests in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting cdiff (from patroni)
Requirement already up-to-date: six>=1.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting python-etcd<0.5,>=0.4.3 (from patroni)
Requirement already up-to-date: prettytable>=0.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: tzlocal in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: boto in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting python-consul>=0.7.0 (from patroni)
  Downloading python_consul-0.7.2-py2.py3-none-any.whl
Requirement already up-to-date: psycopg2>=2.6.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: kazoo==2.2.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: urllib3>=1.9 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: click>=4.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: python-dateutil in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting psutil (from patroni)
Requirement already up-to-date: PyYAML in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: certifi>=2017.4.17 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: idna<2.7,>=2.5 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: dnspython>=1.13.0 in /usr/local/lib/python2.7/dist-packages (from python-etcd<0.5,>=0.4.3->patroni)
Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from tzlocal->patroni)
Installing collected packages: cdiff, python-etcd, python-consul, psutil, patroni
  Found existing installation: python-etcd 0.4.3
    Uninstalling python-etcd-0.4.3:
      Successfully uninstalled python-etcd-0.4.3
  Found existing installation: python-consul 0.6.0
    Uninstalling python-consul-0.6.0:
      Successfully uninstalled python-consul-0.6.0
  Found existing installation: patroni 1.0
    Uninstalling patroni-1.0:
      Successfully uninstalled patroni-1.0
Successfully installed cdiff-1.0 patroni-1.3.6 psutil-5.4.1 python-consul-0.7.2 python-etcd-0.4.5
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

I had to use sudo if I do just pip install patroni --upgrade then it is failing with the below error:-

```<code>pip install patroni  --upgrade
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Collecting patroni
  Downloading patroni-1.3.6.tar.gz (90kB)
    100% |████████████████████████████████| 94kB 1.0MB/s
Requirement already up-to-date: urllib3>=1.9 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: boto in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: psycopg2>=2.6.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: PyYAML in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: requests in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: six>=1.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: kazoo==2.2.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting python-etcd<0.5,>=0.4.3 (from patroni)
  Downloading python-etcd-0.4.5.tar.gz
Collecting python-consul>=0.7.0 (from patroni)
  Downloading python_consul-0.7.2-py2.py3-none-any.whl
Requirement already up-to-date: click>=4.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: prettytable>=0.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: tzlocal in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: python-dateutil in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting psutil (from patroni)
  Downloading psutil-5.4.1.tar.gz (408kB)
    100% |████████████████████████████████| 409kB 1.1MB/s
Collecting cdiff (from patroni)
  Downloading cdiff-1.0.tar.gz
Requirement already up-to-date: certifi>=2017.4.17 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: idna<2.7,>=2.5 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: dnspython>=1.13.0 in /usr/local/lib/python2.7/dist-packages (from python-etcd<0.5,>=0.4.3->patroni)
Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from tzlocal->patroni)
Building wheels for collected packages: patroni, python-etcd, psutil, cdiff
  Running setup.py bdist_wheel for patroni
  Stored in directory: /home/ubuntu/.cache/pip/wheels/86/5a/e3/cb4ac4ecf20bc7a2956062d3c3ad15c660a993a0cc3aa23d35
  Running setup.py bdist_wheel for python-etcd
  Stored in directory: /home/ubuntu/.cache/pip/wheels/d1/79/df/26facc508cdb5fefaf3d574fb634d848754a7e69d95f53f056
  Running setup.py bdist_wheel for psutil
  Stored in directory: /home/ubuntu/.cache/pip/wheels/05/a2/2a/2015d6af91fb5a4cc5bcdfa9699034e2f624fc9cc5acde7ab9
  Running setup.py bdist_wheel for cdiff
  Stored in directory: /home/ubuntu/.cache/pip/wheels/d9/67/dc/d53a3cfea638a5652d0d2054b447d67a7d2a2bdebf0f67765e
Successfully built patroni python-etcd psutil cdiff
Installing collected packages: python-etcd, python-consul, psutil, cdiff, patroni
  Found existing installation: python-etcd 0.4.3
    Uninstalling python-etcd-0.4.3:
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 211, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 311, in run
    root=options.root_path,
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 640, in install
    requirement.uninstall(auto_confirm=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 716, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 125, in remove
    renames(path, new_path)
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 315, in renames
    shutil.move(old, new)
  File "/usr/lib/python2.7/shutil.py", line 303, in move
    os.unlink(src)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/etcd/__init__.py'
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

Can someone let me know

Why is the permission changing after upgrade?

How can I have the same permission even after the upgrade?

答: I'm sure the problem is in sudo. sudo runs a new shell under root user and the new shell reads configuration files from /root/ directory. It seems /root/.bash_profile has a command umask 027 in it. Change it to 022 and the problem should be fixed.

Body:
I am using a python package patroni version 1.0 on Ubuntu 14. On doing ls -lrt /usr/local/lib/python2.7/dist-packages/ I am seeing the permission like below

But once I upgrade the patroni via the command sudo pip install patroni --upgrade I am seeing the permission of the patroni changes after upgrade

The installation output is -

sudo pip install patroni  --upgrade
The directory '/home/ubuntu/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/ubuntu/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Collecting patroni
Requirement already up-to-date: requests in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting cdiff (from patroni)
Requirement already up-to-date: six>=1.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting python-etcd<0.5,>=0.4.3 (from patroni)
Requirement already up-to-date: prettytable>=0.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: tzlocal in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: boto in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting python-consul>=0.7.0 (from patroni)
  Downloading python_consul-0.7.2-py2.py3-none-any.whl
Requirement already up-to-date: psycopg2>=2.6.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: kazoo==2.2.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: urllib3>=1.9 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: click>=4.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: python-dateutil in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting psutil (from patroni)
Requirement already up-to-date: PyYAML in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: certifi>=2017.4.17 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: idna<2.7,>=2.5 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: dnspython>=1.13.0 in /usr/local/lib/python2.7/dist-packages (from python-etcd<0.5,>=0.4.3->patroni)
Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from tzlocal->patroni)
Installing collected packages: cdiff, python-etcd, python-consul, psutil, patroni
  Found existing installation: python-etcd 0.4.3
    Uninstalling python-etcd-0.4.3:
      Successfully uninstalled python-etcd-0.4.3
  Found existing installation: python-consul 0.6.0
    Uninstalling python-consul-0.6.0:
      Successfully uninstalled python-consul-0.6.0
  Found existing installation: patroni 1.0
    Uninstalling patroni-1.0:
      Successfully uninstalled patroni-1.0
Successfully installed cdiff-1.0 patroni-1.3.6 psutil-5.4.1 python-consul-0.7.2 python-etcd-0.4.5
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

I had to use sudo if I do just pip install patroni --upgrade then it is failing with the below error:-

pip install patroni  --upgrade
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
Collecting patroni
  Downloading patroni-1.3.6.tar.gz (90kB)
    100% |████████████████████████████████| 94kB 1.0MB/s
Requirement already up-to-date: urllib3>=1.9 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: boto in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: psycopg2>=2.6.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: PyYAML in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: requests in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: six>=1.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: kazoo==2.2.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting python-etcd<0.5,>=0.4.3 (from patroni)
  Downloading python-etcd-0.4.5.tar.gz
Collecting python-consul>=0.7.0 (from patroni)
  Downloading python_consul-0.7.2-py2.py3-none-any.whl
Requirement already up-to-date: click>=4.1 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: prettytable>=0.7 in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: tzlocal in /usr/local/lib/python2.7/dist-packages (from patroni)
Requirement already up-to-date: python-dateutil in /usr/local/lib/python2.7/dist-packages (from patroni)
Collecting psutil (from patroni)
  Downloading psutil-5.4.1.tar.gz (408kB)
    100% |████████████████████████████████| 409kB 1.1MB/s
Collecting cdiff (from patroni)
  Downloading cdiff-1.0.tar.gz
Requirement already up-to-date: certifi>=2017.4.17 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: idna<2.7,>=2.5 in /usr/local/lib/python2.7/dist-packages (from requests->patroni)
Requirement already up-to-date: dnspython>=1.13.0 in /usr/local/lib/python2.7/dist-packages (from python-etcd<0.5,>=0.4.3->patroni)
Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from tzlocal->patroni)
Building wheels for collected packages: patroni, python-etcd, psutil, cdiff
  Running setup.py bdist_wheel for patroni
  Stored in directory: /home/ubuntu/.cache/pip/wheels/86/5a/e3/cb4ac4ecf20bc7a2956062d3c3ad15c660a993a0cc3aa23d35
  Running setup.py bdist_wheel for python-etcd
  Stored in directory: /home/ubuntu/.cache/pip/wheels/d1/79/df/26facc508cdb5fefaf3d574fb634d848754a7e69d95f53f056
  Running setup.py bdist_wheel for psutil
  Stored in directory: /home/ubuntu/.cache/pip/wheels/05/a2/2a/2015d6af91fb5a4cc5bcdfa9699034e2f624fc9cc5acde7ab9
  Running setup.py bdist_wheel for cdiff
  Stored in directory: /home/ubuntu/.cache/pip/wheels/d9/67/dc/d53a3cfea638a5652d0d2054b447d67a7d2a2bdebf0f67765e
Successfully built patroni python-etcd psutil cdiff
Installing collected packages: python-etcd, python-consul, psutil, cdiff, patroni
  Found existing installation: python-etcd 0.4.3
    Uninstalling python-etcd-0.4.3:
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 211, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 311, in run
    root=options.root_path,
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 640, in install
    requirement.uninstall(auto_confirm=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 716, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 125, in remove
    renames(path, new_path)
  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 315, in renames
    shutil.move(old, new)
  File "/usr/lib/python2.7/shutil.py", line 303, in move
    os.unlink(src)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/etcd/__init__.py'
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Can someone let me know

Why is the permission changing after upgrade?

How can I have the same permission even after the upgrade?


来源: stackexchange

问:
What happens to a running method if its object is deleted?
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

```<code>// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}
</code>```

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)

答:
Code and allocated space for an object are stored separately. Code is only stored once in your binary (and loaded in memory when executing the binary). Objects are created dynamically in memory, on the heap or the stack. The code of a method operates on the object's data using the this pointer (which is an 'invisible' argument to a method, and can be accessed by explicitly writing this in the method, or is used implicitly when accessing members).

Nothing will happen to the running function if you delete the object. It will continue running and execute commands. The this pointer will not change during execution (because, as already mentioned, it's like an argument to the function copied by value). However, if the object is deleted, it will most likely not point to anything useful. So:

Using the this pointer will either give you a SEGFAULT because you access memory that doesn't belong to the application anymore

or will access some random memory in your application, leading to undefined behavior

So to answer your questions:

No, it's not interrupted. It keeps executing the function.

It doesn't 'belong' to anything, just operates on the data pointed to by this. Your second new is not guaranteed to give you the same pointer value (memory address).

It's not interrupted, but pretty much results in undefined behavior if you keep accessing object members.

ContentLicense: CC BY-SA 3.0

Body:
I'm new on StackOverflow and my first question is abot what happens to a running method, when I delete its object? Furthermore, what happens when I create a new object in the method, after I deleted the old one?

There's a small code snippet below to clarify my question. (Programming in C++11)

// Declaration and Definition of the class
class MyClass{
private:
    static int counterFromClass = 0;
    int counterFromObject;
public:
    MyClass() {
        counterFromObject = 0;
    }
    void ~MyClass() {}
    void doSomething();
};

// Somewhere in the code a new object of the class is generated like this:
MyClass object = new MyClass();

// Then the method is called:
object->doSomething();

// Definition of the method
void MyClass::doSomething() {
    this->counterFromObject++;
    delete object;
    MyClass object = new MyClass();
    this->counterFromClass++;
}

If now the method doSomething() is called:

Will the method run until its end or will it be interrupted?

If it runs until the end, does it belong to the deleted object or the new one? Both objects, the deleted and the new one, have the same name.

If it is interrupted, what will happen? Or is this behaviour undefined?

So far what I have expirienced, it seems that the method will run to its end and execute all commands on its way, as long as they don't affect the deleted object. E.g. manipulating a static variable like counterFromClass is allowed. And it seems also possible to manipulate data members of the object like counterFromObject inside the method, as long as they are manipulated before the delete command.

Well, the code works but I know that it's not the best programming style. So I just started to work on a better solution, but I still got curious what exactly happens and if my thougths were correct. I would be grateful for answers.

If something's wrong with the question, please let me know because I am not that familiar with asking questions on StackOverflow yet.

Thank you :)


问:
Can we make an element of block modifier in BEM?
I just wanted to know whether the following code follows BEM methodology best practices? Creating an element for the block modifier i.e. in this case "block--mod" is a modifier for the "block" block. Is it allowed to create a nested element with this pattern: "block--mod__elm". </p>

```<code><div class="block block--mod">
   <div class="block__elm block--mod__elm">
</div>
</code>```

答:
In situations like theming or similar I would use nested selectors. This saves some classes in your HTML and as @Jonathan Nicol said those sub-elements can be hard to follow. Also it will be easier to remove the "branding" later, just remove block class instead of all it's elements.

For example Xmas branding of your header.

```<code>.header--xmas .header__logo {
    /* Jingle bells, jingle bells, jingle all the way.*/
}
</code>```

Source: http://getbem.com/faq/#can-a-block-modifier-affect-elements-

Body:
In situations like theming or similar I would use nested selectors. This saves some classes in your HTML and as @Jonathan Nicol said those sub-elements can be hard to follow. Also it will be easier to remove the "branding" later, just remove block class instead of all it's elements.

For example Xmas branding of your header.

.header--xmas .header__logo {
    /* Jingle bells, jingle bells, jingle all the way.*/
}

Source: http://getbem.com/faq/#can-a-block-modifier-affect-elements-


问:
Component not rendering/displaying
NOTE: This question is very similar to Angular directive crashing browser
 but still differs in what exactly is clashing with the created AngularJS component.

So I created a very simple nav component and immediately after adding that component to another component's template, my browser tab was crashing.

Because it crashed right away, there was no output I could see from the console.

Here is my setup:

HTML

```<code><div id="header">
    <div id="header_main">
        <nav></nav>
    </div>
</div>
</code>```

Nav Template

```<code><div class="dark-blue-section main-color">
  <div class="container">
    <nav class="navbar" role="navigation">
      <div class="navbar-header center-mobile">
        <div class="phone-wrap circled white small-btn mobile-only">Call <a send-ga-notification url="call" to="phone" mobile-only="true" href="tel:{{ $ctrl.digits }}">1.{{ $ctrl.phone }}</a></div>
        <div class="phone-wrap desktop-only">Call <a send-ga-notification url="call" to="phone" mobile-only="true" href="tel:{{ $ctrl.digits }}">1.{{ $ctrl.phone }}</a></div>
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true"
          ng-click="navCollapsed = !navCollapsed">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-menu3"></span>
        </button>
      </div>
      <div class="collapse navbar-collapse" ng-class="!navCollapsed && 'in'">

        <ul class="nav navbar-nav navbar-right desktop-only">
          <li ng-class="{ active: isActive('/financing-and-insurance') }">
            <a ui-sref="index.financing-and-insurance" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Financing & Insurance
            </a>
          </li>
          <li ng-class="{ active: isActive('/ortho-and-braces') }">
            <a ui-sref="index.ortho-and-braces" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Ortho & Braces
            </a>
          </li>
          <li ng-class="{ active: isActive('/your-first-visit') }">
            <a ui-sref="index.first-visit" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Your First Visit
            </a>
          </li>
          <li ng-class="{ active: isActive('/careers') }">
            <a ui-sref="index.careers" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Careers
            </a>
          </li>
          <li ng-class="{ active: isActive('/contact') }">
            <a ui-sref="index.contact" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Contact Us
            </a>
          </li>
        </ul>
        <ul class="nav navbar-nav navbar-right mobile-only">
          <li ng-class="{ active: isActive('/locations') }">
            <a ui-sref="index.locations" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Find An Office
            </a>
          </li>
          <li>
            <a href="" ng-class="{ active: isActive('/appointment') }" ng-click="clickToOpen()" uib-dropdown-toggle>
             Request An Appointment
            </a>
          </li>
          <li ng-class="{ active: isActive('/offers') }">
            <a ui-sref="index.offers-and-discounts" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Offers & Discounts
            </a>
          </li>
          <li ng-class="{ active: isActive('/your-first-visit') }">
            <a ui-sref="index.first-visit" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Your First Visit
            </a>
          </li>
          <li class="mobile-only" ng-class="{ active: isActive('/careers/openings') }">
            <a ui-sref="index.careers.current-openings" ng-click="navCollapsed=true" uib-dropdown-toggle>
              Careers
            </a>
          </li>
        </ul>
      </div>
    </nav>
  </div>
</div>
</code>```

Nav Component

```<code>angular
.module('common')
.component('nav', {
    templateUrl: './nav.html',
});
</code>```

I have created many components before so this is a rare problem.

答:
So it turns out that the name of the nav component itself was colliding with the  HTML tag. All you have to do is rename it to something else and it will solve the issue (don't forget that you can't put dashes ('-') in the name, only camel case will work if the name is long enough).

NOTE:

I first tried renaming it to navbar which is also an HTML class in the template, but this did not cause any issues. This is weird because the similar question referenced above says the issue was a collision with a CSS class so I'm not sure why HTML classes are in the clear and not CSS classes.

Maybe someone else can chime in there.

Title: Component not rendering/displaying

Body:
NOTE: This question is very similar to Angular directive crashing browser
 but still differs in what exactly is clashing with the created AngularJS component.

So I created a very simple nav component and immediately after adding that component to another component's template, my browser tab was crashing.

Because it crashed right away, there was no output I could see from the console.

Here is my setup:

HTML

Nav Template

Call 1.{{ $ctrl.phone }}

Call 1.{{ $ctrl.phone }}

        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true"
          ng-click="navCollapsed = !navCollapsed">
          Toggle navigation

        </button>

              Financing & Insurance

              Ortho & Braces

              Your First Visit

              Careers

              Contact Us

              Find An Office

             Request An Appointment

              Offers & Discounts

              Your First Visit

              Careers

Nav Component

angular
.module('common')
.component('nav', {
    templateUrl: './nav.html',
});

I have created many components before so this is a rare problem.

Body:
So it turns out that the name of the nav component itself was colliding with the <nav> HTML tag. All you have to do is rename it to something else and it will solve the issue (don't forget that you can't put dashes ('-') in the name, only camel case will work if the name is long enough).

NOTE:

I first tried renaming it to navbar which is also an HTML class in the template, but this did not cause any issues. This is weird because the similar question referenced above says the issue was a collision with a CSS class so I'm not sure why HTML classes are in the clear and not CSS classes.

Maybe someone else can chime in there.


问:
Geocoder.getFromLocation grpc failed on Android real device
I need to get the city and state from latitude and longitude. Geocoder does this function to get the city and state. But I am getting an error java.io.IOException: grpc failed in below line only on Android real device. It is working fine in emulators.

```<code>new Geocoder(context).getFromLocation(latLng.latitude, latLng.longitude, 1).get(0);
</code>```

Also I have been calling this function using Asynctask which is suggested in another post Geocoder grpc failed in stack overflow but nothing works for me.

And I have restart the device as well but still it is failing.

Help needed here. Thanks in advance.

Note: I tested in Google Pixel XL, Samsung S6 edge, Samsung S4.

答:
It looks like this is ongoing issue that was reported in the Google issue tracker both for real devices and emulators. You can refer to the following bugs:

https://issuetracker.google.com/issues/64418751

https://issuetracker.google.com/issues/64247769

Unfortunately, Google haven't solved these issues yet.

As a workaround you can consider using the Geocoding API web service. Please note that there is a Java client library for web services that you can find on Github:

https://github.com/googlemaps/google-maps-services-java

Using Java client library for web services you can implement reverse geocoding lookup that shouldn't give you the error that you experience with native Android geocoder.

The Javadoc for client library is located at

https://googlemaps.github.io/google-maps-services-java/v0.2.5/javadoc/

I hope this helps!

Body:
I need to get the city and state from latitude and longitude. Geocoder does this function to get the city and state. But I am getting an error java.io.IOException: grpc failed in below line only on Android real device. It is working fine in emulators.

new Geocoder(context).getFromLocation(latLng.latitude, latLng.longitude, 1).get(0);

Also I have been calling this function using Asynctask which is suggested in another post Geocoder grpc failed in stack overflow but nothing works for me.

And I have restart the device as well but still it is failing.

Help needed here. Thanks in advance.

Note: I tested in Google Pixel XL, Samsung S6 edge, Samsung S4.


问:
Create Border around image when clicked in JavaScript?
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}</code>```

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

```

答:
function addBorder(id) {
  var x = document.getElementsByClassName("img");
  for(i = 0; i < x.length; i++)
  {
   x.item(i).style.border = 'none';
  }
  id.style.border = '5px solid orange';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="img" onclick="addBorder(this)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
<img class="img" onclick="addBorder(this)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
<img class="img" onclick="addBorder(this)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/></code>```

Body:
I'm working on an assignment for school and have been trying to get the code to run as it is supposed to. At this point all I need is for the Onclick to work. I try to put a border around each thumbnail image that is clicked and then have the border removed once another image is clicked. I have looked at multiple resources, but can't seem to get this to work at all. If anyone can provide assistance it would be really appreciated. I am extremely new to JavaScript and am pretty lost with the resources I've been given. My resolution needs to be purely in JavaScript without any JQuery.

// JavaScript Document //
var imgArray = new Array(
  //list of slides
  'chestnutp.jpg',
  'chestnuts.jpg',
  'elephant.jpg',
  'fall.jpg',
  'leaves.jpg'
);
var imgPath = "img/";

function swapImage(imgID) { //pulls image to larger area..
  var theImage = document.getElementById('largeImage');
  var newImg;
  newImg = imgArray[imgID];
  theImage.src = imgPath + newImg;
  var element = document.getElementById("id20");
  element.innerHTML = "New Fall Photo Gallery"; //Additional change to DOM; changes original name
}
var captionArray = [
  //list of captions
  'A chestnut coming out of a plant on a fall day.',
  'A bundle of chestnuts on the ground on a fall day.',
  'An Elephant walking on an African Fall evening.',
  'A fall display with flowers and pumpkins.',
  'Looking up at the leaves on a fall day.'
];

function swapCaption(ID) { //creates caption when larger image is shown
  var theCaption = document.getElementById('caption');
  var newCaption;
  newCaption = captionArray[ID];
  theCaption.innerHTML = newCaption;
}

function mark(ID) { //creates border
  document.getElementById(ID).style.border = "2px solid orange";
}

@charset "utf-8";

/* CSS Document */

body {
  background-color: #322F2F;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, sans-serif;
}

* {
  box-sizing: border-box;
}

.col-1 {
  width: 8.33%;
}

.col-2 {
  width: 16.66%;
}

.col-3 {
  width: 25%;
}

.col-4 {
  width: 33.33%;
}

.col-5 {
  width: 41.66%;
}

.col-6 {
  width: 50%;
}

.col-7 {
  width: 58.33%;
}

.col-8 {
  width: 66.66%;
}

.col-9 {
  width: 75%;
}

.col-10 {
  width: 83.33%;
}

.col-11 {
  width: 91.66%;
}

.col-12 {
  width: 100%;
}

[class*="col-"] {
  float: left;
}

.row:after {
  content: "";
  clear: both;
  display: block;
}

#wrapper {
  height: auto;
  width: 60%;
  margin: auto;
}

h1 {
  font-size: 1.6em;
  color: #fff;
  text-align: center;
}

#thumbnails {
  height: 20%;
  width: 100%;
}

#thumbnails>img:hover {
  border: 1px #9D9C9C solid;
}

.thumbDown {
  border: none;
}

.thumbUp {
  border: 1px #9D9C9C solid;
}

.largeImage {
  height: 100%;
  width: 100%;
}

.caption {
  font-size: .9em;
  height: 25px;
  width: 100%;
  color: #fff;
}

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Fall Air Photo Gallery</title>

  <link rel="stylesheet" type="text/css" href="css/style.css" />

Fall Air Photo Gallery

Body:
function addBorder(id) {
  var x = document.getElementsByClassName("img");
  for(i = 0; i < x.length; i++)
  {
   x.item(i).style.border = 'none';
  }
  id.style.border = '5px solid orange';
}

<img class="img" onclick="addBorder(this)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
<img class="img" onclick="addBorder(this)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>
<img class="img" onclick="addBorder(this)" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTMZPrNzLxySwT9GuHbz33ZyNXFJtBrqg_ruleaepzXq2zf3NOewA"/>


问:
What programming language is most like natural language?
I got the idea for this question from numerous situations where I don't understand what the person is talking about and when others don't understand me.

So, a "smart" solution would be to speak a computer language. :)

I am interested how far a programming language can go to get near to (English) natural language. When I say near, I mean not just to use words and sentences, but to be able to "do" things a natural language can "do" and by "do" I mean that it can be used (in a very limited way) as a replacement for natural language.

I know that this is impossible (is it?) but I think that this can be interesting.

答: Of course it would also have to have an ability to generate concepts and then "name" these concepts, so these could be used to express more complex construct, i.e. basically would have to have some sort of support for ontology of the world, it is supposed to be used in. I think if something like "inform" language describe in an earlier post, coupled with some backend concept network or ontology database, would be a good way to start. </p>

OwnerDisplayName: kliketa

ContentLicense: CC BY-SA 2.5


问:
Printing the exception message in an Ada Last_Chance_Handler
I'm in the process of learning Ada using the GNAT compiler using the AdaCore GPS (GPL) IDE, aimed at ARM "bare board" hardware (STM32F4 using a Ravenscar SFP runtime).

For my ARM based embedded work I've come from a C/C++ background.

Anyway, I've implemented a "last chance handler" that's defined as follows,

```<code>procedure Last_Chance_Handler (Msg : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");
</code>```

Here's the actual procedure (a snippet from the .adb file),

```<code>procedure Last_Chance_Handler (Msg : System.Address; Line : Integer) is
begin
   LEDs_All_On;
   -- Put_Line("Detail :" & Address_To_String(Msg));
   Put_Line("Line   :" & Line'Image);

   loop
      null;
   end loop;
end Last_Chance_Handler;
</code>```

The Msg argument is documented as follows,

The Msg parameter is a C null-terminated string representing the
  source location of the raise statement, as generated by the compiler,
  or a zero-length string if pragma Suppress_Exception_Locations is
  used.

I've been trying to figure out how to convert the null terminated Msg bytes to an Ada string so that I can display it using a Put_Line() call (when debugging I can access this type of output via the semihosting mechanism).

I've previously mapped Ada records (representing device registers etc.) to physical memory addresses by setting their 'Address attribute to a constant value. However, this is the first time I've tried access memory via a System.Address value held in a variable.

Can anyone suggest how I might go about implementing the Address_To_String() procedure?

I have experimented with Ada byte arrays and unchecked conversions between them and System.Address, also with Ada pointers, but so far I've not had any success.

Any help or suggestions would be greatly appreciated!

Many thanks,

...Max

答:
If you come to a last_chance_handler something is probably broken and you shouldnt rely too much on your environment. Ada.Text_IO is a very heavy package. You should try to avoid it generally and especially here.

You could try something like this:

```<code>with GNAT.IO;
with System.Storage_Elements;
procedure Last_Chance_Handler
   (Msg : System.Address; Line : Integer)
is
   use System.Storage_Elements; -- make "+" visible for System.Address

   function Peek (Addr : System.Address) return Character
   is
      C : Character with Address => Addr;
   begin
      return C;
   end Peek;
   A : System.Address := Msg;
begin
   GNAT.IO.Put ("line :");
   GNAT.IO.Put (line); -- avoid the secondary stack for Line'Image
   GNAT.IO.New_Line;
   while Peek(A) /= ASCII.NUL loop
      GNAT.IO.Put (Peek(A));
      A := A + 1;
   end loop;
   GNAT.IO.New_Line;
end;
</code>```

Body:
I'm in the process of learning Ada using the GNAT compiler using the AdaCore GPS (GPL) IDE, aimed at ARM "bare board" hardware (STM32F4 using a Ravenscar SFP runtime).

For my ARM based embedded work I've come from a C/C++ background.

Anyway, I've implemented a "last chance handler" that's defined as follows,

procedure Last_Chance_Handler (Msg : System.Address; Line : Integer);
pragma Export (C, Last_Chance_Handler, "__gnat_last_chance_handler");

Here's the actual procedure (a snippet from the .adb file),

procedure Last_Chance_Handler (Msg : System.Address; Line : Integer) is
begin
   LEDs_All_On;
   -- Put_Line("Detail :" & Address_To_String(Msg));
   Put_Line("Line   :" & Line'Image);

   loop
      null;
   end loop;
end Last_Chance_Handler;

The Msg argument is documented as follows,

The Msg parameter is a C null-terminated string representing the
  source location of the raise statement, as generated by the compiler,
  or a zero-length string if pragma Suppress_Exception_Locations is
  used.

I've been trying to figure out how to convert the null terminated Msg bytes to an Ada string so that I can display it using a Put_Line() call (when debugging I can access this type of output via the semihosting mechanism).

I've previously mapped Ada records (representing device registers etc.) to physical memory addresses by setting their 'Address attribute to a constant value. However, this is the first time I've tried access memory via a System.Address value held in a variable.

Can anyone suggest how I might go about implementing the Address_To_String() procedure?

I have experimented with Ada byte arrays and unchecked conversions between them and System.Address, also with Ada pointers, but so far I've not had any success.

Any help or suggestions would be greatly appreciated!

Many thanks,

...Max

Body:
If you come to a last_chance_handler something is probably broken and you shouldnt rely too much on your environment. Ada.Text_IO is a very heavy package. You should try to avoid it generally and especially here.

You could try something like this:

with GNAT.IO;
with System.Storage_Elements;
procedure Last_Chance_Handler
   (Msg : System.Address; Line : Integer)
is
   use System.Storage_Elements; -- make "+" visible for System.Address

   function Peek (Addr : System.Address) return Character
   is
      C : Character with Address => Addr;
   begin
      return C;
   end Peek;
   A : System.Address := Msg;
begin
   GNAT.IO.Put ("line :");
   GNAT.IO.Put (line); -- avoid the secondary stack for Line'Image
   GNAT.IO.New_Line;
   while Peek(A) /= ASCII.NUL loop
      GNAT.IO.Put (Peek(A));
      A := A + 1;
   end loop;
   GNAT.IO.New_Line;
end;


问:
Why are notSupported error responses handled differently in different QUERY intent scenarios?
This question was prompted by our previous question regarding review requirements for QUERY intents, found here.

Although we are currently unable to implement querying a detailed status of many of our devices, we would like to respond properly to attempts at QUERY intents. Specifically: with a notSupported error response seems appropriate. For a general user query, such as "Is the Desk light on?", this works as we would expect:

"That mode isn't available for the Desk light".

However, when attempting relative operations, such as "Dim the Desk light.", the same response format results in the following response by Google Home:

"Encountered an unknown error for the Desk light."

The same json response is returned in both scenarios:

```<code>{

"requestId": "****************",

"payload": {

    "devices": {
        "********": {
            "errorCode": "notSupported"
            }
        }
    }
}
</code>```

We have verified, by faking a query response with an actual brightness status, that the intent continues properly after the QUERY returns; receiving an EXECUTE intent next to effect the change in brightness.

We are unsure why a notSupported error is handled differently in this case; are we perhaps misunderstanding how an error response to this kind of QUERY should be formatted? If so, how can we distinguish a QUERY intent that will be followed by an EXECUTE intent from a solitary QUERY intent? Perhaps there is something else entirely that we have missed?

Thank you for reading.

答:
just following up on this - i get the logic in the Query - but the Query itself is totally vanilla - how do we know that it's a query that needs to return:
"brightness": 65

rather than - "on": true

Body:
This question was prompted by our previous question regarding review requirements for QUERY intents, found here.

Although we are currently unable to implement querying a detailed status of many of our devices, we would like to respond properly to attempts at QUERY intents. Specifically: with a notSupported error response seems appropriate. For a general user query, such as "Is the Desk light on?", this works as we would expect:

"That mode isn't available for the Desk light".

However, when attempting relative operations, such as "Dim the Desk light.", the same response format results in the following response by Google Home:

"Encountered an unknown error for the Desk light."

The same json response is returned in both scenarios:

{

"requestId": "****************",

"payload": {

    "devices": {
        "********": {
            "errorCode": "notSupported"
            }
        }
    }
}

We have verified, by faking a query response with an actual brightness status, that the intent continues properly after the QUERY returns; receiving an EXECUTE intent next to effect the change in brightness.

We are unsure why a notSupported error is handled differently in this case; are we perhaps misunderstanding how an error response to this kind of QUERY should be formatted? If so, how can we distinguish a QUERY intent that will be followed by an EXECUTE intent from a solitary QUERY intent? Perhaps there is something else entirely that we have missed?

Thank you for reading.


问:
In iOS, how to drag down to dismiss a modal?
A common way to dismiss a modal is to swipe down - How do we allows the user to drag the modal down, if it's far enough, the modal's dismissed, otherwise it animates back to the original position?

For example, we can find this used on the Twitter app's photo views, or Snapchat's "discover" mode.

Similar threads point out that we can use a UISwipeGestureRecognizer and [self dismissViewControllerAnimated...] to dismiss a modal VC when a user swipes down. But this only handles a single swipe, not letting the user drag the modal around.

答:
Here is a one-file solution based on @wilson's answer (thanks  ) with the following improvements:

List of Improvements from previous solution

Limit panning so that the view only goes down:

Avoid horizontal translation by only updating the y coordinate of view.frame.origin

Avoid panning out of the screen when swiping up with let y = max(0, translation.y)

Also dismiss the view controller based on where the finger is released (defaults to the bottom half of the screen) and not just based on the velocity of the swipe

Show view controller as modal to ensure the previous viewcontroller appears behind and avoid a black background (should answer your question @nguyễn-anh-việt)

Remove unneeded currentPositionTouched and originalPosition

Expose the following parameters:

minimumVelocityToHide: what speed is enough to hide (defaults to 1500)

minimumScreenRatioToHide: how low is enough to hide (defaults to 0.5)

animationDuration : how fast do we hide/show (defaults to 0.2s)

Solution

Swift 3 & Swift 4 :

```<code>//
//  PannableViewController.swift
//

import UIKit

class PannableViewController: UIViewController {
    public var minimumVelocityToHide: CGFloat = 1500
    public var minimumScreenRatioToHide: CGFloat = 0.5
    public var animationDuration: TimeInterval = 0.2

    override func viewDidLoad() {
        super.viewDidLoad()

        // Listen for pan gesture
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:)))
        view.addGestureRecognizer(panGesture)
    }

    @objc func onPan(_ panGesture: UIPanGestureRecognizer) {

        func slideViewVerticallyTo(_ y: CGFloat) {
            self.view.frame.origin = CGPoint(x: 0, y: y)
        }

        switch panGesture.state {

        case .began, .changed:
            // If pan started or is ongoing then
            // slide the view to follow the finger
            let translation = panGesture.translation(in: view)
            let y = max(0, translation.y)
            slideViewVerticallyTo(y)

        case .ended:
            // If pan ended, decide it we should close or reset the view
            // based on the final position and the speed of the gesture
            let translation = panGesture.translation(in: view)
            let velocity = panGesture.velocity(in: view)
            let closing = (translation.y > self.view.frame.size.height * minimumScreenRatioToHide) ||
                          (velocity.y > minimumVelocityToHide)

            if closing {
                UIView.animate(withDuration: animationDuration, animations: {
                    // If closing, animate to the bottom of the view
                    self.slideViewVerticallyTo(self.view.frame.size.height)
                }, completion: { (isCompleted) in
                    if isCompleted {
                        // Dismiss the view when it dissapeared
                        dismiss(animated: false, completion: nil)
                    }
                })
            } else {
                // If not closing, reset the view to the top
                UIView.animate(withDuration: animationDuration, animations: {
                    slideViewVerticallyTo(0)
                })
            }

        default:
            // If gesture state is undefined, reset the view to the top
            UIView.animate(withDuration: animationDuration, animations: {
                slideViewVerticallyTo(0)
            })

        }
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)   {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .overFullScreen;
        modalTransitionStyle = .coverVertical;
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        modalPresentationStyle = .overFullScreen;
        modalTransitionStyle = .coverVertical;
    }
}
</code>```

Body:
Here is a one-file solution based on @wilson's answer (thanks  ) with the following improvements:

List of Improvements from previous solution

Limit panning so that the view only goes down:

Avoid horizontal translation by only updating the y coordinate of view.frame.origin

Avoid panning out of the screen when swiping up with let y = max(0, translation.y)

Also dismiss the view controller based on where the finger is released (defaults to the bottom half of the screen) and not just based on the velocity of the swipe

Show view controller as modal to ensure the previous viewcontroller appears behind and avoid a black background (should answer your question @nguyễn-anh-việt)

Remove unneeded currentPositionTouched and originalPosition

Expose the following parameters:

minimumVelocityToHide: what speed is enough to hide (defaults to 1500)

minimumScreenRatioToHide: how low is enough to hide (defaults to 0.5)

animationDuration : how fast do we hide/show (defaults to 0.2s)

Solution

Swift 3 & Swift 4 :

//
//  PannableViewController.swift
//

import UIKit

class PannableViewController: UIViewController {
    public var minimumVelocityToHide: CGFloat = 1500
    public var minimumScreenRatioToHide: CGFloat = 0.5
    public var animationDuration: TimeInterval = 0.2

    override func viewDidLoad() {
        super.viewDidLoad()

        // Listen for pan gesture
        let panGesture = UIPanGestureRecognizer(target: self, action: #selector(onPan(_:)))
        view.addGestureRecognizer(panGesture)
    }

    @objc func onPan(_ panGesture: UIPanGestureRecognizer) {

        func slideViewVerticallyTo(_ y: CGFloat) {
            self.view.frame.origin = CGPoint(x: 0, y: y)
        }

        switch panGesture.state {

        case .began, .changed:
            // If pan started or is ongoing then
            // slide the view to follow the finger
            let translation = panGesture.translation(in: view)
            let y = max(0, translation.y)
            slideViewVerticallyTo(y)

        case .ended:
            // If pan ended, decide it we should close or reset the view
            // based on the final position and the speed of the gesture
            let translation = panGesture.translation(in: view)
            let velocity = panGesture.velocity(in: view)
            let closing = (translation.y > self.view.frame.size.height * minimumScreenRatioToHide) ||
                          (velocity.y > minimumVelocityToHide)

            if closing {
                UIView.animate(withDuration: animationDuration, animations: {
                    // If closing, animate to the bottom of the view
                    self.slideViewVerticallyTo(self.view.frame.size.height)
                }, completion: { (isCompleted) in
                    if isCompleted {
                        // Dismiss the view when it dissapeared
                        dismiss(animated: false, completion: nil)
                    }
                })
            } else {
                // If not closing, reset the view to the top
                UIView.animate(withDuration: animationDuration, animations: {
                    slideViewVerticallyTo(0)
                })
            }

        default:
            // If gesture state is undefined, reset the view to the top
            UIView.animate(withDuration: animationDuration, animations: {
                slideViewVerticallyTo(0)
            })

        }
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)   {
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .overFullScreen;
        modalTransitionStyle = .coverVertical;
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        modalPresentationStyle = .overFullScreen;
        modalTransitionStyle = .coverVertical;
    }
}

ContentLicense: CC BY-SA 4.0


问:
Incorporate Base64 encoded data in Python Web Service call
I am trying to make a web service call in Python 3.  A subset of the request includes a base64 encoded string, which is coming from a list of Python dictionaries.

So I dump the list and encode the string:

```<code>j = json.dumps(dataDictList, indent=4, default = myconverter)
encodedData = base64.b64encode(j.encode('ASCII'))
</code>```

Then, when I build my request, I add in that string.  Because it comes back in bytes I need to change it to string:

```<code>...
\"data\": \"''' + str(encodedData) + '''\"
...
</code>```

The response I'm getting from the web service is that my request is malformed.  When I print our str(encodedData) I get:

b'WwogICAgewogICAgICAgICJEQVlfREFURSI6ICIyMDEyLTAzLTMxIDAwOjAwOjAwIiwKICAgICAgICAiQ0FMTF9DVFJfSUQiOiA1LAogICAgICAgICJUT1RfRE9MTEFSX1NBTEVTIjogMTk5MS4wLAogICAgICAgICJUT1RfVU5JVF9TQUxFUyI6IDQ0LjAsCiAgICAgICAgIlRPVF9DT1NUIjogMTYxOC4xMDM3MDAwMDAwMDA2LAogICAgICAgICJHUk9TU19ET0xMQVJfU0FMRVMiOiAxOTkxLjAKICAgIH0KXQ=='

If I copy this into a base64 decoder, I get gibberish until I remove the b' at the beginning as well as the last single quote.  I think those are causing my request to fail.  According to this note, though, I would think that the b' is ignored: What does the 'b' character do in front of a string literal?

I'll appreciate any advice.

Thank you.

答:
Passing a bytes object into str causes it to be formatted for display, it doesn't convert the bytes into a string (you need to know the encoding for that to work):

```<code>In [1]: x = b'hello'

In [2]: str(x)
Out[2]: "b'hello'"
</code>```

Note that str(x) actually starts with b' and ends with '. If you want to decode the bytes into a string, use bytes.decode:

```<code>In [5]: x = base64.b64encode(b'hello')

In [6]: x
Out[6]: b'aGVsbG8='

In [7]: x.decode('ascii')
Out[7]: 'aGVsbG8='
</code>```

You can safely decode the base64 bytes as ASCII. Also, your JSON should be encoded as UTF-8, not ASCII. The following changes should work:

```<code>j = json.dumps(dataDictList, indent=4, default=myconverter)
encodedData = base64.b64encode(j.encode('utf-8')).decode('ascii')
</code>```

Body:
I am trying to make a web service call in Python 3.  A subset of the request includes a base64 encoded string, which is coming from a list of Python dictionaries.

So I dump the list and encode the string:

j = json.dumps(dataDictList, indent=4, default = myconverter)
encodedData = base64.b64encode(j.encode('ASCII'))

Then, when I build my request, I add in that string.  Because it comes back in bytes I need to change it to string:

...
\"data\": \"''' + str(encodedData) + '''\"
...

The response I'm getting from the web service is that my request is malformed.  When I print our str(encodedData) I get:

b'WwogICAgewogICAgICAgICJEQVlfREFURSI6ICIyMDEyLTAzLTMxIDAwOjAwOjAwIiwKICAgICAgICAiQ0FMTF9DVFJfSUQiOiA1LAogICAgICAgICJUT1RfRE9MTEFSX1NBTEVTIjogMTk5MS4wLAogICAgICAgICJUT1RfVU5JVF9TQUxFUyI6IDQ0LjAsCiAgICAgICAgIlRPVF9DT1NUIjogMTYxOC4xMDM3MDAwMDAwMDA2LAogICAgICAgICJHUk9TU19ET0xMQVJfU0FMRVMiOiAxOTkxLjAKICAgIH0KXQ=='

If I copy this into a base64 decoder, I get gibberish until I remove the b' at the beginning as well as the last single quote.  I think those are causing my request to fail.  According to this note, though, I would think that the b' is ignored: What does the 'b' character do in front of a string literal?

I'll appreciate any advice.

Thank you.

Body:
Passing a bytes object into str causes it to be formatted for display, it doesn't convert the bytes into a string (you need to know the encoding for that to work):

In [1]: x = b'hello'

In [2]: str(x)
Out[2]: "b'hello'"

Note that str(x) actually starts with b' and ends with '. If you want to decode the bytes into a string, use bytes.decode:

In [5]: x = base64.b64encode(b'hello')

In [6]: x
Out[6]: b'aGVsbG8='

In [7]: x.decode('ascii')
Out[7]: 'aGVsbG8='

You can safely decode the base64 bytes as ASCII. Also, your JSON should be encoded as UTF-8, not ASCII. The following changes should work:

j = json.dumps(dataDictList, indent=4, default=myconverter)
encodedData = base64.b64encode(j.encode('utf-8')).decode('ascii')


问:
How to download a pdf that is already made in Rails
How do I place a .pdf into my assets and then have a view's button tag link to it so when clicked it downloads the pdf?

答: Generally, if this is a static asset, you'd place it in the public folder. Then it will be available as /filename.pdf.


问:
how to avoid "Not Responding"

Possible Duplicate:

  Keep app responsive during long task

how to avoid "Not Responding", when processing large query or long process looping?

thx

答:
Never ever use Application.ProcessMessages, it opens up a can of worms.

Really.

Let me repeat: DO NOT USE Application.ProcessMessages.

This is why: it requires all of your messaging to always be reentrant.

Your messaging, and more importantly messaging in libraries you use (the kind of which you cannot be sure it is reentrant).

Now, and in the future.

Even in cases you have not yet tested, or usage patterns you have not yet seen.

You should do multi-threading.

You really should.

It might take some time to get your synchronization right, but using somethine like a backgroundworker encapsulates most that in a neat way.

If you can't do multi-threading, then you can cheat.

But you shouldn't cheat.

Cheating is about postponing your real solution.

Postponing costs more than doing it now.

It is all about upstream decisions and downstream costs.

Fixing a bad decision later is way more expensive than taking the right decision now, and investing a bit of time to do it right.

Edit:

The only exception for using a secondary message loop is when showing modal forms or dialogs. There the secondary message loop has a confined reach of those messages because of the modality.

Edit 2:

The modality results in all other forms to be automatically disabled; timers and other non UI messages however are still being processed, so re-entrancy can still occur.

--jeroen

Title: how to avoid "Not Responding"


问:
How do I convert this csv data into a bar chart?
Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

```<code>ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30
</code>```

I have this so far

```<code>import pandas as pd

df = pd.read_csv("items4.csv",sep=",").set_index('ID')

d = dict(zip(df.index,df.values.tolist()))

print(d)
{12345: ['Italy', 100, 80], 13579: ['China', 50, 30], 24680: ['France', 50, 30]} #This is the output
</code>```

I want to make a bar chart that looks something like this with this given data.

答:
You can also do this without set_index()

```<code>df.plot.bar(x = 'Tour', y = ['Start', 'End'])
</code>```

Body:
Tour = Tour Name

Start = Available reservations at the start

End = Amount of reservations left

csv file columns:

ID     |   Tour   | Start | End

12345  |  Italy   |  100  | 80

13579  |  China   |  50   | 30

24680  |  France  |  50   | 30

I have this so far

import pandas as pd

df = pd.read_csv("items4.csv",sep=",").set_index('ID')

d = dict(zip(df.index,df.values.tolist()))

print(d)
{12345: ['Italy', 100, 80], 13579: ['China', 50, 30], 24680: ['France', 50, 30]} #This is the output

I want to make a bar chart that looks something like this with this given data.

Body:
You can also do this without set_index()

df.plot.bar(x = 'Tour', y = ['Start', 'End'])


问:
How to define and call a function in Jenkinsfile?
I've seen a bunch of questions related to this subject, but none of them offers anything that would be an acceptable solution (please, no loading external Groovy scripts, no calling to sh step etc.)

The operation I need to perform is a oneliner, but pipeline limitations made it impossible to write anything useful in that unter-language...

So, here's minimal example:

```<code>@NonCPS
def encodeProperties(Map properties) {
    properties.collect { k, v -> "$k=$v" }.join('|')
}

node('dockerized') {
    stage('Whatever') {
        properties = [foo: 123, bar: "foo"]
        echo encodeProperties(properties)
    }
}
</code>```

Depending on whether I add or remove @NonCPS annotation, or type declaration of the argument, the error changes, but it never gives any reason for what happened.  It's basically random noise, that contradicts the reality of the situation (at times it would claim that some irrelevant object doesn't have a method encodeProperties, other times it would say that it cannot find a method encodeProperties with a signature that nobody was trying to call it with (like two arguments instead of one) and so on.

From reading the documentation, which is of disastrous quality, I sort of understood that maybe functions in general aren't serializable, and that is why you need to explain this explicitly to the Groovy interpreter... I'm sorry, this makes no sense, but this is roughly what documentation says.

Obviously, trying to use collect inside stage creates a load of new errors...  Which are, at least understandable in that the author confesses that their version of Groovy doesn't implement most of the Groovy standard...

答: It's just a typo. You defined encodeProperties but called encodeProprties.

Body:
I've seen a bunch of questions related to this subject, but none of them offers anything that would be an acceptable solution (please, no loading external Groovy scripts, no calling to sh step etc.)

The operation I need to perform is a oneliner, but pipeline limitations made it impossible to write anything useful in that unter-language...

So, here's minimal example:

@NonCPS
def encodeProperties(Map properties) {
    properties.collect { k, v -> "$k=$v" }.join('|')
}

node('dockerized') {
    stage('Whatever') {
        properties = [foo: 123, bar: "foo"]
        echo encodeProperties(properties)
    }
}

Depending on whether I add or remove @NonCPS annotation, or type declaration of the argument, the error changes, but it never gives any reason for what happened.  It's basically random noise, that contradicts the reality of the situation (at times it would claim that some irrelevant object doesn't have a method encodeProperties, other times it would say that it cannot find a method encodeProperties with a signature that nobody was trying to call it with (like two arguments instead of one) and so on.

From reading the documentation, which is of disastrous quality, I sort of understood that maybe functions in general aren't serializable, and that is why you need to explain this explicitly to the Groovy interpreter... I'm sorry, this makes no sense, but this is roughly what documentation says.

Obviously, trying to use collect inside stage creates a load of new errors...  Which are, at least understandable in that the author confesses that their version of Groovy doesn't implement most of the Groovy standard...


问:
Is an nlobjSearchResultSet and nlobjSearch serializable during nlapiYieldScript and nlapiSetRecoveryPoint?
I was just wondering if anybody knew if these objects are serializable for a yield or recovery.

NetSuite documentation states that the following is serializable (and thus restorable during a yield):

```<code>All JavaScript native types
nlobjConfiguration
nlobjContext
nlobjError
nlobjFile (files up to 5MB in size)
nlobjRecord
nlobjSubrecord
nlobjSearchColumn
nlobjSearchFilter
nlobjSearchResult
nlobjSearchResultCell
all 3rd party XML Library objects
</code>```

I just found it curious that neither was listed in that list.

答:
nlobjSearch certainly didn't used to be and I don't think result sets were either.

I generally ended up wrapping my search in function and returning an array of values to avoid serializable exceptions.

e.g.

```<code>function batchStatements(){

    var statementCusts = (function(){
        var allowResend = 'T' == nlapiGetContext().getSetting('SCRIPT', 'custscript_kotn_statement_resend');
        var filters = [
            sf('balance', null, 'greaterthanorequalto', 35),  // over the threshhold
            sf('emailtransactions', null, 'is','T'),
            sf('custentity_kotn_suppress_statements', null, 'is', 'F')
        ];
        if(!allowResend){
            var resendCutoffDays = parseInt(nlapiGetContext().getSetting('SCRIPT', 'custscript_kotn_resend_limit'),10) || 14;// 14 days allows bi-montly batches if desired.
            var resendCutoff = new Date(new Date().getTime() - resendCutoffDays * 24 * 3600 * 1000);
            nlapiLogExecution("DEBUG", "limit statements since "+ resendCutoff.toISOString());
            filters.push(sf('custentity_kotn_last_statement', null, 'notafter', nlapiDateToString(resendCutoff)));
        }
        var srch = nlapiCreateSearch('customer',
            filters,
            [
                sc('entityid'),
                sc('custentity_kotn_billing_email'),
                sc('email'),
                sc('subsidiary')
            ]);
        var custs = [];
        var accum = function(res){
            custs.push({
                id:res.getId(),
                billingEmail: res.getValue('custentity_kotn_billing_email'),
                email:res.getValue('email'),
                name:res.getValue('entityid'),
                subsidiary:res.getValue('subsidiary')
            });
            return true;
        }

        srch.runSearch().forEachResult(accum);
        return custs;
    })();

    var testEnt = {};

    simpleBatch(statementCusts, function(cust){
        nlapiLogExecution("AUDIT", "Sending Statement for "+ cust.name);
        var entityComms = entityPreferences.getCustEntity(cust.id);
        var pdfFile = generateStatement(cust.id);
        var emailFile = kotnMergeTemplate(entityComms.statementEmailTemplate, 'customer', cust.id);
        nlapiSendEmail(entityComms.emailFromEmp, cust.billingEmail || cust.email || entityComms.actionEmp, emailFile.getName(), emailFile.getValue(), null, null, {entity:cust.id}, pdfFile, true);
    });
}
</code>```

simpleBatch is from https://github.com/BKnights/KotN-Netsuite
it handles governance management by tracking the max governance of the function and yielding when needed.

Body:
I was just wondering if anybody knew if these objects are serializable for a yield or recovery.

NetSuite documentation states that the following is serializable (and thus restorable during a yield):

All JavaScript native types
nlobjConfiguration
nlobjContext
nlobjError
nlobjFile (files up to 5MB in size)
nlobjRecord
nlobjSubrecord
nlobjSearchColumn
nlobjSearchFilter
nlobjSearchResult
nlobjSearchResultCell
all 3rd party XML Library objects

I just found it curious that neither was listed in that list.

Body:
nlobjSearch certainly didn't used to be and I don't think result sets were either.

I generally ended up wrapping my search in function and returning an array of values to avoid serializable exceptions.

e.g.

function batchStatements(){

    var statementCusts = (function(){
        var allowResend = 'T' == nlapiGetContext().getSetting('SCRIPT', 'custscript_kotn_statement_resend');
        var filters = [
            sf('balance', null, 'greaterthanorequalto', 35),  // over the threshhold
            sf('emailtransactions', null, 'is','T'),
            sf('custentity_kotn_suppress_statements', null, 'is', 'F')
        ];
        if(!allowResend){
            var resendCutoffDays = parseInt(nlapiGetContext().getSetting('SCRIPT', 'custscript_kotn_resend_limit'),10) || 14;// 14 days allows bi-montly batches if desired.
            var resendCutoff = new Date(new Date().getTime() - resendCutoffDays * 24 * 3600 * 1000);
            nlapiLogExecution("DEBUG", "limit statements since "+ resendCutoff.toISOString());
            filters.push(sf('custentity_kotn_last_statement', null, 'notafter', nlapiDateToString(resendCutoff)));
        }
        var srch = nlapiCreateSearch('customer',
            filters,
            [
                sc('entityid'),
                sc('custentity_kotn_billing_email'),
                sc('email'),
                sc('subsidiary')
            ]);
        var custs = [];
        var accum = function(res){
            custs.push({
                id:res.getId(),
                billingEmail: res.getValue('custentity_kotn_billing_email'),
                email:res.getValue('email'),
                name:res.getValue('entityid'),
                subsidiary:res.getValue('subsidiary')
            });
            return true;
        }

        srch.runSearch().forEachResult(accum);
        return custs;
    })();

    var testEnt = {};

    simpleBatch(statementCusts, function(cust){
        nlapiLogExecution("AUDIT", "Sending Statement for "+ cust.name);
        var entityComms = entityPreferences.getCustEntity(cust.id);
        var pdfFile = generateStatement(cust.id);
        var emailFile = kotnMergeTemplate(entityComms.statementEmailTemplate, 'customer', cust.id);
        nlapiSendEmail(entityComms.emailFromEmp, cust.billingEmail || cust.email || entityComms.actionEmp, emailFile.getName(), emailFile.getValue(), null, null, {entity:cust.id}, pdfFile, true);
    });
}

simpleBatch is from https://github.com/BKnights/KotN-Netsuite
it handles governance management by tracking the max governance of the function and yielding when needed.


问:
div:nth-child(0) doesn't work
I'm trying to change css attributes of a certain child div inside another div using nth-child index selector, but for some reason no changes occur.

```<code><div class="itemgrid">
    <div class="insideitem"></div>
    <div class="insideitem"></div>
    <div class="insideitem"></div>
    <div class="insideitem"></div>
</div>

.itemgrid{
    width:100%;
    display:block;
    font-style:inherit;
}

.itemgrid div:nth-child(2) :{
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
}
</code>```

Thank you in advance!

答:
because it counts from 1 :

.itemgrid{
    width:100%;
    display:block;
    font-style:inherit;
}

.itemgrid div:nth-child(1){
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
    color : red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="itemgrid">
    <div class="insideitem">Hello</div>
    <div class="insideitem">my</div>
    <div class="insideitem">dear</div>
    <div class="insideitem">friend</div>
</div></code>```

Title: div:nth-child(0) doesn't work

Body:
I'm trying to change css attributes of a certain child div inside another div using nth-child index selector, but for some reason no changes occur.

.itemgrid{
    width:100%;
    display:block;
    font-style:inherit;
}

.itemgrid div:nth-child(2) :{
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
}

Thank you in advance!

Body:
because it counts from 1 :

.itemgrid{
    width:100%;
    display:block;
    font-style:inherit;
}

.itemgrid div:nth-child(1){
    border-width: 1px;
    border-color: #dedede;
    border-style: solid;
    color : red;
}

<div class="itemgrid">
    <div class="insideitem">Hello</div>
    <div class="insideitem">my</div>
    <div class="insideitem">dear</div>
    <div class="insideitem">friend</div>
</div>


问:
Use Url to receive xml
I want to read xml from url:

```<code>URL url = new URL("http://192.168.2.20/test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
</code>```

This works. But when I want to read from a url that needs authentication this method fails.
So for

```<code>url = new URL("http://admin:pass@192.168.2.20/test.xml");
</code>```

it does not work.

Any ideas?

答: Something, like this, may be? http://blogs.deepal.org/2008/01/sending-basic-authentication-using-url.html</p>

Title: Use Url to receive xml

Body:
I want to read xml from url:

URL url = new URL("http://192.168.2.20/test.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();

This works. But when I want to read from a url that needs authentication this method fails.
So for

url = new URL("http://admin:pass@192.168.2.20/test.xml");

it does not work.

Any ideas?


问:
Why does system verilog max() and min() functions return a queue and not a single element?
I noticed this interesting thing about the max() and min() functions in SV LRM (1800-2012) 7.12 (Array manipulation methods). I tried out the max() and min() functions in a dummy SV file

```<code>int a[3] = {0,5,5};
int q[$];
int b;
q = a.max(); // legal
b = a.max(); // illegal
</code>```

The illegal statement error was

```<code>Incompatible complex type assignment
Type of source expression is incompatible with type of target expression.
Mismatching types cannot be used in assignments, initializations and
instantiations. The type of the target is 'int', while the type of the
source is 'int$[$]'.
</code>```

So I commented out the illegal statement and tested it. It compiled and ran fine but I was hoping to get some more insight as to why the function returns a queue and not a single element - I printed out the contents of q and the size, but the size is still 1 and 5 is being printed just once. Kind of redundant then to make the max() and min() functions return a queue ?

答:
The "SystemVerilog for Verification" book by Chris Spear and Greg Tumbush has a good explanation on this topic in Chapter 2.6.2, which I am quoting below:

"The array locator methods find data in an unpacked array.  At first
  you may wonder why these return a queue of values.  After all, there
  is only one maximum value in an array.  However, SystemVerilog needs a
  queue for the case when you ask for a value from an empty queue or
  dynamic array."

Body:
I noticed this interesting thing about the max() and min() functions in SV LRM (1800-2012) 7.12 (Array manipulation methods). I tried out the max() and min() functions in a dummy SV file

int a[3] = {0,5,5};
int q[$];
int b;
q = a.max(); // legal
b = a.max(); // illegal

The illegal statement error was

Incompatible complex type assignment
Type of source expression is incompatible with type of target expression.
Mismatching types cannot be used in assignments, initializations and
instantiations. The type of the target is 'int', while the type of the
source is 'int$[$]'.

So I commented out the illegal statement and tested it. It compiled and ran fine but I was hoping to get some more insight as to why the function returns a queue and not a single element - I printed out the contents of q and the size, but the size is still 1 and 5 is being printed just once. Kind of redundant then to make the max() and min() functions return a queue ?


问:
Why child selector doesn't work?
I'm just wondering why child selector doesn't work between .nav1 and tr:last-child but when I use .nav1 tr:last-child it works, isn't child selector considered a descendant selector so it should work for both codes or does :last-child need a special treatment.

Here's the code:

.nav1 td {
  background-color: #5d93ea;
  padding: 30px 60px;
  border-radius: 20px;
}

/*it works when using:  .nav1 > tr:last-child > td   */

.nav1>tr:last-child>td {
  border-radius: 20px 20px 0px 0px;
}

a {
  text-decoration: none;
  font-family: 'Open Sans', sans-serif;
  font-weight: bold;
  font-size: 1.2em;
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

<table cellspacing="10px" class="nav1">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
</table></code>```

答:
Google Chrome and other browsers that follow standards add a
 tag:

You can see them in the Dev Tools. So you might need to use:

```<code>.nav1 > tbody > tr:last-child > td {
</code>```

Preview

Without > tbody >:

With > tbody >:

Title: Why child selector doesn't work?

Body:
I'm just wondering why child selector doesn't work between .nav1 and tr:last-child but when I use .nav1 tr:last-child it works, isn't child selector considered a descendant selector so it should work for both codes or does :last-child need a special treatment.

Here's the code:

.nav1 td {
  background-color: #5d93ea;
  padding: 30px 60px;
  border-radius: 20px;
}

/*it works when using:  .nav1 > tr:last-child > td   */

.nav1>tr:last-child>td {
  border-radius: 20px 20px 0px 0px;
}

a {
  text-decoration: none;
  font-family: 'Open Sans', sans-serif;
  font-weight: bold;
  font-size: 1.2em;
  color: black;
}

<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

    1
    2
    3
    4

    1
    2
    3
    4

Body:
Google Chrome and other browsers that follow standards add a <tbody> tag:

You can see them in the Dev Tools. So you might need to use:

.nav1 > tbody > tr:last-child > td {

Preview

Without > tbody >:

With > tbody >:


问:
Accessibility: Can a label have children besides the input?
Accessibility question: Can a ... have children besides an <input ... />? We're using Material UI on a project and their <Switch /> component is built like:

```<code><label>
  <div>
    <span>
      <span>
        <input />
      </span>
    </span>
  </div>
</label>
</code>```

which is triggering an accessibility error in HTML_Codesniffer.

Not sure if it's just not used to this structure and expects the label to be the direct parent of input or if it's an actual error.

答:
Can a label have children besides the input?

Yes, and fortunately (or it will be impossible to format the text label). The following is permitted for instance

```<code><label>
  <span>My input label</span>
  <input type="text" />
</label>
</code>```

According to the documentation it can contain any phrasing content:

Phrasing content, but with no descendant labelable elements unless it is the element’s labeled control, and no descendant label elements

In your example, you can't have a div as it's a flow content not a phrasing content although browser and assistive technologies have support for it.

Note that the accessibility error in HTML_Codesniffer might not be linked to that problem, but to the fact that this tool does not link correctly the label with the input.

Body:
Accessibility question: Can a ... have children besides an <input ... />? We're using Material UI on a project and their <Switch /> component is built like:

        <input />

which is triggering an accessibility error in HTML_Codesniffer.

Not sure if it's just not used to this structure and expects the label to be the direct parent of input or if it's an actual error.

Body:
Can a label have children besides the input?

Yes, and fortunately (or it will be impossible to format the text label). The following is permitted for instance

<label>
  <span>My input label</span>
  <input type="text" />
</label>

According to the documentation it can contain any phrasing content:

Phrasing content, but with no descendant labelable elements unless it is the element’s labeled control, and no descendant label elements

In your example, you can't have a div as it's a flow content not a phrasing content although browser and assistive technologies have support for it.

Note that the accessibility error in HTML_Codesniffer might not be linked to that problem, but to the fact that this tool does not link correctly the label with the input.


问:
Extend the View Underneath the Status Bar and Multi-tasking Bar on iPhone X Without Manually Adjusting Constraints in Code?
I was wondering if there's a way to extend a view to be underneath the status bar and multi-tasking bar of the iPhone X without manually adjusting constraints in code based on the device. Using the safe area, container, container margins and top/bottom layout guides doesn't seem to help because the status bar is a different height on the iPhone X vs the previous iPhones and the safe area ends at the top of the multi-tasking bar whereas it ends at the bottom of the screen for previous iPhones. On top of that, the container margins, and top & bottom layout guides are the same as the safe area so those don't seem to work either. It seems like the only way is to make IBOutlets to the layout constraints and adjust the constants in code based on the device. Is there a way to do this purely through Interface Builder?

Here's an example of what I want to accomplish

Here's how it looks on a non-X iPhone. Notice how the scrollview ends off-screen at the bottom and the pineapple gets cut off at the top.

答:
I figured out how to fix the issue. First turn on safe area in your storyboard, then:

for normal view controllers, constrain your view to the superview (top and/or bottom). If you did it right, the constant should be 0 and the view should be flush with the absolute top and/or bottom of the view controller

for table views, do step 1, then with your table view still selected, under size inspector, uncheck 'Insets To Safe Area' and set Content Insets to 'Never'


问:
jQuery dataTable doesn't show sort icon
I am trying to use a jQuery dataTable plugin. The problem is that the sort icon (this arrow which point in which direction data is actual sorted) is not displayed.

My code looks as follows:

$('#example').dataTable({
  "bPaginate": false,
  "bFilter": false,
  "oLanguage": {
    "sInfo": ""
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css" integrity="sha512-BMbq2It2D3J17/C7aRklzOODG1IQ3+MHw3ifzBHMBwGO/0yUqYmsStgBjI0z5EYlaDEFnvYV7gNYdD3vFLRKsA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js" integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<table class="surfClass" cellspacing="1" id="example">
  <thead>
    <tr>
      <th width="120px">Name</th>
      <th width="120px">The hourly rate (points)</th>
      <th>Levels of referrals</th>
      <th>bonuses</th>
      <th width="70px">Payout minimum</th>
    </tr>
  </thead>
</table></code>```

答:
I had the problem too. Just use their own configurator to setup all the options you want form here https://datatables.net/download/ they will generate exactly the .js and .css files you need.
You then can either download or use their own hosted CDN for both files

Title: jQuery dataTable doesn't show sort icon

Body:
I am trying to use a jQuery dataTable plugin. The problem is that the sort icon (this arrow which point in which direction data is actual sorted) is not displayed.

My code looks as follows:

$('#example').dataTable({
  "bPaginate": false,
  "bFilter": false,
  "oLanguage": {
    "sInfo": ""
  }
});

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/dataTables.bootstrap.min.css" integrity="sha512-BMbq2It2D3J17/C7aRklzOODG1IQ3+MHw3ifzBHMBwGO/0yUqYmsStgBjI0z5EYlaDEFnvYV7gNYdD3vFLRKsA==" crossorigin="anonymous" referrerpolicy="no-referrer" />

      Name
      The hourly rate (points)
      Levels of referrals
      bonuses
      Payout minimum


问:
How to pass args to pods based on Ordinal Index in StatefulSets?
Is it possible to pass different args to pods based on their ordinal index in StatefulSets? Didn't find the answer on the StatefulSets documentation. Thanks!</p>

答:
You can avoid using the Downward API by using HOSTNAME:

```<code>command:
- bash
- c
- |
  ordinal=${HOSTNAME##*-}
  if [[ "$ordinal" = "0" ]]; then
    ...
  else
    ...
  fi
</code>```

Body:
You can avoid using the Downward API by using HOSTNAME:

command:
- bash
- c
- |
  ordinal=${HOSTNAME##*-}
  if [[ "$ordinal" = "0" ]]; then
    ...
  else
    ...
  fi


问:
one to one chat in golang
I want to create one to one chat in revel framework but it gives error. Firstly work in revel chat according to demo but refreshing page did not work so I tried this method and dont know how to handle single chat.

Here is an error:

```<code>app server.go:2848: http: panic serving 127.0.0.1:50420: interface conversion: interface is nil, not io.Writer goroutine 166 [running]: net/http.(*conn).serve.func1(0xc4201d03c0)
</code>```

my go code is where I handle ws root,single user chat need to db connection to. I'm using posgres for it

```<code>package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool) // connected clients
var broadcast = make(chan Message)           // broadcast channel

// Configure the upgrader
var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

// Define our message object
type Message struct {
    Email    string `json:"email"`
    Username string `json:"username"`
    Message  string `json:"message"`
    Created  string `json:"created"`
}

func main() {
    // Create a simple file server
    fs := http.FileServer(http.Dir("public"))
    http.Handle("/", fs)

    // Configure websocket route
    http.HandleFunc("/ws", handleConnections)

    // Start listening for incoming chat messages
    go handleMessages()

    // Start the server on localhost port 8000 and log any errors
    log.Println("http server started on :8090")
    err := http.ListenAndServe(":8090", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    // Upgrade initial GET request to a websocket
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    // Make sure we close the connection when the function returns
    defer ws.Close()

    // Register our new client
    clients[ws] = true

    for {
        var msg Message
        // Read in a new message as JSON and map it to a Message object
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, ws)
            break
        }
        // Send the newly received message to the broadcast channel
        broadcast <- msg
    }
}

func handleMessages() {
    for {
        // Grab the next message from the broadcast channel
        msg := <-broadcast
        // Send it out to every client that is currently connected
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}
</code>```

答:
I think you use gorilla/websocket API incorrectly. You copied the echo example which, being a basic demo, is expected to handle a single ws connection only. Start with the chat example. Particularly pay attention to the fact that serveWs is a non-blocking call while your handleConnections is blocking, i.e. it never returns. Take a look here for a full-featured example of gorilla/websocket API use:
https://github.com/tinode/chat/blob/master/server/wshandler.go

As correctly pointed out by Cerise L, you most certainly have a race on your clients although I think it's unlikely to produce a panic. I think the most likely source of panic is a call to Upgrade on a closed http connection. It's impossible to say exactly because you did not post the full output of the panic.

Title: one to one chat in golang

Body:
I want to create one to one chat in revel framework but it gives error. Firstly work in revel chat according to demo but refreshing page did not work so I tried this method and dont know how to handle single chat.

Here is an error:

app server.go:2848: http: panic serving 127.0.0.1:50420: interface conversion: interface is nil, not io.Writer goroutine 166 [running]: net/http.(*conn).serve.func1(0xc4201d03c0)

my go code is where I handle ws root,single user chat need to db connection to. I'm using posgres for it

package main

import (
    "log"
    "net/http"

    "github.com/gorilla/websocket"
)

var clients = make(map[*websocket.Conn]bool) // connected clients
var broadcast = make(chan Message)           // broadcast channel

// Configure the upgrader
var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

// Define our message object
type Message struct {
    Email    string `json:"email"`
    Username string `json:"username"`
    Message  string `json:"message"`
    Created  string `json:"created"`
}

func main() {
    // Create a simple file server
    fs := http.FileServer(http.Dir("public"))
    http.Handle("/", fs)

    // Configure websocket route
    http.HandleFunc("/ws", handleConnections)

    // Start listening for incoming chat messages
    go handleMessages()

    // Start the server on localhost port 8000 and log any errors
    log.Println("http server started on :8090")
    err := http.ListenAndServe(":8090", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

func handleConnections(w http.ResponseWriter, r *http.Request) {
    // Upgrade initial GET request to a websocket
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Fatal(err)
    }
    // Make sure we close the connection when the function returns
    defer ws.Close()

    // Register our new client
    clients[ws] = true

    for {
        var msg Message
        // Read in a new message as JSON and map it to a Message object
        err := ws.ReadJSON(&msg)
        if err != nil {
            log.Printf("error: %v", err)
            delete(clients, ws)
            break
        }
        // Send the newly received message to the broadcast channel
        broadcast <- msg
    }
}

func handleMessages() {
    for {
        // Grab the next message from the broadcast channel
        msg := <-broadcast
        // Send it out to every client that is currently connected
        for client := range clients {
            err := client.WriteJSON(msg)
            if err != nil {
                log.Printf("error: %v", err)
                client.Close()
                delete(clients, client)
            }
        }
    }
}