text:
Q: Distorted / crackling audio: Ubuntu 19.10 on MacBook 7.1, 2010 I have installed Ubuntu 19.10 (Eoan Ermine) on a MacBook 7,1, Mid-2010, A1342. Unfortunately (unlike Ubuntu 19.04), the audio is not working properly, it's very choppy and distorted.
inxi -A :
Audio:
  Device-1: NVIDIA MCP89 High Definition Audio driver: snd_hda_intel
  Sound Server: ALSA v: k5.3.0-19-generic

lspci -nnk :
00:08.0 Audio device [0403]: NVIDIA Corporation MCP89 High Definition Audio [10de:0d94] (rev a2)
    Subsystem: NVIDIA Corporation MCP89 High Definition Audio [10de:cb89]
    Kernel driver in use: snd_hda_intel
    Kernel modules: snd_hda_intel

aplay -l :
**** List of PLAYBACK Hardware Devices ****
card 0: NVidia [HDA NVidia], device 0: CS4206 Analog [CS4206 Analog]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: NVidia [HDA NVidia], device 1: CS4206 Digital [CS4206 Digital]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: NVidia [HDA NVidia], device 3: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: NVidia [HDA NVidia], device 7: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0
card 0: NVidia [HDA NVidia], device 8: HDMI 0 [HDMI 0]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

inxi -F :
System:
  Host: MacBook7.1 Kernel: 5.3.0-19-generic x86_64 bits: 64
  Desktop: Gnome 3.34.1 Distro: Ubuntu 19.10 (Eoan Ermine)
Machine:
  Type: Laptop System: Apple product: MacBook7,1 v: 1.0
  Mobo: Apple model: Mac-F22C89C8 date: 06/01/10
CPU:
  Topology: Dual Core model: Intel Core2 Duo P8600 bits: 64 type: MCP
  L2 cache: 3072 KiB
  Speed: 796 MHz min/max: 798/2394 MHz Core speeds (MHz): 1: 796 2: 796
Graphics:
  Device-1: NVIDIA MCP89 [GeForce 320M] driver: nouveau v: kernel
  Display: x11 server: X.Org 1.20.5 driver: nouveau
  resolution: 1280x800~60Hz
  OpenGL: renderer: NVAF v: 3.3 Mesa 19.2.1

pacmd info :
Memory blocks currently allocated: 2, size: 113,8 KiB.
Memory blocks allocated during the whole lifetime: 30879, size: 50,1 MiB.
Memory blocks imported from other processes: 0, size: 0 B.
Memory blocks exported to other processes: 0, size: 0 B.
Total sample cache size: 49,9 KiB.
Default sample spec: s16le 2ch 44100Hz
Default channel map: front-left,front-right
Default sink name: alsa_output.pci-0000_00_08.0.analog-stereo
Default source name: alsa_output.pci-0000_00_08.0.analog-stereo.monitor
Memory blocks of type POOL: 2 allocated/14605 accumulated.
Memory blocks of type POOL_EXTERNAL: 0 allocated/310 accumulated.
Memory blocks of type APPENDED: 0 allocated/0 accumulated.
Memory blocks of type USER: 0 allocated/0 accumulated.
Memory blocks of type FIXED: 0 allocated/13130 accumulated.
Memory blocks of type IMPORTED: 0 allocated/3144 accumulated.
25 module(s) loaded.
    index: 0
    name: <module-device-restore>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Automatically restore the volume/mute state of devices"
        module.version = "13.0"
    index: 1
    name: <module-stream-restore>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Automatically restore the volume/mute/device state of streams"
        module.version = "13.0"
    index: 2
    name: <module-card-restore>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Automatically restore profile of cards"
        module.version = "13.0"
    index: 3
    name: <module-augment-properties>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Augment the property sets of streams with additional static information"
        module.version = "13.0"
    index: 4
    name: <module-switch-on-port-available>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "David Henningsson"
        module.description = "Switches ports and profiles when devices are plugged/unplugged"
        module.version = "13.0"
    index: 5
    name: <module-switch-on-connect>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Michael Terry"
        module.description = "When a sink/source is added, switch to it or conditionally switch to it"
        module.version = "13.0"
    index: 6
    name: <module-udev-detect>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Detect available audio hardware and load matching drivers"
        module.version = "13.0"
    index: 7
    name: <module-alsa-card>
    argument: <device_id="0" name="pci-0000_00_08.0" card_name="alsa_card.pci-0000_00_08.0" namereg_fail=false tsched=yes fixed_latency_range=no ignore_dB=no deferred_volume=yes use_ucm=yes avoid_resampling=no card_properties="module-udev-detect.discovered=1">
    used: 0
    load once: no
    properties:
        module.author = "Lennart Poettering"
        module.description = "ALSA Card"
        module.version = "13.0"
    index: 8
    name: <module-bluetooth-policy>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Frédéric Dalleau, Pali Rohár"
        module.description = "Policy module to make using bluetooth devices out-of-the-box easier"
        module.version = "13.0"
    index: 9
    name: <module-bluetooth-discover>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "João Paulo Rechi Vita"
        module.description = "Detect available Bluetooth daemon and load the corresponding discovery module"
        module.version = "13.0"
    index: 10
    name: <module-bluez5-discover>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "João Paulo Rechi Vita"
        module.description = "Detect available BlueZ 5 Bluetooth audio devices and load BlueZ 5 Bluetooth audio drivers"
        module.version = "13.0"
    index: 11
    name: <module-native-protocol-unix>
    argument: <>
    used: -1
    load once: no
    properties:
        module.author = "Lennart Poettering"
        module.description = "Native protocol (UNIX sockets)"
        module.version = "13.0"
    index: 12
    name: <module-default-device-restore>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Automatically restore the default sink and source"
        module.version = "13.0"
    index: 13
    name: <module-rescue-streams>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "When a sink/source is removed, try to move its streams to the default sink/source"
        module.version = "13.0"
    index: 14
    name: <module-always-sink>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Colin Guthrie"
        module.description = "Always keeps at least one sink loaded even if it's a null one"
        module.version = "13.0"
    index: 15
    name: <module-intended-roles>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Automatically set device of streams based on intended roles of devices"
        module.version = "13.0"
    index: 16
    name: <module-suspend-on-idle>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "When a sink/source is idle for too long, suspend it"
        module.version = "13.0"
    index: 17
    name: <module-console-kit>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Create a client for each ConsoleKit session of this user"
        module.version = "13.0"
    index: 18
    name: <module-systemd-login>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Create a client for each login session of this user"
        module.version = "13.0"
    index: 19
    name: <module-position-event-sounds>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Position event sounds between L and R depending on the position on screen of the widget triggering them."
        module.version = "13.0"
    index: 20
    name: <module-role-cork>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Lennart Poettering"
        module.description = "Mute & cork streams with certain roles while others exist"
        module.version = "13.0"
    index: 21
    name: <module-snap-policy>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Canonical Ltd"
        module.description = "Ubuntu Snap policy management"
        module.version = "13.0"
    index: 22
    name: <module-filter-heuristics>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Colin Guthrie"
        module.description = "Detect when various filters are desirable"
        module.version = "13.0"
    index: 23
    name: <module-filter-apply>
    argument: <>
    used: -1
    load once: yes
    properties:
        module.author = "Colin Guthrie"
        module.description = "Load filter sinks automatically when needed"
        module.version = "13.0"
    index: 24
    name: <module-cli-protocol-unix>
    argument: <>
    used: -1
    load once: no
    properties:
        module.author = "Lennart Poettering"
        module.description = "Command line interface protocol (UNIX sockets)"
        module.version = "13.0"
1 sink(s) available.
  * index: 0
    name: <alsa_output.pci-0000_00_08.0.analog-stereo>
    driver: <module-alsa-card.c>
    flags: HARDWARE HW_MUTE_CTRL HW_VOLUME_CTRL DECIBEL_VOLUME LATENCY DYNAMIC_LATENCY
    state: SUSPENDED
    suspend cause: IDLE
    priority: 9039
    volume: front-left: 29115 /  44% / -21,14 dB,   front-right: 29115 /  44% / -21,14 dB
            balance 0,00
    base volume: 52057 /  79% / -6,00 dB
    volume steps: 65537
    muted: no
    current latency: 0,00 ms
    max request: 0 KiB
    max rewind: 0 KiB
    monitor source: 0
    sample spec: s16le 2ch 44100Hz
    channel map: front-left,front-right
                 Stereo
    used by: 0
    linked by: 0
    configured latency: 0,00 ms; range is 0,50 .. 371,52 ms
    card: 0 <alsa_card.pci-0000_00_08.0>
    module: 7
    properties:
        alsa.resolution_bits = "16"
        device.api = "alsa"
        device.class = "sound"
        alsa.class = "generic"
        alsa.subclass = "generic-mix"
        alsa.name = "CS4206 Analog"
        alsa.id = "CS4206 Analog"
        alsa.subdevice = "0"
        alsa.subdevice_name = "subdevice #0"
        alsa.device = "0"
        alsa.card = "0"
        alsa.card_name = "HDA NVidia"
        alsa.long_card_name = "HDA NVidia at 0xd3280000 irq 23"
        alsa.driver_name = "snd_hda_intel"
        device.bus_path = "pci-0000:00:08.0"
        sysfs.path = "/devices/pci0000:00/0000:00:08.0/sound/card0"
        device.bus = "pci"
        device.vendor.id = "10de"
        device.vendor.name = "NVIDIA Corporation"
        device.product.id = "0d94"
        device.product.name = "MCP89 High Definition Audio"
        device.form_factor = "internal"
        device.string = "front:0"
        device.buffering.buffer_size = "65536"
        device.buffering.fragment_size = "32768"
        device.access_mode = "mmap+timer"
        device.profile.name = "analog-stereo"
        device.profile.description = "Analog Stereo"
        device.description = "Built-in Audio Analog Stereo"
        alsa.mixer_name = "Cirrus Logic CS4206"
        alsa.components = "HDA:10134206,106b1f00,00100301 HDA:10de000c,10de0101,00100200"
        module-udev-detect.discovered = "1"
        device.icon_name = "audio-card-pci"
    ports:
        analog-output-speaker: Speakers (priority 10000, latency offset 0 usec, available: unknown)
            properties:
                device.icon_name = "audio-speakers"
        analog-output-headphones: Headphones (priority 9900, latency offset 0 usec, available: no)
            properties:
                device.icon_name = "audio-headphones"
    active port: <analog-output-speaker>
