问:
In React ES6, why does the input field lose focus after typing a character?
In my component below, the input field loses focus after typing a character. While using Chrome's Inspector, it looks like the whole form is being re-rendered instead of just the value attribute of the input field when typing.

I get no errors from either eslint nor Chrome Inspector.

Submitting the form itself works as does the actual input field when it is located either in the render's return or while being imported as a separate component but not in how I have it coded below.

Why is this so?

Main Page Component

```<code>import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionPost from '../redux/action/actionPost';
import InputText from './form/InputText';
import InputSubmit from './form/InputSubmit';

class _PostSingle extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            post: {
                title: '',
            },
        };
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }
    onChange(event) {
        this.setState({
            post: {
                title: event.target.value,
            },
        });
    }
    onSubmit(event) {
        event.preventDefault();
        this.props.actions.postCreate(this.state.post);
        this.setState({
            post: {
                title: '',
            },
        });
    }
    render() {
        const onChange = this.onChange;
        const onSubmit = this.onSubmit;
        const valueTitle = this.state.post.title;
        const FormPostSingle = () => (
            <form onSubmit={onSubmit}>
                <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
                <InputSubmit name="Save" />
            </form>
        );
        return (
            <main id="main" role="main">
                <div className="container-fluid">
                    <FormPostSingle />
                </div>
            </main>
        );
    }
}

_PostSingle.propTypes = {
    actions: PropTypes.objectOf(PropTypes.func).isRequired,
};

function mapStateToProps(state) {
    return {
        posts: state.posts,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actionPost, dispatch),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(_PostSingle);
</code>```

Text Input Component

```<code>import React, { PropTypes } from 'react';

const InputText = ({ name, label, placeholder, onChange, value, error }) => {
    const fieldClass = 'form-control input-lg';
    let wrapperClass = 'form-group';
    if (error && error.length > 0) {
        wrapperClass += ' has-error';
    }
    return (
        <div className={wrapperClass}>
            <label htmlFor={name} className="sr-only">{label}</label>
            <input type="text" id={name} name={name} placeholder={placeholder} onChange={onChange} value={value} className={fieldClass} />
            {error &&
                <div className="alert alert-danger">{error}</div>
            }
        </div>
    );
};

InputText.propTypes = {
    name: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    placeholder: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    value: PropTypes.string,
    error: PropTypes.string,
};

InputText.defaultProps = {
    value: null,
    error: null,
};

export default InputText;
</code>```

Submit Button Component

```<code>import React, { PropTypes } from 'react';

const InputSubmit = ({ name }) => {
    const fieldClass = 'btn btn-primary btn-lg';
    return (
        <input type="submit" value={name} className={fieldClass} />
    );
};

InputSubmit.propTypes = {
    name: PropTypes.string,
};

InputSubmit.defaultProps = {
    name: 'Submit',
};

export default InputSubmit;
</code>```

答: set the correct id, make sure no other component has same id, set it unique, and it should not change on state update, most common mistake is updating the id with changed value on state update</p>

Body:
In my component below, the input field loses focus after typing a character. While using Chrome's Inspector, it looks like the whole form is being re-rendered instead of just the value attribute of the input field when typing.

I get no errors from either eslint nor Chrome Inspector.

Submitting the form itself works as does the actual input field when it is located either in the render's return or while being imported as a separate component but not in how I have it coded below.

Why is this so?

Main Page Component

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actionPost from '../redux/action/actionPost';
import InputText from './form/InputText';
import InputSubmit from './form/InputSubmit';

class _PostSingle extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            post: {
                title: '',
            },
        };
        this.onChange = this.onChange.bind(this);
        this.onSubmit = this.onSubmit.bind(this);
    }
    onChange(event) {
        this.setState({
            post: {
                title: event.target.value,
            },
        });
    }
    onSubmit(event) {
        event.preventDefault();
        this.props.actions.postCreate(this.state.post);
        this.setState({
            post: {
                title: '',
            },
        });
    }
    render() {
        const onChange = this.onChange;
        const onSubmit = this.onSubmit;
        const valueTitle = this.state.post.title;
        const FormPostSingle = () => (
            <form onSubmit={onSubmit}>
                <InputText name="title" label="Title" placeholder="Enter a title" onChange={onChange} value={valueTitle} />
                <InputSubmit name="Save" />
            </form>
        );
        return (

                    <FormPostSingle />

        );
    }
}

_PostSingle.propTypes = {
    actions: PropTypes.objectOf(PropTypes.func).isRequired,
};

function mapStateToProps(state) {
    return {
        posts: state.posts,
    };
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators(actionPost, dispatch),
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(_PostSingle);

Text Input Component

import React, { PropTypes } from 'react';

const InputText = ({ name, label, placeholder, onChange, value, error }) => {
    const fieldClass = 'form-control input-lg';
    let wrapperClass = 'form-group';
    if (error && error.length > 0) {
        wrapperClass += ' has-error';
    }
    return (

            {label}
            <input type="text" id={name} name={name} placeholder={placeholder} onChange={onChange} value={value} className={fieldClass} />
            {error &&

{error}

            }

    );
};

InputText.propTypes = {
    name: PropTypes.string.isRequired,
    label: PropTypes.string.isRequired,
    placeholder: PropTypes.string.isRequired,
    onChange: PropTypes.func.isRequired,
    value: PropTypes.string,
    error: PropTypes.string,
};

InputText.defaultProps = {
    value: null,
    error: null,
};

export default InputText;

Submit Button Component

import React, { PropTypes } from 'react';

const InputSubmit = ({ name }) => {
    const fieldClass = 'btn btn-primary btn-lg';
    return (
        <input type="submit" value={name} className={fieldClass} />
    );
};

InputSubmit.propTypes = {
    name: PropTypes.string,
};

InputSubmit.defaultProps = {
    name: 'Submit',
};

export default InputSubmit;


来源: stackexchange

问:
How to put multiple v-for and v-if statements in a table: Vue.js
I am trying to build a table, which has multiple v-if and v-for statements within it. Here is what I am trying to do:

```<code>        <table>
            <span v-for="(option, optionk) in bundle_item.build_options" v-bind:key="optionk">
                <span v-for="(obj, key) in bundle_item.bundle_subs_object" v-bind:key="'k' +key">
                    <span v-if="option == key">
                        <span v-for="(instance, instancek) in obj" v-bind:key="instancek">
                            <tr>
                                <td>
                                    {{instance.name}}
                                </td>
                            </tr>
                        </span>
                    </span>
                </span>
            </span>
        </table>
</code>```

Is there a way to make this possible in a table?

答:
You can use the template tag. This tag will not be present in the produced dom.

  <template v-for="(option, optionk) in bundle_item.build_options">
    <template v-for="(obj, key) in bundle_item.bundle_subs_object">
      <template v-if="option == key">
        <template v-for="(instance, instancek) in obj">
          <tr v-bind:key="`${optionk}${'k' +key}${instancek}`">
            {{instance.name}}

        </template>
      </template>
    </template>
  </template>

```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to build a table, which has multiple v-if and v-for statements within it. Here is what I am trying to do:

                                    {{instance.name}}

Is there a way to make this possible in a table?

Body:
You can use the template tag. This tag will not be present in the produced dom.

<table>
  <template v-for="(option, optionk) in bundle_item.build_options">
    <template v-for="(obj, key) in bundle_item.bundle_subs_object">
      <template v-if="option == key">
        <template v-for="(instance, instancek) in obj">
          <tr v-bind:key="`${optionk}${'k' +key}${instancek}`">
            <td>{{instance.name}}</td>
          </tr>
        </template>
      </template>
    </template>
  </template>
</table>


问:
Why doesn't onMarkerReached get called in the next play unless I leave enough time after stopping?
(Sorry to fix it over and over.)

I want to play a new stream immediately after stopping AudioTrack.

However, if you do not start playback after a few milliseconds after stopping playback with stop (), OnMarkerReached callback may not be called.

I wrote sample code.

Press the button to play the sound.

When the button is pressed, data for 0.5 seconds is written to AudioTrack, and after 0.25 seconds, the waveform for the next 0.5 seconds is written to AudioTrack by onMarkerReached. The sound played is 2 seconds sound.

If you press the button while playing the sound for 2 seconds, it will stop (), flush () and start the next playback. At this time, OnMarkerReached may not be called unless an extra time is inserted before playback.

Verification was performed on two android devices.

OnMarkerReached was called even if device A had 0 seconds of the extra time.
However, OnMarkerReached was not called even if device B had 10ms extra time.

Why does onMarkerReached sometimes not be called?

Here is the sample code.

MainActivity.java

```<code>package com.example.audiotrackexample;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements AudioTrack.OnPlaybackPositionUpdateListener {

    final String TAG = MainActivity.class.getSimpleName();

    Button playBtn;
    Button queryBtn;
    TextView curPosTv;
    TextView curPosTv2;

    public class SinGenerator {

        float freq;
        int samplingRate;
        int sampleCount;

        public SinGenerator(float freq, int samplingRate){
            this.freq = freq;
            this.samplingRate = samplingRate;
            this.sampleCount = 0;
        }

        public short generate(){
            this.sampleCount++;
            double t = (double)freq * sampleCount / samplingRate;
            double sin = Math.sin(2.0 * Math.PI * t);
            return (short) (sin*Short.MAX_VALUE);
        }
    }

    static final int SAMPLING_RATE = 16000;
    static final int AUDIO_DATA_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    static final int CHANNEL = AudioFormat.CHANNEL_OUT_MONO;
    static final int READ_WAVE_BUFFER_SIZE = SAMPLING_RATE / 2;    // 0.5s
    static final int AUDIO_TRACK_MIN_BUFFER_SIZE = SAMPLING_RATE;
    int audioTrackBufferSize;
    AudioTrack audioTrack;
    SinGenerator sinGenerator = new SinGenerator(300, SAMPLING_RATE);
    short[] wave;
    short[] readWaveBuff = new short[READ_WAVE_BUFFER_SIZE];
    int waveReadLen = 0;
    Handler handler = new Handler(Looper.myLooper());

    void setNextWave(){
        System.arraycopy( wave, waveReadLen, readWaveBuff, 0, READ_WAVE_BUFFER_SIZE );
        waveReadLen += READ_WAVE_BUFFER_SIZE;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playBtn = findViewById(R.id.playBtn);
        queryBtn = findViewById(R.id.queryBtn);
        curPosTv = findViewById(R.id.curPosTv);
        curPosTv2 = findViewById(R.id.curPosTv2);

        queryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
                curPosTv2.setText("curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
            }
        });

        audioTrackBufferSize = AudioTrack.getMinBufferSize(
                SAMPLING_RATE,
                CHANNEL,
                AUDIO_DATA_FORMAT);

        if (audioTrackBufferSize < AUDIO_TRACK_MIN_BUFFER_SIZE) {
            audioTrackBufferSize = AUDIO_TRACK_MIN_BUFFER_SIZE;
        }

        Log.d(TAG, "audioTrackBufferSize : " + audioTrackBufferSize);

        audioTrack = new AudioTrack(
              AudioManager.STREAM_MUSIC,
              SAMPLING_RATE,
              CHANNEL,
              AUDIO_DATA_FORMAT,
              audioTrackBufferSize,
              AudioTrack.MODE_STREAM);
        audioTrack.setPlaybackPositionUpdateListener(MainActivity.this);

        wave = new short[READ_WAVE_BUFFER_SIZE * 4];
        for (int i = 0; i < 4; i++) {
            sinGenerator = new SinGenerator(300 + i * 100, SAMPLING_RATE);
            for (int j = 0; j < READ_WAVE_BUFFER_SIZE; j++) {
                wave[i * READ_WAVE_BUFFER_SIZE + j] = sinGenerator.generate();
            }
        }

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                audioTrack.stop();
                audioTrack.flush();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        waveReadLen = 0;
                        setNextWave();

                        audioTrack.setNotificationMarkerPosition(READ_WAVE_BUFFER_SIZE / 2);
                        audioTrack.write(readWaveBuff, 0, READ_WAVE_BUFFER_SIZE);
                        audioTrack.play();
                        curPosTv.setText("curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
                    }
                },0);        // device A is onMarkerReached called. but device B is not.
