问:
ImportError: No module named google.protobuf
I am following this guide and using the exact sample of addressbook.proto.

Post the content of compiler generated addressbook_pb2.py file as well.
When I run the following simple program, there is error saying, cannot find google.protobuf, any ideas how to resolve this issue? Thanks.

BTW, using Python 2.7 on Mac OSX.

```<code>from addressbook_pb2 import Person

p = Person()
p.email = "abc"

print p.email
</code>```

Here is the automated generated file addressbook_pb2.py,

```<code># Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: addressbook.proto

import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='addressbook.proto',
  package='tutorial',
  syntax='proto2',
  serialized_pb=_b('\n\x11\x61\x64\x64ressbook.proto\x12\x08tutorial\"\xda\x01\n\x06Person\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\n\n\x02id\x18\x02 \x02(\x05\x12\r\n\x05\x65mail\x18\x03 \x01(\t\x12+\n\x05phone\x18\x04 \x03(\x0b\x32\x1c.tutorial.Person.PhoneNumber\x1aM\n\x0bPhoneNumber\x12\x0e\n\x06number\x18\x01 \x02(\t\x12.\n\x04type\x18\x02 \x01(\x0e\x32\x1a.tutorial.Person.PhoneType:\x04HOME\"+\n\tPhoneType\x12\n\n\x06MOBILE\x10\x00\x12\x08\n\x04HOME\x10\x01\x12\x08\n\x04WORK\x10\x02\"/\n\x0b\x41\x64\x64ressBook\x12 \n\x06person\x18\x01 \x03(\x0b\x32\x10.tutorial.Person')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_PERSON_PHONETYPE = _descriptor.EnumDescriptor(
  name='PhoneType',
  full_name='tutorial.Person.PhoneType',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='MOBILE', index=0, number=0,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='HOME', index=1, number=1,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='WORK', index=2, number=2,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=207,
  serialized_end=250,
)
_sym_db.RegisterEnumDescriptor(_PERSON_PHONETYPE)

_PERSON_PHONENUMBER = _descriptor.Descriptor(
  name='PhoneNumber',
  full_name='tutorial.Person.PhoneNumber',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='number', full_name='tutorial.Person.PhoneNumber.number', index=0,
      number=1, type=9, cpp_type=9, label=2,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='type', full_name='tutorial.Person.PhoneNumber.type', index=1,
      number=2, type=14, cpp_type=8, label=1,
      has_default_value=True, default_value=1,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=128,
  serialized_end=205,
)

_PERSON = _descriptor.Descriptor(
  name='Person',
  full_name='tutorial.Person',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='name', full_name='tutorial.Person.name', index=0,
      number=1, type=9, cpp_type=9, label=2,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='id', full_name='tutorial.Person.id', index=1,
      number=2, type=5, cpp_type=1, label=2,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='email', full_name='tutorial.Person.email', index=2,
      number=3, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='phone', full_name='tutorial.Person.phone', index=3,
      number=4, type=11, cpp_type=10, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[_PERSON_PHONENUMBER, ],
  enum_types=[
    _PERSON_PHONETYPE,
  ],
  options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=32,
  serialized_end=250,
)

_ADDRESSBOOK = _descriptor.Descriptor(
  name='AddressBook',
  full_name='tutorial.AddressBook',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='person', full_name='tutorial.AddressBook.person', index=0,
      number=1, type=11, cpp_type=10, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=252,
  serialized_end=299,
)

_PERSON_PHONENUMBER.fields_by_name['type'].enum_type = _PERSON_PHONETYPE
_PERSON_PHONENUMBER.containing_type = _PERSON
_PERSON.fields_by_name['phone'].message_type = _PERSON_PHONENUMBER
_PERSON_PHONETYPE.containing_type = _PERSON
_ADDRESSBOOK.fields_by_name['person'].message_type = _PERSON
DESCRIPTOR.message_types_by_name['Person'] = _PERSON
DESCRIPTOR.message_types_by_name['AddressBook'] = _ADDRESSBOOK

Person = _reflection.GeneratedProtocolMessageType('Person', (_message.Message,), dict(

  PhoneNumber = _reflection.GeneratedProtocolMessageType('PhoneNumber', (_message.Message,), dict(
    DESCRIPTOR = _PERSON_PHONENUMBER,
    __module__ = 'addressbook_pb2'
    # @@protoc_insertion_point(class_scope:tutorial.Person.PhoneNumber)
    ))
  ,
  DESCRIPTOR = _PERSON,
  __module__ = 'addressbook_pb2'
  # @@protoc_insertion_point(class_scope:tutorial.Person)
  ))
_sym_db.RegisterMessage(Person)
_sym_db.RegisterMessage(Person.PhoneNumber)

AddressBook = _reflection.GeneratedProtocolMessageType('AddressBook', (_message.Message,), dict(
  DESCRIPTOR = _ADDRESSBOOK,
  __module__ = 'addressbook_pb2'
  # @@protoc_insertion_point(class_scope:tutorial.AddressBook)
  ))
_sym_db.RegisterMessage(AddressBook)

# @@protoc_insertion_point(module_scope)
</code>```

Edit 1

Tried pip install protobuf, met with the following error,

```<code>Requirement already satisfied (use --upgrade to upgrade): protobuf in /Users/foo/miniconda2/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): six>=1.9 in /Users/foo/miniconda2/lib/python2.7/site-packages/six-1.10.0-py2.7.egg (from protobuf)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /Users/foo/miniconda2/lib/python2.7/site-packages (from protobuf)
</code>```

Here is the output of python version,

```<code>python -V
Python 2.7.11 :: Continuum Analytics, Inc.
</code>```

Edit 2

Post exact error message,

```<code>Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1531, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 938, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Users/foo/personal/featureExtraction/protobuf_test.py", line 1, in <module>
    from addressbook_pb2 import Person
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 71, in patched_import
    return original_import(name, *args, **kwargs)
  File "/Users/foo/personal/featureExtraction/addressbook_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 71, in patched_import
    return original_import(name, *args, **kwargs)
ImportError: No module named google.protobuf
</code>```

Edit 3

error message when import google,

Edit 4

Output of which pip,

```<code>which pip
/Users/foo/miniconda2/bin/pip
</code>```

Output of sys.executable,

/Users/foo/anaconda/bin/python

Edit 5

```<code>foo-mn1:featureExtraction foo$ sudo /Users/foo/miniconda2/bin/pip install protobuf
Password:
The directory '/Users/foo/Library/Caches/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 '/Users/foo/Library/Caches/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.
Requirement already satisfied (use --upgrade to upgrade): protobuf in /Users/foo/miniconda2/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): six>=1.9 in /Users/foo/miniconda2/lib/python2.7/site-packages/six-1.10.0-py2.7.egg (from protobuf)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /Users/foo/miniconda2/lib/python2.7/site-packages (from protobuf)
foo-mn1:featureExtraction foo$ sudo /Users/foo/miniconda2/bin/pip install google
The directory '/Users/foo/Library/Caches/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 '/Users/foo/Library/Caches/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.
Requirement already satisfied (use --upgrade to upgrade): google in /Users/foo/miniconda2/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4 in /Users/foo/miniconda2/lib/python2.7/site-packages (from google)
</code>```

答:
This solved my problem with google.protobuf import in Tensorflow and Python 3.7.5 that i had yesterday.

Check where is protobuf

```<code>pip show protobuf
</code>```

If it is installed you will get something like this

```<code>Name: protobuf
Version: 3.6.1
Summary: Protocol Buffers
Home-page: https://developers.google.com/protocol-buffers/
Author: None
Author-email: None
License: 3-Clause BSD License
Location: /usr/lib/python3/dist-packages
Requires:
Required-by: tensorflow, tensorboard
</code>```

(If not, run pip install protobuf )

Now move into the location folder.

```<code>cd /usr/lib/python3/dist-packages
</code>```

Now run

```<code>touch google/__init__.py
</code>```

Body:
I am following this guide and using the exact sample of addressbook.proto.

