问:
Flashlight function crashes after returning from activity
I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.

It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.

This is my code (i did not include my imports to save some space):

```<code>public class MainActivity extends AppCompatActivity {

//    Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;

//  Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;

//    MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;

//  Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;

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

    vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);

    myToolbar = (Toolbar) findViewById(R.id.toolbar);
    mySpinner = (Spinner) findViewById(R.id.spinner);
    flashlightButton = (ImageButton) findViewById(R.id.image);

    myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
    myToolbar.setTitle(getResources().getString(R.string.app_name));

    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
            R.layout.custom_spinner_itam,
            getResources().getStringArray(R.array.Toolbar_dropdown_entries));
    myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner.setAdapter(myAdapter);

    ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
    ringtone = (Button) this.findViewById(R.id.ringtone);

    message = (EditText)findViewById(R.id.messagePublish);

    mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(MainActivity.this,
                    mySpinner.getSelectedItem().toString(),
                    Toast.LENGTH_SHORT)
                    .show();

            if (mySpinner.getSelectedItem().toString().equals("Exit App")){
                exit();
            }else if(mySpinner.getSelectedItem().toString().equals("Settings"))
            {
                Intent intent;
                intent = new Intent(MainActivity.this, SettingsActivity.class);
                intent.putExtra("CURRENT_IP",client.getServerURI());
                intent.putExtra("CURRENT_QOS", Integer.toString(qos));
                intent.putExtra("CURRENT_TOPIC",topicStr);
                startActivityForResult(intent,1);   //  this is so we can take the results back to mainActivity later
            }else{
                System.out.println("ara3e, den exw diale3ei tipota");
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }

    });

    //Flashlight on Create start
    if(isFlashAvailable())   //  check if flash is available on this device, if it is open camera (module) and make button clickable
    {
        camera = Camera.open();
        parameters = camera.getParameters();

    }else
    {  //  if flashlight is not supported dont let the user click the button

        flashlightButton.setEnabled(false);
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Error.");
        builder.setMessage("Flashlight not available on this device. \nExit?");   //  inform the user and let him choose how to continue
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                exit();
            }
        });
        builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    flashlightButton.setOnClickListener(new View.OnClickListener() { //  listen for flash button clicks
        @Override
        public void onClick(View view) {
            flashOnOff();
        }
    });

    ringtone.setOnClickListener(new View.OnClickListener() {    //  Ringtone listener
        @Override
        public void onClick(View view) {
            ringtoneOnOff(ringtoneMP);
        }
    });

    client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
//        client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);

    options = new MqttConnectOptions();
    options.setUserName(Username);
    options.setPassword(Password.toCharArray());

    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
                Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
                setSubscription(client,topicStr,qos);
            }
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                // Something went wrong e.g. connection timeout or firewall problems
                Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
                Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }

    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable throwable) {
            Log.d("Connection:"," Lost");
        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
            myMessageArrived(s,mqttMessage);
        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
        }
    });

}

//Flashlight start
@Override
protected void onStop() {
    super.onStop();
    if(camera!=null)
    {
        camera.release();
        camera = null;
    }
}
//Flashlight end

//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
            .setMessage("Do you want to exit application?")
            .setPositiveButton("Yes", new
                    DialogInterface.OnClickListener() {

                        // when yes is clicked exit the application
                        public void onClick(DialogInterface arg0, int arg1) {
                            exit();
                        }
                    })
            .setNegativeButton("No", new
                    DialogInterface.OnClickListener() {

                        // when no is clicked do nothing
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    })
            .show();

}
//Backkey end

// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
    try{
        client.subscribe(topic, qos);
    }
    catch (MqttException e){
        e.printStackTrace();
    }
}

private void unsetSubscription(MqttAndroidClient client,String topic){
    try{
        client.unsubscribe(topic);
    }catch (MqttException e){
        e.printStackTrace();
    }
}

public void conn(View v){
    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
                Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
                setSubscription(client,topicStr,qos);
//                    pub();
            }
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                // Something went wrong e.g. connection timeout or firewall problems
                Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

public void disconn(View v){
    if (client.isConnected()) {
        try {
            IMqttToken token = client.disconnect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    // We are connected
                    Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    // Something went wrong e.g. connection timeout or firewall problems
                    Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }else {
        Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public void pub(View v) {
    String topic = topicStr;
    try {

        client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

private void ringtoneOnOff(MediaPlayer ringtoneMP){
    if (ringtoneMP.isPlaying()){
        ringtoneMP.pause();
    }else{
        ringtoneMP.start();
    }
}

private void myMessageArrived(String s,MqttMessage mqttMessage){
    if ((mqttMessage.toString()).equals("Flash on")) {
        if (isFlashOn()) {
            Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
            flashOnOff();
        }
    } else if ((mqttMessage.toString()).equals("Flash off")) {
        if (isFlashOn()) {
            Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
            flashOnOff();
        } else {
            Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
        }
    } else if ((mqttMessage.toString()).equals("Ringtone on")) {
        if (ringtoneMP.isPlaying()) {
            Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
            ringtoneMP.start();
        }
    } else if ((mqttMessage.toString()).equals("Ringtone off")) {
        if (ringtoneMP.isPlaying()) {
            ringtoneMP.pause();
        } else {
            Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
        }
    } else {
        Log.d("INFO:", "This Command does not exist");
    }
    vibrator.vibrate(500);
    myRingtone.play();
}

public void exit(){
    finish();
    System.exit(0);
}

public boolean isFlashAvailable(){  //  boolean function that returns true if flash is supported on this device

    return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

public void flashOnOff(){   //  self explanatory

    if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){  //  if the flash is on torch mode
        Log.d("BHKE","408");
        this.flashlightButton.setImageResource(R.drawable.off);
        this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);  //  turn it off
    }else{
        Log.d("BHKE","412");
        this.flashlightButton.setImageResource(R.drawable.on);
        this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);    //  else turn it on
    }
    this.camera.setParameters(this.parameters);
    this.camera.startPreview();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    String tempBrokerIp;
    String temptopic="";
    Integer tempqos;
    Boolean BrokerIpChanged = true;
    Boolean qosChanged = true;
    Boolean topicChanged = true;
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case (1) : {
            if (resultCode == Activity.RESULT_OK) {
                tempBrokerIp = data.getStringExtra("CURRENT_IP");
                tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
                temptopic = data.getStringExtra("CURRENT_TOPIC");

                Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
                if (tempBrokerIp.equals(BrokerIp)) {
                    BrokerIpChanged=false;
                    Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
                }
                if (tempqos.equals(qos)) {
                    qosChanged=false;
                    Log.i("qosChanged =", qosChanged.toString());
                }else {
                    qos = tempqos;
                }
                if (temptopic.equals(topicStr)){
                    topicChanged=false;
                    Log.i("topicChanged =", topicChanged.toString());
                }else{
                    topicStr = temptopic;
                }
                if (!BrokerIpChanged && !qosChanged && !topicChanged) return;

                if (BrokerIpChanged){
                    try {
                        client.disconnect();

                        BrokerIp = tempBrokerIp;
                        topicStr = temptopic;
                        qos = tempqos;
//                            final String clientId = MqttClient.generateClientId();
                        client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);

                        options = new MqttConnectOptions();
                        options.setUserName(Username);
                        options.setPassword(Password.toCharArray());
//                            options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);  //  to user the latest mqtt version

                        try {
                            IMqttToken token = client.connect(options);
                            token.setActionCallback(new IMqttActionListener() {
                                @Override
                                public void onSuccess(IMqttToken asyncActionToken) {
                                    // We are connected
                                    Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
                                    Log.w("Mqtt","Connected to:"+ BrokerIp);

                                    try{
                                        Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
                                        client.subscribe(topicStr,qos);
                                    }catch (MqttException e){
                                        e.printStackTrace();
                                    }
                                }
                                @Override
                                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                                    // Something went wrong e.g. connection timeout or firewall problems
                                    Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
                                    Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
                                }

                            });
                            System.out.println(client.isConnected());
//                                if (client.isConnected()){
//                                    Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
//                                    client.subscribe(temptopic,tempqos);
//                                }

                        } catch (MqttException e) {
                            e.printStackTrace();
                        }

                        client.setCallback(new MqttCallback() {
                            @Override
                            public void connectionLost(Throwable throwable) {

                            }

                            @Override
                            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                                myMessageArrived(s,mqttMessage);
                            }

                            @Override
                            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                            }
                        });

                    }catch (MqttException e){
                        e.printStackTrace();
                    }
                }else
                {
                    try {
                        client.unsubscribe(topicStr);
                        client.subscribe(temptopic,tempqos);

                        topicStr = temptopic;
                        qos = tempqos;

                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
            break;
        }
    }
}

public boolean isFlashOn(){
    return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}
</code>```

I can provide the settings activity code too is needed

答:
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.

Ι added :

```<code>     if (isFlashAvailable()){
        camera = Camera.open();
        parameters = camera.getParameters();
    }
</code>```

at the onActivityResult start and it works like a charm.

