问:
Illegal State Exception in mediaplayer.prepare android
I am using a method in asynctask in the class VideoSurfaceView.

But I am getting crash.

I tried other ways too but didn't worked. Below is the code:

......

```<code>     public class VideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "VideoSurfaceView";

    private MediaPlayer mMediaPlayer;

    private String mVideoPath = "";
    private ScreenSaverView.OnVideoPrepareListener onVideoPrepareListener;

    private Bitmap mPreviewBitmap;

    private boolean locking = false;
    private boolean lockResult = false;
    private boolean reading = false;

    public VideoSurfaceView(Context context) {
        super(context);
        init();
    }

    private void init() {
        LogD.i(TAG, "init");
        SurfaceHolder mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        LogD.i(TAG, "surfaceCreated");
        if (!getVideoPath().isEmpty()) {
            initVideoPlayer();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        LogD.i(TAG, "surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        LogD.i(TAG, "surfaceDestroyed");
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

    }

    private void initVideoPlayer() {
        Canvas canvas = getHolder().lockCanvas();
        if (mPreviewBitmap != null && canvas != null) {
            int w = getWidth();
            int h = getHeight();
            Rect src = new Rect(0, 0, mPreviewBitmap.getWidth(), mPreviewBitmap.getHeight());
            Rect dst = new Rect(0, 0, w, h);
            LogD.d(TAG, "drawFirstFrame:view w: " + getWidth() + " h:" + getHeight());
            canvas.drawBitmap(mPreviewBitmap, src, dst, null);
            getHolder().unlockCanvasAndPost(canvas);
        } else if (canvas != null){
            canvas.drawColor(Color.WHITE);
            getHolder().unlockCanvasAndPost(canvas);
        }

        boolean needClose = onVideoPrepareListener.onPrepare();
        if (needClose) {
            LogD.d(TAG, "initVideoPlayer needClose return: ");
            return;
        }

        LogD.i(TAG, "initFirstPlayer()");
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setVolume(0, 0);
        mMediaPlayer.setDisplay(getHolder());
        startPlayFirstVideo();
    }

    private void startPlayFirstVideo() {

        new AsyncTask<Void, Void, FileCacheMediaDataSource>() {

            @Override
            protected FileCacheMediaDataSource doInBackground(Void... voids) {
                locking = true;
                lockResult = false;
                reading = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LockResult result = LockManager.getInstance().lock(LockReason.DISK_SCREENSAVER_READ_ACCESS);
                        lockResult = result.isLockSuccess();
                        if (!reading && lockResult) {
                            LockManager.getInstance().unlock(LockReason.DISK_SCREENSAVER_READ_ACCESS);
                        }
                        locking = false;
                    }
                }).start();

                String path = AppConst.SCREEN_SAVER_MEDIA_PATH + mVideoPath;
                FileCacheMediaDataSource dataSource = new FileCacheMediaDataSource(path);
                if (!locking && lockResult) {
                    LockManager.getInstance().unlock(LockReason.DISK_SCREENSAVER_READ_ACCESS);
                }
                reading = false;

                return dataSource;
            }

            @Override
            protected void onPostExecute(FileCacheMediaDataSource dataSource) {
                super.onPostExecute(dataSource);
                if (mMediaPlayer == null) {
                    return;
                }
                if (dataSource.getSize() == -1) {
                    LogD.d(TAG, "showErrorScreenSaver");
                    screenSaverError();
                    return;
                }
                try {
                    // stop and reset media player
                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    mMediaPlayer.setDataSource(dataSource);
                    mMediaPlayer.setLooping(true);
                    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mMediaPlayer.start();
                        }
                    });
                    mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                            return false;
                        }
                    });
                    mMediaPlayer.prepare();
                } catch (IOException e) {
                    LogD.i(TAG, "startPlayFirstVideo = " + e.toString());
                }
            }
        };
    }

    private void screenSaverError() {
        if (videoSurfaceCallBack != null) {
            videoSurfaceCallBack.onError();
        }
    }

    public String getVideoPath() {
        return mVideoPath;
    }

    public void setOnVideoPrepareListener(ScreenSaverView.OnVideoPrepareListener onVideoPrepareListener) {
        this.onVideoPrepareListener = onVideoPrepareListener;
    }

    public void setPreviewBitmap(Bitmap bitmap){
        mPreviewBitmap = bitmap;
    }

    public void setVideoPath(String videoPath) {
        mVideoPath = videoPath;

        Bitmap bitmap = mPreviewBitmap;
        if (bitmap != null) {
            int videoWidth = bitmap.getWidth();
            int videoHeight = bitmap.getHeight();
            float max = Math.max((float) videoWidth / (float) 1024,(float) videoHeight / (float) 520);
            videoWidth = (int) Math.ceil((float) videoWidth / max);
            videoHeight = (int) Math.ceil((float) videoHeight / max);
            LogD.d(TAG, "setVideoPath LayoutParams videoWidth:"+videoWidth+" videoHeight:"+videoHeight);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(videoWidth, videoHeight);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            setLayoutParams(layoutParams);
        }
    }

    private VideoSurfaceCallBack videoSurfaceCallBack;

    public void setVideoSurfaceCallBack(VideoSurfaceCallBack videoSurfaceCallBack) {
        this.videoSurfaceCallBack = videoSurfaceCallBack;
    }

    interface VideoSurfaceCallBack {
        void onError();
    }
}
</code>```

I am getting error as,

```<code>   12-23 08:28:11.108  7759  7759 E AndroidRuntime: Process: com.example.custom, PID: 7759
    12-23 08:28:11.108  7759  7759 E AndroidRuntime: java.lang.IllegalStateException
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.media.MediaPlayer._prepare(Native Method)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.media.MediaPlayer.prepare(MediaPlayer.java:1274)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.example.custom.view.VideoSurfaceView$1.onPostExecute(VideoSurfaceView.java:155)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.example.custom.view.VideoSurfaceView$1.onPostExecute(VideoSurfaceView.java:106)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.AsyncTask.finish(AsyncTask.java:755)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.AsyncTask.access$900(AsyncTask.java:192)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:107)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:214)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:7356)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

I am getting error in mMediaPlayer.prepare();. Kindly let me know where exactly I need to fix this issue.

I tried using mMeiaPlayer.perpareAsync too but didn't worked.

答:
You are probably trying to prepare the MediaPlayer when the MediaPlayer is in a wrong state. Check the MediaPlayer State Diagram. The prepare or prepareAsync methods can be called only if the MediaPlayer is in Initialized or Stopped state.

Since the MediaPlayer state is not accessible, you could use this extension to check what's wrong with your MediaPlayer (remember to remove the external player listeners from your code before trying this)

```<code>import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import android.util.Log

class AudioPlayer : MediaPlayer(), MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener {

    enum class AudioPlayerState {
        IDLE,
        INITIALIZED,
        PREPARING,
        PREPARED,
        STARTED,
        STOPPED,
        PAUSED,
        PLAYBACK_COMPLETED,
        ERROR,
        END
    }

    var playerState: AudioPlayerState? = null
        set(value) {
            Log.d(javaClass.name, "Setting new player state $value")
            field = value
        }

    init {
        playerState = AudioPlayerState.IDLE
        setOnPreparedListener(this)
        setOnBufferingUpdateListener(this)
        setOnCompletionListener(this)
        setOnErrorListener(this)
        setOnInfoListener(this)
    }

    override fun setDataSource(context: Context, uri: Uri) {
        if (playerState != AudioPlayerState.IDLE) Log.e(javaClass.name, "Trying to set data source on player state $playerState")
        super.setDataSource(context, uri)
        playerState = AudioPlayerState.INITIALIZED
    }