Post the content of compiler generated addressbook_pb2.py file as well.
When I run the following simple program, there is error saying, cannot find google.protobuf, any ideas how to resolve this issue? Thanks.

BTW, using Python 2.7 on Mac OSX.

from addressbook_pb2 import Person

p = Person()
p.email = "abc"

print p.email

Here is the automated generated file addressbook_pb2.py,

# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: addressbook.proto

import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='addressbook.proto',
  package='tutorial',
  syntax='proto2',
  serialized_pb=_b('\n\x11\x61\x64\x64ressbook.proto\x12\x08tutorial\"\xda\x01\n\x06Person\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\n\n\x02id\x18\x02 \x02(\x05\x12\r\n\x05\x65mail\x18\x03 \x01(\t\x12+\n\x05phone\x18\x04 \x03(\x0b\x32\x1c.tutorial.Person.PhoneNumber\x1aM\n\x0bPhoneNumber\x12\x0e\n\x06number\x18\x01 \x02(\t\x12.\n\x04type\x18\x02 \x01(\x0e\x32\x1a.tutorial.Person.PhoneType:\x04HOME\"+\n\tPhoneType\x12\n\n\x06MOBILE\x10\x00\x12\x08\n\x04HOME\x10\x01\x12\x08\n\x04WORK\x10\x02\"/\n\x0b\x41\x64\x64ressBook\x12 \n\x06person\x18\x01 \x03(\x0b\x32\x10.tutorial.Person')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_PERSON_PHONETYPE = _descriptor.EnumDescriptor(
  name='PhoneType',
  full_name='tutorial.Person.PhoneType',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='MOBILE', index=0, number=0,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='HOME', index=1, number=1,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='WORK', index=2, number=2,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=207,
  serialized_end=250,
)
_sym_db.RegisterEnumDescriptor(_PERSON_PHONETYPE)

_PERSON_PHONENUMBER = _descriptor.Descriptor(
  name='PhoneNumber',
  full_name='tutorial.Person.PhoneNumber',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='number', full_name='tutorial.Person.PhoneNumber.number', index=0,
      number=1, type=9, cpp_type=9, label=2,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='type', full_name='tutorial.Person.PhoneNumber.type', index=1,
      number=2, type=14, cpp_type=8, label=1,
      has_default_value=True, default_value=1,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=128,
  serialized_end=205,
)

_PERSON = _descriptor.Descriptor(
  name='Person',
  full_name='tutorial.Person',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='name', full_name='tutorial.Person.name', index=0,
      number=1, type=9, cpp_type=9, label=2,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='id', full_name='tutorial.Person.id', index=1,
      number=2, type=5, cpp_type=1, label=2,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='email', full_name='tutorial.Person.email', index=2,
      number=3, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='phone', full_name='tutorial.Person.phone', index=3,
      number=4, type=11, cpp_type=10, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[_PERSON_PHONENUMBER, ],
  enum_types=[
    _PERSON_PHONETYPE,
  ],
  options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=32,
  serialized_end=250,
)

_ADDRESSBOOK = _descriptor.Descriptor(
  name='AddressBook',
  full_name='tutorial.AddressBook',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='person', full_name='tutorial.AddressBook.person', index=0,
      number=1, type=11, cpp_type=10, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto2',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=252,
  serialized_end=299,
)

_PERSON_PHONENUMBER.fields_by_name['type'].enum_type = _PERSON_PHONETYPE
_PERSON_PHONENUMBER.containing_type = _PERSON
_PERSON.fields_by_name['phone'].message_type = _PERSON_PHONENUMBER
_PERSON_PHONETYPE.containing_type = _PERSON
_ADDRESSBOOK.fields_by_name['person'].message_type = _PERSON
DESCRIPTOR.message_types_by_name['Person'] = _PERSON
DESCRIPTOR.message_types_by_name['AddressBook'] = _ADDRESSBOOK

Person = _reflection.GeneratedProtocolMessageType('Person', (_message.Message,), dict(

  PhoneNumber = _reflection.GeneratedProtocolMessageType('PhoneNumber', (_message.Message,), dict(
    DESCRIPTOR = _PERSON_PHONENUMBER,
    __module__ = 'addressbook_pb2'
    # @@protoc_insertion_point(class_scope:tutorial.Person.PhoneNumber)
    ))
  ,
  DESCRIPTOR = _PERSON,
  __module__ = 'addressbook_pb2'
  # @@protoc_insertion_point(class_scope:tutorial.Person)
  ))
_sym_db.RegisterMessage(Person)
_sym_db.RegisterMessage(Person.PhoneNumber)

AddressBook = _reflection.GeneratedProtocolMessageType('AddressBook', (_message.Message,), dict(
  DESCRIPTOR = _ADDRESSBOOK,
  __module__ = 'addressbook_pb2'
  # @@protoc_insertion_point(class_scope:tutorial.AddressBook)
  ))
_sym_db.RegisterMessage(AddressBook)

# @@protoc_insertion_point(module_scope)

Edit 1

Tried pip install protobuf, met with the following error,

Requirement already satisfied (use --upgrade to upgrade): protobuf in /Users/foo/miniconda2/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): six>=1.9 in /Users/foo/miniconda2/lib/python2.7/site-packages/six-1.10.0-py2.7.egg (from protobuf)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /Users/foo/miniconda2/lib/python2.7/site-packages (from protobuf)

Here is the output of python version,

python -V
Python 2.7.11 :: Continuum Analytics, Inc.

Edit 2

Post exact error message,

Traceback (most recent call last):
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 1531, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/pydevd.py", line 938, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Users/foo/personal/featureExtraction/protobuf_test.py", line 1, in <module>
    from addressbook_pb2 import Person
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 71, in patched_import
    return original_import(name, *args, **kwargs)
  File "/Users/foo/personal/featureExtraction/addressbook_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor
  File "/Applications/PyCharm CE.app/Contents/helpers/pydev/_pydev_bundle/pydev_monkey_qt.py", line 71, in patched_import
    return original_import(name, *args, **kwargs)
ImportError: No module named google.protobuf

Edit 3

error message when import google,

Edit 4

Output of which pip,

which pip
/Users/foo/miniconda2/bin/pip

Output of sys.executable,

/Users/foo/anaconda/bin/python

Edit 5

foo-mn1:featureExtraction foo$ sudo /Users/foo/miniconda2/bin/pip install protobuf
Password:
The directory '/Users/foo/Library/Caches/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 '/Users/foo/Library/Caches/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.
Requirement already satisfied (use --upgrade to upgrade): protobuf in /Users/foo/miniconda2/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): six>=1.9 in /Users/foo/miniconda2/lib/python2.7/site-packages/six-1.10.0-py2.7.egg (from protobuf)
Requirement already satisfied (use --upgrade to upgrade): setuptools in /Users/foo/miniconda2/lib/python2.7/site-packages (from protobuf)
foo-mn1:featureExtraction foo$ sudo /Users/foo/miniconda2/bin/pip install google
The directory '/Users/foo/Library/Caches/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 '/Users/foo/Library/Caches/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.
Requirement already satisfied (use --upgrade to upgrade): google in /Users/foo/miniconda2/lib/python2.7/site-packages
Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4 in /Users/foo/miniconda2/lib/python2.7/site-packages (from google)

Body:
This solved my problem with google.protobuf import in Tensorflow and Python 3.7.5 that i had yesterday.

Check where is protobuf

pip show protobuf

If it is installed you will get something like this

Name: protobuf
Version: 3.6.1
Summary: Protocol Buffers
Home-page: https://developers.google.com/protocol-buffers/
Author: None
Author-email: None
License: 3-Clause BSD License
Location: /usr/lib/python3/dist-packages
Requires:
Required-by: tensorflow, tensorboard

(If not, run pip install protobuf )

Now move into the location folder.

cd /usr/lib/python3/dist-packages

Now run

touch google/__init__.py


来源: stackexchange