Body:
I have this android app which connects to an mqtt broker and listens for instructions to play/pause a ringtone or open/close the flashlight.

It runs as supposed to until i change my settings and call the function flashOnOff after this. Then i get a null pointer exception but i can not understand why.

This is my code (i did not include my imports to save some space):

public class MainActivity extends AppCompatActivity {

//    Layout related parameters
Toolbar myToolbar;
Spinner mySpinner;
ImageButton flashlightButton;
Button ringtone;
EditText message;

//  Camera/flashlight related parameters
Camera camera;
Camera.Parameters parameters;

//    MQTT related parameters
private String BrokerIp = "tcp://192.168.1.3:1883";
private int qos = 2;
static String Username = "user1";
static String Password = "user1";
String topicStr = "commands";
String clientId = "AndroidClient";
MqttConnectOptions options;
MqttAndroidClient client;
Vibrator vibrator;

//  Ringtone related parameters
Ringtone myRingtone;
MediaPlayer ringtoneMP ;

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

    vibrator = (Vibrator)getSystemService(VIBRATOR_SERVICE);

    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    myRingtone = RingtoneManager.getRingtone(getApplicationContext(),uri);

    myToolbar = (Toolbar) findViewById(R.id.toolbar);
    mySpinner = (Spinner) findViewById(R.id.spinner);
    flashlightButton = (ImageButton) findViewById(R.id.image);

    myToolbar.setLogo(R.drawable.twoguyswatchmrrobot);
    myToolbar.setTitle(getResources().getString(R.string.app_name));

    ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(MainActivity.this,
            R.layout.custom_spinner_itam,
            getResources().getStringArray(R.array.Toolbar_dropdown_entries));
    myAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner.setAdapter(myAdapter);

    ringtoneMP = MediaPlayer.create(this,R.raw.games_of_thrones);
    ringtone = (Button) this.findViewById(R.id.ringtone);

    message = (EditText)findViewById(R.id.messagePublish);

    mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            Toast.makeText(MainActivity.this,
                    mySpinner.getSelectedItem().toString(),
                    Toast.LENGTH_SHORT)
                    .show();

            if (mySpinner.getSelectedItem().toString().equals("Exit App")){
                exit();
            }else if(mySpinner.getSelectedItem().toString().equals("Settings"))
            {
                Intent intent;
                intent = new Intent(MainActivity.this, SettingsActivity.class);
                intent.putExtra("CURRENT_IP",client.getServerURI());
                intent.putExtra("CURRENT_QOS", Integer.toString(qos));
                intent.putExtra("CURRENT_TOPIC",topicStr);
                startActivityForResult(intent,1);   //  this is so we can take the results back to mainActivity later
            }else{
                System.out.println("ara3e, den exw diale3ei tipota");
            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }

    });

    //Flashlight on Create start
    if(isFlashAvailable())   //  check if flash is available on this device, if it is open camera (module) and make button clickable
    {
        camera = Camera.open();
        parameters = camera.getParameters();

    }else
    {  //  if flashlight is not supported dont let the user click the button

        flashlightButton.setEnabled(false);
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Error.");
        builder.setMessage("Flashlight not available on this device. \nExit?");   //  inform the user and let him choose how to continue
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
                exit();
            }
        });
        builder.setNegativeButton("Stay without flashlight", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    flashlightButton.setOnClickListener(new View.OnClickListener() { //  listen for flash button clicks
        @Override
        public void onClick(View view) {
            flashOnOff();
        }
    });

    ringtone.setOnClickListener(new View.OnClickListener() {    //  Ringtone listener
        @Override
        public void onClick(View view) {
            ringtoneOnOff(ringtoneMP);
        }
    });

    client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);
//        client = pahoMqttClient.getMqttClient(MainActivity.this,BrokerIp,clientId);

    options = new MqttConnectOptions();
    options.setUserName(Username);
    options.setPassword(Password.toCharArray());

    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
                Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
                setSubscription(client,topicStr,qos);
            }
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                // Something went wrong e.g. connection timeout or firewall problems
                Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
                Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }

    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable throwable) {
            Log.d("Connection:"," Lost");
        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
            myMessageArrived(s,mqttMessage);
        }
        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            Log.d("Delivery"," completed with iMqttDeliveryToken: " + iMqttDeliveryToken);
        }
    });

}

//Flashlight start
@Override
protected void onStop() {
    super.onStop();
    if(camera!=null)
    {
        camera.release();
        camera = null;
    }
}
//Flashlight end

//Backkey exit confirmation
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
            .setMessage("Do you want to exit application?")
            .setPositiveButton("Yes", new
                    DialogInterface.OnClickListener() {

                        // when yes is clicked exit the application
                        public void onClick(DialogInterface arg0, int arg1) {
                            exit();
                        }
                    })
            .setNegativeButton("No", new
                    DialogInterface.OnClickListener() {

                        // when no is clicked do nothing
                        public void onClick(DialogInterface arg0, int arg1) {
                        }
                    })
            .show();

}
//Backkey end

// PUBLISH MESSAGE
private void setSubscription(MqttAndroidClient client, String topic, int qos){
    try{
        client.subscribe(topic, qos);
    }
    catch (MqttException e){
        e.printStackTrace();
    }
}

private void unsetSubscription(MqttAndroidClient client,String topic){
    try{
        client.unsubscribe(topic);
    }catch (MqttException e){
        e.printStackTrace();
    }
}

