text:
Q: HTML 5 Section and Main semantic tags use While studying the HTML 5 semantic tags, I've ran upon some doubts on how to proper utilize the main and section tags, and since the W3Schools reference seems a little vague and other references on the Web seems to diverge I would like to know if there is a proper guideline to the following questions or if its pretty much up to the programmer:

*

*Does the main tag also has the meaning of grouping related elements or in that case should it be within a section tag?

*Does it make sense to wrap single elements, such as an image, into a section tag?

*It's pretty common to have a header and footer of the page (not inside any section), in that case, should the remaining in between those tags be wrapped inside a section tag, as if delimiting the "content" of the page?

A:
Does the main tag also has the meaning of grouping related elements

Only to the same extent that <div> groups related elements. The primary purpose of <main> is to indicate where the dominant content of the page starts. (and additionally, according to the WHATWG spec but not the W3C one, where the dominant content of the page resumes).

or in that case should it be within a section tag?

A section tag is one way of grouping your content, to indicate that its contents are on a particular theme, in a way that differs from the content which is not in the section. Typically, you can and should give the section a heading using a <h[1-6]> element, which states what that theme is.

Does it make sense to wrap single elements, such as an image, into a
  section tag?

Rarely. For one thing that would mean that the section didn't contain a heading. See above. It's unlikely that any new information would be conveyed by wrapping an image on its own in a section tag.

It's pretty common to have a header and footer of the page (not inside
  any section), in that case, should the remaining in between those tags
  be wrapped inside a section tag, as if delimiting the "content" of the
  page?

No. The "content" of the section is the section less its header and footer. There's no need to add another sectioning element container.


text:
Q: Por que está dando o erro string indices must be integers? Sou iniciante em python
Estou tentando plotar um gráfico, chamando a função:
def plota_grafico(sistema, resultado, r, variavel)

Como possuo poucas variáveis criei blocos de if dependendo da escolha da variável. Todos eles funcionam corretamente, exceto o bloco a seguir:
  if variavel == 'CMO':
for i, iusi in enumerate(resultado["DGer"]):
  plt.plot(x+1, iusi['CMO'], marker='d')
plt.title('Evolução do Custo Marginal de Operação ($)')
plt.xlabel('Período ou Mês de Planejamento')
plt.ylabel('Custo Marginal de Operação ($)')
plt.xticks(x+1)
plt.grid()
plt.tight_layout()

O erro marca a terceira linha. Se necessário, compartilho o resto do código. Porém ele é extenso, possui outras funções além da plotagem.

A: Esse erro é gerado quando tenta-se acessar uma posição em uma string utilizando outra string (vide link). Como strings não são dicionários, apenas números inteiros podem ser utilizados como índice, retornando a respectiva letra daquela posição.
Não tenho muitos detalhes, então imagino que a variável iusi possa ser (ou conter um valor que seja) uma string, e quando você executa iusi['CMO'], gera o erro, pois tenta-se acessar uma posição indexada por 'CMO' nessa string.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to resolve Media player error(-38,0) I have used media player in my android application.That plays 3gp files but if i play mp4 or other formats it shows MediaPlayer error (-38, 0) and MediaPlayer error (1, -2147483648) errors.can anybody help me to solve this problem?
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {

SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
TextView txtvalue;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    registerBaseActivityReceiver();
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_video_player);

    String value = getIntent().getExtras().getString("url");

    txtvalue=(TextView)findViewById(R.id.value);

    videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
    SurfaceHolder videoHolder = videoSurface.getHolder();
    videoHolder.addCallback(this);

    player = new MediaPlayer();
    controller = new VideoControllerView(this);

    try {
        txtvalue.setText(value);
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(this, Uri.parse(value));
        player.setOnPreparedListener(this);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unRegisterBaseActivityReceiver();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    controller.show();
    return false;
}

// Implement SurfaceHolder.Callback
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Override
public void surfaceCreated(SurfaceHolder holder) {
    player.setDisplay(holder);
    player.prepareAsync();
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}
// End SurfaceHolder.Callback

// Implement MediaPlayer.OnPreparedListener
@Override
public void onPrepared(MediaPlayer mp) {
    controller.setMediaPlayer(this);
    controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
    player.start();
}
// End MediaPlayer.OnPreparedListener

// Implement VideoMediaController.MediaPlayerControl
@Override
public boolean canPause() {
    return true;
}

@Override
public boolean canSeekBackward() {
    return true;
}

@Override
public boolean canSeekForward() {
    return true;
}

@Override
public int getBufferPercentage() {
    return 0;
}

@Override
public int getCurrentPosition() {
    return player.getCurrentPosition();
}

@Override
public int getDuration() {
    return player.getDuration();
}

@Override
public boolean isPlaying() {
    return player.isPlaying();
}

@Override
public void pause() {
    player.pause();
}

@Override
public void seekTo(int i) {
    player.seekTo(i);
}

@Override
public void start() {
    player.start();
}

@Override
public boolean isFullScreen() {
    return false;
}

@Override
public void toggleFullScreen() {

}
// End VideoMediaController.MediaPlayerControl

}
public class VideoControllerView extends FrameLayout {
private static final String TAG = "VideoControllerView";

private MediaPlayerControl  mPlayer;
private Context             mContext;
private ViewGroup           mAnchor;
private View                mRoot;
private ProgressBar         mProgress;
private TextView            mEndTime, mCurrentTime;
private boolean             mShowing;
private boolean             mDragging;
private static final int    sDefaultTimeout = 3000;
private static final int    FADE_OUT = 1;
private static final int    SHOW_PROGRESS = 2;
private boolean             mUseFastForward;
private boolean             mFromXml;
private boolean             mListenersSet;
private View.OnClickListener mNextListener, mPrevListener;
StringBuilder               mFormatBuilder;
Formatter                   mFormatter;
private ImageButton         mPauseButton;
private ImageButton         mFfwdButton;
private ImageButton         mRewButton;
private ImageButton         mNextButton;
private ImageButton         mPrevButton;
private ImageButton         mFullscreenButton;
private Handler             mHandler = new MessageHandler(this);

public VideoControllerView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mRoot = null;
    mContext = context;
    mUseFastForward = true;
    mFromXml = true;

    Log.i(TAG, TAG);
}

public VideoControllerView(Context context, boolean useFastForward) {
    super(context);
    mContext = context;
    mUseFastForward = useFastForward;

    Log.i(TAG, TAG);
}

public VideoControllerView(Context context) {
    this(context, true);

    Log.i(TAG, TAG);
}

@Override
public void onFinishInflate() {
    if (mRoot != null)
        initControllerView(mRoot);
}

public void setMediaPlayer(MediaPlayerControl player) {
    mPlayer = player;
    updatePausePlay();
    updateFullScreen();
}

/**
 * Set the view that acts as the anchor for the control view.
 * This can for example be a VideoView, or your Activity's main view.
 * @param view The view to which to anchor the controller when it is visible.
 */
public void setAnchorView(ViewGroup view) {
    mAnchor = view;

    FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
    );

    removeAllViews();
    View v = makeControllerView();
    addView(v, frameParams);
}

/**
 * Create the view that holds the widgets that control playback.
 * Derived classes can override this to create their own.
 * @return The controller view.
 * @hide This doesn't work as advertised
 */
protected View makeControllerView() {
    LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mRoot = inflate.inflate(R.layout.media_controller, null);

    initControllerView(mRoot);

    return mRoot;
}

private void initControllerView(View v) {
    mPauseButton = (ImageButton) v.findViewById(R.id.pause);
    if (mPauseButton != null) {
        mPauseButton.requestFocus();
        mPauseButton.setOnClickListener(mPauseListener);
    }

    mFullscreenButton = (ImageButton) v.findViewById(R.id.fullscreen);
    if (mFullscreenButton != null) {
        mFullscreenButton.requestFocus();
        mFullscreenButton.setOnClickListener(mFullscreenListener);
    }

    mFfwdButton = (ImageButton) v.findViewById(R.id.ffwd);
    if (mFfwdButton != null) {
        mFfwdButton.setOnClickListener(mFfwdListener);
        if (!mFromXml) {
            mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
        }
    }

    mRewButton = (ImageButton) v.findViewById(R.id.rew);
    if (mRewButton != null) {
        mRewButton.setOnClickListener(mRewListener);
        if (!mFromXml) {
            mRewButton.setVisibility(mUseFastForward ? View.VISIBLE : View.GONE);
        }
    }

    // By default these are hidden. They will be enabled when setPrevNextListeners() is called
    mNextButton = (ImageButton) v.findViewById(R.id.next);
    if (mNextButton != null && !mFromXml && !mListenersSet) {
        mNextButton.setVisibility(View.GONE);
    }
    mPrevButton = (ImageButton) v.findViewById(R.id.prev);
    if (mPrevButton != null && !mFromXml && !mListenersSet) {
        mPrevButton.setVisibility(View.GONE);
    }

    mProgress = (ProgressBar) v.findViewById(R.id.mediacontroller_progress);
    if (mProgress != null) {
        if (mProgress instanceof SeekBar) {
            SeekBar seeker = (SeekBar) mProgress;
            seeker.setOnSeekBarChangeListener(mSeekListener);
        }
        mProgress.setMax(1000);
    }

    mEndTime = (TextView) v.findViewById(R.id.time);
    mCurrentTime = (TextView) v.findViewById(R.id.time_current);
    mFormatBuilder = new StringBuilder();
    mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

    installPrevNextListeners();
}

/**
 * Show the controller on screen. It will go away
 * automatically after 3 seconds of inactivity.
 */
public void show() {
    show(sDefaultTimeout);
}

/**
 * Disable pause or seek buttons if the stream cannot be paused or seeked.
 * This requires the control interface to be a MediaPlayerControlExt
 */
private void disableUnsupportedButtons() {
    if (mPlayer == null) {
        return;
    }

    try {
        if (mPauseButton != null && !mPlayer.canPause()) {
            mPauseButton.setEnabled(false);
        }
        if (mRewButton != null && !mPlayer.canSeekBackward()) {
            mRewButton.setEnabled(false);
        }
        if (mFfwdButton != null && !mPlayer.canSeekForward()) {
            mFfwdButton.setEnabled(false);
        }
    } catch (IncompatibleClassChangeError ex) {
        // We were given an old version of the interface, that doesn't have
        // the canPause/canSeekXYZ methods. This is OK, it just means we
        // assume the media can be paused and seeked, and so we don't disable
        // the buttons.
    }
}

/**
 * Show the controller on screen. It will go away
 * automatically after 'timeout' milliseconds of inactivity.
 * @param timeout The timeout in milliseconds. Use 0 to show
 * the controller until hide() is called.
 */