问:
Why does this wrapping allocator's constructor take in the wrong type during template substitution (perfect forwarding ctor)?
For some context, I'm writing an allocator that takes in a base allocator as a template type, and does nothing but forward the allocate() and deallocate() calls to the underlying allocator member. Creating std::vectors with this custom allocator works fine. I tried writing a make_shared wrapper that will use dummy_allocator<T, std::allocator<T>> by default but it wasn't successful. Here is a reproducible example:

```<code>#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc<U>> other;
    };

    template<typename... Args>
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
std::shared_ptr<T> allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
std::shared_ptr<T> make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    auto ptr = test::make_shared<double>();
    return 0;
}
</code>```

When I ran the above code, the compiler generated some bizarre template substitution failure errors:

```<code>/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/testing/src/alloc.cpp:44:35:   required from ‘std::shared_ptr<_Tp> test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:50:36:   required from ‘std::shared_ptr<_Tp> test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:86:46:   required from here
/home/ray/home/testing/src/alloc.cpp:25:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/testing/src/alloc.cpp:25:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided
... (The above error basically is repeated 2 more times)
</code>```

In particular, this error seemed representative of the problem occurring:

```<code>error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
</code>```

Where it basically says "in the constructor of dummy_allocator, you can't pass in a dummy_allocator to the std::allocator's constructor". But I'm not doing that. In allocate_shared, I'm passing in the std::allocator into the dummy_allocator.

I've really scratched my head reading the compiler error but came to no conclusions on what I'm doing wrong. Any help would be greatly appreciated!

EDIT: I think I have a hunch that whatever magic shared_ptr is doing underneath, it's trying to do a copy constructor of my dummy_allocator, and perfect forwarding is capturing the copy construction instead an actual copy constructor. However, I have no idea how to solve this as it's a variadic template and I can't use std::is_same<Args, dummy_allocator> as a requires clause in the perfect forwarding constructor.

So as Daniel Langr has pointed out, just copy constructing the dummy_allocator will fail. I fixed that issue with the following requires clause:

```<code>...
    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;
...

</code>```

However, that's not enough to fix the shared_ptr issue, where the error is a bit longer...*

So here is the error you get:

```<code>#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    /// Necessary for allocators, propagate exactly what the base_allocator
    /// wants.
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc<U>> other;
    };

    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
auto allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
auto make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    // This will fail
    auto ptr = test::make_shared<double>();

    // This will now work
    auto dummy_alloc = test::dummy_allocator<int, std::allocator<int>>();
    auto dummy_alloc2 = test::dummy_allocator<int, std::allocator<int>>(dummy_alloc);
    return 0;
}
</code>```

The associated error:

```<code>/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/test/src/alloc.cpp:53:35:   required from ‘auto test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/test/src/alloc.cpp:59:36:   required from ‘auto test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/test/src/alloc.cpp:95:46:   required from here
/home/ray/home/test/src/alloc.cpp:31:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/test/src/alloc.cpp:31:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided
</code>```

答:
Just remove the variadic constructor and add these two:

```<code>dummy_allocator(const base_allocator& a) : alloc(a)
{}

template<class U, class Alloc>
dummy_allocator(const dummy_allocator<U, Alloc>& a) : alloc(a.alloc)
{}
</code>```

Demo

This doesn't solve the issue if I wanted to forward arguments to an allocator that requires arguments :(

Then you can use std::is_constructible:

```<code>template<class... Args>
dummy_allocator(Args&&... args)
requires(std::is_constructible_v<base_allocator, Args...>)
    : alloc(std::forward<Args>(args)...)
{}

template<class U, class Alloc>
dummy_allocator(const dummy_allocator<U, Alloc>& a) : alloc(a.alloc)
{}
</code>```

Demo

Note that template<class U, class Alloc> dummy_allocator constuctor is needed in both cases, because dummy_allocator a(b) should be well-formed for any b of rebinded allocator type.

ContentLicense: CC BY-SA 4.0

Body:
For some context, I'm writing an allocator that takes in a base allocator as a template type, and does nothing but forward the allocate() and deallocate() calls to the underlying allocator member. Creating std::vectors with this custom allocator works fine. I tried writing a make_shared wrapper that will use dummy_allocator<T, std::allocator<T>> by default but it wasn't successful. Here is a reproducible example:

#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc> other;
    };

    template<typename... Args>
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
std::shared_ptr<T> allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
std::shared_ptr<T> make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    auto ptr = test::make_shared<double>();
    return 0;
}

When I ran the above code, the compiler generated some bizarre template substitution failure errors:

/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/testing/src/alloc.cpp:44:35:   required from ‘std::shared_ptr<_Tp> test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:50:36:   required from ‘std::shared_ptr<_Tp> test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/testing/src/alloc.cpp:86:46:   required from here
/home/ray/home/testing/src/alloc.cpp:25:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/testing/src/alloc.cpp:25:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   25 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/testing/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided
... (The above error basically is repeated 2 more times)

In particular, this error seemed representative of the problem occurring:

error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’

Where it basically says "in the constructor of dummy_allocator, you can't pass in a dummy_allocator to the std::allocator's constructor". But I'm not doing that. In allocate_shared, I'm passing in the std::allocator into the dummy_allocator.

I've really scratched my head reading the compiler error but came to no conclusions on what I'm doing wrong. Any help would be greatly appreciated!

EDIT: I think I have a hunch that whatever magic shared_ptr is doing underneath, it's trying to do a copy constructor of my dummy_allocator, and perfect forwarding is capturing the copy construction instead an actual copy constructor. However, I have no idea how to solve this as it's a variadic template and I can't use std::is_same<Args, dummy_allocator> as a requires clause in the perfect forwarding constructor.

So as Daniel Langr has pointed out, just copy constructing the dummy_allocator will fail. I fixed that issue with the following requires clause:

...
    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;
...

However, that's not enough to fix the shared_ptr issue, where the error is a bit longer...*

So here is the error you get:

#include <memory>
namespace test {

template<typename T, typename base_allocator=std::allocator<T>>
class dummy_allocator {
public:
    /// Necessary for allocators, propagate exactly what the base_allocator
    /// wants.
    typedef typename std::allocator_traits<base_allocator>::size_type size_type;
    typedef typename std::allocator_traits<base_allocator>::difference_type difference_type;
    typedef typename std::allocator_traits<base_allocator>::pointer pointer;
    typedef typename std::allocator_traits<base_allocator>::const_pointer const_pointer;
    typedef typename std::allocator_traits<base_allocator>::value_type value_type;

    template<class U>
    struct rebind {
        typedef dummy_allocator<U,
                typename std::allocator_traits<base_allocator>::template rebind_alloc> other;
    };

    template <typename T1, typename ...TV>
    struct is_dummy : std::is_same<typename std::decay<T1>::type, dummy_allocator<T, base_allocator>>{
    };

    template<typename... Args>
    requires (!is_dummy<Args...>::value)
    dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}

    dummy_allocator() = default;
    dummy_allocator(const dummy_allocator& a) = default;

    [[nodiscard]] T *allocate(std::size_t n) {
        T *p = alloc.allocate(n);
        return p;
    }

    void deallocate(T *p, std::size_t size) noexcept {
        alloc.deallocate(p, size);
    }

private:
    base_allocator alloc;
};

/// Allocate using a wrapped version of passed in allocator
template <typename T, typename Alloc, typename... Args>
auto allocate_shared(const Alloc& alloc, Args&&... args) {
    auto dummy_alloc = dummy_allocator<T, Alloc>(alloc);
    return std::allocate_shared<T>(dummy_alloc, std::forward<Args>(args)...);
}

/// Create a shared pointer from a default stl allocator wrapped in profile allocator.
template <typename T, typename... Args>
auto make_shared(Args&&... args) {
    return test::allocate_shared<T>(std::allocator<T>(), std::forward<Args>(args)...);
}

} // namespace test

int main() {
    // This will fail
    auto ptr = test::make_shared<double>();

    // This will now work
    auto dummy_alloc = test::dummy_allocator<int, std::allocator<int>>();
    auto dummy_alloc2 = test::dummy_allocator<int, std::allocator<int>>(dummy_alloc);
    return 0;
}