//                }, 10);        // device A is onMarkerReached called. but device B is not.
//                }, 100);     // Devices A and B call onMarkerReached.

            }
        });
    }

    @Override
    public void onMarkerReached(AudioTrack track) {

        curPosTv.setText("curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
        if(waveReadLen == wave.length) {
            audioTrack.stop();
            audioTrack.flush();
            Log.d(TAG, "finish playing");
        } else {

            setNextWave();
            audioTrack.write(readWaveBuff, 0, READ_WAVE_BUFFER_SIZE);
            int newMarkerPosition = audioTrack.getNotificationMarkerPosition();
            if (waveReadLen == wave.length) {
                newMarkerPosition += (READ_WAVE_BUFFER_SIZE / 2) + READ_WAVE_BUFFER_SIZE;
            } else {
                newMarkerPosition += READ_WAVE_BUFFER_SIZE;
            }

            audioTrack.setNotificationMarkerPosition(newMarkerPosition);
            Log.d(TAG, "curPos : " + audioTrack.getPlaybackHeadPosition() + " markerPos : " + audioTrack.getNotificationMarkerPosition());

        }
    }

    @Override
    public void onPeriodicNotification(AudioTrack track) {
    }

}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/playBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Audio Play">
    </Button>

    <TextView
        android:id="@+id/curPosTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>

    <Button
        android:id="@+id/queryBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Query marker position">
    </Button>

    <TextView
        android:id="@+id/curPosTv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>

</LinearLayout>
</code>```

build.gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.audiotrackexample"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

答:
onMarkerReached is a pretty poorly-specified API; behavior appears to change from OEM to OEM, and from what I've seen, update intervals can be as large as a second (just as coarse as the return values from AudioTrack.getNotificationMarkerPosition()). IMHO, the only acceptable use case for onMarkerReached() is periodic seekbar updates for a mediaplayer-type control.

It's a much better idea to just stream your new content into a single, pre-existing AudioTrack. In other words, you just start one AudioTrack, leave it playing, and make sure it never starves (you can insert silence into the track to fill any gaps). That way, you get to decide how "playback 1" transitions into "playback2", and you have precise control over the timing.

Body:
(Sorry to fix it over and over.)

I want to play a new stream immediately after stopping AudioTrack.

However, if you do not start playback after a few milliseconds after stopping playback with stop (), OnMarkerReached callback may not be called.

I wrote sample code.

Press the button to play the sound.

When the button is pressed, data for 0.5 seconds is written to AudioTrack, and after 0.25 seconds, the waveform for the next 0.5 seconds is written to AudioTrack by onMarkerReached. The sound played is 2 seconds sound.

If you press the button while playing the sound for 2 seconds, it will stop (), flush () and start the next playback. At this time, OnMarkerReached may not be called unless an extra time is inserted before playback.

Verification was performed on two android devices.

OnMarkerReached was called even if device A had 0 seconds of the extra time.
However, OnMarkerReached was not called even if device B had 10ms extra time.

Why does onMarkerReached sometimes not be called?

Here is the sample code.

MainActivity.java

package com.example.audiotrackexample;

import androidx.appcompat.app.AppCompatActivity;

import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements AudioTrack.OnPlaybackPositionUpdateListener {

    final String TAG = MainActivity.class.getSimpleName();

    Button playBtn;
    Button queryBtn;
    TextView curPosTv;
    TextView curPosTv2;

    public class SinGenerator {

        float freq;
        int samplingRate;
        int sampleCount;

        public SinGenerator(float freq, int samplingRate){
            this.freq = freq;
            this.samplingRate = samplingRate;
            this.sampleCount = 0;
        }

        public short generate(){
            this.sampleCount++;
            double t = (double)freq * sampleCount / samplingRate;
            double sin = Math.sin(2.0 * Math.PI * t);
            return (short) (sin*Short.MAX_VALUE);
        }
    }

    static final int SAMPLING_RATE = 16000;
    static final int AUDIO_DATA_FORMAT = AudioFormat.ENCODING_PCM_16BIT;
    static final int CHANNEL = AudioFormat.CHANNEL_OUT_MONO;
    static final int READ_WAVE_BUFFER_SIZE = SAMPLING_RATE / 2;    // 0.5s
    static final int AUDIO_TRACK_MIN_BUFFER_SIZE = SAMPLING_RATE;
    int audioTrackBufferSize;
    AudioTrack audioTrack;
    SinGenerator sinGenerator = new SinGenerator(300, SAMPLING_RATE);
    short[] wave;
    short[] readWaveBuff = new short[READ_WAVE_BUFFER_SIZE];
    int waveReadLen = 0;
    Handler handler = new Handler(Looper.myLooper());

    void setNextWave(){
        System.arraycopy( wave, waveReadLen, readWaveBuff, 0, READ_WAVE_BUFFER_SIZE );
        waveReadLen += READ_WAVE_BUFFER_SIZE;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        playBtn = findViewById(R.id.playBtn);
        queryBtn = findViewById(R.id.queryBtn);
        curPosTv = findViewById(R.id.curPosTv);
        curPosTv2 = findViewById(R.id.curPosTv2);

        queryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
                curPosTv2.setText("curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
            }
        });

        audioTrackBufferSize = AudioTrack.getMinBufferSize(
                SAMPLING_RATE,
                CHANNEL,
                AUDIO_DATA_FORMAT);

        if (audioTrackBufferSize < AUDIO_TRACK_MIN_BUFFER_SIZE) {
            audioTrackBufferSize = AUDIO_TRACK_MIN_BUFFER_SIZE;
        }

        Log.d(TAG, "audioTrackBufferSize : " + audioTrackBufferSize);

        audioTrack = new AudioTrack(
              AudioManager.STREAM_MUSIC,
              SAMPLING_RATE,
              CHANNEL,
              AUDIO_DATA_FORMAT,
              audioTrackBufferSize,
              AudioTrack.MODE_STREAM);
        audioTrack.setPlaybackPositionUpdateListener(MainActivity.this);

        wave = new short[READ_WAVE_BUFFER_SIZE * 4];
        for (int i = 0; i < 4; i++) {
            sinGenerator = new SinGenerator(300 + i * 100, SAMPLING_RATE);
            for (int j = 0; j < READ_WAVE_BUFFER_SIZE; j++) {
                wave[i * READ_WAVE_BUFFER_SIZE + j] = sinGenerator.generate();
            }
        }

        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                audioTrack.stop();
                audioTrack.flush();

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        waveReadLen = 0;
                        setNextWave();

                        audioTrack.setNotificationMarkerPosition(READ_WAVE_BUFFER_SIZE / 2);
                        audioTrack.write(readWaveBuff, 0, READ_WAVE_BUFFER_SIZE);
                        audioTrack.play();
                        curPosTv.setText("curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
                    }
                },0);        // device A is onMarkerReached called. but device B is not.
//                }, 10);        // device A is onMarkerReached called. but device B is not.
//                }, 100);     // Devices A and B call onMarkerReached.

            }
        });
    }

    @Override
    public void onMarkerReached(AudioTrack track) {

        curPosTv.setText("curPlaybackPos : " + audioTrack.getPlaybackHeadPosition());
        if(waveReadLen == wave.length) {
            audioTrack.stop();
            audioTrack.flush();
            Log.d(TAG, "finish playing");
        } else {

            setNextWave();
            audioTrack.write(readWaveBuff, 0, READ_WAVE_BUFFER_SIZE);
            int newMarkerPosition = audioTrack.getNotificationMarkerPosition();
            if (waveReadLen == wave.length) {
                newMarkerPosition += (READ_WAVE_BUFFER_SIZE / 2) + READ_WAVE_BUFFER_SIZE;
            } else {
                newMarkerPosition += READ_WAVE_BUFFER_SIZE;
            }

            audioTrack.setNotificationMarkerPosition(newMarkerPosition);
            Log.d(TAG, "curPos : " + audioTrack.getPlaybackHeadPosition() + " markerPos : " + audioTrack.getNotificationMarkerPosition());

        }
    }

    @Override
    public void onPeriodicNotification(AudioTrack track) {
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/playBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Audio Play">
    </Button>

    <TextView
        android:id="@+id/curPosTv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>

    <Button
        android:id="@+id/queryBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Query marker position">
    </Button>

    <TextView
        android:id="@+id/curPosTv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

    </TextView>

</LinearLayout>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.audiotrackexample"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}


问:
I can not select list item in selenium
What is the script for selenium in li tag. I used Xpath in selenium.

```<code>driver.findElement(By.xpath(" //*[@id='select2-product_cat-container']")).click() ;
</code>```

But it is not working.

答:
The id which is present on the html can be dynamic, so you can use the text in xpath to find the element.

You can click on it like:

```<code>driver.findElement(By.xpath("//li[text()='Uncategorized']")).click();
</code>```

Title: I can not select list item in selenium

Body:
What is the script for selenium in li tag. I used Xpath in selenium.

driver.findElement(By.xpath(" //*[@id='select2-product_cat-container']")).click() ;

But it is not working.

Body:
The id which is present on the html can be dynamic, so you can use the text in xpath to find the element.

You can click on it like:

driver.findElement(By.xpath("//li[text()='Uncategorized']")).click();


问:
NewSoftSerial library is not working for me
I am trying to get the data from GY-NEO6MV2 GPS and I've tried every solution, but I stil get error:
C:\Users\Szymon\Documents\Arduino\libraries\NewSoftSerial\NewSoftSerial.cpp:43:10: fatal error: WConstants.h: No such file or directory

I use the most simple possible code, it only includes the library and does nothing else, so it's not a problem with my code.
None of the solutions from the internet is working, anybody has an idea why it is not working?

答: NewSoftSerial is Arduino library for AVR ATmega MCU. It can't be used with other MCU Arduino platforms.</p>


问:
CallLog.Calls.NEW? What does it mean?
I am currently trying to figure out what

```<code>CallLog.Calls.NEW
</code>```

means.

The documentation says:

Whether or not the call has been
  acknowledged

( http://developer.android.com/reference/android/provider/CallLog.Calls.html#NEW ). I tried to reproduce this.

I made a call to another phone and hung up once it started ringing. What would I expect? An entry with TYPE = OUTGOING_TYPE and NEW = 0, right? But NEW is 1. That really doesn't make any sense to me...

Any ideas?

答:
It's String. It seems to be used as a key in maps:

http://codesearch.google.com/codesearch?hl=pl&lr=&q=package%3Aandroid.git.kernel.org+Calls.NEW

The documentation describes what this key is used for.

Call values are:

```<code>    public static final int INCOMING_TYPE = 1;
    public static final int OUTGOING_TYPE = 2;
    public static final int MISSED_TYPE = 3;