public void show(int timeout) {
    if (!mShowing && mAnchor != null) {
        setProgress();
        if (mPauseButton != null) {
            mPauseButton.requestFocus();
        }
        disableUnsupportedButtons();

        FrameLayout.LayoutParams tlp = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT,
            Gravity.BOTTOM
        );

        mAnchor.addView(this, tlp);
        mShowing = true;
    }
    updatePausePlay();
    updateFullScreen();

    // cause the progress bar to be updated even if mShowing
    // was already true.  This happens, for example, if we're
    // paused with the progress bar showing the user hits play.
    mHandler.sendEmptyMessage(SHOW_PROGRESS);

    Message msg = mHandler.obtainMessage(FADE_OUT);
    if (timeout != 0) {
        mHandler.removeMessages(FADE_OUT);
        mHandler.sendMessageDelayed(msg, timeout);
    }
}

public boolean isShowing() {
    return mShowing;
}

/**
 * Remove the controller from the screen.
 */
public void hide() {
    if (mAnchor == null) {
        return;
    }

    try {
        mAnchor.removeView(this);
        mHandler.removeMessages(SHOW_PROGRESS);
    } catch (IllegalArgumentException ex) {
        Log.w("MediaController", "already removed");
    }
    mShowing = false;
}

private String stringForTime(int timeMs) {
    int totalSeconds = timeMs / 1000;

    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours   = totalSeconds / 3600;

    mFormatBuilder.setLength(0);
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}

private int setProgress() {
    if (mPlayer == null || mDragging) {
        return 0;
    }

    int position = mPlayer.getCurrentPosition();
    int duration = mPlayer.getDuration();
    if (mProgress != null) {
        if (duration > 0) {
            // use long to avoid overflow
            long pos = 1000L * position / duration;
            mProgress.setProgress( (int) pos);
        }
        int percent = mPlayer.getBufferPercentage();
        mProgress.setSecondaryProgress(percent * 10);
    }

    if (mEndTime != null)
        mEndTime.setText(stringForTime(duration));
    if (mCurrentTime != null)
        mCurrentTime.setText(stringForTime(position));

    return position;
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    show(sDefaultTimeout);
    return true;
}

@Override
public boolean onTrackballEvent(MotionEvent ev) {
    show(sDefaultTimeout);
    return false;
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (mPlayer == null) {
        return true;
    }

    int keyCode = event.getKeyCode();
    final boolean uniqueDown = event.getRepeatCount() == 0
            && event.getAction() == KeyEvent.ACTION_DOWN;
    if (keyCode ==  KeyEvent.KEYCODE_HEADSETHOOK
            || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
            || keyCode == KeyEvent.KEYCODE_SPACE) {
        if (uniqueDown) {
            doPauseResume();
            show(sDefaultTimeout);
            if (mPauseButton != null) {
                mPauseButton.requestFocus();
            }
        }
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
        if (uniqueDown && !mPlayer.isPlaying()) {
            mPlayer.start();
            updatePausePlay();
            show(sDefaultTimeout);
        }
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
            || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
        if (uniqueDown && mPlayer.isPlaying()) {
            mPlayer.pause();
            updatePausePlay();
            show(sDefaultTimeout);
        }
        return true;
    } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
            || keyCode == KeyEvent.KEYCODE_VOLUME_UP
            || keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) {
        // don't show the controls for volume adjustment
        return super.dispatchKeyEvent(event);
    } else if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_MENU) {
        if (uniqueDown) {
            hide();
        }
        return true;
    }

    show(sDefaultTimeout);
    return super.dispatchKeyEvent(event);
}

private View.OnClickListener mPauseListener = new View.OnClickListener() {
    public void onClick(View v) {
        doPauseResume();
        show(sDefaultTimeout);
    }
};

private View.OnClickListener mFullscreenListener = new View.OnClickListener() {
    public void onClick(View v) {
        doToggleFullscreen();
        show(sDefaultTimeout);
    }
};

public void updatePausePlay() {
    if (mRoot == null || mPauseButton == null || mPlayer == null) {
        return;
    }

    if (mPlayer.isPlaying()) {
        mPauseButton.setImageResource(R.drawable.ic_media_pause);
    } else {
        mPauseButton.setImageResource(R.drawable.ic_media_play);
    }
}

public void updateFullScreen() {
    if (mRoot == null || mFullscreenButton == null || mPlayer == null) {
        return;
    }

    if (mPlayer.isFullScreen()) {
        mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_shrink);
    }
    else {
        mFullscreenButton.setImageResource(R.drawable.ic_media_fullscreen_stretch);
    }
}

private void doPauseResume() {
    if (mPlayer == null) {
        return;
    }

    if (mPlayer.isPlaying()) {
        mPlayer.pause();
    } else {
        mPlayer.start();
    }
    updatePausePlay();
}

private void doToggleFullscreen() {
    if (mPlayer == null) {
        return;
    }

    mPlayer.toggleFullScreen();
}

// There are two scenarios that can trigger the seekbar listener to trigger:
//
// The first is the user using the touchpad to adjust the posititon of the
// seekbar's thumb. In this case onStartTrackingTouch is called followed by
// a number of onProgressChanged notifications, concluded by onStopTrackingTouch.
// We're setting the field "mDragging" to true for the duration of the dragging
// session to avoid jumps in the position in case of ongoing playback.
//
// The second scenario involves the user operating the scroll ball, in this
// case there WON'T BE onStartTrackingTouch/onStopTrackingTouch notifications,
// we will simply apply the updated position without suspending regular updates.
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
    public void onStartTrackingTouch(SeekBar bar) {
        show(3600000);

        mDragging = true;

        // By removing these pending progress messages we make sure
        // that a) we won't update the progress while the user adjusts
        // the seekbar and b) once the user is done dragging the thumb
        // we will post one of these messages to the queue again and
        // this ensures that there will be exactly one message queued up.
        mHandler.removeMessages(SHOW_PROGRESS);
    }

    public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
        if (mPlayer == null) {
            return;
        }

        if (!fromuser) {
            // We're not interested in programmatically generated changes to
            // the progress bar's position.
            return;
        }

        long duration = mPlayer.getDuration();
        long newposition = (duration * progress) / 1000L;
        mPlayer.seekTo( (int) newposition);
        if (mCurrentTime != null)
            mCurrentTime.setText(stringForTime( (int) newposition));
    }

    public void onStopTrackingTouch(SeekBar bar) {
        mDragging = false;
        setProgress();
        updatePausePlay();
        show(sDefaultTimeout);

        // Ensure that progress is properly updated in the future,
        // the call to show() does not guarantee this because it is a
        // no-op if we are already showing.
        mHandler.sendEmptyMessage(SHOW_PROGRESS);
    }
};

@Override
public void setEnabled(boolean enabled) {
    if (mPauseButton != null) {
        mPauseButton.setEnabled(enabled);
    }
    if (mFfwdButton != null) {
        mFfwdButton.setEnabled(enabled);
    }
    if (mRewButton != null) {
        mRewButton.setEnabled(enabled);
    }
    if (mNextButton != null) {
        mNextButton.setEnabled(enabled && mNextListener != null);
    }
    if (mPrevButton != null) {
        mPrevButton.setEnabled(enabled && mPrevListener != null);
    }
    if (mProgress != null) {
        mProgress.setEnabled(enabled);
    }
    disableUnsupportedButtons();
    super.setEnabled(enabled);
}

private View.OnClickListener mRewListener = new View.OnClickListener() {
    public void onClick(View v) {
        if (mPlayer == null) {
            return;
        }

        int pos = mPlayer.getCurrentPosition();
        pos -= 5000; // milliseconds
        mPlayer.seekTo(pos);
        setProgress();

        show(sDefaultTimeout);
    }
};

private View.OnClickListener mFfwdListener = new View.OnClickListener() {
    public void onClick(View v) {
        if (mPlayer == null) {
            return;
        }

        int pos = mPlayer.getCurrentPosition();
        pos += 15000; // milliseconds
        mPlayer.seekTo(pos);
        setProgress();

        show(sDefaultTimeout);
    }
};

private void installPrevNextListeners() {
    if (mNextButton != null) {
        mNextButton.setOnClickListener(mNextListener);
        mNextButton.setEnabled(mNextListener != null);
    }

    if (mPrevButton != null) {
        mPrevButton.setOnClickListener(mPrevListener);
        mPrevButton.setEnabled(mPrevListener != null);
    }
}

public void setPrevNextListeners(View.OnClickListener next, View.OnClickListener prev) {
    mNextListener = next;
    mPrevListener = prev;
    mListenersSet = true;

    if (mRoot != null) {
        installPrevNextListeners();

        if (mNextButton != null && !mFromXml) {
            mNextButton.setVisibility(View.VISIBLE);
        }
        if (mPrevButton != null && !mFromXml) {
            mPrevButton.setVisibility(View.VISIBLE);
        }
    }
}

public interface MediaPlayerControl {
    void    start();
    void    pause();
    int     getDuration();
    int     getCurrentPosition();
    void    seekTo(int pos);
    boolean isPlaying();
    int     getBufferPercentage();
    boolean canPause();
    boolean canSeekBackward();
    boolean canSeekForward();
    boolean isFullScreen();
    void    toggleFullScreen();
}

private static class MessageHandler extends Handler {
    private final WeakReference<VideoControllerView> mView;

    MessageHandler(VideoControllerView view) {
        mView = new WeakReference<VideoControllerView>(view);
    }
    @Override
    public void handleMessage(Message msg) {
        VideoControllerView view = mView.get();
        if (view == null || view.mPlayer == null) {
            return;
        }

        int pos;
        switch (msg.what) {
            case FADE_OUT:
                view.hide();
                break;
            case SHOW_PROGRESS:
                pos = view.setProgress();
                if (!view.mDragging && view.mShowing && view.mPlayer.isPlaying()) {
                    msg = obtainMessage(SHOW_PROGRESS);
                    sendMessageDelayed(msg, 1000 - (pos % 1000));
                }
                break;
        }
    }
}

}

A: The error no. -38 corresponds to INVALID_OPERATION from MediaPlayer::start. Please note that INVALID_OPERATION is set to -ENOSYS which is -38 from errno.h.
You may have to investigate why your MediaPlayer is in an erroneous state.
You seem to try to start the playing before the preparation is complete. Use the setOnPreparedListener() method to set a preparation listener and call the start() method only after the preparation is complete.
  mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
   public void onPrepared(MediaPlayer mp) {
     mp.start();
   }
    });
   mediaPlayer.prepareAsync();

And remove the current mediaPlayer.start() invocation from the code.

