text:
Q: Can't install speechrecognition and pyttsx3 on Mac I'm using 3.8.1, macOS Catalina 10.15.5, I'm new in Python, I tried use pip install speechrecognition and pyttsx3 but it's doesn't work. I tried install pyaudio too but it have a fault.
125:~ quan$ pip install speechrecognition
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: speechrecognition in ./Library/Python/2.7/lib/python/site-packages (3.8.1)

125:~ quan$ pip install PyAudio
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Collecting PyAudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Building wheels for collected packages: PyAudio
  Building wheel for PyAudio (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/setup.py'"'"'; __file__='"'"'/private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-wheel-p9cG4j
       cwd: /private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/
  Complete output (16 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.macosx-10.15-x86_64-2.7
  copying src/pyaudio.py -> build/lib.macosx-10.15-x86_64-2.7
  running build_ext
  building '_portaudio' extension
  creating build/temp.macosx-10.15-x86_64-2.7
  creating build/temp.macosx-10.15-x86_64-2.7/src
  cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -iwithsysroot /usr/local/libressl/include -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -pipe -DMACOSX=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/_portaudiomodule.c -o build/temp.macosx-10.15-x86_64-2.7/src/_portaudiomodule.o
  src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found
  #include "portaudio.h"
           ^~~~~~~~~~~~~
  1 error generated.
  error: command 'cc' failed with exit status 1
  ----------------------------------------
  ERROR: Failed building wheel for PyAudio
  Running setup.py clean for PyAudio
Failed to build PyAudio
Installing collected packages: PyAudio
    Running setup.py install for PyAudio ... error
    ERROR: Command errored out with exit status 1:
     command: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/setup.py'"'"'; __file__='"'"'/private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-record-XU4eyt/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /Users/quan/Library/Python/2.7/include/python2.7/PyAudio
         cwd: /private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/
    Complete output (16 lines):
    running install
    running build
    running build_py
    creating build
    creating build/lib.macosx-10.15-x86_64-2.7
    copying src/pyaudio.py -> build/lib.macosx-10.15-x86_64-2.7
    running build_ext
    building '_portaudio' extension
    creating build/temp.macosx-10.15-x86_64-2.7
    creating build/temp.macosx-10.15-x86_64-2.7/src
    cc -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -iwithsysroot /usr/local/libressl/include -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -pipe -DMACOSX=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c src/_portaudiomodule.c -o build/temp.macosx-10.15-x86_64-2.7/src/_portaudiomodule.o
    src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found
    #include "portaudio.h"
             ^~~~~~~~~~~~~
    1 error generated.
    error: command 'cc' failed with exit status 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /System/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/setup.py'"'"'; __file__='"'"'/private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-install-7DfK8S/PyAudio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/dv/_f33qv0x0j16djzj64q5c6hh0000gn/T/pip-record-XU4eyt/install-record.txt --single-version-externally-managed --user --prefix= --compile --install-headers /Users/quan/Library/Python/2.7/include/python2.7/PyAudio Check the logs for full command output.

125:~ quan$ pip  install pyttsx3
DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support
Defaulting to user installation because normal site-packages is not writeable
Requirement already satisfied: pyttsx3 in ./Library/Python/2.7/lib/python/site-packages (2.7)
Requirement already satisfied: pyobjc>=2.4 in ./Library/Python/2.7/lib/python/site-packages (from pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ColorSync==5.3; platform_release >= "17.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Quartz==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-MediaAccessibility==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-VideoSubscriberAccount==5.3; platform_release >= "18.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreBluetooth==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-DictionaryServices==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ImageCaptureCore==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ExternalAccessory==5.3; platform_release >= "17.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-AVFoundation==5.3; platform_release >= "11.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-StoreKit==5.3; platform_release >= "11.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Network==5.3; platform_release >= "18.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-NotificationCenter==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-PreferencePanes==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-MapKit==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreAudio==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-GameController==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Social==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreSpotlight==5.3; platform_release >= "17.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-InstallerPlugins==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-AVKit==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SecurityFoundation==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-FinderSync==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-MediaPlayer==5.3; platform_release >= "16.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ContactsUI==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SceneKit==5.3; platform_release >= "11.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-DVDPlayback==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-PhotosUI==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-FSEvents==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-AdSupport==5.3; platform_release >= "18.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SyncServices==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreServices==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CFNetwork==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SecurityInterface==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-MultipeerConnectivity==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-WebKit==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-NaturalLanguage==5.3; platform_release >= "18.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-MediaToolbox==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-LocalAuthentication==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreMediaIO==5.3; platform_release >= "11.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-GameKit==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-UserNotifications==5.3; platform_release >= "18.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Automator==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CloudKit==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreLocation==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-AppleScriptKit==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Security==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Vision==5.3; platform_release >= "17.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-OpenDirectory==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-InstantMessage==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ApplicationServices==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-EventKit==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ScreenSaver==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ServiceManagement==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CalendarStore==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-GameplayKit==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-NetworkExtension==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreAudioKit==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-VideoToolbox==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreMedia==5.3; platform_release >= "11.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ScriptingBridge==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-NetFS==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-MediaLibrary==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-IMServicePlugIn==5.3; platform_release >= "11.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-PubSub==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreWLAN==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-DiscRecordingUI==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Intents==5.3; platform_release >= "16.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-DiscRecording==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-libdispatch==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CryptoTokenKit==5.3; platform_release >= "14.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Cocoa==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-OSAKit==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-LaunchServices==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Accounts==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-InputMethodKit==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-DiskArbitration==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Collaboration==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-iTunesLibrary==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ExceptionHandling==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-AddressBook==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-AppleScriptObjC==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-LatentSemanticMapping==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreText==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SafariServices==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-ModelIO==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-IOSurface==5.3; platform_release >= "10.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-BusinessChat==5.3; platform_release >= "18.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreML==5.3; platform_release >= "17.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-CoreData==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SearchKit==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-core==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SpriteKit==5.3; platform_release >= "13.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Contacts==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-SystemConfiguration==5.3 in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-GameCenter==5.3; platform_release >= "12.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-Photos==5.3; platform_release >= "15.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
Requirement already satisfied: pyobjc-framework-QTKit==5.3; platform_release >= "9.0" in ./Library/Python/2.7/lib/python/site-packages (from pyobjc>=2.4->pyttsx3) (5.3)
125:~ quan$


text:
Q: Не срабатывает фунция execve() в Linux При компиляции через g++ 5.4.0 этого кода получаю вывод, из которого могу судить, что execve попросту не срабатывает. Подскажите, пожалуйста, почему?
Исходный код:
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>

int main(int argc, char** argv)
{
    if (argc > 1)
    {
        for(int i = 0; i < argc; i++)
        {
            std::cout << argv[i] << std::endl;
        }

        return 0;
    }

    pid_t pid = fork();
    if (pid < 0)
    {
        std::cout << "Error creating process" << std::endl;
    }
    else if (pid == 0)
    {
        //child
        std::cout << "Hello from Child" << std::endl;

        char** params = new char*[5];

        for (int i = 0; i < 3; i++)
        {
            params[0] = new char[10];
        }

        strcpy(params[0], "1st");
        strcpy(params[1], "2nd");
        strcpy(params[2], "3rd");
        params[3] = nullptr;

        execve("test", params, nullptr);
        return 0;
    }
    else
    {
        //parent
        waitpid(pid, nullptr, 0);

        std::cout << "Hello from parent" << std::endl;
    }

    std::cin.get();

    return 0;
}

Сам вывод:
Hello from Child
Hello from parent

P.S. Компилировал с параметром -std=c++11

A: Исправьте-ка код
for (int i = 0; i < 3; i++)
{
    params[0] = new char[10];
}

Зачем присваивать указатель одной и той же переменной params[0] целых три раза?...

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP absolute file How do we return the absolute path of largest file in a particular directory?
I've been fishing around and haven't turned up anything concrete?
I'm thinking it has something to do with glob()?

A: $sz = 0;
$dir = '/tmp'; // will find largest for `/tmp`
if ($handle = opendir($dir)) { // will iterate through $dir
  while (false !== ($entry = readdir($handle))) {
    if(($curr = filesize($dir . '/' . $entry)) > $sz) { // found larger!
      $sz = $curr;
      $name = $entry;
    }
  }
}
echo $dir . '/' . $name; // largest

A: $dir = 'DIR_NAME';
$max_filesize = 0;
$path= '';

foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator(realpath($dir),FilesystemIterator::SKIP_DOTS)) as $file){
     if ($file->getSize() >= $max_filesize){
       $max_filesize = $file->getSize();
       $path = $file->getRealPath(); // get absolute path
     }
}
echo $path;

A: function getFileSize($directory) {
    $files = array();
    foreach (glob($directory. '*.*') as $file) {
        $files[] = array('path' => $file, 'size' => filesize($file));
    }
    return $files;
}

function getMaxFile($files) {
    $maxSize = 0;
    $maxIndex = -1;
    for ($i = 0; $i < count($files); $i++) {
        if ($files[$i]['size'] > $maxSize) {
            $maxSize = max($maxSize, $files[$i]['size']);
            $maxIndex = $i;
        }
    }
    return $maxIndex;
}

usage:
$dir = '/some/path';
$files = getFileSize($dir);
echo '<pre>';
print_r($files);
echo '</pre>';

$maxIndex = getMaxFile($files);
var_dump($files[$maxIndex]);


text:
Q: Space filling curves The classic Hahn-Mazurkiewicz theorem has the following consequence: Let $X$ be a compact, connected topological manifold. Then there is a continuous surjective map $f: [0,1] \rightarrow X$.
It is also true that such a $f$ cannot be injective unless $X=[0,1]$ (since then $f$ would be a homeomorphism). I was wondering if some weaker notions of this is possible, where injectivity holds (this would be very useful for my research). Specifically, suppose we have a compact, connected Riemannian manifold $(M,g)$, without any boundary. Let $d$ be the metric induced on $M$ by $g$. Then I want to know the following:
For every $\epsilon > 0$, does there exist a map $f_{\epsilon}: [0,1] \rightarrow M$ that is continuous and injective, such that for any $x \in M$ there exists $y \in [0,1]$ such that $d(x,f_{\epsilon}(y)) < \epsilon$?
Does anything change if $M$ is non-compact?

A: I would call such $f_\epsilon$ coarsely $\epsilon$-dense, or more simply $\epsilon$-dense. These exist in the compact case as follows. Tile $M$ by $n$-balls (these may overlap, but only finitely).  Each ball is homeomorphic to $[0, 1]^n$, so admits an $\epsilon/2$-dense smooth Hilbert arc.  A small perturbation of these makes them pairwise disjoint.  Choose an ordering of the $n$-balls.  Now connect the Hilbert arcs together, in order. Tubular neighbourhoods allow us to do this smoothly and injectively.
In the complete, non-compact case this is not possible. This is because the continuous image of a compact set is compact, and thus contained in a metric ball.


text:
Q: C# reference type conditional without comparator I see this sort of thing in javascript all the time, iffy/falsy statements
if (someUnknownType) {
    // will check null | undefined | 0 | false | ''
}

but I've encountered this today in C# for the first time and I can't find seem to find the right words that I can search for this.
_existingInstance = getTheInstanceOrNull();
if (_existingInstance)
    DoSomeThings();

I thought it was odd since it didn't explicitly say existingInstance != null, so I decided to test out a couple things
if (null)
    DoSomeThings();

// Err: Cannot convert null to 'bool' because it is non-nullable

I double checked the return type of the method in question, and ended up testing this next
MyType instance = null;
if (instance)
    DoSomeThings(); // Roslyn says it's okay

Which I suspected would pass, since it's the source of my doubt. I then proceeded to test one last scenario
bool? doNotPass = null;
if (doNotPass)
    DoSomeThings();

// Err: Cannot implicitly convert 'bool?' to 'bool'

What exactly is being checked when a reference type is not explicitly checked against a comparator in a conditional?
I'be been working with C# for a few years now, so if it's well known, is this simply unpopular?
As a last note, I looked at the class definition to make sure there was no  operator overload, and I didn't see any

A: first, bool? is not a reference type.  it's actually a struct, which is a value type.  it's a shortcut to Nullable<bool>.
so that will fail in your comparison.
this was throwing you off.


text:
Q: Unrecognized element 'pollingDuplexHttpBinding' in service reference configuration Im using WCF with two endpoints basicHttpBinding and pollingDuplexHttpBinding.
Consuming WCF in Silverlight 4.
If I have alone basic.. and polling.. it works good. But if I used both in one service and one silverlight project I got message on client side:
"Unrecognized element 'pollingDuplexHttpBinding' in service reference configuration. Note that only a subset of the Windows Communication Foundation configuration functionality is available in Silverlight."
WFC is right referenced to silverlight project, but is not working.
Here is web.config of WCF:
 <services>
      <service behaviorConfiguration="Service1Behavior" name="Service1">
        <endpoint
          address=""
          binding="basicHttpBinding"
          bindingConfiguration="LargeBuffer"
          contract="IService1"
          listenUri="http://localhost:7007/Service1.svc">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint
          address=""
          binding="pollingDuplexHttpBinding"
          bindingConfiguration="multipleMessagesPerPollPollingDuplexHttpBinding"
          contract="ILongService1"
          listenUri="http://localhost:7007/Service1.svc/LongService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>

And here is config on client side:
<endpoint address="http://localhost:7007/ServiceWebTDM.svc/LongService"
      binding="pollingDuplexHttpBinding" bindingConfiguration="multipleMessagesPerPollPollingDuplexHttpBinding"
      contract="GXWebTDM.Web.ILongServiceWebTDM" name="LongServiceWebTDMDev" />

          <endpoint address="http://localhost:7007/ServiceWebTDM.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IServiceWebTDM1" contract="GXWebTDMService.IServiceWebTDM"
                name="ServiceWebTDMDev" />

A: Check out this article
You will need to add the following snippet in client config:
<!-- Register the binding extension from the SDK. -->
<extensions>
  <bindingExtensions>
    <add name=
        "pollingDuplexHttpBinding"
        type="System.ServiceModel.Configuration.PollingDuplexHttpBindingCollectionElement,System.ServiceModel.PollingDuplex, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </bindingExtensions>


text:
Q: How to sort a list by a specific property in .NET 2.0? In .NET 4.0 you can simply use LINQ to quickly sort a list by a specific property:
  List<Point> list = ...;
  sorted = list.OrderBy(p => p.X).ToList(); // sort list of points by X

Can you do something similar when you cannot use .NET 4.0 LINQ syntax?
Is there a one-liner sort syntax?

A: Check Sort method, that takes Comparison<T>. Avaliable from .NET 2.0
var list = new List<Point>{ /* populate list */ };

list.Sort(Comparison);

public int Comparison (Point a, Point b)
{
    //do logic comparison with a and b
    return -1;
}

A: You need to use a delegate, almost a one-liner :)
list.Sort(delegate(Point p1, Point p2){
        return p1.X.CompareTo(p2.X);
});