The associated error:

/usr/include/c++/10.1.0/bits/shared_ptr_base.h:679:43:   required from ‘std::__shared_count<_Lp>::__shared_count(_Tp*&, std::_Sp_alloc_shared_tag<_Alloc>, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr_base.h:1371:71:   required from ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double; __gnu_cxx::_Lock_policy _Lp = __gnu_cxx::_S_atomic]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:408:59:   required from ‘std::shared_ptr<_Tp>::shared_ptr(std::_Sp_alloc_shared_tag<_Tp>, _Args&& ...) [with _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}; _Tp = double]’
/usr/include/c++/10.1.0/bits/shared_ptr.h:859:14:   required from ‘std::shared_ptr<_Tp> std::allocate_shared(const _Alloc&, _Args&& ...) [with _Tp = double; _Alloc = test::dummy_allocator<double, std::allocator<double> >; _Args = {}]’
/home/ray/home/test/src/alloc.cpp:53:35:   required from ‘auto test::allocate_shared(const Alloc&, Args&& ...) [with T = double; Alloc = std::allocator<double>; Args = {}]’
/home/ray/home/test/src/alloc.cpp:59:36:   required from ‘auto test::make_shared(Args&& ...) [with T = double; Args = {}]’
/home/ray/home/test/src/alloc.cpp:95:46:   required from here
/home/ray/home/test/src/alloc.cpp:31:82: error: no matching function for call to ‘std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >::allocator(const test::dummy_allocator<double, std::allocator<double> >&)’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note: candidate: ‘template<class _Tp1> constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator<_Tp1>&) [with _Tp1 = _Tp1; _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  157 |  allocator(const allocator<_Tp1>&) _GLIBCXX_NOTHROW { }
      |  ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:157:2: note:   template argument deduction/substitution failed:
/home/ray/home/test/src/alloc.cpp:31:82: note:   ‘const test::dummy_allocator<double, std::allocator<double> >’ is not derived from ‘const std::allocator<_Up>’
   31 |     dummy_allocator(Args &&... args) noexcept : alloc(std::forward<Args>(args)...) {}
      |                                                                                ^
In file included from /usr/include/c++/10.1.0/list:61,
                 from /home/ray/home/test/src/alloc.cpp:3:
/usr/include/c++/10.1.0/bits/allocator.h:147:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator(const std::allocator< <template-parameter-1-1> >&) [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:147:34: note:   no known conversion for argument 1 from ‘const test::dummy_allocator<double, std::allocator<double> >’ to ‘const std::allocator<std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic> >&’
  147 |       allocator(const allocator& __a) _GLIBCXX_NOTHROW
      |                 ~~~~~~~~~~~~~~~~~^~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note: candidate: ‘constexpr std::allocator< <template-parameter-1-1> >::allocator() [with _Tp = std::_Sp_counted_ptr_inplace<double, test::dummy_allocator<double, std::allocator<double> >, __gnu_cxx::_S_atomic>]’
  144 |       allocator() _GLIBCXX_NOTHROW { }
      |       ^~~~~~~~~
/usr/include/c++/10.1.0/bits/allocator.h:144:7: note:   candidate expects 0 arguments, 1 provided

Body:
Just remove the variadic constructor and add these two:

dummy_allocator(const base_allocator& a) : alloc(a)
{}

template<class U, class Alloc>
dummy_allocator(const dummy_allocator<U, Alloc>& a) : alloc(a.alloc)
{}

Demo

This doesn't solve the issue if I wanted to forward arguments to an allocator that requires arguments :(

Then you can use std::is_constructible:

template<class... Args>
dummy_allocator(Args&&... args)
requires(std::is_constructible_v<base_allocator, Args...>)
    : alloc(std::forward<Args>(args)...)
{}

template<class U, class Alloc>
dummy_allocator(const dummy_allocator<U, Alloc>& a) : alloc(a.alloc)
{}

Demo

Note that template<class U, class Alloc> dummy_allocator constuctor is needed in both cases, because dummy_allocator a(b) should be well-formed for any b of rebinded allocator type.


问:
Mocking Internal State
I'm looking for a suitable mocking tool to mock internal states (e.g. void methods).  I know Powermock and JMock can do this but I have not made a choice yet.  I have more experience with EasyMock but have not tried mocking internal states.  I'm not so sure if it is inherently supported.  I'm still scouring its documentation.</p>

答:
By internal state, i assume you might be meaning some private or package-private method that your public method calls in order to do its job.  In my view, if your internally-called method is so complicated that you want to mock it out, then you should really pull it out into it's own class, test that class separately, and then inject it as a service to the original class you wanted to test as a service.

So your class looks something like this and you want to test someMethod.

```<code>public class Original {
    public void someMethod() {
        // ... stuff
        Object someValue = callComplicatedPrivateMethod();
        // ... more stuff
    }
}
</code>```

I would change it to this:

```<code>public class Original {
    private ComplicatedService service;

    public Original(ComplicatedService service) {
        this.service = service;
    }

    public void someMethod() {
        // ... stuff
        Object someValue = service.callComplicatedMethod();
        // ... more stuff
    }
}
</code>```

Now you can easily (normally) mock ComplicatedService and test your Original class as normal.

ContentLicense: CC BY-SA 3.0

Title: Mocking Internal State

Body:
By internal state, i assume you might be meaning some private or package-private method that your public method calls in order to do its job.  In my view, if your internally-called method is so complicated that you want to mock it out, then you should really pull it out into it's own class, test that class separately, and then inject it as a service to the original class you wanted to test as a service.

So your class looks something like this and you want to test someMethod.

public class Original {
    public void someMethod() {
        // ... stuff
        Object someValue = callComplicatedPrivateMethod();
        // ... more stuff
    }
}

I would change it to this:

public class Original {
    private ComplicatedService service;

    public Original(ComplicatedService service) {
        this.service = service;
    }

    public void someMethod() {
        // ... stuff
        Object someValue = service.callComplicatedMethod();
        // ... more stuff
    }
}

Now you can easily (normally) mock ComplicatedService and test your Original class as normal.


问:
sqlite dot commands variable expansion like bash
I have a loop in bash that sets some pathnames as variables.

Within that loop I want to perform some sqlite commands based on these variables.

for example:

sqlitedb="/Users/Documents/database.db"
for mm in 01 02 03; do
filename1="A:/data1-${mm}.csv"
filename2="D:/data2-${mm}.csv"
sqlite3 "$sqlitedb" #create new file, it is a temporary file.  no problem with this command.
.mode csv
.import "$filename1" data_1 #try to import the first data file.  This command doesn't work
.import "$filename2" data_2 #try to import the second data file.  This command doesn't work
# now do some important sql stuff which joins these files.
.quit
rm -f "$sqlitedb" #remove old file, ready for the next loop
done

```

Clearly, SQLITE doesn't know about my BASH variables.  What is the best way to set variables, loop through files, etc within sqlite3?

If it helps, I'm using  WSL ubuntu 18.04

答:
You need a heredoc, as mentioned in comments:

```<code>for mm in 01 02 03; do
    filename1="A:/data1-${mm}.csv"
    filename2="D:/data2-${mm}.csv"
    sqlite3 -batch -csv <<EOF
.import "$filename1" data_1
.import "$filename2" data_2
-- Do stuff with the tables
EOF
done
</code>```

(If you leave off a filename, sqlite uses a in-memory database so you don't need a manual temporary database file unless you have a lot of data to store)

Body:
I have a loop in bash that sets some pathnames as variables.

Within that loop I want to perform some sqlite commands based on these variables.

for example:

sqlitedb="/Users/Documents/database.db"
for mm in 01 02 03; do
filename1="A:/data1-${mm}.csv"
filename2="D:/data2-${mm}.csv"
sqlite3 "$sqlitedb" #create new file, it is a temporary file.  no problem with this command.
.mode csv
.import "$filename1" data_1 #try to import the first data file.  This command doesn't work
.import "$filename2" data_2 #try to import the second data file.  This command doesn't work
# now do some important sql stuff which joins these files.
.quit
rm -f "$sqlitedb" #remove old file, ready for the next loop
done

Clearly, SQLITE doesn't know about my BASH variables.  What is the best way to set variables, loop through files, etc within sqlite3?

If it helps, I'm using  WSL ubuntu 18.04

Body:
You need a heredoc, as mentioned in comments:

for mm in 01 02 03; do
    filename1="A:/data1-${mm}.csv"
    filename2="D:/data2-${mm}.csv"
    sqlite3 -batch -csv <<EOF
.import "$filename1" data_1
.import "$filename2" data_2
-- Do stuff with the tables
EOF
done

(If you leave off a filename, sqlite uses a in-memory database so you don't need a manual temporary database file unless you have a lot of data to store)


问:
Java print the Value List
Hello i m searching for solution to how see the valus exists at my list ,
code :

```<code>public Iterable<RfpActiveObject> getactive(){
    List<Rfxobject> rx =     rfx.findAll();
    List<Rfpobject> rp = rfp.findAll();

    Long compteurRfx =rfp.count();
    Long CompteurRfp= rfx.count();
    long TabMax = compteurRfx+CompteurRfp;
    List<Object> newList = new ArrayList<Object>();
    newList.add(rx);
    newList.add(rp);
    for(int i =0 ; i<  TabMax ; i++) {
        RfpActiveObject rf =  new RfpActiveObject();
        System.out.println("**** Liste "+i+"  :");
        System.out.println(newList.get(0));
        System.out.println("**** *****************");
     }
}
</code>```

The input to my list is :

```<code>**** Liste 13  :
[com.pfe.backend.models.Rfxobject@2767bc, com.pfe.backend.models.Rfxobject@2389804e, com.pfe.backend.models.Rfxobject@31eda7ed, com.pfe.backend.models.Rfxobject@5ba91ebd, com.pfe.backend.models.Rfxobject@600898f3, com.pfe.backend.models.Rfxobject@fecef4c]
**** *****************
</code>```

I need to get the real value not adress please what i should to do

答:
You have to overwrite the toString() method inside both of your classes - Rfxobject and Rfpobject.

More details

Title: Java print the Value List

Body:
Hello i m searching for solution to how see the valus exists at my list ,
code :

public Iterable<RfpActiveObject> getactive(){
    List<Rfxobject> rx =     rfx.findAll();
    List<Rfpobject> rp = rfp.findAll();

    Long compteurRfx =rfp.count();
    Long CompteurRfp= rfx.count();
    long TabMax = compteurRfx+CompteurRfp;
    List<Object> newList = new ArrayList<Object>();
    newList.add(rx);
    newList.add(rp);
    for(int i =0 ; i<  TabMax ; i++) {
        RfpActiveObject rf =  new RfpActiveObject();
        System.out.println("**** Liste "+i+"  :");
        System.out.println(newList.get(0));
        System.out.println("**** *****************");
     }
}

The input to my list is :

**** Liste 13  :
[com.pfe.backend.models.Rfxobject@2767bc, com.pfe.backend.models.Rfxobject@2389804e, com.pfe.backend.models.Rfxobject@31eda7ed, com.pfe.backend.models.Rfxobject@5ba91ebd, com.pfe.backend.models.Rfxobject@600898f3, com.pfe.backend.models.Rfxobject@fecef4c]
**** *****************

I need to get the real value not adress please what i should to do


问:
Unable to load asset: error when loading an .mp3 file Flutter
I'm adding sounds to my app using the audioplayers package but at first build no sound is played. After a Hot-restart dough when loading the file I get this exception:

```<code>E/flutter (32175): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Unable to load asset: assets/assets/click.mp3
E/flutter (32175): #0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
E/flutter (32175): <asynchronous suspension>
E/flutter (32175): #1      AudioCache._fetchAsset (package:audioplayers/audio_cache.dart:60:29)
E/flutter (32175): #2      AudioCache.fetchToMemory (package:audioplayers/audio_cache.dart:67:30)
E/flutter (32175): <asynchronous suspension>
E/flutter (32175): #3      AudioCache.load (package:audioplayers/audio_cache.dart:82:37)
E/flutter (32175): #4      AudioCache.getAbsoluteUrl (package:audioplayers/audio_cache.dart:140:23)
E/flutter (32175): #5      AudioCache.play (package:audioplayers/audio_cache.dart:103:24)
E/flutter (32175): #6      _MapScreenState.build.<anonymous closure> (package:fixit_cloud_biking/Screens/map_screen.dart:1239:46)
E/flutter (32175): #7      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (32175): #8      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (32175): #9      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (32175): #10     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (32175): #11     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (32175): #12     BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (32175): #13     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (32175): #14     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (32175): #15     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (32175): #16     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (32175): #17     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (32175): #18     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (32175): #19     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (32175): #20     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (32175): #21     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (32175): #22     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (32175): #23     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (32175): #24     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (32175): #25     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (32175): #26     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (32175): #27     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (32175): #28     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (32175):
</code>```

I did put the files in the same assets folder that contains all the images I use for the icons so indentation in pubspec.yaml file is correct.
The problem shouldn't be the file naming either as I use camel cased or single word naming(lesson learned from images naming with empty spaces..).
One thing though worth to mention is that if I drag and drop files onto the assetsfolder I get an error. I tried deleting the folder, recreating it and then drag and drop works, but only once.. files added in a second moment throw the error.
This is the button that should play the sound:

```<code>IconButton(
                        icon: Image.asset('assets/centerMapButton.png'),
                        iconSize: 60,
                        onPressed: () async {
                          await widget.cache.play('assets/click.mp3',
                              volume: 50, mode: PlayerMode.MEDIA_PLAYER);
                          print('Center map button pressed');
                          _mapController.move(userLocation, 16);
                        }),
</code>```

and the AudioCache()is declared as AudioCache cache = new AudioCache();.

答:
TRY CHANGING THIS
assets/click.mp3
TO
click.mp3

I had the same error neglecting the "assets/" in the path makes it play sounds from local seamlessly. Audioplayers assumes that its default path is assets/

Body:
I'm adding sounds to my app using the audioplayers package but at first build no sound is played. After a Hot-restart dough when loading the file I get this exception:

E/flutter (32175): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Unable to load asset: assets/assets/click.mp3
E/flutter (32175): #0      PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
E/flutter (32175): <asynchronous suspension>
E/flutter (32175): #1      AudioCache._fetchAsset (package:audioplayers/audio_cache.dart:60:29)
E/flutter (32175): #2      AudioCache.fetchToMemory (package:audioplayers/audio_cache.dart:67:30)
E/flutter (32175): <asynchronous suspension>
E/flutter (32175): #3      AudioCache.load (package:audioplayers/audio_cache.dart:82:37)
E/flutter (32175): #4      AudioCache.getAbsoluteUrl (package:audioplayers/audio_cache.dart:140:23)
E/flutter (32175): #5      AudioCache.play (package:audioplayers/audio_cache.dart:103:24)
E/flutter (32175): #6      _MapScreenState.build.<anonymous closure> (package:fixit_cloud_biking/Screens/map_screen.dart:1239:46)
E/flutter (32175): #7      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (32175): #8      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (32175): #9      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (32175): #10     TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (32175): #11     BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (32175): #12     BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (32175): #13     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (32175): #14     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (32175): #15     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (32175): #16     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (32175): #17     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (32175): #18     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (32175): #19     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (32175): #20     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (32175): #21     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (32175): #22     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (32175): #23     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (32175): #24     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (32175): #25     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (32175): #26     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (32175): #27     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (32175): #28     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
E/flutter (32175):

I did put the files in the same assets folder that contains all the images I use for the icons so indentation in pubspec.yaml file is correct.
The problem shouldn't be the file naming either as I use camel cased or single word naming(lesson learned from images naming with empty spaces..).
One thing though worth to mention is that if I drag and drop files onto the assetsfolder I get an error. I tried deleting the folder, recreating it and then drag and drop works, but only once.. files added in a second moment throw the error.
This is the button that should play the sound:

IconButton(
                        icon: Image.asset('assets/centerMapButton.png'),
                        iconSize: 60,
                        onPressed: () async {
                          await widget.cache.play('assets/click.mp3',
                              volume: 50, mode: PlayerMode.MEDIA_PLAYER);
                          print('Center map button pressed');
                          _mapController.move(userLocation, 16);
                        }),

and the AudioCache()is declared as AudioCache cache = new AudioCache();.


问:
multiple match on condition after aggregate lookup in mongodb
```<code>db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: ids
      }
    }
  },
  {
    $lookup: {
      from: "admin",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },

])
</code>```

I am getting one value but even expected multiple data which are greater then equal to 01 jan 2020. How can I fix it please guide thanks

答:
You have to unwind the result after lookup to perform $match.

```<code>db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: ids
      }
    }
  },
  {
    $lookup: {
      from: "admin",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  { $unwind: "$data"}
  {
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },
  {
    $group: {
        _id: "$_id",
        status: { "$first": "$status" },
        deleted_at: { "$first": "$deleted_at" }, //You can project more
        data: { "$push": "$data" }
    }
  }
])
</code>```

Body:
db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: ids
      }
    }
  },
  {
    $lookup: {
      from: "admin",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  {
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },

])

I am getting one value but even expected multiple data which are greater then equal to 01 jan 2020. How can I fix it please guide thanks

Body:
You have to unwind the result after lookup to perform $match.

db.setting.aggregate([
  {
    $match: {
      status: true,
      deleted_at: 0,
      _id: {
        $in: ids
      }
    }
  },
  {
    $lookup: {
      from: "admin",
      localField: "_id",
      foreignField: "admin_id",
      as: "data"
    }
  },
  { $unwind: "$data"}
  {
    $match: {
      "data.createdAt": {
        $gte: new Date("2020-01-01")
      }
    }
  },
  {
    $group: {
        _id: "$_id",
        status: { "$first": "$status" },
        deleted_at: { "$first": "$deleted_at" }, //You can project more
        data: { "$push": "$data" }
    }
  }
])


问:
xcopy file, rename, suppress "Does xxx specify a file name..." message
This seems pretty simple and maybe I'm just overlooking the proper flag, but how would I, in one command, copy a file from one directory to another and rename it in the destination directory?  Here's my command:

```<code>if exist "bin\development\whee.config.example"
  if not exist "TestConnectionExternal\bin\Debug\whee.config"
    xcopy "bin\development\whee.config.example"
          "TestConnectionExternal\bin\Debug\whee.config"