A: Are you sure it is the only scenario you get this error?
You need to set more listeners on the player so you could get more details:
essentials is the following:
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            Log.i("VideoPlayerManager", "Error code (what): " + what);
            if (what == 100) {
                mVideoView.stopPlayback();
                mVideoView.start();
                enforcedStop = true;
            } else if (what == 1) {
                mVideoView.stopPlayback();
                mVideoView.start();
                enforcedStop = true;

            } else if (what == 800) {
                mVideoView.stopPlayback();
                mVideoView.start();
                enforcedStop = true;

            } else if (what == 701) {
                mVideoView.stopPlayback();
                mVideoView.start();
                enforcedStop = true;

            } else if (what == 700) {
                mVideoView.stopPlayback();
                mVideoView.start();
                enforcedStop = true;
            } else if (what == -38) {
                mVideoView.stopPlayback();
                mVideoView.start();
                enforcedStop = true;
            }
            return false;
        }
    });

Another ones should be the oncompletion listener as follows:
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (enforcedStop) {
                enforcedStop = false;
                return;
            }
            // setLooping(true) did not work, so we use this 2 lines of code
            mediaPlayer.seekTo(0);
            mediaPlayer.start();
        }
    });


text:
Q: Inserting survey data to mySql database in jsp/servlet I have created survey form and trying to insert multiple question at a time in database but it showing null pointer error.I have dynamically created the field
jsp file: here, I am creating survey question on clicking show priview button it is added to preview div.By this i am creating multiple questions then submitted to database by clicking on save button
    <form method="post" action="getSurvey">

            Enter Survey Title
            <input type="text" id="surveyName" name="surveyName[]" >

            Enter Question
            <input type="text" id="surveyQuestion" name="surveyQuestion[]" >
            <select name="answerType" id="answerType" class="selectPicker" >
                <option selected="selected">None</option>
                <option value="multiple">Multiple Choice type</option>
                <option value="single">Single Choice Type</option>
                <option value="short">Short Answer Type</option>
            </select>

            <button type="button"  id="showPreview" name="showPreview" class="button">Show Preview</button>

            <input type="submit" name="saveSurvey" id="saveSurvey" value="Save" class="button" >

Preview

    </form>

jquery: to generate fields dynamically

        $(document).ready(function(){
    var questionCounter=1;
    const $previewid = $('#preview');
    $("select.selectPicker").change(function(){
        var option = $(this).children("option:selected").val();
        if(option=="multiple")
            $.fn.callMultiple();
        else if(option=="single")
            $.fn.callSingle();
        else if(option=="short")
            $.fn.callShort();
        else
            alert("Please select from options");
    });
    $.fn.callMultiple = function() {
        $('#newSurvey').empty();
        var selectType = $('#answerType').val();
        let newrow='<input type="checkbox" name="check1"><input type="text" id="t1" name="txt1[]">
'+
                    '<input type="checkbox" name="check2"><input type="text" id="t2" name="txt2[]">
'+
                    '<input type="checkbox" name="check3"><input type="text" id="t3" name="txt3[]">
'+
                    '<input type="checkbox" name="check4"><input type="text" id="t4" name="txt4[]">
';+
                    '<input type="hidden" name="stype[]" id="stype" value="'+selectType+'">';
        $('#newSurvey').append(newrow);
      }
    $.fn.callSingle = function() {
        $('#newSurvey').empty();
        var selectType = $('#answerType').val();
        let newrow='<input type="radio" name="radioval"><input type="text" id="t1" name="txt1[]">
'+
        '<input type="radio" name="radioval"><input type="text" id="t2" name="txt2[]">
'+
        '<input type="radio" name="radioval"><input type="text" id="t3" name="txt3[]">
'+
        '<input type="radio" name="radioval"><input type="text" id="t4" name="txt4[]">
';+
        '<input type="hidden" name="stype[]" id="stype" value="'+selectType+'">';
        $('#newSurvey').append(newrow);
      }
    $.fn.callShort = function() {
        $('#newSurvey').empty();
        var selectType = $('#answerType').val();
        let newrow='<input type="text" name="shortanswer[]" id="shortanswer">';+
        '<input type="hidden" name="stype[]" id="stype" value="'+selectType+'">';
        $('#newSurvey').append(newrow);
      }

    $('#showPreview').on('click',function(e){
        questionCounter++;
        var title = $('#surveyName').val();
        var question = $('#surveyQuestion').val();
        var uprow='
<input type="text" id="surveyName" name="surveyName[]" value='+title+' readonly>
'+
        ' <input type="text" id="surveyQuestion" name="surveyQuestion[]" value='+question+' readonly>

';
        const $firstRow = $('#newSurvey').find("*");
        let $newrowhtml = $firstRow.clone(true);
        $('#section1').find(":input").val("");
        $previewid.prepend($newrowhtml);
        $previewid.prepend(uprow);
        $previewid.find(":input").attr('readonly','readonly');
    });
});

servlet I am trying to save data which are part of preview div in jsp file
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    PrintWriter out = response.getWriter();
    String surveyTitle[] = request.getParameterValues("surveyName[]");
    String question[] = request.getParameterValues("surveyQuestion[]");
    String[] option1, option2, option3, option4, single;
    int row1=0,row2=0;
    int i;
    option1=option2=option3=option4=single=null;

    option1=request.getParameterValues("txt1[]");
    option2=request.getParameterValues("txt2[]");
    option3=request.getParameterValues("txt3[]");
    option4=request.getParameterValues("txt4[]");
    String selectType[]=request.getParameterValues("stype[]");
    out.println(selectType.length);
    for( i=0;i<selectType.length;i++)
        out.println(selectType[i]+" "+i);
    if(request.getParameterValues("shortanswer[]") != null)
    {
        single=request.getParameterValues("shortanswer[]");
    }
    for( i=0;i<single.length;i++)
        out.println(single[i]+" "+i);
    String[] op1,op2,op3,op4,ans;
    op1=op2=op3=op4=ans=null;
    int k=0,j=0;
    for(i=1;i<surveyTitle.length;i++)
    {
        if((selectType[i].equals("multiple"))||selectType[i].equals("single"))
        {
            op1[i]=option1[j];
            op2[i]=option2[j];
            op3[i]=option3[j];
            op4[i]=option4[j];
            ans[i]=null;
            j++;
        }
        else if(selectType.equals("short"))
        {
            op1[i]=null;
            op2[i]=null;
            op3[i]=null;
            op4[i]=null;
            ans[i]=single[k];
            k++;
        }
        out.println(op1[i]+""+op2[i]+""+op3[i]+""+op4[i]+""+ans[i]);
    }
    try
    {
        Class.forName(JDBC_Driver);
        con = DriverManager.getConnection(URL, username, password);
        for(i=1;i<surveyTitle.length;i++)
        {
            if((selectType[i].equals("multiple"))||selectType[i].equals("single"))
            {
                query1 ="insert into surveydetail (surveyTitle,questionName,optionOne,optionTwo,optionThree,optionFour,selectType) values (?,?,?,?,?,?,?)";
                pstmt1 = con.prepareStatement(query1);
                pstmt1.clearParameters();
                pstmt1.setString(1, surveyTitle[i]);
                pstmt1.setString(2, question[i]);
                pstmt1.setString(3, op1[i]);
                pstmt1.setString(4, op2[i]);
                pstmt1.setString(5, op3[i]);
                pstmt1.setString(6, op4[i]);
                pstmt1.setString(7, selectType[i]);
                row1=pstmt1.executeUpdate();
            }
            else if(selectType.equals("short"))
            {
                query2 ="insert into surveydetail (surveyTitle,questionName,shortAnswer,selectType) values (?,?,?,?)";
                pstmt2 = con.prepareStatement(query2);
                pstmt2.clearParameters();
                pstmt2.setString(1, surveyTitle[i]);
                pstmt2.setString(2, question[i]);
                pstmt2.setString(3, ans[i]);
                pstmt2.setString(4, selectType[i]);
                row2=pstmt1.executeUpdate();
            }
        }
        if((row1>0)||(row2>0))
        {
            response.sendRedirect("CreateSurveyView.jsp");
        }
        else
        {
            response.sendRedirect("Error.jsp");
        }
    }
    catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

A: In your jsp code you have not added any inputs which will identify whether the select-type is single,short or multiple .Now to add that simply when user will select any option from dropdown you can just append a hidden input with the radios or checkboxes.
Some changes you need to make in jsp and jquery :

  <form method="post" action="getSurvey">

           <input type="submit" name="saveSurvey" id="saveSurvey" value="Save" class="button" >

Preview

  </form>

Jquery code :
$(document).ready(function() {
  var questionCounter = 1;
  $("select.selectPicker").change(function() {
    //your codes
  });
  $.fn.callMultiple = function() {
    $('#newSurvey').empty();
    //added hidden input with name="answerType1[]"
    var newrow = '<input type="hidden" name="answerType1[]" value="multiple"/>' +
      '<input type="checkbox" name="check1"><input type="text" id="t1_" name="txt1[]">
' +
      '<input type="checkbox" name="check2"><input type="text" id="t2" name="txt2[]">
' +
      '<input type="checkbox" name="check3"><input type="text" id="t3" name="txt3[]">
' +
      '<input type="checkbox" name="check4"><input type="text" id="t4" name="txt4[]">
';
    $('#newSurvey').append(newrow);
  }
  $.fn.callSingle = function() {
    $('#newSurvey').empty();
    //added hidden input with name="answerType1[]"
    var newrow =  '<input type="hidden" name="answerType1[]" value="single"/>' +
      '<input type="radio" name="radioval"><input type="text" id="t1" name="txt1[]">
' +
      '<input type="radio" name="radioval"><input type="text" id="t2" name="txt2[]">
' +
      '<input type="radio" name="radioval"><input type="text" id="t3" name="txt3[]">
' +
      '<input type="radio" name="radioval"><input type="text" id="t4" name="txt4[]">
';
    $('#newSurvey').append(newrow);
  }
  $.fn.callShort = function() {
    $('#newSurvey').empty();
    //added hidden input with name="answerType1[]"
    var newrow = '<input type="hidden" name="answerType1[]" value="short"/>' + '<input type="text" name="txt[]" id="t1">';
    $('#newSurvey').append(newrow);
  }
//other codes
});