text:
Q: Silverlight, SSL, HTTPS, WCF, MVC, and Forms Authentication I have an MVC 3 website that is using Forms authentication. The user logins and navigates to a Silverlight 5 application. The Silverlight app is calling a Silverlight-Enabled WCF service on another port. Because one of my requirements is to use Https/SSL, I decided to move the WCF services into a "Services" folder in my MVC application.
To see if the service is working, I typed in the address of my service. I got an error message stating my service requires anonymous access, but the website is specified to use forms authentication. So, I removed my mexHttpBinding in my web.config for my service and added authenticationScheme="Negotiate" to my httpTransport of my binding. (I'm not to https yet).
Now, I get a 302 and am redirected to the log-in page. It seems that my service is suggesting i'm not logged in. So, I added
routes.IgnoreRoute("{resource}.svc/{*pathInfo}");

and
routes.IgnoreRoute("Services/");

but that hasn't made a difference. I think the service says i'm not authenticated, but I'm certain I am.
Can someone explain what I'm doing wrong?
All of this works when I debug on my localhost, but I can't access the service when I deploy to a server.
Edit
I may have found my answer. I turned on anonymous access for my website in IIS and changed the httpTransport's authenticationScheme to the default (Anonymous). I then added
<authorization>
    <deny users="?"/>
</authorization>

along with
<authentication mode="Forms">
  <forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>

which seems to be requiring the user to be authenticated in order to access the service. I am now going to check my silverlight application to make sure it can reach the service and get/post data. This was all in a test application, so I'll have to change my real application accordingly. Then, I'll tackle ssl/https.
Does all this sound right?
EDIT 2
I had to ensure mex was enabled and aspNetCompatibilityEnabled was set to 'false' to get the conctracts to update in my silverlight app. But after updating my services, I set the aspNetCompatibilityEnabled to 'true', and everything appears to be working.
I hope I'm still headed down the right path...

A: I ended up setting up IIS to add the webservice as a website under the parent website. Then, I used the Location tag in the parent site's web.config to implement forms authentication on the webservice.


text:
Q: How to use gedit from putty remote connection on Putty I am struggling to use gedit through a remote connection using Putty from a windows machine, it will really help if someone can find a way to do this.
Is there a way we can use gedit from a windows machine by using putty to remotely connect?

A: There are two different ways of achieving this:

*

*executing a remote gedit using X Forwarding via SSH

*executing a local gedit on a remote file through SSH

Remote gedit
Normally you do that using X Forwarding via SSH. On Windows you will need some kind of X server, for example xming. See http://www.math.umn.edu/systems_guide/putty_xwin32.html for instructions.
There are more tutorials on the web, from brief Googling:

*

*http://courses.cms.caltech.edu/cs11/misc/xwindows.html

*X11 Forwarding using Putty on Windows (Youtube)
Local gedit
You point your local gedit installed on your machine to the remote file through SSH. See e.g. http://thecodecentral.com/2010/04/02/use-gedit-as-remote-file-editor-via-ftp-and-ssh-ubuntu how to do that on Ubuntu.
On Windows, you might want to mount a remote folder as a local disk: How do I mount a remote Linux folder in Windows through SSH?
Alternatively, it might be possible to use a Gedit plugin: https://code.google.com/p/gedit-remote-editing-file/


text:
Q: Using the height of river to approximate its extreme flood boundaries - terrain analysis in QGIS? Using QGIS I'm trying to analyse an area/DEM with this criteria: - heights 10 meter above the river-centerline in both sides of river.
I can do it with the calculation of contours (2m) from DEM and geting the hights of the river-centerline and manually try to draw a line(vector) 10 meters higher than River-Centerline heights (see image below) . But I can't figure out an easy way to filter the boundary area in which the water level of extreme flood cannot reach that hight.

Anyone have any ideas or thoughts on this problem?


text:
Q: Showing a set which is not diophantine contains a thick subset I need to show the set X = {x ∈ [0, 1] : x is not diophantine} contains a thick subset of [0, 1].
A real number x is said to be Diophatine if for every ε > 0, there exists a constant cε such that |x - y| ≥ cε/(|q|2+ε) where y = a/q is a rational number.
So for x not diophantine, we have |x - y| < cε/(|q|2+ε) but i don't know how to use that to show X has a thick subset of [0,1]
any hints?


text:
Q: Borrow a value wrapped in an Option using a method I would like to write a method on a struct which borrows a value wrapped in an Option in one of its properties/fields.
Is it doable ?
Consider
struct A {}

struct Obj {
    a: Option<A>
}

impl Obj {
    fn ref_to_a(&self) -> &A {
        //&self.a.unwrap() <-- How do I implement this ?
    }
}

Playground

A: You can use Option::as_ref to "Convert from Option<T> to Option<&T>."
impl Obj {
    fn ref_to_a(&self) -> &A {
        self.a.as_ref().unwrap()
    }
}

Of course you shouldn't use unwrap, but at least expect.

A: I don't know why you are not borrowing Option itself, but you can mimic unwrap behavior by this way :
impl Obj {
    fn ref_to_a(&self) -> &A {
        match self.a {
            Some(ref a) => return a,
            None => panic!("There is no value"),
        }
    }
}

Note :
Should I avoid unwrap in production application?


text:
Q: Spring - use in injected request scope component in async call I have a rest service that need to do some operations in async mode.
The REST service do the operation on scope request component.
My question:
Do i allowed to use request scope component in an new thread (outside the original http request thread)?
What will happened to resources like entity manager that need to be created in the end of the scope , when spring will close them now? will it be at the end of the http request , so entity manager can be closed in the middle of the async call ?
What is the recipe for this scenario ? what should be the scope of PaymentService, so entity manager will be opened and closed around the async call ?
I can do it explicit , but i am looking for best practice in case exist.
public class RestPayment{
      @Autowired PaymentService paymentService;

      public void pay(){
             new Thread(new Runnable() {
                  public void run() {
                     paymentService.charge(....);
              }
               }).start();
      }
}

@Component
@Scope(value="request")
public class PaymentService{
        @Transactional(value="MainDB", propagation=Propagation.REQUIRED)
        public void charge(...){
        }
}

A: I would say that Spring is out of the picture the moment you call "new".  That object wasn't created by the bean factory, so it's not under Spring's control.  It won't inject those dependencies - it's all on you.
A much better solution would be to create an executor service pool that is under Spring's control.  Let it create the Runnable class that you want to execute.  That way it'll know to inject in the service that you need.


text:
Q: How to pass more than one argument to a worker at backgroundrb I'm trying to pass a list of arguments to a backgroundrb
in documentation it says: MiddleMan.worker(:billing_worker).async_charge_customer(:arg => current_customer.id)
but it only works for just one argument, I tried these but none worked for me
args => [1,2,3]
args => {:t=>"t", :r=> "r"}
any ideas how to solve this??

A: What you are trying seems reasonable to me. I took a look at rails_worker_proxy.rb (from the github source code). From a code read, the async_* methods accept both :arg and :args:
arg,job_key,host_info,scheduled_at,priority = arguments && arguments.values_at(:arg,:job_key,:host,:scheduled_at, :priority)

# allow both arg and args
arg ||= arguments && arguments[:args]

# ...

if worker_method =~ /^async_(\w+)/
  method_name = $1
  worker_options = compact(:worker => worker_name,:worker_key => worker_key,
                           :worker_method => method_name,:job_key => job_key, :arg => arg)
  run_method(host_info,:ask_work,worker_options)

Can you share a code snippet? Have you added any debugging statements in your code and/or in the backgroundrb code itself? (I usually add a few puts statements and inspect things when things go wrong.)
Lastly, have you considered using delayed_job? It has more traction nowadays in the Rails community.

A: Actually, the second method you've tried (args => {:t=>"t", :r=> "r"}) should work.
In your worker:
def charge_customer(arg)
  customer_id   = arg[:customer_id]
  customer_name = arg[:customer_name]

  #do whatever you need to do with these arguments...
end

And then, you can call the worker like this:
MiddleMan.worker(:billing_worker).async_charge_customer(:arg => { :customer_id => current_customer.id, :customer_name => current_customer.name })

Basically, what you're doing here is pass a single Hash as the one argument the worker accepts. But since a Hash can contain multiple key-value pairs, you can access all of these individually inside your worker.


text:
Q: Mapbox Geocoding API - 'Cross-Origin Request Blocked' error I'm trying to call Geocoding API but I'm not having any luck. I keep receiving the following error.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.mapbox.com/gecoding/v5/mapbox.places/fort%20coll…7nugng&autocomplete=true&bbox=-105.214,40.451,-104.85,40.841. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

When I add the header it says it can't run the script. Not sure what else to do. My link is formated properly because it works in mapbox search-Playground
var searchId = document.getElementById('mySearch');
searchId.addEventListener('keyup', function onEvent(e) {
    if (e.keyCode === 13) {
        console.log(searchId.value)
        var urlBase = 'https://api.mapbox.com/gecoding/v5/mapbox.places/';
        var location = searchId.value;
        var bbox = [-105.214, 40.451, -104.850, 40.841]

        var query = urlBase + location + '.json?access_token=' + mapboxgl.accessToken + '&autocomplete=true&bbox=' + bbox;
        $.ajax({
            method: 'GET',
            url: query,
            success: function(data){
              console.log(data)
            }
          })
    }
});


text:
Q: LeJOS GyroSensor sample always 0 I would like to read the current angle from my Ev3GyroSensor, however the returned value is always 0.
I tested multiple Ports nothing worked.
If I test the sensor with the LeJOS integrated Tool, everything works fine.
    EV3GyroSensor ev3GyroSensor = new EV3GyroSensor(SensorPort.S4);

    SampleProvider sampleProvider = ev3GyroSensor.getAngleAndRateMode();
    float[] sample = new float[sampleProvider.sampleSize()];

    sampleProvider.fetchSample(sample, 0);
    System.out.println(sample[0]);

    //I move the robot with my hand
    Delay.msDelay(3000);

    sampleProvider.fetchSample(sample, 0);
    System.out.println(sample[0]);

    ev3GyroSensor.close();

A: try using only angle mode, from my experience, angle and rate mode doesn't always work correctly.
There is also a possibility that you are reading the rate from the sample, but I'm not really sure.


text:
Q: RuntimeError: There is no current event loop in thread 'Thread-1' , multithreading and asyncio error I am having a thread which calls asyncio loops, however this causes the mentioned exception:
RuntimeError: There is no current event loop in thread 'Thread-1'.

This question: RuntimeError: There is no current event loop in thread in async + apscheduler came across the same problem, however they refered to a scheduler which I do not have.
My code is the following:
def worker(ws):
      l1 = asyncio.get_event_loop()
      l1.run_until_complete(ws.start())

      l2 = asyncio.get_event_loop()
      l2.run_forever()

if __name__ == '__main__':
    ws = Server()
    p = threading.Thread(target=worker,args=(ws,))
    p.start()

    while True:
        try:
            #...do sth
        except KeyboardInterrupt:
            p.join()
            exit()

A: I had this issue for running a Bokeh Server in a thread.  When I tried to create the server = Server({'/': app}, port=0), I would get this error.  From the Tornado documentation I found the following...
Class tornado.platform.asyncio.AnyThreadEventLoopPolicy[source]

Event loop policy that allows loop creation on any thread.
The default asyncio event loop policy only automatically creates event loops in the main threads. Other threads must create event loops explicitly or asyncio.get_event_loop (and therefore IOLoop.current) will fail. Installing this policy allows event loops to be created automatically on any thread, matching the behavior of Tornado versions prior to 5.0 (or 5.0 on Python 2).
Usage:
asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy())