public void conn(View v){
    try {
        IMqttToken token = client.connect(options);
        token.setActionCallback(new IMqttActionListener() {
            @Override
            public void onSuccess(IMqttToken asyncActionToken) {
                // We are connected
                Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
                setSubscription(client,topicStr,qos);
//                    pub();
            }
            @Override
            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                // Something went wrong e.g. connection timeout or firewall problems
                Toast.makeText(MainActivity.this, "not connected", Toast.LENGTH_SHORT).show();
            }
        });
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

public void disconn(View v){
    if (client.isConnected()) {
        try {
            IMqttToken token = client.disconnect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    // We are connected
                    Toast.makeText(MainActivity.this, "disconnected", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    // Something went wrong e.g. connection timeout or firewall problems
                    Toast.makeText(MainActivity.this, "could not disconnect", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }else {
        Toast.makeText(MainActivity.this, "Client is already disconnected", Toast.LENGTH_LONG).show();
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public void pub(View v) {
    String topic = topicStr;
    try {

        client.publish(topic, String.valueOf(message.getText()).getBytes(),qos,false);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

private void ringtoneOnOff(MediaPlayer ringtoneMP){
    if (ringtoneMP.isPlaying()){
        ringtoneMP.pause();
    }else{
        ringtoneMP.start();
    }
}

private void myMessageArrived(String s,MqttMessage mqttMessage){
    if ((mqttMessage.toString()).equals("Flash on")) {
        if (isFlashOn()) {
            Toast.makeText(MainActivity.this, "Flashlight already on", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, "Turning flashlight on", Toast.LENGTH_SHORT).show();
            flashOnOff();
        }
    } else if ((mqttMessage.toString()).equals("Flash off")) {
        if (isFlashOn()) {
            Toast.makeText(MainActivity.this, "Turning flashlight off", Toast.LENGTH_SHORT).show();
            flashOnOff();
        } else {
            Toast.makeText(MainActivity.this, "Flashlight already off", Toast.LENGTH_SHORT).show();
        }
    } else if ((mqttMessage.toString()).equals("Ringtone on")) {
        if (ringtoneMP.isPlaying()) {
            Toast.makeText(MainActivity.this, "Ringtone already playing", Toast.LENGTH_SHORT).show();

        } else {
            Toast.makeText(MainActivity.this, "Playing ringtone", Toast.LENGTH_SHORT).show();
            ringtoneMP.start();
        }
    } else if ((mqttMessage.toString()).equals("Ringtone off")) {
        if (ringtoneMP.isPlaying()) {
            ringtoneMP.pause();
        } else {
            Toast.makeText(MainActivity.this, "Ringtone already not being played", Toast.LENGTH_SHORT).show();
        }
    } else {
        Log.d("INFO:", "This Command does not exist");
    }
    vibrator.vibrate(500);
    myRingtone.play();
}

public void exit(){
    finish();
    System.exit(0);
}

public boolean isFlashAvailable(){  //  boolean function that returns true if flash is supported on this device

    return getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}

public void flashOnOff(){   //  self explanatory

    if (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH)){  //  if the flash is on torch mode
        Log.d("BHKE","408");
        this.flashlightButton.setImageResource(R.drawable.off);
        this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);  //  turn it off
    }else{
        Log.d("BHKE","412");
        this.flashlightButton.setImageResource(R.drawable.on);
        this.parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);    //  else turn it on
    }
    this.camera.setParameters(this.parameters);
    this.camera.startPreview();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    String tempBrokerIp;
    String temptopic="";
    Integer tempqos;
    Boolean BrokerIpChanged = true;
    Boolean qosChanged = true;
    Boolean topicChanged = true;
    super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode) {
        case (1) : {
            if (resultCode == Activity.RESULT_OK) {
                tempBrokerIp = data.getStringExtra("CURRENT_IP");
                tempqos = Integer.parseInt(data.getStringExtra("CURRENT_QOS"));
                temptopic = data.getStringExtra("CURRENT_TOPIC");

                Log.d("Info BROKER, TOPIC, QOS", ":"+ tempBrokerIp+ " " + temptopic+ " " + tempqos);
                if (tempBrokerIp.equals(BrokerIp)) {
                    BrokerIpChanged=false;
                    Log.i("BrokerIpChanged =", BrokerIpChanged.toString());
                }
                if (tempqos.equals(qos)) {
                    qosChanged=false;
                    Log.i("qosChanged =", qosChanged.toString());
                }else {
                    qos = tempqos;
                }
                if (temptopic.equals(topicStr)){
                    topicChanged=false;
                    Log.i("topicChanged =", topicChanged.toString());
                }else{
                    topicStr = temptopic;
                }
                if (!BrokerIpChanged && !qosChanged && !topicChanged) return;

                if (BrokerIpChanged){
                    try {
                        client.disconnect();

                        BrokerIp = tempBrokerIp;
                        topicStr = temptopic;
                        qos = tempqos;
//                            final String clientId = MqttClient.generateClientId();
                        client = new MqttAndroidClient(MainActivity.this, BrokerIp, clientId);

                        options = new MqttConnectOptions();
                        options.setUserName(Username);
                        options.setPassword(Password.toCharArray());
//                            options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);  //  to user the latest mqtt version

                        try {
                            IMqttToken token = client.connect(options);
                            token.setActionCallback(new IMqttActionListener() {
                                @Override
                                public void onSuccess(IMqttToken asyncActionToken) {
                                    // We are connected
                                    Toast.makeText(MainActivity.this, "connected", Toast.LENGTH_SHORT).show();
                                    Log.w("Mqtt","Connected to:"+ BrokerIp);

                                    try{
                                        Log.v("INFO 11111:", "about to subscribe with: "+ topicStr + qos);
                                        client.subscribe(topicStr,qos);
                                    }catch (MqttException e){
                                        e.printStackTrace();
                                    }
                                }
                                @Override
                                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                                    // Something went wrong e.g. connection timeout or firewall problems
                                    Log.w("Mqtt","Failed to connect to:"+ BrokerIp + exception.toString());
                                    Toast.makeText(MainActivity.this, "Failed to connect to:" +exception.toString(), Toast.LENGTH_SHORT).show();
                                }

                            });
                            System.out.println(client.isConnected());
//                                if (client.isConnected()){
//                                    Log.v("INFO 22222:", "about to subscribe with: "+ temptopic + tempqos);
//                                    client.subscribe(temptopic,tempqos);
//                                }

                        } catch (MqttException e) {
                            e.printStackTrace();
                        }

                        client.setCallback(new MqttCallback() {
                            @Override
                            public void connectionLost(Throwable throwable) {

                            }

                            @Override
                            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                                myMessageArrived(s,mqttMessage);
                            }

                            @Override
                            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

                            }
                        });

                    }catch (MqttException e){
                        e.printStackTrace();
                    }
                }else
                {
                    try {
                        client.unsubscribe(topicStr);
                        client.subscribe(temptopic,tempqos);

                        topicStr = temptopic;
                        qos = tempqos;

                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }
            }
            break;
        }
    }
}

public boolean isFlashOn(){
    return (this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_ON) || this.parameters.getFlashMode().equals(android.hardware.Camera.Parameters.FLASH_MODE_TORCH));
}

I can provide the settings activity code too is needed

Body:
It seems that the two variables needed for the flashOnOff where not initiallized after i returned from the settings activity.

Ι added :

     if (isFlashAvailable()){
        camera = Camera.open();
        parameters = camera.getParameters();
    }

at the onActivityResult start and it works like a charm.


来源: stackexchange

问:
What is the tf.maximum equivalent in C++
I am trying to find tf.maximum(X, Y) function equivalence in C++. Basically, what tf.maximum() does is "Returns the max of x and y (i.e. x > y ? x : y) element-wise."

If there is a library or a built-in function, I would like to use it.

I really want to find the fastest option for that except going through all the elements in a matrix or vector.

The main reason why I want to use a max function, I would like to replace any negative value item with 0 in a matrix or a vector in C++.

Any suggestions? Thank you in advance.

答:
The normal C++ way of replacing values with other values is std::transform and a function object

```<code>std::transform(thing.begin(), thing.end(), thing.begin(), [](float value) { return std::max(0, value); });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The normal C++ way of replacing values with other values is std::transform and a function object

std::transform(thing.begin(), thing.end(), thing.begin(), [](float value) { return std::max(0, value); });


问:
UML composition 1.* and 0.*
I have a question in UML. I'm a beginner in UML and I do not know if I can do this :

答:
You can't. A composition means a whole/part relationship and it can only be 0*-1, 1*-1 or 0*-0..1 at most.

For more information on the subject I'd read this:
https://www.uml-diagrams.org/composition.html

EDIT: Think about what a whole/part relationship is. A bedroom is part of a house, but the same bedroom cannot belong to multiple houses. However, a house can have multiple bedrooms. This is the same kind of relationship as in the house/bedroom case.

Title: UML composition 1.* and 0.*


问:
Controlling row height in kableExtra()
Hi i made this awesome table with kableExtra, but my only problem is that the height of the rows is not always equal. Does any one know a remedy for this?

my table:

for example, as you can see, the line for item number 22 (6th row) has a larger height (spacing) than other lines.

my code:

```<code>my_column_names = c("Item number", "Item",
                "Emotion", "Social",
                "At Home", "Body", "Emotion",
                "Social 1", "Social 2",
                "At Home", "Body")

kable(df1,
      format = "latex", booktabs = TRUE,
      col.names = my_column_names,
      caption = "Factor loadings for the 4 and 5 Factor Model") %>%
      kable_styling(latex_options = c("striped", "hold_position"),
                    full_width = FALSE) %>%
      add_header_above(c(" " = 2,
                 "4 Factor Model " = 4, "5 Factor model" = 5)) %>%
      add_header_above(c(" " = 2,
                 "Model" = 9)) %>%
      kableExtra::landscape()
</code>```

答: The reason why the row height is not always equal is that by default kable inserts a \addlinespace every 5th rows. To get rid of it, put linesep = "" in kable(). See Get rid of \addlinespace in kable for details.

Title: Controlling row height in kableExtra()

Body:
Hi i made this awesome table with kableExtra, but my only problem is that the height of the rows is not always equal. Does any one know a remedy for this?

my table:

for example, as you can see, the line for item number 22 (6th row) has a larger height (spacing) than other lines.

my code:

my_column_names = c("Item number", "Item",
                "Emotion", "Social",
                "At Home", "Body", "Emotion",
                "Social 1", "Social 2",
                "At Home", "Body")

kable(df1,
      format = "latex", booktabs = TRUE,
      col.names = my_column_names,
      caption = "Factor loadings for the 4 and 5 Factor Model") %>%
      kable_styling(latex_options = c("striped", "hold_position"),
                    full_width = FALSE) %>%
      add_header_above(c(" " = 2,
                 "4 Factor Model " = 4, "5 Factor model" = 5)) %>%
      add_header_above(c(" " = 2,
                 "Model" = 9)) %>%
      kableExtra::landscape()


问:
Web scraping hidden texts not available in page source?
I was developing a web scraper to obtain full curriculum from a UDEMY course. I used beautiful soup and request in python. Although, some in the page the last sections of the curriculum is collapsed and we have to click to expand. How to extract the entire curriculum?

URL: https://www.udemy.com/python-the-complete-python-developer-course/

```<code>from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as Soup

my_url = "https://www.udemy.com/python-the-complete-python-developer-course/"
head = {'User-Agent':'Mozilla/5.0'}
pagereq = Request(my_url, headers=head)

pager = urlopen(pagereq)

page = pager.read()
pager.close()
Sp = Soup(page, "html.parser")
Sections = Sp.findAll("div", {"class": "content-container"})
numlec = Sp.find("div", {"class": "num-lectures"})

for section in Sections:
    SecTitle = section.find("span", {"class": "lecture-title-text"}).text.strip()
    SecLen = section.find("span", {"class": "section-header-length"}).text.strip()
    lectures = section.findAll("div", {"class": "lecture-container"})
    print("-" * 40)
    print(SecTitle+"\t"+SecLen)
    print()
    for lecture in lectures:
        name = lecture.find("div", {"class": "title"}).text.strip()
        leng = lecture.find("span", {"class": "content-summary"}).text.strip()
        print("\t {}\t{}".format(name, leng))
    print("-" * 40)
</code>```

This will scrape all data till the collapsed text. But I want the full curriculum. Is there any easy way to do this?

答:
Try this. It will firstly click on the 7 more sections button then it will click on each plus sign button to unfold all the hidden items and finally It will fetch you all the titles and it's curriculum under the course from that page.

```<code>from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("https://www.udemy.com/python-the-complete-python-developer-course/")
time.sleep(2)

driver.find_element_by_css_selector(".content-container.js-load-more").click()

for link in driver.find_elements_by_css_selector('.lecture-title-text'):
    link.click()
    time.sleep(2)

for items in driver.find_elements_by_css_selector(".content-container"):
    title = items.find_element_by_css_selector(".lecture-title-text").text
    course_list = ' '.join([item.text for item in items.find_elements_by_css_selector(".title")])
    print("Course_title: {}\nCurriculum: {}\n".format(title,course_list))

driver.quit()
</code>```

Partial output:

```<code>Course_title: Introduction
Curriculum:

Course_title: Python Setup for Windows
Curriculum: Introduction Install Python on Windows IDLE On Windows with a cool demo app! Downloading and Installing IntelliJ (FREE and PAID versions) on Windows Free 90 Day Extended Trial of IntelliJ Ultimate Edition Now Available Move to next section!

Course_title: Python Setup for Mac
Curriculum: Introduction Downloading And Installing Python On Mac OS X IDLE on Mac OS X with a cool demo app! Downloading and Installing IntelliJ (FREE and PAID version) for a Mac Free 90 Day Extended Trial of IntelliJ Ultimate Edition Now Available Move to next section!
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I was developing a web scraper to obtain full curriculum from a UDEMY course. I used beautiful soup and request in python. Although, some in the page the last sections of the curriculum is collapsed and we have to click to expand. How to extract the entire curriculum?

URL: https://www.udemy.com/python-the-complete-python-developer-course/

from urllib.request import Request, urlopen
from bs4 import BeautifulSoup as Soup

my_url = "https://www.udemy.com/python-the-complete-python-developer-course/"
head = {'User-Agent':'Mozilla/5.0'}
pagereq = Request(my_url, headers=head)

pager = urlopen(pagereq)

page = pager.read()
pager.close()
Sp = Soup(page, "html.parser")
Sections = Sp.findAll("div", {"class": "content-container"})
numlec = Sp.find("div", {"class": "num-lectures"})

for section in Sections:
    SecTitle = section.find("span", {"class": "lecture-title-text"}).text.strip()
    SecLen = section.find("span", {"class": "section-header-length"}).text.strip()
    lectures = section.findAll("div", {"class": "lecture-container"})
    print("-" * 40)
    print(SecTitle+"\t"+SecLen)
    print()
    for lecture in lectures:
        name = lecture.find("div", {"class": "title"}).text.strip()
        leng = lecture.find("span", {"class": "content-summary"}).text.strip()
        print("\t {}\t{}".format(name, leng))
    print("-" * 40)

This will scrape all data till the collapsed text. But I want the full curriculum. Is there any easy way to do this?

Body:
Try this. It will firstly click on the 7 more sections button then it will click on each plus sign button to unfold all the hidden items and finally It will fetch you all the titles and it's curriculum under the course from that page.

from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("https://www.udemy.com/python-the-complete-python-developer-course/")
time.sleep(2)

driver.find_element_by_css_selector(".content-container.js-load-more").click()

for link in driver.find_elements_by_css_selector('.lecture-title-text'):
    link.click()
    time.sleep(2)

for items in driver.find_elements_by_css_selector(".content-container"):
    title = items.find_element_by_css_selector(".lecture-title-text").text
    course_list = ' '.join([item.text for item in items.find_elements_by_css_selector(".title")])
    print("Course_title: {}\nCurriculum: {}\n".format(title,course_list))

driver.quit()

Partial output:

Course_title: Introduction
Curriculum:

Course_title: Python Setup for Windows
Curriculum: Introduction Install Python on Windows IDLE On Windows with a cool demo app! Downloading and Installing IntelliJ (FREE and PAID versions) on Windows Free 90 Day Extended Trial of IntelliJ Ultimate Edition Now Available Move to next section!

Course_title: Python Setup for Mac
Curriculum: Introduction Downloading And Installing Python On Mac OS X IDLE on Mac OS X with a cool demo app! Downloading and Installing IntelliJ (FREE and PAID version) for a Mac Free 90 Day Extended Trial of IntelliJ Ultimate Edition Now Available Move to next section!


问:
What are Sockets afterall? Why can't we use sockets instead of HTTP?
Are sockets just a connection between 2 machines?

And if sockets can be established why do we even use HTTP connection?

答:
Http is a protocol built on top of sockets.

When you use Http, you're using a higher level of abstraction on top of sockets.  You're still using sockets.

It's kind of like saying "Why would you use a .xyz document when you could just use a file?"

ContentLicense: CC BY-SA 2.5


问:
Why if statement always is true?
```<code>if[ "$x"="*.c" ]
then
    echo $x
else
    echo "not .c"
</code>```

I want to examine if  the input parameter ends with ".c"  ("*.c").

答:
The conditional in the posted code is always true,
because the "$x"="*.c" you have inside the [ ... ] is interpreted by the shell as a single non-empty string value, and non-empty string values are truthy in Bash.

But why is that a "single non-empty string value"? What about the = sign?

To be treated as the conditional operator of the [ ... ] builtin, you must put spaces around the = sign. Otherwise the shell doesn't recognize it as an operator.

That is, write like this (fixing other syntax errors as well):

```<code>if [ "$x" = "*.c" ]; then echo "$x"; else echo "not .c"; fi
</code>```

This will make the condition not always true, but it still won't do what you want. To check if the variable ends with .c you need to write it differently, using the [[ ... ]] builtin:

```<code>if [[ "$x" == *.c ]]; then echo "$x"; else echo "not .c"; fi
</code>```

Title: Why if statement always is true?

Body:
if[ "$x"="*.c" ]
then
    echo $x
else
    echo "not .c"

I want to examine if  the input parameter ends with ".c"  ("*.c").

Body:
The conditional in the posted code is always true,
because the "$x"="*.c" you have inside the [ ... ] is interpreted by the shell as a single non-empty string value, and non-empty string values are truthy in Bash.

But why is that a "single non-empty string value"? What about the = sign?

To be treated as the conditional operator of the [ ... ] builtin, you must put spaces around the = sign. Otherwise the shell doesn't recognize it as an operator.

That is, write like this (fixing other syntax errors as well):

if [ "$x" = "*.c" ]; then echo "$x"; else echo "not .c"; fi

This will make the condition not always true, but it still won't do what you want. To check if the variable ends with .c you need to write it differently, using the [[ ... ]] builtin:

if [[ "$x" == *.c ]]; then echo "$x"; else echo "not .c"; fi


问:
Automapper - Mapper already initialized error
I am using AutoMapper 6.2.0 in my ASP.NET MVC 5 application.

When I call my view through controller it shows all things right. But, when I refresh that view, Visual Studio shows an error:

System.InvalidOperationException: 'Mapper already initialized. You must call Initialize once per application domain/process.'

I am using AutoMapper only in one controller. Not made any configuration in any place yet nor used AutoMapper in any other service or controller.

My controller:

```<code>public class StudentsController : Controller
{
    private DataContext db = new DataContext();

    // GET: Students
    public ActionResult Index([Form] QueryOptions queryOptions)
    {
        var students = db.Students.Include(s => s.Father);

        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Student, StudentViewModel>();
        });
            return View(new ResulList<StudentViewModel> {
            QueryOptions = queryOptions,
            Model = AutoMapper.Mapper.Map<List<Student>,List<StudentViewModel>>(students.ToList())
        });
    }

    // Other Methods are deleted for ease...
</code>```

Error within controller:

My Model class:

```<code>public class Student
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual Father Father { get; set; }
    public virtual Sarparast Sarparast { get; set; }
    public virtual Zamin Zamin { get; set; }
    public virtual ICollection<MulaqatiMehram> MulaqatiMehram { get; set; }
    public virtual ICollection<Result> Results { get; set; }
}
</code>```

My ViewModel Class:

```<code>public class StudentViewModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual FatherViewModel Father { get; set; }
    public virtual SarparastViewModel Sarparast { get; set; }
    public virtual ZaminViewModel Zamin { get; set; }
}
</code>```

答:
If you want/need to stick with the static implementation in a unit testing scenario, note that you can call AutoMapper.Mapper.Reset() before calling initialize. Do note that this should not be used in production code as noted in the documentation.

Source: AutoMapper documentation.

Body:
I am using AutoMapper 6.2.0 in my ASP.NET MVC 5 application.

When I call my view through controller it shows all things right. But, when I refresh that view, Visual Studio shows an error:

System.InvalidOperationException: 'Mapper already initialized. You must call Initialize once per application domain/process.'

I am using AutoMapper only in one controller. Not made any configuration in any place yet nor used AutoMapper in any other service or controller.

My controller:

public class StudentsController : Controller
{
    private DataContext db = new DataContext();

    // GET: Students
    public ActionResult Index([Form] QueryOptions queryOptions)
    {
        var students = db.Students.Include(s => s.Father);

        AutoMapper.Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<Student, StudentViewModel>();
        });
            return View(new ResulList<StudentViewModel> {
            QueryOptions = queryOptions,
            Model = AutoMapper.Mapper.Map<List<Student>,List<StudentViewModel>>(students.ToList())
        });
    }

    // Other Methods are deleted for ease...