</code>```

ContentLicense: CC BY-SA 3.0

Title: CallLog.Calls.NEW? What does it mean?

Body:
I am currently trying to figure out what

CallLog.Calls.NEW

means.

The documentation says:

Whether or not the call has been
  acknowledged

( http://developer.android.com/reference/android/provider/CallLog.Calls.html#NEW ). I tried to reproduce this.

I made a call to another phone and hung up once it started ringing. What would I expect? An entry with TYPE = OUTGOING_TYPE and NEW = 0, right? But NEW is 1. That really doesn't make any sense to me...

Any ideas?

Body:
It's String. It seems to be used as a key in maps:

http://codesearch.google.com/codesearch?hl=pl&lr=&q=package%3Aandroid.git.kernel.org+Calls.NEW

The documentation describes what this key is used for.

Call values are:

    public static final int INCOMING_TYPE = 1;
    public static final int OUTGOING_TYPE = 2;
    public static final int MISSED_TYPE = 3;


问:
Remove duplicates from String[]
I've created a webscraper to pull links, every now and then I'm getting dupe entries, I'm storing them in an Array of String[], I've thrown a couple of loops together to check for dupes but failing to remove the duplicates.</p>

```<code>    public static void checkForDupes(String[] links) {

    for (int i = 0; i<links.length; i++) {
        String check = links[i];

        for (String link : links) {

            if (check.equals(link)) {
                // remove link
            }
        }
    }

}
</code>```

答:
Simple arrays have a fixed number of references to objects with fixed position. Therefore you cannot remove objects, you can only replace them by others or null, which would leave wholes in the middle of the array. And that is possibly not what you want.

Since you cannot remove elements from an array, you would need to replace the whole array by a new one which contains only the wanted entries. But that arises a new problem: At start you have to specify the size of the target array but you do not know which size you will finally need. So you either need to oversize the array and store the real used length in another variable use a LinkedList which supports a variable size and good performance when adding elements.

In addition, such nested loops tend to become very slow when they are large. When you have more than 20 entries, collecting values in a HashSet is much quicker than such simple for-loops and also does eliminate duplicates already as a side effect.

A very similar class is the HashMap which would not eliminate duplicates. You should google for an explanation how hashing algorithms and hash maps work. That is a very interesting topic.

Example:

```<code>import java.util.Arrays;
import java.util.HashSet;

public class Main
{
    public static void main(String[] args) throws Exception
    {

        String[] links = {"a","b","a","c","b","c","d","e","f"};

        HashSet<String> set=new HashSet<>();
        set.addAll(Arrays.asList(links));

        System.out.println(set);
    }
}
</code>```

Outputs:

```<code>[a, b, c, d, e, f]
</code>```

To read an individual element out of the set, you may use set.get(index).

The following example shows how to achieve the same without HashSet:

```<code>import java.util.Arrays;
import java.util.HashSet;

public class Main
{
    public static void main(String[] args) throws Exception
    {

        String[] input = {"a", "b", "a", "c", "b", "c", "d", "e", "f"};

        String[] output = new String[input.length];
        int count = 0;

        // Iterate over the input array
        for (String in : input)
        {
            // Check if the string is already in the output array
            boolean found=false;
            for (String out : output)
            {
                if (in.equals(out))
                {
                    found=true;
                    break; // break the inner for loop, no need to continue the search
                }
            }

            if (!found)
            {
                output[count++]=in;
            }
        }

        System.out.println(Arrays.toString(output));
    }
}
</code>```

Outputs:

```<code>[a, b, c, d, e, f, null, null, null]
</code>```

Note how I simplified the for loops. Also notice that the output array contains some unused spaces. The counter variable contains the real used size of the array.

Title: Remove duplicates from String[]

Body:
I've created a webscraper to pull links, every now and then I'm getting dupe entries, I'm storing them in an Array of String[], I've thrown a couple of loops together to check for dupes but failing to remove the duplicates.

    public static void checkForDupes(String[] links) {

    for (int i = 0; i<links.length; i++) {
        String check = links[i];

        for (String link : links) {

            if (check.equals(link)) {
                // remove link
            }
        }
    }

}

Body:
Simple arrays have a fixed number of references to objects with fixed position. Therefore you cannot remove objects, you can only replace them by others or null, which would leave wholes in the middle of the array. And that is possibly not what you want.

Since you cannot remove elements from an array, you would need to replace the whole array by a new one which contains only the wanted entries. But that arises a new problem: At start you have to specify the size of the target array but you do not know which size you will finally need. So you either need to oversize the array and store the real used length in another variable use a LinkedList which supports a variable size and good performance when adding elements.

In addition, such nested loops tend to become very slow when they are large. When you have more than 20 entries, collecting values in a HashSet is much quicker than such simple for-loops and also does eliminate duplicates already as a side effect.

A very similar class is the HashMap which would not eliminate duplicates. You should google for an explanation how hashing algorithms and hash maps work. That is a very interesting topic.

Example:

import java.util.Arrays;
import java.util.HashSet;

public class Main
{
    public static void main(String[] args) throws Exception
    {

        String[] links = {"a","b","a","c","b","c","d","e","f"};

        HashSet<String> set=new HashSet<>();
        set.addAll(Arrays.asList(links));

        System.out.println(set);
    }
}

Outputs:

[a, b, c, d, e, f]

To read an individual element out of the set, you may use set.get(index).

The following example shows how to achieve the same without HashSet:

import java.util.Arrays;
import java.util.HashSet;

public class Main
{
    public static void main(String[] args) throws Exception
    {

        String[] input = {"a", "b", "a", "c", "b", "c", "d", "e", "f"};

        String[] output = new String[input.length];
        int count = 0;

        // Iterate over the input array
        for (String in : input)
        {
            // Check if the string is already in the output array
            boolean found=false;
            for (String out : output)
            {
                if (in.equals(out))
                {
                    found=true;
                    break; // break the inner for loop, no need to continue the search
                }
            }

            if (!found)
            {
                output[count++]=in;
            }
        }

        System.out.println(Arrays.toString(output));
    }
}

Outputs:

[a, b, c, d, e, f, null, null, null]

Note how I simplified the for loops. Also notice that the output array contains some unused spaces. The counter variable contains the real used size of the array.


问:
User Data is not saving to Database in Laravel 6
User Data is not saving to Database in Laravel 6. I am using socialite to save data to the database with the following code lines.

```<code>protected $fillable = [
    'email','name','password','username','picture'
];
</code>```

In the login controller. I am able to fetch data from socialite correctly(I Checked).

```<code>$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()],
          ['username'=> $social_user->getName()],
          ['name'=> $social_user->getName()],
          ['picture'=> $social_user->getAvatar()],
          ['password'=> 'sdsdsdsad'],
          ['ip_address'=> '127.0.0.1'],

      );