1 source(s) available.
  * index: 0
    name: <alsa_output.pci-0000_00_08.0.analog-stereo.monitor>
    driver: <module-alsa-card.c>
    flags: DECIBEL_VOLUME LATENCY DYNAMIC_LATENCY
    state: SUSPENDED
    suspend cause: IDLE
    priority: 1030
    volume: front-left: 65536 / 100% / 0,00 dB,   front-right: 65536 / 100% / 0,00 dB
            balance 0,00
    base volume: 65536 / 100% / 0,00 dB
    volume steps: 65537
    muted: no
    current latency: 0,00 ms
    max rewind: 0 KiB
    sample spec: s16le 2ch 44100Hz
    channel map: front-left,front-right
                 Stereo
    used by: 0
    linked by: 0
    configured latency: 0,00 ms; range is 0,50 .. 371,52 ms
    monitor_of: 0
    card: 0 <alsa_card.pci-0000_00_08.0>
    module: 7
    properties:
        device.description = "Monitor of Built-in Audio Analog Stereo"
        device.class = "monitor"
        alsa.card = "0"
        alsa.card_name = "HDA NVidia"
        alsa.long_card_name = "HDA NVidia at 0xd3280000 irq 23"
        alsa.driver_name = "snd_hda_intel"
        device.bus_path = "pci-0000:00:08.0"
        sysfs.path = "/devices/pci0000:00/0000:00:08.0/sound/card0"
        device.bus = "pci"
        device.vendor.id = "10de"
        device.vendor.name = "NVIDIA Corporation"
        device.product.id = "0d94"
        device.product.name = "MCP89 High Definition Audio"
        device.form_factor = "internal"
        device.string = "0"
        module-udev-detect.discovered = "1"
        device.icon_name = "audio-card-pci"
11 client(s) logged in.
    index: 0
    driver: <module-systemd-login.c>
    owner module: 18
    properties:
        application.name = "Login Session 1"
        systemd-login.session = "1"
    index: 4
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "GNOME Shell Volume Control"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.id = "org.gnome.VolumeControl"
        application.icon_name = "multimedia-volume-control"
        application.version = "3.34.1"
        application.process.id = "1171"
        application.process.user =
        application.process.host =
        application.process.binary = "gnome-shell"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
    index: 5
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "GNOME Volume Control Media Keys"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.id = "org.gnome.VolumeControl"
        application.icon_name = "multimedia-volume-control"
        application.version = ""
        application.process.id = "1371"
        application.process.user =
        application.process.host =
        application.process.binary = "gsd-media-keys"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
    index: 7
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "Firefox"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        window.x11.display = ":0"
        window.x11.screen = "0"
        application.process.id = "2756"
        application.process.user =
        application.process.host =
        application.process.binary = "firefox"
        application.language = "en_US.UTF-8"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
        application.icon_name = "firefox"
    index: 8
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "Firefox"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.icon_name = "firefox"
        application.version = "69.0.3"
        application.process.id = "2756"
        application.process.user =
        application.process.host =
        application.process.binary = "firefox"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
    index: 9
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "AudioIPC Server"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.process.id = "2756"
        application.process.user =
        application.process.host =
        application.process.binary = "firefox"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
        application.icon_name = "firefox"
    index: 10
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "Terminal"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.icon_name = "org.gnome.Terminal"
        window.x11.display = ":0"
        window.x11.screen = "0"
        application.process.id = "3166"
        application.process.user =
        application.process.host =
        application.process.binary = "gnome-terminal-server"
        application.language = "en_US.UTF-8"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
    index: 12
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "GNOME Settings"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.id = "org.gnome.VolumeControl"
        application.icon_name = "multimedia-volume-control"
        application.version = ""
        application.process.id = "4207"
        application.process.user =
        application.process.host =
        application.process.binary = "gnome-control-center"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
    index: 13
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "Settings"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        window.x11.display = ":0"
        window.x11.screen = "0"
        application.process.id = "4207"
        application.process.user =
        application.process.host =
        application.process.binary = "gnome-control-center"
        application.language = "en_US.UTF-8"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
        application.icon_name = "org.gnome.Settings"
    index: 14
    driver: <protocol-native.c>
    owner module: 11
    properties:
        application.name = "Mutter"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.process.id = "1171"
        application.process.user =
        application.process.host =
        application.process.binary = "gnome-shell"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"
    index: 16
    driver: <cli.c>
    owner module: 24
    properties:
        application.name = "UNIX socket client"
1 card(s) available.
    index: 0
    name: <alsa_card.pci-0000_00_08.0>
    driver: <module-alsa-card.c>
    owner module: 7
    properties:
        alsa.card = "0"
        alsa.card_name = "HDA NVidia"
        alsa.long_card_name = "HDA NVidia at 0xd3280000 irq 23"
        alsa.driver_name = "snd_hda_intel"
        device.bus_path = "pci-0000:00:08.0"
        sysfs.path = "/devices/pci0000:00/0000:00:08.0/sound/card0"
        device.bus = "pci"
        device.vendor.id = "10de"
        device.vendor.name = "NVIDIA Corporation"
        device.product.id = "0d94"
        device.product.name = "MCP89 High Definition Audio"
        device.form_factor = "internal"
        device.string = "0"
        device.description = "Built-in Audio"
        module-udev-detect.discovered = "1"
        device.icon_name = "audio-card-pci"
    profiles:
        input:analog-stereo: Analog Stereo Input (priority 65, available: unknown)
        output:analog-stereo: Analog Stereo Output (priority 6500, available: unknown)
        output:analog-stereo+input:analog-stereo: Analog Stereo Duplex (priority 6565, available: unknown)
        output:analog-surround-21: Analog Surround 2.1 Output (priority 1300, available: unknown)
        output:analog-surround-21+input:analog-stereo: Analog Surround 2.1 Output + Analog Stereo Input (priority 1365, available: unknown)
        output:analog-surround-40: Analog Surround 4.0 Output (priority 1200, available: unknown)
        output:analog-surround-40+input:analog-stereo: Analog Surround 4.0 Output + Analog Stereo Input (priority 1265, available: unknown)
        output:iec958-stereo: Digital Stereo (IEC958) Output (priority 5500, available: unknown)
        output:iec958-stereo+input:analog-stereo: Digital Stereo (IEC958) Output + Analog Stereo Input (priority 5565, available: unknown)
        output:hdmi-stereo: Digital Stereo (HDMI) Output (priority 5900, available: no)
        output:hdmi-stereo+input:analog-stereo: Digital Stereo (HDMI) Output + Analog Stereo Input (priority 5965, available: no)
        output:hdmi-surround: Digital Surround 5.1 (HDMI) Output (priority 800, available: no)
        output:hdmi-surround+input:analog-stereo: Digital Surround 5.1 (HDMI) Output + Analog Stereo Input (priority 865, available: no)
        output:hdmi-surround71: Digital Surround 7.1 (HDMI) Output (priority 800, available: no)
        output:hdmi-surround71+input:analog-stereo: Digital Surround 7.1 (HDMI) Output + Analog Stereo Input (priority 865, available: no)
        output:hdmi-stereo-extra1: Digital Stereo (HDMI 2) Output (priority 5700, available: no)
        output:hdmi-stereo-extra1+input:analog-stereo: Digital Stereo (HDMI 2) Output + Analog Stereo Input (priority 5765, available: no)
        output:hdmi-surround-extra1: Digital Surround 5.1 (HDMI 2) Output (priority 600, available: no)
        output:hdmi-surround-extra1+input:analog-stereo: Digital Surround 5.1 (HDMI 2) Output + Analog Stereo Input (priority 665, available: no)
        output:hdmi-surround71-extra1: Digital Surround 7.1 (HDMI 2) Output (priority 600, available: no)
        output:hdmi-surround71-extra1+input:analog-stereo: Digital Surround 7.1 (HDMI 2) Output + Analog Stereo Input (priority 665, available: no)
        output:hdmi-stereo-extra2: Digital Stereo (HDMI 3) Output (priority 5700, available: no)
        output:hdmi-stereo-extra2+input:analog-stereo: Digital Stereo (HDMI 3) Output + Analog Stereo Input (priority 5765, available: no)
        output:hdmi-surround-extra2: Digital Surround 5.1 (HDMI 3) Output (priority 600, available: no)
        output:hdmi-surround-extra2+input:analog-stereo: Digital Surround 5.1 (HDMI 3) Output + Analog Stereo Input (priority 665, available: no)
        output:hdmi-surround71-extra2: Digital Surround 7.1 (HDMI 3) Output (priority 600, available: no)
        output:hdmi-surround71-extra2+input:analog-stereo: Digital Surround 7.1 (HDMI 3) Output + Analog Stereo Input (priority 665, available: no)
        off: Off (priority 0, available: unknown)
    active profile: <output:analog-stereo>
    sinks:
        alsa_output.pci-0000_00_08.0.analog-stereo/#0: Built-in Audio Analog Stereo
    sources:
        alsa_output.pci-0000_00_08.0.analog-stereo.monitor/#0: Monitor of Built-in Audio Analog Stereo
    ports:
        analog-input-mic: Microphone (priority 8700, latency offset 0 usec, available: unknown)
            properties:
                device.icon_name = "audio-input-microphone"
        analog-output-speaker: Speakers (priority 10000, latency offset 0 usec, available: unknown)
            properties:
                device.icon_name = "audio-speakers"
        analog-output-headphones: Headphones (priority 9900, latency offset 0 usec, available: no)
            properties:
                device.icon_name = "audio-headphones"
        iec958-stereo-output: Digital Output (S/PDIF) (priority 0, latency offset 0 usec, available: unknown)
            properties:

        hdmi-output-0: HDMI / DisplayPort (priority 5900, latency offset 0 usec, available: no)
            properties:
                device.icon_name = "video-display"
        hdmi-output-1: HDMI / DisplayPort 2 (priority 5800, latency offset 0 usec, available: no)
            properties:
                device.icon_name = "video-display"
        hdmi-output-2: HDMI / DisplayPort 3 (priority 5700, latency offset 0 usec, available: no)
            properties:
                device.icon_name = "video-display"