Now ,  in your servlet code do below changes :
 String surveyTitle[] = request.getParameterValues("surveyName[]");
 String question[] = request.getParameterValues("surveyQuestion[]");

 String[] option1, option2, option3, option4, answer;
 int row1 = 0, row2 = 0;
 int i;
 PreparedStatement pstmt1, pstmt2;
 option1 = option2 = option3 = option4 = answer = null;
 //if txt1[] not null get values
 if (request.getParameterValues("txt1[]") != null) {
  option1 = request.getParameterValues("txt1[]");
  option2 = request.getParameterValues("txt2[]");
  option3 = request.getParameterValues("txt3[]");
  option4 = request.getParameterValues("txt4[]");
 }
 //if txt[] "short ans" is not null get value
 if (request.getParameterValues("txt[]") != null) {
  answer = request.getParameterValues("txt[]");

 }
 //get select type
 String selectType[] = request.getParameterValues("answerType1[]");
 //for answer
 int j = 0;

 try {
  Class.forName(JDBC_Driver);
  con = DriverManager.getConnection(URL, username, password);
  out.println(question.length); //seeing length of question
  //looping through question array
  for (i = 0; i < question.length; i++) {
   //chcking the selecttype
   if ((selectType[i].equals("multiple")) || (selectType[i].equals("single"))) {
    //insert
    String query1 = "insert into surveydetail (surveyTitle,questionName,optionOne,optionTwo,optionThree,optionFour,selectType) values (?,?,?,?,?,?,?)";
    pstmt1 = con.prepareStatement(query1);
    pstmt1.clearParameters();
    pstmt1.setString(1, surveyTitle[i]);
    pstmt1.setString(2, question[i]);
    pstmt1.setString(3, option1[i]);
    pstmt1.setString(4, option2[i]);
    pstmt1.setString(5, option3[i]);
    pstmt1.setString(6, option4[i]);
    pstmt1.setString(7, selectType[i]);
    out.println("  " + surveyTitle[i] + " " + question[i] + " " + option1[i] + "  " + option2[i] + " " + option3[i] + " " + option4[i] + " " + selectType[i]);
    row1 = pstmt1.executeUpdate();
   } else if (selectType[i].equals("short")) {
    //insert
    String query2 = "insert into surveydetail (surveyTitle,questionName,shortAnswer,selectType) values (?,?,?,?)";
    pstmt2 = con.prepareStatement(query2);
    pstmt2.clearParameters();
    pstmt2.setString(1, surveyTitle[i]);
    pstmt2.setString(2, question[i]);
    pstmt2.setString(3, answer[j]);//here we will pass "j" value
    pstmt2.setString(4, selectType[i]);
    row2 = pstmt2.executeUpdate();
    out.println("  " + surveyTitle[i] + " " + question[i] + "  " + answer[j] + " " + selectType[i]);
    j++;
   }
  }
  if ((row1 > 0) || (row2 > 0)) {
   response.sendRedirect("CreateSurveyView.jsp");
  } else {
     response.sendRedirect("Error.jsp");
  }
 } catch (Exception e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }

(Above codes are already tested with database and working fine)


text:
Q: Automapper unmapped properties error with simple objects mappings I need to map a model object coming from API to my actual entity object on DbContext. It is used when creating a new machine object using a POST action.
As always, I created a simple map for the source/destination objects.
In this case we consider the source object as the API model and the destination object as the entity. Also the model has just a subset of properties of the entity.
Source/destination types
// Destination (entity on DbContext)
public class Machine
{
    public long Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string MnmConfiguration { get; set; }
    public MachineBootStatus Status { get; set; }
    public long MachineDriverId { get; set; }
    public MachineDriver MachineDriver { get; set; }
    public string DriverConfiguration { get; set; }
    public string DriverStatus { get; set; }
}

// Source (from API controller)
public class MachineCreateModel
{
    public string Name { get; set; }
    public string Description { get; set; }
    public string MnmConfiguration { get; set; }
    public long MachineDriverId { get; set; }
}

Mapping configuration
public class DomainProfile : Profile
{
    public DomainProfile()
    {
        //CreateMap<MachineCreateModel, Machine>();
        // Update 2019/01/30 with proposed solution
        CreateMap<MachineCreateModel, Machine>(MemberList.Source);
    }
}

I'm using Unity DI container and the configuration of AutoMapper is this:
container = new UnityContainer();
// ... some other configurations...
container.RegisterType<IMapper, Mapper>(new InjectionConstructor(new MapperConfiguration(cfg => cfg.AddProfile<DomainProfile>())));

Version
Using AutoMapper v8.0.0.
Expected behavior
I expect to obtain a simple automatic mapping without errors, since my source model is just a subset of properties of the destination model, with same names.
Actual behavior
I get this error about unmapped properties when I hit this line of code:
Machine entity = Mapper.Map<Machine>(request.Machine);

[14:08:34.363 8 2e62361a INF] Creating new machine: TEST M1
[14:08:36.205 8 bd577466 ERR] An unhandled exception has occurred while executing the request.
AutoMapper.AutoMapperConfigurationException:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
=================================================================================================
AutoMapper created this type map for you, but your types cannot be mapped using the current configuration.
MachineCreateModel -> Machine (Destination member list)
MyApplication.Dcs.Application.Models.MachineCreateModel -> MyApplication.Dcs.Domain.Entities.Machine (Destination member list)