</code>```

It prompts me with the following every time:

Does TestConnectionExternal\bin\Debug\whee.config specify a file name
  or directory name on the target (F = file, D = directory)?

I want to suppress this prompt; the answer is always F.

答:
I met same issue when try to copy file with new name only if file does not exist in destination or exist (with new name), but is older. The solution is to add * char at end of destination file name. Example:

```<code>xcopy "C:\src\whee.config.txt" "C:\dest\bee.config.txt*" /D /Y
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This seems pretty simple and maybe I'm just overlooking the proper flag, but how would I, in one command, copy a file from one directory to another and rename it in the destination directory?  Here's my command:

if exist "bin\development\whee.config.example"
  if not exist "TestConnectionExternal\bin\Debug\whee.config"
    xcopy "bin\development\whee.config.example"
          "TestConnectionExternal\bin\Debug\whee.config"

It prompts me with the following every time:

Does TestConnectionExternal\bin\Debug\whee.config specify a file name
  or directory name on the target (F = file, D = directory)?

I want to suppress this prompt; the answer is always F.

Body:
I met same issue when try to copy file with new name only if file does not exist in destination or exist (with new name), but is older. The solution is to add * char at end of destination file name. Example:

xcopy "C:\src\whee.config.txt" "C:\dest\bee.config.txt*" /D /Y