0 sink input(s) available.
0 source output(s) available.
1 cache entrie(s) available.
    name: <bell-window-system>
    index: 0
    sample spec: s16le 2ch 44100Hz
    channel map: front-left,front-right
                 Stereo
    length: 51048
    duration: 0,3 s
    volume: n/a
            balance 0,00
    lazy: no
    filename: <n/a>
    properties:
        media.role = "event"
        event.description = "Bell event"
        event.id = "bell-window-system"
        media.name = "bell-window-system"
        media.filename = "/usr/share//sounds/Yaru/stereo/bell.oga"
        application.name = "Mutter"
        native-protocol.peer = "UNIX socket client"
        native-protocol.version = "33"
        application.process.id = "1171"
        application.process.user = "Macbook"
        application.process.host = "MacBook"
        application.process.binary = "gnome-shell"
        application.language = "en_US.UTF-8"
        window.x11.display = ":0"
        application.process.machine_id = "3510375181dd40a892dccb932abb57ce"

A: I have the same problem with the same Mac model.
The fact that it worked fine with 19.04 suggests that something may have happened between kernel 5.0 and kernel 5.3 (the one of 19.10).
Indeed, this user had the same problem just by updating the kernel from 4.19 to 5.2.
The bug was reported on kernel.org, someone identified the faulty commit, and a patch has been proposed.
So I guess either you recompile a 5.3 kernel with this patch or you install a 5.0 kernel ; or like I did you roll back to 19.04!


text:
Q: Check data from a database in discord.py I am implementing a documentation system and it was necessary that the user can only register his data once, so I create a database to store the data given by the subject through the command. So, I need to find a way to verify that the subject used the command and if he does, then prohibit him from doing it again.
Create a function which would be in charge of taking the data and comparing if the user ID is in the database, then if it is, the command is prohibited. My function did not work.
Does anyone have a solution to check and ban the user from using the command? Thank you.
async def on_BDLA(ctx):
    user = ctx.author.id
    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:
            datos = cursor.fetchall()
    if datos[4] == user:
        await ctx.send("Tu dni ya está registrado, no puedes hacerte otro.")

@bot.command()
@commands.check(on_BDLA)
async def crear_dni(ctx):
    status = True
    await ctx.send("Envía tu mensaje")
    respuesta = await bot.wait_for("message", timeout=60)
    respuesta = respuesta.content.split(", ")
    if status == False:
        await ctx.send("No tienes un DNI creado")
    elif status == True:
        dni_info = discord.Embed(title = f":card_index:DNI de {ctx.author.name}", description= f"**Nombre** \n➥ *{respuesta[0]}* \n**Apellido** \n➥ *{respuesta[1]}* \n**Nacimiento** \n➥ *{respuesta[2]}* \n**Nacionalidad** \n➥ *{respuesta[3]}* \n**ID** \n➥ *{ctx.author.id}*", color = discord.Color.purple() )
        dni_info.set_image(url="https://media.discordapp.net/attachments/1052061231680344134/1053135738180472832/banner.png")
        await ctx.send(embed = dni_info)
        async with aiosqlite.connect("main.db") as db:
            async with db.cursor() as cursor:
                await cursor.execute(f"INSERT INTO users (nombre, apellido, nacimiento, nacionalidad, id) VALUES (?, ?, ?, ?, ?)", (respuesta[0], respuesta[1], respuesta[2], respuesta[3], ctx.author.id))
            await db.commit()
    return respuesta

I hope to achieve a function that can help me verify the data and a way to prohibit it from using the command again.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get multi-data from an API JSON in Solidity Smart Contract? I have to develop a smart contract that when it's called a method it have to return some data from an API Json. I've followed the Chainlink's tutorial for single response at this link: Single Word Response and I'm trying to get more data by adding:
req.add("path", "0,symbol");
req.add("path", "0,name");
req.add("path", "0,image");

but when I call the "requestVolumeData" it doesn't return any value.
This is the full code:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
import "@chainlink/contracts/src/v0.8/ConfirmedOwner.sol";

contract MyToken is ERC721, ChainlinkClient, ConfirmedOwner {

    using Chainlink for Chainlink.Request;

    string public id;

    bytes32 private jobId;
    uint256 private fee;

    event RequestDataJson(bytes32 indexed requestId, string id);

    /**
     * @notice Initialize the link token and target oracle
     *
     * Goerli Testnet details:
     * Link Token: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
     * Oracle: 0xCC79157eb46F5624204f47AB42b3906cAA40eaB7 (Chainlink DevRel)
     * jobId: 7223acbd01654282865b678924126013
     *
     */

    constructor() ERC721("MyToken", "MTK") ConfirmedOwner(msg.sender) {
        setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
        setChainlinkOracle(0xCC79157eb46F5624204f47AB42b3906cAA40eaB7);
        jobId = "7d80a6386ef543a3abb52817f6707e3b";
        fee = (1 * LINK_DIVISIBILITY) / 10; // 0,1 * 10**18 (Varies by network and job)
    }

    function safeMint(address to, uint256 tokenId) public onlyOwner {
        _safeMint(to, tokenId);
    }

      /**
     * Create a Chainlink request the gas price from Etherscan
     */
    function requestDataJson() public returns (bytes32 requestId) {
        Chainlink.Request memory req = buildChainlinkRequest(
            jobId,
            address(this),
            this.fulfill.selector
        );
        // Set the URL to perform the GET request on
        // API docs: https://www.casabufalini.it/common/api/metadata.json
        req.add(
            "get",
            "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&per_page=10"
        );

        // Set the path to find the desired data in the API response, where the response format is:
        // [{
        //  "id": "bitcoin",
        //  "symbol": btc",
        // ...
        // },
        //{
        // ...
        // .. }]
        // request.add("path", "0.id"); // Chainlink nodes prior to 1.0.0 support this format
        req.add("path", "0,id"); // Chainlink nodes 1.0.0 and later support this format
        req.add("path", "0,symbol");
        req.add("path", "0,name");
        req.add("path", "0,image");
        // Sends the request
        return sendChainlinkRequest(req, fee);
    }

     /**
     * Receive the responses in the form of uint256
     */
    function fulfill(
        bytes32 _requestId,
        string memory _id
    ) public recordChainlinkFulfillment(_requestId) {
        emit RequestDataJson(_requestId, _id);
        id = _id;
    }

    /**
     * Allow withdraw of Link tokens from the contract
     */
    function withdrawLink() public onlyOwner {
        LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
        require(
            link.transfer(msg.sender, link.balanceOf(address(this))),
            "Unable to transfer"
        );
    }
}

Can anyone explain me how to get the other variables (data) of the API JSON?


text:
Q: Multiple custom validation in angular 2 I am facing a issue while adding multiple custom validation to a form. I can only add a single custom validation to my form. How to add multiple validations.
Eg:
this.user = this.fb.group({
  name: ['', Validators.required],
  account: this.fb.group({
    email: ['', Validators.required],
    confirm: ['', Validators.required]
  }, { validator: emailMatcher })
});

I want to add more validations like: { validator: [emailMatcher, matchPassword, othervalidation]}
Is there something in angular 2 which can help me in this.

A: Instead of :
{ validator: emailMatcher })

Use syntax:
{ validators:  [emailMatcher, matchPassword, othervalidation]}

Good luck.


text:
Q: MassEmailMessage does not work with more than 10 targetObjectIds MassEmailMessage should support 250 IDs per email according to documentation.
As of recently, I'm experiencing errors when there are more than 10 users. The SendEmailResult result is always false, with the message Too many target object ids.
Have there been some platform changes that I'm not aware of?
Example code block:
List<Id> userIds = new List<Id>{
    // more than 10 user Ids
};
Messaging.MassEmailMessage massEmail = new Messaging.MassEmailMessage();
massEmail.setTargetObjectIds(userIds);
massEmail.setSaveAsActivity(false);
massEmail.setTemplateId(templateId);
List<Messaging.Email> emails = new List<Messaging.Email>{massEmail};
Messaging.SendEmailResult[] results = Messaging.sendEmail(emails, false);

A: Support says that Salesforce previously hardcoded the number to 250, but have since started treating this as a limit based on the type of the org. For trial orgs, the undocumented limit became 10.
They quoted email limits section which states:

In Developer Edition orgs and orgs evaluating Salesforce during a trial period, you can send mass email to no more than 10 external email addresses per day. This lower limit doesn't apply if your org was created before the Winter '12 release and already had mass email enabled with a higher limit. Additionally, your org can send single emails to a maximum of 15 email addresses per day.

However, this previously did not apply, as stated in another section:

There's no limit on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity, case, campaign, or custom object pages.


text:
Q: Can I add GridView inside a Listview item? I want to add a GirdView inside a ListView ? Is it possible ? where I set a different adapter for each
edit // upon the following code (gridView) deosn't appear why?
this is thew adapter for GridView
package com.android.utils;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.uis.R;

public class TimesAdapter extends BaseAdapter {

    private ArrayList<String> listTitle;
    private ArrayList<String> listDates;
    private Activity activity;