Unmapped properties:
Id
Status
MachineDriver
DriverConfiguration
DriverStatus

   at AutoMapper.ConfigurationValidator.AssertConfigurationIsValid(IEnumerable`1 typeMaps)
   at lambda_method(Closure , MachineCreateModel , Machine , ResolutionContext )
   at lambda_method(Closure , Object , Object , ResolutionContext )
   at AutoMapper.Mapper.AutoMapper.IMapper.Map[TDestination](Object source)
   at MyApplication.Dcs.Application.Commands.MachineCreateCommandHandler.Handle(MachineCreateCommand request, CancellationToken cancellationToken) ..Commands\MachineCreateCommand.cs:line 28

Note
In my solution I've many projects and 3 of them are making use of AutoMapper (same version for all). There're 3 different DomainProfile.cs files (1 for each project) with the needed mappings.
In the other 2 DomainProfile classes I've some manual mappings (see example below) because I need to "translate" an object with italian property names to another one with english property names. So there're many lines for each object mapping, such as:
CreateMap<ArticleCreateUpdateModel, Articoli>()
    .ForMember(d => d.Categoria, opt => opt.MapFrom(src => src.Category))
    .ForMember(d => d.CodiceArticolo, opt => opt.MapFrom(src => src.Code))
    .ForMember(d => d.Descrizione, opt => opt.MapFrom(src => src.Description))
    .ForMember(d => d.Famiglia, opt => opt.MapFrom(src => src.Family))
    .ForMember(d => d.Note, opt => opt.MapFrom(src => src.Note))
    ...

I don't know if the usage of those manual members mapping on one or more DomainProfile class, obliges me in some way to always explain all the subsequent mappings, even if they should be simple like those of this example.

A: By default, AutoMapper validates the destination properties. As there are neither matching properties nor ForMember constructs for a bunch of properties in your destination type you get the exception above.
Try to validate on the source properties instead:
CreateMap<ArticleCreateUpdateModel, Articoli>(MemberList.Source)
    .ForMember(d => d.Categoria, opt => opt.MapFrom(src => src.Category))
    // ...

Remark:
On the other hand, I have to mention that this is the typical case when AutoMapper is an overkill. Apart from trivial cases I would never use it anymore.
I had to use it in a project for more than a year but actually it is only good for making simple things more complicated than necessary. Some FromDto and ToDto [extension] methods are just simpler, faster, easier to debug and more reactive to code changes. Mapping between different class layouts or property names often results practically as much code (or even more with tons of lambdas) as simply writing the mapping manually. See also this link.


text:
Q: python - ctypes, retrieve value of void pointer sent to shared c library Im calling a cpp function from dll with ctypes
the function definition is
int foo(strc *mystrc, int *varsize);

And the structure:
typedef struct
{
    int type;
    int count;
    void *value;
} strc;

So what I tried in python was to define:
class strc(ctypes.Structure):
    _fields_ = [('type', ctypes.c_int),
                ('count', ctypes.c_int),
                ('value', ctypes.c_void_p)]

And to call the function as
varsize = ctypes.c_int()
mystrc = strc()
foo(ctypes.byref(mystrc), ctypes.byref(varsize))

I can perfectly call the function and retrieve all values except for the "value". It should be an array of variables indicated by the "type", have size "varsize" and be an array of "count" variables.
How can I retrieve what is indicated by the void pointer?

A: template<class T> void iterate_strc_value(const void* value, int size)
{
    const T* element = reinterpret_cast<const T*>(value);
    for(int offset = 0; offset != size; ++offset)
        *(element + offset) // at this point you have the element at the offset+1th position
}

switch(strc_var.type)
{
    case 0: iterate_strc_value<char>(strc_var.value, element_count); break;
    case 1: iterate_strc_value<int>(strc_var.value, element_count); break;
    case 2: iterate_strc_value<std::string>(strc_var.value, element_count); break;
    default: // invalid type -> maybe throw exception within python?!
}

The value pointer is the pointer that you also named value, while size specifies the amount of elements within the array. The size of the type is not needed, as the size of your types is known at compile time.
Basically the function just converts the void* to a pointer of your desired type and then uses pointer arithmetic to iterate over the array. This approach is general enough to just iterate over any void* which points to an array as long as you know it's size.
You could also add a third argument as a callback which performs the given action on each element to keep specialized code outside of the template function.


text:
Q: Connecting SATA Hard Disk drive as a slave/seconda disk to a PC? I have a motherboard with only two SATA ports. I am using both, one for a HDD and one to a CDROM/DVD.
I want to connect a second SATA hard disk drive(HDD), but as stated the mother board I have does not have an extra SATA connector.
So I just unplugged the CDROM/DVD SATA connector and power connector and used them to connect this second SATA HDD to the existing system.
Question: Is this correct way of connecting a second SATA disk as slave?
The PC did booted up(Windows-7 x64) but could not show me the second disk as a drive?
Question 2: If everything else is fine, should this drive be detected?

A: yes this is the way to go. You can connect only one device per channel
It is strange you have only 2 SATA ports on the motherboard - maybe very old one

A: You need to change it all in the BIOS. The BIOS controls boot order for SATA: it's actually really nice compared to the horrible jumpers. You just tell it which SATA device is the boot device, and you're done. Very simple.
As for why it's not showing up, SATA is a little picky, so it's probably not picking up the new drive because the type is set incorrectly. Some DVD drives need to have IDE emulation set, even though they have SATA connectors. If that was done, it would cause this sort of issue. Again, this is set in the BIOS. You can probably just switch it to "AUTO".

A: This sounds strange because in SATA it is just plug and play thing. since both the HDDS are not sharing channels it should not give you problems, and as you explained you did your connections well. please do not get tired and redo your connections again may be something is loose some where,still enter Bios and set the booting order the HDD having OS being number one.


text:
Q: OPA engine support for concurrent calls How many concurrent REST Put/Patch calls can an OPA engine support to update the policy/data?
I tried looking through the documentation, but couldn't find any information pertaining to this.

A: OPA currently supports multiple concurrent policy queries (which are read-only) and 1 concurrent write (e.g., an HTTP PUT on /v1/data). The reads and write can be processed concurrently. When the write is committed, the server will block until outstanding policy queries complete.


text:
Q: Sort fetched data according to date in mysql i want to fetch data from mysql database in order of date with returning only 1 record from database,
if someone register today and other some minute after i want it to bring the first person details and not the other second
which approach among these two i should use?
mysqli_query($conn,"select * from provided_user where status = '1' AND plan = '{$_SESSION['plan']}' ORDER By date_of_ph ASC LIMIT 1");
or
mysqli_query($conn,"select * from provided_user where status = '1' AND plan = '{$_SESSION['plan']}' ORDER By date_of_ph DESC LIMIT 1");

Little explanation would be helpfull

A: mysqli_query($conn,"select * from provided_user where status = '1' AND plan = '{$_SESSION['plan']}' ORDER By date_of_ph ASC LIMIT 1");

This approach will work in your current scinario as it'll fetch you all record of the date you give as a parameter in ascending order so first ever record will be return first & later later added records. By limiting it to 1 you're making sure only first record for that day will return by query.
Good luck


text:
Q: Calculating volatility of a spread (with positive and negative values) in R I am trying to using the TTR package and volatility() function in R to calculate the rolling 30 day volatility of a spread between two underlyings.
Here is a stripped version of my code so far (already pulled/cleaned data, date matched, etc.):
asset1 <-c(rnorm(100, mean=50))
asset2 <-c(rnorm(100, mean=50))
spread <-c(asset1-asset2)
vClose.spread <-volatility(spread, n=30, calc="close", N=252)

Now the error I get here is:
Error in runCov(x, x, n, use = "all.obs", sample = sample, cumulative) :
  Series contain non-leading NAs
In addition: Warning message:
In log(x) : NaNs produced

Any assistance or direction is greatly appreciated.

A: volatility computes the volatility from a time series of prices:
it will only work for positive quantities.
You can use runSD directly.
# Standard deviation of the spread
sqrt(252) * runSD( spread, 30 )
# Standard deviation of the change in spread
sqrt(252) * runSD( diff(spread), 30 )


text:
Q: WPF Control binding does not always update UI I have a button whose IsEnabled property is bound within my view model to a value indicating whether or not the data in the current view has been modified. This binding has been working fine so far until I'd tried adding Drag/Drop functionality to an ItemsControl within the view.
The Drag/Drop function is working fine and does everything it's supposed to. When it's completed any data manipulation it needs to, it sets the View Model's IsModified property to true. I've verified that the value is actually set to true.
The problem I'm having is that, when the IsModified property is changed from within my Drop method, the button's IsEnabled property isn't updating; when IsModified is set to true during the drag/drop operation, the button remains disabled. If I click the button, it suddenly updates and becomes enabled, requiring me to press the button a second time to actually do as it's intended.
The Drop method is being called on the Drop event on the ItemsControl item. Is this being called from another thread or something that is not informing the UI of the property change? I've tried finding supporting docs, but am having a bit of trouble.
Once again, setting the IsModified property continues to work under any other circumstances and updates the UI properly.
The code in question is fairly simple.
XAML:
<ItemsControl.ItemContainerStyle>
    <Style TargetType="ContentPresenter">
        <EventSetter Event="DragEnter" Handler="IcFields_DragEnter"/>
        <EventSetter Event="Drop" Handler="IcFields_Drop"/>
    </Style>
</ItemsControl.ItemContainerStyle>

...
...
...

<Button Margin="5" Padding="10,0,10,0" IsEnabled="{Binding IsModified}"
    Command="{Binding SaveChangesCommand}">Save Changes</Button>

where the IcFields_Drop handler allows the changes to be made to the model and, in the end, sets IsModified to true.
Edit:
Here's an abbreviated example of the implementation. Use the XAML above as the XAML for this example.
C# - Code-Behind
private void IcFields_Drop(object sender, DragEventArgs e)
{
    ViewModel.Drop();
}

C# - View Model
private bool isModified;
public bool IsModified
{
    get { return isModified; }
    set { SetProperty(ref isModified, value); }
}

public void Drop()
{
    //PSEUDO: Do some drag/drop logic for the items attached to the ItemsControl.
    ...
    ...

    IsModified = true;
}

A: Instead of binding the IsEnabled property, you should return a bool from the CanExecute method of your command to indicate whether the Button should be enabled. You would then call a method that raises the CanExecuteChanged event of the command in your Drop() method.
Most ICommand implementations include a RaiseCanExecuteChanged() method or similar that you can call to refresh the status of the command:
public void Drop()
{
    ...
    SaveChangesCommand.RaiseCanExecuteChanged();
}


text:
Q: sqlalchemy event on column update I registered an event at updating User.name for apply some rules after or just before update.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import event
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///:memory:', echo=True)
Session = sessionmaker(bind=engine)   # engine part

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)
    password = Column(String)
    rule = Column(String)
Base.metadata.create_all(engine)

session = Session()
u1 = User(id=1, name="hello world", fullname="hello kitty")
u2 = User(id=2, name="hello world2", fullname="hello kitty2")
session.add(u1)
session.add(u2)

@event.listens_for(User, 'before_update')
def User_before_update(target, value, initiator):
    print ":::::received before insert event for target"

@event.listens_for(User.name, 'set')
def name_set(target, value, old_value, initiator):
    print ":::::set before insert event for target"

### option A
user = session.query(User).get(2)
user.name = u"wawamsma"
session.merge(user)

### option B
session.query(User).filter(User.id == 2).update({User.name: u"eenimenee"})

option A
Every things works fine, but I have some update method using many fields to sqlalchemy.
option B
Updated, but do not trigger both print func.
So I wonder, is this the Wrong way to register event or wrong way to do the update?

A: To receive events when using the query.update() method, you need to use the after_bulk_update event.   As this operation does not deal with individual objects and instead emits an UPDATE statement directly, the actual objects in memory which may have been affected here are not locally available; you may need to query for them.  The context will have a matched_objects attribute if "synchronize_session" is set to "evaluate".


text:
Q: What with close suggestions with target question being closed? I'm encountering the questions that were flagged as duplicate, or have such close vote, but the destination question is already closed.
I'm not sure what to do with such questions. For me, closing the question as duplicate of closed question makes no sense, because if target question was so bad that it had to be closed, why to redirect anyone to that question?
I think that if both questions are very similar, the second should be closed for same reason as original, especially when both are downvoted. However, when the questions is upvoted, it shouldn't be closed as duplicate of closed (or downvoted) question. If something is better than original, it is logical to assume it is not a duplicate.
However, I might be missing some important points for closing question as duplicate of closed question. Because the lack of consequence can be very disturbing for the OPs, I ask it here: What are the standards of handling such questions? Should they be closed, and if so, for what reason? Duplicate or something else?

A: So... Vote your conscience then. Just because the duplicate vote put the question up for review doesn't mean you have to vote the same way. You can vote to close it for a different reason, vote to leave it open, or edit it (which is implicitly a vote to leave it open) (ok, neither Leave Open or Edit are exactly votes, but let's not split hairs...)
Point being, as a reviewer you're trusted to examine the situation and decide what outcome is best - for the site and for those involved with the question being reviewed. You're under no obligation to agree with anyone else - if you believe strongly in a given outcome, then let your review reflect that.
See also: Should users be closing questions as duplicates of closed NARQs?


text:
Q: Is there any way to determine what process has triggered an Application onCreate? Basically, we've got a bunch of sdks and whatnot that start up in the app's oncreate code.
However, even if the app is force closed, android will boot up the oncreate just to show a push notification.
I'm trying to switch code paths based on whether or not the app was actually launched or if the app was just kicked awake by a service or receiver.
While I know I can use the intents for this, because it happens in a background, I can't actually get an intent from an activity to determine this.


text:
Q: Sonata: translations with parameters I can't seem to be able to use translations with variables in Sonata as I do in normal symfony controllers.
In my controller:
$this->setSonataFlashSuccess(
    $this->get('translator')->trans('flash_create_success', [
        '%link%' => 'abcd',
        '%id%' => '1234'
    ])
);

My template:
{{ message|trans|raw }}

My translations file 'SonataAdminBundle.yml':
flash_create_success: Created with success: #%id%

The rendered HTML:
Created with success: #%id%

So the translation worked but not the replacement of the expressions Link and Id. Is there something especial about translations in Sonata? Everything works fine in the rest of the app.

A: When you write a translations file, you have to name it differently than the original (e.g. admin_messages.[langage].yml), otherwise the original SonataAdminBundle.[locale].yml will be used.
So, you should create a file in your bundle like :
# YourBundle/Resources/translations/admin_messages.en.yml`
flash_create_success: Created with success: #%id%

And specify it in your controller :
$this->get('translator')->trans(
    'flash_create_success',
    array(
        '%link%' => 'abcd',
        '%id%' => '1234'
    ),
    'admin_messages', // By default looks for a "messages.[_locale].yml"
);

Note that you don't need to translate the message one more time in your template, as it is already translated in your controller.


text:
Q: How to make games for Android devices in Android Studios I develop games for IOS devices and I wanted to make games for android devices as well. The problem is I dont think you can do it with Android Studios alone. correct ?
In IOS development we have Spritekit, which helps us make games and good ones.
Does Android Studios have anything similar to that ? I've looked up many sites and I cant find the answer. I see many android developers use Unity, buildblocks, etc. To make games. Is this the only way to make the games for android devices or can you make exact games like the ones in unity and Spritekit by only using Android Studios ?
Thank You In Advance !

A: You definitely can create games with Android Studio alone -- creating your own game engine is one way.
If you mean using a ready game engine, an excellent alternative is libgdx - https://libgdx.badlogicgames.com - but there are others.


text:
Q: CSS Have a div which can fit 5 li per row how to make 6 go to new line So in my footer I display a bunch of menu links as column where each columns has like
Header Column
 Column Link
 Column Link
 ...

And I can fit 5 of these per row. What I want is that if the content user add a 6th Column that it wraps to next line and is underneath the first column header.
Right now it wraps to next line but seems to place it randomly at the next line depending on the  height of the 1st row.
Mark up looks like

..subitems

..subitems

..subitems

..subitems

..subitems

..subitems

  ...

Right for each column I am setting width, which leaves enough for 5 per row
.boldMenu {
    max-width: 170px;
    width: 170px;
}

Also floating left
Any ideas ?

A: Try this (CSS3, not compatible with IE8) to make every (5n+1)th list element move to a new line:
#mainMenuList > li:nth-child(5n+1) {
    clear: left;
}

http://jsfiddle.net/mblase75/J4gQP/
If backwards compatibility is an issue, you can add a class directly to every (5n+1)th element yourself, or write JavaScript to do it for you, and clear:left that class as well.


text:
Q: Python Regular Expressions - Accepting Sentences alone containing only Letters This is a module in one part of my task however I'm trying to adapt the regular expression string to accept sentences rather than only single words with letters only. I'm fairly new to python programming and have been learning it for my GCSE for about a year and would appreciate some help.
validateLoop = True
while validateLoop: #While loop used to loop back around if choice is invalid
    shift = input("Enter a sentence: ").lower() #Takes input for a sentence
    if not (re.match('[a-z]+$', shift)): #This is where i'm stuck
        print("Invalid input message, only include letters a-z with no other characters")
        print("Any upper case letters will be converted into lowercase")
    else:
        validateLoop = False