    override fun prepare() {
        if (playerState != AudioPlayerState.INITIALIZED && playerState != AudioPlayerState.STOPPED) Log.e(javaClass.name, "Trying to prepare on player state $playerState")
        playerState = try {
            super.prepare()
            AudioPlayerState.PREPARED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player prepare ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun prepareAsync() {
        playerState = try {
            super.prepareAsync()
            AudioPlayerState.PREPARING
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player prepare async ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun start() {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to start on player state $playerState")
        playerState = try {
            super.start()
            AudioPlayerState.STARTED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player start ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun stop() {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.STOPPED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to stop on player state $playerState")
        playerState = try {
            super.stop()
            AudioPlayerState.STOPPED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player stop ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun pause() {
        if (playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to pause on player state $playerState")
        playerState = try {
            super.pause()
            AudioPlayerState.PAUSED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player pause ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun seekTo(msec: Int) {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to seek to on player state $playerState")
        try {
            super.seekTo(msec)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player seek to ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
    }

    override fun seekTo(msec: Long, mode: Int) {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to seek to with mode on player state $playerState")
        try {
            super.seekTo(msec, mode)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player seek to with mode ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
    }

    override fun getCurrentPosition(): Int {
        if (playerState == null) return 0
        if (playerState != AudioPlayerState.IDLE &&
            playerState != AudioPlayerState.INITIALIZED &&
            playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.STOPPED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to get current position on player state $playerState")
        try {
            return super.getCurrentPosition()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player current position ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
        return 0
    }

    override fun isPlaying(): Boolean {
        if (playerState == null) return false
        if (playerState != AudioPlayerState.IDLE &&
            playerState != AudioPlayerState.INITIALIZED &&
            playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.STOPPED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to get is playing on player state $playerState")
        try {
            return super.isPlaying()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player is playing ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
        return false
    }

    override fun reset() {
        playerState = try {
            super.reset()
            AudioPlayerState.IDLE
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player reset ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun release() {
        playerState = try {
            super.release()
            AudioPlayerState.END
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player release ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun onPrepared(mp: MediaPlayer?) {
        if (playerState != AudioPlayerState.STARTED) {
            playerState = AudioPlayerState.PREPARED
        }
    }

    override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        return false
    }

    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        playerState = AudioPlayerState.ERROR
        return false
    }

    override fun onCompletion(mp: MediaPlayer?) {
        playerState = AudioPlayerState.PLAYBACK_COMPLETED
        seekTo(0)
    }

    override fun onBufferingUpdate(mp: MediaPlayer?, percent: Int) {

    }
}
</code>```

Body:
I am using a method in asynctask in the class VideoSurfaceView.

But I am getting crash.

I tried other ways too but didn't worked. Below is the code:

......

     public class VideoSurfaceView extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "VideoSurfaceView";

    private MediaPlayer mMediaPlayer;

    private String mVideoPath = "";
    private ScreenSaverView.OnVideoPrepareListener onVideoPrepareListener;

    private Bitmap mPreviewBitmap;

    private boolean locking = false;
    private boolean lockResult = false;
    private boolean reading = false;

    public VideoSurfaceView(Context context) {
        super(context);
        init();
    }

    private void init() {
        LogD.i(TAG, "init");
        SurfaceHolder mSurfaceHolder = getHolder();
        mSurfaceHolder.addCallback(this);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        LogD.i(TAG, "surfaceCreated");
        if (!getVideoPath().isEmpty()) {
            initVideoPlayer();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        LogD.i(TAG, "surfaceChanged");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        LogD.i(TAG, "surfaceDestroyed");
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }

    }

    private void initVideoPlayer() {
        Canvas canvas = getHolder().lockCanvas();
        if (mPreviewBitmap != null && canvas != null) {
            int w = getWidth();
            int h = getHeight();
            Rect src = new Rect(0, 0, mPreviewBitmap.getWidth(), mPreviewBitmap.getHeight());
            Rect dst = new Rect(0, 0, w, h);
            LogD.d(TAG, "drawFirstFrame:view w: " + getWidth() + " h:" + getHeight());
            canvas.drawBitmap(mPreviewBitmap, src, dst, null);
            getHolder().unlockCanvasAndPost(canvas);
        } else if (canvas != null){
            canvas.drawColor(Color.WHITE);
            getHolder().unlockCanvasAndPost(canvas);
        }

        boolean needClose = onVideoPrepareListener.onPrepare();
        if (needClose) {
            LogD.d(TAG, "initVideoPlayer needClose return: ");
            return;
        }

        LogD.i(TAG, "initFirstPlayer()");
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setVolume(0, 0);
        mMediaPlayer.setDisplay(getHolder());
        startPlayFirstVideo();
    }

    private void startPlayFirstVideo() {

        new AsyncTask<Void, Void, FileCacheMediaDataSource>() {

            @Override
            protected FileCacheMediaDataSource doInBackground(Void... voids) {
                locking = true;
                lockResult = false;
                reading = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        LockResult result = LockManager.getInstance().lock(LockReason.DISK_SCREENSAVER_READ_ACCESS);
                        lockResult = result.isLockSuccess();
                        if (!reading && lockResult) {
                            LockManager.getInstance().unlock(LockReason.DISK_SCREENSAVER_READ_ACCESS);
                        }
                        locking = false;
                    }
                }).start();

                String path = AppConst.SCREEN_SAVER_MEDIA_PATH + mVideoPath;
                FileCacheMediaDataSource dataSource = new FileCacheMediaDataSource(path);
                if (!locking && lockResult) {
                    LockManager.getInstance().unlock(LockReason.DISK_SCREENSAVER_READ_ACCESS);
                }
                reading = false;

                return dataSource;
            }

            @Override
            protected void onPostExecute(FileCacheMediaDataSource dataSource) {
                super.onPostExecute(dataSource);
                if (mMediaPlayer == null) {
                    return;
                }
                if (dataSource.getSize() == -1) {
                    LogD.d(TAG, "showErrorScreenSaver");
                    screenSaverError();
                    return;
                }
                try {
                    // stop and reset media player
                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    mMediaPlayer.setDataSource(dataSource);
                    mMediaPlayer.setLooping(true);
                    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mMediaPlayer.start();
                        }
                    });
                    mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                        @Override
                        public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                            return false;
                        }
                    });
                    mMediaPlayer.prepare();
                } catch (IOException e) {
                    LogD.i(TAG, "startPlayFirstVideo = " + e.toString());
                }
            }
        };
    }

    private void screenSaverError() {
        if (videoSurfaceCallBack != null) {
            videoSurfaceCallBack.onError();
        }
    }

    public String getVideoPath() {
        return mVideoPath;
    }

    public void setOnVideoPrepareListener(ScreenSaverView.OnVideoPrepareListener onVideoPrepareListener) {
        this.onVideoPrepareListener = onVideoPrepareListener;
    }

    public void setPreviewBitmap(Bitmap bitmap){
        mPreviewBitmap = bitmap;
    }

    public void setVideoPath(String videoPath) {
        mVideoPath = videoPath;

        Bitmap bitmap = mPreviewBitmap;
        if (bitmap != null) {
            int videoWidth = bitmap.getWidth();
            int videoHeight = bitmap.getHeight();
            float max = Math.max((float) videoWidth / (float) 1024,(float) videoHeight / (float) 520);
            videoWidth = (int) Math.ceil((float) videoWidth / max);
            videoHeight = (int) Math.ceil((float) videoHeight / max);
            LogD.d(TAG, "setVideoPath LayoutParams videoWidth:"+videoWidth+" videoHeight:"+videoHeight);
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(videoWidth, videoHeight);
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
            setLayoutParams(layoutParams);
        }
    }

    private VideoSurfaceCallBack videoSurfaceCallBack;

    public void setVideoSurfaceCallBack(VideoSurfaceCallBack videoSurfaceCallBack) {
        this.videoSurfaceCallBack = videoSurfaceCallBack;
    }

    interface VideoSurfaceCallBack {
        void onError();
    }
}

I am getting error as,

   12-23 08:28:11.108  7759  7759 E AndroidRuntime: Process: com.example.custom, PID: 7759
    12-23 08:28:11.108  7759  7759 E AndroidRuntime: java.lang.IllegalStateException
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.media.MediaPlayer._prepare(Native Method)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.media.MediaPlayer.prepare(MediaPlayer.java:1274)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.example.custom.view.VideoSurfaceView$1.onPostExecute(VideoSurfaceView.java:155)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.example.custom.view.VideoSurfaceView$1.onPostExecute(VideoSurfaceView.java:106)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.AsyncTask.finish(AsyncTask.java:755)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.AsyncTask.access$900(AsyncTask.java:192)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:107)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:214)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:7356)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    12-23 08:28:11.108  7759  7759 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

I am getting error in mMediaPlayer.prepare();. Kindly let me know where exactly I need to fix this issue.

I tried using mMeiaPlayer.perpareAsync too but didn't worked.

Body:
You are probably trying to prepare the MediaPlayer when the MediaPlayer is in a wrong state. Check the MediaPlayer State Diagram. The prepare or prepareAsync methods can be called only if the MediaPlayer is in Initialized or Stopped state.

Since the MediaPlayer state is not accessible, you could use this extension to check what's wrong with your MediaPlayer (remember to remove the external player listeners from your code before trying this)

import android.content.Context
import android.media.MediaPlayer
import android.net.Uri
import android.util.Log

class AudioPlayer : MediaPlayer(), MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener, MediaPlayer.OnPreparedListener {

    enum class AudioPlayerState {
        IDLE,
        INITIALIZED,
        PREPARING,
        PREPARED,
        STARTED,
        STOPPED,
        PAUSED,
        PLAYBACK_COMPLETED,
        ERROR,
        END
    }

    var playerState: AudioPlayerState? = null
        set(value) {
            Log.d(javaClass.name, "Setting new player state $value")
            field = value
        }

    init {
        playerState = AudioPlayerState.IDLE
        setOnPreparedListener(this)
        setOnBufferingUpdateListener(this)
        setOnCompletionListener(this)
        setOnErrorListener(this)
        setOnInfoListener(this)
    }

    override fun setDataSource(context: Context, uri: Uri) {
        if (playerState != AudioPlayerState.IDLE) Log.e(javaClass.name, "Trying to set data source on player state $playerState")
        super.setDataSource(context, uri)
        playerState = AudioPlayerState.INITIALIZED
    }

    override fun prepare() {
        if (playerState != AudioPlayerState.INITIALIZED && playerState != AudioPlayerState.STOPPED) Log.e(javaClass.name, "Trying to prepare on player state $playerState")
        playerState = try {
            super.prepare()
            AudioPlayerState.PREPARED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player prepare ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun prepareAsync() {
        playerState = try {
            super.prepareAsync()
            AudioPlayerState.PREPARING
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player prepare async ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun start() {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to start on player state $playerState")
        playerState = try {
            super.start()
            AudioPlayerState.STARTED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player start ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun stop() {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.STOPPED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to stop on player state $playerState")
        playerState = try {
            super.stop()
            AudioPlayerState.STOPPED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player stop ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun pause() {
        if (playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to pause on player state $playerState")
        playerState = try {
            super.pause()
            AudioPlayerState.PAUSED
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player pause ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun seekTo(msec: Int) {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to seek to on player state $playerState")
        try {
            super.seekTo(msec)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player seek to ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
    }

    override fun seekTo(msec: Long, mode: Int) {
        if (playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to seek to with mode on player state $playerState")
        try {
            super.seekTo(msec, mode)
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player seek to with mode ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
    }

    override fun getCurrentPosition(): Int {
        if (playerState == null) return 0
        if (playerState != AudioPlayerState.IDLE &&
            playerState != AudioPlayerState.INITIALIZED &&
            playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.STOPPED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to get current position on player state $playerState")
        try {
            return super.getCurrentPosition()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player current position ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
        return 0
    }

    override fun isPlaying(): Boolean {
        if (playerState == null) return false
        if (playerState != AudioPlayerState.IDLE &&
            playerState != AudioPlayerState.INITIALIZED &&
            playerState != AudioPlayerState.PREPARED &&
            playerState != AudioPlayerState.STARTED &&
            playerState != AudioPlayerState.PAUSED &&
            playerState != AudioPlayerState.STOPPED &&
            playerState != AudioPlayerState.PLAYBACK_COMPLETED
        ) Log.e(javaClass.name, "Trying to get is playing on player state $playerState")
        try {
            return super.isPlaying()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player is playing ${e.message} with state $playerState")
            playerState = AudioPlayerState.ERROR
        }
        return false
    }

    override fun reset() {
        playerState = try {
            super.reset()
            AudioPlayerState.IDLE
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player reset ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun release() {
        playerState = try {
            super.release()
            AudioPlayerState.END
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e(javaClass.name, "Exception on audio player release ${e.message} with state $playerState")
            AudioPlayerState.ERROR
        }
    }

    override fun onPrepared(mp: MediaPlayer?) {
        if (playerState != AudioPlayerState.STARTED) {
            playerState = AudioPlayerState.PREPARED
        }
    }

    override fun onInfo(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        return false
    }

    override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean {
        playerState = AudioPlayerState.ERROR
        return false
    }

    override fun onCompletion(mp: MediaPlayer?) {
        playerState = AudioPlayerState.PLAYBACK_COMPLETED
        seekTo(0)
    }

    override fun onBufferingUpdate(mp: MediaPlayer?, percent: Int) {

    }
}


来源: stackexchange

问:
Are Rails ActiveRecord object id's guaranteed to be monotonically increasing?
I'd like to be able to return objects in the order they were created. Obviously I could use the created_at field to do this but this will not work in my test scripts where I have stubbed out Time.zone.now to always return the same time.

Does AR guarantee that the next id will always be greater than the last object or is there the possibility that it will reuse deleted ids. I'm pretty sure that databases offer both types of functionality but what does Rails choose by default?

EDIT:

Testing with the SQLite driver suggest that it is monotonic. Even if I delete all the records in the table, close the session, open the session and create more records the id's of the new records are given id's greater than those of the previous deleted objects. However I don't want to rely on empircal evidence here. If someone has a definitive answer on the design intention of ActiveRecord that would be appreciated.

答:
There is no guarantee that the IDs will match the insertion order but you'll usually be safe.

For example: if you have a really large database that has accumulated a lot of holes due to deleted items, you might compact it and reset the underlying sequences (or whatever your database uses to generate the IDs) to recover some unused values. Rails just uses the database's implementation but your DBA (or you with your DBA hat on) is not so constrained.

The IDs should be monotonically increasing over the short term unless you end up using some sort of hateful database that wants you to suffer.

ContentLicense: CC BY-SA 3.0


问:
Can't display or read file object in Javascript
I have file object and I wish to grab the URL.

screenshot of file object on Chrome console

I tried to output the properties like below, but all are giving me "undefined" except type and date.

```<code>      console.log("file: " + file.type);
      console.dir(file.attachment.attributes);
      console.dir(file.attachment.attributes.date);
      console.dir(JSON.stringify(file.attachment.attributes.author));
      console.dir(file.attachment.attributes.width);
</code>```

Here's how the file type looks like as below.

screenshot of file type on Chrome console

Is there something wrong with how I try to read them?

My code is based on WordPress wp-plupload.js that comes with core WordPress. Yeah, I know I shouldn't edit the core codes but I was just experimenting.

UPDATE: Below is the code.

```<code>/**
     * After a file is successfully uploaded, update its model.
     *
     * @param {plupload.Uploader} up       Uploader instance.
     * @param {plupload.File}     file     File that was uploaded.
     * @param {Object}            response Object with response properties.
     */
    fileUploaded = function (up, file, response) {
      var complete;
   // Remove the "uploading" UI elements.
      _.each(["file", "loaded", "size", "percent"], function (key) {
        file.attachment.unset(key);
      });

      file.attachment.set(_.extend(response.data, { uploading: false }));

      wp.media.model.Attachment.get(response.data.id, file.attachment);

      complete = Uploader.queue.all(function (attachment) {
        return !attachment.get("uploading");
      });

      if (complete) {
        Uploader.queue.reset();
      }

      self.success(file.attachment);
    };
</code>```

UPDATE: I just realized the file is NOT a file object after all.

```<code>  $isFile = file instanceof File;
  console.log("File? " + $isFile);
</code>```

I received a "File? false". It's not a blob too! But I still wonder why I can't read the object and get the URL.

答:
Ok, I solved the problem this way. To get the file object, I need to call file.getNative() as stated here -> https://www.plupload.com/docs/v2/File

Thanks to all for your guidance, for without you I would be a lesser coder..

ContentLicense: CC BY-SA 4.0

Body:
I have file object and I wish to grab the URL.

screenshot of file object on Chrome console

I tried to output the properties like below, but all are giving me "undefined" except type and date.

      console.log("file: " + file.type);
      console.dir(file.attachment.attributes);
      console.dir(file.attachment.attributes.date);
      console.dir(JSON.stringify(file.attachment.attributes.author));
      console.dir(file.attachment.attributes.width);

Here's how the file type looks like as below.

screenshot of file type on Chrome console

Is there something wrong with how I try to read them?

My code is based on WordPress wp-plupload.js that comes with core WordPress. Yeah, I know I shouldn't edit the core codes but I was just experimenting.

UPDATE: Below is the code.

/**
     * After a file is successfully uploaded, update its model.
     *
     * @param {plupload.Uploader} up       Uploader instance.
     * @param {plupload.File}     file     File that was uploaded.
     * @param {Object}            response Object with response properties.
     */
    fileUploaded = function (up, file, response) {
      var complete;
   // Remove the "uploading" UI elements.
      _.each(["file", "loaded", "size", "percent"], function (key) {
        file.attachment.unset(key);
      });

      file.attachment.set(_.extend(response.data, { uploading: false }));

      wp.media.model.Attachment.get(response.data.id, file.attachment);

      complete = Uploader.queue.all(function (attachment) {
        return !attachment.get("uploading");
      });

      if (complete) {
        Uploader.queue.reset();
      }

      self.success(file.attachment);
    };

UPDATE: I just realized the file is NOT a file object after all.

  $isFile = file instanceof File;
  console.log("File? " + $isFile);

I received a "File? false". It's not a blob too! But I still wonder why I can't read the object and get the URL.


问:
ARMv7 Assembly How to Read value of each bit
If I have a register that holds a value, how do I read each bit separately and process it in a way to store whether the bit is a 0 or 1? My understanding is to read the first bit, shift right, read first bit, shift right, and repeat until empty. But I can't figure out how to read the bit. I understand shift is just LSR which is easy.</p>

答:
There are multiple ways to achieve this.

You can you a tst instruction:

```<code>tst r0, #4           @ set Z if bit 0x04 is clear in R0
</code>```

You can shift the desired bit out of the register into the carry flag:

```<code>movs r0, r0, lsr #3  @ set C if bit 0x04 was set in R0
</code>```

You can extract the desired bit into a register on its own:

```<code>ubfx r1, r0, #2, #1  @ set R1 to 1 if bit 0x04 is set in R0
</code>```

If you want to do this in a loop to process each bit in sequence, using the C flag (which you can conditionally execute code on with the CS and CC condition codes) is probably the best choice.  For example, to count the bits in R0 you can use code like this:

```<code>        mov    r1, #0          @ initialise counter to zero
loop:   movs   r0, r0, lsr #1  @ shift R0 to the right and set C to its LSB
        addcs  r1, r1, #1      @ increment R1 if C was set
        bne    loop            @ loop until R0 is clear
</code>```

Body:
There are multiple ways to achieve this.

You can you a tst instruction:

tst r0, #4           @ set Z if bit 0x04 is clear in R0

You can shift the desired bit out of the register into the carry flag:

movs r0, r0, lsr #3  @ set C if bit 0x04 was set in R0

You can extract the desired bit into a register on its own:

ubfx r1, r0, #2, #1  @ set R1 to 1 if bit 0x04 is set in R0

If you want to do this in a loop to process each bit in sequence, using the C flag (which you can conditionally execute code on with the CS and CC condition codes) is probably the best choice.  For example, to count the bits in R0 you can use code like this:

        mov    r1, #0          @ initialise counter to zero
loop:   movs   r0, r0, lsr #1  @ shift R0 to the right and set C to its LSB
        addcs  r1, r1, #1      @ increment R1 if C was set
        bne    loop            @ loop until R0 is clear


问:
Moving a sub-directory into the parent of the main directory in C#
I'm looking to figure out how to move a directory out of its parent, into its parents, parent. It sounds a little odd, so I'll visualize it. We have Folder A, B, C, C Being in B, etc. I need to move folder C out of B, and into directory A.

I've already attempted it using this (extractPath is folder A, FolderB is, well folder B):

```<code>Directory.Move(Directory.GetDirectories(extractPath + @"\FolderB")[0],Directory.GetParent(extractPath + @"\FolderB").ToString());
</code>```

However from this error, it appears to be trying to move it:
System.IO.IOException: 'The file 'C:\Users\user\Documents\FolderA\FolderB\FolderC\ExampleFile.png' already exists.'

I should be using Path.Combine rather than adding the two, but I just need it to work, I'll fix that later.

Thanks for your help.

Edit: I rewrote my code to be easier to read, and probably lower the chance of me messing something up

```<code>String newDir = Directory.GetDirectories(extractPath + @"\FolderB")[0]; //Should return folder C
Directory.Move(newDir, extractPath); //Moves folder C to folder A.
``
</code>```

答:
I fixed it! It was a combination of a few minor details but the main issue is this:

I had

```<code>Directory.Move(newDir, extractPath);
</code>```

You've got to add the name of the file of newDir, my original folder im moving.
You can get the name of just that folder with

```<code>Path.GetFileName(newDir);
</code>```

You will then have

```<code>Directory.Move(newDir, extractPath + Path.GetFileName(newDir));
</code>```

Body:
I'm looking to figure out how to move a directory out of its parent, into its parents, parent. It sounds a little odd, so I'll visualize it. We have Folder A, B, C, C Being in B, etc. I need to move folder C out of B, and into directory A.

I've already attempted it using this (extractPath is folder A, FolderB is, well folder B):

Directory.Move(Directory.GetDirectories(extractPath + @"\FolderB")[0],Directory.GetParent(extractPath + @"\FolderB").ToString());

However from this error, it appears to be trying to move it:
System.IO.IOException: 'The file 'C:\Users\user\Documents\FolderA\FolderB\FolderC\ExampleFile.png' already exists.'

I should be using Path.Combine rather than adding the two, but I just need it to work, I'll fix that later.

Thanks for your help.

Edit: I rewrote my code to be easier to read, and probably lower the chance of me messing something up

String newDir = Directory.GetDirectories(extractPath + @"\FolderB")[0]; //Should return folder C
Directory.Move(newDir, extractPath); //Moves folder C to folder A.
``

Body:
I fixed it! It was a combination of a few minor details but the main issue is this:

I had

Directory.Move(newDir, extractPath);

You've got to add the name of the file of newDir, my original folder im moving.
You can get the name of just that folder with

Path.GetFileName(newDir);

You will then have

Directory.Move(newDir, extractPath + Path.GetFileName(newDir));


问:
WPF binding TextBox with ResourceDictionary
I have a TextBox and I made a ResourceDictionary for it for designing purpose. How can I bind it's Text property to its ViewModel in MVVM architecture? The current code is not working.

TextboxTheme.xaml:

```<code><ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type TextBox}" x:Key="ModernTextbox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border CornerRadius="10" Background="#353340" Width="200" Height="30">
                        <Grid>
                            <Rectangle StrokeThickness="1"/>
                            <TextBox Margin="1" BorderThickness="0" Background="Transparent" VerticalContentAlignment="Center" Padding="5" Foreground="#CFCFCF" x:Name="SearchBox"/>
                            <TextBlock IsHitTestVisible="False" Text="{TemplateBinding ToolTip}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" FontSize="11" Foreground="DarkGray" Grid.Column="1">
                                <TextBlock.Style>
                                    <Style TargetType="{x:Type TextBlock}">
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding Text, ElementName=SearchBox}" Value="">
                                                <Setter Property="Visibility" Value="Visible"/>
                                            </DataTrigger>
                                        </Style.Triggers>
                                        <Setter Property="Visibility" Value="Hidden"/>
                                    </Style>
                                </TextBlock.Style>
                            </TextBlock>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>
</code>```

An example for TextBox in the corresponding View (SettingsView.xaml):

```<code><TextBox Text="{Binding DailyCalories}" ToolTip="Napi kalóriamennyiség" Width="250" Height="30" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="2" Style="{StaticResource ModernTextbox}"/>
</code>```

The property in the viewmodel:

```<code>private String _dailyCalories;
public String DailyCalories
{
    get { return _dailyCalories; }
    set
    {
        if (_dailyCalories != value)
        {
            _dailyCalories = value;
            OnPropertyChanged();
        }
    }
}
</code>```

App.xaml:

```<code><Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Theme/TextboxTheme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</code>```

答:
You missed to bind the Text property inside of your template.

It is as simple as

<TextBox
  x:Name="SearchBox"
  Margin="1"
  Padding="5"
  VerticalContentAlignment="Center"
  Background="Transparent"
  BorderThickness="0"
  Foreground="#CFCFCF"
  Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}" />
```

Body:
I have a TextBox and I made a ResourceDictionary for it for designing purpose. How can I bind it's Text property to its ViewModel in MVVM architecture? The current code is not working.

TextboxTheme.xaml:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

                                        <Setter Property="Visibility" Value="Hidden"/>
                                    </Style>
                                </TextBlock.Style>
                            </TextBlock>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

An example for TextBox in the corresponding View (SettingsView.xaml):

<TextBox Text="{Binding DailyCalories}" ToolTip="Napi kalóriamennyiség" Width="250" Height="30" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="2" Style="{StaticResource ModernTextbox}"/>

The property in the viewmodel:

private String _dailyCalories;
public String DailyCalories
{
    get { return _dailyCalories; }
    set
    {
        if (_dailyCalories != value)
        {
            _dailyCalories = value;
            OnPropertyChanged();
        }
    }
}

App.xaml:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Theme/TextboxTheme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>


问:
Is @EntityGraph applied on the Select or the FROM?
I am trying to debug a n+1 query issue and I was trying to use EntityGraphs to solve it.

Say I have the following query

```<code>@Query("select om.organization from OrganizationMember om")
</code>```

And Organization has some extra fields say "attributes"

Would the EntityGraph optimization get applied to the select?

```<code>@EntityGraph(attributePaths = {
  "attributes",
})
@Query("select om.organization from OrganizationMember om")
</code>```

Or should I do it like this?

```<code>@EntityGraph(attributePaths = {
  "organization.attributes",
})
@Query("select om.organization from OrganizationMember om")
</code>```

答:
Did my experiment, it appears to be on the from field.

```<code>@EntityGraph(attributePaths = {
  "organization.attributes",
})
@Query("select om.organization from OrganizationMember om")
</code>```

Doing otherwise would get

org.springframework.dao.InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [attributes] on this ManagedType ...

Body:
I am trying to debug a n+1 query issue and I was trying to use EntityGraphs to solve it.

Say I have the following query

@Query("select om.organization from OrganizationMember om")

And Organization has some extra fields say "attributes"

Would the EntityGraph optimization get applied to the select?

@EntityGraph(attributePaths = {
  "attributes",
})
@Query("select om.organization from OrganizationMember om")

Or should I do it like this?

@EntityGraph(attributePaths = {
  "organization.attributes",
})
@Query("select om.organization from OrganizationMember om")

Body:
Did my experiment, it appears to be on the from field.

@EntityGraph(attributePaths = {
  "organization.attributes",
})
@Query("select om.organization from OrganizationMember om")

Doing otherwise would get

org.springframework.dao.InvalidDataAccessApiUsageException: Unable to locate Attribute  with the the given name [attributes] on this ManagedType ...


问:
How to change background color depending on the day of the week using PHP
I need to change the background color of the header box according to the day of the week. For example if the day is Monday or Wednesday the background of the header should be pink, otherwise it should be blue. I found something like this online but it doesn't work. Also I'm not sure where to put the if statement, in the head or the body part? I put this code in the head part and it didn't work.

$t = date("l");
if ($t == 'Monday' || $t == 'Wednesday') {
    echo "";
} else {
    echo "";
}
```

Anything I found online was with javascript and I don't know js (I'm very new to coding) so I'm not sure If I should learn and use it or try something else.
Thanks for the help in advance.

答:
Unfortunately I don't know PHP, but if you're interested in trying JavaScript, which in this case has some advantages, you can do it like this:</p>
```<code><html>
  <head>
    <script type="text/javascript">
      function setBgColor() {
        const body = document.getElementsByTagName("body")[0];
        const today = new Date().getDay();
        let color;
        if (today == 1 || today == 3) { // Sunday = 0, Monday = 1, etc.
          color = "pink";
        } else {
          color = "blue";
        };
        body.setAttribute("style", "background-color: " + color + ";");
      };
    </script>
  </head>
  <body onload="setBgColor()">
    <p>Hello, world!</p>
  </body>
</html>
</code>```

Body:
I need to change the background color of the header box according to the day of the week. For example if the day is Monday or Wednesday the background of the header should be pink, otherwise it should be blue. I found something like this online but it doesn't work. Also I'm not sure where to put the if statement, in the head or the body part? I put this code in the head part and it didn't work.

$t = date("l");
if ($t == 'Monday' || $t == 'Wednesday') {
    echo "";
} else {
    echo "";
}

Anything I found online was with javascript and I don't know js (I'm very new to coding) so I'm not sure If I should learn and use it or try something else.
Thanks for the help in advance.

Body:
Unfortunately I don't know PHP, but if you're interested in trying JavaScript, which in this case has some advantages, you can do it like this:

<html>
  <head>
    <script type="text/javascript">
      function setBgColor() {
        const body = document.getElementsByTagName("body")[0];
        const today = new Date().getDay();
        let color;
        if (today == 1 || today == 3) { // Sunday = 0, Monday = 1, etc.
          color = "pink";
        } else {
          color = "blue";
        };
        body.setAttribute("style", "background-color: " + color + ";");
      };
    </script>
  </head>
  <body onload="setBgColor()">
    <p>Hello, world!</p>
  </body>
</html>


问:
Invalid constant value in extended class
The following code snippet displays some styled TextFields in a flutter app:

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label0')),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label1')),
          ],
        )));
  }
</code>```

Because I want all my TextFields to look the same I thought of doing this:

```<code>class mTextField extends TextField{
  const mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}
</code>```

To remodel my original code as

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            mTextField(hint: 'Label0'),//simplified here
            SizedBox(height: 20),
            mTextField(hint: 'Label1'),//simplified here
          ],
        )));
  }
</code>```

But this gives me an "invalid constant value" error for the labelText: hint. Of course I could just make the children of the Container non-const, but as far as I see it, it should be possible to have mTextField be constant because it is no different from a regular TextField which can be const.

答:
The const giving the error is the const in the mTextfield not the Column children. You can remove the const in the mTextField

```<code>class mTextField extends TextField{
 mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}
</code>```

Although this will cause the Column const to give the error. You can convert your mTextfield to be built like this instead

```<code>        class mTextField extends StatelessWidget{
     const mTextField({Key? key, this.hint}) : super(key: key);

      final String? hint;

      @override
      Widget build(BuildContext context){
        return TextField(decoration: InputDecoration(labelText: hint));
      }
    }
</code>```

Body:
The following code snippet displays some styled TextFields in a flutter app:

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label0')),
            SizedBox(height: 20),
            TextField(decoration: InputDecoration(labelText: 'Label1')),
          ],
        )));
  }

Because I want all my TextFields to look the same I thought of doing this:

class mTextField extends TextField{
  const mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}

To remodel my original code as

@override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Some input form')),
        body: Container(
          padding: const EdgeInsets.all(32),
            child: Column(
          children: const [
            Placeholder(fallbackHeight: 200, fallbackWidth: 200),
            SizedBox(height: 20),
            mTextField(hint: 'Label0'),//simplified here
            SizedBox(height: 20),
            mTextField(hint: 'Label1'),//simplified here
          ],
        )));
  }

But this gives me an "invalid constant value" error for the labelText: hint. Of course I could just make the children of the Container non-const, but as far as I see it, it should be possible to have mTextField be constant because it is no different from a regular TextField which can be const.

Body:
The const giving the error is the const in the mTextfield not the Column children. You can remove the const in the mTextField

class mTextField extends TextField{
 mTextField({Key? key, String? hint}) : super(key: key, decoration: InputDecoration(labelText: hint));//this line gives the error
}

Although this will cause the Column const to give the error. You can convert your mTextfield to be built like this instead

        class mTextField extends StatelessWidget{
     const mTextField({Key? key, this.hint}) : super(key: key);

      final String? hint;

      @override
      Widget build(BuildContext context){
        return TextField(decoration: InputDecoration(labelText: hint));
      }
    }


问:
Difference between codePointAt and charCodeAt
What is the difference between String.prototype.codePointAt() and String.prototype.charCodeAt() in JavaScript?

```<code>'A'.codePointAt(); // 65
'A'.charCodeAt();  // 65
</code>```

答:
Example in JS

On The example with strings and emojis, I am going to illustrate how things could go wrong when you do not know that some of the characters could consist of 2 code units. Some of the characters take up more than one code unit. Consider using codePointAt() over charCodeAt() or use the first one if you are sure that your characters lie in of between 0 and 65535 (216)

more about code units here

// charCodeAt() is UTF-16
// codePointAt() is Unicode

/* UTF-16 is generally considered a bad idea today */

const strings = ["o", "four", "to"];
const emojis = ["", ""];

function printItemsLength(arr) {
    for (const item of arr) {
    console.log(item, item.length);
  }
}

printItemsLength(strings);
console.log('================================');
printItemsLength(emojis);
console.log('================================');
console.log("i.charCodeAt(0)", "i".charCodeAt(0)); // 105
console.log("i.charCodeAt(1)", "i".charCodeAt(1)); // 105
console.log("i.codePointAt(0)", "i".codePointAt(0)); // 105
console.log('=============EMOJIS=============');
// getting the decimal (dec) by which you can find them

console.log('===========charCodeAt===========');
// "surrogate pair"
console.log(emojis[0] + '.charCodeAt(0)', emojis[0].charCodeAt(0)); // only half-character - 55357
console.log(emojis[0] + '.charCodeAt(1)', emojis[0].charCodeAt(1)); // only half-character - 55357

console.log('===========codePointAt===========');
console.log(emojis[0] + '.codePointAt(0)', emojis[0].codePointAt(0)); // 128014

console.log('===========charCodeAt===========');
// "surrogate pair"
console.log(emojis[1] + '.charCodeAt(0)', emojis[1].charCodeAt(0)); // only half-character - 55357
console.log(emojis[1] + '.charCodeAt(1)', emojis[1].charCodeAt(1)); // only half-character - 55357

console.log('===========codePointAt===========');
// full-character
console.log(emojis[1] + '.codePointAt(0)', emojis[1].codePointAt(0)); // 128095
console.log(emojis[1] + '.codePointAt(1)', emojis[1].codePointAt(1)); // will return lower surragate (non-displayable character)
// to find this emojis have a look here: https://www.w3schools.com/charsets/ref_emoji.asp```

as someone may have noticed I have tried to convert back from charcode to the emoji, and it did not work on one of the symbols (that is because it is not in range of UTF-16

Introduction to Unicode and UTF-16

please skip this section if you already familiar with it

Unicode – is a set of characters used around the world; UTF-16 -
00000000 00100100 for "$" (one 16-bits);11011000 01010010 11011111
01100010 for "" (two 16-bits)
read more

"surrogate pair" characters are emoji and some letters that consist of more than 1 character as it is explained here

The term "surrogate pair" refers to a means of encoding Unicode
characters with high code-points in the UTF-16 encoding scheme. In the
Unicode character encoding, characters are mapped to values between
0x0 and 0x10FFFF.
read more

Unicode - It assigns every character a unique number called a code point.

Differentiating charCodeAt() from codePointAt()

charCodeAt(pos) returns code a code unit (not a full character).

If you need a character (that could be either one or two code units), you can use codePointAt(pos) to get its code.

charCodeAt() - returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index link
codePointAt() - returns a non-negative integer that is the Unicode code point value at the given position link

where pos is the index of the character you want to check.
Quote from the book:

UTF-16 is generally considered a bad idea today. It seems almost
intentionally designed to invite mistakes. It’s easy to write programs
that pretend code units and characters are the same things.

read more

jsfiddle sandbox
Sources:

What is Unicode, UTF-8, UTF-16?

Marijn Haverbeke Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming [Text] – City(not-specified) : No Starch Press, 2018 – 447 p. can be found here

What is "surrogate pair"

to find this emojis have a look w3schools.com/charsets/ref_emoji

Chapter 5, p. 91 => Strings and character codes

Body:
What is the difference between String.prototype.codePointAt() and String.prototype.charCodeAt() in JavaScript?

'A'.codePointAt(); // 65
'A'.charCodeAt();  // 65

Body:
Example in JS

On The example with strings and emojis, I am going to illustrate how things could go wrong when you do not know that some of the characters could consist of 2 code units. Some of the characters take up more than one code unit. Consider using codePointAt() over charCodeAt() or use the first one if you are sure that your characters lie in of between 0 and 65535 (216)

more about code units here

// charCodeAt() is UTF-16
// codePointAt() is Unicode

/* UTF-16 is generally considered a bad idea today */

const strings = ["o", "four", "to"];
const emojis = ["", ""];

function printItemsLength(arr) {
    for (const item of arr) {
    console.log(item, item.length);
  }
}

printItemsLength(strings);
console.log('================================');
printItemsLength(emojis);
console.log('================================');
console.log("i.charCodeAt(0)", "i".charCodeAt(0)); // 105
console.log("i.charCodeAt(1)", "i".charCodeAt(1)); // 105
console.log("i.codePointAt(0)", "i".codePointAt(0)); // 105
console.log('=============EMOJIS=============');
// getting the decimal (dec) by which you can find them

console.log('===========charCodeAt===========');
// "surrogate pair"
console.log(emojis[0] + '.charCodeAt(0)', emojis[0].charCodeAt(0)); // only half-character - 55357
console.log(emojis[0] + '.charCodeAt(1)', emojis[0].charCodeAt(1)); // only half-character - 55357

console.log('===========codePointAt===========');
console.log(emojis[0] + '.codePointAt(0)', emojis[0].codePointAt(0)); // 128014

console.log('===========charCodeAt===========');
// "surrogate pair"
console.log(emojis[1] + '.charCodeAt(0)', emojis[1].charCodeAt(0)); // only half-character - 55357
console.log(emojis[1] + '.charCodeAt(1)', emojis[1].charCodeAt(1)); // only half-character - 55357

console.log('===========codePointAt===========');
// full-character
console.log(emojis[1] + '.codePointAt(0)', emojis[1].codePointAt(0)); // 128095
console.log(emojis[1] + '.codePointAt(1)', emojis[1].codePointAt(1)); // will return lower surragate (non-displayable character)
// to find this emojis have a look here: https://www.w3schools.com/charsets/ref_emoji.asp

as someone may have noticed I have tried to convert back from charcode to the emoji, and it did not work on one of the symbols (that is because it is not in range of UTF-16

Introduction to Unicode and UTF-16

please skip this section if you already familiar with it

Unicode – is a set of characters used around the world; UTF-16 -
00000000 00100100 for "$" (one 16-bits);11011000 01010010 11011111
01100010 for "" (two 16-bits)
read more

"surrogate pair" characters are emoji and some letters that consist of more than 1 character as it is explained here

The term "surrogate pair" refers to a means of encoding Unicode
characters with high code-points in the UTF-16 encoding scheme. In the
Unicode character encoding, characters are mapped to values between
0x0 and 0x10FFFF.
read more

Unicode - It assigns every character a unique number called a code point.

Differentiating charCodeAt() from codePointAt()

charCodeAt(pos) returns code a code unit (not a full character).

If you need a character (that could be either one or two code units), you can use codePointAt(pos) to get its code.

charCodeAt() - returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index link
codePointAt() - returns a non-negative integer that is the Unicode code point value at the given position link

where pos is the index of the character you want to check.
Quote from the book:

UTF-16 is generally considered a bad idea today. It seems almost
intentionally designed to invite mistakes. It’s easy to write programs
that pretend code units and characters are the same things.

read more

jsfiddle sandbox
Sources:

What is Unicode, UTF-8, UTF-16?

Marijn Haverbeke Eloquent JavaScript, 3rd Edition: A Modern Introduction to Programming [Text] – City(not-specified) : No Starch Press, 2018 – 447 p. can be found here

What is "surrogate pair"

to find this emojis have a look w3schools.com/charsets/ref_emoji

Chapter 5, p. 91 => Strings and character codes


问:
How do you write nested routes after dynamic path in React Router v5.2?
I'm trying to write a route that uses a dynamic path and then add an additional parameter after that. The problem is it's being ignored and not rendering my component. As an example the following code works.

```<code><Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}
<Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
</code>```

However, the following doesn't work. This will render the CaseView component in the previous example. This should render the <Sars /> component, but it gets ignored.

Update:

```<code>                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases/:caseToken`} exact component={CaseView} />}
                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases`}><CasesView /></Route>}
                    <Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
                    <Route path={`${SPA_PREFIX}/audit`}><AuditView /></Route>
                    <Route path={`${SPA_PREFIX}/cases/:caseToken/sars`} component={Sars} />
                    <Route path={`${SPA_PREFIX}/settings`}><SettingsView /></Route>
</code>```

What am I doing wrong?

答:
I suspect the issue is just a route ordering issue. I see you are rendering path={`${SPA_PREFIX}/cases/:caseToken`} before path={`${SPA_PREFIX}/cases/:caseToken/sars`}. Remember that when using the Switch component that it renders the first child <Route> or <Redirect> that matches the location. "/cases/:caseToken" is less specific than "/cases/:caseToken/sars" so it matches more URL paths, so if it is found first it will be matched and render the routed component.

Within the Switch you should order the routes in descending order path specificity. If ordered correctly there is a near-zero need to use the exact prop. ${SPA_PREFIX}/cases/:caseToken/sars is more specific than ${SPA_PREFIX}/cases/:caseToken is more specific than ${SPA_PREFIX}/cases, and should be rendered in this order within the Switch component.

There should also be no other components between the Switch and Route or Redirect components for the exclusive route matching to work correctly.

Example:

```<code><Switch>
  <Route
    path={`${SPA_PREFIX}/cases/:caseToken/sars`}
    component={Sars}
  />
  <Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />
  <Route path={`${SPA_PREFIX}/cases`}>
    <CasesView />
  </Route>
  <Route path={`${SPA_PREFIX}/notifications`}>
    <NotificationsView />
  </Route>
  <Route path={`${SPA_PREFIX}/audit`}>
    <AuditView />
  </Route>
  <Route path={`${SPA_PREFIX}/settings`}>
    <SettingsView />
  </Route>
</Switch>
</code>```

Body:
I'm trying to write a route that uses a dynamic path and then add an additional parameter after that. The problem is it's being ignored and not rendering my component. As an example the following code works.

<Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />}
<Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>

However, the following doesn't work. This will render the CaseView component in the previous example. This should render the <Sars /> component, but it gets ignored.

Update:

                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases/:caseToken`} exact component={CaseView} />}
                    {caseManagement
                      && <Route path={`${SPA_PREFIX}/cases`}><CasesView /></Route>}
                    <Route path={`${SPA_PREFIX}/notifications`}><NotificationsView /></Route>
                    <Route path={`${SPA_PREFIX}/audit`}><AuditView /></Route>
                    <Route path={`${SPA_PREFIX}/cases/:caseToken/sars`} component={Sars} />
                    <Route path={`${SPA_PREFIX}/settings`}><SettingsView /></Route>

What am I doing wrong?

Body:
I suspect the issue is just a route ordering issue. I see you are rendering path={`${SPA_PREFIX}/cases/:caseToken`} before path={`${SPA_PREFIX}/cases/:caseToken/sars`}. Remember that when using the Switch component that it renders the first child <Route> or <Redirect> that matches the location. "/cases/:caseToken" is less specific than "/cases/:caseToken/sars" so it matches more URL paths, so if it is found first it will be matched and render the routed component.

Within the Switch you should order the routes in descending order path specificity. If ordered correctly there is a near-zero need to use the exact prop. ${SPA_PREFIX}/cases/:caseToken/sars is more specific than ${SPA_PREFIX}/cases/:caseToken is more specific than ${SPA_PREFIX}/cases, and should be rendered in this order within the Switch component.

There should also be no other components between the Switch and Route or Redirect components for the exclusive route matching to work correctly.

Example:

<Switch>
  <Route
    path={`${SPA_PREFIX}/cases/:caseToken/sars`}
    component={Sars}
  />
  <Route path={`${SPA_PREFIX}/cases/:caseToken`} component={CaseView} />
  <Route path={`${SPA_PREFIX}/cases`}>
    <CasesView />
  </Route>
  <Route path={`${SPA_PREFIX}/notifications`}>
    <NotificationsView />
  </Route>
  <Route path={`${SPA_PREFIX}/audit`}>
    <AuditView />
  </Route>
  <Route path={`${SPA_PREFIX}/settings`}>
    <SettingsView />
  </Route>
</Switch>


问:
Combining an array with multiple columns into a single column using Excel or Python
I am working with a large array of values in Excel. These values are organized vertically (starting at the top for each column) and span across 194 columns. I want to stitch each column together into a single column (so that I can copy/paste all of the values into a separate program for additional calculations). Basically, starting with the first column, I want to take the column on the right and add the values to the column on the left (so that the value at the top of the column being added comes after the value at the bottom of the column preceding it). I want to do this for all columns in the spreadsheet.

I haven't been able to figure out how to do this in Excel or through my Jupyter notebook (after converting the Excel file to a .csv and trying to use a loop to stitch the files together).

Any help would be greatly appreciated!

答:
If you can use Power Query (available in Excel 2010+ and Office 365), you can do it with just a few lines of code.

```<code>let

//change the table name in the next line to the real table name in your worksheet
    Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
    oneCol = Table.FromList(List.Combine(Table.ToColumns(Source)),Splitter.SplitByNothing())
in
    oneCol
</code>```

If your columns do not all have the same number of rows, you may have to RemoveNulls or do some other processing depending on the nature of your data and desired output

eg:

```<code>oneCol=Table.FromList(List.RemoveNulls(List.Combine(Table.ToColumns(Source))),Splitter.SplitByNothing())
</code>```

Body:
If you can use Power Query (available in Excel 2010+ and Office 365), you can do it with just a few lines of code.

let

//change the table name in the next line to the real table name in your worksheet
    Source = Excel.CurrentWorkbook(){[Name="Table3"]}[Content],
    oneCol = Table.FromList(List.Combine(Table.ToColumns(Source)),Splitter.SplitByNothing())
in
    oneCol

If your columns do not all have the same number of rows, you may have to RemoveNulls or do some other processing depending on the nature of your data and desired output

eg:

oneCol=Table.FromList(List.RemoveNulls(List.Combine(Table.ToColumns(Source))),Splitter.SplitByNothing())


问:
Split a single data frame into multiple data frames based on a columns value in pandas
I have a data frame that has thousands of rows in a Jupyter Notebook using Pandas. I am attempting to use a particular column in this data frame to split the df into multiple dfs based on the columns values. If there is a way to do this without specifying the different values in the column explicitly, that would be great.

Col1
Col2
Col3
Col4

dat1
Val1
etc1
set1

dat2
Val2
etc2
set2

dat3
Val3
etc3
set2

dat4
Val4
etc4
set3

An example of one of the variations of my code:

```<code>NAM_df2 = NAM_df1.loc[NAM_df1["Col4"] == 'set2']
</code>```

答:
what about</p>
```<code>df1s = [df.loc[df['Col1']==x, :] for x in df['Col1'].unique()]
df4s = [df.loc[df['Col4']==x, :] for x in df['Col4'].unique()]
</code>```

Body:
I have a data frame that has thousands of rows in a Jupyter Notebook using Pandas. I am attempting to use a particular column in this data frame to split the df into multiple dfs based on the columns values. If there is a way to do this without specifying the different values in the column explicitly, that would be great.

Col1
Col2
Col3
Col4

dat1
Val1
etc1
set1

dat2
Val2
etc2
set2

dat3
Val3
etc3
set2

dat4
Val4
etc4
set3

An example of one of the variations of my code:

NAM_df2 = NAM_df1.loc[NAM_df1["Col4"] == 'set2']

Body:
what about

df1s = [df.loc[df['Col1']==x, :] for x in df['Col1'].unique()]
df4s = [df.loc[df['Col4']==x, :] for x in df['Col4'].unique()]


问:
Moving data from Google Big Query to Azure Data Lake Store using Azure Data Factory
I have a scenario where I need to connect the Azure Data Factory (v2) in Google Big Query for to move data to my Azure Data Lake but I don't work.

When I create a Linked Service, I choose Big Query as Source, I put all informations about BigQuery, as project-name, type of connection, etc but when I click in Validade button a message is show for me: (for exemple)...

UserError: ERROR [28000] [Microsoft][BigQuery] (80) Authentication
  failed: invalid_grant ERROR [28000] [Microsoft][BigQuery] (80)
  Authentication failed: invalid_grant'Type=,Message=ERROR [28000]
  [Microsoft][BigQuery] (80) Authentication failed: invalid_grant ERROR
  [28000] [Microsoft][BigQuery] (80) Authentication failed:
  invalid_grant,Source=,', activityId:
  05ff5ce1-5262-4794-853c-c9e39b7f4b71

Any idea? Someone already tested this connector?

Tks.
Peeter Bonomo

答:
This is the error you get for any access issues unfortunately.  It's also the error you get when your refresh token has expired which it always does after 60 minutes.  Which is incredibly curious....this like so many sets of instructions on OAuth2.0 authentication for ADF never mention all this work is to get a code that expires in 60 minutes.  Without some method of refreshing it everytime you connect this is worthless. At least the following link mentions this error and you get it because the token has expired...its the only blog post (or Microsoft documentation) that bothers to mention this super big issue.  https://medium.com/@varunck/data-transfer-from-google-bigquery-to-azure-blob-storage-using-azure-data-factory-adf-80659c078f83

Here's a different method which is what I will be attempting...it uses service account and IR  https://www.youtube.com/watch?v=oRqRt7ya_DM


问:
Iterating over Map object
I'm new to javascript and I'm trying to understand how to use the Map feature.
I have an array of numbers, and if the value is 0, I want the key of the object to be false, and for any other value; true.</p>

答: Welcome to stackoverflow! What you need to know is that a key is unique in a map object. You have only two keys which are true and false. So, if you try to insert into the map a key that already exists, then it will be updated with the new key/value pair you are setting. This is why you only see two key/value pairs as output. Also as a little side-note when you declare values of array1 since you are working with a single element in each iteration of the loop it would be better to have value of array1 to make the code a little more cleaner.

Title: Iterating over Map object


问:
Unity inspector can't edit public array's values
I want a script that has a public array so that I can modify the values in the inspector. Here's an example script:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Foo : MonoBehaviour
{
    public int[] bars;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}
</code>```

When I add the script to a game object, I can see the empty list in the inspector (as expected).

But when I add elements to the array, the array area is just blank so I can't set the value of each element (or see what the element values are).

Is this just a bug, or am I doing something wrong?

I'm running Unity 2021.2.5f1 on macOS Monterey 12.0.1.

答: I had this same problem after upgrading to a new version of Unity, and I discovered that it works if I move the editor window over to a different screen. Maybe because my main screen is widescreen? I dunno, I can't explain it. If I move the editor back to my main screen, they disappear again. So for now, I just adjust the values on my smaller side-screen, then move back when I'm done. If you don't have more than one screen, perhaps try to change the resolution or something.</p>

Body:
I want a script that has a public array so that I can modify the values in the inspector. Here's an example script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Foo : MonoBehaviour
{
    public int[] bars;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {

    }
}

When I add the script to a game object, I can see the empty list in the inspector (as expected).

But when I add elements to the array, the array area is just blank so I can't set the value of each element (or see what the element values are).

Is this just a bug, or am I doing something wrong?

I'm running Unity 2021.2.5f1 on macOS Monterey 12.0.1.


问:
Escape dot in Helm template
In values.yaml I have:

```<code>key1:
  key2.yaml:
    key3:
    - name
      value
    - name
      value
</code>```

Inside a template, how can I get to key3? {{ .Values.key1.key2.yaml.key3 }}  does not work because key2.yaml in this context corresponds to

```<code>key1:
  key2:
    yaml:
      key3:
      ...
</code>```

Escaping the . with \ results in:

```<code>$ helm template .
Error: parse error at (...): bad character U+005C '\'
</code>```

答:
The core Go text/template language includes an index function, which can look up an arbitrary item in a map by string key (or an array by numeric key).  The key can be any valid template expression, including a string literal.  index can take multiple parameters to do nested lookups.

So, you can use index to do that specific lookup like:

{{ index .Values "key1" "key2.yaml" "key3" }}
```
<p>If that mapping is supposed to be an arbitrary list of files and their contents, the template <code>range</code> function will return the keys and values, and you don't necessarily need the lookups.</p>
<pre class="lang-none prettyprint-override"><code>{{- range $filename, $contents := .Values.key1 }}
$filename: |-
{{ $contents | toYaml | indent 2 }}
{{ end -}}
</code>```

Title: Escape dot in Helm template

Body:
In values.yaml I have:

key1:
  key2.yaml:
    key3:
    - name
      value
    - name
      value

Inside a template, how can I get to key3? {{ .Values.key1.key2.yaml.key3 }}  does not work because key2.yaml in this context corresponds to

key1:
  key2:
    yaml:
      key3:
      ...

Escaping the . with \ results in:

$ helm template .
Error: parse error at (...): bad character U+005C '\'

Body:
The core Go text/template language includes an index function, which can look up an arbitrary item in a map by string key (or an array by numeric key).  The key can be any valid template expression, including a string literal.  index can take multiple parameters to do nested lookups.

So, you can use index to do that specific lookup like:

{{ index .Values "key1" "key2.yaml" "key3" }}

If that mapping is supposed to be an arbitrary list of files and their contents, the template range function will return the keys and values, and you don't necessarily need the lookups.

{{- range $filename, $contents := .Values.key1 }}
$filename: |-
{{ $contents | toYaml | indent 2 }}
{{ end -}}


问:
ImageBackground won't render react native
I'm doing a project in react native and my ImageBackgroud component does not want to render. The odd thing is I am already using ImageBackground in another component and it works there. I tried resizing the image but that didn't help.

Here is my component that renders child component with ImageBackground:

```<code>const DuringStay = () => {

  return (
        <View style={styles.container}>
             <FlatList
              data={test}
              numColumns={2}
              columnWrapperStyle={{
                justifyContent: 'space-between',
                marginBottom: 15,
              }}
              keyExtractor={item => item.id}
              renderItem={({ item }) => (
              <DuringStayTile item={item} />
              )}
            />
        </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 20,
    flex: 1,
  },
});

export default DuringStay;
</code>```

Here is my component that doesn't want to render ImageBackground. My data comes correctly to the component and inside Pressable i can render other components but ImageBackground won't show up

```<code>const DuringStayTile = ({item}) => {
  const { title, uri } = item;
  console.log(title,uri)
  return (
    <Pressable style={styles.container}>
        <ImageBackground source={uri} resizeMode="cover" style={styles.image}>
              <LinearGradient
              style={styles.textBox}
              colors={['transparent','rgba(0,0,0,0.6)']}>
                <Text>
                  {title}
                </Text>
              </LinearGradient>
        </ImageBackground>
    </Pressable>
  );
};

export default DuringStayTile;

const styles = StyleSheet.create({
  container: {
    width: '48%',
    padding: 20,
    borderRadius: 10,
    padding:60,
    backgroundColor:'pink'
  },
  title: {
    fontWeight: 'bold',
    fontSize: 16,
  },
  image: {
    flex: 1,
    overflow:'hidden',
    justifyContent:'center'
  },
  textBox:{
    position:'absolute',
    right:0,
    bottom:0,
    width:'100%'

  },
});
</code>```

Data that is imported:

```<code> export const test = [
  {
      uri:require('../assets/f1.jpg'),
      title: 'Zip Line',
      id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba'
    },
    {
      uri: require('../assets/during.jpeg'),
      title: 'Blue Cave',
     id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    },
    {
      uri: require('../assets/post.jpg'),
      title: 'Rafting',
      id: '58694a0f-3da1-471f-bd96-145571e29d72',
    }
  ]
</code>```

答:
```<code>image: {
    flex: 1,
    overflow:'hidden',
    justifyContent:'center',
 padding:30
  },
</code>```

Body:
I'm doing a project in react native and my ImageBackgroud component does not want to render. The odd thing is I am already using ImageBackground in another component and it works there. I tried resizing the image but that didn't help.

Here is my component that renders child component with ImageBackground:

const DuringStay = () => {

  return (
        <View style={styles.container}>
             <FlatList
              data={test}
              numColumns={2}
              columnWrapperStyle={{
                justifyContent: 'space-between',
                marginBottom: 15,
              }}
              keyExtractor={item => item.id}
              renderItem={({ item }) => (
              <DuringStayTile item={item} />
              )}
            />
        </View>
  );
};

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: 20,
    flex: 1,
  },
});

export default DuringStay;

Here is my component that doesn't want to render ImageBackground. My data comes correctly to the component and inside Pressable i can render other components but ImageBackground won't show up

const DuringStayTile = ({item}) => {
  const { title, uri } = item;
  console.log(title,uri)
  return (
    <Pressable style={styles.container}>
        <ImageBackground source={uri} resizeMode="cover" style={styles.image}>
              <LinearGradient
              style={styles.textBox}
              colors={['transparent','rgba(0,0,0,0.6)']}>
                <Text>
                  {title}
                </Text>
              </LinearGradient>
        </ImageBackground>
    </Pressable>
  );
};

export default DuringStayTile;

const styles = StyleSheet.create({
  container: {
    width: '48%',
    padding: 20,
    borderRadius: 10,
    padding:60,
    backgroundColor:'pink'
  },
  title: {
    fontWeight: 'bold',
    fontSize: 16,
  },
  image: {
    flex: 1,
    overflow:'hidden',
    justifyContent:'center'
  },
  textBox:{
    position:'absolute',
    right:0,
    bottom:0,
    width:'100%'

  },
});

Data that is imported:

 export const test = [
  {
      uri:require('../assets/f1.jpg'),
      title: 'Zip Line',
      id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba'
    },
    {
      uri: require('../assets/during.jpeg'),
      title: 'Blue Cave',
     id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    },
    {
      uri: require('../assets/post.jpg'),
      title: 'Rafting',
      id: '58694a0f-3da1-471f-bd96-145571e29d72',
    }
  ]


问:
Finding element in QList
Suppose I have a struct SignalError which has an element "errName" and many other elements:

```<code>typedef struct SignalError
{
    QString errName;
    .....
};
</code>```

I create QList of this struct:

```<code>QList<SignalError> signalErrList;
</code>```

I will append the struct element to the QList using append call.

```<code>SignalError sgErr1 = {"Error_1"};

signalerrList.append(sgErr1);
</code>```

Before appending the element to the list I want to check if there is any element with the same name "errName" already existing in the QList or not. If it is then I will not add the element to the list.
How do I do this?

Also, should I create a list of objects like:

```<code>QList<SignalError> signalErrList;
</code>```

or create list of pointer to the object:

```<code>QList<SignalError*> signalErrList;
</code>```

答:
You should use QList<SignalError> signalErrList; not a QList of pointers.

If you don’t care about order, you should use a std::set<SignalError> which will give you deduplication automatically.

If you care about order and the O(N) search isn’t a problem, then use QList or std::vector and do

```<code>if (auto it = std::find(signalErrList.begin(), signalErrList.end(), sgErr1;
    it == signalErrList.end()) {
    signalErrList.push_back(std::move(sgErr1));
}
</code>```

which you could (and should) name as a function:

```<code>//! A linear-time (O(n)) search followed by push-back if not found
//! API modeled on https://en.cppreference.com/w/cpp/container/set/emplace
template <typename Container, typename Value>
std::pair<typename Container::iterator, bool>
emplaceBackLinearUnique(Container& c, Value&& v) {
    if (auto it = std::find(c.begin(), c.end(), v); it != c.end()) {
        // Return iterator to the found one and say that it wasn't emplaced.
        return { it, false };
    }
    // Not found:
    c.emplace_back(std::forward<Value>(v));
    // Return iterator to the new last element and report that it was emplaced:
    return { c.begin() + c.size() - 1, true };
}
</code>```

which lets you replace. your use case with this.:

```<code>emplaceBackLinearUnique(signalErrList, sgErr1);
</code>```

Title: Finding element in QList

Body:
Suppose I have a struct SignalError which has an element "errName" and many other elements:

typedef struct SignalError
{
    QString errName;
    .....
};

I create QList of this struct:

QList<SignalError> signalErrList;

I will append the struct element to the QList using append call.

SignalError sgErr1 = {"Error_1"};

signalerrList.append(sgErr1);

Before appending the element to the list I want to check if there is any element with the same name "errName" already existing in the QList or not. If it is then I will not add the element to the list.
How do I do this?

Also, should I create a list of objects like:

QList<SignalError> signalErrList;

or create list of pointer to the object:

QList<SignalError*> signalErrList;

Body:
You should use QList<SignalError> signalErrList; not a QList of pointers.

If you don’t care about order, you should use a std::set<SignalError> which will give you deduplication automatically.

If you care about order and the O(N) search isn’t a problem, then use QList or std::vector and do

if (auto it = std::find(signalErrList.begin(), signalErrList.end(), sgErr1;
    it == signalErrList.end()) {
    signalErrList.push_back(std::move(sgErr1));
}

which you could (and should) name as a function:

//! A linear-time (O(n)) search followed by push-back if not found
//! API modeled on https://en.cppreference.com/w/cpp/container/set/emplace
template <typename Container, typename Value>
std::pair<typename Container::iterator, bool>
emplaceBackLinearUnique(Container& c, Value&& v) {
    if (auto it = std::find(c.begin(), c.end(), v); it != c.end()) {
        // Return iterator to the found one and say that it wasn't emplaced.
        return { it, false };
    }
    // Not found:
    c.emplace_back(std::forward<Value>(v));
    // Return iterator to the new last element and report that it was emplaced:
    return { c.begin() + c.size() - 1, true };
}

which lets you replace. your use case with this.:

emplaceBackLinearUnique(signalErrList, sgErr1);