    public TimesAdapter(Activity activity, ArrayList<String> listDates,ArrayList<String> listTitle){
        this.listTitle=listTitle;
        this.listDates=listDates;
        this.activity=activity;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder view;
        LayoutInflater inflator = activity.getLayoutInflater();
        if(convertView==null){
            view = new ViewHolder();
            //inflate : inflate xml resources into object
            convertView = inflator.inflate(R.layout.gridview_times_row, null);
            view.tvTitle=(TextView) convertView.findViewById(R.id.tvTitle);
            view.tvDate=(TextView) convertView.findViewById(R.id.tvDate);

            convertView.setTag(view);

        }else{
            view = (ViewHolder) convertView.getTag();
        }
        view.tvTitle.setText(listTitle.get(position));
        view.tvDate.setText(listDates.get(position));
        return convertView;
    }

    static class ViewHolder{
        public TextView tvTitle;
        public TextView tvDate;
    }

}

This is the class of ListView(that show a GridView) with it's adapter class
package com.android.uis;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.classes.Appointment;
import com.android.database.DatabaseHelper;
import com.android.networkservices.TimeTableWebService;
import com.android.utils.TimesAdapter;

public class DaysActivity extends Activity {
    private ListView lvDay;
    private Button bUpdateTimeTable,bChangeDate;
    private ArrayList<String> items;
    private ArrayList<Appointment> appointments;
    private ArrayList appointmentsArray[] = new ArrayList[7];
    private EfficientAdapter adap;
    private int mYear;
    private int mMonth;
    private int mDay;
    static final int DATE_DIALOG_ID = 0;
    private Activity activity;
    int dayIndex;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.day_layout);
        lvDay = (ListView)this.findViewById(R.id.lvDay);
        bUpdateTimeTable = (Button)this.findViewById(R.id.bUpdateTimeTable);
        bChangeDate = (Button)this.findViewById(R.id.bChangeDate);
        items = new ArrayList<String>();
        appointments = new ArrayList<Appointment>();
        lvDay.setClickable(true);
        activity = this;

        if(getIntent()!=null)
            if(getIntent().getExtras()!=null)
                if(getIntent().getExtras().getString("day")!="")
                    dayIndex = Integer.parseInt(getIntent().getExtras().getString("day"));
                else
                    dayIndex = -1;
            else
                dayIndex = -1;
        else
            dayIndex = -1;
        Log.d("dayIndex",dayIndex+"");
        bindList(dayIndex);// to bind list items

        lvDay.setOnItemClickListener(new OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position,long id) {

            }
        });
        bUpdateTimeTable.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                DatabaseHelper db = new DatabaseHelper(getApplicationContext());

                // At first delete the previous data then retrieve the new one
                    db.deteleAllAppointments();
                    appointments.clear();
                    items.clear();

                    TimeTableWebService ttws = new TimeTableWebService();
                    ttws.execute("http://mmu4bader.com/AppointmentJSon/getAppointments1");
                    ttws.getResult(getApplicationContext());
                    //bindList();
            }

        });
        bChangeDate.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showDialog(DATE_DIALOG_ID);
                Toast.makeText(getApplicationContext(), "date", Toast.LENGTH_SHORT).show();
            }
        });
        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();

    }
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
    };
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(this,mDateSetListener,mYear, mMonth, mDay);
        }
        return null;
    }
    private void updateDisplay() {
        // TODO Auto-generated method stub

    }
    private void bindList(int DayIndex){
        DatabaseHelper db = new DatabaseHelper(getApplicationContext());
        ArrayList<Appointment> tempAppointments = db.getAllAppointments();

        for(int i=0;i<tempAppointments.size();i++)
        {
            Date currentDate = new Date();// get current date
            Date eventDate = tempAppointments.get(i).mStartDate;
        //  int dateEqual = getZeroTimeDate(currentDate).compareTo(getZeroTimeDate(eventDate));

        //  Log.d("event day index",eventDate.getDay()+" "+eventDate);
        //  Log.d("current day index",currentDate.getDay()+" "+currentDate);

            if(eventDate.getDay()==DayIndex)
            {
                items.add(String.valueOf(tempAppointments.get(i).mTitle));
                appointments.add(tempAppointments.get(i));

            }

        }

        adap = new EfficientAdapter(this);
        adap.notifyDataSetChanged();
        lvDay.setAdapter(adap);
    }
    public static Date getZeroTimeDate(Date fecha) {
        Date res = fecha;
        Calendar calendar = Calendar.getInstance();

        calendar.setTime( fecha );
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        res = calendar.getTime();

        return res;
    }
    public void onResume() {
        super.onResume();
    }
    public class EfficientAdapter extends BaseAdapter implements Filterable{

        LayoutInflater inflater;
        Context context;

        public EfficientAdapter(Context context){
            inflater = LayoutInflater.from(context);
            this.context = context;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return items.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return items.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            ArrayList<String> listDates = new ArrayList<String>();
            ArrayList<String>listTitle = new ArrayList<String>();
            listDates.add("17/5/1987");
            listTitle.add("Gaza");
            if(convertView == null){
                convertView = inflater.inflate(R.layout.adaptor_timetable_content, null);
                holder = new ViewHolder();

                holder.gvDates = (GridView)convertView.findViewById(R.id.gvDates);
                holder.textLineTitle = (TextView)convertView.findViewById(R.id.textLineTitle);
                holder.textLineTime = (TextView)convertView.findViewById(R.id.textLineTime);

                convertView.setOnClickListener(new OnClickListener() {
                    private int pos = position;

                        public void onClick(View v) {
                        /*  Intent i = new Intent(context,RoutingMapActivity.class);
                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            i.putExtra("Department", depts.get(pos).toBunlde());
                            getApplicationContext().startActivity(i);  */
                            }
                        });

                convertView.setTag(holder);
            }else{
                holder = (ViewHolder)convertView.getTag();
            }
            // Bind the data efficiently with the holder.
            try{

                holder.textLineTitle.setText(String.valueOf(appointments.get(position).mTitle));
                holder.textLineTime.setText(String.valueOf(appointments.get(position).mStartDate));
                holder.gvDates.setAdapter(new TimesAdapter(activity,listDates,listTitle));
                Log.d("-----adapter",listDates.size()+"");
                holder.gvDates.setOnItemClickListener(new OnItemClickListener() {
                    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                        // show time info.
                    }
                });

            }catch(Exception ex){

            }
            return convertView;
        }

        public Filter getFilter() {
            // TODO Auto-generated method stub
            return null;
        }

    }
    static class ViewHolder {
        TextView textLineTitle;
        TextView textLineTime;
        GridView gvDates;
    }

}

A: Your TimesAdapter does not contain any data. The getCount() method always returns 0 which is telling the OS that there are no entries.


text:
Q: How to use the SublimeSBT plugin? I'm trying to run a simple Scala program in Sublime text using the SublimeSBT plugin, but I can't seem to get it to work. Firstly, following http://www.scala-sbt.org/0.13/docs/Hello.html I ran the command
sbt new sbt/scala-seed.g8

This creates a directory called hello. If I cd to that directory and launch sublime using subl ., and bring up the command palette, I don't see the commands prefixed with SBT: which should be there according to the SublimeSBT usage instructions:

I'm pretty sure that I installed the plugin as it shows up as SublimeSBT in Sublime Text -> Preferences -> Package Settings. Can anyone explain why this is not working?