A: How about:
regexp = re.compile(r'^[a-zA-Z\s!-~]+$')
regexp.match(shift)

The !-~ bit should get you the punctuation. the \s gets you the space.
The r prefix makes the string a raw string. Try to use raw strings in your regular expressions.

A: if not (re.match(r"^[A-Za-z]*$", shift)):

This will find everything from the start of the sentence ^
Square brackets will find ONLY the characters that are within them [ ]
A-Za-z specifies which characters to find
* is everything
and $ matches the end of the string
Edit:
if you want to include spaces, use \s
if not (re.match(r"^[A-Za-z\s]*$", shift)):

A: Perhaps this would work better?
if not (re.match('^[a-z0-9`\'\",/;:\(\)\[\]\$\&\s]+[\.\?!]$', shift)):

It guarantees that the "sentence" ends with a period, question mark, or exclamation.
This could be made a little smarter, since it will miss some valid sentences, such as when there is a quote at the end of the sentence (e.g. Cassius said, "The fault, dear Brutus, is not in our stars, but in ourselves, that we are underlings."), but I think it covers your needs.

A: Rework your regex in the following steps. Refer to Python regex syntax and maybe regular expression basics for the building blocks you have at your disposal.
(not all items may apply to you depending on your task specifics and elaboration)

*

*Apart from letters, each character can be a space; there can be capital letters as well (for simplicity, allow them at any position, too - there are all sorts of abbreviations out there, anyway);

*The 1st letter shall be capital, the last character is a full stop, question mark or exclamation mark;

*There can be punctuation marks at the end of each word, i.e. after a letter and before a space; they, however, cannot be any of sentence-ending marks;

*ellipsis can be either a \u2026 (…) or three consecutive dots. It can be both at the end of a word and sentence (I'm not sure if they add an extra dot in English);

*a "dotted" abbreviation is one or more runs of letters followed by single dots, without any spaces. Also note that they don't add an extra dot if this is at the end of the sentence. At this point, you probably need to store this construct in a separate variable and insert it into relevant parts of the main expression;

*Direct speech or dialogue punctuation is probably not part of your task. But if it is, you need to use a subexpression to detect such a construct as a whole.


text:
Q: Meaning of It did not help that I am reading the book 'Shoe Dog' by Phil Knight'. There is a paragraph in this book which starts with the following sentence:

It didn't help that, when I wasn't a foot soldier in Hayes's Army, I was still serving in the Reserves. (A seven year commitment.)

I want to know what is he referring to by the phrase "it didn't help that".
What is the correct meaning of "it didn't help that"?
Moreover, what does "a foot soldier" as the person (Hayes) is an accountant in the book.

A: I have not read the book which you are referring to, so perhaps some context which is relevant is missed to me. In general English, however, the phrase "It did not help that X" is usually used to express than an already negative event is further amplified by X. For example

The elevator in my apartment was broken.
  It did not help that my limp had only gotten worse.

Here, the narrator expresses their frustration that the elevator is broken implying that they must use the stairs - this is the negative event. The negative event is further amplified by the fact the narrator has a limp, making it even less convenient for them to use the stairs; hence, "it did not help that my limp had gotten worse."

A:
It didn't help that, when I wasn't a foot soldier in Hayes's Army, I
  was still serving in the Reserves.

The comma-separated phrase "when ... Army" is a "parenthetical phrase" -- it adds information which, while perhaps necessary for comprehension, is not needed to have a "correct" sentence.
So analyze "It didn't help that I was still serving in the Reserves".  "It didn't help" is the syntactic "meat" of the sentence, and "that ... Reserves" is a conjunctive clause (may be called other things, depending on your religion) that identifies what "It" means.
So "It" is the subject "did not help" is the verb, and "I was still serving in the Reserves" tells us what "It" means.
"Reserves", especially when capitalized, would be taken to mean "US Army Reserves", people who work "normal" jobs but who can be "called up" on short notice to serve in the military.  They generally must attend training sessions at regular intervals, somewhat disrupting their "normal" lives.
It's difficult to say with any certainty but I would interpret "Hayes's Army" to mean that "Hayes" is a business manager who expects military-like obedience and subservience from his underlings.  "Foot soldier" implies that our narrator was in the lower ranks of Hayes's organization.

A: Perhaps Phil Knight is referring to the amount of alcohol he is ingesting, and it not being a particularly good thing that he is drinking so much at that time in his life. After talking about drinking a lot with Hayes everyday after work (because Hayes insisted all the junior accountants join him), Knight also mentions "marching double-time to the bar the moment we were dismissed" from duty on Tuesday nights. He has a line a little further down: "Between the Reserves and Hayes, I wasn't sure my liver was going to see 1966."
When Knight talks about being a foot soldier in Hayes's army, he is noting the fact that he (Knight) is a junior accountant. As a junior accountant Knight does important work, however he has no authority. Hayes has the authority, thus it is Hayes's army. Knight is a foot soldier - he has to do what Hayes tells him (e.g., going to the bar to drink after work).
I hope this helps.


text:
Q: How to join two tables with a pivot table using Laravel? I have these three tables:
tbl_lista_contactabilidad  tbl_equipo_postventaatc  users
-------------------------  -----------------------  -----
id                         id                       id
usuarios_id                asesor_id                name

tbl_lista_contactabilidad.usuarios_id should be related with tbl_equipo_postventaatc.asesor_id. asesor_id should be the "pivot" between tbl_lista_contactabilidad.usuarios_id and users.id to make the relation.
I want to make this relation so I tried to do this relation in this way (I will put only the relation of the model)
Tbl_Lista_Contactabilidad (Model 1)
public function postventaatc(){

return $this->belongsTo('App\Models\Tbl_EquipoPostventaatc','usuarios_id');

}

Tbl_Equipo_Postventaatc (Model 2) -> This should be the pivot model
public function contactabilidad(){

return $this->hasMany('App\Models\Tbl_Lista_Contactabilidad','usuarios_id');

}

public function user(){

return $this->belongsTo('App\Models\User','asesor_id');

}

User (Model 3)
public function postventaatc(){

return $this->hasMany('App\Models\Tbl_Lista_Postventaatc','asesor_id');

}

EXAMPLE:

As you see in the image... if I relate usuarios_id with users directly I will get another name and I don't want that... I want the relation just like in the image

A: A pivot table is a structure used to join two separate models together with a single relationship. This is called a many-to-many relationship in Eloquent.
From what you've described, this is not the case here. Rather, it looks like a has-many-through relationship.
If I'm understanding correctly, your relationships should look like this:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Tbl_Lista_Contactabilidad extends Model {
    protected $table = 'tbl_lista_contactabilidad';
    public function postventaatc() {
        return $this->belongsTo(Tbl_EquipoPostventaatc::class, 'usuarios_id');
    }
}

class Tbl_EquipoPostventaatc extends Model {
    protected $table = 'tbl_equipo_postventaatc';
    public function contactabilidad() {
        return $this->hasMany(Tbl_Lista_Contactabilidad::class, 'usuarios_id');
    }
}

class User extends Model {
    public function postventaatc() {
        return $this->belongsTo(Tbl_EquipoPostventaatc::class, 'asesor_id');
    }
    public function contactabilidad() {
        return $this->hasManyThrough(Tbl_Lista_Contactabilidad::class, Tbl_EquipoPostventaatc::class, 'asesor_id', 'usuarios_id');
    }
}

Obviously this is easier for a native English speaker, but I cannot stress how much easier this would be if you were following the Laravel rules around naming your models, tables, and columns. Why does usuarios_id column relate to a table called tbl_equipo_postventaatc? Why use asesor_id instead of user_id? ♂ Those names have nothing to do with each other, and make it hard to figure out what is going on.


text:
Q: Problems with SHA-256 hash of file passed through PHP SoapClient I'm trying to use PHP SoapClient to call a web service function which these two parameters (taken from documentation):
byte[] file,     // byte array of file
byte[] hashFile // byte array of hash SHA-256 of the original file

It's a XML file, but I don't have the file, i just generate its content on-the-fly with : $fileContent = $this->xmlDocument->saveXML()

The problem is that when I do the call to the function the server answers: invalid file hash

I can't understand what's my mistake.
This is the WSDL part which defines these parameters:
<wsdl:part name="file" type="xsd:base64Binary"/>
<wsdl:part name="hashFile" type="xsd:base64Binary"/>

And this is my code :
<?php
function sendDocument($xmlDocument,$soapClient)
{
    $fileContent = $xmlDocument->saveXML()
    $params = [
        "file"     => getByteArray($fileContent),
        "hashFile" => getByteArray(getHash($fileContent)),
    ];
    $response = $soapClient->__soapCall("sendDocument", $params);
}
function getByteArray($string)
{
    return base64_encode($string);
}
function getHash($string)
{
    return hash("sha256", $string);
}
?>


text:
Q: How to access sub index values in an array list Preface : I am trying to get customer data using a webservice. I am having issues with storing the data into an array. Where this array will be passed to a text writer method.
Issue:
I am adding values into an Array List from an array. Every iteration is adding 1000 values into the list Array List as per index.
1st Iteration : arraylist -index 0 will have 1000 values.
2nd Iteration : arraylist -index 1 will have 1000 values.
like this i will have until arraylist -index 7.
array list image
Now my question is that I want to store all the 7000 values into an array.
I tried accessing the sub index of the list also tried to save all 7000 records in an array but , even if I declare array size as 7000 , it is only saving 1000 values at once and in the next iteration replacing second iteration values in the first set of values. Reason for seeking only 1000 records is that my web service gives only 1000 records in one request. So I am saving every iteration values into an array List and stuck with this issue.
Code Snippet
If I can save all the records into an array , I can pass the array to text writer and the issue will be solved.
public static void GetCustomerData(string _url)
{
    string todaysDate = DateTime.Now.ToString("yyMMdd");
    MyWebServices.Service obj = new MyWebServices.Service();

    obj.Url = _url;

    BlockRange bckr = new BlockRange();

    bckr.lorecord = 1;
    bckr.hirecord = 1000;

    RecordRange rcdr = new RecordRange();
    CustomerElement cust = new CustomerElement();
    List<CustomerElement cus = new List<CustomerElement();
    int finalrcdr = 50000;
    int hrecord = 0;
    int lrecord = 0;

    lrecord = Convert.ToInt32(bckr.lorecord);
    hrecord = Convert.ToInt32(bckr.hirecord);

    Array arr = new Array[finalrcdr];
    Array brr = new Array[finalrcdr];
    ArrayList list = new ArrayList();

    int a = 0;

    for (int i = 0; i <= (finalrcdr/ increment); i++)
    {
        if ((hrecord <= finalrcdr) == true)
        {
            if (((lrecord < hrecord) && lrecord  0) && ((hrecord  lrecord) && hrecord  0))
            {
                bckr.lorecord = lrecord;
                bckr.hirecord = hrecord;

                cus = obj.getcustomerDetails(bckr).ToList();
                arr = cus.ToArray();
                list.Add(arr);

                Array tarr = new Array[finalrcdr];
            }

            TextWriter tw = new StreamWriter(CustomerFilePath + todaysDate + "_" + cus.Count + "." + member_ID, true);

            WriteCustomers(arr, tw);

            lrecord = hrecord+1;
            hrecord = lrecord + 999;
        }
    }
}