http://www.tornadoweb.org/en/stable/asyncio.html#tornado.platform.asyncio.AnyThreadEventLoopPolicy

A: New thread doesn't have an event loop so you have to pass and set it explicitly:
def worker(ws, loop):
    asyncio.set_event_loop(loop)
    loop.run_until_complete(ws.start())

if __name__ == '__main__':
    ws = Server()
    loop = asyncio.new_event_loop()
    p = threading.Thread(target=worker, args=(ws, loop,))
    p.start()

Also, p.join() won't terminate your script correctly as you never stop the server so your loop will continue running, presumably hanging up the thread. You should call smth like loop.call_soon_threadsafe(ws.shutdown) before joining the thread, ideally waiting for the server's graceful shutdown.

A: On Windows with Python 3.7.3, instead of creating the event loop directly in the thread,
I have to:
asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

Otherwise, the problem would persist.


text:
Q: Deleting hierarchical data in mysql I'm working on hierarchical structure using mysql, here is the sample table
SELECT * FROM category ORDER BY category_id;
+-------------+----------------------+--------+
| category_id | name                 | parent |
+-------------+----------------------+--------+
|           1 | ELECTRONICS          |   NULL |
|           2 | TELEVISIONS          |      1 |
|           3 | TUBE                 |      2 |
|           4 | LCD                  |      2 |
|           5 | PLASMA               |      2 |
|           6 | PORTABLE ELECTRONICS |      1 |
|           7 | MP3 PLAYERS          |      6 |
|           8 | FLASH                |      7 |
|           9 | CD PLAYERS           |      6 |
|          10 | 2 WAY RADIOS         |      6 |
+-------------+----------------------+--------+