</code>```

答:
Try the following

```<code>// you may dump($social); to check if $social contains valid data before using it
$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()]
          [
           'username'=> $social_user->getName(),
           'name'=> $social_user->getName(),
           'picture'=> $social_user->getAvatar(),
           // Password Hash
           'password'=> bcrypt('sdsdsdsad'),
           'ip_address'=> '127.0.0.1']

);
</code>```

Check FirstOrCreate Usage

Body:
User Data is not saving to Database in Laravel 6. I am using socialite to save data to the database with the following code lines.

protected $fillable = [
    'email','name','password','username','picture'
];

In the login controller. I am able to fetch data from socialite correctly(I Checked).

$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()],
          ['username'=> $social_user->getName()],
          ['name'=> $social_user->getName()],
          ['picture'=> $social_user->getAvatar()],
          ['password'=> 'sdsdsdsad'],
          ['ip_address'=> '127.0.0.1'],

      );

Body:
Try the following

// you may dump($social); to check if $social contains valid data before using it
$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()]
          [
           'username'=> $social_user->getName(),
           'name'=> $social_user->getName(),
           'picture'=> $social_user->getAvatar(),
           // Password Hash
           'password'=> bcrypt('sdsdsdsad'),
           'ip_address'=> '127.0.0.1']

);

Check FirstOrCreate Usage


问:
How to give a numeric value to an object while writing an rdf triple
I am tryin to write an rdf triple for
MixedFruitJuice is made of 2 Oranges, 1 Pomegranate and 1 Pineapple.

HereMixedFruitJuice is an instance of class FruitJuiceand Orange Pomegranate and Pineapple are instances of Fruit.

I don't understand how I can give a numeric value to the objects. Like "2" oranges, or "1" Pomegranate.

答:
There are different ways to achieve this. For example, using OWL, you can apply owl:Restriction to define either an rdfs:subClass or an owl:equivalentClass, depending if you see your recipe as necessary or as necessary and sufficient conditions for a MixedFruitJuice.

I would suggest declaring Orange, Pomegranate and Pineapple as rdfs:subClass of Fruit. This way a concrete juice, if made of concrete fruits according to the recipe, could be MixedFruitJuice. Now, assuming necessary but insufficient conditions (after all they'd also need some shaking), a :MixedFruitJuice can be described as:

```<code>:MixedFruitJuice rdf:type owl:Class ;
          rdfs:subClassOf [ owl:intersectionOf ( :Juice
                 [ rdf:type owl:Restriction ;
                 owl:onProperty :hasIngredient ;
                 owl:qualifiedCardinality "1"^^xsd:nonNegativeInteger ;
                 owl:onClass :Pineapple]
                 [ rdf:type owl:Restriction ;
                 owl:onProperty :hasIngredient ;
                 owl:qualifiedCardinality "1"^^xsd:nonNegativeInteger ;
                 owl:onClass :Pomegranate]
                 [ rdf:type owl:Restriction ;
                 owl:onProperty :hasIngredient ;
                 owl:qualifiedCardinality "2"^^xsd:nonNegativeInteger ;
                 owl:onClass :Orange]
                                                          ) ;
                                       rdf:type owl:Class
                                     ] .
</code>```

Apart from OWL, this can be achieved also with SHACL in some cases, bringing better results.

If you want to keep Orange, Pomegranate and Pineapple as instances and not as subclasses of Fruit, then you may consider using RDF reification or RDF*.

Using reification can create problems and anyway there is a simple way to represent it, using just RDF, which I should've thought of before suggesting OWL. Here it is:

```<code>:MixedFruitJuice
  rdf:type :Juice ;
  :isMadeOf [
      rdf:type :Orange ;
      :numberOfUnits "2"^^xsd:decimal ;
    ] ;
  :isMadeOf [
      rdf:type :Pineapple ;
      :numberOfUnits "1"^^xsd:decimal ;
    ] ;
  :isMadeOf [
      rdf:type :Pomegranate ;
      :numberOfUnits "1"^^xsd:decimal ;
    ] ;
.
</code>```

For :numberOfUnits I could've chosen an xsd:int range but I assume that in juices might require 1.5 apples for example.

Body:
There are different ways to achieve this. For example, using OWL, you can apply owl:Restriction to define either an rdfs:subClass or an owl:equivalentClass, depending if you see your recipe as necessary or as necessary and sufficient conditions for a MixedFruitJuice.

I would suggest declaring Orange, Pomegranate and Pineapple as rdfs:subClass of Fruit. This way a concrete juice, if made of concrete fruits according to the recipe, could be MixedFruitJuice. Now, assuming necessary but insufficient conditions (after all they'd also need some shaking), a :MixedFruitJuice can be described as:

:MixedFruitJuice rdf:type owl:Class ;
          rdfs:subClassOf [ owl:intersectionOf ( :Juice
                 [ rdf:type owl:Restriction ;
                 owl:onProperty :hasIngredient ;
                 owl:qualifiedCardinality "1"^^xsd:nonNegativeInteger ;
                 owl:onClass :Pineapple]
                 [ rdf:type owl:Restriction ;
                 owl:onProperty :hasIngredient ;
                 owl:qualifiedCardinality "1"^^xsd:nonNegativeInteger ;
                 owl:onClass :Pomegranate]
                 [ rdf:type owl:Restriction ;
                 owl:onProperty :hasIngredient ;
                 owl:qualifiedCardinality "2"^^xsd:nonNegativeInteger ;
                 owl:onClass :Orange]
                                                          ) ;
                                       rdf:type owl:Class
                                     ] .

Apart from OWL, this can be achieved also with SHACL in some cases, bringing better results.

If you want to keep Orange, Pomegranate and Pineapple as instances and not as subclasses of Fruit, then you may consider using RDF reification or RDF*.

Using reification can create problems and anyway there is a simple way to represent it, using just RDF, which I should've thought of before suggesting OWL. Here it is:

:MixedFruitJuice
  rdf:type :Juice ;
  :isMadeOf [
      rdf:type :Orange ;
      :numberOfUnits "2"^^xsd:decimal ;
    ] ;
  :isMadeOf [
      rdf:type :Pineapple ;
      :numberOfUnits "1"^^xsd:decimal ;
    ] ;
  :isMadeOf [
      rdf:type :Pomegranate ;
      :numberOfUnits "1"^^xsd:decimal ;
    ] ;
.

For :numberOfUnits I could've chosen an xsd:int range but I assume that in juices might require 1.5 apples for example.


问:
Create right and left side vertical line of the page - Android Java iTextPdf
I need to create a vertical line on the right and left side of the page, just in the dimension I defined, it cannot be on the entire page. two vertical lines covering 80% of the page.

This line cannot be fixed, as the receipt may have a list of products.

Thanks.

答:
Solution.

```<code> Rectangle small = new Rectangle(292, 720);
        Font smallfont = new Font(Font.FontFamily.HELVETICA, 10);
        Font boldfont = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD);

        Document document = new Document(small, 5, 5, 15, 5);
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(new float[]{ 160, 120 });
        table.setLockedWidth(true);

// first row
        PdfPCell cell
        cell = new PdfPCell(new Phrase("item1", boldfont));
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(Rectangle.LEFT);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("item2", smallfont));
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.LEFT);
        cell.setBorder(Rectangle.RIGHT);
        cell.setPadding(5);
        table.addCell(cell);
