问:
Android, python: MediaRecorder: start failed: -2147483648
The code I am working with, recorderSetup() is only called once

```<code>from jnius import autoclass
.......

def recorderSetup(self):
    if platform == 'android':
        MediaRecorder = autoclass('android.media.MediaRecorder')
        AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
        OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
        AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')

        ParcelFileDescriptor = autoclass('android.os.ParcelFileDescriptor')
        self.fd = ParcelFileDescriptor.createPipe()[1].getFileDescriptor()

        self.mRecorder = MediaRecorder()

        self.mRecorder.setAudioSource(AudioSource.MIC)
        self.mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
        self.mRecorder.setAudioEncoder(AudioEncoder.AMR_NB)
        print(f'Output file descriptor: {self.fd}')
        self.mRecorder.setOutputFile(self.fd)
        try:
            self.mRecorder.prepare()
        except Exception as e:
            print(f'Error preparing MediaRecorder: {e}')
        try:
            self.mRecorder.start()
        except Exception as e:
            print(f'Error starting MediaRecorder: {e}')

        sleep(1)
        try:
            self.mRecorder.stop()
        except Exception as e:
            print(f'Error stopping MediaRecorder: {e}')
        return True
</code>```

Some output from the logs

```<code>python  : Error starting MediaRecorder: JVM exception occurred: start failed. java.lang.RuntimeException
</code>```
```<code>01-02 17:07:42.673 24752 25066 E MediaRecorder: start failed: -2147483648
01-02 17:07:42.673  2032 18974 W StagefrightRecorder: audio source is exist, set interval to audio
01-02 17:07:42.673  2032 18974 D MPEG4Writer: reset()
01-02 17:07:42.673  2032 18974 D MPEG4Writer: Audio track stopping. Stop source
01-02 17:07:42.673  2032 18974 E MPEG4Writer: Stop() called but track is not started or stopped
01-02 17:07:42.673  7614  7614 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1926 android.content.ContextWrapper.startService:834
android.content.ContextWrapper.startService:834 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.a:4 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.onReceive:4
01-02 17:07:42.673 24752 25066 E MediaRecorder: start failed: -2147483648
</code>```
```01-02 17:07:42.538 24752 25066 I python  : Output file descriptor: <java.io.FileDescriptor at 0x70283b2ae0 jclass=java/io/FileDescriptor jself=<LocalRef obj=0xd46a at 0x702839c670>>
01-02 17:07:42.539  2443  7954 D RestrictionPolicy: userId: 0, isMicrophoneEnabledAsUser : true
01-02 17:07:42.539  2443  5040 D RestrictionPolicy: userId: 0 isAudioRecordAllowed : true
01-02 17:07:42.539 24752 25066 I MediaRecorderJNI: setOutputFile
01-02 17:07:42.539 24752 25066 I MediaRecorderJNI: prepare
01-02 17:07:42.542  2443  7954 I EDMNativeHelperService: isMicrophoneEnabled
01-02 17:07:42.543  2443  7954 D RestrictionPolicy: userId: 0, isMicrophoneEnabledAsUser : true
01-02 17:07:42.543  2443  5040 I EDMNativeHelperService: isAudioRecordAllowed
01-02 17:07:42.543  2443  5040 D RestrictionPolicy: userId: 0 isAudioRecordAllowed : true
01-02 17:07:42.543 24752 25066 I MediaRecorder: prepare elapsed time : 4 ms
01-02 17:07:42.544 24752 25066 I MediaRecorderJNI: start
01-02 17:07:42.547  2032 18974 E MPEG4Writer: cannot seek mFd: Illegal seek (29) 8
01-02 17:07:42.547  2032 18974 D MPEG4Writer: release()
01-02 17:07:42.547  2032 18974 D MPEG4Writer: PreAllocation disabled. fallocate : Bad file descriptor, 9
01-02 17:07:42.567  1705 30058 V APM_AudioPolicyManager: getInputForAttr() source 1, sampling rate 8000, format 0x1, channel mask 0x10, session 47337, flags 0 attributes={ Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: AUDIO_SOURCE_MIC Flags: 0x0 Tags:  } requested device ID 0
01-02 17:07:42.568  2443  5040 I EDMNativeHelperService: isMicrophoneEnabled
01-02 17:07:42.568  2443  5040 D RestrictionPolicy: userId: 0, isMicrophoneEnabledAsUser : true
01-02 17:07:42.568  2443  5040 I EDMNativeHelperService: isAudioRecordAllowed
01-02 17:07:42.568  2443  5040 D RestrictionPolicy: userId: 0 isAudioRecordAllowed : true
01-02 17:07:42.571  1705 30058 V APM_AudioPolicyManager: getInputForAttr found device type is 0x80000004
01-02 17:07:42.575  1705 30058 I MultiRecordManager: openMultiRecordAllowed() skipMultiRecord 1, openMultiRecordAllowed 0, moduleName primary, source 1, flag 0
01-02 17:07:42.575  1705 30058 I MultiRecordManager: openInputStream() skipMultiRecord
01-02 17:07:42.583  1600 20089 D AHAL: AudioDevice: adev_open_input_stream: 956: enter: sample_rate(8000) channel_mask(0x10) devices(0x80000004)        io_handle(1982) source(1) format 1
01-02 17:07:42.584  1600 20089 D AHAL: AudioStream: StreamPrimary: 5737: handle: 1982 channel_mask: 16
01-02 17:07:42.584  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5526: enter: handle (7be) format(0x1) sample_rate(8000) channel_mask(0x10) devices(1) flags(0)
01-02 17:07:42.585  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5623: local : handle (7be) format(0x1) sample_rate(8000) channel_mask(0x10) devices(0x80000004) flags(0)
01-02 17:07:42.585  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5632: No of devices 1
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: GetPalDeviceIds: 2465: haldeviceIds: 1
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: GetPalDeviceIds: 2472: Found haldeviceId: 80000004 and PAL Device ID 24
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: GetPalDeviceIds: 2491: devices allocated 1, pal device ids before returning 1
01-02 17:07:42.585  1600 20089 I AHAL: AudioStream: GetInputUseCase: 5232: usecase(21: audio-record)
01-02 17:07:42.585  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5700: Exit
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: CreateStreamIn: 649: input stream 1 0x7466c57bb8
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: adev_open_input_stream: 1014: Exit ret: 0
01-02 17:07:42.586  1600 20089 D AHAL: AudioStream: in_update_sink_metadata_v7: 1464: in_update_sink_metadata_v7: sink device 0
01-02 17:07:42.594  1600 20089 V sec_audio_hw: sec_dev_open_audio_stream: enter: handle 1982, type 1, tag
01-02 17:07:42.594  1600 20089 V sec_audio_hw: sec_dev_open_audio_stream: exit
01-02 17:07:42.604  1705 30058 I AudioEffectStage: StageAttribute name input_normal_input_voice_changer, io 2, mixerType 3, openDevice 0, threadFlags 0
01-02 17:07:42.604  1705 30058 I AudioEffectStage:     format 0, sample -1, streamMask 0,InChannelMask ffffffff, OutChannelMask ffffffff, usage 0, content 0
01-02 17:07:42.606   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio.effect@7.1::IEffectsFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.607   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio@7.1::IDevicesFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.621   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio.effect@7.1::IEffectsFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.622   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio@7.1::IDevicesFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.624  1705 30058 I EffectsFactory: EffectCreate() create_effect
01-02 17:07:42.626  1705 25109 I AudioFlinger: AudioFlinger's thread 0xb4000073f2e0cb70 tid=25109 ready to run
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: astream_in_standby: 1659: enter: stream (0xb40000758406e790) usecase(21: audio-record)
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: Standby: 4466: Enter
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: Standby: 4496: Exit ret: 0
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: astream_in_standby: 1668: Exit ret: 0
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: astream_in_standby: 1659: enter: stream (0xb40000758406e790) usecase(21: audio-record)
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: Standby: 4466: Enter
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: Standby: 4496: Exit ret: 0
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: astream_in_standby: 1668: Exit ret: 0
01-02 17:07:42.633  1705 30058 V APM_AudioPolicyManager: getInputForAttr() returns input 1982 type 0 selectedDeviceId 23 for port ID 9341
01-02 17:07:42.634  1705 12993 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 0 ports 0xb40000710f9ecf10
01-02 17:07:42.634  1705 12993 V APM_AudioPolicyManager: listAudioPorts() got 0 ports needed 17
01-02 17:07:42.635  1705 25232 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 0 ports 0xb40000710f9ef850
01-02 17:07:42.635  1705 25232 V APM_AudioPolicyManager: listAudioPorts() got 0 ports needed 17
01-02 17:07:42.635  1705 12993 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 17 ports 0xb40000733fc9e100
01-02 17:07:42.635  1705 12993 V APM_AudioPolicyManager: listAudioPorts() got 17 ports needed 17
01-02 17:07:42.636  1705 25232 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 17 ports 0xb40000733fb1e080
01-02 17:07:42.636  1705 25232 V APM_AudioPolicyManager: listAudioPorts() got 17 ports needed 17
01-02 17:07:42.638  2032 18974 W AudioRecord: createRecord_l(9341): Server adjusted notificationFrames from 1024 to 160 for frameCount 2048
01-02 17:07:42.640  1705 12993 W AudioFlinger: acquireAudioSessionId() unknown client 24752 for session 47337
01-02 17:07:42.642  2032 18974 D MediaCodecList: codecHandlesFormat: no format, so no extra checks
01-02 17:07:42.642  2032 18974 D MediaCodecList: codecHandlesFormat: no format, so no extra checks
01-02 17:07:42.643  2032 25110 I CCodec  : state->set(ALLOCATING)
01-02 17:07:42.643  2032 25110 I CCodec  : allocate(c2.android.amrnb.encoder)
01-02 17:07:42.645  2032 25110 I CCodec  : setting up 'default' as default (vendor) store
01-02 17:07:42.646  2090 20145 V C2Store : in init
01-02 17:07:42.646  2090 20145 V C2Store : loading dll
01-02 17:07:42.650  2032 25110 I CCodec  : Created component [c2.android.amrnb.encoder]
01-02 17:07:42.650  2032 25110 I CCodec  : state->set(ALLOCATED)
01-02 17:07:42.650  2032 25110 D CCodecConfig: read media type: audio/3gpp
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.max-count.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: output.subscribed-indices.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: input.buffers.allocator-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: output.buffers.allocator-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.allocator-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: output.buffers.pool-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.pool-ids.values
01-02 17:07:42.655  2032 25110 I CCodecConfig: query failed after returning 7 values (BAD_INDEX)
01-02 17:07:42.656  2032 25110 D CCodecConfig: c2 config diff is Dict {
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 coded.bitrate.value = 4750
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 input.buffers.max-size.value = 8192
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 input.delay.value = 0
01-02 17:07:42.656  2032 25110 D CCodecConfig:   string input.media-type.value = "audio/raw"
01-02 17:07:42.656  2032 25110 D CCodecConfig:   string output.media-type.value = "audio/3gpp"
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 raw.channel-count.value = 1
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 raw.sample-rate.value = 8000
01-02 17:07:42.656  2032 25110 D CCodecConfig: }
01-02 17:07:42.657  2032 18974 D MediaCodec: shapeMediaFormat: deltas(0): AMessage(what = 0x00000000) = {
01-02 17:07:42.657  2032 18974 D MediaCodec:   }
01-02 17:07:42.658  2032 25110 D CCodec  : [c2.android.amrnb.encoder] buffers are bound to CCodec for this session
01-02 17:07:42.658  2032 25110 I CCodec  : appPid(2032) width(0) height(0)
01-02 17:07:42.658  2032 25110 D CCodecConfig: no c2 equivalents for file-type
01-02 17:07:42.658  2032 25110 D CCodecConfig: no c2 equivalents for flags
01-02 17:07:42.658  2032 25110 D CCodecConfig: no c2 equivalents for encoder
01-02 17:07:42.659  2032 25110 D CCodecConfig: config failed => CORRUPTED
01-02 17:07:42.659  2032 25110 D CCodecConfig: c2 config diff is   c2::u32 coded.bitrate.value = 12200
01-02 17:07:42.660  2032 25110 W Codec2Client: query -- param skipped: index = 1107298332.
01-02 17:07:42.660  2032 25110 D CCodec  : client requested max input size 2048, which is smaller than what component recommended (8192); overriding with component recommendation.
01-02 17:07:42.660  2032 25110 W CCodec  : This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range.
01-02 17:07:42.660  2032 25110 D CCodec  : Setting encoder options for disabling wrapping
01-02 17:07:42.660  2032 25110 D CCodec  : encoding statistics level = 0
01-02 17:07:42.660  2032 25110 D CCodec  : setup formats input: AMessage(what = 0x00000000) = {
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t channel-count = 1
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t max-input-size = 8192
01-02 17:07:42.660  2032 25110 D CCodec  :   string mime = "audio/raw"
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t sample-rate = 8000
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t android._config-pcm-encoding = 2
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t bytebuffer-wrapping-disable = 1
01-02 17:07:42.660  2032 25110 D CCodec  : }
01-02 17:07:42.660  2032 25110 D CCodec  : setup formats output: AMessage(what = 0x00000000) = {
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t bitrate = 12200
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t channel-count = 1
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t max-bitrate = 12200
01-02 17:07:42.660  2032 25110 D CCodec  :   string mime = "audio/3gpp"
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t sample-rate = 8000
01-02 17:07:42.660  2032 25110 D CCodec  : }
01-02 17:07:42.660  2032 25110 I CCodecConfig: query failed after returning 7 values (BAD_INDEX)
01-02 17:07:42.661   922  1144 I servicemanager: Found vendor.samsung.frameworks.codecsolution.ISehCodecSolution/default in framework VINTF manifest.
01-02 17:07:42.662  2443  7971 D SehCodecSolutionService: updateMediaStatisticsData: (action=1@1986621044;category=3@1986621044;label=1634951534@1986621044)
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: MediaStatisticsData: action=1@1986621044;category=3@1986621044;label=1634951534@1986621044
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: Category.valueOf: 3
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: Action.valueOf: 1
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: Label.valueOf: 0x6173616e
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: category: AENC
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: action: INSTANTIATE
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: label: ANDROID_SW_AMRNB
01-02 17:07:42.662  2443  2443 D SehCodecSolutionService: handleMessage : 900
01-02 17:07:42.662  2032 25110 I MediaCodec: MediaCodec will operate in async mode
01-02 17:07:42.663  2032 18974 D MediaCodec: keep callback message for reclaim
01-02 17:07:42.663  2032 25110 I CCodec  : state->set(STARTING)
01-02 17:07:42.664  2443  2443 D SehCodecSolutionService: event : AENC
01-02 17:07:42.664  2443  2443 D CodecSolution_Logging: dma : true, feature: AENC, extra: ANDROID_SW_AMRNB, value: -1
01-02 17:07:42.664  2443  2443 D CodecSolution_Logging: insert diagmon log
01-02 17:07:42.664  2443  2443 D CodecSolution_Logging: permission granted
01-02 17:07:42.664  2443  2443 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1252 vendor.samsung.frameworks.codecsolution.Logging
.insertDiagmonLog:78 vendor.samsung.frameworks.codecsolution.Logging.insertLog:54 vendor.samsung.frameworks.codecsolution.Logging.insertLog:46 vendor.samsung.frameworks.codecsolution.SehCodecSolutionSe
rvice$1.handleMessage:210
01-02 17:07:42.665  2032 25110 W Codec2Client: query -- param skipped: index = 1342179345.
01-02 17:07:42.665  2032 25110 W Codec2Client: query -- param skipped: index = 2415921170.
01-02 17:07:42.666  2032 25110 W Codec2Client: query -- param skipped: index = 3254792206.
01-02 17:07:42.666  2032 25110 W Codec2Client: query -- param skipped: index = 3254792194.
01-02 17:07:42.667  2032 25110 D CCodecBufferChannel: [c2.android.amrnb.encoder#516] Created input block pool with allocatorID 16 => poolID 1680 - OK (0)
01-02 17:07:42.667  2090 20145 D BufferPoolAccessor2.0: bufferpool2 0xb400007209bdb8a8 : 0(0 size) total buffers - 0(0 size) used buffers - 119/123 (recycle/alloc) - 4/122 (fetch/transfer)
01-02 17:07:42.667  2090 20145 D BufferPoolAccessor2.0: Destruction - bufferpool2 0xb400007209bdb8a8 cached: 0/0M, 0/0% in use; allocs: 123, 97% recycled; transfers: 122, 97% unfetched
01-02 17:07:42.668  2032 13242 D BufferPoolAccessor2.0: bufferpool2 0xecc083c8 : 0(0 size) total buffers - 0(0 size) used buffers - 120/128 (recycle/alloc) - 8/250 (fetch/transfer)
01-02 17:07:42.668  2032 13242 D BufferPoolAccessor2.0: Destruction - bufferpool2 0xecc083c8 cached: 0/0M, 0/0% in use; allocs: 128, 94% recycled; transfers: 250, 97% unfetched
01-02 17:07:42.668  2032 25110 I CCodecBufferChannel: [c2.android.amrnb.encoder#516] Created output block pool with allocatorID 16 => poolID 965 - OK
01-02 17:07:42.669  2032 25110 D CCodecBufferChannel: [c2.android.amrnb.encoder#516] Configured output block pool ids 965 => OK
01-02 17:07:42.669  2032 25110 I CCodec  : state->set(RUNNING)
01-02 17:07:42.669  1654  1654 I QC2CompStore: Setting heap usage to system
01-02 17:07:42.669 22974 22974 I Finsky:background: [2] qaa.onTrimMemory(1): Memory trim requested to level 80
01-02 17:07:42.669 23558 23558 I Finsky  : [2] qaa.onTrimMemory(1): Memory trim requested to level 60
01-02 17:07:42.669 23558 23558 I Finsky  : [2] jyn.accept(12): Flushing in-memory image cache
01-02 17:07:42.670 22801 22801 I Finsky  : [2] qaa.onTrimMemory(1): Memory trim requested to level 40
01-02 17:07:42.672  2032 25110 I CCodecBufferChannel: [c2.android.amrnb.encoder#516] 4 initial input buffers available
01-02 17:07:42.672 22801 22801 I Finsky  : [2] jyn.accept(12): Flushing in-memory image cache
01-02 17:07:42.672  2090 25111 D SimpleC2Component: Using output block pool with poolID 965 => got 965 - 0
01-02 17:07:42.672  1654  1654 I QC2CompStore: Setting heap usage to system
01-02 17:07:42.673  2032 18974 W StagefrightRecorder: audio source is exist, set interval to audio
01-02 17:07:42.673  2032 18974 D MPEG4Writer: reset()
01-02 17:07:42.673  2032 18974 D MPEG4Writer: Audio track stopping. Stop source
01-02 17:07:42.673  2032 18974 E MPEG4Writer: Stop() called but track is not started or stopped
01-02 17:07:42.673  7614  7614 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1926 android.content.ContextWrapper.startService:834
android.content.ContextWrapper.startService:834 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.a:4 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.onReceive:4
01-02 17:07:42.675 24752 25066 I python  : Error starting MediaRecorder: JVM exception occurred: start failed. java.lang.RuntimeException
01-02 17:07:42.707  1716  1716 D SurfaceFlinger: Display 4630947232161729154 HWC layers:
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb4000074423464b0 | 0102 | RGBA_8888    |    0.0    0.0 1080.0 2106.0 |    0   75 1080 2181 | SurfaceView[org.test.myapp/org.kivy.android
.PythonActivity]@0(BLAST)#59317
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb400007442347110 | 0100 | RGBA_8888    |    0.0    0.0 1080.0 2316.0 |    0    0 1080 2316 | org.test.myapp/org.kivy.android.PythonActivity$_24752#59310
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb400007442338290 | 0100 | RGBA_8888    |    0.0    0.0 1080.0   75.0 |    0    0 1080   75 | StatusBar$_4129#95
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb40000744232da60 | 0100 | RGBA_8888    |    0.0    0.0   67.0  342.0 | 1013  309 1080  651 | com.samsung.android.app.cocktailbars[...]rv
ice.CocktailBarService$_8507#59266
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb4000074423480d0 | 0100 | RGBA_8888    |    0.0    0.0 1080.0  135.0 |    0 2181 1080 2316 | NavigationBar0$_4129#90
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:
01-02 17:07:42.738  2443  2586 I GestureDetector: handleMessage TAP
01-02 17:07:42.739  2443  2443 I GestureDetector: handleMessage TAP
01-02 17:07:42.830  7817  7817 I ResourceOverlayService_0: waitAndQuit called
01-02 17:07:42.831  7817  7817 I ResourceOverlayService_0: activity user id 0 process id 0
01-02 17:07:43.167  2443  5599 D SemWifiUsabilityStatsMonitor: onWifiUsabilityStats - seqNum 35415, isSameBssidAndFreq true
01-02 17:07:43.168  2443  3958 D ConnectivityService: notifyType CALLBACK_CAP_CHANGED for [196 WIFI]
01-02 17:07:43.169  2443  4015 I SemWifiLinkQualityMonitor: Link Qos Query: 0.060 ms / 132.980 Mbps (260 / 0.011 / 1.452)
01-02 17:07:43.185  2443  3992 I WifiConnectivityMonitor.NCC: sNetworkCallback(oCC) FULL : 196(true/false)[ Transports: WIFI Capabilities: NOT_METERED&INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&VALIDATED&
NOT_ROAMING&FOREGROUND&NOT_CONGESTED&NOT_SUSPENDED&NOT_VCN_MANAGED LinkUpBandwidth>=31256Kbps LinkDnBandwidth>=45171Kbps TransportInfo: <SSID: <unknown ssid>, BSSID: 02:00:00:**:**:00, MAC: 02:00:00:**
:**:00, IP: /192.168.1.85, Security type: 2, Supplicant state: COMPLETED, Wi-Fi standard: 5, RSSI: -52,

```
<p>full code (looks weird because of debugging)</p>
```import kivy
import numpy as np
kivy.require('2.1.0')

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.audio import SoundLoader
from kivy.utils import platform
from jnius import autoclass
from time import sleep

class MyApp(App):
    def __init__(self):
        super(MyApp, self).__init__()
        self.mRecorder = None
        self.recording = False

    def build(self):
        layout = BoxLayout(orientation='vertical')
        self.label = Label(text='Press the button to start noise detection')
        layout.add_widget(self.label)
        self.button = Button(text='Start/stop recording')
        self.button.bind(on_press=self.start_stop_recording)
        layout.add_widget(self.button)
        return layout

    def on_start(self, **kwargs):
        if platform == 'android':
            from android.permissions import request_permissions, Permission
            request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.RECORD_AUDIO])

    def recorderSetup(self):
        if platform == 'android':
            MediaRecorder = autoclass('android.media.MediaRecorder')
            AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
            OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
            AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')

            ParcelFileDescriptor = autoclass('android.os.ParcelFileDescriptor')
            self.fd = ParcelFileDescriptor.createPipe()[1].getFileDescriptor()

            self.mRecorder = MediaRecorder()

            self.mRecorder.setAudioSource(AudioSource.MIC)
            self.mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
            self.mRecorder.setAudioEncoder(AudioEncoder.AMR_NB)
            print(f'Output file descriptor: {self.fd}')
            self.mRecorder.setOutputFile(self.fd)
            try:
                self.mRecorder.prepare()
            except Exception as e:
                print(f'Error preparing MediaRecorder: {e}')
            try:
                self.mRecorder.start()
            except Exception as e:
                print(f'Error starting MediaRecorder: {e}')

            sleep(1)
            try:
                self.mRecorder.stop()
            except Exception as e:
                print(f'Error stopping MediaRecorder: {e}')
            return True
        return False

    def start_stop_recording(self, instance):
        if self.recording:
            self.stop_record_loop()
        else:
            self.start_detect_loop()

    def start_detect_loop(self):
        self.label.text = 'Noise detection in progress...'
        self.recording = True
        self.recorderSetup()

        return
```
<p>snippet from builddozer.spec (it fails to build if I add the write permission here</p>
```# (list) Permissions
android.permissions = READ_EXTERNAL_STORAGE,RECORD_AUDIO
```

So I am trying to record audio but not into a file. Instead I just need it in memory so I can do some calculations on it with numpy.

I've tried using a buffer, java output stream, and neither worked. The current method I have is based on this Using MediaRecorder to write to a buffer or FIFO which apparently works for them.

I am running this on an updated S22 ultra

Body:
The code I am working with, recorderSetup() is only called once

from jnius import autoclass
.......

def recorderSetup(self):
    if platform == 'android':
        MediaRecorder = autoclass('android.media.MediaRecorder')
        AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
        OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
        AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')

        ParcelFileDescriptor = autoclass('android.os.ParcelFileDescriptor')
        self.fd = ParcelFileDescriptor.createPipe()[1].getFileDescriptor()

        self.mRecorder = MediaRecorder()

        self.mRecorder.setAudioSource(AudioSource.MIC)
        self.mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
        self.mRecorder.setAudioEncoder(AudioEncoder.AMR_NB)
        print(f'Output file descriptor: {self.fd}')
        self.mRecorder.setOutputFile(self.fd)
        try:
            self.mRecorder.prepare()
        except Exception as e:
            print(f'Error preparing MediaRecorder: {e}')
        try:
            self.mRecorder.start()
        except Exception as e:
            print(f'Error starting MediaRecorder: {e}')

        sleep(1)
        try:
            self.mRecorder.stop()
        except Exception as e:
            print(f'Error stopping MediaRecorder: {e}')
        return True

Some output from the logs

python  : Error starting MediaRecorder: JVM exception occurred: start failed. java.lang.RuntimeException

01-02 17:07:42.673 24752 25066 E MediaRecorder: start failed: -2147483648
01-02 17:07:42.673  2032 18974 W StagefrightRecorder: audio source is exist, set interval to audio
01-02 17:07:42.673  2032 18974 D MPEG4Writer: reset()
01-02 17:07:42.673  2032 18974 D MPEG4Writer: Audio track stopping. Stop source
01-02 17:07:42.673  2032 18974 E MPEG4Writer: Stop() called but track is not started or stopped
01-02 17:07:42.673  7614  7614 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1926 android.content.ContextWrapper.startService:834
android.content.ContextWrapper.startService:834 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.a:4 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.onReceive:4
01-02 17:07:42.673 24752 25066 E MediaRecorder: start failed: -2147483648

01-02 17:07:42.538 24752 25066 I python  : Output file descriptor: <java.io.FileDescriptor at 0x70283b2ae0 jclass=java/io/FileDescriptor jself=<LocalRef obj=0xd46a at 0x702839c670>>
01-02 17:07:42.539  2443  7954 D RestrictionPolicy: userId: 0, isMicrophoneEnabledAsUser : true
01-02 17:07:42.539  2443  5040 D RestrictionPolicy: userId: 0 isAudioRecordAllowed : true
01-02 17:07:42.539 24752 25066 I MediaRecorderJNI: setOutputFile
01-02 17:07:42.539 24752 25066 I MediaRecorderJNI: prepare
01-02 17:07:42.542  2443  7954 I EDMNativeHelperService: isMicrophoneEnabled
01-02 17:07:42.543  2443  7954 D RestrictionPolicy: userId: 0, isMicrophoneEnabledAsUser : true
01-02 17:07:42.543  2443  5040 I EDMNativeHelperService: isAudioRecordAllowed
01-02 17:07:42.543  2443  5040 D RestrictionPolicy: userId: 0 isAudioRecordAllowed : true
01-02 17:07:42.543 24752 25066 I MediaRecorder: prepare elapsed time : 4 ms
01-02 17:07:42.544 24752 25066 I MediaRecorderJNI: start
01-02 17:07:42.547  2032 18974 E MPEG4Writer: cannot seek mFd: Illegal seek (29) 8
01-02 17:07:42.547  2032 18974 D MPEG4Writer: release()
01-02 17:07:42.547  2032 18974 D MPEG4Writer: PreAllocation disabled. fallocate : Bad file descriptor, 9
01-02 17:07:42.567  1705 30058 V APM_AudioPolicyManager: getInputForAttr() source 1, sampling rate 8000, format 0x1, channel mask 0x10, session 47337, flags 0 attributes={ Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: AUDIO_SOURCE_MIC Flags: 0x0 Tags:  } requested device ID 0
01-02 17:07:42.568  2443  5040 I EDMNativeHelperService: isMicrophoneEnabled
01-02 17:07:42.568  2443  5040 D RestrictionPolicy: userId: 0, isMicrophoneEnabledAsUser : true
01-02 17:07:42.568  2443  5040 I EDMNativeHelperService: isAudioRecordAllowed
01-02 17:07:42.568  2443  5040 D RestrictionPolicy: userId: 0 isAudioRecordAllowed : true
01-02 17:07:42.571  1705 30058 V APM_AudioPolicyManager: getInputForAttr found device type is 0x80000004
01-02 17:07:42.575  1705 30058 I MultiRecordManager: openMultiRecordAllowed() skipMultiRecord 1, openMultiRecordAllowed 0, moduleName primary, source 1, flag 0
01-02 17:07:42.575  1705 30058 I MultiRecordManager: openInputStream() skipMultiRecord
01-02 17:07:42.583  1600 20089 D AHAL: AudioDevice: adev_open_input_stream: 956: enter: sample_rate(8000) channel_mask(0x10) devices(0x80000004)        io_handle(1982) source(1) format 1
01-02 17:07:42.584  1600 20089 D AHAL: AudioStream: StreamPrimary: 5737: handle: 1982 channel_mask: 16
01-02 17:07:42.584  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5526: enter: handle (7be) format(0x1) sample_rate(8000) channel_mask(0x10) devices(1) flags(0)
01-02 17:07:42.585  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5623: local : handle (7be) format(0x1) sample_rate(8000) channel_mask(0x10) devices(0x80000004) flags(0)
01-02 17:07:42.585  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5632: No of devices 1
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: GetPalDeviceIds: 2465: haldeviceIds: 1
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: GetPalDeviceIds: 2472: Found haldeviceId: 80000004 and PAL Device ID 24
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: GetPalDeviceIds: 2491: devices allocated 1, pal device ids before returning 1
01-02 17:07:42.585  1600 20089 I AHAL: AudioStream: GetInputUseCase: 5232: usecase(21: audio-record)
01-02 17:07:42.585  1600 20089 D AHAL: AudioStream: StreamInPrimary: 5700: Exit
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: CreateStreamIn: 649: input stream 1 0x7466c57bb8
01-02 17:07:42.585  1600 20089 D AHAL: AudioDevice: adev_open_input_stream: 1014: Exit ret: 0
01-02 17:07:42.586  1600 20089 D AHAL: AudioStream: in_update_sink_metadata_v7: 1464: in_update_sink_metadata_v7: sink device 0
01-02 17:07:42.594  1600 20089 V sec_audio_hw: sec_dev_open_audio_stream: enter: handle 1982, type 1, tag
01-02 17:07:42.594  1600 20089 V sec_audio_hw: sec_dev_open_audio_stream: exit
01-02 17:07:42.604  1705 30058 I AudioEffectStage: StageAttribute name input_normal_input_voice_changer, io 2, mixerType 3, openDevice 0, threadFlags 0
01-02 17:07:42.604  1705 30058 I AudioEffectStage:     format 0, sample -1, streamMask 0,InChannelMask ffffffff, OutChannelMask ffffffff, usage 0, content 0
01-02 17:07:42.606   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio.effect@7.1::IEffectsFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.607   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio@7.1::IDevicesFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.621   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio.effect@7.1::IEffectsFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.622   923   923 I hwservicemanager: getTransport: Cannot find entry android.hardware.audio@7.1::IDevicesFactory/default in either framework or device VINTF manifest.
01-02 17:07:42.624  1705 30058 I EffectsFactory: EffectCreate() create_effect
01-02 17:07:42.626  1705 25109 I AudioFlinger: AudioFlinger's thread 0xb4000073f2e0cb70 tid=25109 ready to run
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: astream_in_standby: 1659: enter: stream (0xb40000758406e790) usecase(21: audio-record)
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: Standby: 4466: Enter
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: Standby: 4496: Exit ret: 0
01-02 17:07:42.627  1600 20089 D AHAL: AudioStream: astream_in_standby: 1668: Exit ret: 0
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: astream_in_standby: 1659: enter: stream (0xb40000758406e790) usecase(21: audio-record)
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: Standby: 4466: Enter
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: Standby: 4496: Exit ret: 0
01-02 17:07:42.631  1600 20089 D AHAL: AudioStream: astream_in_standby: 1668: Exit ret: 0
01-02 17:07:42.633  1705 30058 V APM_AudioPolicyManager: getInputForAttr() returns input 1982 type 0 selectedDeviceId 23 for port ID 9341
01-02 17:07:42.634  1705 12993 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 0 ports 0xb40000710f9ecf10
01-02 17:07:42.634  1705 12993 V APM_AudioPolicyManager: listAudioPorts() got 0 ports needed 17
01-02 17:07:42.635  1705 25232 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 0 ports 0xb40000710f9ef850
01-02 17:07:42.635  1705 25232 V APM_AudioPolicyManager: listAudioPorts() got 0 ports needed 17
01-02 17:07:42.635  1705 12993 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 17 ports 0xb40000733fc9e100
01-02 17:07:42.635  1705 12993 V APM_AudioPolicyManager: listAudioPorts() got 17 ports needed 17
01-02 17:07:42.636  1705 25232 V APM_AudioPolicyManager: listAudioPorts() role 0 type 0 num_ports 17 ports 0xb40000733fb1e080
01-02 17:07:42.636  1705 25232 V APM_AudioPolicyManager: listAudioPorts() got 17 ports needed 17
01-02 17:07:42.638  2032 18974 W AudioRecord: createRecord_l(9341): Server adjusted notificationFrames from 1024 to 160 for frameCount 2048
01-02 17:07:42.640  1705 12993 W AudioFlinger: acquireAudioSessionId() unknown client 24752 for session 47337
01-02 17:07:42.642  2032 18974 D MediaCodecList: codecHandlesFormat: no format, so no extra checks
01-02 17:07:42.642  2032 18974 D MediaCodecList: codecHandlesFormat: no format, so no extra checks
01-02 17:07:42.643  2032 25110 I CCodec  : state->set(ALLOCATING)
01-02 17:07:42.643  2032 25110 I CCodec  : allocate(c2.android.amrnb.encoder)
01-02 17:07:42.645  2032 25110 I CCodec  : setting up 'default' as default (vendor) store
01-02 17:07:42.646  2090 20145 V C2Store : in init
01-02 17:07:42.646  2090 20145 V C2Store : loading dll
01-02 17:07:42.650  2032 25110 I CCodec  : Created component [c2.android.amrnb.encoder]
01-02 17:07:42.650  2032 25110 I CCodec  : state->set(ALLOCATED)
01-02 17:07:42.650  2032 25110 D CCodecConfig: read media type: audio/3gpp
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.max-count.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: output.subscribed-indices.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: input.buffers.allocator-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: output.buffers.allocator-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.allocator-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: output.buffers.pool-ids.values
01-02 17:07:42.652  2032 25110 D ReflectedParamUpdater: extent() != 1 for single value type: algo.buffers.pool-ids.values
01-02 17:07:42.655  2032 25110 I CCodecConfig: query failed after returning 7 values (BAD_INDEX)
01-02 17:07:42.656  2032 25110 D CCodecConfig: c2 config diff is Dict {
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 coded.bitrate.value = 4750
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 input.buffers.max-size.value = 8192
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 input.delay.value = 0
01-02 17:07:42.656  2032 25110 D CCodecConfig:   string input.media-type.value = "audio/raw"
01-02 17:07:42.656  2032 25110 D CCodecConfig:   string output.media-type.value = "audio/3gpp"
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 raw.channel-count.value = 1
01-02 17:07:42.656  2032 25110 D CCodecConfig:   c2::u32 raw.sample-rate.value = 8000
01-02 17:07:42.656  2032 25110 D CCodecConfig: }
01-02 17:07:42.657  2032 18974 D MediaCodec: shapeMediaFormat: deltas(0): AMessage(what = 0x00000000) = {
01-02 17:07:42.657  2032 18974 D MediaCodec:   }
01-02 17:07:42.658  2032 25110 D CCodec  : [c2.android.amrnb.encoder] buffers are bound to CCodec for this session
01-02 17:07:42.658  2032 25110 I CCodec  : appPid(2032) width(0) height(0)
01-02 17:07:42.658  2032 25110 D CCodecConfig: no c2 equivalents for file-type
01-02 17:07:42.658  2032 25110 D CCodecConfig: no c2 equivalents for flags
01-02 17:07:42.658  2032 25110 D CCodecConfig: no c2 equivalents for encoder
01-02 17:07:42.659  2032 25110 D CCodecConfig: config failed => CORRUPTED
01-02 17:07:42.659  2032 25110 D CCodecConfig: c2 config diff is   c2::u32 coded.bitrate.value = 12200
01-02 17:07:42.660  2032 25110 W Codec2Client: query -- param skipped: index = 1107298332.
01-02 17:07:42.660  2032 25110 D CCodec  : client requested max input size 2048, which is smaller than what component recommended (8192); overriding with component recommendation.
01-02 17:07:42.660  2032 25110 W CCodec  : This behavior is subject to change. It is recommended that app developers double check whether the requested max input size is in reasonable range.
01-02 17:07:42.660  2032 25110 D CCodec  : Setting encoder options for disabling wrapping
01-02 17:07:42.660  2032 25110 D CCodec  : encoding statistics level = 0
01-02 17:07:42.660  2032 25110 D CCodec  : setup formats input: AMessage(what = 0x00000000) = {
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t channel-count = 1
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t max-input-size = 8192
01-02 17:07:42.660  2032 25110 D CCodec  :   string mime = "audio/raw"
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t sample-rate = 8000
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t android._config-pcm-encoding = 2
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t bytebuffer-wrapping-disable = 1
01-02 17:07:42.660  2032 25110 D CCodec  : }
01-02 17:07:42.660  2032 25110 D CCodec  : setup formats output: AMessage(what = 0x00000000) = {
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t bitrate = 12200
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t channel-count = 1
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t max-bitrate = 12200
01-02 17:07:42.660  2032 25110 D CCodec  :   string mime = "audio/3gpp"
01-02 17:07:42.660  2032 25110 D CCodec  :   int32_t sample-rate = 8000
01-02 17:07:42.660  2032 25110 D CCodec  : }
01-02 17:07:42.660  2032 25110 I CCodecConfig: query failed after returning 7 values (BAD_INDEX)
01-02 17:07:42.661   922  1144 I servicemanager: Found vendor.samsung.frameworks.codecsolution.ISehCodecSolution/default in framework VINTF manifest.
01-02 17:07:42.662  2443  7971 D SehCodecSolutionService: updateMediaStatisticsData: (action=1@1986621044;category=3@1986621044;label=1634951534@1986621044)
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: MediaStatisticsData: action=1@1986621044;category=3@1986621044;label=1634951534@1986621044
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: Category.valueOf: 3
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: Action.valueOf: 1
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: Label.valueOf: 0x6173616e
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: category: AENC
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: action: INSTANTIATE
01-02 17:07:42.662  2443  7971 D CodecSolution_MediaStatisticsData: label: ANDROID_SW_AMRNB
01-02 17:07:42.662  2443  2443 D SehCodecSolutionService: handleMessage : 900
01-02 17:07:42.662  2032 25110 I MediaCodec: MediaCodec will operate in async mode
01-02 17:07:42.663  2032 18974 D MediaCodec: keep callback message for reclaim
01-02 17:07:42.663  2032 25110 I CCodec  : state->set(STARTING)
01-02 17:07:42.664  2443  2443 D SehCodecSolutionService: event : AENC
01-02 17:07:42.664  2443  2443 D CodecSolution_Logging: dma : true, feature: AENC, extra: ANDROID_SW_AMRNB, value: -1
01-02 17:07:42.664  2443  2443 D CodecSolution_Logging: insert diagmon log
01-02 17:07:42.664  2443  2443 D CodecSolution_Logging: permission granted
01-02 17:07:42.664  2443  2443 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1252 vendor.samsung.frameworks.codecsolution.Logging
.insertDiagmonLog:78 vendor.samsung.frameworks.codecsolution.Logging.insertLog:54 vendor.samsung.frameworks.codecsolution.Logging.insertLog:46 vendor.samsung.frameworks.codecsolution.SehCodecSolutionSe
rvice$1.handleMessage:210
01-02 17:07:42.665  2032 25110 W Codec2Client: query -- param skipped: index = 1342179345.
01-02 17:07:42.665  2032 25110 W Codec2Client: query -- param skipped: index = 2415921170.
01-02 17:07:42.666  2032 25110 W Codec2Client: query -- param skipped: index = 3254792206.
01-02 17:07:42.666  2032 25110 W Codec2Client: query -- param skipped: index = 3254792194.
01-02 17:07:42.667  2032 25110 D CCodecBufferChannel: [c2.android.amrnb.encoder#516] Created input block pool with allocatorID 16 => poolID 1680 - OK (0)
01-02 17:07:42.667  2090 20145 D BufferPoolAccessor2.0: bufferpool2 0xb400007209bdb8a8 : 0(0 size) total buffers - 0(0 size) used buffers - 119/123 (recycle/alloc) - 4/122 (fetch/transfer)
01-02 17:07:42.667  2090 20145 D BufferPoolAccessor2.0: Destruction - bufferpool2 0xb400007209bdb8a8 cached: 0/0M, 0/0% in use; allocs: 123, 97% recycled; transfers: 122, 97% unfetched
01-02 17:07:42.668  2032 13242 D BufferPoolAccessor2.0: bufferpool2 0xecc083c8 : 0(0 size) total buffers - 0(0 size) used buffers - 120/128 (recycle/alloc) - 8/250 (fetch/transfer)
01-02 17:07:42.668  2032 13242 D BufferPoolAccessor2.0: Destruction - bufferpool2 0xecc083c8 cached: 0/0M, 0/0% in use; allocs: 128, 94% recycled; transfers: 250, 97% unfetched
01-02 17:07:42.668  2032 25110 I CCodecBufferChannel: [c2.android.amrnb.encoder#516] Created output block pool with allocatorID 16 => poolID 965 - OK
01-02 17:07:42.669  2032 25110 D CCodecBufferChannel: [c2.android.amrnb.encoder#516] Configured output block pool ids 965 => OK
01-02 17:07:42.669  2032 25110 I CCodec  : state->set(RUNNING)
01-02 17:07:42.669  1654  1654 I QC2CompStore: Setting heap usage to system
01-02 17:07:42.669 22974 22974 I Finsky:background: [2] qaa.onTrimMemory(1): Memory trim requested to level 80
01-02 17:07:42.669 23558 23558 I Finsky  : [2] qaa.onTrimMemory(1): Memory trim requested to level 60
01-02 17:07:42.669 23558 23558 I Finsky  : [2] jyn.accept(12): Flushing in-memory image cache
01-02 17:07:42.670 22801 22801 I Finsky  : [2] qaa.onTrimMemory(1): Memory trim requested to level 40
01-02 17:07:42.672  2032 25110 I CCodecBufferChannel: [c2.android.amrnb.encoder#516] 4 initial input buffers available
01-02 17:07:42.672 22801 22801 I Finsky  : [2] jyn.accept(12): Flushing in-memory image cache
01-02 17:07:42.672  2090 25111 D SimpleC2Component: Using output block pool with poolID 965 => got 965 - 0
01-02 17:07:42.672  1654  1654 I QC2CompStore: Setting heap usage to system
01-02 17:07:42.673  2032 18974 W StagefrightRecorder: audio source is exist, set interval to audio
01-02 17:07:42.673  2032 18974 D MPEG4Writer: reset()
01-02 17:07:42.673  2032 18974 D MPEG4Writer: Audio track stopping. Stop source
01-02 17:07:42.673  2032 18974 E MPEG4Writer: Stop() called but track is not started or stopped
01-02 17:07:42.673  7614  7614 W ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1926 android.content.ContextWrapper.startService:834
android.content.ContextWrapper.startService:834 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.a:4 com.sec.android.diagmonagent.sa.receiver.CFLogReceiver.onReceive:4
01-02 17:07:42.675 24752 25066 I python  : Error starting MediaRecorder: JVM exception occurred: start failed. java.lang.RuntimeException
01-02 17:07:42.707  1716  1716 D SurfaceFlinger: Display 4630947232161729154 HWC layers:
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb4000074423464b0 | 0102 | RGBA_8888    |    0.0    0.0 1080.0 2106.0 |    0   75 1080 2181 | SurfaceView[org.test.myapp/org.kivy.android
.PythonActivity]@0(BLAST)#59317
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb400007442347110 | 0100 | RGBA_8888    |    0.0    0.0 1080.0 2316.0 |    0    0 1080 2316 | org.test.myapp/org.kivy.android.PythonActivity$_24752#59310
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb400007442338290 | 0100 | RGBA_8888    |    0.0    0.0 1080.0   75.0 |    0    0 1080   75 | StatusBar$_4129#95
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb40000744232da60 | 0100 | RGBA_8888    |    0.0    0.0   67.0  342.0 | 1013  309 1080  651 | com.samsung.android.app.cocktailbars[...]rv
ice.CocktailBarService$_8507#59266
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:      DEVICE | 0xb4000074423480d0 | 0100 | RGBA_8888    |    0.0    0.0 1080.0  135.0 |    0 2181 1080 2316 | NavigationBar0$_4129#90
01-02 17:07:42.707  1716  1716 D SurfaceFlinger:
01-02 17:07:42.738  2443  2586 I GestureDetector: handleMessage TAP
01-02 17:07:42.739  2443  2443 I GestureDetector: handleMessage TAP
01-02 17:07:42.830  7817  7817 I ResourceOverlayService_0: waitAndQuit called
01-02 17:07:42.831  7817  7817 I ResourceOverlayService_0: activity user id 0 process id 0
01-02 17:07:43.167  2443  5599 D SemWifiUsabilityStatsMonitor: onWifiUsabilityStats - seqNum 35415, isSameBssidAndFreq true
01-02 17:07:43.168  2443  3958 D ConnectivityService: notifyType CALLBACK_CAP_CHANGED for [196 WIFI]
01-02 17:07:43.169  2443  4015 I SemWifiLinkQualityMonitor: Link Qos Query: 0.060 ms / 132.980 Mbps (260 / 0.011 / 1.452)
01-02 17:07:43.185  2443  3992 I WifiConnectivityMonitor.NCC: sNetworkCallback(oCC) FULL : 196(true/false)[ Transports: WIFI Capabilities: NOT_METERED&INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&VALIDATED&
NOT_ROAMING&FOREGROUND&NOT_CONGESTED&NOT_SUSPENDED&NOT_VCN_MANAGED LinkUpBandwidth>=31256Kbps LinkDnBandwidth>=45171Kbps TransportInfo: <SSID: <unknown ssid>, BSSID: 02:00:00:**:**:00, MAC: 02:00:00:**
:**:00, IP: /192.168.1.85, Security type: 2, Supplicant state: COMPLETED, Wi-Fi standard: 5, RSSI: -52,

full code (looks weird because of debugging)

import kivy
import numpy as np
kivy.require('2.1.0')

from kivy.app import App
from kivy.clock import Clock
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.core.audio import SoundLoader
from kivy.utils import platform
from jnius import autoclass
from time import sleep

class MyApp(App):
    def __init__(self):
        super(MyApp, self).__init__()
        self.mRecorder = None
        self.recording = False

    def build(self):
        layout = BoxLayout(orientation='vertical')
        self.label = Label(text='Press the button to start noise detection')
        layout.add_widget(self.label)
        self.button = Button(text='Start/stop recording')
        self.button.bind(on_press=self.start_stop_recording)
        layout.add_widget(self.button)
        return layout

    def on_start(self, **kwargs):
        if platform == 'android':
            from android.permissions import request_permissions, Permission
            request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, Permission.RECORD_AUDIO])

    def recorderSetup(self):
        if platform == 'android':
            MediaRecorder = autoclass('android.media.MediaRecorder')
            AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
            OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
            AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')

            ParcelFileDescriptor = autoclass('android.os.ParcelFileDescriptor')
            self.fd = ParcelFileDescriptor.createPipe()[1].getFileDescriptor()

            self.mRecorder = MediaRecorder()

            self.mRecorder.setAudioSource(AudioSource.MIC)
            self.mRecorder.setOutputFormat(OutputFormat.THREE_GPP)
            self.mRecorder.setAudioEncoder(AudioEncoder.AMR_NB)
            print(f'Output file descriptor: {self.fd}')
            self.mRecorder.setOutputFile(self.fd)
            try:
                self.mRecorder.prepare()
            except Exception as e:
                print(f'Error preparing MediaRecorder: {e}')
            try:
                self.mRecorder.start()
            except Exception as e:
                print(f'Error starting MediaRecorder: {e}')

            sleep(1)
            try:
                self.mRecorder.stop()
            except Exception as e:
                print(f'Error stopping MediaRecorder: {e}')
            return True
        return False

    def start_stop_recording(self, instance):
        if self.recording:
            self.stop_record_loop()
        else:
            self.start_detect_loop()

    def start_detect_loop(self):
        self.label.text = 'Noise detection in progress...'
        self.recording = True
        self.recorderSetup()

        return

snippet from builddozer.spec (it fails to build if I add the write permission here

# (list) Permissions
android.permissions = READ_EXTERNAL_STORAGE,RECORD_AUDIO

So I am trying to record audio but not into a file. Instead I just need it in memory so I can do some calculations on it with numpy.

I've tried using a buffer, java output stream, and neither worked. The current method I have is based on this Using MediaRecorder to write to a buffer or FIFO which apparently works for them.

I am running this on an updated S22 ultra


来源: stackexchange

问:
Return updated value in getter function of model class in android studio java
I am calculating the number of units available base on the units sold in "Sale" table. I am using Firebase Datastore. My code looks like below inside the Post Model

```<code>public String getUnits() {

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Sale").child(this.postid);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            Long count = Long.parseLong(units) - snapshot.getChildrenCount();
            units = count.toString();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    return units;
}
</code>```

I need to return the value inside onDataChange(). It is showing exception.

I am trying to get this value inside a Adapter in Android Studio.

```<code>private void getCardCount( Post post){
  cardCount.setText("Remaining " + post.getUnits());
}
</code>```

If I put return inside onDataChange(), it gives the error : Cannot return a value from a method with void result type

and when I change the return type to String, it gives the error: 'onDataChange(DataSnapshot)' in 'Anonymous class derived from com.google.firebase.database.ValueEventListener' clashes with 'onDataChange(DataSnapshot)' in 'com.google.firebase.database.ValueEventListener'; attempting to use incompatible return type

I am new to android studio and some help will be much appreciated. Thank you in advance.

ContentLicense: CC BY-SA 4.0

Body:
I am calculating the number of units available base on the units sold in "Sale" table. I am using Firebase Datastore. My code looks like below inside the Post Model

public String getUnits() {

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Sale").child(this.postid);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            Long count = Long.parseLong(units) - snapshot.getChildrenCount();
            units = count.toString();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    return units;
}

I need to return the value inside onDataChange(). It is showing exception.

I am trying to get this value inside a Adapter in Android Studio.

private void getCardCount( Post post){
  cardCount.setText("Remaining " + post.getUnits());
}

If I put return inside onDataChange(), it gives the error : Cannot return a value from a method with void result type

and when I change the return type to String, it gives the error: 'onDataChange(DataSnapshot)' in 'Anonymous class derived from com.google.firebase.database.ValueEventListener' clashes with 'onDataChange(DataSnapshot)' in 'com.google.firebase.database.ValueEventListener'; attempting to use incompatible return type

I am new to android studio and some help will be much appreciated. Thank you in advance.


问:
How can I select and display a random data from multiple rows and columns in a spreadsheet in LibreOffice Calc?
I've a spreadsheet in LibreOffice Calc as shown below in the figure. I want to select  and display a random data from multiple rows and columns in that spreadsheet.


问:
VertexAI GCP not allowing me to connect to Github via SSH keeps erroring
I have connected my managed notebook to Github using the instructions  here

I cloned my repository using the HTTPS url which works fine only issues is it asks me for UN and PW every time I push or pull so I tried to clone the repository using SSH url which failed to work

I then tried these steps here to Switching remote URLs from HTTPS to SSH using

```<code>$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
</code>```

this failed to work also with VertexAI basically freezing up disconnecting from the HTTPS and not recognising the SSH

I have added the relevant SSH keys to my account using the instructions here

does anybody have any advice or any solutions

In short I want to be able to connect VertexAI managed notebook to GitHub via SSH to avoid having to re-enter by UN and PW every time I push or pull

I've tried to clone the repository using the SSH url no avail
I've also tried to change the remote repository using

```<code>$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git
</code>```

Body:
I have connected my managed notebook to Github using the instructions  here

I cloned my repository using the HTTPS url which works fine only issues is it asks me for UN and PW every time I push or pull so I tried to clone the repository using SSH url which failed to work

I then tried these steps here to Switching remote URLs from HTTPS to SSH using

$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git

this failed to work also with VertexAI basically freezing up disconnecting from the HTTPS and not recognising the SSH

I have added the relevant SSH keys to my account using the instructions here

does anybody have any advice or any solutions

In short I want to be able to connect VertexAI managed notebook to GitHub via SSH to avoid having to re-enter by UN and PW every time I push or pull

I've tried to clone the repository using the SSH url no avail
I've also tried to change the remote repository using

$ git remote set-url origin git@github.com:USERNAME/REPOSITORY.git


问:
"SQL translate error: Extra placeholder" when using prepared statements
I'm trying to use prepared statements in my SQL but I can't get it working. I'm getting error "SQL translate error: Extra placeholder" when I add something like this to my code

```<code>if ($cpucooler_socket != "") {

            $myArray = explode(',', trim($cpucooler_socket));

            for ($i = 0; $i < count($myArray); $i++) {

                if(count($myArray)>1) {

                    $socket = $myArray[$i];

                    if ($i === 0) {
                        $query .= " AND (socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    } else if ($i === count($myArray) - 1) {
                        $query .= " OR socket LIKE ?)";
                        $query_params[] = '%' . $socket . '%';
                    } else {
                        $query .= " OR socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    }

                } else {
                    $query .= " AND socket LIKE ?";
                    $query_params[] = '%' . $socket . '%';
                }
            }
        }
</code>```

What am I doing wrong? What is the right syntax that I should be using in this case? If I don't use the for loop and I add only for example this instead:

```<code>$query .= " AND socket LIKE ?";
$query_params[] = '%' . $myArray[0] . '%';
</code>```

then it's working fine. Here is my full code if it helps:

```<code>public function getCompatibleMb($case_format_dosky, $cpu_socket, $ram_typ, $pocet_ram, $intel_socket, $amd_socket, $select_after_id, $search) {

    $cpucooler_socket = null;

    if(isset($intel_socket) || isset($amd_socket)){
        if ($intel_socket != null && $amd_socket != null) {
            $cpucooler_socket = $intel_socket.", ".$amd_socket;
        } else if($intel_socket != null) {
            $cpucooler_socket = $intel_socket;
        } else if ($amd_socket != null){
            $cpucooler_socket = $amd_socket;
        }
    } else {
        $cpucooler_socket = null;
    }

    $query_params = array();

    $query = "SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1";

    if ($cpu_socket != "") {
        $query .= " AND socket = ?";
        $query_params[] = $cpu_socket;
    } else {
        if ($cpucooler_socket != "") {

            $myArray = explode(',', trim($cpucooler_socket));

            for ($i = 0; $i < count($myArray); $i++) {

                if(count($myArray)>1) {

                    $socket = $myArray[$i];

                    if ($i === 0) {
                        $query .= " AND (socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    } else if ($i === count($myArray) - 1) {
                        $query .= " OR socket LIKE ?)";
                        $query_params[] = '%' . $socket . '%';
                    } else {
                        $query .= " OR socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    }

                } else {
                    $query .= " AND socket LIKE ?";
                    $query_params[] = '%' . $socket . '%';
                }
            }
        }
    }

    if ($ram_typ != "") {
        $query .= " AND ram_type = ?";
        $query_params[] = $ram_typ;
    }

    if ($pocet_ram != "") {
        $query .= " AND ram_slots >= ?";
        $query_params[] = $pocet_ram;
    }

    if($case_format_dosky !="") {

        $myArray = explode(',', trim($case_format_dosky));

        for ($i = 0; $i < count($myArray); $i++) {

            if(count($myArray)>1) {

                $formfactor = trim($myArray[$i]);

                if ($i === 0) {
                    $query .= " AND (form_factor = ?";
                    $query_params[] = $formfactor;
                } else if ($i === count($myArray) - 1) {
                    $query .= " OR form_factor = ?";
                    $query_params[] = $formfactor;
                } else {
                    $query .= " OR form_factor = ?)";
                    $query_params[] = $formfactor;
                }

            } else {
                $query .= " AND form_factor LIKE ?";
                $query_params[] = '%' . $formfactor . '%';
            }
        }
    }

    if ($select_after_id != "") {
        $decrypted = $this->McryptServices->decryptData($select_after_id);
        $query .= " AND id > ?";
        $query_params[] = $decrypted;
    }
    if ($search != "") {
        $new_search = str_replace(" ", "%",$search);
        $query .= " AND produkt LIKE ?";
        $query_params[] = '%'.$new_search.'%';
    }

    $query .= " LIMIT 32";

    $vytah = $this->Database->query($query, $query_params)->fetchAll();

    $arr[] = $vytah;

    foreach ($arr[0] as $key => $value) {
        $arr[0][$key]->{'encryptid'} = $this->McryptServices->encryptData($arr[0][$key]->{'id'});
    }

    return json_encode($arr);

}
</code>```

This is the response after an error:

```<code>"line":225,"args":[["string","SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1 AND (form_factor = ? OR form_factor = ? OR form_factor = ?) LIMIT 32"],["array",[["string","ATX"],["string","mATX (Micro ATX)"],["string","mITX (Mini ITX)"]]]]}
</code>```

Body:
I'm trying to use prepared statements in my SQL but I can't get it working. I'm getting error "SQL translate error: Extra placeholder" when I add something like this to my code

if ($cpucooler_socket != "") {

            $myArray = explode(',', trim($cpucooler_socket));

            for ($i = 0; $i < count($myArray); $i++) {

                if(count($myArray)>1) {

                    $socket = $myArray[$i];

                    if ($i === 0) {
                        $query .= " AND (socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    } else if ($i === count($myArray) - 1) {
                        $query .= " OR socket LIKE ?)";
                        $query_params[] = '%' . $socket . '%';
                    } else {
                        $query .= " OR socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    }

                } else {
                    $query .= " AND socket LIKE ?";
                    $query_params[] = '%' . $socket . '%';
                }
            }
        }

What am I doing wrong? What is the right syntax that I should be using in this case? If I don't use the for loop and I add only for example this instead:

$query .= " AND socket LIKE ?";
$query_params[] = '%' . $myArray[0] . '%';

then it's working fine. Here is my full code if it helps:

public function getCompatibleMb($case_format_dosky, $cpu_socket, $ram_typ, $pocet_ram, $intel_socket, $amd_socket, $select_after_id, $search) {

    $cpucooler_socket = null;

    if(isset($intel_socket) || isset($amd_socket)){
        if ($intel_socket != null && $amd_socket != null) {
            $cpucooler_socket = $intel_socket.", ".$amd_socket;
        } else if($intel_socket != null) {
            $cpucooler_socket = $intel_socket;
        } else if ($amd_socket != null){
            $cpucooler_socket = $amd_socket;
        }
    } else {
        $cpucooler_socket = null;
    }

    $query_params = array();

    $query = "SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1";

    if ($cpu_socket != "") {
        $query .= " AND socket = ?";
        $query_params[] = $cpu_socket;
    } else {
        if ($cpucooler_socket != "") {

            $myArray = explode(',', trim($cpucooler_socket));

            for ($i = 0; $i < count($myArray); $i++) {

                if(count($myArray)>1) {

                    $socket = $myArray[$i];

                    if ($i === 0) {
                        $query .= " AND (socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    } else if ($i === count($myArray) - 1) {
                        $query .= " OR socket LIKE ?)";
                        $query_params[] = '%' . $socket . '%';
                    } else {
                        $query .= " OR socket LIKE ?";
                        $query_params[] = '%' . $socket . '%';
                    }

                } else {
                    $query .= " AND socket LIKE ?";
                    $query_params[] = '%' . $socket . '%';
                }
            }
        }
    }

    if ($ram_typ != "") {
        $query .= " AND ram_type = ?";
        $query_params[] = $ram_typ;
    }

    if ($pocet_ram != "") {
        $query .= " AND ram_slots >= ?";
        $query_params[] = $pocet_ram;
    }

    if($case_format_dosky !="") {

        $myArray = explode(',', trim($case_format_dosky));

        for ($i = 0; $i < count($myArray); $i++) {

            if(count($myArray)>1) {

                $formfactor = trim($myArray[$i]);

                if ($i === 0) {
                    $query .= " AND (form_factor = ?";
                    $query_params[] = $formfactor;
                } else if ($i === count($myArray) - 1) {
                    $query .= " OR form_factor = ?";
                    $query_params[] = $formfactor;
                } else {
                    $query .= " OR form_factor = ?)";
                    $query_params[] = $formfactor;
                }

            } else {
                $query .= " AND form_factor LIKE ?";
                $query_params[] = '%' . $formfactor . '%';
            }
        }
    }

    if ($select_after_id != "") {
        $decrypted = $this->McryptServices->decryptData($select_after_id);
        $query .= " AND id > ?";
        $query_params[] = $decrypted;
    }
    if ($search != "") {
        $new_search = str_replace(" ", "%",$search);
        $query .= " AND produkt LIKE ?";
        $query_params[] = '%'.$new_search.'%';
    }

    $query .= " LIMIT 32";

    $vytah = $this->Database->query($query, $query_params)->fetchAll();

    $arr[] = $vytah;

    foreach ($arr[0] as $key => $value) {
        $arr[0][$key]->{'encryptid'} = $this->McryptServices->encryptData($arr[0][$key]->{'id'});
    }

    return json_encode($arr);

}

This is the response after an error:

"line":225,"args":[["string","SELECT id encryptid, id,produkt,vyrobca,dostupnost,cena,socket,series,chipset,form_factor,bluetooth,wifi,rgb,m2,sata3,sietova_karta,zvukova_karta,pci_express_3_0,pci_express_4_0,pci_express_5_0,ram_type,ram_slots,rezim_ram,max_mhz_ram,mosfet_coolers,crossfire_support,sli_support,raid_support,audio_chipset,audio_channels,ext_connectors,int_connectors,max_lan_speed,pci_x16_slots,pci_x4_slots,pci_x1_slots,m2_ports,usb_2_0,usb_3_2_gen_1,usb_3_1_gen_2,usb_3_2_gen_2,sata_3_ports,img_count,produkt_number,vyrobca_url FROM mb_list WHERE dostupnost=1 AND (form_factor = ? OR form_factor = ? OR form_factor = ?) LIMIT 32"],["array",[["string","ATX"],["string","mATX (Micro ATX)"],["string","mITX (Mini ITX)"]]]]}


问:
compare two array of objects to validate if the date is within the range

let array1 = [
    {
        start_date: 2022-12-01,
        end_date: 2022-12-07,
        status: ready,
    },
   {
        start_date: 2022-12-15,
        end_date: 2022-12-21,
        status: overlap,
    },

   {
        start_date: 2022-12-18,
        end_date: 2022-12-24,
        status: overlap,
    },
    {
        start_date: 2022-12-18,
        end_date: 2022-12-31,
        status: match,
    },
    {
        start_date: 2022-11-22,
        end_date: 2022-11-28,
        status: match,
    },
    {
        start_date: 2022-11-17,
        end_date: 2022-11-23,
        status: overlap
    },
    {
        start_date: 2022-11-15,
        end_date: 2022-11-21,
        status: overlap
    },
    {
        start_date: 2022-11-01,
        end_date: 2022-11-07,
        status: ready
    }
 ];

let array2 = [
    {
        start_date: 2022-12-18,
        end_date: 2022-12-31
    }
    {
        start_date: 2022-11-22,
        end_date: 2022-11-28
    }
];
```

I have two array of objects and

would like to compare start date of array 1 against array 2 to see if array 1 start date is within the range of array 2 start date and end date
then also compare end date of array 1 against array 2 to see if array 1 end date is within the range of array 2 start date and end date

if both the condition above are met then validate if array 1 status is overlap.

eg: Dec 15-21 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

if array1 start date is outside the range of array 2 start and end date, then validate array 1 status is ready . and if array1 end date is outside the range of array 2 start and end date, then validate array 1 status is ready .
eg: Dec 01-07 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

and if array 1 start date matches array 2 start date and array 1 end date matches array 2 end date then validate array 1 status is match,
eg: Dec 18-31 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

Can you please advise how to achieve this using javascript.

Now I have both the array with both Dec and Nov month, Is there a way to verify Dec month start and date from array 1 to only with Dec month dates in array 2, and likewise Nov month start date and end date from array 1 against only Nov month dates in array 2 to verify if the date is within the range, or match, or overlap. Can you please suggest,?

Compare two arrays of objects and find out if the date from the first array is within the specified range in the second array in Javascript
Here is the answer suggested to verify for Dec mont for reference.

Compare two arrays of objects and find out if the date from the first array is within the specified range in the second array in Javascript

Body:
let array1 = [
    {
        start_date: 2022-12-01,
        end_date: 2022-12-07,
        status: ready,
    },
   {
        start_date: 2022-12-15,
        end_date: 2022-12-21,
        status: overlap,
    },

   {
        start_date: 2022-12-18,
        end_date: 2022-12-24,
        status: overlap,
    },
    {
        start_date: 2022-12-18,
        end_date: 2022-12-31,
        status: match,
    },
    {
        start_date: 2022-11-22,
        end_date: 2022-11-28,
        status: match,
    },
    {
        start_date: 2022-11-17,
        end_date: 2022-11-23,
        status: overlap
    },
    {
        start_date: 2022-11-15,
        end_date: 2022-11-21,
        status: overlap
    },
    {
        start_date: 2022-11-01,
        end_date: 2022-11-07,
        status: ready
    }
 ];

let array2 = [
    {
        start_date: 2022-12-18,
        end_date: 2022-12-31
    }
    {
        start_date: 2022-11-22,
        end_date: 2022-11-28
    }
];

I have two array of objects and

would like to compare start date of array 1 against array 2 to see if array 1 start date is within the range of array 2 start date and end date
then also compare end date of array 1 against array 2 to see if array 1 end date is within the range of array 2 start date and end date

if both the condition above are met then validate if array 1 status is overlap.

eg: Dec 15-21 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

if array1 start date is outside the range of array 2 start and end date, then validate array 1 status is ready . and if array1 end date is outside the range of array 2 start and end date, then validate array 1 status is ready .
eg: Dec 01-07 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

and if array 1 start date matches array 2 start date and array 1 end date matches array 2 end date then validate array 1 status is match,
eg: Dec 18-31 (array 1 - start date -end date ) Dec 18-31 (from array 2 start date -end date)

Can you please advise how to achieve this using javascript.

Now I have both the array with both Dec and Nov month, Is there a way to verify Dec month start and date from array 1 to only with Dec month dates in array 2, and likewise Nov month start date and end date from array 1 against only Nov month dates in array 2 to verify if the date is within the range, or match, or overlap. Can you please suggest,?

Compare two arrays of objects and find out if the date from the first array is within the specified range in the second array in Javascript
Here is the answer suggested to verify for Dec mont for reference.

Compare two arrays of objects and find out if the date from the first array is within the specified range in the second array in Javascript


问:
C++ Builder FMX StretchDraw a bitmap to change the size
I notice that in Firemonkey there is no equivalent of StretchDraw for changing the size of a bitmap that I have in memory.

I need to increase the size of a bitmap in memory before displaying it in a TImage Control.  I want the size of the bitmap in memory to match that of a TImage Control before displaying it.  The image bitmap is then sent off to a database blob field.  When I recall the bitmap from the database, it is the original size and not the stretched size that I need.
Tried using Wrapmode and that works great for displaying and stretching the bitmaps in a TImage but It doesn't save the bitmap as stretched.

Any ideas how to do this in C++ Builder?


问:
In Spring, Controller does not return the response at all after infinite looping
First of all, I am sorry what I am asking is so vague and not provided enough context to make you understand.

Here it is my endpoint in Controller.java

```<code>    @GetMapping("/endpoint")
    public ResponseEntity<?> addDocument(@RequestParam String param1, @RequestParam String param2) {

        AddDocumentRequest request = new AddDocumentRequest(param1, param2);

        callRequestHandler(request);

        log.info("Job Done");
        return ResponseEntity.ok(true);
    }
</code>```

And it is the callRequestHandler in Controller.java. It just calls handler and handle the exceptions.

```<code>    private void callRequestHandler(AddDocumentRequest request) {
        try {
requestHandler.requestHandler(request);
        } catch (Exception e) {
            log.error("error");
        }
    }
</code>```

It is the method of RequestHandler.java and it acts as @Service. It calls the Async method which send requests to other APIs.

```<code>    public void requestHandler(AddDocumentRequest request) throws Exception {

        //calls @Async method.
        CompletableFuture<String> registry = service.addDocuments(request);

        //blocks the thread and wait for the desire state.
        blockAndWaitResponses(request);
    }
</code>```

And here it is the infinite loop waiting to meet the desire state, if it meets the state it inserts the data and break the infinite loop, else update state and sleep for 2mins.

This infinite loop takes a time up to several hours and in this specific situation, it takes 15 mins.

I am aware of the busy waiting is bad design, but there is no better solution for my business situation.

```<code>private void blockAndWaitResponses(AddDocumentRequest request) throws Exception {
        while (true) {
            //busy wait
            Thread.sleep(2mins);

            if (desiredStateOccured()) {
                insertDataToDB();
                break;
            }
            else {
                updateState();
            }
        }
    }
</code>```

And after all of that, back to controller, log.info("Job Done"); is called but return ResponseEntity.ok(true); is not called.

All I can say is just it is not called. In my Postman, Sending request... is not gone.
I have debugged it, nothing is occured. It just looks so normal.

And some requests which goes exact same flow work fine (meaning it returns ResponseEntity.ok(true) without any problem.) but some does not.

I have got no idea how to deal with it. Any help would be thankful.

Body:
First of all, I am sorry what I am asking is so vague and not provided enough context to make you understand.

Here it is my endpoint in Controller.java

    @GetMapping("/endpoint")
    public ResponseEntity<?> addDocument(@RequestParam String param1, @RequestParam String param2) {

        AddDocumentRequest request = new AddDocumentRequest(param1, param2);

        callRequestHandler(request);

        log.info("Job Done");
        return ResponseEntity.ok(true);
    }

And it is the callRequestHandler in Controller.java. It just calls handler and handle the exceptions.

    private void callRequestHandler(AddDocumentRequest request) {
        try {
requestHandler.requestHandler(request);
        } catch (Exception e) {
            log.error("error");
        }
    }

It is the method of RequestHandler.java and it acts as @Service. It calls the Async method which send requests to other APIs.

    public void requestHandler(AddDocumentRequest request) throws Exception {

        //calls @Async method.
        CompletableFuture<String> registry = service.addDocuments(request);

        //blocks the thread and wait for the desire state.
        blockAndWaitResponses(request);
    }

And here it is the infinite loop waiting to meet the desire state, if it meets the state it inserts the data and break the infinite loop, else update state and sleep for 2mins.

This infinite loop takes a time up to several hours and in this specific situation, it takes 15 mins.

I am aware of the busy waiting is bad design, but there is no better solution for my business situation.

private void blockAndWaitResponses(AddDocumentRequest request) throws Exception {
        while (true) {
            //busy wait
            Thread.sleep(2mins);

            if (desiredStateOccured()) {
                insertDataToDB();
                break;
            }
            else {
                updateState();
            }
        }
    }

And after all of that, back to controller, log.info("Job Done"); is called but return ResponseEntity.ok(true); is not called.

All I can say is just it is not called. In my Postman, Sending request... is not gone.
I have debugged it, nothing is occured. It just looks so normal.

And some requests which goes exact same flow work fine (meaning it returns ResponseEntity.ok(true) without any problem.) but some does not.

I have got no idea how to deal with it. Any help would be thankful.


问:
How to count the CPE in Practice Problem 5.5 in CSAPP
I'm working on this practice question 5.5 in the textbook:

Randal E. Bryant, David R. O’Hallaron - Computer Systems. A Programmer’s Perspective [3rd ed.] (2016, Pearson).

Here is the problem description:

In B, my idea is that CPE for this func  is 8n because the performance-limiting computation is result, which requires floating point mul and floating point add. However, the solution says it's 5n   due to xpwr=x * xpwr.

Can someone help explain what's wrong in my idea?

Figure 5.12:

This is the data-flow I drew.


问:
Strange behavior on mobile device running app script / wrong data shown in cells after hide/unhide columns
I wrote some app script running in a google spreadsheet that gives me a weather forecast for a column of GPS coordinates. For UI purposes I hide and unhide columns for the mobile device user. Everything works great and the values in the various cells are all correct. But it is not SHOWN correct on Android phones. It appears to the user that values from other cells are located in the wrong cells - strange. It's just a visual problem.

If I manually change from dark theme to light theme on the mobile device (or vice versa) then everything looks the way it should.

If I stop hiding/unhiding columns the problem goes away, but would really like this to work as is -- again, just a visual display problem with the sheets app. How can I refresh the screen?

Ideas?

The cells should be showing the value that is actually in them.


问:
How can I handle EGL problem that causes in Android Webview? (EGL_BAD_PARAMETER, EGL_BAD_ATTRIBUTE)
I got this error when I load a page with WebView.

This is my setting.

```<code>settings.apply {
    userAgentString.replace("Android", "android")
    databaseEnabled = true
    javaScriptEnabled = true
    javaScriptCanOpenWindowsAutomatically = true
    domStorageEnabled = true
    loadWithOverviewMode = true
    allowContentAccess = true
    loadWithOverviewMode = true
    mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
}
CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);

</code>```
```<code>tid 14645: eglDestroySyncKHR(2470): error 0x300c (EGL_BAD_PARAMETER)

[ERROR:android_image_reader_utils.cc(19)] Failed to create android native fence sync object.

tid 14645: eglCreateSyncKHR(2361): error 0x3004 (EGL_BAD_ATTRIBUTE)

eglDestroySyncKHR: null sync object!
</code>```

Especially, I think when it has video content, this error is shown, and If the video is not visible(For example, scroll down to hide the video), Then, this error isn't shown.

How can I handle this issue? Or is this ignorable issue? Actually, I haven't got any crash yet. Or should the Front End developer fix this?

Body:
I got this error when I load a page with WebView.

This is my setting.

settings.apply {
    userAgentString.replace("Android", "android")
    databaseEnabled = true
    javaScriptEnabled = true
    javaScriptCanOpenWindowsAutomatically = true
    domStorageEnabled = true
    loadWithOverviewMode = true
    allowContentAccess = true
    loadWithOverviewMode = true
    mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
}
CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);

tid 14645: eglDestroySyncKHR(2470): error 0x300c (EGL_BAD_PARAMETER)

[ERROR:android_image_reader_utils.cc(19)] Failed to create android native fence sync object.

tid 14645: eglCreateSyncKHR(2361): error 0x3004 (EGL_BAD_ATTRIBUTE)

eglDestroySyncKHR: null sync object!

Especially, I think when it has video content, this error is shown, and If the video is not visible(For example, scroll down to hide the video), Then, this error isn't shown.

How can I handle this issue? Or is this ignorable issue? Actually, I haven't got any crash yet. Or should the Front End developer fix this?


问:
How to correctly use "yAxisID" for a Chart.js
I am new to using Chart.js objects and have run into a bug or syntax error using "yAxisID" as a property of my datasets. I am sending to QuickChart using the PowerShell command:

```<code>Invoke-RestMethod -Method Post -Uri "https://quickchart.io/chart/create" -Body $json -ContentType "application/json"
</code>```

Note that the png outfile approach seems to work fine..

```<code>Invoke-RestMethod -Method Post -Uri "https://quickchart.io/chart" -Body $json -ContentType "application/json" -OutFile <outfile.png>"
</code>```

Here is the $json

```<code>{
  data: {
    labels: [
      '2022Dec2',
      '2022Dec7',
      '2022Dec12',
      '2022Dec22',
      '2022Dec27',
      '2022Dec30',
    ],
    datasets: [
      {
        data: [0.0, -3.38, -1.96, -6.44, -6.27, -6.02],
        label: 'SPY',
        borderDash: [1, 0],
        fill: false,
        borderColor: '#4E79A7',
        yAxisID: 'y',
      },
      {
        data: [0.0, -4.11, -2.38, -8.82, -9.9, -8.98],
        label: 'QQQ',
        borderDash: [1, 0],
        fill: false,
        borderColor: '#F28E2B',
        yAxisID: 'y1',
      },
    ],
  },
  options: {
    title: {
      text: 'Stock Symbol % Change',
      display: true,
    },
    scales: {
      yAxes: [
        {
          position: 'left',
          id: 'y',
          display: true,
        },
        {
          position: 'right',
          gridLines: {
            drawOnChartArea: false,
          },
          id: 'y1',
          display: true,
        },
      ],
    },
    legend: {
      position: 'bottom',
    },
  },
  type: 'line',
}
</code>```

I tried deleting the "yAxisID" lines of the $json and that seems to work fine (although on just a single y-axis). I am expecting the "yAxisID" lines to plot the first dataset on the left y-axis and the second dataset on the right y-axis.

Body:
I am new to using Chart.js objects and have run into a bug or syntax error using "yAxisID" as a property of my datasets. I am sending to QuickChart using the PowerShell command:

Invoke-RestMethod -Method Post -Uri "https://quickchart.io/chart/create" -Body $json -ContentType "application/json"

Note that the png outfile approach seems to work fine..

Invoke-RestMethod -Method Post -Uri "https://quickchart.io/chart" -Body $json -ContentType "application/json" -OutFile <outfile.png>"

Here is the $json

{
  data: {
    labels: [
      '2022Dec2',
      '2022Dec7',
      '2022Dec12',
      '2022Dec22',
      '2022Dec27',
      '2022Dec30',
    ],
    datasets: [
      {
        data: [0.0, -3.38, -1.96, -6.44, -6.27, -6.02],
        label: 'SPY',
        borderDash: [1, 0],
        fill: false,
        borderColor: '#4E79A7',
        yAxisID: 'y',
      },
      {
        data: [0.0, -4.11, -2.38, -8.82, -9.9, -8.98],
        label: 'QQQ',
        borderDash: [1, 0],
        fill: false,
        borderColor: '#F28E2B',
        yAxisID: 'y1',
      },
    ],
  },
  options: {
    title: {
      text: 'Stock Symbol % Change',
      display: true,
    },
    scales: {
      yAxes: [
        {
          position: 'left',
          id: 'y',
          display: true,
        },
        {
          position: 'right',
          gridLines: {
            drawOnChartArea: false,
          },
          id: 'y1',
          display: true,
        },
      ],
    },
    legend: {
      position: 'bottom',
    },
  },
  type: 'line',
}

I tried deleting the "yAxisID" lines of the $json and that seems to work fine (although on just a single y-axis). I am expecting the "yAxisID" lines to plot the first dataset on the left y-axis and the second dataset on the right y-axis.


问:
Serving SvelteKit app through VSCode Webview API
This question is being asked after spending weeks and giving up multiple times on trying to solve this.

I'm developing a VSCode extension that needs to make use of the Webview API. For a while, this could be using Svelte, but now with SvelteKit released as stable and being treated as default when you do npm create svelte, I targetted to use that. After configuring the app to be static SPA with SSR turned off and using the @sveltejs/adapter-static, it seems that serving it is not the same as it was with vanilla Svelte.

This is the svelte.config.js:

import adapter from '@sveltejs/adapter-static';
import preprocess from 'svelte-preprocess';

/**
 * Consult https://github.com/sveltejs/svelte-preprocess
 * for more information about preprocessors
 *
 * @type {import('@sveltejs/kit').Config} */
export default {
  preprocess: preprocess(),
  kit: {
    adapter: adapter({ fallback: 'index.html' }),
    // ssr: false, // deprecated
    csp: {
      directives: {
        'default-src': ['none'],
        'img-src': ['{{cspSource}} https:'],
        'script-src': ['{{cspSource}}'],
        'style-src': ['{{cspSource}}'],
      },
    },
    // paths: {
    //   base: '{{baseURL}}', // not accepted
    // },
  },
};
```
<p>This is the built HTML:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.png" />
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="content-security-policy" content="default-src 'none'; img-src {{cspSource}} https:; script-src {{cspSource}} 'sha256-N2DRY+AREasGSTE5X4BdHoEYZsaGOpTvUwTBIHmryVA='; style-src {{cspSource}}">
        <link rel="modulepreload" href="/_app/immutable/start-e16b6a0f.js">
        <link rel="modulepreload" href="/_app/immutable/chunks/index-0576dc7c.js">
        <link rel="modulepreload" href="/_app/immutable/chunks/singletons-51070258.js">
  </head>
  <body data-sveltekit-preload-data="hover">
    <div style="display: contents">
        <script type="module" data-sveltekit-hydrate="45h">
            import { start } from "/_app/immutable/start-e16b6a0f.js";

            start({
                env: {},
                paths: {"base":"","assets":""},
                target: document.querySelector('[data-sveltekit-hydrate="45h"]').parentNode,
                version: "1672682689612"
            });
        </script></div>
  </body>
</html>
</code>```

Contrary to vanilla Svelte that would generate something like:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.png" />
    <meta name="viewport" content="width=device-width" />

```
<p>That could be served through Webview like:</p>
<pre class="lang-js prettyprint-override"><code>function getWebviewContent(webview, context) {
    return `
    <!DOCTYPE html>
    <html lang="en">
        <head>
      <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <meta
                http-equiv="Content-Security-Policy"
                content="${[
          "default-src 'none'",
          `img-src ${webview.cspSource} https:`,
          `script-src ${webview.cspSource}`,
          `style-src ${webview.cspSource}`,
        ].join(';')};"
            />
      <title>My Extension</title>
            <script type="module" crossorigin src="${webview.asWebviewUri(
        vscode.Uri.joinPath(context.extensionUri, 'dist/app/main.js')
      )}"></script>
            <link rel="stylesheet" href="${webview.asWebviewUri(
        vscode.Uri.joinPath(context.extensionUri, 'dist/app/style.css')
      )}">
        </head>
        <body><div id="app"></div></body>
    </html>
  `;
}
</code>```

The file is bit more complex now, so I can't (and shouldn't) try to rewrite it in this function.

The following are the conditions:

VSCode needs absolute paths since it has different environments and protocols. Keep in mind that an extension is served locally to every user. (context.extensionUri is IMPORTANT)

SvelteKit has its set of configurations (different from Vite) that may pose to be restrictive specially with SPA mode.

Content Security Policy for Webview is also restrictive to what and what can't be used.

Probably due to Vite, the file names have hashes, so it's not consistent - but I'm preferring to keep that.

The script block in the HTML (may also need a nonce) is importing the start function relatively as a module.

Instead of writing another template as a string for VSCode that would need to be maintained, it would be ideal to have the generated HTML read into VSCode and served. Using Mustache seems good (hence you see {{cspSource}} in the HTML above).

How would one suggest to architecture and integrate this?

Body:
This question is being asked after spending weeks and giving up multiple times on trying to solve this.

I'm developing a VSCode extension that needs to make use of the Webview API. For a while, this could be using Svelte, but now with SvelteKit released as stable and being treated as default when you do npm create svelte, I targetted to use that. After configuring the app to be static SPA with SSR turned off and using the @sveltejs/adapter-static, it seems that serving it is not the same as it was with vanilla Svelte.

This is the svelte.config.js:

import adapter from '@sveltejs/adapter-static';
import preprocess from 'svelte-preprocess';

/**
 * Consult https://github.com/sveltejs/svelte-preprocess
 * for more information about preprocessors
 *
 * @type {import('@sveltejs/kit').Config} */
export default {
  preprocess: preprocess(),
  kit: {
    adapter: adapter({ fallback: 'index.html' }),
    // ssr: false, // deprecated
    csp: {
      directives: {
        'default-src': ['none'],
        'img-src': ['{{cspSource}} https:'],
        'script-src': ['{{cspSource}}'],
        'style-src': ['{{cspSource}}'],
      },
    },
    // paths: {
    //   base: '{{baseURL}}', // not accepted
    // },
  },
};

This is the built HTML:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.png" />
    <meta name="viewport" content="width=device-width" />
    <meta http-equiv="content-security-policy" content="default-src 'none'; img-src {{cspSource}} https:; script-src {{cspSource}} 'sha256-N2DRY+AREasGSTE5X4BdHoEYZsaGOpTvUwTBIHmryVA='; style-src {{cspSource}}">
        <link rel="modulepreload" href="/_app/immutable/start-e16b6a0f.js">
        <link rel="modulepreload" href="/_app/immutable/chunks/index-0576dc7c.js">
        <link rel="modulepreload" href="/_app/immutable/chunks/singletons-51070258.js">

Contrary to vanilla Svelte that would generate something like:

<!DOCTYPE html>

    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.png" />
    <meta name="viewport" content="width=device-width" />

That could be served through Webview like:

function getWebviewContent(webview, context) {
    return `
    <!DOCTYPE html>

      <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1.0" />
            <meta
                http-equiv="Content-Security-Policy"
                content="${[
          "default-src 'none'",
          `img-src ${webview.cspSource} https:`,
          `script-src ${webview.cspSource}`,
          `style-src ${webview.cspSource}`,
        ].join(';')};"
            />
      <title>My Extension</title>

            <link rel="stylesheet" href="${webview.asWebviewUri(
        vscode.Uri.joinPath(context.extensionUri, 'dist/app/style.css')
      )}">

  `;
}

The file is bit more complex now, so I can't (and shouldn't) try to rewrite it in this function.

The following are the conditions:

VSCode needs absolute paths since it has different environments and protocols. Keep in mind that an extension is served locally to every user. (context.extensionUri is IMPORTANT)

SvelteKit has its set of configurations (different from Vite) that may pose to be restrictive specially with SPA mode.

Content Security Policy for Webview is also restrictive to what and what can't be used.

Probably due to Vite, the file names have hashes, so it's not consistent - but I'm preferring to keep that.

The script block in the HTML (may also need a nonce) is importing the start function relatively as a module.

Instead of writing another template as a string for VSCode that would need to be maintained, it would be ideal to have the generated HTML read into VSCode and served. Using Mustache seems good (hence you see {{cspSource}} in the HTML above).

How would one suggest to architecture and integrate this?


问:
How can i get codelens on visual studio for macOS?
On MacOS nothing options in tools visual studio

anyone can help?