Error within controller:

My Model class:

public class Student
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual Father Father { get; set; }
    public virtual Sarparast Sarparast { get; set; }
    public virtual Zamin Zamin { get; set; }
    public virtual ICollection<MulaqatiMehram> MulaqatiMehram { get; set; }
    public virtual ICollection<Result> Results { get; set; }
}

My ViewModel Class:

public class StudentViewModel
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }
    public string CNIC { get; set; }
    public string FormNo { get; set; }
    public string PreviousEducaton { get; set; }
    public string DOB { get; set; }
    public int AdmissionYear { get; set; }

    public virtual FatherViewModel Father { get; set; }
    public virtual SarparastViewModel Sarparast { get; set; }
    public virtual ZaminViewModel Zamin { get; set; }
}


问:
Reversing words in shell
Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

EDIT: Let's assume word is a not interrupted sequence of letters from english alphabet.

( letter: ASCII range A-Z && a-z)

Example:

Input: "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them."

Output: "enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."

I have been able to write this script, but it sruggles with words with special chracters such as {,.} that are not supposed to be reversed.

```<code>#!/bin/bash

    word_length=0
    touch tmp

    for word in $(cat ./TEXT)
    do
            word_length=$(echo -n $word | wc -c )
            if [ $word_length -le 5 ]
            then
                    echo -n $word | rev >> tmp
                    echo -n " " >> tmp
            else
                    echo -n $word >> tmp
                    echo -n " " >> tmp
            fi
    done

    cat tmp > TEXT
    echo " " >> TEXT
    rm -rf tmp
</code>```