</code>```

cell.setBorder defines the border.

cell.setBorder (Rectangle.LEFT) or cell.setBorder (Rectangle.RIGHT)
or cell.setBorder (Rectangle.LEFT | Rectangle.RIGHT);

Body:
Solution.

 Rectangle small = new Rectangle(292, 720);
        Font smallfont = new Font(Font.FontFamily.HELVETICA, 10);
        Font boldfont = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD);

        Document document = new Document(small, 5, 5, 15, 5);
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        PdfPTable table = new PdfPTable(2);
        table.setTotalWidth(new float[]{ 160, 120 });
        table.setLockedWidth(true);

// first row
        PdfPCell cell
        cell = new PdfPCell(new Phrase("item1", boldfont));
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setBorder(Rectangle.LEFT);
        cell.setPadding(5);
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("item2", smallfont));
        cell.setVerticalAlignment(Element.ALIGN_CENTER);
        cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cell.setBorder(Rectangle.LEFT);
        cell.setBorder(Rectangle.RIGHT);
        cell.setPadding(5);
        table.addCell(cell);

cell.setBorder defines the border.

cell.setBorder (Rectangle.LEFT) or cell.setBorder (Rectangle.RIGHT)
or cell.setBorder (Rectangle.LEFT | Rectangle.RIGHT);


问:
Keep task working when the app is in the background
I'm coding a map tracking app on Xamarin forms. I'm using async tasks(with Device.StartTimer) to keep track of the location and another task for counter timer, but when I need to open another app, like a music app or whatever the app can't keep track while it is in the background. All tasks are stopping when I send the app in the background. When I start the app again, the tasks are not continued.
I just need to keep working while app running.

How could this be done?

答: You should use background task in this case, which is running outside the life cycle of the application. You can find more information here Xamarin background tasks</p>


问:
R replacing words in column by annotation dataframe
I have a dataframe with in 1 column gene IDs (data1). In another dataframe I have the corresponding gene names (data2). Data1 also contains cells with multiple genenames, separated with ':', and also a lot of NAs. Preferably I want to add a column to data1 with the corresponding gene names, also separated by ':' if there are multiple. An alternative would be to replace all the genenames in data1 with the corresponding gene names. Any idea how to go about this? Thanks!</p>

```<code>a <- c("ENSG00000150401:ENSG00000150403", "ENSG00000185294", "NA")
data1 <- data.frame(a)

b <- c("ENSG00000150401", "ENSG00000150403", "ENSG00000185294")
c <- c("GeneA", "GeneB", "GeneC")
data2 <- data.frame(b,c)
</code>```

答:
We can get data1 in long format, left_join data2 and paste values together.

```<code>library(dplyr)

data1 %>%
  mutate(row = row_number()) %>%
  tidyr::separate_rows(a, sep = ":") %>%
  left_join(data2, by = c('a' = 'b')) %>%
  group_by(row) %>%
  summarise(a = paste0(a, collapse = ":"),
            c = paste0(c, collapse = ":")) %>%
  select(-row)

#  a                               c
#  <chr>                           <chr>
#1 ENSG00000150401:ENSG00000150403 GeneA:GeneB
#2 ENSG00000185294                 GeneC
#3 NA                              NA
</code>```

Body:
I have a dataframe with in 1 column gene IDs (data1). In another dataframe I have the corresponding gene names (data2). Data1 also contains cells with multiple genenames, separated with ':', and also a lot of NAs. Preferably I want to add a column to data1 with the corresponding gene names, also separated by ':' if there are multiple. An alternative would be to replace all the genenames in data1 with the corresponding gene names. Any idea how to go about this? Thanks!

a <- c("ENSG00000150401:ENSG00000150403", "ENSG00000185294", "NA")
data1 <- data.frame(a)

b <- c("ENSG00000150401", "ENSG00000150403", "ENSG00000185294")
c <- c("GeneA", "GeneB", "GeneC")
data2 <- data.frame(b,c)

Body:
We can get data1 in long format, left_join data2 and paste values together.

library(dplyr)

data1 %>%
  mutate(row = row_number()) %>%
  tidyr::separate_rows(a, sep = ":") %>%
  left_join(data2, by = c('a' = 'b')) %>%
  group_by(row) %>%
  summarise(a = paste0(a, collapse = ":"),
            c = paste0(c, collapse = ":")) %>%
  select(-row)

#  a                               c
#  <chr>                           <chr>
#1 ENSG00000150401:ENSG00000150403 GeneA:GeneB
#2 ENSG00000185294                 GeneC
#3 NA                              NA


问:
Laravel get user id in unprotected route
I am using Laravel guard to to protect routes, now I want to get user id in unprotected (common) routes, for example:

Protected:

/Profile

Unprotected:

/Search

I able to get user id in protected routes, for example ProfileController.php, like this:

```<code>$id = auth()->guard('agent')->user()->id;
</code>```

But I want to get this in searchController.php but it return null, any idea?

api.php:

```<code>Route::middleware('auth:agent')->group(function () {
    Route::get('profile', 'ProfileController@details');
});

Route::post('search', 'searchController@search');
</code>```

In other hand, when user is logged, and open search page, I want to get user id.

答:
So continuing from my comments above - here's what I tried and works without any glitch:

config/auth.php

```<code>'guards' => [
    //..

    'agent' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    //...
],
</code>```

app/Http/Controllers/HomeController.php

```<code>public function index(): JsonResponse
{
    return new JsonResponse([
        'user' => auth()->guard('agent')->user(),
    ]);
}
</code>```

routes/web.php

```<code>Route::get('/', 'HomeController@index')->name('home');
</code>```

tests/Feature/HomeTest.php

```<code>/**
 * @test
 */
public function returns_user()
{
    $this->actingAs($user = factory(User::class)->create(), 'agent');

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user, 'agent');

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user_id' => $user->toArray()
    ]);
}

/**
 * @test
 */
public function does_not_return_user_for_non_agent_guard()
{
    $this->actingAs($user = factory(User::class)->create(), 'web');

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user, 'web');

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user_id' => null
    ]);
}
</code>```

And the test passes just fine so I can only guess that there's either something with your implementation of the agent guard or the auth:agent middleware.

Body:
I am using Laravel guard to to protect routes, now I want to get user id in unprotected (common) routes, for example:

Protected:

/Profile

Unprotected:

/Search

I able to get user id in protected routes, for example ProfileController.php, like this:

$id = auth()->guard('agent')->user()->id;

But I want to get this in searchController.php but it return null, any idea?

api.php:

Route::middleware('auth:agent')->group(function () {
    Route::get('profile', 'ProfileController@details');
});

Route::post('search', 'searchController@search');

In other hand, when user is logged, and open search page, I want to get user id.

Body:
So continuing from my comments above - here's what I tried and works without any glitch:

config/auth.php

'guards' => [
    //..

    'agent' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    //...
],

app/Http/Controllers/HomeController.php

public function index(): JsonResponse
{
    return new JsonResponse([
        'user' => auth()->guard('agent')->user(),
    ]);
}

routes/web.php

Route::get('/', 'HomeController@index')->name('home');

tests/Feature/HomeTest.php

/**
 * @test
 */
public function returns_user()
{
    $this->actingAs($user = factory(User::class)->create(), 'agent');

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user, 'agent');

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user_id' => $user->toArray()
    ]);
}

/**
 * @test
 */
public function does_not_return_user_for_non_agent_guard()
{
    $this->actingAs($user = factory(User::class)->create(), 'web');

    $this->assertTrue($user->exists);
    $this->assertAuthenticatedAs($user, 'web');

    $response = $this->get(route('home'));

    $response->assertExactJson([
        'user_id' => null
    ]);
}

And the test passes just fine so I can only guess that there's either something with your implementation of the agent guard or the auth:agent middleware.


问:
Can't connect to database with pdo
This is my code to connect to a database.

```<code>$host = 'http://databases.000webhost.com/';
    $dbname = 'myDb';
    $username = 'root';
    $password = 'myPsw';

  try {

    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    echo "Connecté à $dbname sur $host avec succès.";

  } catch (PDOException $e) {

    die("Impossible de se connecter à la base de données $dbname :" . $e->getMessage());

  }
</code>```

I followed this tutorial: https://waytolearnx.com/2019/10/connexion-a-une-base-de-donnees-mysql-avec-php-pdo.html

And here is the error that comes up.

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Failed to parse address “http://databases.000webhost.com

答: Use $host = 'databases.000webhost.com';, you just need to provide host name (or IP address), not URL. MySQL doesn't use HTTP protocol.

Title: Can't connect to database with pdo

Body:
This is my code to connect to a database.

$host = 'http://databases.000webhost.com/';
    $dbname = 'myDb';
    $username = 'root';
    $password = 'myPsw';

  try {

    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);

    echo "Connecté à $dbname sur $host avec succès.";

  } catch (PDOException $e) {

    die("Impossible de se connecter à la base de données $dbname :" . $e->getMessage());

  }

I followed this tutorial: https://waytolearnx.com/2019/10/connexion-a-une-base-de-donnees-mysql-avec-php-pdo.html

And here is the error that comes up.

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Failed to parse address “http://databases.000webhost.com


问:
stupid questionmarks in wordpress using @fontface
I made a wordpress theme.

In Chrome on Windows, some stupid question marks are displayed.

The result works fine in all other browsers, including Chrome under macOS.

答:
Declare page encoding:

http://tlt.its.psu.edu/suggestions/international/web/tips/declare.html


问:
Typescript not reading the correct type
I have this React hook:

import { ChangeEvent, RefObject, useEffect, useState } from "react";

type OriginalOnchange = (e: ChangeEvent<HTMLInputElement>) => void;
type OnchangeEvent = ChangeEvent<HTMLInputElement>;
export type OnChangeWrapper = (originalOnchange?: OriginalOnchange) => (onchangeEvent: OnchangeEvent) => void;

export const useTrackValidity = (
  inputRef: RefObject<HTMLInputElement | undefined>,
  value: string,
  invalidInputMessage?: string
) => {
  const [isValid, setIsValid] = useState<boolean>();

  const onChangeWrapper: OnChangeWrapper = (originalOnchange?: OriginalOnchange) => (onChangeEvent: OnchangeEvent) => {
    setIsValid(!(!!invalidInputMessage || !onChangeEvent.currentTarget.validity.valid));
    if (!!originalOnchange) {
      originalOnchange(onChangeEvent);
    }
  };

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.setCustomValidity(invalidInputMessage || "");
      setIsValid(!(!!invalidInputMessage || !inputRef.current.validity.valid));
    }
  }, [inputRef, invalidInputMessage, value]);

  return [isValid, onChangeWrapper];
};

```