A: What I wanted was to simply run simple scripts (like https://scalafiddle.io/) and I solved this problem by
brew install scala

and adding the following build system as Scala.sublime-build (cf. Configure Sublime Text build system for Scala?):
{
    "cmd": ["/usr/local/bin/scala", "$file_name"],
    "working_dir": "${project_path:${folder}}",
    "selector": "source.scala"
}

Now when you press Cmd + B it will run the script (see screen grab below).


text:
Q: jQuery - On scroll remove class above and below This is my first post and question here. Please look at the image below:

I have the page with a block element divs (example, one div in a row, with height of 100px, and 30 divs one under another). I need solution which will add class to divs which are in "red" offset, and while I'm scrolling up or down to remove same class to divs which are out of offset.
I know it has to be something with offsets, but I can't really find solution. I'm trying to do this with jQuery.

A: To calculate elements position relative to viewport you need to check getBoundingClientRect, than it is easy:

function isInScreenPlusOffset(el, offset) {
    var rect = el[0].getBoundingClientRect();
    return (
        rect.top >= -offset &&
        rect.bottom <= $(window).height()+offset
    );
};
$(window).on('scroll', function(e){
    $('.basic').each(function(i) {
        var thisBox = $(this);
        thisBox.toggleClass('standard', isInScreenPlusOffset(thisBox , 300));
    });
});
.basic {
    border: 1px solid #000;
    width: 200px;
    height: 200px;
    margin: 10px auto;
}
.standard {
    border-color: green;
}

Also on Fiddle.


text:
Q: Can I convert a DateTimeField to a string for use with my model with wicket So I have DateTimeField (a TimeField really... But wicket is obscure enough).  It would seem to instantiate this field the PropertyModel needs to be of Type.  Well, In my model, I have the date as a type of string.  That is how it will be stored in the database.  There are other downstream consequences as well.  Is there a way in wicket to convert the type of the Timefield to string instead of date?
right now I am overriding toString().  I doubt that will do anything, but hey, its worth a shot.
Sample code for those who need it to answer abstract questions (the model is the SimpleObjectVO btw):
public SimpleObjectVO
{
    ...
    String wackyDueTime = null;
}

...

wackyDueTime = new TimeField("wackyDueTime", new PropertyModel<Date>(model, , "wackyDueTime"))
{
    @Override
    public String toString(){
        return HOURS + ":" + MINUTES + " " + AM_OR_PM_CHOICE;
    }
}

A: TimeField works with java.util.Date(). You can use Date for the UI and then store it as you'd like in the database.


text:
Q: If there is a way to deploy jdbc driver using Arquillian I am trying to run the test by using embedded wildFly. I want Arquillian to deploy the jdbc driver before test. If it is possible, or I forced to deploy this driver manualy to the server before testing?

A: i had the same problem like you- trying to get our jpa-unit tests run with arquillian and using an embedded wildfly for it.
I´ve resolved it partially- for the moment i was able to add the MSSQL-driver to the embedded wildfly. My current problem is to add a datasource, to connect to the database...
But here´s my part of the POM, which extracts the wildfly to the /target folder and then copying the db-driver to the standalone/deployments folder of the embedded wildfly. So the driver get registered succesfull (I´ve checked this in the management console of the embedded wildfly):
I hope this helps you. Maybe you have a solution how to add the datasource for the embedded wildfly? (If you need this too)
<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <id>unpack</id>
            <phase>process-test-classes</phase>
            <goals>
                <goal>unpack</goal>
            </goals>
            <configuration>
                <artifactItems>
                    <artifactItem>
                        <groupId>org.wildfly</groupId>
                        <artifactId>wildfly-dist</artifactId>
                        <version>8.2.0.Final</version>
                        <type>zip</type>
                        <overWrite>false</overWrite>
                        <outputDirectory>target</outputDirectory>
                    </artifactItem>
                </artifactItems>
            </configuration>
        </execution>

        <execution>
            <id>copy-db-driver</id>
            <phase>process-test-resources</phase>
            <goals>
                <goal>copy</goal>
            </goals>
            <configuration>
                <artifactItems>
                    <artifactItem>
                        <groupId>com.microsoft</groupId>
                        <artifactId>sqljdbc</artifactId>
                        <version>4.0.2206.100</version>
                        <outputDirectory>target/wildfly-8.2.0.Final/standalone/deployments</outputDirectory>
                    </artifactItem>
                </artifactItems>
            </configuration>
        </execution>
    </executions>
</plugin>


text:
Q: Cannot find namespace error I have the following setup:
// enums.ts
export enum DocumentType {
  Email = 0,
  Unknown = 1
}

-
// remote.ts
/// <reference path="./remote.d.ts" />
import enums = require('./enums');

class Remote implements test.IRemote {
  public docType: enums.DocumentType;

  constructor() {
    this.docType = enums.DocumentType.Unknown;
  }
}

export = Remote;

-
// remote.d.ts
import * as enums from './enums';

declare module test {
  export interface IRemote {
    docType: enums.DocumentType;
  }
}

But when I run tsc over this I get Cannot find namespace 'test' from remotes.ts. What am I missing?
Other information that might be useful: I've recently upgraded from Typescript 1.5 to Typescript 1.8 and replaced the use of const enums with plain enums as in the example.

A: You need to export the internal module from remote.d.ts as well:
remote.d.ts
import * as enums from './enums';

export declare module test {
    export interface IRemote {
        docType: enums.DocumentType;
    }
}

This is because you have the external module remote (the file itself is the module when there is a top-level import or export statement), from which types and other symbols are available when they are exported, much like how IRemote is exported from module test.
In other words, you have an internal module inside an external module, but the internal module is not exported. Also, the IRemote interface is effectively double wrapped, and would qualify for the fullname remote.test.IRemote.

Note: IMO, mixing internal modules and external modules in the same project can lead to many issues and inconveniences if you are not careful and as such, should be avoided when possible.

A: In my universe Cannot find namespace error is CLI service thing that goes away after restarting npm watcher.


text:
Q: jsPdf Android Stock browser error I'm developing a script that transforms a HTML table in pdf document. To do this i use jsPdf and jsPDF-AutoTable. I did some testing on various brwser and everything works fine except for the Android Stock Browser.

Android stock browser error :

Resource interpreted as Document but transferred with MIME type
  application/pdf:
  "data:application/pdf;base64,JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJ…l6ZSAxOQovUm9vdCAxOCAwIFIKL0luZm8gMTcgMCBSCj4+CnN0YXJ0eHJlZgozMDk5CiUlRU9G".

jsPdf Code
Error jspdf.debug.js line 863

case 'dataurl':   return global.document.location.href = datauri;

jspdf version: jspdf/1.0.272/jspdf.debug.js
What's wrong?

A: The "Android stock browser error" is probably just a warning that you most likely don't have to worry about. However it might be that old versions of the android stock browser don't support datauri as location href. I would try to use the save method instead to get the pdf.
doc.save('table.pdf');


text:
Q: What is the exact difference between 'tty' and a 'console'? I know the general idea of console, tty as here explains https://unix.stackexchange.com/questions/4126/what-is-the-exact-difference-between-a-terminal-a-shell-a-tty-and-a-con
But when run who (using iTerm2) I got these and I don't understand the difference here. BTW, I open 2 tabs in iTerms
ws ➤ who
qiulang  console  Dec  5 17:47
qiulang  ttys002  Dec  5 17:48
qiulang  ttys004  Dec  6 10:41

A: The console is your physical computer and the various tty are virtual terminals.
Each tab or window of a terminal emulator like iTerm2.app or Terminal.app will connect to a different tty.  MacOS works the same as this quote from one of the answers on your linked question:

So when you look to a "text window" on your linux system (under X11) you are looking to: a terminal emulator, connected to a virtual terminal, identified by a tty file, inside which runs a shell.

It is more clear what is happening if you run who with who -a (to show all details) and if you also use the tty command (which returns the current terminal).

An example
Here I rebooted at 13:20, left it on the FileVault password entry screen until 13:25 then opened a Terminal.app session at 13:29.
Last login: Fri Dec  6 13:25:54 on console
A1398% tty
/dev/ttys000
A1398%

You can see the last logon was 13:25:54 on console (when FileVault unlocked startup disk) and Terminal.app is running on /dev/ttys000.
Next at 13:30 opened a iTerm2.app session:
Last login: Fri Dec  6 13:29:06 on ttys000
A1398% tty
/dev/ttys001
A1398% who -a
reboot   ~        Dec  6 13:25   .           1
hali     console  Dec  6 13:25 00:04        97
hali     ttys000  Dec  6 13:29 00:01       577
hali     ttys001  Dec  6 13:30   .         600
   .       run-level 3
A1398%

You can see the last logon is shown to be 13:29:06 on ttys000 (when Terminal.app was opened) and iTerm2.app connected at 13:30 to /dev/ttys001.
who -a shows

*

*console connecting at 13:25 (when password was entered and FileVault unlocked startup disk).

*ttys000 connecting at 13:29 (when Terminal.app was opened).

*ttys001 connecting at 13:30 (when this session of iTerm2 was opened).

If you boot into single user mode and type tty you will see the result /dev/console (who is not available)


text:
Q: Using Hibernate with MS ACCESS 2007 Database (Free JDBC Driver) 1.
I want to do a reverse engineering action with the Hibernate plugin of Eclipse on a MS Access 2007 Database. I'm forced to use a existing MS Access 2007 db.
A easy solution is to buy the HXTT. But I want to use a free driver to do my work.
So I tried to apply this post :
http://www.programmingforfuture.com/2011/06/how-to-use-ms-access-with-hibernate.html
(That uses the SQL Server dialect and the driver sun.jdbc.odbc.JdbcOdbcDriver)
Unfortunately I have an error that nobody seems to have been on the internet:

Exception while generating code
Reason :
org.hibernate.exception.GenericJDBCException: Error while reading primary key meta data for `c:/myaccessdb.mdb`.TableTest1

I have try to change the primary key on my MS Access DB (deleting all primary key) or to try the reverse engineering on a MS ACCESS with only one table without primary key, but I got all times the problems.
2.
The purpose of my job is to transfer daily (weekly) an Oracle 11g database with data from an existing database MS ACCESS 2007. And I thought to use a procedure (Hibernate EJB) Java to be launched automatically every week to do the data transfer. Is this is the best solution ?
Configuration :

*

*sun.jdbc.odbc.JdbcOdbcDriver v???

*Hibernate v3.4

*Eclipse

ps: If you are a HXTT developer or seller please be indulgent with my post ;). Making money by making people believe that you help, it's bad !

A solution is to use Derby Client driver, as the solution in the post:
Does anyone know if Hibernate and java will work effectively with Access?
But a clarification of the answer of Rich Seller is required. Could you explain your answer and explain your configuration (hibernate.cfg.xml, persistence.xml and what URL you use in the property name="hibernate.connection.url") without using paying HXTT driver but with the free Derby driver.

A: the only available solution is to connect your JDBC driver like that :
//Load the JDBC driver, useless with a Type 4 JDBC driver
Class.forName(DRIVER_NAME);

//To add specific properties such as a username/password pair
Properties connectionProperties = new Properties();

//Try to establish a connection to the database
connection = DriverManager.getConnection(DATABASE_URL, connectionProperties);

And, then, make free reverse engineering is'nt possible...
The only way is to make entitiesManager whit yours beautifuls hands.
Have Fun!

A: As per the Hibernate forum the HXTT driver is the only solution currently available for using Hibernate with MS Access.


text:
Q: Skip white space and return one word at a time in C This code is supposed to skip white space and return one word at a time. A couple of questions on this code:  When the code gets to the *word++=c; line I get a core dump.  Have I written this line correctly? and is return correct.  And Do I need to somehow allocate memory to store the word?
//get_word

int get_word(char *word,int lim){
int i=0;
int c;
int quotes=0;
int inword = 1;

while(
       inword &&
       (i < (lim-1)) &&
       ((c=getchar()) != EOF)
      ){

  if(c==('\"')){//this is so i can get a "string"
    if (quotes) {
      inword = 0;
    }
    quotes = ! quotes;
  }
  else if(quotes){ //if in a string keep storing til the end of the string
    *word++=c;//pointer word gets c and increments the pointer
    i++;
  }
  else if(!isspace(c)) {//if not in string store
    *word++=c;
    i++;
  }
  else {
    // Only end if we have read some character ...
    if (i)
      inword = 0;
  }
}
*word='\0';                            //null at the end to signify
return i;                               //value

}