Anyway to delete all rows in below table ?
SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
FROM category AS t1
LEFT JOIN category AS t2 ON t2.parent = t1.category_id
LEFT JOIN category AS t3 ON t3.parent = t2.category_id
LEFT JOIN category AS t4 ON t4.parent = t3.category_id
WHERE t1.name = 'ELECTRONICS';

+-------------+----------------------+--------------+-------+
| lev1        | lev2                 | lev3         | lev4  |
+-------------+----------------------+--------------+-------+
| ELECTRONICS | TELEVISIONS          | TUBE         | NULL  |
| ELECTRONICS | TELEVISIONS          | LCD          | NULL  |
| ELECTRONICS | TELEVISIONS          | PLASMA       | NULL  |
| ELECTRONICS | PORTABLE ELECTRONICS | MP3 PLAYERS  | FLASH |
| ELECTRONICS | PORTABLE ELECTRONICS | CD PLAYERS   | NULL  |
| ELECTRONICS | PORTABLE ELECTRONICS | 2 WAY RADIOS | NULL  |
+-------------+----------------------+--------------+-------+

Is there anyway to delete all records from select query above?


text:
Q: Qual anotação é usado no mapeamento ORMLite para o Enum como Foreign? Tenho a classe Cliente e o enum AnimaisEstimacao, onde um cliente pode ter 1 ou mais animais de estimação. Ficaria assim:
@DatabaseTable(tableName = "cliente")
public class Cliente{

@DatabaseField(generateId = true)
private Long id;

@DatabaseField
private String nome;

@????
List<AnimaisEstimacao> animais;

Enum AnimaisEstimacao
public enum AnimaisEstimacao{
GATO(0);
CACHORRO(1);
PASSARO(2);
OUTROS(3);
//implementacao
}

Qual seria a anotação ORMLite para o Enum AnimaisEstimacao presente na classe Cliente?

A: Segundo a documentação do ORMLite ficaria assim:
@DatabaseTable(tableName = "cliente")
public class Cliente{

@DatabaseField(generateId = true)
private Long id;

@DatabaseField
private String nome;

@DatabaseField(dataType = DataType.ENUM_INTEGER)
List<AnimaisEstimacao> animais;

A: Há um tempo atrás eu fiz um código parecido. Tenta resolver dessa forma:
@DatabaseTable(tableName = "cliente")
public class Cliente{

@DatabaseField(generateId = true)
private Long id;

@DatabaseField
private String nome;

@ForeignCollectionField(foreign = true, eager = true)
Collection<AnimaisEstimacaoCliente> animais;

Então  você cria uma classe, por exemplo, "AnimaisEstimacaoCliente" com os campos "AnimalEstimacao" e "Cliente" para que haja o relacionamento. Esta classe deve ser uma representação de uma tabela no banco de dados.
@DatabaseTable(tableName = "animais_estimacao_cliente")
    public class AnimaisEstimacaoCliente{

    @DatabaseField(generateId = true)
    private Long id;

    @ForeignCollectionField(foreign = true )
    private Cliente cliente;

    @DatabaseField(dataType = DataType.ENUM_INT)
    private AnimalEstimacao animal;
}

Mais informações estão disponíveis nos links:

*

*http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_2.html#index-collections-of-objects

*https://github.com/j256/ormlite-jdbc/tree/master/src/test/java/com/j256/ormlite/examples/foreignCollection


text:
Q: ArangoDB and velocypack, using immutable classes as dtos I'm starting to use ArangoDB as the persistence layer for an existing java SpringBoot (and SpringData) application.
There are many DTOs, all of which are immutable classes (using AutoValue).
There is, therefore, no default constructor, and arango is unable to instanatiate the dto in order to populate it from the DB.
Is it possible to have the arango spring data layer use the Builder as the way to instantiate and populate the class (ie during deserialization)
It is possible to have jackson use the dto's builder when unnarshalling from json, so as a fallback option, is it possible to configure arango/java/springdata to use jackson/json instead of velocypack ??
with thanks,
Simon
update1
Thanks for the quick answer.  One of the complications I am facing is with autovalue, the generated constructor will be private if there is a builder.  I can take out the generated builder, and will get a package protected constructor, however I am also seeing this ...
com.arangodb.ArangoDBException: com.arangodb.velocypack.exception.VPackParserException: java.lang.InstantiationException: com.arangodb.springframework.core.convert.DBEntity
    at com.arangodb.internal.util.ArangoDeserializerImpl.deserialize(ArangoDeserializerImpl.java:59) ~[arangodb-java-driver-4.4.0.jar:na]
    at com.arangodb.internal.util.ArangoUtilImpl.deserialize(ArangoUtilImpl.java:92) ~[arangodb-java-driver-4.4.0.jar:na]
    at com.arangodb.internal.ArangoExecutor.deserialize(ArangoExecutor.java:120) ~[arangodb-java-driver-4.4.0.jar:na]
.....
Caused by: com.arangodb.velocypack.exception.VPackParserException: java.lang.InstantiationException: com.arangodb.springframework.core.convert.DBEntity
    at com.arangodb.velocypack.VPack.deserialize(VPack.java:398) ~[velocypack-1.1.0.jar:na]
    at com.arangodb.internal.util.ArangoDeserializerImpl.deserialize(ArangoDeserializerImpl.java:55) ~[arangodb-java-driver-4.4.0.jar:na]
    ... 128 common frames omitted
Caused by: java.lang.InstantiationException: com.arangodb.springframework.core.convert.DBEntity
    at java.lang.Class.newInstance(Class.java:427) ~[na:1.8.0_171]
    at com.arangodb.velocypack.VPack.createInstance(VPack.java:488) ~[velocypack-1.1.0.jar:na]
    at com.arangodb.velocypack.VPack.deserializeObject(VPack.java:450) ~[velocypack-1.1.0.jar:na]
    at com.arangodb.velocypack.VPack.getValue(VPack.java:569) ~[velocypack-1.1.0.jar:na]
    at com.arangodb.velocypack.VPack.deserialize(VPack.java:396) ~[velocypack-1.1.0.jar:na]
    ... 129 common frames omitted
Caused by: java.lang.NoSuchMethodException: com.arangodb.springframework.core.convert.DBEntity.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082) ~[na:1.8.0_171]
    at java.lang.Class.newInstance(Class.java:412) ~[na:1.8.0_171]
    ... 133 common frames omitted

update2
So... turns out there are 2 different issues, and neither of are actually problems with the arango sping data implementation (which seems good to me, better than what I've seen for similar mixed model document/graph DBs)
First, reworking the auto value class to not use a generated builder, means the generated class is package proteced, and that works well, thanks to @Christian for that.
The second is - which I will take to a different question - concerns using the spring (crudrepo) 'save' to save a new document, but also provide a user generated id.   This is a different issue from unmarshalling to an immutable object, so I will start a new question for that.

A: You can generate a constructor (can even be package protected) that takes all parameters (with your IDE or Lombok) of your DTO. If this isn't the only constructor inside your DTO, annotate the constructor with @PersistenceConstructor.
UPDATE:
Are your DTO classes abstract and are you passing them to Spring Data ArangoDB? If yes, this may be the cause of the exceptions you get. You should pass the generated concrete class.


text:
Q: How to decrease radio button drawable size? I have four radio button.
xml source
<RadioButton
    android:id="@+id/fragBtn1"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="@drawable/btn_bg_selector"
    android:button="@null"
    android:drawableTop="@drawable/btn_img_selector" />

btn_img_selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/selected_btn" android:gravity="center" android:state_checked="true"/>
    <item android:drawable="@drawable/nonselected_btn" android:gravity="center"/>
</selector>

btn_bg_selector
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/btnPressed" android:state_pressed="true"/>
    <item android:drawable="@color/btnNonPressed"/>
</selector>

But button image is too big.
I want to decrease a button image size only..(not decrease button size)
For example, I want to scale a button image size 30px * 30px.
Is it possible?

A: Sclae the button
<RadioButton
        android:scaleX="0.75"
        android:scaleY="0.75" />

A: Finally found the correct solution :
Step 1 :
Use your @drawable/selected_btn or @drawable/nonselected_btn as an INSET DRAWABLE .
Step 2 :
Provide padding as desirous.
Step 3 :
Yuhuuuu !! You've decreased the size of the radio button image.

A: If you want to do it correctly , you should resize your assets accordingly. Otherwise, i'm not sure how to drecrease the button image size without decreasing the button by itself

A: I can't find a solution.
But I find a another solution.
xml source
<RadioButton
    android:id="@+id/fragBtn1"
    android:layout_width="0dp"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:background="@drawable/btn_bg_selector"
    android:button="@null"
    android:drawableLeft="@drawable/btn_selector" />

MyActivity.java
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);

    BitmapDrawable bd = (BitmapDrawable) this.getResources().getDrawable(R.drawable.mybtn);

    int iconWidth = bd.getBitmap().getWidth();
    int leftPadding = (btn.getWidth() / 2) - (iconWidth / 2);