<p>When I call it like this:</p>

<pre class="lang-js prettyprint-override"><code> const [isValid, onChangeWrapper] = useTrackValidity(inputRef, value?.toString() ?? "", invalidInputMessage);

  return (
    <StyledInput
      ref={inputRef}
      type={inputType || type}
      name={inputName || name}
      required={isRequired || required}
      onChange={onChangeWrapper(onChange)}
      onBlur={onChangeWrapper()}
      isValid={isValid}
      value={value}
      {...props}
    />
  );
</code>```

I get this error:

```<code>TS2349: This expression is not callable.
  Not all constituents of type 'boolean | OnChangeWrapper' are callable.
    Type 'false' has no call signatures. TS2722: Cannot invoke an object which is possibly 'undefined'.
</code>```

whenever I call onChangeWrapper.

When I change the above to this:

const [isValid, onChangeWrapper] = useTrackValidity(inputRef, value?.toString() ?? "", invalidInputMessage) as [
    boolean | undefined,
    OnChangeWrapper
  ];
```

It does work, which strikes me as odd because I basically reiterated the return type.

答:
TypeScript infers that the returned array will be Array<boolean|yourfunctiontype> — that is, that all elements will be the intersection of those types. boolean isn't callable, so you can't call any of the elements without some kind of guard.

To solve it, tell TypeScript that your hook function returns [boolean, yourFunctionType], specifically:

```<code>type onChangeWrapperType = /*...the function type here...*/;

// ...

export const useTrackValidity = (
  // ...
): [boolean, onChangeWrapperType] => {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−− here
    // ...
    const onChangeWrapper: onChangeWrapperType = /*...*/;
    // ...
    return [isVaild, onChangeWrapper];
};
</code>```

Title: Typescript not reading the correct type

Body:
I have this React hook:

import { ChangeEvent, RefObject, useEffect, useState } from "react";

type OriginalOnchange = (e: ChangeEvent<HTMLInputElement>) => void;
type OnchangeEvent = ChangeEvent<HTMLInputElement>;
export type OnChangeWrapper = (originalOnchange?: OriginalOnchange) => (onchangeEvent: OnchangeEvent) => void;

export const useTrackValidity = (
  inputRef: RefObject<HTMLInputElement | undefined>,
  value: string,
  invalidInputMessage?: string
) => {
  const [isValid, setIsValid] = useState<boolean>();

  const onChangeWrapper: OnChangeWrapper = (originalOnchange?: OriginalOnchange) => (onChangeEvent: OnchangeEvent) => {
    setIsValid(!(!!invalidInputMessage || !onChangeEvent.currentTarget.validity.valid));
    if (!!originalOnchange) {
      originalOnchange(onChangeEvent);
    }
  };

  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.setCustomValidity(invalidInputMessage || "");
      setIsValid(!(!!invalidInputMessage || !inputRef.current.validity.valid));
    }
  }, [inputRef, invalidInputMessage, value]);

  return [isValid, onChangeWrapper];
};

When I call it like this:

 const [isValid, onChangeWrapper] = useTrackValidity(inputRef, value?.toString() ?? "", invalidInputMessage);

  return (

Body:
TypeScript infers that the returned array will be Array<boolean|yourfunctiontype> — that is, that all elements will be the intersection of those types. boolean isn't callable, so you can't call any of the elements without some kind of guard.

To solve it, tell TypeScript that your hook function returns [boolean, yourFunctionType], specifically:

type onChangeWrapperType = /*...the function type here...*/;

// ...

export const useTrackValidity = (
  // ...
): [boolean, onChangeWrapperType] => {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−− here
    // ...
    const onChangeWrapper: onChangeWrapperType = /*...*/;
    // ...
    return [isVaild, onChangeWrapper];
};


答:
None could mean that it did not find a solution. Most likely your limits are too low
by increasing the limits, it works fine.
but for better understanding, it's better to check solver status. time limit errors mostly refer to the low limitations.
in this example we have many value more than 300 in time matrix but the maximum time for every vehicle is 300.so there is not a feasible solution for this problem.</p>

Title: ortools vrp does not give me any solution

Body:
I want solve a vehicle routing problem with ORTools, both distance and duration matrix will be used.
but the problem is when I change the matrix , it wouldn't give me any solutions anymore!
there are 2 groups of matrixes. with the commented matrixes there is solution, but with the other group, there is not. do you have any idea why this is happening:

from __future__ import print_function
from ortools.constraint_solver import routing_enums_pb2
from ortools.constraint_solver import pywrapcp

def create_data_model():
    """Stores the data for the problem."""
    data = {}
    #data['distance_matrix']=[[0, 329, 146, 157, 318, 528, 457, 242, 491, 335, 471, 456, 391,       128, 461, 555, 460], [329, 0, 399, 384, 544, 493, 339, 378, 108, 243, 125, 394, 136, 561, 505, 315, 447], [146, 399, 0, 262, 471, 316, 297, 227, 548, 377, 267, 430, 383, 154, 234, 188, 400], [157, 384, 262, 0, 440, 271, 383, 525, 223, 367, 511, 354, 112, 539, 159, 152, 373], [318, 544, 471, 440, 0, 423, 112, 381, 346, 512, 161, 239, 581, 291, 284, 145, 143], [528, 493, 316, 271, 423, 0, 380, 196, 409, 212, 199, 277, 387, 515, 391, 261, 318], [457, 339, 297, 383, 112, 380, 0, 379, 298, 267, 482, 247, 462, 256, 296, 533, 200], [242, 378, 227, 525, 381, 196, 379, 0, 156, 230, 551, 555, 338, 372, 403, 358, 506], [491, 108, 548, 223, 346, 409, 298, 156, 0, 140, 532, 405, 531, 129, 220, 482, 222], [335, 243, 377, 367, 512, 212, 267, 230, 140, 0, 418, 440, 526, 255, 455, 296, 430], [471, 125, 267, 511, 161, 199, 482, 551, 532, 418, 0, 439, 285, 181, 254, 208, 304], [456, 394, 430, 354, 239, 277, 247, 555, 405, 440, 439, 0, 397, 229, 121, 385, 147], [391, 136, 383, 112, 581, 387, 462, 338, 531, 526, 285, 397, 0, 544, 205, 197, 226], [128, 561, 154, 539, 291, 515, 256, 372, 129, 255, 181, 229, 544, 0, 150, 204, 516], [461, 505, 234, 159, 284, 391, 296, 403, 220, 455, 254, 121, 205, 150, 0, 192, 544], [555, 315, 188, 152, 145, 261, 533, 358, 482, 296, 208, 385, 197, 204, 192, 0, 138], [460, 447, 400, 373, 143, 318, 200, 506, 222, 430, 304, 147, 226, 516, 544, 138, 0]]

    data['distance_matrix']=[[0, 228, 299, 301, 235, 208, 405, 447, 144, 579], [228, 0, 343, 288, 357, 426, 530, 510, 122, 490], [299, 343, 0, 236, 228, 523, 274, 377, 397, 530], [301, 288, 236, 0, 594, 523, 289, 397, 154, 380], [235, 357, 228, 594, 0, 558, 370, 444, 173, 558], [208, 426, 523, 523, 558, 0, 219, 278, 504, 507], [405, 530, 274, 289, 370, 219, 0, 195, 283, 257], [447, 510, 377, 397, 444, 278, 195, 0, 407, 417], [144, 122, 397, 154, 173, 504, 283, 407, 0, 273], [579, 490, 530, 380, 558, 507, 257, 417, 273, 0]]
     data['time_matrix']=[[0, 205, 519, 308, 428, 574, 399, 138, 573, 541], [205, 0, 447, 578, 296, 536, 135, 345, 198, 315], [519, 447, 0, 209, 438, 174, 231, 382, 104, 522], [308, 578, 209, 0, 235, 264, 492, 305, 134, 538], [428, 296, 438, 235, 0, 600, 177, 435, 204, 556], [574, 536, 174, 264, 600, 0, 476, 119, 183, 476], [399, 135, 231, 492, 177, 476, 0, 497, 208, 167], [138, 345, 382, 305, 435, 119, 497, 0, 344, 454], [573, 198, 104, 134, 204, 183, 208, 344, 0, 422], [541, 315, 522, 538, 556, 476, 167, 454, 422, 0]]
    data['cost_matrix']=[[0, 160, 135, 433, 581, 453, 336, 329, 343, 237], [160, 0, 313, 596, 576, 458, 264, 380, 348, 354], [135, 313, 0, 591, 391, 211, 561, 236, 304, 414], [433, 596, 591, 0, 539, 253, 427, 300, 214, 118], [581, 576, 391, 539, 0, 243, 521, 499, 560, 255], [453, 458, 211, 253, 243, 0, 571, 216, 121, 314], [336, 264, 561, 427, 521, 571, 0, 425, 271, 165], [329, 380, 236, 300, 499, 216, 425, 0, 425, 549], [343, 348, 304, 214, 560, 121, 271, 425, 0, 176], [237, 354, 414, 118, 255, 314, 165, 549, 176, 0]]
    data['num_vehicles'] = 4
    data['depot'] = 0
    return data

def print_solution(data, manager, routing, assignment):
"""Prints assignment on console."""
total_cost ,total_distance,total_time= 0,0,0
print('Objective: {}'.format(assignment.ObjectiveValue()))
distance_dimension=routing.GetDimensionOrDie('Distance')
time_dimension=routing.GetDimensionOrDie('Time')
for vehicle_id in range(data['num_vehicles']):
    index = routing.Start(vehicle_id)
    plan_output = 'Route for vehicle {}:\n'.format(vehicle_id)
    route_cost = 0
    route_distance = 0
    route_time = 0
    while not routing.IsEnd(index):
        plan_output += ' {} -> '.format(manager.IndexToNode(index))
        distance_var=distance_dimension.CumulVar(index)
        time_var=time_dimension.CumulVar(index)
        previous_index = index
        index = assignment.Value(routing.NextVar(index))
        route_cost += routing.GetArcCostForVehicle(previous_index, index, vehicle_id)
        route_distance+=assignment.Value(distance_var)
        route_time+=assignment.Value(time_var)
    plan_output += '{}\n'.format(manager.IndexToNode(index))
    plan_output += 'Cost of the route: {0}\nDistance of the route: {1}m\nTime of route: {2}\n'.format(
        route_cost,
        route_distance,
        route_time)
    print(plan_output)
    total_cost += route_cost
    total_time+=route_time
    total_distance+=route_distance
print('Total Cost of all routes: {}\nTotal Distance of all routes: {}\nTotal Time of all routes: {}\n'.format(total_cost,total_distance,total_time))

def get_routes(manager, routing, solution, num_routes):
"""Get vehicle routes from a solution and store them in an array."""
# Get vehicle routes and store them in a two dimensional array whose
# i,j entry is the jth location visited by vehicle i along its route.
routes = []
for route_nbr in range(num_routes):
    index = routing.Start(route_nbr)
    route = [manager.IndexToNode(index)]
    while not routing.IsEnd(index):
        index = solution.Value(routing.NextVar(index))
        route.append(manager.IndexToNode(index))
    routes.append(route)
return routes

def main():
# Instantiate the data problem.
data = create_data_model()

# Create the routing index manager.
manager = pywrapcp.RoutingIndexManager(len(data['cost_matrix']), data['num_vehicles'], data['depot'])

# Create Routing Model.
routing = pywrapcp.RoutingModel(manager)

# Create and register a transit callback.
def cost_callback(from_index, to_index):
    """Returns the distance between the two nodes."""
    # Convert from routing variable Index to distance matrix NodeIndex.
    from_node = manager.IndexToNode(from_index)
    to_node = manager.IndexToNode(to_index)
    return data['cost_matrix'][from_node][to_node]

transit_callback_index = routing.RegisterTransitCallback(cost_callback)
routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)