A: It's impossible to tell why this core dumps without seeing the code that calls get_word.  The failure at the line you named implies that you are passing it something invalid in the first parameter. There's nothing wrong with that line in and of itself, but if word does not point to writable memory large enough to hold your output characters, you are in trouble.
The answer to your question about allocating memory to hold it is yes - however this could be local (e.g. a char array in the caller's local variables, global, or heap-based (e.g. from char * wordHolder = malloc(wordLimit);).  The fact you are asking this supports the guess that your parameter 1 value is the problem.


text:
Q: C# Lazy execution + memory understandings Can you please explain to me what happens in the memory while executing the following code:
Case 1:
public static void Execute()
{
    foreach(var text in DownloadTexts())
    {
          Console.WriteLine(text);
    }
}

public static IEnumerable<string> DownloadTexts()
{
     foreach(var url in _urls)
     {
         using (var webClient = new WebClient())
         {
              yield return webClient.DownloadText(url);
         }
     }
}

Let's assume after the first iteration I get html1.
When will html1 be cleared from the memory ?

*

*on the next iteration?

*when the foreach ends?

*when the function ends ?

Thanks
** Edit **
Case 2:
public static void Execute()
{
    var values = DownloadTexts();
    foreach(var text in values)
    {
          Console.WriteLine(text);
    }
}

public static IEnumerable<string> DownloadTexts()
{
     foreach(var url in _urls)
     {
         using (var webClient = new WebClient())
         {
              yield return webClient.DownloadText(url);
         }
     }
}

To my understanding, Case 1 is better for the memory then case 2 right?
In case 2 will still keep a reference to the texts we already downloaded while in Case 1 every text is marked for garbage collection once its not used. Am I correct?

A: *

*_urls will stay indefinitely because it is located in a field as it seems.

*DownloadTexts() (the iterator returned by it) is kept alive until the end of the loop.

*the WebClient and the html it produces stay alive for one iteration. If you want to know the absolute precise lifetime of it, you need to use Reflector and mentally simulate where the reference travels around. You'll find that the IEnumerator used in the loop references it until the next iteration has begun.

All objects that are not alive can be GC'ed. This happens whenever the GC thinks that is a good idea.
Regarding your Edit: The cases are equivalent. If you don't put the enumerator into a variable, the compiler will do that for you. It has to keep a reference till the end of the loop. It does not matter how many references there are. There is at least one.
Actually, the loop only requires the enumerator to be kept alive. The additional variable you added will also keep the enumerable alive. On the other hand you are not using the variable so the GC does not keep it alive.
You can test this easily:
//allocate 1TB of memory:
var items =
    Enumerable.Range(0, 1024 * 1024 * 1024)
    .Select(x => new string('x', 1024));
foreach (var _ in items) { } //constant memory usage

A: It will be cleared from memory when the garbage collector runs and determines that it's no longer in use.
The value will no longer be in use at the moment when the foreach causes the IEnumerator.MoveNext() method to be invoked. So, effectively, #1.

A: It will be cleared from memory when Garbage Collector will feel like doing so.
But starting point is when code holds no more references to instance of object.
So the answer in this case is: sometime after block in which you created object ends.
Have trust in GC, it is good at doing its job.


text:
Q: Why am I getting the error 'No such module FirebaseUI' in swift? Every time I try to build I get the error 'No such module FirebaseUI'
Things I have tried:

*

*Clearing derived data

*running 'pod update' to make sure all dependencies are up to date

*running my install as arch -x86_64 pod install

*making sure I am running the app by opening .xcworkspace as opposed to .xcodeproj

*Cleaning my build folder(Command+Shift+K)

*Deleting my project and redownloading from Git

*Adding the FirebaseUI Framework directly to my project

*Changing the Scheme to FirebaseCore allows the project to build but the simulator does not open for testing, nor does it run on a physical device.

*Running pod deintegrate && pod install, I noted that this command did mention that FirebaseUI was included and that the version was 11.03

*Running xcode in Rosetta

I am running this project on a new MacBook Pro with the M1 chip. Previously, my project ran fine on the older intel chip. My Xcode version is 12.5.1, and my OS is 11.4
Here is my pod file:
# Uncomment the next line to define a global platform for your project
 platform :ios, '12.0'

post_install do |pi|
    pi.pods_project.targets.each do |t|
      t.build_configurations.each do |config|
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0'
      end
    end
end

target 'Pikit' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Fixed Pod configuration
  # Pods for Pikit
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Firestore'
  pod 'Firebase/Functions'
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
  pod 'Firebase/DynamicLinks'
  pod 'FirebaseUI/Auth'
  pod 'FirebaseUI/Email'
  pod 'FirebaseUI/Google'
  pod 'FirebaseUI/OAuth' # Used for Sign in with Apple, Twitter, etc

  # Other Podfiles
  pod 'OnboardKit'
  # Auto move screen for keyboard
  pod 'SDWebImage'
  pod 'PureLayout'
  pod 'IQKeyboardManagerSwift'
  pod 'Google-Mobile-Ads-SDK'

end

Edit
the previously selected answer was working for a while but after changing the version of an unrelated pod the application is showing the same issue.

A: FirebaseUI version 11 is now broken into submodules so you will need to import individual modules (e.g. import FirebaseAuthUI) rather than previously using just import FirebaseUI.  Or instruct your Podfile to use an older version.
From FirebaseUI 11.0.0 release notes:

Breaking change: Broke monolithic FirebaseUI module into separate modules per feature. You'll need to update the imports in your project accordingly.
// FirebaseUI 10.x
import FirebaseUI
// FirebaseUI 11
import FirebaseAuthUI
import FirebaseDatabaseUI
// ...

A: I recommend you running the pod install command under the x86 architecture because I've seen that running this command native bring some problems, try:
arch -x86_64 pod install

A: I found a solution but I am going to keep this open as I am not sure it is a permanent solution/ not sure why it worked. This conflicts directly with one of the earlier answers. I removed all FirebaseUI pods besides the base one so that my pods related to fire base include only the following:
  pod 'Firebase'
  pod 'Firebase/Storage'
  pod 'Firebase/Auth'
  pod 'Firebase/Firestore'
  pod 'Firebase/Functions'
  pod 'Firebase/Analytics'
  pod 'Firebase/Messaging'
  pod 'Firebase/DynamicLinks'
  pod 'FirebaseUI'


text:
Q: Finding a child of a HTMLCollection by attribute value Within a unit test for an angular directive, I want to inspect the DOM that has been compiled:
var element = $compile("

")($rootScope);
var children = element[0].children;   // HTMLCollection

expect(children.length).toBeGreaterThan(0);  // that's fine

Especially, I want to check for the existence of a specific child element having an attribute pr-swipe-handler='right'.
I know I could iterate the children and their attributes-collections, but I'm sure there is a more tense solution.
Here's what I tried (refering to this answer of a similar post):
// TypeError: angular.element(...).querySelector is not a function
angular.element(children).querySelector("[pr-swipe-handler='right']")

// TypeError: children.querySelector is not a function
angular.element(children.querySelector("[pr-swipe-handler='right']"))

A: Here's a plunkr that should help you:
http://plnkr.co/edit/YRSgbsGCWGujhiOGV97z?p=preview
Code:
app.controller('MainCtrl', function($compile, $document, $scope) {
  $scope.name = 'World';
  var element = $compile('

')($scope);
  console.log(element[0]);
  console.log(element);
  $document.append(element);
  console.log(document.querySelectorAll('[pr-swipe-handler="right"]'))
});

You can not call querySelector on an element, but you can call it on document. You'll need to append the element to document in your tests, but you should be doing that anyway.

A: Peter Ashwell's answer showed me the right direction. Inspecting the HTMLCollection using the querySelector-api is possible only if the elements of the HTMLCollection are part of the actual DOM. Therefore it is necessary to append the compiled elements to it.
Thanks to that answer to a similar question, it turns out that the compiled element has to be appended to a concrete element in the DOM of the browser, such as body. $document is not enough:
  var element = $compile('

')($scope);
  var body = $document.find('body');
  $document.append(element);   // That's not enough.
  //body.append(element);      // That works fine.
  var rightHandler = document.querySelectorAll('[pr-swipe-handler="right"]');
  $scope.info = rightHandler.length + ' element(s) found.';

Refer to this plunk.


text:
Q: Erlang - spawning processes and passing arguments I keep running into this. I want to spawn processes and pass arguments
to them without using the MFA form (module/function/arguments), so
basically without having to export the function I want to spawn with
arguments. I've gotten around this a few times using closures(fun's)
and having the arguments just be bound values outside the fun(that I then reference inside the fun), but its
limiting my code structure... I've looked at the docs and spawn only
has the regular spawn/1 and the spawn/3 form, nothing else...
I understand that code reloading in spawned processes is not possible without the use of the MFA form but the spawned processes are not of the long running nature and finish relatively quickly so that's not an issue (I also want to contain all the code in one module-level function with sub-jobs being placed in funs inside that function).
much appreciated
thanks

A: Short answer: you can't.  Spawn (in all it's varying forms) only takes a 0-arity function.  Using a closure and bringing in bound variables from the spawning function is the way to go, short of using some sort of shared data store like ETS (which is Monster Overkill).
I've never found using a closure to severely hamper my code structure, though; can you give an example of the problems you're having, and perhaps someone can tidy it up for you?

A: This is an old question but I believe it can be properly answered with a bit of creativity:
The goal of the question is to

*

*Invoke a function

With the following limits;

*

*No M:F/A formatting

*No exporting of the Invoked function

This can be solved in the following;
Using the 1st limitation leads us to the following solution:
run() ->
    Module = module,
    Function = function,
    Args = [arg1, arg2, arg3],
    erlang:spawn(Module, Function, Args).

In this solution however, the function is required to be exported.
Using the 2nd limitation (No exporting of the Invoked function) alongside the 1st leads us to the following solution using conventional erlang logic:
run() ->
    %% Generate an anonymous fun and execute it
    erlang:spawn(fun() -> function(arg1, arg2, arg3) end).

This solution generates Anonymous Funs every execution which may or may not be wanted based on your design due to the extra work that the Garbage Colelctor will need to perform (note that, generally, this will be neglible and issues will potentially only be seen in larger systems).
An alternative way to write the above without generating Anonymous Funs would be to spawn an erlang:apply/2 which can execute functions with given parameters.
By passing a Function Ref. to erlang:apply/2, we can reference a local function and invoke it with the given arguments.
The following implements this solution:
run() ->
    %% Function Ref. to a local (non-exported) function
    Function = fun function/arity,
    Args = [arg1, arg2, arg3],
    erlang:spawn(erlang, apply, [Function, Args]).

Edit: This type of solution can be found within the Erlang Src whereby erlang:apply/2 is being called to execute a fun() with args.
%% https://github.com/erlang/otp/blob/71af97853c40d8ac5f499b5f2435082665520642/erts/preloaded/src/erlang.erl#L2888%% Spawn and atomically set up a monitor.

-spec spawn_monitor(Fun) -> {pid(), reference()} when
      Fun :: function().
spawn_monitor(F) when erlang:is_function(F, 0) ->
    erlang:spawn_opt(erlang,apply,[F,[]],[monitor]);
spawn_monitor(F) ->
    erlang:error(badarg, [F]).

A: actually Richard pointed me in the right direction to take to avoid the issue nicelly (in a reply to the same post I  put up on the Erlang GoogleGroups):
http://groups.google.com/group/erlang-programming/browse_thread/thread/1d77a697ec67935a
His answer:
By "using closures", I hope you mean something like this:
Pid = spawn(fun () -> any_function(Any, Number, Of, Arguments) end)
How would that be limiting to your code structure?
 /Richard

thank you for promptly commenting you my question. Much appreciated

A: first, there is no code and we can't help you a lot, so the best way to control your functions and their args with your spawned processes is to spawn the process with a receive function then you will be in contact with your process across the send and receive method, try:
Pid=spawn(Node, ModuleName, functionThatReceive, [])
%%or just spawn(ModuleName....) if the program is not %%distributed
Pid ! {self(), {M1, f1, A1}},
receive
{Pid, Reply} ->Reply
end,

Pid ! {self(), {M2, f2, A2}},
receive
{Pid, Reply} ->Reply
end,
.......
functionThatReceive() ->
receive
{From, {M1, f1, A1}} ->From ! {self(), doSomething1} ;
{From, {M2, f2, A2}} ->From ! {self(), doSomething2}
end.


text:
Q: How do I compare elements between two arrays and then print the equal elements? I'm coding a lottery program, and right now I'm kind of stuck. I let the user pick seven numbers, and at the end I want the program to tell the user which numbers he answered correctly.
I'm having so much trouble understanding arrays that I'm not sure how to store the correctly guessed numbers in an array and then print the elements in the array at the end. I've tried all sorts of variations but nothing is working for me.
package whatevs;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;

public class lottery {

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    int[] userNumbers = new int[7];
    int[] winningNumbers = new int[7];
    int guesses;
    int i;
    int counter = 0;
    int[]correctGuessed=new int[8];
    int x;

    ArrayList<Integer> list = new ArrayList<Integer>();
        for (x=1; x<40; x++) {
            list.add(new Integer(x));
        }
        Collections.shuffle(list);
        for (x=0; x<7;x++) {
           winningNumbers[x] = list.get(x);
        }

    System.out.println("Pick 7 numbers between 1 and 39: ");
    for(i = 0; i < 7; i++){
        guesses = reader.nextInt();
        userNumbers[i] = guesses;
       // System.out.println(userNumbers[i]);
        for(x = 0; x<7;x++){
            if(winningNumbers[x] == userNumbers[i]){
                correctGuessed[x] = userNumbers[i];
                counter+=1;
            }
    }

    if (counter == 7){
        System.out.println("You won!");
    }
    else
        System.out.println("You had " + counter + " numbers correct: " + correctGuessed[x]  );
    }
}

A: I would use Sets instead of arrays. Sets have two advantages over arrays:

*

*they ensure that there is no duplicate in the set (which is what you want, since you have distinct 40 numbers, and want the user to pick 7 distinct numbers)

*they are much higher-level, and thus have many useful methods that bare arrays don't have

So here is the logic you should have:

*

*Fill a list with 40 numbers

*Shuffle it

*Create a HashSet<Integer> and add the first 7 elements of the list. Those are the winning numbers

*Create a new empty Hashset<Integer>

*Ask the user to enter numbers. Add each number to this new HashSet, and keep asking until the set has 7 numbers

*Use the retainAll() method of HashSet to know which of the guessed numbers are also part of the winning numbers. The javadoc is your friend to understand what this method does.

A: Use list.contains(v) to check if wining values are among the guessed one.
Something like this:
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    Integer[] userNumbers = new Integer[7];
    Integer[] winningNumbers = new Integer[7];
    int guesses;
    int i;
    int counter = 0;
    int[] correctGuessed = new int[8];
    int x;

    ArrayList<Integer> list = new ArrayList<Integer>();
    for (x = 1; x < 40; x++) {
        list.add(Integer.valueOf(x));
    }
    Collections.shuffle(list);
    for (x = 0; x < 7; x++) {
        winningNumbers[x] = list.get(x);
    }

    System.out.println("Pick 7 numbers between 1 and 39: ");
    for (i = 0; i < 7; i++) {
        guesses = reader.nextInt();
        userNumbers[i] = guesses;
    }

    List<Integer> winList = Arrays.asList(winningNumbers);
    List<Integer> guessList = Arrays.asList(userNumbers);
    List<Integer> matchList = new ArrayList<Integer>();
    for (Integer guess : guessList) {
        if (winList.contains(guess)) {
            matchList.add(guess);
        }

    }
    counter = matchList.size();

    if (counter == 7) {
        System.out.println("You won!");
    } else {
        System.out.println("You had " + counter + " numbers correct: " + Arrays.toString(matchList.toArray()));
    }
}// main

A: Your code is a little complex but it is almost good to work.
Some remarks :

*

*The object which contains the guessed numbers should not be a array of 7 elements : int[7] because otherwise it contains always 7 elements while the user may found less than 7 numbers. In this case, the other values will be to 0 (default value of int) and it you use Integer[7], it will be to NULL. It is probably not a suitable choice. You should rather declare :
Set<Integer> correctGuessed = new HashSet<Integer>();
instead of int[]correctGuessed=new int[8];

*When a number is guessed, you assign the found number in this way : correctGuessed[x] = userNumbers[i];
You could replace now by this :
correctGuessed.add(userNumbers[i]);

*At the end, you write in the output :
`System.out.println("You had " + counter + " numbers correct: " + correctGuessed[x]  );`

It is not right for two reasons :
 - x has always as value 7 after the loop. So, it is not necessarily the value of the index of the array you have just filled. In your original solution, you should use a break if you want to keep the value of x when the number is guessed :
for(x = 0; x<7;x++){
            if(winningNumbers[x] == userNumbers[i]){
                correctGuessed[x] = userNumbers[i];
                counter+=1;
                break;
            }
    }

*

*you refer "to numbers correct" in the output. So, it seems more logical to display all guessed number :
System.out.println("You had " + counter + " numbers correct: " +  correctGuessed);
The final solution is very near from our one :
public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    int[] userNumbers = new int[7];
    int[] winningNumbers = new int[7];
    int guesses;
    int i;
    int counter = 0;
    Set<Integer> correctGuessed = new HashSet<Integer>();
    int x;

    ArrayList<Integer> list = new ArrayList<Integer>();
    for (x = 1; x < 40; x++) {
        list.add(new Integer(x));
    }
    Collections.shuffle(list);

    for (x = 0; x < 7; x++) {
        winningNumbers[x] = list.get(x);
    }

    System.out.println("Pick 7 numbers between 1 and 39: ");
    for (i = 0; i < 7; i++) {
        guesses = reader.nextInt();
        userNumbers[i] = guesses;
        for (x = 0; x < 7; x++) {
          if (winningNumbers[x] == userNumbers[i]) {
            correctGuessed.add(userNumbers[i]);
            counter += 1;
          }
        }

        if (counter == 7) {
          System.out.println("You won!");
        }
        else
          System.out.println("You had " + counter + " numbers correct: " +  correctGuessed);
        }
      }