问:
Notched corner rectangles in React Native
I've been trying to figure out a way to create notched/clipped corners in React Native all night.  It seems like something that would be super easy to do but it's apparently not.  I'm guessing SVG is maybe the right call.  Would love to control the corners independently.  How can I make this happen?

答:
You can make a button like this by combination of 3 View: Top notched view, the rectangular central button with text and bottom notched view, your component should look like this:

```<code>import React from 'react';
import {
  StyleSheet, Text, TouchableOpacity, View
} from 'react-native';

const NotchedButton = ({ width, color }) => (
  <TouchableOpacity>
    <View style={{
      ...styles.notchStyle, borderBottomWidth: 10, borderBottomColor: color, width
    }}
    />
    <View style={{ ...styles.centerViewStyle, width, backgroundColor: color }}>
      <Text style={styles.textStyle}>Button</Text>
    </View>
    <View style={{
      ...styles.notchStyle, borderTopWidth: 10, borderTopColor: color, width
    }}
    />
  </TouchableOpacity>
);

NotchedButton.defaultProps = {
  width: '90%',
  color: 'red',
};

const styles = StyleSheet.create({
  notchStyle: {
    height: 10,
    borderLeftWidth: 10,
    borderLeftColor: 'transparent',
    borderRightWidth: 10,
    borderRightColor: 'transparent',
    borderStyle: 'solid'
  },
  centerViewStyle: {
    justifyContent: 'center', alignItems: 'center', height: 50
  },
  textStyle: { fontSize: 24, color: 'white' }
});

export default NotchedButton;
</code>```

This component will look like this:

You can extract properties from this component as props like button text, width, height, color...

For complex react-native shapes I recommend this excellent tutorial, every time I need a complex ui I follow this tutorial and I find what I want.

Body:
You can make a button like this by combination of 3 View: Top notched view, the rectangular central button with text and bottom notched view, your component should look like this:

import React from 'react';
import {
  StyleSheet, Text, TouchableOpacity, View
} from 'react-native';

const NotchedButton = ({ width, color }) => (
  <TouchableOpacity>
    <View style={{
      ...styles.notchStyle, borderBottomWidth: 10, borderBottomColor: color, width
    }}
    />
    <View style={{ ...styles.centerViewStyle, width, backgroundColor: color }}>
      <Text style={styles.textStyle}>Button</Text>
    </View>
    <View style={{
      ...styles.notchStyle, borderTopWidth: 10, borderTopColor: color, width
    }}
    />
  </TouchableOpacity>
);

NotchedButton.defaultProps = {
  width: '90%',
  color: 'red',
};

const styles = StyleSheet.create({
  notchStyle: {
    height: 10,
    borderLeftWidth: 10,
    borderLeftColor: 'transparent',
    borderRightWidth: 10,
    borderRightColor: 'transparent',
    borderStyle: 'solid'
  },
  centerViewStyle: {
    justifyContent: 'center', alignItems: 'center', height: 50
  },
  textStyle: { fontSize: 24, color: 'white' }
});

export default NotchedButton;

This component will look like this:

You can extract properties from this component as props like button text, width, height, color...

For complex react-native shapes I recommend this excellent tutorial, every time I need a complex ui I follow this tutorial and I find what I want.


问:
Simple way to reference member variables of base class templates
Is there any way to reference member variables of base class templates without base class names and scope resolution operator?

```<code>template<typename D>
struct B0 {
    int value;
};
struct D0: B0<D0> {
    D0() {
        B0<D0>::value = 1; // OK.
        value = 1;         // OK without `B0<D0>::`.
    }
};

template<typename T>
struct B1 {
    T value;
};
template<typename T>
struct D1: B1<T> {
    D1() {
        B1<T>::value = 1; // OK.
        // value = 1; // Compile error without `B1<T>::`.
                      // Compile error: use of undeclared identifier 'value'
                      // `B1<T>::` is tedious everywhere `value` is referenced.
    }
};

template<typename T, typename D>
struct B2 {
    T value;
};
template<typename T>
struct D2: B2<T, D2<T>> { // CRTP
    D2() {
        B2<T, D2<T>>::value = 1; // OK.
        // value = 1; // Compile error without `B2<T, D2<T>>::`.
                      // Compile error: use of undeclared identifier 'value'
                      // `B2<T, D2<T>>::` is more tedious for CRTP.
    }
};

int main() {
    return 0;
}
</code>```