# Add Cost constraint.
routing.AddDimension(
    transit_callback_index,
    0,  # no slack
    3000,  # vehicle maximum travel distance
    False,  # start cumul to zero
    'Cost')
cost_dimension = routing.GetDimensionOrDie('Cost')
cost_dimension.SetGlobalSpanCostCoefficient(1000)

#Add Distance constraint.
def distance_callback(from_index,to_index):
    from_node = manager.IndexToNode(from_index)
    to_node = manager.IndexToNode(to_index)
    return data['distance_matrix'][from_node][to_node]

distance_callback_index=routing.RegisterTransitCallback(distance_callback)
routing.AddDimension(
    distance_callback_index,
    0,
    3000,
    False,
    'Distance')
distance_dimension=routing.GetDimensionOrDie('Distance')

#Add Time constraint.
def time_callback(from_index,to_index):
    from_node = manager.IndexToNode(from_index)
    to_node = manager.IndexToNode(to_index)
    return data['time_matrix'][from_node][to_node]

time_callback_index=routing.RegisterTransitCallback(time_callback)
routing.AddDimension(
    time_callback_index,
    0,
    300,
    False,
    'Time')
time_dimension=routing.GetDimensionOrDie('Time')

# Setting first solution heuristic.
search_parameters = pywrapcp.DefaultRoutingSearchParameters()
search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)
search_parameters.solution_limit = 100
search_parameters.time_limit.seconds = 3

# Solve the problem.
assignment = routing.SolveWithParameters(search_parameters)

# Print solution on console.
if assignment:
    print_solution(data, manager, routing, assignment)
routes = get_routes(manager, routing, assignment, data['num_vehicles'])
# Display the routes.
for i, route in enumerate(routes):
    print('Route', i, route)

if __name__ == '__main__':
main()