A: Your code quickly fixed looks like this:
    System.out.println("Pick 7 numbers between 1 and 39: ");
    for(i = 0; i < 7; i++) {
        guesses = reader.nextInt();
        userNumbers[i] = guesses;
        // System.out.println(userNumbers[i]);
        for (x = 0; x < 7; x++) {
            if (winningNumbers[x] == userNumbers[i]) {
                correctGuessed[counter] = userNumbers[i];
                counter += 1;
            }
        }
    }

        if (counter == 7){
            System.out.println("You won!");
        }
        else
            System.out.println("You had " + counter + " numbers correct: " + Arrays.toString(correctGuessed));

There is however a lot that can be improved, as other users already said. You don't want to use an array to store the winning values, you could use a Set to do that:
    Set<Integer> correctGuesses = new HashSet<>();

    for(i = 0; i < 7; i++) {
        guesses = reader.nextInt();
        userNumbers[i] = guesses;
        for (x = 0; x < 7; x++) {
            if (winningNumbers[x] == userNumbers[i]) {
                correctGuesses.add(userNumbers[i]);
            }
        }
    }

    if (correctGuesses.size() == 7){
            System.out.println("You won!");
    }
    else {
            System.out.println("You had " + correctGuesses.size() + " numbers correct: " + correctGuesses);
    }