    btn.setPadding(leftPadding, 0, 0, 0);
}


text:
Q: How to send multipart formdata from remote function api? I am trying to build the multipart request on client side itself because to avoid the need to send the files back to apex for processing. Also at a time 10 files needs to be sent via rest api, so sending them to apex for firing rest is another issue.
This is my remoteFunction.
$('#input-b6').on('filelock', function (event, filestack, extraData) {
            var strFiles = "";
            Object.keys(blob).forEach(function(key) {
                var r = new FileReader();
                console.log(key, blob[key]);
                sforce.connection.remoteFunction({
                    url : 'https://localrestapi.herokuapp.com/consumeFiles',
                    onSuccess : successCallBack,
                    onFailure : errorCallBack,
                    method : 'POST',
                    requestHeaders : 'Content-Type: multipart/form-data',
                    async : true,
                    requestData : 'filename: ' +r.readAsBinaryString(blob[key]),
                    timeout : 120000
                });
            });
        });

I have written and hosted a spring boot service which accepts the multipart form data, it works when i hit the service via postman.
But when I try to hot it via Javascript in Visualforce page:
This is the error I get :
"{"timestamp":"2019-06-30T08:45:26.461+0000","status":500,"error":"Internal Server Error","message":"Current request is not a multipart request","path":"/consumeFiles"}"

I think I the requestData should change, but not sure what to pass there? ANy ideas?
Update
            Object.keys(filesBase64).forEach(function (key) {
                console.log(key, filesBase64[key]);

                var data = new FormData();
                data.append('filename', filesBase64[key]);

                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'https://localrestapi.herokuapp.com/consumeFiles', true);
                xhr.onload = function () {
                    // do something to response
                    console.log(this.responseText);
                };
                xhr.send(data);
            });

The console.log does not gets printed out. And getting this console error: Access to XMLHttpRequest at 'https://localrestapi.herokuapp.com/consumeFiles' from origin 'https://nagesingh-dev-ed--c.visualforce.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Though the files gets passed to the rest repository.

A: Visualforce remoting, remoteFunction, are used to call Apex on the Platform. If you wanna call any third party site from javascript then do a normal AJAX call.
Also, as it will be a cross-origin request from javascript so make sure the end-server supports CORS from SF domain.


text:
Q: Why does this circular import fail in Python 2 but not in Python 3? Assume the following package structure with code inline:
main.py

from a.b import c

a/__init__.py

a/b/__init__.py

a/b/c.py

from a.b import d

a/b/d.py

from a.b import c

python2 main.py gives me an import error:
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from a.b import c
  File "/home/runner/a/b/c.py", line 1, in <module>
    from a.b import d
  File "/home/runner/a/b/d.py", line 1, in <module>
    from a.b import c
ImportError: cannot import name c

However python3 main.py works fine. Does anyone know what is going on? How do I fix this issue in Python 2? I am trying to convert relative imports to absolute imports!
Python 2 Repl.It
Python 3 Repl.It

A: A quick work around is to move from the format
from a.b import d

to
import a.b.d

I tried it here and it seems to work for Python 2.


text:
Q: jsonnet import local variable from another jsonnet file I have a a.libsonnet file:
local panel = {
  new(...)::{... },
  createFromConfig(config)::
    this.new(),
};

local config = std.extVar('config');
panel.createFromConfig(config)

It seams if i only do in another file local panel = import 'a.libsonnet' will also execute panel.createFromConfig(config)
Is there a way I can only import panel?

A: I think your original question is somewhat truncated (that strange 1st line).
In any case, below may implement what I guess you're after:
file: a.libsonnet
// a.libsonnet
{
  local this = self,
  new(config):: { initWhat: config },
  createFromConfig(config)::
    this.new(config),
}

file: foo.jsonnet
// foo.jsonnet
local panel = import 'a.libsonnet';

local config = std.extVar('config');
panel.createFromConfig(config)

CLI output
$ jsonnet --ext-str config=Foo foo.jsonnet
{
   "initWhat": "Foo"
}


text:
Q: PHP bindParam does not seem to work with a PARAM_INT out parameter The following is my MySQL stored procedure:
DROP PROCEDURE IF EXISTS sp_authenticate;
CREATE PROCEDURE sp_authenticate(IN user_name VARCHAR(50),
  IN password1 VARCHAR(50), OUT nmatch INT)
BEGIN

  SELECT COUNT(*) INTO nmatch
    FROM user1 u
    WHERE u.name = user_name AND
      u.password1 = password1;

END//

This is how I am calling it from PHP:
function authenticate($pdo, $user_name, $password){
  $stmt = $pdo->prepare('CALL sp_authenticate(:user_name, :password, :nmatch)');
  $stmt->bindValue(':user_name', $user_name, PDO::PARAM_STR);
  $stmt->bindValue(':password', $password, PDO::PARAM_STR);
  $nmatch = 888888;
  $stmt->bindParam(':nmatch', $nmatch, PDO::PARAM_INT, 4);
  $result = $stmt->execute();

  return $nmatch;
}

$nmatch always retains it's old value and does not receive the value from the stored procedure. What could I be doing wrong here?
MySQL Server Version: 5.5.22
PHP Version: 5.3.10

A: As mentioned in this blog:

Unfortunately there's a bug with the MySQL C API that PDO uses which means that trying to fetch an output parameter when calling a procedure results in the error:

"Syntax error or access violation: 1414 OUT or INOUT argument $parameter_number for routine $procedure_name is not a variable or NEW pseudo-variable".

You can see the bug report on bugs.mysql.com. It's been fixed for version 5.5.3+ & 6.0.8+.
To workaround the issue, you would need to keep in & out parameters separate and call the procedure.  Example #11 on the PHP PDO documentation would then read:
$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(:in_string, @out_string)");
$stmt->bindParam(':in_string', 'hello');

// call the stored procedure
$stmt->execute();

// fetch the output
$outputArray = $this->dbh->query("select @out_string")->fetch(PDO::FETCH_ASSOC);

print "procedure returned " . $outputArray['@out_string'] . "\n";


text: Q: How we can get image from camera with fragment in kotlin? I search documentation and tutorial for this, but all the tutorial using activity than fragment. And when i try it, it doesn't work in fragment. Do you have any documentation, artikel, or tutorial about this? I'm trully new in kotlin. Thank you.