Output of this script:
"enO gnir ot elur meht ,lla eno gnir ot dnif ,meht enO gnir ot gnirb meht lla dna ni eht darkness dnib .meht"

You can see that {,.} are in the wrong place.

答:
another gawk

```<code>gawk -v RS='[^a-zA-Z]' 'function rev(x,rx) {n=split(x,a,"");
                                           while(n) rx=rx a[n--];
                                           return rx}

             {printf "%s", (length()>5?$0:rev($0)) RT}' file

enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht.
</code>```

Title: Reversing words in shell

Body:
Task is to reverse all letters (a-zA-Z) in words that have 5 or less characters.

EDIT: Let's assume word is a not interrupted sequence of letters from english alphabet.

( letter: ASCII range A-Z && a-z)

Example:

Input: "One ring to rule them all, one ring to find them, One ring to bring them all and in the darkness bind them."

Output: "enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht."

I have been able to write this script, but it sruggles with words with special chracters such as {,.} that are not supposed to be reversed.

#!/bin/bash

    word_length=0
    touch tmp

    for word in $(cat ./TEXT)
    do
            word_length=$(echo -n $word | wc -c )
            if [ $word_length -le 5 ]
            then
                    echo -n $word | rev >> tmp
                    echo -n " " >> tmp
            else
                    echo -n $word >> tmp
                    echo -n " " >> tmp
            fi
    done

    cat tmp > TEXT
    echo " " >> TEXT
    rm -rf tmp

Output of this script:
"enO gnir ot elur meht ,lla eno gnir ot dnif ,meht enO gnir ot gnirb meht lla dna ni eht darkness dnib .meht"

You can see that {,.} are in the wrong place.

Body:
another gawk

gawk -v RS='[^a-zA-Z]' 'function rev(x,rx) {n=split(x,a,"");
                                           while(n) rx=rx a[n--];
                                           return rx}

             {printf "%s", (length()>5?$0:rev($0)) RT}' file

enO gnir ot elur meht lla, eno gnir ot dnif meht, enO gnir ot gnirb meht lla dna ni eht darkness dnib meht.


答:
Another bash approach, note that this code will convert the apostrophe in word like don't to tnod' :-

```<code>while read line
do
        printf "$line\n"
        for word in $line
        do
                for (( i = ${#word}; i >= 0; i-- ))
                do
                        if [[ "${word:$i:1}" =~ '[[:alpha:]]' ]]
                        then
                                printf "${word:$i:1}"
                        else
                                symb="${word:$i:1}"
                        fi
                done
                printf "${symb} "
        done
        printf "\n"
done < TEXT
</code>```

Title: Reversing words in shell

Body:
Another bash approach, note that this code will convert the apostrophe in word like don't to tnod' :-