Is it possible to not write B1<T>:: or B2<T, D2<T>>:: which is tedious everywhere value is referenced?

答:
As the solutions, you have to make the name value dependent to make it visible for name lookup. Besides the one you've showed, you can also:

Use using to introduce the name,

```<code>template<typename T>
struct D1: B1<T> {
    using B1<T>::value;   // or move it in method's scope according to your intent
    D1() {
        value = 1;        // OK.
    }
};
</code>```

Qualify with this->.

```<code>template<typename T>
struct D1: B1<T> {
    D1() {
        this->value = 1;  // OK.
    }
};
</code>```

Body:
Is there any way to reference member variables of base class templates without base class names and scope resolution operator?

template<typename D>
struct B0 {
    int value;
};
struct D0: B0<D0> {
    D0() {
        B0<D0>::value = 1; // OK.
        value = 1;         // OK without `B0<D0>::`.
    }
};

template<typename T>
struct B1 {
    T value;
};
template<typename T>
struct D1: B1<T> {
    D1() {
        B1<T>::value = 1; // OK.
        // value = 1; // Compile error without `B1<T>::`.
                      // Compile error: use of undeclared identifier 'value'
                      // `B1<T>::` is tedious everywhere `value` is referenced.
    }
};

template<typename T, typename D>
struct B2 {
    T value;
};
template<typename T>
struct D2: B2<T, D2<T>> { // CRTP
    D2() {
        B2<T, D2<T>>::value = 1; // OK.
        // value = 1; // Compile error without `B2<T, D2<T>>::`.
                      // Compile error: use of undeclared identifier 'value'
                      // `B2<T, D2<T>>::` is more tedious for CRTP.
    }
};

int main() {
    return 0;
}

Is it possible to not write B1<T>:: or B2<T, D2<T>>:: which is tedious everywhere value is referenced?

Body:
As the solutions, you have to make the name value dependent to make it visible for name lookup. Besides the one you've showed, you can also:

Use using to introduce the name,

template<typename T>
struct D1: B1<T> {
    using B1<T>::value;   // or move it in method's scope according to your intent
    D1() {
        value = 1;        // OK.
    }
};

Qualify with this->.

template<typename T>
struct D1: B1<T> {
    D1() {
        this->value = 1;  // OK.
    }
};


问:
Using DefaultTabController in widget tree with variable height
In my app I have a PageView and then in that PageView I have some tabbed content (through use of DefaultTabController).  In those tabs, I have some content of variable height.  No matter what I do, whenever I try to use the DefaultTabController, Flutter throws this error:

```<code>Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was:
  TabBarView file:///C:/code/samples/tabbed/lib/main.dart:104:23
</code>```

I have tried:

Wrapping everything in a ListView with shrinkWrap: true

Using a Column with a minimum Main Axis Size

No matter what I do the TabBarView always tries to render off into infinity.  How can I use a DefaultTabController to show variable height tabs?

This is my code:

```<code> @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: PageView(
        children: [
          Container(
            height: 200,
            color: Colors.blueGrey,
            child: DefaultTabController(
              length: 2,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TabBar(
                    tabs: [
                      Tab(
                        text: "Okay",
                      ),
                      Tab(
                        text: "Go",
                      )
                    ],
                  ),
                  ListView(
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    children: [
                      TabBarView(
                        children: [
                          Text("one"),
                          Text("two"),
                        ],
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Colors.deepOrange,
          ),
          Container(
            color: Colors.cyan,
          )
        ],
      ),
    );
  }
</code>```

答:
Remove the ListView and wrap TabBarView with Expanded, and you should be good to go:

```<code>Expanded(
  child: TabBarView(
    children: [
      Text("one"),
      Text("two"),
    ],
  ),
)
</code>```

Note that now you have a conflict between TabBarView and PageView swiping gestures (You can only swipe the PageView from the TabBar since everything below the latter is covered by TabBarView)

Body:
In my app I have a PageView and then in that PageView I have some tabbed content (through use of DefaultTabController).  In those tabs, I have some content of variable height.  No matter what I do, whenever I try to use the DefaultTabController, Flutter throws this error:

Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
The relevant error-causing widget was:
  TabBarView file:///C:/code/samples/tabbed/lib/main.dart:104:23

I have tried:

Wrapping everything in a ListView with shrinkWrap: true

Using a Column with a minimum Main Axis Size

No matter what I do the TabBarView always tries to render off into infinity.  How can I use a DefaultTabController to show variable height tabs?