text:
Q: Line Buffered Cat is there a way to do line-bufferd cat? For example, I want to watch a UART device, and I only want to see it's message when there is a whole line. Can I do some thing like:
cat --line-buffered /dev/crbif0rb0c0ttyS0

Thanks.

A: You can also use bash to your advantage here:
cat /dev/crbif0rb0c0ttyS0 | while read line; do echo $line; done

Since the read command reads a line at a time, it will perform the line buffering that cat does not.

A: No, but GNU grep with --line-buffered can do this. Just search for something every line has, such as '^'.

A: Pipe it through perl in a no-op line-buffered mode:
perl -pe 1 /dev/whatever


text:
Q: Sys.WebForms.PageRequestManager.getInstance() causing error with Google maps API I have problem with Sys.WebForms.PageRequestManager.getInstance().It is causing script error in my page.I have used Ajax in my page.I am facing postback issues in Google Maps.
      function CallInitialiseInPost() {
        initialize();
       }

   var prm = window.Sys.WebForms.PageRequestManager.getInstance();
   prm.add_endRequest(CallInitialiseInPost);
    function initialize() {
        var input = document.getElementById('streetTxt');

        var autocomplete = new google.maps.places.Autocomplete(input);

        google.maps.event.addListener(autocomplete, 'place_changed', function() {
            var place = autocomplete.getPlace();
            if (place.address_components) {
                for (var i = 0; i < place.address_components.length; i++) {
                var addr = place.address_components[i];
                    var getCity;
                    var getPostal;
                    var getStreet;
                    if (addr.types[0] == 'locality') {
                        getCity = addr.long_name;
                        document.getElementById('cityTxt').value = getCity;
                    }
                    if (addr.types[0] == 'postal_code') {
                        getPostal = addr.long_name;
                        document.getElementById('postalTxt').value = getPostal;
                    }
                }

            }

        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);


text:
Q: jQuery Option Select How could I make the required input text boxes show when the correct drop down item is selected.
Example:
When yes is selected it will ask for the details about the domain.
<label for="domainRequired">Domain required: </label>
<select name="domainRequired">
    <option value="pleaseSelect">Please Select</option>
    <option value="yes">Yes</option>
    <option value="no">No</option>
</select>

Update:
HTML:
<label for="domainRequired">Domain required: </label>
            <select name="domainRequired">
                <option value="pleaseSelect">Please Select</option>
                <option value="yes">Yes</option>
                <option value="no">No</option>
            </select>
            <label for="domaintobereged">Domain:</label><input name="domaintobereged" id="domaintobereged" type="text" placeholder="http://"/>

jQuery:
<script type="text/javascript">
    $(document).ready(function() {
        $('#domainRequired').change(function() {
            var $domain = $('#domaintobereged');
            if ($(this).val() == 'yes') {
                $domain.show();
            } else {
                $domain.hide();
            }
        });
     });
    </script>

I have loaded my jQuery in the footer above the </body> tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>window.jQuery || document.write('<script src="http://#.co.nz/_assets/js/jquery-1.7.2.min.js"><\/script>')</script>

A: Supposing you have added the appropriate id's to your elements - the major work could be done as:
$('#domainRequired').change(function() {
    var $domain = $('#domain');
    if ($(this).val() == 'yes') {
        $domain.show();
    } else {
        $domain.hide();
    }
});

or even
$('#domainRequired').change(function() {
    $('#domain').toggle($(this).val() == 'yes');
});

Live examples: http://jsfiddle.net/zerkms/3XYMT/ & http://jsfiddle.net/zerkms/3XYMT/1

A: $('select[name="domainRequired"]').change(function(e){
    if(e.target.value === 'yes') {
        // Do stuff
    }
});

A: Have a look at .change().
Used roughly like this:
$("[name=domainRequired]").change(function()
{
    // Show a text box if YES was selected (perhaps using .val() ?)

});

A: Cross browser solution:
var $select = $('select[name="domainRequired"]');
$select.change(function() {
    if ($select.find('option:selected').val() == 'yes') {
        // make inputs required
    } else {
        // make inputs optional
    }
});


text:
Q: Vue: Group data by day, then by time I'm trying to group a list of events first by tay, and then by time. I'm able to get one layer of this, but I'm stuck on the second.
In the end, it should look something like this:

Friday
  8:00 - Event 1, Event 2, etc…
  9:00 - Event 1, Event 2, etc…
  …
Saturday
  8:00 - Event 1, Event 2, etc…
  9:00 - Event 1, Event 2, etc…
  …

Here's my code so far, which gives me the day-level groupings. I'm extremely new to this, so if there's an obviously better approach, I'm happy to explore it.
Here's a CodePen version. This does the day grouping, but not the time grouping.
I've tried several things. I understand that I probably need to do something similar to what I'm doing with the date, but I'm not sure how to create, loop through, and display arrays that don't exist yet.

{{ day == today ? 'Today' : day }}

      {{ event.date.toLocaleTimeString() }} - {{ event.title }}

function groupBy(array, fn) {
  let result = {};
  array.forEach(item => {
    let key = fn(item);

    if (!result[key]) {
      result[key] = [];
    }
    result[key].push(item);
  });
  return result;
}

let conferenceDays = [];

for (let [key, session] of Object.entries(sessions)) {
  // console.log(session.Start);
  conferenceDays.push({
    date: new Date(session.Start),
    title: session.Title
  });
}

new Vue({
  el: "#vue",
  data() {
    return {
      conferenceDays,
      today: new Date().toDateString()
    };
  },
  computed: {
    groupedDays() {
      return groupBy(this.conferenceDays, day => day.date.toDateString());
    }
  }
});

I know somebody will very helpfully label this as a duplicate of some vaguely similar question, so please know that I did search extensively, and I didn't locate any questions with two levels of groupings. Again, I'm open to different solutions if I'm approaching this in a bad way.

A: A possible solution could be the following:
In the groupBy function, first sort the array in ascending order and then transform each day into an object whose keys and values would be the starting hours and the conferences that start at that time, respectively.
function groupBy(array) {
  return array
    .sort((c1, c2) => c1.date.getTime() - c2.date.getTime())
    .reduce((acc, crt) => {
    const k = crt.date.toDateString();
    const hr = crt.date.toLocaleTimeString();

    if (!acc[k]) {
      acc[k] = {};
    }

    acc[k][hr] = acc[k][hr] || [];
    acc[k][hr].push(crt.title);

    return acc;
  }, {})
}

As a result, your html would look like this:

{{ day == today ? 'Today' : day }}

      {{ time }} - {{ conferences.join(', ') }}

Here's the CodePen.

A: for the data wrangling you propose you need to proceed in three steps:
i will use lodash as my data-plumbing library of choice, you dont have to use it
group all the conferences per day (that you have achieved)
function groupAllConferencesByDay(all) {
    return _(all)
           .groupBy(conference => conference.date.toDateString())
           .mapValues(groupDaysConferencesByTime) // <---
           .value()
}

for each day, group this days conferences by their timeslot
function groupDaysConferencesByTime(day) {
    return _(day)
           .groupBy(conference=>conference.date.toLocaleTimeString())
           .mapValues(concatTitleOfSimultaniousConferences)
           .value()
}

for each timeslot get the conferences titles and join them with commas
function concatTitleOfSimultaniousConferences(timeslot) {
  return _.map(timeslot, conference => conference.title )
          .join(", ")
         // dont need .value() here as we are using _.map(X, Y)
         // as opposite to _(X).map(Y)
}

you can then present the data to user like

{{ day == today ? 'Today' : day }}

      {{ time }} - {{ conferences }}

pen here


text:
Q: Scala - printing specific fields in each line from a file While learning, I'm trying to read a web log and extract few fields from it. The web log will be like below
147.172.225.10 - 16401 [16/Sep/2013:23:52:35 +0100] "GET /KBDOC-00057.html HTTP/1.0" 200 11761 "http://www.newbie.com"  "test F20L"
147.172.225.10 - 16401 [16/Sep/2013:23:52:35 +0100] "GET /theme.css HTTP/1.0" 200 12353 "http://www.newbie.com"  "test Mobile Browser Sorrento F20L"
23.53.29.101 - 32693 [16/Sep/2013:23:49:50 +0100] "GET /KBDOC-00035.html HTTP/1.0" 200 9337 "http://www.newbie.com"  "test Mobile Browser i3"

And I need to extract just the IP address and User id(3rd field) from the logs and print as
147.172.225.10/16401
147.172.225.10/16401
23.53.29.101/32693

If I have to use map or flatMap, could someone help me how and let me know if there is a better way to accomplish it. Thanks in advance !!

A: For each line(as string) in the weblog, you can use split method on the basis of a blank character, and after splitting it will return an array of string, with that, you can extract the required values.
lines map { line =>
  val lineArray = line.split(" ")
  lineArray(0), lineArray(2)
}

A: Thanks everyone, I used below to get the required results.
map(line => line.split(' ')).map(fields => (fields(0) + "/" + fields(2)))


text:
Q: Using Map algebra to "burn" a river into a a landcover map using GRASS I have a map of various polygons where each polygon represent the cost of passage for different vegetations (values range from 10-50). I have a separate map of a river, where the river currently has a value of 1 and the rest of the map is "no data" (this has been rasterised using "File" → "Map type conversions").
Can I use map algebra to "burn" the river into the landcover map, in a way where the new map represents a channel of uniformly low-cost movement?

A: You can choose one of two possible solutions using GRASS-GIS:
Vector based:
Using the module v.overlay and its operator parameter "not" you can get the landcover polygons with the river "clipped out". Then patch the clipped landcover together with the river. Finally assign the landcover polygon whatever value is appropriate. Here are the commands (assuming two polygon vectors: "landcover" and "river", where the column "cost_val" contains the cost value)
v.overlay ain=landcover bin=river operator="not" output=landcover_clipped
v.patch input=landcover_clipped,river output=landcover_river
v.db.update map=landcover_river column=cost_val value=10 where="cost_val=1"

Raster based
Typically "map calculator" and "burning in" refer to raster layers. You could choose to convert the polygons to rasters, as follows (you need to choose a suitable raster resolution so that you have, perhaps, a few thousand pixels e-w and n-s):
g.region -ap vect=landcover res=<...>
v.to.rast landcover output=landcover use=attr attribute_column=cost_val
v.to.rast river output=river use=val value=10
r.mapcalc "landcover_river = if(isnull(river), landcover, river)"
# If necessary, convert back to polygons
r.to.vect landcover_river type=area output=landcover_river column=cost_val

HTH


text:
Q: Routing over Synology VPN Server PPTP tunnel I have a couple of LANs I'm trying to connect over the internet by way of a PPTP tunnel between a Unifi USG on one side and a Synology NAS running DSM on the other.
Update: it's been helpfully pointed out that PPTP is insecure - however, there are external considerations that preclude me from using OpenVPN or L2TP/IPsec, at least for now.
For reference, here's a diagram of the two networks:

I set up the VPN Server package on DSM like so:

The local subnet for the DSM box is 192.168.0.0/24.
On the USG, whose WAN address is 10.0.0.95 (natted) and local subnet is 192.168.1.0/24, I configured a PPTP client like so:

When I save this configuration and the USG is provisioned, the PPTP client connects successfully to DSM:

After adding a firewall rule on the USG to accept all traffic from the PPTP network, I can open an ssh connection in both directions (i.e., ssh to USG from the DSM NAS, and then ssh back to the NAS from the USG), so I'm certain that the tunnel itself is working.
I can also ping the NAS from the USG.
But this is where I'm a bit stumped: I want to be able to route traffic through this tunnel from 192.168.0.0/24 to 192.168.1.0/24 (and vice versa, but that's less important).  On the NAS I have this routing table:

But ping 10.0.7.1 fails (although traceroute 10.0.7.1 seems to get a response, which confuses me).
On the USG, I have the following routes:

But I can't traceroute 192.168.1.7 (for example) from the NAS.
Does anyone have any suggestions as to why the PPTP tunnel would work, but my routes fail to route traffic through it?
Update: cross-post on Ubnt community forum: https://community.ubnt.com/t5/UniFi-Routing-Switching/ICMP-routing-not-working-over-PPTP-Client/m-p/2194121#M72278


text:
Q: mongoDB user not found error while connecting from python code I have a local mongoDB server running and I created an admin user through this command:
db.createUser({user:"admin",pwd:"abc", roles:[{role:"root",db:"admin"}]})

I can also see following comming up in mongoDB shell when I execute db.getUser('admin')
{
        "_id" : "test.admin",
        "user" : "admin",
        "db" : "test",
        "roles" : [
                {
                        "role" : "root",
                        "db" : "admin"
                }
        ]
}

But when I try to connect to this mongoDB instance from my python code using below line I get following error: I ACCESS   [conn5] SCRAM-SHA-1 authentication failed for admin on admin from client 127.0.0.1:51174 ; UserNotFound: Could not find user admin@admin
host = os.environ.get('MONGO_HOST') or 'localhost'
port = os.environ.get('MONGO_PORT') or '27017'
username = os.environ.get('MONGO_USERNAME') or 'admin'
password = os.environ.get('MONGO_PASSWORD') or 'abc'
database = os.environ.get('MONGO_DB') or 'admin'
client = MongoClient('mongodb://'+username+':'+password+'@'+host+':'+str(port)+'/admin')

What is the mistake here and why is it throwing this error?


text:
Q: There is a bijection between $\{ f: X \to Y \text{ continuous} \}$ and $ \tau_{_X} \times \tau _{_Y}$ Let $\tau _{_X}$ and $\tau _{_Y}$ denote the topologies on $X$ and $Y$ respectively. I know that the statement in the topic is not true, but my feelings say that with a small modification, this will be true.
I want to keep the $\{ f: X \to Y \text{ continuous} \}$ part.
Maybe it would be true if $ \tau_{_X} \times \tau _{_Y}$ is replaced by $ \mathcal P  (\tau_{_X}) \times \mathcal P (\tau _{_Y})$?
Q: Is there a bijection between continuous functions $X \to Y$ and a set obtained by some operations on the topologies of $X$ and $Y$ ?
Thanks for any help.


text:
Q: Does probability change throughout card games that involve hands as cards are played I am trying to work out the probability of cards games where cards are played, Im not sure if the odds change or not.
For instance lets say there are 2 players playing a game of high card (Ace is high) but with hands of cards instead of single games and the only other rule is suits must match in order to win (ie you can only play beat a played heart card with a higher heart card, eg only card that beats the king of hearts is the ace of hearts)
Each player has 5 cards from 52, In this example, before any card is played, if I look at my hand see I have a king card, The probability that my opponent has the ace I calculate to opponent hand count divided by the total number of cards remaining in the deck minus my hand
5 / (52 -5) = ~10%
Now lets say the first round I play a different card, the 5 of clubs and the opponent plays the 4 of clubs, now thats two cards out of the way. If I look at my cards now and check the chances of playing my king and the chance the opponent has the ace of the same suit, is the probability the same as originally calculated or does it change?
The equation now looks like this Opponents hand count divided by remaining cards in the deck minus my hand minus the played cards
4 / (52 - 4 - 2) = ~8.7%
The Monty Hall problem shows that original odds still can influence the game as it progresses but is this the same in card games. I cannot see any examples or reasons of how odds change or don't change as the games progress
If anyone has any reference material where I can learn about calculating card games that are not related to Poker please share also. I assume that adding in more people the the game would change the equations again as the playing position of each player would now come into effect so I would love to see some info on this


text:
Q: Angular mat-form-field with FormControl and NgModel issue I have a mat-form-field with an input box with type="number".
I'm not sure if for my case I should use FormControl or NgModel.
I have a child component that recieves an Input object and I should save what's written in the input field onto a property of this object.
this is my child controller:
@Input()
  building: Building;

@ViewChild("numberMatInput", {read: MatInput})
  numberMatInput: MatInput;
  numberInput: FormControl = new FormControl();

ngOnInit() {
    this.numberInput.valueChanges
    .subscribe(s => {
      this.building.radius = s;
    });
}

and my view is:
<mat-form-field appearance="outline">
     <mat-label>KM</mat-label>
     <input type="number" matInput #numberMatInput [formControl]="numberInput">
</mat-form-field>
<mat-icon matListIcon (click)="numberInput.setValue('')">close</mat-icon>

so it works, the input value gets saved onto the object property -> this.building.radius but what doesn't work, this is a panel that can be opened when selecting a building, and if I close the panel and open it again, the input field is empty instead of showing the latest value before closing the panel.
Should I use NgModel? so I can use on the NgModel directly building.radius ?
Sorry but I m pretty new to Angular!

A: for now I solved it like this, changed from FormControl to:
[(ngModel)]="building.radius"

and that's it, so it directly writes on the property of the object, not sure if it's the best way, but it works


text:
Q: Деление массива Scala, Ocaml Задание: Напишите функцию, которая генерирует другую функцию (factory (??)). Функция должна выполнять следующее: принять массив целых чисел и разделить его на три массива ([числа которые делятся на х], [числа которые делятся на у], [все остальные числа]). x,y должны быть переданы как параметры генеративной функции. Используйте соответствие шаблону (match the pattern), хвостовую рекурсию и  анонимные функции. Внимание! Каждый элемент массива может быть проверен только 1 раз. Нельзя пользоваться готовыми библиотечными функциями. Выполните задание хотя бы в одном из языков: Scala или OCaml.
Пример(OCaml):
    let groupingFunction = generateGroupingFunctionFactory 3 5;;
    groupingFunction [1;2;3;4;5;6;7;8;9;10] => ([3;6;9],[5,10],[1;2;4;7;8]);;

Вот что у меня есть на данный момент(Ocaml):
   let generateGroupingFunctionFactory x y =
let rec generate list =
    match list with
        [] -> ([],[],[])
        | (hd::tail) when hd mod x = 0 ->
            match generate tail with
                (x,y,rest) -> (hd::x,y,rest)
        | (hd::tail) when hd mod y = 0 ->
            match generate tail with
                (x,y,rest) -> (x,hd::y,rest)
        | (hd::tail) ->
            match generate tail with
                (x,y,rest) -> (x,y,hd::rest)
in generate;;

let groupingFunction = generateGroupingFunctionFactory 3 5;;
groupingFunction [1;2;3;4;5;6;7;8;9;10];;

Но я не до конца понимаю что в этом коде можно выразить в виде анонимной функции и как написать функцию которая генерирует другую функцию. Буду рад любой помощи либо информации на эту тему.

A: import scala.annotation.tailrec
import scala.collection.mutable.ListBuffer

def generateGroupingFunctionFactory(x: Int, y: Int): List[Int] => (List[Int], List[Int], List[Int]) = {
  val splitByX = ListBuffer.empty[Int]
  val splitByY = ListBuffer.empty[Int]
  val other = ListBuffer.empty[Int]

  @tailrec
  def go(input: List[Int]): (List[Int], List[Int], List[Int]) = {

    input match {
      case Nil => (splitByX.toList, splitByY.toList, other.toList)
      case head :: tail =>

        val canDivideByX = head % x == 0
        val canDivideByY = head % y == 0

        if (canDivideByX) splitByX += head
        if (canDivideByY) splitByY += head
        if (!(canDivideByX || canDivideByY)) other += head

        go(tail)
    }
  }

  go
}

val groupingFunction = generateGroupingFunctionFactory(3, 5)

groupingFunction((1 to 10).toList) // (List(3, 6, 9),List(5, 10),List(1, 2, 4, 7, 8))

A: Итоговый вариант в Scala:
def generateGroupingFunctionFactory(x: Int, y: Int): List[Int] => (List[Int], List[Int], List[Int]) = {
  def generate(list: List[Int]): (List[Int], List[Int], List[Int]) = {
    def generateHelper(listIn: List[Int], listX: List[Int], listY: List[Int], listRest: List[Int]): (List[Int], List[Int], List[Int]) =
      listIn match {
        case Nil => (listX, listY, listRest)
        case head::tail => (head%x==0, head%y==0) match {
            case (true, true) => generateHelper(tail, listX:::List(head), listY:::List(head), listRest)
            case (true, false) => generateHelper(tail, listX:::List(head), listY, listRest)
            case (false, true) => generateHelper(tail, listX, listY:::List(head), listRest)
            case (false, false) => generateHelper(tail, listX, listY, listRest:::List(head))
          }
      }
    generateHelper(list, List(), List(), List())
  }
  generate
}

def groupingFunction = generateGroupingFunctionFactory(4,7)
def test = assert(groupingFunction(List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15))==(List(4,8,12),List(7,14),List(1,2,3,5,6,7,9,10,11,13,15)))
test

Всем спасибо за помощь.