问:
non-wasteful way to store subgraphs
Suppose I have 6 elements: A, B, C, D, E, and F.  A connects to B (alternatively B connects to A -- there's no notion of direction), B connects to C, D connects to E, and F is not connected to anything.  But what I actually want is not the direct connections but just to know which elements have some path connecting them.

I know one way of encoding this in Python is with a 6x6 adjacency matrix.  But as it's a fairly sparse matrix, that is memory wasteful.

The other way I know of with a dictionary.  Here's how it would look in Python.

```<code>graph = {
    A: [B, C],
    B: [A, C],
    C: [A, B],
    D: [E],
    E: [D],
    F: []
}
</code>```

However, this structure really seems to be better at keeping track of direct connections rather than connected subgraphs.  In particular, there is a lot of wasted memory being used as for example A: [B, C] and B: [A, C] encode the exact same thing.

Can anyone recommend a data structure that would be better for storing this information and/ or an algorithm for creating that structure which scales better than either an adjacency matrix or the above dictionary?

答:
If you're strictly looking for efficient storage of a non-directed graph, you could use a string with a couple of conventions.  First the node names pairings (edges) are always expressed in descending alphabetical (or alphanumerical) order. Second, you don't repeat the left side of that pairing by only listing related nodes after their larger counterpart.

This would give a string like this: "B,A|C,A,B|E,D|F"

You can go back and forth between this string encoding and the fully expanded dictionary representation in memory (which will be necessary for any meaningful manipulation):

From string to dictionary:

```<code>sGraph = "B,A|C,A,B|E,D|F"
dGraph = { v:[] for v in sGraph.replace("|",",").split(",") }
dGraph.update({ v[0]:v[1:] for vG in sGraph.split("|") for v in[vG.split(",")]})
for v1,v2 in [(v1,v2) for v1,vN in dGraph.items() for v2 in vN]:dGraph[v2].append(v1)
</code>```

Output:

```<code>print(dGraph)
# {'B': ['A', 'C'], 'A': ['B', 'C'], 'C': ['A', 'B'], 'E': ['D'], 'D': ['E'], 'F': []}
</code>```

note: depending on your processing needs the last for loop (above) could be omitted. This would give you a full representation of the graph with no redundancy in edges (but it would make it much harder to manipulate)

```<code># {'B': ['A'], 'A': [], 'C': ['A', 'B'], 'E': ['D'], 'D': [], 'F': []}
</code>```

Form dictionary to string (based on the fully expanded representation) :

```<code>dGraph = {'B': ['A', 'C'], 'A': ['B', 'C'], 'C': ['A', 'B'], 'E': ['D'], 'D': ['E'], 'F': []}
sGraph = sorted(v for v,vN in dGraph.items() if any(v2<v for v2 in vN) or not vN)
sGraph = "|".join( ",".join([v1,*(v2 for v2 in dGraph[v1] if v2<v1)]) for v1 in sGraph)
</code>```

output:

```<code>print(sGraph)
# B,A|C,A,B|E,D|F
</code>```

The length of the string will always be smaller than 2*(E+V) where E is the number of edges and V is the number of vertices (assuming one letter/character per vertex name).

Title: non-wasteful way to store subgraphs

Body:
Suppose I have 6 elements: A, B, C, D, E, and F.  A connects to B (alternatively B connects to A -- there's no notion of direction), B connects to C, D connects to E, and F is not connected to anything.  But what I actually want is not the direct connections but just to know which elements have some path connecting them.

I know one way of encoding this in Python is with a 6x6 adjacency matrix.  But as it's a fairly sparse matrix, that is memory wasteful.

The other way I know of with a dictionary.  Here's how it would look in Python.

graph = {
    A: [B, C],
    B: [A, C],
    C: [A, B],
    D: [E],
    E: [D],
    F: []
}

However, this structure really seems to be better at keeping track of direct connections rather than connected subgraphs.  In particular, there is a lot of wasted memory being used as for example A: [B, C] and B: [A, C] encode the exact same thing.

Can anyone recommend a data structure that would be better for storing this information and/ or an algorithm for creating that structure which scales better than either an adjacency matrix or the above dictionary?

Body:
If you're strictly looking for efficient storage of a non-directed graph, you could use a string with a couple of conventions.  First the node names pairings (edges) are always expressed in descending alphabetical (or alphanumerical) order. Second, you don't repeat the left side of that pairing by only listing related nodes after their larger counterpart.

This would give a string like this: "B,A|C,A,B|E,D|F"

You can go back and forth between this string encoding and the fully expanded dictionary representation in memory (which will be necessary for any meaningful manipulation):

From string to dictionary:

sGraph = "B,A|C,A,B|E,D|F"
dGraph = { v:[] for v in sGraph.replace("|",",").split(",") }
dGraph.update({ v[0]:v[1:] for vG in sGraph.split("|") for v in[vG.split(",")]})
for v1,v2 in [(v1,v2) for v1,vN in dGraph.items() for v2 in vN]:dGraph[v2].append(v1)

Output:

print(dGraph)
# {'B': ['A', 'C'], 'A': ['B', 'C'], 'C': ['A', 'B'], 'E': ['D'], 'D': ['E'], 'F': []}

note: depending on your processing needs the last for loop (above) could be omitted. This would give you a full representation of the graph with no redundancy in edges (but it would make it much harder to manipulate)

# {'B': ['A'], 'A': [], 'C': ['A', 'B'], 'E': ['D'], 'D': [], 'F': []}

Form dictionary to string (based on the fully expanded representation) :

dGraph = {'B': ['A', 'C'], 'A': ['B', 'C'], 'C': ['A', 'B'], 'E': ['D'], 'D': ['E'], 'F': []}
sGraph = sorted(v for v,vN in dGraph.items() if any(v2<v for v2 in vN) or not vN)
sGraph = "|".join( ",".join([v1,*(v2 for v2 in dGraph[v1] if v2<v1)]) for v1 in sGraph)

output:

print(sGraph)
# B,A|C,A,B|E,D|F

The length of the string will always be smaller than 2*(E+V) where E is the number of edges and V is the number of vertices (assuming one letter/character per vertex name).


问:
Pass string class variable by reference in C++
Look at the following code:

```<code>#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}
</code>```

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?

答:
How to pass string by reference in C++?

You simply add & to the parameter.

Are strings a normal array?

No, std::string is not an array.

Body:
Look at the following code:

#include <iostream>
#include <string>
using namespace std;
void reverseStr(string arr, int start, int end)
{
    while (start < end)
    {
        swap(arr[start], arr[end]);
        ++start;
        --end;
    }
}
int main()
{
    string str = "CPP";
    reverseStr(str, 0, 3);
    cout << str;
    return 0;
}

The output is CPP, while PCC is expected.

Question: How to pass string by reference in C++? Are strings a normal array? If yes then the reference must be passed automatically, while it just creates a copy in the formal parameters.

My question is that why I have to use my function like void reverseStr(string &arr, int start, int end) instead of just void reverseStr(string arr, int start, int end). Why I have to use extra & informal parameters? Aren't string variables just other arrays?


问:
Uncaught ReferenceError: writeIn is not defined at change (<anonymous>:5:4) at <anonymous>:7:1
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

```<code>function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);
</code>```

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

```<code>var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);
</code>```

答:
Be careful in your code. First of all you missed the ";" in the third line. In this case it's OK, but I recomment you input ";" after every instruction.

Secondly, is the a global variable? And id? Use at least var, but better let or const to declare the variables. As I undersand id is local and a is global (from the parent scope). Here you can read about let, const and var.

And about your answer: there are no function writeIn. You shold just assign:

```<code>id.style.backgoundColor = a;
</code>```

Body:
I try to write a function to change the color of a text, but the error occurs. I winder how to fix this.

function change() {
var colour = prompt("What's your favourite colour?");
a = colour.value
id = document.querySelector('.tab ');
id.style.backgoundColor = writeIn(a) ;
}
change();
console.log(a);

I edited the code as below, the error went, but still the value is undifined and no change occurs in the text.

var changing = function change() {
var cls = document.querySelector('.tab ');
var colour = prompt("What's your favourite colour?");
var a = colour.value;
cls.style.backgoundColor = a ;
alert(a);
}
changing();
console.log(a);

Body:
Be careful in your code. First of all you missed the ";" in the third line. In this case it's OK, but I recomment you input ";" after every instruction.

Secondly, is the a global variable? And id? Use at least var, but better let or const to declare the variables. As I undersand id is local and a is global (from the parent scope). Here you can read about let, const and var.

And about your answer: there are no function writeIn. You shold just assign:

id.style.backgoundColor = a;


问:
TypeError: undefined is not an object (evaluating 'event.target.value')
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

```<code>export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}
</code>```

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

答:
You're using React Native and not React DOM. <TextInput />'s onChangeText does not pass an event as the first argument, just a plain string. In general, event handling code you see from regular React examples that utilize the DOM don't transfer well here because those events don't actually exist in their native counterparts.

You need to change your current event handling code from this

```<code>  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }
</code>```

to this:

```<code>  handleChange(text) {
    this.setState({
      email: text,
      password: text,
    });
  }
</code>```

However, this will also fail because as @Rawrplus mentioned, you have not bound the method to the context. this in JavaScript is special and doesn't work like it does in other languages and refers to the execution context of a method rather than the definition context. This can be fixed by using arrow functions:

```<code>  handleChange = (text) => {
    this.setState({
      email: text,
      password: text,
    });
  }
</code>```

Body:
I'm working on a React Native project and I'm trying to make a Login form.

But I have some trouble to handle the text change in the TextInput.

My login form code

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  onLogin() {
    const { email, password } = this.state;
    Alert.alert('Credentials', `${email} + ${password}`);
  }

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

  render() {
    const { email, password } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.form}>
          <Title>Connectez-vous</Title>
          <TextInput
            style={{ backgroundColor: '#f8f8ff' }}
            value={email}
            onChangeText={this.handleChange}
            label="Adresse email"
            mode="outlined"
          />
          <TextInput
            style={{
              backgroundColor: '#f8f8ff',
            }}
            value={password}
            onChangeText={this.handleChange}
            label="Mot de passe"
            mode="outlined"
            secureTextEntry
          />
          <Button
            mode="outlined"
            onPress={() => this.onLogin}
            style={{ marginTop: '5%', marginHorizontal: '25%' }}
          >
            Connexion
          </Button>
        </View>
      </View>
    );
  }
}

When I try to write something in the TextInput I got the error : TypeError: undefined is not an object (evaluating 'event.target.value').

Body:
You're using React Native and not React DOM. <TextInput />'s onChangeText does not pass an event as the first argument, just a plain string. In general, event handling code you see from regular React examples that utilize the DOM don't transfer well here because those events don't actually exist in their native counterparts.

You need to change your current event handling code from this

  handleChange(event) {
    this.setState({
      email: event.target.value,
      password: event.target.value,
    });
  }

to this:

  handleChange(text) {
    this.setState({
      email: text,
      password: text,
    });
  }

However, this will also fail because as @Rawrplus mentioned, you have not bound the method to the context. this in JavaScript is special and doesn't work like it does in other languages and refers to the execution context of a method rather than the definition context. This can be fixed by using arrow functions:

  handleChange = (text) => {
    this.setState({
      email: text,
      password: text,
    });
  }


问:
I want the CSS of a page to change when a button is clicked
I found how you could do this with individual elements but I couldn't find anything that would change the the body CSS of a page. I am trying to make a thing where it will switch between light and dark mode when you click the button.

```<code><!DOCTYPE html>
<button style="background-color: #252525;
border: 2px;
border-style: solid;
border-color: white;
color: white;
padding: 10px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
font-weight: bold;
margin: 4px 2px;
cursor: pointer;" id="changethemebutton" onclick="changeTheme()">Change Theme</button>
</code>```

```<code>function changeTheme() {
document.getElementById(".background").style.background = "black";
}
</script>
<style>
body{
    background-color:white
}
</style>
</code>```

答:
You're trying to target an element with a class using an incorrect method. getElementById targets elements with a specified id. If you're trying to target a class, the most ideal method to do this with is querySelector:

```<code>document.querySelector(".background").style.background = "black";
</code>```

Body:
I found how you could do this with individual elements but I couldn't find anything that would change the the body CSS of a page. I am trying to make a thing where it will switch between light and dark mode when you click the button.

<!DOCTYPE html>
<button style="background-color: #252525;
border: 2px;
border-style: solid;
border-color: white;
color: white;
padding: 10px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
font-weight: bold;
margin: 4px 2px;
cursor: pointer;" id="changethemebutton" onclick="changeTheme()">Change Theme</button>

function changeTheme() {
document.getElementById(".background").style.background = "black";
}
</script>

Body:
You're trying to target an element with a class using an incorrect method. getElementById targets elements with a specified id. If you're trying to target a class, the most ideal method to do this with is querySelector:

document.querySelector(".background").style.background = "black";


答:
This works</p>

```<code>$user = User::firstOrCreate(

    ['email'=> $social_user->getEmail(),
     'username'=> $social_user->getName(),
     'name'=> $social_user->getName(),
     'picture'=> $social_user->getAvatar(),
     'password'=> 'sdsdsdsad',
     'ip_address'=> '127.0.0.1'],
);
</code>```

Body:
User Data is not saving to Database in Laravel 6. I am using socialite to save data to the database with the following code lines.

protected $fillable = [
    'email','name','password','username','picture'
];

In the login controller. I am able to fetch data from socialite correctly(I Checked).

$user = User::firstOrCreate(

          ['email'=> $social_user->getEmail()],
          ['username'=> $social_user->getName()],
          ['name'=> $social_user->getName()],
          ['picture'=> $social_user->getAvatar()],
          ['password'=> 'sdsdsdsad'],
          ['ip_address'=> '127.0.0.1'],

      );

Body:
This works

$user = User::firstOrCreate(

    ['email'=> $social_user->getEmail(),
     'username'=> $social_user->getName(),
     'name'=> $social_user->getName(),
     'picture'=> $social_user->getAvatar(),
     'password'=> 'sdsdsdsad',
     'ip_address'=> '127.0.0.1'],
);