while read line
do
        printf "$line\n"
        for word in $line
        do
                for (( i = ${#word}; i >= 0; i-- ))
                do
                        if [[ "${word:$i:1}" =~ '[[:alpha:]]' ]]
                        then
                                printf "${word:$i:1}"
                        else
                                symb="${word:$i:1}"
                        fi
                done
                printf "${symb} "
        done
        printf "\n"
done < TEXT


问:
db.createCollection is not a function
I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.

My mongo instance is running within docker and the ports have been opened up to my local.

```<code>TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

Copied from w3schools...

```<code>var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    db.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
    });
});
</code>```

No error is returned through the run, and no methods are exposed on the db object.

any ideas?

答:
According to the changelog for Mongodb 3.0 you now get a client object containing the database object instead:

So you need the db object that points to the database you want to use, in your case mydb. Try this:

```<code>var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {   //here db is the client obj
    if (err) throw err;
    var dbase = db.db("mydb"); //here
    dbase.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();   //close method has also been moved to client obj
    });
});
</code>```

Title: db.createCollection is not a function

Body:
I am attempting to create a mongo instance however I am unable to access any of the helper methods from the mongodb nodejs driver.

My mongo instance is running within docker and the ports have been opened up to my local.

TypeError: db.createCollection is not a function
at /var/www/html/beacon/index.js:6:8
at args.push (/var/www/html/beacon/node_modules/mongodb/lib/utils.js:431:72)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:254:5
at connectCallback (/var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:933:5)
at /var/www/html/beacon/node_modules/mongodb/lib/mongo_client.js:794:11
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)

Copied from w3schools...

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    db.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
    });
});

No error is returned through the run, and no methods are exposed on the db object.

any ideas?

Body:
According to the changelog for Mongodb 3.0 you now get a client object containing the database object instead:

So you need the db object that points to the database you want to use, in your case mydb. Try this:

var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {   //here db is the client obj
    if (err) throw err;
    var dbase = db.db("mydb"); //here
    dbase.createCollection("customers", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();   //close method has also been moved to client obj
    });
});


问:
Can I copy multiple rows from the Visual Studio "Find Symbol Results" window?
Does anyone know how to copy all the lines in the Visual Studio "Find Symbol Results" window onto the clipboard?  You can copy a single line, but I want to copy them all.

I can't believe that I'm the first one to want to do this, but I can't even find a discussion about this apparently missing feature.

答:
Visual Studio Code works as a browser.
it is possible to open the developer tools and search for that part of the code

Menu: Help > Toggle Developer tools

write the following instructions to the developer tools console:

```<code>var elementos = document.getElementsByClassName("plain match")
console.log(elementos.length)
for(var i = 0; i<elementos.length;i++) console.log(elementos[i].title)
</code>```

and you can see the match results.

Now if you can copy the results

Body:
Visual Studio Code works as a browser.
it is possible to open the developer tools and search for that part of the code

Menu: Help > Toggle Developer tools

write the following instructions to the developer tools console:

var elementos = document.getElementsByClassName("plain match")
console.log(elementos.length)
for(var i = 0; i<elementos.length;i++) console.log(elementos[i].title)

and you can see the match results.

Now if you can copy the results


问:
jQuery - run a function when DOM changes
I've been using livequery so far which works, but it makes the page browsing seem really slow.
So I'm trying to find a alternative solution for this.

I'm attaching a function that runs some ajax on elements with a certain class, like:

```<code>$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});
</code>```

Now I have several events hooked on different elements that can append html in the DOM, like:

```<code>$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});
</code>```

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

Update:

I also found this plugin:
http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

Update 2:

Unfortunately it only works with element IDs for some weird reason :(

答:
It's true because the new elements do not have events bound to callbacks, they are just new fresh elements. I would recommend to bind events on the newly created elements just after they are created (i.e. inside the ajax success function):</p>

```<code>    $(".blah").each(function(){
      $.ajax({
          ...
          success: function(data) {
            $(this).removeClass(".blah");
            // add handlers to new elements with class "button"
            $(this).find('.button').click(function() {
                     $.ajax({
                          success: function(data) {
                            $(this).append(data);
                          });
          }
      });
    }
</code>```

Body:
I've been using livequery so far which works, but it makes the page browsing seem really slow.
So I'm trying to find a alternative solution for this.

I'm attaching a function that runs some ajax on elements with a certain class, like:

$(".blah").each(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).removeClass(".blah");
        // do other stuff
      }
  });
});

Now I have several events hooked on different elements that can append html in the DOM, like:

$(".button").click(function(){
  $.ajax({
      ...
      success: function(data) {
        $(this).append(data);
        // here, new elements with ".blah" class could be inserted in the DOM
        // the event above won't be fired...
      }
  });
});

How could I make so the first ajax function above runs when the DOM gets updated in the other events?

Update:

I also found this plugin:
http://www.thunderguy.com/semicolon/2007/08/14/elementready-jquery-plugin/

Do you think it would be a better solution? From a quick look it seems to, because it allows you to set a "polling" interval, which might decrease cpu usage if you set it to 1 sec or somehting. I'm testing it now :)

Update 2:

Unfortunately it only works with element IDs for some weird reason :(

Body:
It's true because the new elements do not have events bound to callbacks, they are just new fresh elements. I would recommend to bind events on the newly created elements just after they are created (i.e. inside the ajax success function):

    $(".blah").each(function(){
      $.ajax({
          ...
          success: function(data) {
            $(this).removeClass(".blah");
            // add handlers to new elements with class "button"
            $(this).find('.button').click(function() {
                     $.ajax({
                          success: function(data) {
                            $(this).append(data);
                          });
          }
      });
    }


问:
How to remove First and Last Line in Powershell
This script will do some processing on csv file notably removing first line (subsequent to How to export to "non-standard" CSV with Powershell ) :

```<code>Import-Csv in.csv -header Date,Time,O,H,L,C,V|select * -ExcludeProperty time|
%{$_.date = [datetime]::ParseExact($_.date,"yyyy.MM.dd",$null).tostring("yyMMdd");$_.v=1;$_}|
ConvertTo-Csv -NoTypeInformation|
select -skip 1|
%{$_ -replace '"'}|
Set-Content out.csv -encoding ascii
</code>```

Now I need to refine it by also removing last line. I tried to add :

select -skip ($_.Count - 1)

but it generates exception.

So what the right syntax ?

答:
If you cannot run -SkipLast because you don't have Powershell 5, rather than using a for loop, I would suggest using this :

```<code>$csv[1..$($csv.Count - 2)]
</code>```

This way, you will skip the first and last line. Then, you must do some checks on your $csv variable (length, etc.) add your set-content code, and it should work fine.

Body:
This script will do some processing on csv file notably removing first line (subsequent to How to export to "non-standard" CSV with Powershell ) :

Import-Csv in.csv -header Date,Time,O,H,L,C,V|select * -ExcludeProperty time|
%{$_.date = [datetime]::ParseExact($_.date,"yyyy.MM.dd",$null).tostring("yyMMdd");$_.v=1;$_}|
ConvertTo-Csv -NoTypeInformation|
select -skip 1|
%{$_ -replace '"'}|
Set-Content out.csv -encoding ascii

Now I need to refine it by also removing last line. I tried to add :

select -skip ($_.Count - 1)

but it generates exception.

So what the right syntax ?

Body:
If you cannot run -SkipLast because you don't have Powershell 5, rather than using a for loop, I would suggest using this :

$csv[1..$($csv.Count - 2)]

This way, you will skip the first and last line. Then, you must do some checks on your $csv variable (length, etc.) add your set-content code, and it should work fine.


问:
Run a function in tryCatch in case of error/warning
I'm using a tryCatch function in which I want another function to be run in case of error/warning. This other function depends on some arguments and for some reason, tryCatch does not recognize them when they are the error and warning functions.
Here is a simplified function where I'm facing the same problem:

```<code>essai <- function(x){
 y <- 2
 result <- tryCatch({
  sqrt(x*y)
 } , warning = function(cond,x,y) {
  message(cond)
  sqrt(abs(x*y))
 } , error = function(cond,x,y) {
  message(cond)
  sqrt(abs(x*y))
 } , finally = {
  message("done")
 } )
}

nbs <- c(1,2,3,-1,-2)
lapply(nbs, essai)
</code>```

But here I have an error message saying Error in value[[3L]](cond) : argument "x" is missing, with no default. R doesn't understand it has to reuse x and y used in the failed function, why?

答:
error and warning take functions of one argument. This works fine:

```<code>essai <- function(x, cond = 'problem'){
  y <- 2
  result <- tryCatch({
    sqrt(x*y)
  } , warning = function(w) {
    message(cond)
    sqrt(abs(x*y))
  } , error = function(e) {
    message(cond)
    sqrt(abs(x*y))
  } , finally = {
    message("done")
  } )
}
</code>```

The rest of the arguments can be specified in your essai function and will be available from both warning and error.

```<code>nbs <- c(1,2,3,-1,-2)
lapply(nbs, essai)
#done
#done
#done
#problem
#done
#problem
#done
# [[1]]
# [1] 1.414214
#
# [[2]]
# [1] 2
#
# [[3]]
# [1] 2.44949
#
# [[4]]
# [1] 1.414214
#
# [[5]]
# [1] 2
</code>```

Body:
I'm using a tryCatch function in which I want another function to be run in case of error/warning. This other function depends on some arguments and for some reason, tryCatch does not recognize them when they are the error and warning functions.
Here is a simplified function where I'm facing the same problem:

essai <- function(x){
 y <- 2
 result <- tryCatch({
  sqrt(x*y)
 } , warning = function(cond,x,y) {
  message(cond)
  sqrt(abs(x*y))
 } , error = function(cond,x,y) {
  message(cond)
  sqrt(abs(x*y))
 } , finally = {
  message("done")
 } )
}

nbs <- c(1,2,3,-1,-2)
lapply(nbs, essai)

But here I have an error message saying Error in value[[3L]](cond) : argument "x" is missing, with no default. R doesn't understand it has to reuse x and y used in the failed function, why?

Body:
error and warning take functions of one argument. This works fine:

essai <- function(x, cond = 'problem'){
  y <- 2
  result <- tryCatch({
    sqrt(x*y)
  } , warning = function(w) {
    message(cond)
    sqrt(abs(x*y))
  } , error = function(e) {
    message(cond)
    sqrt(abs(x*y))
  } , finally = {
    message("done")
  } )
}

The rest of the arguments can be specified in your essai function and will be available from both warning and error.

nbs <- c(1,2,3,-1,-2)
lapply(nbs, essai)
#done
#done
#done
#problem
#done
#problem
#done
# [[1]]
# [1] 1.414214
#
# [[2]]
# [1] 2
#
# [[3]]
# [1] 2.44949
#
# [[4]]
# [1] 1.414214
#
# [[5]]
# [1] 2


问:
Memory allocation of Integers
Let's say I have a UInt16 made up of 2 UInt8s (upper bits and lower bits)

Is this statement correct?

As long as the value of the UInt16 is less than 256, all of the memory will exist in the lower bits and the upper bits will be 0

答:
All of the set bits will be in the lower byte when the value is treated as a 16-bit unit, however if you cast the address of your variable to a char * you may find that the 'low byte' precedes the 'high byte' in memory.

This is called little-endian storage and is true, for example, on intel x86 based processors.

Title: Memory allocation of Integers


问:
How to export request Json string using DeveloperTools/Network of FF or Chrome
We want to rewrite a large web project. To make the work more safe we want to cover it by numerous API tests that will be extracted from peeking at the real web calls. (And let us be honest, from the code analysis, too).

Thus I am trying to extract the Json strings sent by different requests. The problem is that the tool provided by the browser (it is practically the same for both FF and Chrome) gives me the Json in a structured form. And I need to use it as strings.

To rewrite all large and deeply structured strings from more than a hundred of requests manually is a horror. How can I copypaste the string representation of request parameters?

答:
In Firefox: Right click > Copy > Copy POST Data.

You can also "Copy All As HAR" to get the raw body (of every request and response in the list), and "Edit and Resend" will show you the raw body in the UI.


问:
Unity3d character move with arrows keys from point to point
I have a waypoints script that I apply to an object. For example, on a character that goes from point to point and stops for a certain time and then continues to walk. How can I modify the code if I wanted to control the character with the arrow keys on the keyboard, but still have them walk from point to point, staying on the route.</p>

```<code>@script ExecuteInEditMode()

var PathFolder : GameObject;
@Range (1.0, 18.0)
var speed : float = 3.0;
var closedLoop : boolean;
var usePingpong : boolean;
var showPaths : boolean = true;
@Range (10, 100)
var SlerpSegments : int = 20;
var useSlerp : boolean;
@Range (.01, .4)
var slerpPoint: float = .1; // amount before turning
//enum SlerpColor { Black=0,White=1,Grey=2,Blue=3,Cyan=4,Green=5,Magenta=6,Red=7,Yellow=8}
//var slerpColor = SlerpColor.Cyan;
//var colorArray = Array();
//var scolor;

private var numpoints : int=0;
private var curindex : int ;  // current index
private var once : int = 0;
private var purpleArray = Array() ;
private var ppoint : float = 1.0 ;  // purple point
private var ptimes : int = 0 ;  // purple

private var waypoints = Array();
private var target : Vector3;
private var dir: Vector3; // direction
private var disttotarget: float;  //distance to target
private var distofline: float;  //distance of current line
private var distnormal: float;  //distance normalized
private var rot: Quaternion; // rotation
private var turnam: float; // rotation
var stop : boolean;
var timer : float ;

private var cislo : float = 4.0 ;  // purple point
 function Start(){

 }
function Update(){

        if (!Application.isPlaying) {
        RebuildWaypointList (); DrawWaypoints (); return;
    }
    if(showPaths) DrawWaypoints (); // remark this out later to speed up the program
    if(once==0) RebuildWaypointList ();
        MoveForward();
    turnam=0.01;  // for no slerping = almost at zero
    if (useSlerp)turnam=slerpPoint;
    if (distnormal<turnam)NextWayPoint();

}

//============= subroutines =============

function MoveForward(){

        FindDistance(); dir= target - transform.position;
    //==========================
    if(useSlerp){
        var rot: Quaternion = Quaternion.LookRotation(dir);
    transform.rotation = Quaternion.Slerp(transform.rotation, rot, speed * Time.deltaTime);
    } else {
        transform.LookAt(target);  // no Slerping
    }
    // move in the current forward direction at specified speed:
    // to keep it grounded , use Rigidbody and check "Use Gravity".
    //Debug.Log(curindex);
if(stop){
     timer -= Time.deltaTime;
     transform.Translate(Vector3.zero);

     if(timer <= 0){
        timer = 0.0;

        stop=false;                      // kocka může zase jít
        transform.Translate(Vector3(0, 0, speed * Time.deltaTime));

    }else{
 // timer -= Time.deltaTime;
  transform.Translate(Vector3.zero);
}

}else{
transform.Translate(Vector3(0, 0, speed * Time.deltaTime));
}
}
function NextWayPoint(){

switch(curindex){

case 4:  stop=true;          //stop in point 3

               timer=5;              //5s

               break;
default: stop=false;       //go

                }

    if((curindex+1) < numpoints){   // normal going forward
        curindex+=1;
    }else{
        curindex=0;
    }
    // ========= if ping pong then reverse  =========
    if(usePingpong && curindex==0){  // then at the end

            // swap allthe Vector3 info in waypoints()
        var n=numpoints-1; var nn=(numpoints)/2;
        for(var a : int = 0; a <nn; a++){
            var tempVector=waypoints[a];
            waypoints[a] = waypoints[n-a];
            waypoints[n-a] = tempVector;
        }
        curindex=0;     target=waypoints[curindex]; return;
    }
    // ========= if no loop then jump to beginning =========
    if(!closedLoop && curindex==0){
        curindex=1; target=waypoints[1];
            // go to first waypoint and exit subroutine
        transform.position=waypoints[0];
        transform.LookAt(target);
        return;
    }
    target=waypoints[curindex];   // else update target
}

function FindDistance(){
    var tempindex = curindex;
    if((tempindex-1) >-0.5){
        tempindex-=1;
    }else{
        tempindex=numpoints-1;
    }
    distofline = Vector3.Distance(target,waypoints[tempindex]);
    disttotarget= Vector3.Distance(target,transform.position);
    distnormal= disttotarget/distofline;  // make a percentage  0.0 to 1.0
}

// =========================================
function RebuildWaypointList () {
    var allpoints = PathFolder.GetComponentsInChildren(Transform);
    for(var i : int = 1; i < allpoints.Length; i++){
        waypoints[i-1] = (allpoints[i].position);
    }
    numpoints=allpoints.Length-1;
    once=1;   // flag to do this coroutine only once
    target=waypoints[curindex];  // starts at 0
}

// =========================================
function DrawWaypoints () {
    //if (Application.isPlaying)  return;
    for ( i=0; i < numpoints; i++){
        if (i<numpoints-1){  // open path  -1
            if (Physics.Linecast(waypoints[i],waypoints[i+1])) {  // true if collider
            Debug.DrawLine (waypoints[i],waypoints[i+1], Color.red);
            }else{
            Debug.DrawLine (waypoints[i],waypoints[i+1], Color.green);
            }
        }
        else if(closedLoop) {  // closed loop
            if (Physics.Linecast(waypoints[i],waypoints[0])) {  // true if collider
            Debug.DrawLine (waypoints[i],waypoints[0], Color.red);
            }else{
            Debug.DrawLine (waypoints[i],waypoints[0], Color.blue);
            }
        }
    }

    if (Application.isPlaying) {  // game is running ... draw purple path
        ppoint -=Time.deltaTime;   // one second?

        if(ppoint<0){
                    //print("ptimes1 =" + ptimes + " : purpArray ="+purpleArray);
            purpleArray.Add(this.transform.position); ptimes +=1;
            if(ptimes>SlerpSegments){
                purpleArray.RemoveAt(0);  // remove the first index
                ptimes -=1;
            }
            //print("ptimes2 =" + ptimes + " : purpArray ="+purpleArray);
            ppoint=(1/speed)*.75;
        }

        SelectColor();

        if(ptimes<1 || !useSlerp)return;
        for ( i=0; i < ptimes-1; i++){
            //Debug.Log("parray" +i+"=" +purpleArray[i]+ " parray"+(i+1)+"=" + purpleArray[i+1]);
            var a = purpleArray[i];
            var b = purpleArray[i+1];
            //Debug.Log(">>" + a + b);
            Debug.DrawLine (a,b, Color.magenta);
        }
    }
}

function SelectColor(){
// I gave up on this after a whole day...... maybe you can get it working.

//var colors : Color[]={Color.black=0,Color.white=1}
//,Color.grey,Color.blue,Color.cyan,Color.green,Color.magenta,Color.red,Color.yellow}
//GUI.color = new Color( 1, 1, 1, 0.5f )

    //GUI.color = colors[1];
    //Black=0,White=1,Grey=2,Blue=3,Cyan=4,
    //Green=5,Magenta=6,Red=7,Yellow=8

    //print("GUIcolor="+GUI.color);

//int indx= Random.Range(0,colors.Length);

//GUIText.material.color = colors[indx];

        //  print("color="+slerpColor);
    //if(slerpColor="Magenta")scolor="magenta";
    //colorArray[0] = Vector4(0,0,0,1);
    //colorArray[1] = Vector4(1,1,1,1);
    //var cVector = colorArray[1];      print ("cv " +cVector);
    //GUI.color = new Color(colorArray[1]);

    //print (colorArray);
    //var color : Color = Color(0.2, 0.3, 0.4, 0.5);
    //print ("v=" + colorArray[1]);
        //GUI.color= colorArray[1];

    /*
    black   Solid black. RGBA is (0, 0, 0, 1).
blue    Solid blue. RGBA is (0, 0, 1, 1).
clear   Completely transparent. RGBA is (0, 0, 0, 0).
cyan    Cyan. RGBA is (0, 1, 1, 1).
gray    Gray. RGBA is (0.5, 0.5, 0.5, 1).
green   Solid green. RGBA is (0, 1, 0, 1).
grey    English spelling for gray. RGBA is the same (0.5, 0.5, 0.5, 1).
magenta Magenta. RGBA is (1, 0, 1, 1).
red Solid red. RGBA is (1, 0, 0, 1).
white   Solid white. RGBA is (1, 1, 1, 1).
yellow  Yellow. RGBA is (1, 0.92, 0.016, 1), but the color is nice to look at!

var colors : Color[] = {Color.red, Color.cyan, Color.yellow }; //etc

    switch (slerpColor)  {
        case 0: GUI.color = Color.black; break;
        case 1: GUI.color = Color.white; break;
        case 2: GUI.color = Color.grey; break;
        case 3: GUI.color = Color.blue; break;
        case 4: GUI.color = Color.cyan; break;
        case 5: GUI.color = Color.green; break;
        case 6: GUI.color = Color.magenta; break;
        case 7: GUI.color = Color.red; break;
        case 8: GUI.color = Color.yellow; break;
    }
                //print("scolor="+scolor);
    //GUI.color = Color.scolor;
    //Black=0,White=1,Grey=2,Blue=3,Cyan=4,
    //Green=5,Magenta=6,Red=7,Yellow=8

    print("GUIcolor="+GUI.color);
        */
}
</code>```

答:
Move

```<code>if (distnormal<turnam)NextWayPoint();
</code>```

into a KeyDown event handler.

Body:
I have a waypoints script that I apply to an object. For example, on a character that goes from point to point and stops for a certain time and then continues to walk. How can I modify the code if I wanted to control the character with the arrow keys on the keyboard, but still have them walk from point to point, staying on the route.

@script ExecuteInEditMode()

var PathFolder : GameObject;
@Range (1.0, 18.0)
var speed : float = 3.0;
var closedLoop : boolean;
var usePingpong : boolean;
var showPaths : boolean = true;
@Range (10, 100)
var SlerpSegments : int = 20;
var useSlerp : boolean;
@Range (.01, .4)
var slerpPoint: float = .1; // amount before turning
//enum SlerpColor { Black=0,White=1,Grey=2,Blue=3,Cyan=4,Green=5,Magenta=6,Red=7,Yellow=8}
//var slerpColor = SlerpColor.Cyan;
//var colorArray = Array();
//var scolor;

private var numpoints : int=0;
private var curindex : int ;  // current index
private var once : int = 0;
private var purpleArray = Array() ;
private var ppoint : float = 1.0 ;  // purple point
private var ptimes : int = 0 ;  // purple

private var waypoints = Array();
private var target : Vector3;
private var dir: Vector3; // direction
private var disttotarget: float;  //distance to target
private var distofline: float;  //distance of current line
private var distnormal: float;  //distance normalized
private var rot: Quaternion; // rotation
private var turnam: float; // rotation
var stop : boolean;
var timer : float ;

private var cislo : float = 4.0 ;  // purple point
 function Start(){

 }
function Update(){

        if (!Application.isPlaying) {
        RebuildWaypointList (); DrawWaypoints (); return;
    }
    if(showPaths) DrawWaypoints (); // remark this out later to speed up the program
    if(once==0) RebuildWaypointList ();
        MoveForward();
    turnam=0.01;  // for no slerping = almost at zero
    if (useSlerp)turnam=slerpPoint;
    if (distnormal<turnam)NextWayPoint();

}

//============= subroutines =============

function MoveForward(){

        FindDistance(); dir= target - transform.position;
    //==========================
    if(useSlerp){
        var rot: Quaternion = Quaternion.LookRotation(dir);
    transform.rotation = Quaternion.Slerp(transform.rotation, rot, speed * Time.deltaTime);
    } else {
        transform.LookAt(target);  // no Slerping
    }
    // move in the current forward direction at specified speed:
    // to keep it grounded , use Rigidbody and check "Use Gravity".
    //Debug.Log(curindex);
if(stop){
     timer -= Time.deltaTime;
     transform.Translate(Vector3.zero);

     if(timer <= 0){
        timer = 0.0;

        stop=false;                      // kocka může zase jít
        transform.Translate(Vector3(0, 0, speed * Time.deltaTime));

    }else{
 // timer -= Time.deltaTime;
  transform.Translate(Vector3.zero);
}

}else{
transform.Translate(Vector3(0, 0, speed * Time.deltaTime));
}
}
function NextWayPoint(){

switch(curindex){

case 4:  stop=true;          //stop in point 3

               timer=5;              //5s

               break;
default: stop=false;       //go

                }

    if((curindex+1) < numpoints){   // normal going forward
        curindex+=1;
    }else{
        curindex=0;
    }
    // ========= if ping pong then reverse  =========
    if(usePingpong && curindex==0){  // then at the end

            // swap allthe Vector3 info in waypoints()
        var n=numpoints-1; var nn=(numpoints)/2;
        for(var a : int = 0; a <nn; a++){
            var tempVector=waypoints[a];
            waypoints[a] = waypoints[n-a];
            waypoints[n-a] = tempVector;
        }
        curindex=0;     target=waypoints[curindex]; return;
    }
    // ========= if no loop then jump to beginning =========
    if(!closedLoop && curindex==0){
        curindex=1; target=waypoints[1];
            // go to first waypoint and exit subroutine
        transform.position=waypoints[0];
        transform.LookAt(target);
        return;
    }
    target=waypoints[curindex];   // else update target
}

function FindDistance(){
    var tempindex = curindex;
    if((tempindex-1) >-0.5){
        tempindex-=1;
    }else{
        tempindex=numpoints-1;
    }
    distofline = Vector3.Distance(target,waypoints[tempindex]);
    disttotarget= Vector3.Distance(target,transform.position);
    distnormal= disttotarget/distofline;  // make a percentage  0.0 to 1.0
}

// =========================================
function RebuildWaypointList () {
    var allpoints = PathFolder.GetComponentsInChildren(Transform);
    for(var i : int = 1; i < allpoints.Length; i++){
        waypoints[i-1] = (allpoints[i].position);
    }
    numpoints=allpoints.Length-1;
    once=1;   // flag to do this coroutine only once
    target=waypoints[curindex];  // starts at 0
}

// =========================================
function DrawWaypoints () {
    //if (Application.isPlaying)  return;
    for ( i=0; i < numpoints; i++){
        if (i<numpoints-1){  // open path  -1
            if (Physics.Linecast(waypoints[i],waypoints[i+1])) {  // true if collider
            Debug.DrawLine (waypoints[i],waypoints[i+1], Color.red);
            }else{
            Debug.DrawLine (waypoints[i],waypoints[i+1], Color.green);
            }
        }
        else if(closedLoop) {  // closed loop
            if (Physics.Linecast(waypoints[i],waypoints[0])) {  // true if collider
            Debug.DrawLine (waypoints[i],waypoints[0], Color.red);
            }else{
            Debug.DrawLine (waypoints[i],waypoints[0], Color.blue);
            }
        }
    }

    if (Application.isPlaying) {  // game is running ... draw purple path
        ppoint -=Time.deltaTime;   // one second?

        if(ppoint<0){
                    //print("ptimes1 =" + ptimes + " : purpArray ="+purpleArray);
            purpleArray.Add(this.transform.position); ptimes +=1;
            if(ptimes>SlerpSegments){
                purpleArray.RemoveAt(0);  // remove the first index
                ptimes -=1;
            }
            //print("ptimes2 =" + ptimes + " : purpArray ="+purpleArray);
            ppoint=(1/speed)*.75;
        }

        SelectColor();

        if(ptimes<1 || !useSlerp)return;
        for ( i=0; i < ptimes-1; i++){
            //Debug.Log("parray" +i+"=" +purpleArray[i]+ " parray"+(i+1)+"=" + purpleArray[i+1]);
            var a = purpleArray[i];
            var b = purpleArray[i+1];
            //Debug.Log(">>" + a + b);
            Debug.DrawLine (a,b, Color.magenta);
        }
    }
}

function SelectColor(){
// I gave up on this after a whole day...... maybe you can get it working.

//var colors : Color[]={Color.black=0,Color.white=1}
//,Color.grey,Color.blue,Color.cyan,Color.green,Color.magenta,Color.red,Color.yellow}
//GUI.color = new Color( 1, 1, 1, 0.5f )

    //GUI.color = colors[1];
    //Black=0,White=1,Grey=2,Blue=3,Cyan=4,
    //Green=5,Magenta=6,Red=7,Yellow=8

    //print("GUIcolor="+GUI.color);

//int indx= Random.Range(0,colors.Length);

//GUIText.material.color = colors[indx];

        //  print("color="+slerpColor);
    //if(slerpColor="Magenta")scolor="magenta";
    //colorArray[0] = Vector4(0,0,0,1);
    //colorArray[1] = Vector4(1,1,1,1);
    //var cVector = colorArray[1];      print ("cv " +cVector);
    //GUI.color = new Color(colorArray[1]);

    //print (colorArray);
    //var color : Color = Color(0.2, 0.3, 0.4, 0.5);
    //print ("v=" + colorArray[1]);
        //GUI.color= colorArray[1];

    /*
    black   Solid black. RGBA is (0, 0, 0, 1).
blue    Solid blue. RGBA is (0, 0, 1, 1).
clear   Completely transparent. RGBA is (0, 0, 0, 0).
cyan    Cyan. RGBA is (0, 1, 1, 1).
gray    Gray. RGBA is (0.5, 0.5, 0.5, 1).
green   Solid green. RGBA is (0, 1, 0, 1).
grey    English spelling for gray. RGBA is the same (0.5, 0.5, 0.5, 1).
magenta Magenta. RGBA is (1, 0, 1, 1).
red Solid red. RGBA is (1, 0, 0, 1).
white   Solid white. RGBA is (1, 1, 1, 1).
yellow  Yellow. RGBA is (1, 0.92, 0.016, 1), but the color is nice to look at!

var colors : Color[] = {Color.red, Color.cyan, Color.yellow }; //etc

    switch (slerpColor)  {
        case 0: GUI.color = Color.black; break;
        case 1: GUI.color = Color.white; break;
        case 2: GUI.color = Color.grey; break;
        case 3: GUI.color = Color.blue; break;
        case 4: GUI.color = Color.cyan; break;
        case 5: GUI.color = Color.green; break;
        case 6: GUI.color = Color.magenta; break;
        case 7: GUI.color = Color.red; break;
        case 8: GUI.color = Color.yellow; break;
    }
                //print("scolor="+scolor);
    //GUI.color = Color.scolor;
    //Black=0,White=1,Grey=2,Blue=3,Cyan=4,
    //Green=5,Magenta=6,Red=7,Yellow=8

    print("GUIcolor="+GUI.color);
        */
}

Body:
Move

if (distnormal<turnam)NextWayPoint();

into a KeyDown event handler.