text:
Q: how to make usb printer work on ubuntu 16.04? I have tried an USB thermal printer to work on Ubuntu 16.04 with no success. All updates are installed.
I have tried with CUPS, installed the manufacturer .ppd file, but the print job just stays on the queue without print output.
I also have tried with usblp, the printer is on /dev/usb/lp0 but echo "test" >> /dev/usb/lp0 outputs nothing as it's waiting the writing feedback and nothing.
If I change the printer jumper to work as serial over usb, it works. I can print on /dev/ttyACM0 (but I don't want to change every printer on the company).
Any ideas what may be wrong? It does not seem anything with cups itself, it seems to be related to usb communication.

*

*lsusb lists the device as Bus 001 Device 008: ID 1c8a:3012

*lpinfo -v also list the device as
direct usb://SWEDA/SI-300L?serial=0000000000002

*dmesg:
[ 1389.650521] usb 1-2: new full-speed USB device number 9 using xhci_hcd
[ 1391.505603] usb 1-2: New USB device found, idVendor=1c8a,  idProduct=3012
[ 1391.505608] usb 1-2: New USB device strings: Mfr=1, Product=2, SerialNumber=6
[ 1391.505611] usb 1-2: Product: Printer Class
[ 1391.505613] usb 1-2: Manufacturer: SAM4S CORP.
[ 1391.505616] usb 1-2: SerialNumber: 0000000000002
UPDATE: Tested on a ubuntu 16.04 virtual machine on a windows host and it works. One difference that I noticed is that the virtual machine uses ohci-pci and the physical machine uses xhci_hcd.
Thanks.


text:
Q: Azure Pipelines (DevOps) Selenium Automation Browsers Running Headless in Memory Causing Errors I am running an Azure Pipelines (DevOps) pipeline that builds my automation test solution into a dll, and loads that dll to get all of the integration automation tests.
I am using the default cloud "Host" agents to run the automation. However, the drivers throw tons of errors. I recognize the errors as the same ones that I encountered when I set up automation via Jenkins -- when I was running Jenkins as a service.
To fix the issue in Jenkins, I stopped running it as a Windows service, and started launching it as a java -jar Jenkins.war command in Powershell. That allowed the selenium drivers to launch browsers as normal on the VM's desktop, rather than running the browser instances and drivers completely in memory.
So, when it ran the browser windows and drivers completely in memory, I received the same driver errors as I am now encounting on the Host agents in Azure Pipelines. The problem is that I cannot find how to make the Agents run the tests on the VM desktop. I don't have any idea where to start on solving this problem, and can't seem to find any info online about this.
Edit: To be as clear as possible. The ONLY error occurring is "$ is not defined". This is because the DOM does not load properly because the browser executables and driver executables are running completely in memory, headless. I need to be able to run the executables in a rendered part of the host machines. So, what I mean is, if I were to remote desktop into this machine, I would actively see browser windows rendering, and automation running. Right now though, if I were to remote into this VM, I would see chrome.exe, and chromedriver.exe in TaskManager, but nothing would be visible on the desktop.

A: I found the answer.
https://learn.microsoft.com/en-us/azure/devops/pipelines/test/ui-testing-considerations?view=vsts&tabs=mstest#visible-ui-mode
You must manually configure the hosts to run Selenium non-headless. This will prevent everything from running as a service, which is purely in memory, with no UI components. This is the problem I mentioned that Jenkins encountered when running Jenkins as a service.
The fix for Jenkins running automation with a GUI is the same for the Hosted agents in Azure pipelines, ultimately. It's just a manual configuration. This is done via a plugin and build step in pipelines.


text:
Q: get deserialize data from serialize data jquery decodeURIComponent var ser=$("input[name=\"convs[]\"]:checked").serialize();
var v=decodeURIComponent(ser);
console.log(v);

i get o/p is convs[]=91&convs[]=89
is it posssible to get 91 and 89 any idea

A: use serializeArray() for this
http://api.jquery.com/serializearray/
and then iterate over the array:
var results = [];

$("input[name=\"convs[]\"]:checked").serializeArray().forEach( function( val ) {
   results.push( val.value );
});


text:
Q: ambiguous error : C++11 use variadic template multiple inheritance Objectif of this code is to create a wrap around diffent template design (an implementation with always the same handler work), but with this try I have the following error "error: request for member 'pushEvent' is ambiguous" I don't understand (detail of the error on the bottom of the message)
template<typename T>
struct EventHandler {
    EventHandler() {}

    inline void pushEvent(T & msg) {
    printf("pushEvent %s", typeid(T).name());
        q_.push(msg);
}

protected:
    std::queue<T> q_;
};

The wrapper of deferend template (some method will be add to handle the different type of events
template<typename... EventHandler>
    struct _EventsHandler : EventHandler... {

};

// usage sample : We create the type that will instantiate the event manager
 using EventHandlerType = EventsHandler<EventHandler<int>,EventHandler<float>,EventHandler<char>>;

int main(void) {
    EventHandlerType test;

    int msp = 1;
    test.pushEvent(msp);
}

I don't understand the ambiguous error as msp type is int and should give information to solve the ambiguity ?
error: request for member 'pushEvent' is ambiguous
  test.pushEvent(msp);
       ^
note: candidates are: void _EventHandler<T>::pushEvent(T&) [with T = char]
     inline void pushEvent(T & msg) {
                 ^
note: void _EventHandler<T>::pushEvent(T&) [with T = float]
note: void _EventHandler<T>::pushEvent(T&) [with T = int]
note: void _EventHandler<T>::pushEvent(T&) [with T = char]

I know that such solution can be handled differently, but I want to understand the WHY of this error, so please don't mark this question as "already answered" if the answer is "there is an other way to solve your problem"

A: Before overload resolution, name lookup is performed, which has its own set of rules. It has to find an unambiguous name and there isn't one in your case.
You may use the following instead (https://ideone.com/ChvQ4q)
template<typename... Ts>
struct _EventsHandler;

template<typename T>
struct _EventsHandler<T> : T
{
    using T::pushEvent;
};

template<typename T, typename... Ts>
struct _EventsHandler<T, Ts...> : T, _EventsHandler<Ts...>
{
    using T::pushEvent;
    using _EventsHandler<Ts...>::pushEvent;
};

A: This works :
#include <typeinfo>
#include <queue>
#include <cstdio>

template<typename T>
struct EventHandler {
    EventHandler() {}

    void pushEvent(T & msg) {
    printf("pushEvent %s", typeid(T).name());
        q_.push(msg);
}

protected:
    std::queue<T> q_;
};

template<typename... EventHandler>
    struct _EventsHandler : EventHandler... {
        template <typename T>
        void pushEvent(T & msg) {
            // Choose appropriate superclass
            ::EventHandler<T>::pushEvent(msg);
        }
};

using EventHandlerType = _EventsHandler<EventHandler<int>,EventHandler<float>,EventHandler<char>>;

int main(int, char**) {
    EventHandlerType test;

    int msp = 1;
    test.pushEvent(msp);
}

I lack sufficient template voodoo to explain this one, but no doubt someone will be able to (and probably nail it with the exact paragraph from the standard)


text:
Q: Virtualisation server for a small business: questions on design, hardware components and vendor I need to build or buy a server in order to migrate a small business to its own infrastructure. The business has under 20 employees across 4 sites. Currently, the head office site (where this new server will be located) shares the same IT infrastructure with a sister company.
What the business needs the server to do:

*

*Host their low-traffic websites

*Host their SMTP/IMAP email servers, including and malware/spam filtering

*Host their Windows file shares

*Host backups/archives for their 3 satellite sites

*Not cost too much, say under A$5000

The plan:

*

*Buy a single server with good hardware virtualisation capabilities and a reasonable amount of redundancy

*Setup (at least) two virtual machines:

*

*one for any public-facing services (ie. web, email)

*one to host internal file shares and remote backups

*Use FOSS software for virtualisation and services, eg. CentOS, KVM/Xen, Apache, PostgreSQL, PHP, Postfix, etc.

*Do the storage/software setup myself (ie. I don't need the vendor's help with setting up the RAID or OS)

Design considerations:

*

*Hardware must be fully compatible with RHEL/CentOS 5.5 x86_64 (eventually the OS will be upgraded to RHEL/CentOS 6). This means no 3rd-party driver disks.

*Provide all services using virtual machines, for ease of administration (eg. snapshots, rollback)

*Connect the VM to dedicated LVM volumes on the VM host where applicable (eg. the file server), in order to avoid trapping company data in a VM (think of this as a poor man's SAN/NAS)

*Don't upgrade this server if more hardware resources are required in the future. Instead, look at building a SAN and perhaps adding a dedicated SAN NIC to this server through which it connects to the SAN

Hardware I'm considering:

*

*single-socket motherboard with VT-d support and built-in dual-port Gigabit Ethernet

*redudant power supply

*4-core, Nehalem-based Intel Xeon with Intel VT and IOMMU support

*12GB (3x4GB) 1333MHz single-rank RDIMMs

*4x 3.5" drive bays holding 4x SATAII enterprise (ie. decent MTBF/IOPS) drives for full hardware RAID10 (aiming for an approx. 300GB logical drive). SAS would be nice, but it seems too expensive

*slimline DVD-ROM drive

*remote console with dedicated Ethernet port, eg. like DRAC/iLO.

*preferably cross-platform system management software (eg. monitoring, firmware updates, remote console). One vendor wants to sell me a Supermicro-based solution, but this seems to be Windows-only remote console, ie. it runs on Linux too but with only limited features.

*at least two spare PCIe slots for future expansion: one for the Ethernet to a SAN, and the other to a tape drive unit (this is assuming that the sytem or its RAID controller doesn't already have an external jack to attach a tape drive unit to). Note that a tape unit isn't required at this stage as backups will go to a remote over a VPN.

Questions:

*

*Can anyone forsee any problems with this setup or have any alternate recommendations?

*Does anyone already know of a specific server model which accomodates these requirements (either out of the box by some miracle, or with some customisation by the vendor)?

*Does anyone have any recommendations for a hardware vendor? Please keep in mind that this is a Melbourne-based business. At the moment I am considering Dell and Digicor. I would have included HP, but the boss isn't a huge fan of HP for some reason. The vendor needs to:

*

*be reputable

*be cost-effective

*have quick turnaround time for replacing faulty parts

*be able to build custom servers (ie. not just try and sell me some "cookie-cutter" system which doesn't quite meet my needs).

*Should I just build this myself? This doesn't seem like a popular option among sysadmins, because of the lack of support in case of a breakdown (eg. waiting weeks for the right part to be delivered).

*Which RAID controller model do I want?

*

*how much cache do I need, if any?

*do I need a battery-backed write controller (BBWC)? I don't think so because it's RAID10, not RAID5/6, but someone may know better

*is there some open RAID metadata format so that you can switch RAID controller vendors and still have your logical drive work?

*Is CentOS with KVM/Xen a good idea for the VM host? I can't see why it would be bad, but perhaps there are some horror stories out there.

*Do I want a dedicated NIC for each VM, or is a software bridge fine?

*Is there any particular motherboard chipset to get/avoid?

*Does it cost much more to get the same hardware as above, but a dual-socket board and 8 drive bays? I figure it's better not to get these to keep costs down. If I really need to upgrade, I still can (replace CPU, add RAM, attach to a SAN, etc.)

*Do I care how many rack units the system takes? I will have enough rack space for anything (eg. 1U to 5U), but is there a benefit to a certain size, eg. cost?

A: Too little RAM, too little IO.
CHeap end user based:

*

*AMD board with a 6 crore Phenom II, 16gb Memory. Adaptec 3405 RAID controller and you can fix up 8 discs. I have one of them here, soon two.

*Discs used in this case for me are 4 x wd scorpio black as raid 10, 4x wd scorpio blue as raid 5. the blacks hold all vms and the os, the blue are a large file share... performane is ok, with bottlenecks occasionally.
Or you go long term.

*

*Amd Opteron based board, two sockets. I have one of those (soon two). 32 to 64 gb ram. Supermicro has a nice cage that has 24 disc bays on a SAS backplance in 2 rack units.... an Adaptec 58005 runs that. Discs are all raptors - so far I hve 12 Velociraptors in there, 300gb each, as RAID 10. 6 for os and virtualization, 6 for a larger database. I started with one processor, 32gb ram. More expensivbe, but high quality and something you can expand on.

12gb ram sound like a bottleneck coming. And the disc layout is going to be problematic. Upragdes to a SAN are stupid - sorry - from a cost point. A SAN makes sense for MANY servers, but to get SAN hardware for ONE server... look at the prices. It is not funny. For 1-2 servers, DAS (Directly attached discs) are mostly a lot better in price.
XEN is a good virtualizer if windows is involved - as XEN is supported natively by WIndows Server 2008.... there are no third party components to install in the virtual machines. Keeps updating a little easier.
For a vendor... SUPERMICRO;) They have all kinds of very nice stuff, especially for high density systems.

A: Have you taken into account the reliability of your ISP? I would highly recommend hosting web servers and mail servers with a hosting company who can provide the uptime those services need.
You might be able to afford 30 minutes without a file server, but can you afford to have your website down? (Googlebot doesn't sleep!) Or for your email servers to be unable to receive messages? No matter how much hardware redundancy you have, you can't stop the phone/cable company from being stupid.
You should also think about what your ISP will allow. Some block critical ports such as 80 coming in and 25 going out. You can't expect your customers to visit www.yoursite.com:85 because you're forced by your ISP to run your web server on a non-standard port.
Hosting is so dirt cheap you can get a basic "online business card" type website with email receiving for less than $5/mo.
As for file serving, that should be done on-site since disks are cheaper to buy than to rent and there is far less latency over a gigabit lan than 6mbps DSL or Cable.
For mail, our company uses a high-availability (ie. hosted professionally, not on-site) mail server that receives our incoming mail and serves it via POP3s. Then, our on-site server uses Fetchmail to retrieve the messages from the off-site server and places them in Cyrus IMAP for permanent on-site storage and deletes the off-site copy. Our employees access mail via the local Cyrus server.
We do this because long-term IMAP mail storage takes lots of disk space and its cheaper to buy our own disks, but we want the high-availability of being able to receive mail even if the ISP is down.
Are you planning to use Samba to host your files for Windows users? Are you planning to use it as a Primary Domain Controller for central user account management? Is your network mixed with both Windows/Linux clients?
As far as virtual machines, we separate every service into its own machine. This keeps everything isolated in case of any mistakes. That way if someone gets a little overzealous with the rm command and the * for example, you would loose only your mail or only your web server, but not both like you would if they were on the same VM.


text:
Q: How do I disable automatic printer discovery in Ubuntu 20.10+? How do I disable automatic printer discovery in Ubuntu 20.10?
I already tried this suggestion that includes these commands:
sudo systemctl stop cups-browsed
sudo systemctl disable cups-browsed

But executing both of them does not disable the automatic printer discovery in Ubuntu 20.10.
The printer I am using is the Brother MFC-J5330DW and it is connected to the same LAN as my Ubuntu system. When I go into the Settings section and there under Printers, the printer is automatically added with the name "Brother_MFC_J5330DW". If I delete it, then leave the printers section and return again, the printer is back with the same name. And for some reason I cannot use it for printing neither. When I use this printer entry the printer does not react at all. My guess is that Ubuntu has some issues with this automatic printer discovery protocol (i.e. Bonjour or what its name is). For this I manually created a printer entry that works perfectly. The only thing now is that I find myself having two entries for the same printer - one that works and another useless one that does not.
How can I prevent Ubuntu or rather CUPS to automatically add printers without my concent?

A: The only application that discovers printers on the network and sets up permanent print queues for them is cups-browsed. Purging it from the system is the surefire way of preventing this. Why bother stopping and masking it? It's a waste of time when all you want to do is prevent discovery and set up of a printer. But stopping and masking has gained traction without its proponents explaining why it is better than purging cups-browsed.
That's one issue. Now for a second, completely separate one.
The GTK print dialog (used by Gnome) also discovers and displays printers. It does not install print queues. The displayed printers (which are not queues) often do not print. This is a bug in GTK. A user can do nothing about it.
Are you experiencing the first or second issue? That will decide your course of action.

A: Having the same problem ("second issue" in reference to @brian_p's answer), and after reading this and that, I ran
sudo systemctl stop avahi-daemon.service
sudo systemctl disable avahi-daemon.service
sudo systemctl stop avahi-daemon.socket
sudo systemctl disable avahi-daemon.socket

and the network printer list in qpdfview's print dialog is gone. Phew!
Disclaimer: in the second link it is said that "disabl[ing] all network computer discovery [...] probably isn't a good idea", so YMMV.


text:
Q: undefined method `valid_options' for nil:NilClass with simple_form and Mongoid I have two models, Category and Post.
Category.rb
class Category
include Mongoid::Document

field :title, :type => String
has_many :posts, :autosave => true, dependent: :destroy

end

Post.rb
class Post
include Mongoid::Document

field :title, :type => String
belongs_to :category
end

I'm using simple_form gem
If I write in my post form the next:
<%= simple_form_for(@post) do |f| %>
 <%= f.collection_select :category, Category.all, :id, :title, :prompt => "Choose a Category"%>
 <%= f.input :title %>
 <%= f.button :submit %>
<% end %>

The form does works fine :).
but if I use the next form with simple_form format:
<%= simple_form_for(@post) do |f| %>
  <%= f.association :category, :prompt => "Choose a Category" %>
  <%= f.input :title %>
  <%= f.button :submit %>
 <% end %>

I get the next error:
Completed 500 Internal Server Error in 23ms
ActionView::Template::Error (undefined method `valid_options' for nil:NilClass):

How can I fix it?
Thank you!

A: The problem was fixed. Thank you to Carlos Antonio da Silva :D.
you can find the fix in http://groups.google.com/group/plataformatec-simpleform/browse_thread/thread/f384f0445af8468e or:
<%= f.input :category, :collection => Category.all, :prompt => "Choose a Category" %>

Thank you!


text:
Q: My Tomcat v9.0 server can not run a servlet listener clas despite correct xml file Tomcat server could not find the servlet class. Even I tried only with a servlet class. Still, the server could not find the servlet class, giving the same error message. I am very new to web application.

This is my servlet file.
This is my listener file.
This is my expected output. If I put manually the link: http://localhost:8081/listener_Demo/TestServlet, I get it on console (look at console).

A: Update welcome-file-list and add your custom jsp to open directly.
for example :
<welcome-file-list>
   <welcome-file>display.jsp</welcome-file>
</welcome-file-list>

Now, you can use http://localhost:8081/listener_Demo/ to open directly your page.
Note you have to keep the .jsp in the root WEB-INF folder for accessing.


text:
Q: Infinite scroll alternate Is  there any javascript code or any other way to convert infinite scroll into pagination on facebook or any other website.
Or is there any way to load more results while scrolling using javascript ?

A: Infinite scroll is easy to develop. But infinite scroll only appends contents. Therefore, if contents are long, scrolling is so slow and the browser is blocked.
If you consider long contents and high performance, I recommended eg.infiniteGrid.
eg.infiniteGrid keeps a number of DOMs when scrolling.
If a user scrolls down, eg.infiniteGrid remove top DOMs. If a user scrolls up, eg.infiniteGrid remove bottom DOMs.
Therefore, eg.infiniteGrid has high performance.
Checks out this video: eg.infiniteGrid benchmark: append item performance

A: There are a few Javascript/jQuery plugins you can use to implement infinite scrolling on your website. One of them you could check out is jScroll (http://jscroll.com/).
If you're loading paginated content from Facebook or another API, you could use the callback method in jScroll to make a request to fetch each page of data.


text:
Q: Python path help how can i run my program using test files on my desktop without typing in the specific pathname. I just want to be able to type the file name and continue on with my program. Since i want to be able to send it to a friend and not needing for him to change the path rather just read the exact same file that he has on his desktop.

A: If you are on Unix/Mac you can add a shebang at the top of your script and set it as executable. Usually you'd do:
#!/usr/bin/env python

And then to make it executable, from a terminal use chmod:
chmod +x script.py

Now you can run the script (if you are in the same directory) like:
./script.py

If you are on Windows you'll want to add the Python executable to your %PATH% enviromental variable, then you can run your script with python script.py. They talk about this in more depth in the Python documentation: http://docs.python.org/using/windows.html

A: f = open(os.path.join(os.environ['USERPROFILE'], 'DESKTOP', my_filename))

A: If you place your Python script in the same directory as the files your script is going to open, then you don't need to specify any paths. Be sure to allow the Python installer to "Register Extensions", so Python is called when you double-click on a Python script.

A: You can tell your friend to make *.py files to be executed by the interpreter.  Change it from Explorer:Tools:Folder Options:File Types.


text:
Q: jQuery $.each multiple div names Hello following problem,
i need the id attribute string for each div in a loop how i can make this ?

Here is my sample jquery code which does nothing -.-
$.each("div.upload-progress-bar", function (index,value) {

    alert(index);

    $('#' + value + 'ProgressBar').animate({
        'width': 10 + '%'
    }, 250).animate({
        'width': 25 + '%'
    }, 250).animate({
        'width': 65 + '%'
    }, 250).animate({
        'width': 95 + '%'
    }, 250).animate({
        'width': 100 + '%'
    }, 250);
});

A: In the callback function, this refers to each of the elements you are looping trough, so you don't need the ID at all to animate the element. Just call $(this).animate(
But in order to iterate trough the div elements, you have to use $("div.upload-progress-bar").each(function(

A: this.id

will get you the id attribute's text of the current element.
Example of proper .each()...
$("div.upload-progress-bar").each(function (index,value) {
    alert(this.id);
});

See Darhazer's Answer for an answer that will probably help your use case.

A: You want $(...).each not $.each
It also doesn't look to me like you actually need the id at all - use this
$("div.upload-progress-bar").each(function (index,value) {
    //use `this` and `this.id` if you _really_ need the id
    $(this).animate(
        //...
      )
 });

A: valuetry this
$("div.upload-progress-bar").each(function (index,elem) {

    var value = $(elem).attr("id"); // try elem.id, i guess that would work too

    $('#' + value).animate({ // you must remove ProgressBar it is included in the value variable
        'width': 10 + '%'
    }, 250).animate({
        'width': 25 + '%'
    }, 250).animate({
        'width': 65 + '%'
    }, 250).animate({
        'width': 95 + '%'
    }, 250).animate({
        'width': 100 + '%'
    }, 250);
});

A: Try this:
$("div.upload-progress-bar").each(function (index,value) {

    alert($(this).attr("id"));

    $('#' + value + 'ProgressBar').animate({
        'width': 10 + '%'
    }, 250).animate({
        'width': 25 + '%'
    }, 250).animate({
        'width': 65 + '%'
    }, 250).animate({
        'width': 95 + '%'
    }, 250).animate({
        'width': 100 + '%'
    }, 250);
});


text:
Q: Change Row Color Based On Condition In C# Hi I'm very new to C#. But I have this weblist that print out some result, that I'm trying to change, What I'm trying to do is to make an if statement. If row[4] is less then [2] then the row should be red. I have tried to copy some of the code.
//##############Print result##############
foreach ( string[] row in dataResult)
{
//Birn.Util.cellDecimalPrinter(row[0],"#,0.0")
//

%>

<%=row[0]%>
<%=row[1]%>
<%=row[2]%>
<%=row[3]%>
<%=row[4]%>

<%
}

A: You can change the style of the row using CSS. I have assumed that whatever you are comparing in rows 2 and 4 is a string representation of a Decimal: adjust the Convert.ToDecimal to the appropriate type if needed:
foreach ( string[] row in dataResult)
{
    string redStyle= "";
    If (Convert.ToDecimal(row[4]) < Convert.ToDecimal(row[2])) {
        // ideally you would have a style defined in a separate CSS file for this
        redStyle = " style=\"background-color: Red; color: White\"";
    }
}
%>
<tr<%=redStyle%>>
<%=row[0]%>
<%=row[1]%>
<%=row[2]%>
<%=row[3]%>
<%=row[4]%>

<%
}


text:
Q: How to show a picture? I'm having a problem calling a picture to view.  In my app after they click the button i want to take them to a new page where it will display a picture and under it some text.  For this example say i want a pic if dog to be at the top of the page then under it say i want something like the breed and the cost of breed. Can anyone help me?

A: Use this XML for your page what will display the image:
<ImageView
    android:id="@+id/image"
    android:src="src"
/>
<TextView
    android:text="image text"
    android:layout_below ="@id/image"
 />

Of course, add more options to the views
Some good references:
http://developer.android.com/reference/android/widget/ImageView.html
http://developer.android.com/reference/android/widget/TextView.html
http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

A: Use ImageView.
Also for other questions like this, I highly recommend reading the User Interface section of the online Android Developer's Guide.

A: In a layout XML, put a LinearLayout, oriented vertically, containing first an ImageView widget then a TextView widget. You can set the text using TextView#setText(String) and the image using ImageView#setDrawable(...).
This layout will be used by an activity that reads the Extra information (for example the text to show and the image URL or the image path on the SDCard) when it starts.
You should read more about Views on the Android developer's guide as advised by Shawn Lauzon.

A: write the above code in your .xml
<ImageView android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center">
</ImageView>

and add this line in your .java class
img = (ImageView) findViewById(R.id.img);


text:
Q: Python. How to make list from another list by mark? I have list:
['a','ab','abc','1','2','3','4','123','1234','12345']

Need to get:
['a','ab','abc','1','2','3','4',['123','1234','12345']]

If sorted by [0:3] symbols
[['a','ab','abc'],'2','3','4',['1','123','1234','12345']]

if sorted by [0:1] symbols
list with another lists (strings with the same symbols only first symbol or any [:])
another example:
['some','son','abc','123','12345']

If sorted by "123" - need:
['some','son','abc',['123','12345']]

If sorted by [0:1] - need:
[['some','son'],'abc',['123','12345']]

and so on...
Sorry for my english and simple question.
Need help. Don't kill me at first question. Thank you.

A: You want to group items on their prefix, so use itertools.groupby():
from itertools import groupby
from operator import itemgetter

def group_by_start(inputlist, n):
    return [list(g) for k, g in groupby(inputlist, key=itemgetter(slice(n)))]

This returns a list of lists, consistently.
Note that this only groups consecutive values, it won't sort the input list for you. Adding sorting is as easy as re-using the key:
def sorted_group_by_start(inputlist, n):
    key = itemgetter(slice(n))
    return [list(g) for k, g in groupby(sorted(inputlist, key=key), key=key)]

Demo:
>>> group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 3)
[['a'], ['ab'], ['abc'], ['1'], ['2'], ['3'], ['4'], ['123', '1234', '12345']]
>>> group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 1)
[['a', 'ab', 'abc'], ['1'], ['2'], ['3'], ['4'], ['123', '1234', '12345']]
>>> sorted_group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 3)
[['1'], ['123', '1234', '12345'], ['2'], ['3'], ['4'], ['a'], ['ab'], ['abc']]
>>> sorted_group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 1)
[['1', '123', '1234', '12345'], ['2'], ['3'], ['4'], ['a', 'ab', 'abc']]

If you must have lists only for groups longer than one elements use:
def group_by_start(inputlist, n):
    return [res[0] if len(res) == 1 else res for k, g in groupby(inputlist, key=itemgetter(slice(n))) for res in (list(g),)]

or
def sorted_group_by_start(inputlist, n):
    key = itemgetter(slice(n))
    return [res[0] if len(res) == 1 else res for k, g in groupby(sorted(inputlist, key=key), key=key) for res in (list(g),)]

This gives:
>>> group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 3)
['a', 'ab', 'abc', '1', '2', '3', '4', ['123', '1234', '12345']]
>>> group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 1)
[['a', 'ab', 'abc'], '1', '2', '3', '4', ['123', '1234', '12345']]
>>> sorted_group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 3)
['1', ['123', '1234', '12345'], '2', '3', '4', 'a', 'ab', 'abc']
>>> sorted_group_by_start(['a','ab','abc','1','2','3','4','123','1234','12345'], 1)
[['1', '123', '1234', '12345'], '2', '3', '4', ['a', 'ab', 'abc']]
>>> sorted_group_by_start(['asdf', 'fdsa', 'asd','123','1234','1','12345'], 3)
['1', ['123', '1234', '12345'], ['asdf', 'asd'], 'fdsa']

You can turn either version into a generator to build the output lazily:
def group_by_start(inputlist, n):
    return (list(g) for k, g in groupby(inputlist, key=itemgetter(slice(n))))

or
def group_by_start(inputlist, n):
    for k, g in groupby(inputlist, key=itemgetter(slice(n))):
        res = list(g)
        yield res[0] if len(res) == 1 else res

then just loop over the output of the generator with for or cast to a list with list().


text:
Q: Lyapunov exponents in bounded systems This is the definition used to numerically calculate the maximal Lyapunov exponent:
$$
|\delta Z(t)| \approx e^{\lambda t} |\delta Z_0|
$$
$$
\lambda \approx \frac{1}{t} \ln\left(\frac{|\delta Z(t)|}{|\delta Z_0|}\right)
$$
Consider a system to be bounded in a region of space, like two balls moving inside a room, where we want to see if the dynamics are chaotic or not. We start recording the trajectory of a ball and after a good amount of time, we go back and start from a tiny dislocated initial position. We see that the trajectories diverge and we may conclude that the system is chaotic. Like the following:

But here is what I do not understand. If the room is bounded, then these two trajectories cannot get arbitrarily far from each other and their distance would not be larger than the size of the room. So in the formula for the Lyapunov exponent, $t$ would get larger and larger over time so $\lambda$ would become smaller and finally zero, no matter if it was positive at first.
Would this mean the Lyapunov exponent decays with time in bounded systems? A double pendulum is a bounded system, two trajectories (angles) can not be more than $\pi$ apart at any moment, so does its Lyapunov exponent decay to zero over time?

A: TLDR: if you want to look at longer and longer time scales, you need to have smaller and smaller initial displacements so that the displacement doesn't blow up to the full system size.
You are right that in a bounded system, if you look at a fixed initial displacement $|\delta Z_0|$ and then let $t \to \infty$, the quantity you care about will have to tend to zero.  For a fixed $|\delta Z_0|$, the displacement should evolve like $|\delta Z(t)| \approx e^{\lambda t} |\delta Z_0|$ for some range of time, but eventually the displacement becomes comparable with the size of the system, and then it can't keep expanding any more.  Because of that, to calculate the Lyapunov exponent it only makes sense to estimate the displacement for a time range that is short enough so that the displacement doesn't blow up to become comparable with the size of the system.
If you want to be more precise you can define the Lyapunov exponent like this, to ensure that you only look at the displacement at time scales which are still good for the initial displacement you started with.


text:
Q: POST csv/Text file using cURL How can I send POST request with a csv or a text file to the server running on a localhost using cURL.
I have tried curl -X POST -d @file.csv http://localhost:5000/upload but I get

{
      "message": "The browser (or proxy) sent a request that this server could not understand."
  }

My server is flask_restful API. Thanks a lot in advance.

A: Curl's default Content-Type is application/x-www-form-urlencoded so your problem is probably that the data you are POSTing is not actually form data. It might work if you set the content type header properly:

-H "Content-Type: text/csv"

Though it does depend on the server.

A: There are many alternate ways to accomplish this. One way is
I have used the following:
curl -F 'data=@<file_location>' <URL>

Eg. curl -F data=@data.csv localhost:5000/h
Your command can also be changed slightly like this
curl -X POST -H 'Content-Type: text/csv' -d @file.csv http://localhost:5000/upload

The above is one of the many ways.It can be sent either as a part of form or data, or multipart, etc. You can refer Medium Post