I suggest not to use arrays at all, since they might be pretty complex to use. If you use Collection types, you have a lot of handy shorthand methods. Instead of looping over the array with winning numbers to see if the userNumber is in it, you can just use contains(userGuess). You also don't need to save everything. If you don't need to save the numbers the user has guessed, you could just not store them and only work with the current guess. For example:
System.out.println("Pick 7 numbers between 1 and 39: ");
    for(i = 0; i < 7; i++) {
        int currentGuess = reader.nextInt();
        if (winningNumbers.contains(currentGuess)) {
            correctGuesses.add(currentGuess);
        }
    }

But if you want to make sure that the user played distinct numbers in your lottery, you will want to save the users guesses. So you can use a Set again, and add the guess every time the user guesses. You could use a while loop to keep asking for a number until the user has given you 7 unique numbers. Something like this:
while (guessedNumbers.size() < 7){
        int currentGuess = reader.nextInt();
        guessedNumbers.add(currentGuess);
        if (winningNumbers.contains(currentGuess)) {
            correctGuesses.add(currentGuess);
        }
 }

This should give you enough material to go refactor the other code with all the hints of JB Nizet and Alex.
May I mention one extra thing: try to use methods and variables with intention revealing names. You are doing good already, but try to be as specific as possible, if the int contains 1 guess, call it guessedNumber and not guesses. Or if the user has won when the counter is 7, you could introduce a boolean won for example, or an extra method. I must say the code looks pretty good already, considering the fact that you are struggling with arrays.


text:
Q: Smarty dynamic error list Im new to Smarty in combination with PHP and I really like it.
Unfortunatly im running into a problem while validating fields after a $_POST has been done.
I've made an array called $errors and use that to save error messages in, for example: $errors[] .= "Wrong email";.
My problem is in sending the $errors array over to the template so I can use it to display the error messages.
My question: How do you 'transfer' the $errors variable over to the template file so you can use it there with, for example {foreach}. I was planning on doing something like
{if $hasErrors}
    {foreach from=errors item=error}
          <li>{$error}</li>
    {/foreach}
{/if}

Thanks in advance

A: You can assign arrays to your template like you can any other variable.
$smarty->assign('errors', $errors);

Also, when building your array initially, drop the concatenation operator and just use:
$errors[] = 'Wrong email';

Finally, be sure to initialize your array before attempting to add elements to it, or assigning it.
$errors = array()

EDIT: Now that you've included the additional information, I think the problem has to do with your Smarty tag syntax.  Try this line instead, adding a $ to your variable:
{foreach from=$errors item=error}


text:
Q: Why can curved spacetime be locally a Minkowskian spacetime? The gravity field is determined by the metric $\eta_{\mu \nu}$ we impose on a flat (Minkowskian) spacetime, for which the metric has diagonal elements only: $(1,-1,-1,-1)$. Solving the Einstein equation gives you the space- and time components of the metric if a stress-energy tensor $T_{\mu \nu}$ is present. Time variations in the metric represent gravitational waves.
So we can say that the gravity field is a metric field defined on a flat (Minkowskian) spacetime and from this we can calculate what the real (non-Minkowskian) spacetime looks like (if a stress-energy tensor is present). How can we say that locally this curved spacetime is Minkowskian if a Minkowskian metric is only there in Minkowskian spacetime? Isn't it Minkowskian everywhere if it's locally so?
Of course, by looking close enough, you can say the curved spacetime looks flat (like a function can be approximated by a linear function for small values of its argument). If curved spacetime looks flat locally, then why will mass move in curved paths?


text:
Q: angularjs Click to Edit with validation Im having a problem in my forms in validating empty fields. When the user clicked the edit button and clear the input field then click the send button, there is no validation that's happening. I've tried angularjs's form validation but it seems not working. Here's the live view Thanks
http://jsfiddle.net/5DMjt/920/
function ClickToEditCtrl($scope) {
$scope.name = "joe Doe";
$scope.email = "joe@yahoo.com";

$scope.enableEditor = function () {
    $scope.showEditor = true;
    $scope.editName = $scope.name;
    $scope.editEmail = $scope.email;

};

$scope.disableEditor = function () {
    $scope.showEditor = false;
};

$scope.saveEditor = function () {
    $scope.name = $scope.editName;
    $scope.email = $scope.editEmail;

    $scope.disableEditor();
};

}

A: There are multiple issues with your fiddle.
Firstly the scope properties such as studentForm.name.$dirty for ngModelController used in submit is incorrect.
Each of your input should have name properties so that i can be referenced in code under form controller reference.
Secondly for ng-disable it should be button or input not div.
Lastly you can check the form state instead of all input state.
Please check my fiddle:
http://jsfiddle.net/cmyworld/dxzeggtp/


text:
Q: What is the area of the polygon fromed by the points (x,y) which satisfy the inequality: $ |x| + \frac{|y|}{2} \leq 1$ I have an SAT II question that asks: What is the area of the polygon formed by the points (x,y) which satisfy the inequality:
$ |x| + \frac{|y|}{2} \leq 1$
a) 2    b) 3  c) 4   d) 8  e) 10
How would you go about solving this?

A: The shape above will have twice the area of the points that satisfy
$|x|+|y| \le 1$ which is four times the area of the points that satisfy
$x+y \le 1$ and $x,y \ge 0$. The latter is easily seen to be ${ 1\over 2}$
hence the answer is $4$.

A: Hint
Divide your graph into quadrants. In each one, draw the region formed. e.g., in the top right hand quadrant you have the half plane $x+y/2\le1$, in the lower left quadrant you have $-x -y/2 \le 1$ and so on.

A: $$|x| + \frac{|y|}{2} \leq 1$$
This is a taxicab geometry ellipse or, better yet, a rhombus. The coordinates of the vertices are
$(0,\pm 2), (\pm 1, 0)$.
The lengths of its diagonals are $D = 2-(-2) = 4$ and $d=1-(-1) = 2$
Notice that the diagonals break up the rhombus into four congruent right triangles with sides of $\frac 12D$ and $\frac 12d$ and area of $\frac 18dD$.
So the area of the rhombus is $4(\frac 18dD) = \frac 12 dD = 4$


text:
Q: Unsure what this while statement is doing So, I'm doing homework.  I've encountered something I haven't seen before and cannot find a decent explanation of what it does.  Basically,
Object object;
...
while((value1, value2) = function(object)) {
    object.foo(value1, value2);
}

The (value1, value2) in the while statement really throws me.  Any ideas?

A: Its a comma operator.
The result of the comma operator is the last value (the others are evaluated and discarded).
while((value1, value2) = function(object)) {
    object.foo(value1, value2);
}

If value1 is just a variable and not an expression then it is equivalent too:
while(value2 = function(object)) {
    object.foo(value1, value2);
}

If value1 is an expression then it is evaluated each time around the loop. The result is discarded, but if the expression has side effects these will take effect.


text:
Q: Room, how to set 'field's notnull value' is false? I want to add a new column in my database using room. I use Room's migration to migrate my database to a new version, but it doesn't work properly. Default notnull value of a INTERGER field is true, that 's really a trouble for me. Please help me. I has stucked in it for many hours.
I have a Location class.
package com.example.phamf.javamvvmapp.Model;
import ...

@Entity (tableName = "location")
public class Location {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private float x;

    private float y;

    private String name;

    public Location(int id, float x, float y, String name) {
        this.id = id;
        this.x = x;
        this.y = y;
        this.name = name;
    }

    public Location () {

    }

    // Getter and setter
}

I want to add a new field which named type, its type is INTEGER so i modify my Location.java file above like
package com.example.phamf.javamvvmapp.Model;
import ...

@Entity (tableName = "location")
public class Location {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private int type;

    private float x;

    private float y;

    private String name;

    public Location(int id, float x, float y, String name, int type) {
        this.id = id;
        this.x = x;
        this.y = y;
        this.name = name;
        this.type = type;
    }

    public Location () {

    }

    // Getter and setter
}

Here is my RoomDatabase class.
    @Database(entities = {Location.class}, version = 2)
    public abstract class LocationRoomDatabase extends RoomDatabase {

    private static LocationRoomDatabase DATABASE;

    public static LocationRoomDatabase getDatabase (final Context context) {

        Migration migration = new Migration(1, 2) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
                database.execSQL("ALTER TABLE location ADD type INTEGER");
            }
        };

        if (DATABASE == null) {
            DATABASE = Room.databaseBuilder(context, LocationRoomDatabase.class, "database")
                           .addMigrations(migration).build();
    }

        return DATABASE;
    }

    public abstract LocationDAO locationDAO();
}

Problem is when i run the code above, i get an error
//...

Caused by: java.lang.IllegalStateException:
   Migration didn't properly handle location(com.example.phamf.javamvvmapp.Model.Location).
Expected:
     TableInfo{..., type=Column{name='type', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=0}, foreignKeys=[], indices=[]}
Found:
     TableInfo{..., type=Column{name='type', type='INTEGER', affinity='3', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}

//...

The only different thing between Expected TableInfo and Found TableInfo is 'the notNull value'. Expected wants it to be true but Found doesn't. I realized the problems were right there so i modified my Migration code
        Migration migration = new Migration(1, 2) {
            @Override
            public void migrate(@NonNull SupportSQLiteDatabase database) {
                database.execSQL("ALTER TABLE location ADD type INTEGER not null");
            }
        };

I thought it would perfectly ran but then i got an error
Caused by: android.database.sqlite.SQLiteException: Cannot add a NOT NULL column with default value NULL (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE location ADD type INTEGER not null

I also tried adding a default value to 'type' field but it doesn't work too
 private int type = 0;

Any way to solve this problem, please help me. Thank you so much.
Apologize for any error of grammar.

A: I finally found a solution for this. By adding "DEFAULT someValue" after "... ADD COLUMN column_name" in the command of SQL. This make my field have a defaut value that matches with the expected table info.
i.e :
sql.execSQL("ALTER TABLE table_name ADD COLUMN column_name INTEGER DEFAULT 1 not null")