This is my code:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: PageView(
        children: [
          Container(
            height: 200,
            color: Colors.blueGrey,
            child: DefaultTabController(
              length: 2,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TabBar(
                    tabs: [
                      Tab(
                        text: "Okay",
                      ),
                      Tab(
                        text: "Go",
                      )
                    ],
                  ),
                  ListView(
                    scrollDirection: Axis.vertical,
                    shrinkWrap: true,
                    children: [
                      TabBarView(
                        children: [
                          Text("one"),
                          Text("two"),
                        ],
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          Container(
            color: Colors.deepOrange,
          ),
          Container(
            color: Colors.cyan,
          )
        ],
      ),
    );
  }

Body:
Remove the ListView and wrap TabBarView with Expanded, and you should be good to go:

Expanded(
  child: TabBarView(
    children: [
      Text("one"),
      Text("two"),
    ],
  ),
)

Note that now you have a conflict between TabBarView and PageView swiping gestures (You can only swipe the PageView from the TabBar since everything below the latter is covered by TabBarView)


问:
How to find the sub folder id in Google Drive using pydrive in Python?
The directory stricture on Google Drive is as follows:
Inside mydrive/BTP/BTP-4

I need to get the folder ID for BTP-4 so that I can transfer a specific file from the folder. How do I do it?

```<code>fileList = GoogleDrive(self.driveConn).ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file in fileList:
    if (file['title'] == "BTP-4"):
        fileID = file['id']
        print(remoteFile, fileID)
        return fileID
</code>```

答:
Will be able to give path like /MyDrive/BTP/BTP-4 and filename as "test.csv" and then directly download the file?

Answer:

Unfortunately, this is not possible.

More Information:

Google Drive supports creating multiple files or folders with the same name in the same location:

As a result of this, in some cases, providing a file path isn't enough to identify a file or folder uniquiely - in this case mydrive/Parent folder/Child folder/Child doc points to two different files, and mydrive/Parent folder/Child folder/Child folder points to five different folders.

You have to either directly search for the folder with its ID, or to get a folder/file's ID you have to search for children recursively through the folders like you are already doing.

Body:
The directory stricture on Google Drive is as follows:
Inside mydrive/BTP/BTP-4

I need to get the folder ID for BTP-4 so that I can transfer a specific file from the folder. How do I do it?

fileList = GoogleDrive(self.driveConn).ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file in fileList:
    if (file['title'] == "BTP-4"):
        fileID = file['id']
        print(remoteFile, fileID)
        return fileID


问:
Tooltip on Hover of select box options generated by ng-options in Angularjs
I am using ng-options to iterate options in select box , Here is my code below ..

```<code><select id="multiSelectAvailable" ng-model="selected.available" multiple
        ng-options="e as e[displayAttr] for e in available"></select>
</code>```

How to show a tooltip of displayAttr when hover on options?

答:
I had similar problem that I solved with a simplistic approach using jquery inside my angular controller.

JS file

```<code>scope.addToolTip = function(){

  $(#multiSelectAvailable option).each(function(i){
     if(i>0){
       var title =  $(this).text();
       $(this).attr('title',title);
     }
  });
}
</code>```

HTML

```<code><select id="multiSelectAvailable" ng-model="selected.available" ng-options="e as e[displayAttr] for e in available" ng-mouseover="addToolTip()"></select>
</code>```

NOTE: addToolTip() method can also be written using simple java script code to modulate dom.

Body:
I am using ng-options to iterate options in select box , Here is my code below ..

<select id="multiSelectAvailable" ng-model="selected.available" multiple
        ng-options="e as e[displayAttr] for e in available"></select>

How to show a tooltip of displayAttr when hover on options?

Body:
I had similar problem that I solved with a simplistic approach using jquery inside my angular controller.

JS file

scope.addToolTip = function(){

  $(#multiSelectAvailable option).each(function(i){
     if(i>0){
       var title =  $(this).text();
       $(this).attr('title',title);
     }
  });
}

HTML

<select id="multiSelectAvailable" ng-model="selected.available" ng-options="e as e[displayAttr] for e in available" ng-mouseover="addToolTip()"></select>

NOTE: addToolTip() method can also be written using simple java script code to modulate dom.


问:
How to add days, months or years to a Primefaces calendar input
i have the following code in an .xhtml file

```<code><!-- /row -->
    <div class="row" id="penaltyStartingDate" style="margin-top: 15px">
        <div class="span8">
            <div class="control-group">
                <label class="hcg-control-label span5">Ημερομηνία Έναρξης Ισχύος Ποινής</label>
                <div class="controls span7">
                    <p:calendar id="penaltyStartingDate" styleClass="hcg-full-width cursor-pointer" pattern="dd/MM/yyyy"
                                value="#{penaltiesView.penalty.penaltyStartingDate}" />
                    <i class="fa fa-calendar hcg-input-icon"></i>
                </div>
            </div>
        </div>
        <!-- /span -->
    </div>
    <!-- /row -->
    <div id="forfeitureDurationContainer" class="row" style="margin-top: 15px">
        <div class="span8">
            <div class="control-group">
                <label class="hcg-control-label span5">Χρόνος Στέρησης</label>
                <div class="controls span7">
                    <p:inputText id="ForfeitureDurationValue" styleClass="hcg-full-width" value="#{penaltiesView.penalty.forfeitureDurationValue}" disabled="#{!penaltiesView.canEdit()}" style="width:30%" required="false" requiredMessage="Ο χρόνος στέρησης είναι υποχρεωτικός." />
                    <p:selectOneMenu id="ForfeitureDurationType" value="#{penaltiesView.penalty.forfeitureDurationType}" disabled="#{!penaltiesView.canEdit()}" styleClass="margin-bottom-10" style="width:70%">
                        <f:selectItem itemLabel="Μήνες" itemValue="Months" />
                        <f:selectItem itemLabel="Ημέρες" itemValue="Days" />
                        <f:selectItem itemLabel="Χρόνια" itemValue="Years" />
                    </p:selectOneMenu>
                </div>
            </div>
        </div>
        <!-- /span -->
    </div>
    <!-- /row -->
    <div class="row" id="penaltyStopDate" style="margin-top: 15px">
        <div class="span8">
            <div class="control-group">
                <label class="hcg-control-label span5">Ημερομηνία Παύσης Ισχύος Ποινής</label>
                <div class="controls span7">
                    <p:calendar id="penaltyStopDate" styleClass="hcg-full-width cursor-pointer" pattern="dd/MM/yyyy" disabled="true"
                                value="#{penaltiesView.penalty.penaltyStopDate}" />
                    <i class="fa fa-calendar hcg-input-icon"></i>
                </div>
            </div>
        </div>
        <!-- /span -->
    </div>
</code>```

And this is what it generates in the webpage
screenshot

The first field is a primefaces calendar. The next one is a field where you put a number and from what you choose in the dropdown menu (which includes days, months, years), a calculated date must appear in the final field which i have disabled. So for example, if I add 01/06/2020 and then type 2 and choose the "days(Ημέρες)" option, in the final field must appear the date 03/06/2020.

Can you help me with this one? I would really appreciate it.

答:
you can achieve it with Calendar. Add ajax in selectOneMenu:

```<code><p:selectOneMenu id="ForfeitureDurationType" value="#{penaltiesView.penalty.forfeitureDurationType}"
                 disabled="#{!penaltiesView.canEdit()}" styleClass="margin-bottom-10" style="width:70%">
                        <p:ajax event="change" listener="#{penaltiesView.calculatePenalty()}"
process="penaltyStartingDate,ForfeitureDurationValue,ForfeitureDurationType"/>
                        <f:selectItem itemLabel="Μήνες" itemValue="Months" />
                        <f:selectItem itemLabel="Ημέρες" itemValue="Days" />
                        <f:selectItem itemLabel="Χρόνια" itemValue="Years" />
                    </p:selectOneMenu>
</code>```

Then in penaltiesView:

```<code>public void calculatePenalty() {
    Calendar c = Calendar.getInstance();
    c.setTime(penalty.penaltyStartingDate);
    if (penalty.forfeitureDurationType.equals("Months") {
        c.add(Calendar.MONTH, penalty.forfeitureDurationValue);
        penalty.penaltyStopDate = c.getTime();
    } else if (penalty.forfeitureDurationType.equals("Days") {
        c.add(Calendar.DAY_OF_MONTH, penalty.forfeitureDurationValue);
        penalty.penaltyStopDate = c.getTime();
    } else {
        c.add(Calendar.YEAR, penalty.forfeitureDurationValue);
        penalty.penaltyStopDate = c.getTime();
    }
    PrimeFaces.current().ajax().update("penaltyStopDate");
}
</code>```

Body:
i have the following code in an .xhtml file

                Ημερομηνία Έναρξης Ισχύος Ποινής

                Χρόνος Στέρησης

                        <f:selectItem itemLabel="Μήνες" itemValue="Months" />
                        <f:selectItem itemLabel="Ημέρες" itemValue="Days" />
                        <f:selectItem itemLabel="Χρόνια" itemValue="Years" />

                Ημερομηνία Παύσης Ισχύος Ποινής

And this is what it generates in the webpage
screenshot

The first field is a primefaces calendar. The next one is a field where you put a number and from what you choose in the dropdown menu (which includes days, months, years), a calculated date must appear in the final field which i have disabled. So for example, if I add 01/06/2020 and then type 2 and choose the "days(Ημέρες)" option, in the final field must appear the date 03/06/2020.

Can you help me with this one? I would really appreciate it.

Body:
you can achieve it with Calendar. Add ajax in selectOneMenu:

<p:selectOneMenu id="ForfeitureDurationType" value="#{penaltiesView.penalty.forfeitureDurationType}"
                 disabled="#{!penaltiesView.canEdit()}" styleClass="margin-bottom-10" style="width:70%">
                        <p:ajax event="change" listener="#{penaltiesView.calculatePenalty()}"
process="penaltyStartingDate,ForfeitureDurationValue,ForfeitureDurationType"/>
                        <f:selectItem itemLabel="Μήνες" itemValue="Months" />
                        <f:selectItem itemLabel="Ημέρες" itemValue="Days" />
                        <f:selectItem itemLabel="Χρόνια" itemValue="Years" />
                    </p:selectOneMenu>

Then in penaltiesView:

public void calculatePenalty() {
    Calendar c = Calendar.getInstance();
    c.setTime(penalty.penaltyStartingDate);
    if (penalty.forfeitureDurationType.equals("Months") {
        c.add(Calendar.MONTH, penalty.forfeitureDurationValue);
        penalty.penaltyStopDate = c.getTime();
    } else if (penalty.forfeitureDurationType.equals("Days") {
        c.add(Calendar.DAY_OF_MONTH, penalty.forfeitureDurationValue);
        penalty.penaltyStopDate = c.getTime();
    } else {
        c.add(Calendar.YEAR, penalty.forfeitureDurationValue);
        penalty.penaltyStopDate = c.getTime();
    }
    PrimeFaces.current().ajax().update("penaltyStopDate");
}