问:
Get ECEF XYZ given starting coordinates, range, azimuth, and elevation
I'm having a problem locating anything on converting RAE to XYZ.

If I am on a WGS84 spheroid, at say position -742507, -5462738, 3196706 and I detect an object at a range of 30km, azimuth of 310, and elevation angle of 18 degrees how can I convert that to ECEF XYZ coordinates?

Thanks.

答:
lumberjack's answer is superb. Here it is in javascript just in case anyone needs it:</p>

```<code>main();

function main() {
    // NOTE: distances are in meters, while angles are in degrees

    var siteECR = {
        X: -763997.48,
        Y: -5458565.87,
        Z: 3196706.0
    };

    var siteLLA = {
        Latitude: 30.28011211999193,
        Longitude: -97.96753350982041,
        Altitude: -1033.8619585652073
    };

    var objRAE = {
        Range: 30000.0,
        Azimuth: 310.0,
        Elevation: 18.0
    }

    var objECR = { X: 0, Y: 0, Z: 0 }

    // Should return ~[-764142.7629, -5458517.683, 3217218.18] in objECR
    RAEtoECR(siteECR, siteLLA, objRAE, objECR);

    console.log(objECR);
}

/************************************************************************************************************************/
/*  Converts a Range, Azimuth, Elevation location to a Latitude, Longitude, Altitude location         */
/*  siteLLA - array holding the Latitude, Longitude, and Altitude of the site location in degrees and meters      */
/*  rae     - array holding the Range, Azimuth, and Elevation, in degrees, of the object viewed from the site location  */
/*  objECR  - destination array to hold the ECR X, Y, Z location in meters             */
/************************************************************************************************************************/
function RAEtoECR(siteECR, siteLLA, rae, objECR) {
    var tempSEZ = { South: 0, East: 0, Zenith: 0 };

    //ECRtoLLA(siteECR, siteLLA);
    RAEtoSEZ(siteLLA, rae, tempSEZ);
    SEZtoECR(siteECR, siteLLA, tempSEZ, objECR);
}

function toRadians(angle) {
    return angle * (Math.PI / 180);
}

/************************************************************************************************************************/
/*  Converts a Range, Azimuth, Elevation location to a South, East, Zenith location          */
/*  siteLLA - array holding the Latitude, Longitude, and Altitude of the site location in degrees and meters   */
/*  rae     - array holding the Range, Azimuth, and Elevation, in degrees, of the object viewed from the site location  */
/*  sez     - destination array to hold the South, East, and Zenith coordinates of the object being viewed in meters */
/************************************************************************************************************************/
function RAEtoSEZ(siteLLA, rae, sez) {
    var range = rae.Range;
    var azimuth = rae.Azimuth;
    var elevation = rae.Elevation;

    // Compute needed math
    var slat = Math.sin(toRadians(siteLLA.Latitude));
    var slon = Math.sin(toRadians(siteLLA.Longitude));
    var clat = Math.cos(toRadians(siteLLA.Latitude));
    var clon = Math.cos(toRadians(siteLLA.Longitude));

    // Convert to radians
    azimuth   = toRadians(azimuth);
    elevation = toRadians(elevation);

    // Convert
    sez.South = -range * Math.cos(elevation) * Math.cos(azimuth);
    sez.East =  range * Math.cos(elevation) * Math.sin(azimuth);
    sez.Zenith =  range * Math.sin(elevation);
}

/************************************************************************************************************************/
/*  Converts a South, East, Zenith location to an ECR X, Y, Z location              */
/*  siteLLA - array holding the Latitude, Longitude, and Altitude of the site location in degrees and meters      */
/*  sez     - array holding the South, East, and Zenith coordinates of the object being viewed in meters       */
/*  ecr     - destination array to hold the ECR X, Y, Z location in meters             */
/************************************************************************************************************************/
function SEZtoECR(siteXYZ, siteLLA, sez, ecr) {

    var south  = sez.South;
    var east   = sez.East;
    var zenith = sez.Zenith;

    // Compute needed math
    var slat = Math.sin(toRadians(siteLLA.Latitude));
    var slon = Math.sin(toRadians(siteLLA.Longitude));
    var clat = Math.cos(toRadians(siteLLA.Latitude));
    var clon = Math.cos(toRadians(siteLLA.Longitude));

    // Convert
    ecr.X = ( slat * clon * south) + (-slon * east) + (clat * clon * zenith) + siteXYZ.X;
    ecr.Y = ( slat * slon * south) + ( clon * east) + (clat * slon * zenith) + siteXYZ.Y;
    ecr.Z = (-clat *        south) + ( slat * zenith) + siteXYZ.Z;
}
</code>```

Body:
lumberjack's answer is superb. Here it is in javascript just in case anyone needs it:

main();

function main() {
    // NOTE: distances are in meters, while angles are in degrees

    var siteECR = {
        X: -763997.48,
        Y: -5458565.87,
        Z: 3196706.0
    };

    var siteLLA = {
        Latitude: 30.28011211999193,
        Longitude: -97.96753350982041,
        Altitude: -1033.8619585652073
    };

    var objRAE = {
        Range: 30000.0,
        Azimuth: 310.0,
        Elevation: 18.0
    }

    var objECR = { X: 0, Y: 0, Z: 0 }

    // Should return ~[-764142.7629, -5458517.683, 3217218.18] in objECR
    RAEtoECR(siteECR, siteLLA, objRAE, objECR);

    console.log(objECR);
}

/************************************************************************************************************************/
/*  Converts a Range, Azimuth, Elevation location to a Latitude, Longitude, Altitude location         */
/*  siteLLA - array holding the Latitude, Longitude, and Altitude of the site location in degrees and meters      */
/*  rae     - array holding the Range, Azimuth, and Elevation, in degrees, of the object viewed from the site location  */
/*  objECR  - destination array to hold the ECR X, Y, Z location in meters             */
/************************************************************************************************************************/
function RAEtoECR(siteECR, siteLLA, rae, objECR) {
    var tempSEZ = { South: 0, East: 0, Zenith: 0 };

    //ECRtoLLA(siteECR, siteLLA);
    RAEtoSEZ(siteLLA, rae, tempSEZ);
    SEZtoECR(siteECR, siteLLA, tempSEZ, objECR);
}

function toRadians(angle) {
    return angle * (Math.PI / 180);
}

/************************************************************************************************************************/
/*  Converts a Range, Azimuth, Elevation location to a South, East, Zenith location          */
/*  siteLLA - array holding the Latitude, Longitude, and Altitude of the site location in degrees and meters   */
/*  rae     - array holding the Range, Azimuth, and Elevation, in degrees, of the object viewed from the site location  */
/*  sez     - destination array to hold the South, East, and Zenith coordinates of the object being viewed in meters */
/************************************************************************************************************************/
function RAEtoSEZ(siteLLA, rae, sez) {
    var range = rae.Range;
    var azimuth = rae.Azimuth;
    var elevation = rae.Elevation;

    // Compute needed math
    var slat = Math.sin(toRadians(siteLLA.Latitude));
    var slon = Math.sin(toRadians(siteLLA.Longitude));
    var clat = Math.cos(toRadians(siteLLA.Latitude));
    var clon = Math.cos(toRadians(siteLLA.Longitude));

    // Convert to radians
    azimuth   = toRadians(azimuth);
    elevation = toRadians(elevation);

    // Convert
    sez.South = -range * Math.cos(elevation) * Math.cos(azimuth);
    sez.East =  range * Math.cos(elevation) * Math.sin(azimuth);
    sez.Zenith =  range * Math.sin(elevation);
}

/************************************************************************************************************************/
/*  Converts a South, East, Zenith location to an ECR X, Y, Z location              */
/*  siteLLA - array holding the Latitude, Longitude, and Altitude of the site location in degrees and meters      */
/*  sez     - array holding the South, East, and Zenith coordinates of the object being viewed in meters       */
/*  ecr     - destination array to hold the ECR X, Y, Z location in meters             */
/************************************************************************************************************************/
function SEZtoECR(siteXYZ, siteLLA, sez, ecr) {

    var south  = sez.South;
    var east   = sez.East;
    var zenith = sez.Zenith;

    // Compute needed math
    var slat = Math.sin(toRadians(siteLLA.Latitude));
    var slon = Math.sin(toRadians(siteLLA.Longitude));
    var clat = Math.cos(toRadians(siteLLA.Latitude));
    var clon = Math.cos(toRadians(siteLLA.Longitude));

    // Convert
    ecr.X = ( slat * clon * south) + (-slon * east) + (clat * clon * zenith) + siteXYZ.X;
    ecr.Y = ( slat * slon * south) + ( clon * east) + (clat * slon * zenith) + siteXYZ.Y;
    ecr.Z = (-clat *        south) + ( slat * zenith) + siteXYZ.Z;
}


来源: stackexchange

问:
Cannot find symbol variable activity_main
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

```<code>xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>
</code>```

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
}

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }
</code>```

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me

答:
check package name is matching here
tools:context="com.example.android.justjava.MainActivity"

other isssue is "\" in your findValueById in place of "."

ContentLicense: CC BY-SA 3.0

Body:
I am new. Whenever i try to build and run this code this message appears.

Here is the XML code:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">

<TextView
    android:id="@+id/quantity_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="quantity"
    android:textAllCaps="true"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<TextView
    android:id="@+id/zero_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="0"
    android:layout_below="@+id/quantity_text_view"
    android:textSize="16sp"
    android:textColor="@android:color/black"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="order"
    android:textAllCaps="true"
    android:layout_below="@+id/zero_text_view"
    android:layout_marginLeft="16dp"
    android:layout_marginTop="16dp"
    android:onClick="submitOrder"/>

Here is the Java code:

/**  * IMPORTANT: Add your package below. Package name can be found in
  the project's AndroidManifest.xml file.  * This is the package name
  our example uses:  *  * package com.example.android.justjava;   *  */

import android.R; import android.os.Bundle; import
  android.support.v7.app.AppCompatActivity; import android.view.View;
  import android.widget.TextView;

import static com.example.android.justjava.R.id.quantity_text_view;

/**  * This app displays an order form to order coffee.  */ public
  class MainActivity extends AppCompatActivity {

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

/**
 * This method is called when the order button is clicked.
 */
public void submitOrder(View view) {
    display(1);
}

/**
 * This method displays the given quantity value on the screen.
 */
private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
    quantityTextView.setText("" + number);
} }

Here is the pic of the error:

https://i.stack.imgur.com/tlrUi.png

Please Help me


问:
c# getting item in row from datatable
```<code>    foreach (DataRow row in dt.Rows)
    {
        string[] temprow={"","","",row[3].ToString()};
        dtworklist.Rows.Add(temprow);
    }
</code>```

dt is my datatable. i need to get the 3rd element in the row and put it into an array. the above is what i tried so far with no luck. how do i do it?

答:
Try this:</p>

```<code>    int i=0;
    List<string> l=new List<string>();
    foreach (DataRow row in dt.Rows)
    {
        l.Add(Convert.ToString(row[2]));
    }
    string[] stringArray=l.ToArray();
</code>```

ContentLicense: CC BY-SA 2.5

Title: c# getting item in row from datatable

Body:
    foreach (DataRow row in dt.Rows)
    {
        string[] temprow={"","","",row[3].ToString()};
        dtworklist.Rows.Add(temprow);
    }

dt is my datatable. i need to get the 3rd element in the row and put it into an array. the above is what i tried so far with no luck. how do i do it?

Body:
Try this:

    int i=0;
    List<string> l=new List<string>();
    foreach (DataRow row in dt.Rows)
    {
        l.Add(Convert.ToString(row[2]));
    }
    string[] stringArray=l.ToArray();


问:
Python seemingly not reading from text file
```<code>files = []
with open("[...].log", "a+") as posshell:
    for line in files:
        print(line)
        posshell_files.append(line)
</code>```

I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.

答:
You are passing the incorrect second argument to the open call to read the file in this way:

```<code>posshell_files = []
with open("posshell.log", "r") as posshell:
    for line in posshell:
        print(line)
        posshell_files.append(line)
</code>```

According to the Python docs for open, 'r' if the default flag for reading while 'a+' is for reading and writing but you will have to do so in a different manner:

```<code>with open("posshell.log","a+") as f:
    f.seek(0)
    print(f.read())
</code>```

Body:
files = []
with open("[...].log", "a+") as posshell:
    for line in files:
        print(line)
        posshell_files.append(line)

I have no clue. It prints nothing. The array is empty. I've tried grabbing every null character and removing them in case it's UTF16 -> open as UTF8, didn't work.

Body:
You are passing the incorrect second argument to the open call to read the file in this way:

posshell_files = []
with open("posshell.log", "r") as posshell:
    for line in posshell:
        print(line)
        posshell_files.append(line)

According to the Python docs for open, 'r' if the default flag for reading while 'a+' is for reading and writing but you will have to do so in a different manner:

with open("posshell.log","a+") as f:
    f.seek(0)
    print(f.read())


问:
Angular - Date pipe
I'm trying to show a date correctly on IE in Angular. It's working fine in Chrome, Firefox, etc., but not on IE. This is my code :

```<code><span>{{menu.modifiedDate ? (menu.modifiedDate | date : "dd-MM-y HH:mm:ss") : '-'}}</span>
</code>```

This is what Google Chrome is showing :

```<code>15-06-2017 08:39:39
</code>```

And this is what IE is showing :

```<code>15-06-2017 08:00:6/15/2017 8:39:39 AM:6/15/2017 8:39:39 AM
</code>```

What's wrong ?

答:
It's a common issue on IE. The best solution is to create your own pipe like this:

```<code>import { Pipe, PipeTransform } from '@angular/core';

    @pipe({
    name: 'date'
    })

    export class DataPipe implements PipeTransform {
    transform(value: string): string {

        let dd = value.substr(8, 2);
        let MM = value.substr(5, 2);
        let yyyy = value.substr(0, 4);
        let date = `${dd}/${MM}/${yyyy}`;

        return `${date}`;
    }
    }`
</code>```

With this it should solve your problem.

Title: Angular - Date pipe

Body:
I'm trying to show a date correctly on IE in Angular. It's working fine in Chrome, Firefox, etc., but not on IE. This is my code :

{{menu.modifiedDate ? (menu.modifiedDate | date : "dd-MM-y HH:mm:ss") : '-'}}

This is what Google Chrome is showing :

15-06-2017 08:39:39

And this is what IE is showing :

15-06-2017 08:00:6/15/2017 8:39:39 AM:6/15/2017 8:39:39 AM

What's wrong ?

Body:
It's a common issue on IE. The best solution is to create your own pipe like this:

import { Pipe, PipeTransform } from '@angular/core';

    @pipe({
    name: 'date'
    })

    export class DataPipe implements PipeTransform {
    transform(value: string): string {

        let dd = value.substr(8, 2);
        let MM = value.substr(5, 2);
        let yyyy = value.substr(0, 4);
        let date = `${dd}/${MM}/${yyyy}`;

        return `${date}`;
    }
    }`

With this it should solve your problem.


问:
concatenate two lists of string and attach index in r
Here is my sample:

```<code>stringa = c("a","b","c")
stringb = c("high","low","average")
index = c(1,2,3)

data <- data.frame(stringa,stringb,index)
</code>```

I would like to concatenate stringa and stringb, and attach the corresponding index in another column. For example, the first row of the result should be "a high" with index "1".

Now I have used this function to concatenate the two strings:

```<code>c(outer(a, b, paste))
</code>```

答:
For "a high", "b low", "c average" you can do:

```<code>stringa = c("a","b","c")
stringb = c("high","low","average")
index = c(1,2,3)
data.frame(concatenated = paste(stringa, stringb),index)
  concatenated
1    a high
2    b low
3    c average
</code>```

For the full permutations of stringa and stringb:

```<code>stringa = c("a","b","c")
stringb = c("high","low","average")
data.frame(concatenated = c(outer(stringa, stringb, paste) ) )
    concatenated
1       a high
2       b high
3       c high
...
9    c average
</code>```

If you want to explicitly add the row index:

```<code>df = data.frame(concatenated = c(outer(stringa, stringb, paste) ) )
df$index = rownames(df)
df
  concatenated index
1       a high     1
2       b high     2
3       c high     3
...
9    c average     9
</code>```

Body:
Here is my sample:

stringa = c("a","b","c")
stringb = c("high","low","average")
index = c(1,2,3)

data <- data.frame(stringa,stringb,index)

I would like to concatenate stringa and stringb, and attach the corresponding index in another column. For example, the first row of the result should be "a high" with index "1".

Now I have used this function to concatenate the two strings:

c(outer(a, b, paste))

Body:
For "a high", "b low", "c average" you can do:

stringa = c("a","b","c")
stringb = c("high","low","average")
index = c(1,2,3)
data.frame(concatenated = paste(stringa, stringb),index)
  concatenated
1    a high
2    b low
3    c average

For the full permutations of stringa and stringb:

stringa = c("a","b","c")
stringb = c("high","low","average")
data.frame(concatenated = c(outer(stringa, stringb, paste) ) )
    concatenated
1       a high
2       b high
3       c high
...
9    c average

If you want to explicitly add the row index:

df = data.frame(concatenated = c(outer(stringa, stringb, paste) ) )
df$index = rownames(df)
df
  concatenated index
1       a high     1
2       b high     2
3       c high     3
...
9    c average     9


问:
Can't change activations in existing Keras model
I have a normal VGG16 model with relu activations, i.e.

```<code>def VGG_16(weights_path=None):
    model = Sequential()
    model.add(ZeroPadding2D((1, 1),input_shape=(3, 224, 224)))
    model.add(Convolution2D(64, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1, 1)))
    model.add(Convolution2D(64, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2, 2), strides=(2, 2)))
[...]
    model.add(Flatten())
    model.add(Dense(4096, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4096, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1000, activation='softmax'))

    if weights_path:
        model.load_weights(weights_path)

    return model
</code>```

and I'm instantiating it with existing weights and now want to change all relu activations to softmax (not useful, I know)

```<code>model = VGG_16('vgg16_weights.h5')
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)

softmax_act = keras.activations.softmax
for (n, layer) in enumerate(model.layers):
    if 'activation' in layer.get_config() and layer.get_config()['activation'] == 'relu':
        print('replacing #{}: {}, {}'.format(n, layer, layer.activation))
        layer.activation = softmax_act
        print('-> {}'.format(layer.activation))

model.compile(optimizer=sgd, loss='categorical_crossentropy')
</code>```

Note: model.compile is called after the changes, so the model should still be modifiable I guess.

However, even though the debug-prints correctly say

```<code>replacing #1: <keras.layers.convolutional.Convolution2D object at 0x7f7d7c497f50>, <function relu at 0x7f7dbe699a28>
-> <function softmax at 0x7f7d7c4972d0>
[...]
</code>```

the actual results are identical to the model with relu activations.

Why doesn't Keras use the changed activation function?

答:
you might want to use apply_modifications</p>

```<code>idx_of_layer_to_change = -1
model.layers[idx_of_layer_to_change].activation = activations.softmax
model = utils.apply_modifications(model)
</code>```

Body:
I have a normal VGG16 model with relu activations, i.e.

def VGG_16(weights_path=None):
    model = Sequential()
    model.add(ZeroPadding2D((1, 1),input_shape=(3, 224, 224)))
    model.add(Convolution2D(64, 3, 3, activation='relu'))
    model.add(ZeroPadding2D((1, 1)))
    model.add(Convolution2D(64, 3, 3, activation='relu'))
    model.add(MaxPooling2D((2, 2), strides=(2, 2)))
[...]
    model.add(Flatten())
    model.add(Dense(4096, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4096, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(1000, activation='softmax'))

    if weights_path:
        model.load_weights(weights_path)

    return model

and I'm instantiating it with existing weights and now want to change all relu activations to softmax (not useful, I know)

model = VGG_16('vgg16_weights.h5')
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)

softmax_act = keras.activations.softmax
for (n, layer) in enumerate(model.layers):
    if 'activation' in layer.get_config() and layer.get_config()['activation'] == 'relu':
        print('replacing #{}: {}, {}'.format(n, layer, layer.activation))
        layer.activation = softmax_act
        print('-> {}'.format(layer.activation))

model.compile(optimizer=sgd, loss='categorical_crossentropy')

Note: model.compile is called after the changes, so the model should still be modifiable I guess.

However, even though the debug-prints correctly say

replacing #1: <keras.layers.convolutional.Convolution2D object at 0x7f7d7c497f50>, <function relu at 0x7f7dbe699a28>
-> <function softmax at 0x7f7d7c4972d0>
[...]

the actual results are identical to the model with relu activations.

Why doesn't Keras use the changed activation function?

Body:
you might want to use apply_modifications

idx_of_layer_to_change = -1
model.layers[idx_of_layer_to_change].activation = activations.softmax
model = utils.apply_modifications(model)


问:
Simple VBA to Select a Range from First .Find Value?
I want to locate a value within column "A" then select from that address to the first blank row encountered. Here is what I have, but Set f isn't working. My Set c works and returns $A$32, which is the correct address. What am I missing?</p>

```<code>With Workbooks("MyBook").Sheets("Mysheet")
    Set c = .Range("$A:$A").Find("Red Car").Offset(2, 0)
    Set f = .Range(c.Address & Range("A").End(xlDown).Row)
End With
</code>```

答:
Removed Code

You are just trying to assign Range($A$32 & LastRow).  Without adding the : (colon) and column letter (A), it cannot properly assign the range to F.  Try this code and see if it works now.

Body:
I want to locate a value within column "A" then select from that address to the first blank row encountered. Here is what I have, but Set f isn't working. My Set c works and returns $A$32, which is the correct address. What am I missing?

With Workbooks("MyBook").Sheets("Mysheet")
    Set c = .Range("$A:$A").Find("Red Car").Offset(2, 0)
    Set f = .Range(c.Address & Range("A").End(xlDown).Row)
End With


问:
Convert U1 array to int in Python
I have the following array "class_id"

```<code>array([[array(['2'],
  dtype='<U1')],
   [array(['3'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   ...,
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')]], dtype=object)
</code>```

When I'm using the function:

class_id.astype(int)

I get the following error:

```<code>   ValueError: setting an array element with a sequence.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-124-3ad39bf87e7d> in <module>()
----> 1 class_id.astype(int)
ValueError: setting an array element with a sequence.
</code>```

I would like to get the following array:

```<code>array([[1],
   [2],
   [1],
   ...,
   [1],
   [1],
   [1]])
</code>```

Which function should I use?

答:
You have an array of lists of array, you need to drop one layer/dimension to get your desired output; You can try this:

```<code>import numpy as np
np.array([s[0].astype(int) for s in class_id])

#array([[2],
#       [3],
#       [2],
#       [2],
#       [2],
#       [2]])
</code>```

```<code>class_id = array([[array(['2'],
  dtype='<U1')],
   [array(['3'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')]], dtype=object)
</code>```

Title: Convert U1 array to int in Python

Body:
I have the following array "class_id"

array([[array(['2'],
  dtype='<U1')],
   [array(['3'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   ...,
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')]], dtype=object)

When I'm using the function:

class_id.astype(int)

I get the following error:

   ValueError: setting an array element with a sequence.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-124-3ad39bf87e7d> in <module>()
----> 1 class_id.astype(int)
ValueError: setting an array element with a sequence.

I would like to get the following array:

array([[1],
   [2],
   [1],
   ...,
   [1],
   [1],
   [1]])

Which function should I use?

Body:
You have an array of lists of array, you need to drop one layer/dimension to get your desired output; You can try this:

import numpy as np
np.array([s[0].astype(int) for s in class_id])

#array([[2],
#       [3],
#       [2],
#       [2],
#       [2],
#       [2]])

class_id = array([[array(['2'],
  dtype='<U1')],
   [array(['3'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')]], dtype=object)


问:
Where does my footer go
I have made a site with Bootstrap and now I'm facing this problem that the footer that I just created does not show up at all somehow!

Here's the footer html codes:

```<code><div class="footer">
                <div class="container-fluid">
                    <div class="topfooter">
                        <div class="row">
                            <div class="col-md-1"></div>
                            <div class="col-md-10 socails">
                                <ul>
                                    <li><a href="default.asp">Home</a></li>
                                    <li><a href="news.asp">News</a></li>
                                    <li><a href="contact.asp">Contact</a></li>
                                    <li><a href="about.asp">About</a></li>
                                </ul>
                            </div>
                            <div class="col-md-1"></div>
                        </div>
                    </div>
                    <div class="middlefooter">
                        <div class="row BKoodakBold">
                            <div class="col-md-3">
                                <h1 class="footerTitle">واحد امور مالی</h1>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                            </div>
                            <div class="col-md-3">
                                <h1 class="footerTitle">واحد امور مالی</h1>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                            </div>
                            <div class="col-md-3">
                                <h1 class="footerTitle">واحد امور مالی</h1>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                            </div>
                            <div class="col-md-3">
                                <h1 class="footerTitle">واحد امور مالی</h1>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                                <a class="footerPara">پیگیری سفارش</a></br>
                            </div>
                        </div>
                    </div>
                    <div class="bottomfooter">
                        <div class="row">
                            <div class="col-md-1"></div>
                            <div class="col-md-10 socails">
                                <ul>
                                    <li><a href="default.asp">Home</a></li>
                                    <li><a href="news.asp">News</a></li>
                                    <li><a href="contact.asp">Contact</a></li>
                                    <li><a href="about.asp">About</a></li>
                                </ul>
                            </div>
                            <div class="col-md-1"></div>
                        </div>
                    </div>
                </div>
            </div>
</code>```

And the result I get, is this:

print screen

So as you can see it does not show up correctly! And this is also the css for this footer:

```<code>    .footer{
    height:400px;
    background-color:black;
}

.socials{

}
.socials ul {
    list-style-type: none;
    margin: 0;
    padding: 0;

}
.socials ul li {
    display: inline;
    text-decoration:none;
}
.footerTitle{
    font-size:20px;
}
.footerPara{
    padding-right:3px;
}
.footerPara, .footerTitle{
    text-align:right;
    color:#fff;
}
</code>```

So what am I doing wrong ? Why it does not appear correctly ?

Not that my footer is inside of a div with id of content with this settings:

```<code>#content{
background-color:black;
width:100%;
position:absolute;
top:550px;
background:#ebebeb;
height:3800px;
overflow:hidden;
</code>```

}

答:
You don't need to specify the height of #content. Try changing height: 3800px to height: auto an see if that works.

The problem is that when you specified height with overflow: hidden you have limited space for content, extra content will be hidden.

Also your #content has duplicated background color, you probably want only one of this two background-color: black and background: #ebebeb.

Title: Where does my footer go

Body:
I have made a site with Bootstrap and now I'm facing this problem that the footer that I just created does not show up at all somehow!

Here's the footer html codes:

Home

News

Contact

About

واحد امور مالی

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

واحد امور مالی

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

واحد امور مالی

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

واحد امور مالی

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

                                پیگیری سفارش

Home

News

Contact

About

And the result I get, is this:

print screen

So as you can see it does not show up correctly! And this is also the css for this footer:

    .footer{
    height:400px;
    background-color:black;
}

.socials{

}
.socials ul {
    list-style-type: none;
    margin: 0;
    padding: 0;

}
.socials ul li {
    display: inline;
    text-decoration:none;
}
.footerTitle{
    font-size:20px;
}
.footerPara{
    padding-right:3px;
}
.footerPara, .footerTitle{
    text-align:right;
    color:#fff;
}

So what am I doing wrong ? Why it does not appear correctly ?

Not that my footer is inside of a div with id of content with this settings:

#content{
background-color:black;
width:100%;
position:absolute;
top:550px;
background:#ebebeb;
height:3800px;
overflow:hidden;

}


问:
Unit Testing with a DateTime
I am unit testing with a date but the build fails because the date has a timestamp in it. How would I remove it to enable the testing works?

```<code> DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m => m.Now).Returns(mockDateTime)
</code>```

The mockDateTime returns 4/18/2025 12:00:00 AM but I only want 4/18/2025

答:
instead of (m => m.Now), have you tried (m=> m.Today) instead?

```<code>DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m => m.Today).Returns(mockDateTime)
</code>```

also, DateTimes always have a time component. Are you doing any toString actions in your code? you should probably just check ToShortDateString(), which is what will give you just the date part of the datetime:
https://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring(v=vs.110).aspx

Title: Unit Testing with a DateTime

Body:
I am unit testing with a date but the build fails because the date has a timestamp in it. How would I remove it to enable the testing works?

 DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m => m.Now).Returns(mockDateTime)

The mockDateTime returns 4/18/2025 12:00:00 AM but I only want 4/18/2025

Body:
instead of (m => m.Now), have you tried (m=> m.Today) instead?

DateTime mockDateTime = new DateTime(2025, 4, 18).Date;
 _dateTimeWrapper.Setup(m => m.Today).Returns(mockDateTime)

also, DateTimes always have a time component. Are you doing any toString actions in your code? you should probably just check ToShortDateString(), which is what will give you just the date part of the datetime:
https://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring(v=vs.110).aspx


问:
Determine 'this week' in T-SQL
This is locale specific to the US wherein it considered that the start of a week is Sunday; I want to be able to ask SQL to give me the date of the next Sunday relative to today [getDate()]. If today is Jan 15 it should return Jan 18; if today were Sunday it should return the following Sunday which is the 25th. This would be trivial to write a UDF for but I was curious if anyone had other tricks/ideas?</p>

答:
Today's day-of-week:

SELECT @dow = DATEPART(d, GETDATE()) where 1 = Sunday, 7 = Saturday

You want to add enough days to get the next Sunday.

If today is 1 = Sunday, add 7

If today is 2 = Monday, add 6

If today is 3 = Tuesday, add 5
etc.

so you are always adding 8 - today's day-of-week value.

SELECT DATEADD(d, GETDATE(), 8 - @dow(GETDATE))

EDIT: But Cade wins!

Title: Determine 'this week' in T-SQL

LastEditorDisplayName: Cade Roux

OwnerDisplayName: le dorfier

LastEditorDisplayName: le dorfier


问:
adding some jquery script to Magento page
this has been driving me insane. I can't figure out how to append some jquery script to the head section of a particular page in Magento 1.4.2. I've added the latest jquery library to all pages by editing page.xml, and i've added the no conflict thing.

I know i need to add some code to the custom layout update area for the page in question. However nothing works, i've tried many pieces of code and none appear in the head of the page when i later check the source code.

I posted the same question on official mangeto forum but eight days later and no replies. That forum is horrible for getting advice most questions are unanswered :(. Any idea how i could add to the head via custom layout update this for example?

```<code>$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});
</code>```

I've tried enclosing that in script tags, in reference = head tag. Nothing works. Pulling my hair out and i've googled every word phrase i can think of but no examples of how to add scrip to a page's head in Magento. Please help.

答:
Here's three different ways you can do this.  I'd be hard pressed to call one of these more "right" than the other.

First approach: It sounds like you've used page.xml to add the base jQuery library to your page.  If you know how to do that, you can add something like

```<code><action method="addJs"><script>path/to/my/file.js</script></action>
</code>```

below the action you added for jQuery. Then, place your code the file.js file that ends up linked in your head.

Second approach: If you look at the Block class for the head, you'll see where the template file is set.

```<code>app/code/core/Mage/Page/Block/Html/Head.php

...
protected function _construct()
{
    $this->setTemplate('page/html/head.phtml');
}
</code>```

Find the page/html/head.phtml in your theme and add the code directly to page.html.

Third approach: If you look at the stock page.html mentioned above, you'll see this line

```<code><?php echo $this->getChildHtml() ?>
</code>```

Normally, the getChildHtml method is used to render a specific child block.  However, if called with no paramater, getChildHtml will automatically render all the child blocks.  That means you can add something like

```<code><!-- existing line --> <block type="page/html_head" name="head" as="head">
    <!-- new sub-block you're adding --> <block type="core/template" name="stackoverflow" as="stackoverflow" template="page/stackoverflow.phtml"/>
    ...
</code>```

to page.xml, and then add the stackoverflow.phtml file. Any block added to the head block will be automatically rendered. (this automatic rendering doesn't apply for all layout blocks, only for blocks where getChildHtml is called without paramaters)

Your phtml file doesn't need to be in page/, you can place it anywhere in your theme's template folder structure.  The stackoverflow.phtml file will contain the javascript you want added to the head

```<code><script type="text/javascript">
    alert("Test");
</script>
</code>```

Body:
this has been driving me insane. I can't figure out how to append some jquery script to the head section of a particular page in Magento 1.4.2. I've added the latest jquery library to all pages by editing page.xml, and i've added the no conflict thing.

I know i need to add some code to the custom layout update area for the page in question. However nothing works, i've tried many pieces of code and none appear in the head of the page when i later check the source code.

I posted the same question on official mangeto forum but eight days later and no replies. That forum is horrible for getting advice most questions are unanswered :(. Any idea how i could add to the head via custom layout update this for example?

$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

I've tried enclosing that in script tags, in reference = head tag. Nothing works. Pulling my hair out and i've googled every word phrase i can think of but no examples of how to add scrip to a page's head in Magento. Please help.

Body:
Here's three different ways you can do this.  I'd be hard pressed to call one of these more "right" than the other.

First approach: It sounds like you've used page.xml to add the base jQuery library to your page.  If you know how to do that, you can add something like

<action method="addJs"><script>path/to/my/file.js</script></action>

below the action you added for jQuery. Then, place your code the file.js file that ends up linked in your head.

Second approach: If you look at the Block class for the head, you'll see where the template file is set.

app/code/core/Mage/Page/Block/Html/Head.php

...
protected function _construct()
{
    $this->setTemplate('page/html/head.phtml');
}

Find the page/html/head.phtml in your theme and add the code directly to page.html.

Third approach: If you look at the stock page.html mentioned above, you'll see this line

<?php echo $this->getChildHtml() ?>

Normally, the getChildHtml method is used to render a specific child block.  However, if called with no paramater, getChildHtml will automatically render all the child blocks.  That means you can add something like

<!-- existing line --> <block type="page/html_head" name="head" as="head">
    <!-- new sub-block you're adding --> <block type="core/template" name="stackoverflow" as="stackoverflow" template="page/stackoverflow.phtml"/>
    ...

to page.xml, and then add the stackoverflow.phtml file. Any block added to the head block will be automatically rendered. (this automatic rendering doesn't apply for all layout blocks, only for blocks where getChildHtml is called without paramaters)

Your phtml file doesn't need to be in page/, you can place it anywhere in your theme's template folder structure.  The stackoverflow.phtml file will contain the javascript you want added to the head

<script type="text/javascript">
    alert("Test");
</script>


问:
How come my order by section gives a 'not a group by' error
My SQL-query works fine until I add in the 'order by' clause.
I receive a 'not a group by expression' error
I thought you were supposed to put an exact copy of the column in the 'select' clause ,in the 'order by' clause if you wish to edit the order of said column in your table...

```<code>select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1)
from regios
WHERE latitude is not null and niveau=0
group by case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end
order by case when latitude between -18 and 18 then 5
 when latitude between -36 and 36 then 4
 when latitude between -54 and 54 then 3
 when latitude between -72 and 72 then 2
 else 1 end
</code>```

EDIT: To clarify , I am not necessarily looking for a solution to this problem but rather an explanation on why this particular piece of code doesn't work

答:
The expressions that are not encapsulated within an aggregate function must be included in the GROUP BY clause and only those which are encapsulated within an aggregate function can be used in an order by, unless you are using number position for the column.

So, In your example,the expression evaluated in the non-encapsulated column (klimaat) is different from the columns used in the ORDER BY clause.If you use MAX(latitude) in your ORDER BY , it will work because now it is encapsulated within an aggregate function.

Body:
My SQL-query works fine until I add in the 'order by' clause.
I receive a 'not a group by expression' error
I thought you were supposed to put an exact copy of the column in the 'select' clause ,in the 'order by' clause if you wish to edit the order of said column in your table...

select
case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end klimaat,
count(1)
from regios
WHERE latitude is not null and niveau=0
group by case when latitude between -18 and 18 then 'tropical'
 when latitude between -36 and 36 then 'subtropical'
 when latitude between -54 and 54 then 'average'
 when latitude between -72 and 72 then 'subpolar'
 else 'polar' end
order by case when latitude between -18 and 18 then 5
 when latitude between -36 and 36 then 4
 when latitude between -54 and 54 then 3
 when latitude between -72 and 72 then 2
 else 1 end

EDIT: To clarify , I am not necessarily looking for a solution to this problem but rather an explanation on why this particular piece of code doesn't work


问:
How can I access list values using DOM in javascript?
I want an array (or simple string values, if not an array) containing values in
. My code is below :

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>Unordered List with Disc Bullets</h2>

<ul style="list-style-type:disc">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>

<script type="text/javascript">
    function changeColor(){
        var a=document.childNodes[1].childNodes[2].childNodes[3];
        alert(a.childNodes[0]);
    }
</script>
</body>
</html>
</code>```

The values I get alerted are either undefined or [object text], while I want an array so I can access them using array[0] or something like that.

答:
Do with querySelectorAll()

function changeColor() {
  var a = document.querySelectorAll('ul li')
  console.log(a[0].innerHTML);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Unordered List with Disc Bullets</h2>

<ul style="list-style-type:disc">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button></code>```

For Nodelist array creation with li text and forEach() iterate the array .Then push textContent to array arr

function changeColor() {
var arr=[];
document.querySelectorAll('ul li').forEach(function(a){
     arr.push(a.textContent)
  })
  console.log(arr);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Unordered List with Disc Bullets</h2>

<ul style="list-style-type:disc">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button></code>```

Body:
I want an array (or simple string values, if not an array) containing values in
. My code is below :

<!DOCTYPE html>

Unordered List with Disc Bullets

Coffee

Tea

Milk

<button onclick="changeColor()">Change</button>

The values I get alerted are either undefined or [object text], while I want an array so I can access them using array[0] or something like that.

Body:
Do with querySelectorAll()

function changeColor() {
  var a = document.querySelectorAll('ul li')
  console.log(a[0].innerHTML);
}

<h2>Unordered List with Disc Bullets</h2>

<ul style="list-style-type:disc">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>

For Nodelist array creation with li text and forEach() iterate the array .Then push textContent to array arr

function changeColor() {
var arr=[];
document.querySelectorAll('ul li').forEach(function(a){
     arr.push(a.textContent)
  })
  console.log(arr);

}

<h2>Unordered List with Disc Bullets</h2>

<ul style="list-style-type:disc">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>


问:
Data table not show print
when i write "

```<code>print

 "$(function () {
        $("#example1").DataTable(
            {
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'print',
                        text: 'Print current page',
                        autoPrint: false
                    }]
            }
        );
        $("#structure_field-add-form").validate({});
    });"
</code>```

this not make print button show to use it how can I fix this, please? output like the picture

答:
Did you put all required JS files in place ?

please check this link. https://datatables.net/extensions/buttons/examples/initialisation/simple.html

You have to add following JS files.

```<code>https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js
//cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js
//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js
//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js
//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js
//cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js
//cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js
</code>```

Also please check below code. this is the working example of datatable button which I am using in my project.

```<code>var table1 =  $('#task-table').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'csv','excel','selectAll','selectNone',
            {
                extend: 'copy',
                text: 'COPY ALL',
                className: 'pull_right',
                exportOptions: {
                    modifier: {
                        page: 'all'
                    }
                }
            }
        ],
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0,
            checkboxes: {
                'selectRow': true
            }
        } ],
        select: {
            style:    'multi',
            selector: 'td:first-child'
        },
        order: [[ 1, 'asc' ]],
        "iDisplayLength" : 20,
    });
</code>```

Title: Data table not show print

Body:
when i write "

print

 "$(function () {
        $("#example1").DataTable(
            {
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'print',
                        text: 'Print current page',
                        autoPrint: false
                    }]
            }
        );
        $("#structure_field-add-form").validate({});
    });"

this not make print button show to use it how can I fix this, please? output like the picture

Body:
Did you put all required JS files in place ?

please check this link. https://datatables.net/extensions/buttons/examples/initialisation/simple.html

You have to add following JS files.

https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js
//cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js
//cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js
//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js
//cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js
//cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js
//cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js

Also please check below code. this is the working example of datatable button which I am using in my project.

var table1 =  $('#task-table').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'csv','excel','selectAll','selectNone',
            {
                extend: 'copy',
                text: 'COPY ALL',
                className: 'pull_right',
                exportOptions: {
                    modifier: {
                        page: 'all'
                    }
                }
            }
        ],
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0,
            checkboxes: {
                'selectRow': true
            }
        } ],
        select: {
            style:    'multi',
            selector: 'td:first-child'
        },
        order: [[ 1, 'asc' ]],
        "iDisplayLength" : 20,
    });


问:
Merging iris when cube.var_name differs
I’ve run into a problem with merging cubes.  I have a cube list that I would like to merge into a smaller set of cubes.
However, when I try and merge iris gives me the following error message:

```<code>Traceback (most recent call last):
  File "site-packages/iris/cube.py", line 377, in merge_cube
    proto_cube.register(cube, error_on_mismatch=True)
  File "site-packages/iris/_merge.py", line 1260, in register
    error_on_mismatch)
  File "site-packages/iris/_merge.py", line 420, in match
    raise iris.exceptions.MergeError(msgs)
iris.exceptions.MergeError: failed to merge into a single cube.
  cube.var_name differs: u'air_pressure_at_sea_level_0' != u'air_pressure_at_sea_level_2'
</code>```

I’m using Iris version 1.13.0 with python 2.7.

I have tried removing the var_name coordinate but got an exception when I did cube.remove_coord('var_name'):

```<code>iris.exceptions.CoordinateNotFoundError: 'Expected to find exactly 1  coordinate, but found none.'
</code>```

Other than this detail, I consider the two cubes to be suitable for merging and would appreciate any guidance.

答:
var_name is an attribute on a cube (and, as it happens, on coordinates) and it is this that differs between your two cubes.

Simply homogenising your var_names should be all that is needed in this instance. For example, you might want to set them all to air_pressure_at_sea_level with:

```<code>for cube in cubes:
    cube.var_name = 'air_pressure_at_sea_level'
</code>```

After that, cubes.merge_cube() should work (or potentially raise a further incompatibility).

Title: Merging iris when cube.var_name differs

Body:
I’ve run into a problem with merging cubes.  I have a cube list that I would like to merge into a smaller set of cubes.
However, when I try and merge iris gives me the following error message:

Traceback (most recent call last):
  File "site-packages/iris/cube.py", line 377, in merge_cube
    proto_cube.register(cube, error_on_mismatch=True)
  File "site-packages/iris/_merge.py", line 1260, in register
    error_on_mismatch)
  File "site-packages/iris/_merge.py", line 420, in match
    raise iris.exceptions.MergeError(msgs)
iris.exceptions.MergeError: failed to merge into a single cube.
  cube.var_name differs: u'air_pressure_at_sea_level_0' != u'air_pressure_at_sea_level_2'

I’m using Iris version 1.13.0 with python 2.7.

I have tried removing the var_name coordinate but got an exception when I did cube.remove_coord('var_name'):

iris.exceptions.CoordinateNotFoundError: 'Expected to find exactly 1  coordinate, but found none.'

Other than this detail, I consider the two cubes to be suitable for merging and would appreciate any guidance.

Body:
var_name is an attribute on a cube (and, as it happens, on coordinates) and it is this that differs between your two cubes.

Simply homogenising your var_names should be all that is needed in this instance. For example, you might want to set them all to air_pressure_at_sea_level with:

for cube in cubes:
    cube.var_name = 'air_pressure_at_sea_level'

After that, cubes.merge_cube() should work (or potentially raise a further incompatibility).


问:
C# how to pass unknown value variable ( user input ) to return method
Good Morning/Afternoon,

I'm would love some clarification on passing by reference and value. The program being posted works if I set the variable value to "0" but does not override after user input. So I believe the issue is passing, however my professor said everything should be static in this program.

Short: How to pass an input variable without the use of void?

I am very new. This is only chapter 3 so any assistance would be wonderful.

```<code>namespace Lesson3
{

class Program
{
    public static void Main(string[] args)
    {

        // declarations
        // 12 inches to a foot
        // 36 inches to a yard
        // 63360 inches per 1 mile
        double userInput= 0; // if "0" is removed the program will not function CS0165 error
        double feet = 12;
        double yards = 36;
        double miles = 63360;
        double ansFeet = userDivFeet(ref feet, ref userInput);
        double ansYards = userDivYards(ref yards, ref userInput);
        double ansMiles = userDivMiles(ref miles, ref userInput);

        Console.WriteLine("Please enter the number of inches to convert: ");
        userInput = Convert.ToInt32(Console.ReadLine());

        // output each calculation and display with console to hold the results
        WriteLine(userInput + " inches converts into " + ansFeet + " feet.");
        WriteLine(userInput + " inches converts into " + ansYards + " yards.");
        WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
        Console.ReadKey();
    }

        public static double userDivFeet(ref double userInput, ref double feet)
    {
        return userInput / feet;
    }
    public static double userDivYards(ref double userInput, ref double yards)
    {
        return userInput / yards;
    }
    public static double userDivMiles(ref double userInput, ref double miles)

    {
        return userInput / miles;
    }

    }
</code>```

}

答:
The reason you don't see any changes is because you're calling your methods before getting the input of the user so userInput will always be equal to 0 you should move them after the

```<code>userInput = Convert.ToInt32(Console.ReadLine());
</code>```

So it would look like this

```<code>public static void Main(string[] args)
{
    // declarations
    // 12 inches to a foot
    // 36 inches to a yard
    // 63360 inches per 1 mile
    double userInput = 0; // if "0" is removed the program will not function CS0165 error
    double feet = 12;
    double yards = 36;
    double miles = 63360;

    Console.WriteLine("Please enter the number of inches to convert: ");
    userInput = Convert.ToInt32(Console.ReadLine());

    double ansFeet = userDivFeet(ref feet, ref userInput);
    double ansYards = userDivYards(ref yards, ref userInput);
    double ansMiles = userDivMiles(ref miles, ref userInput);

    // output each calculation and display with console to hold the results
    WriteLine(userInput + " inches converts into " + ansFeet + " feet.");
    WriteLine(userInput + " inches converts into " + ansYards + " yards.");
    WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
    Console.ReadKey();
}
</code>```

And as Polyfun stated you don't need to use ref, Also the reason your teacher said it must all be static is because you're calling those methods directly from the main.

If you want the user to be able to enter number with decimals like 1.25 you should change the Convert.ToInt32 to a Convert.ToDouble

You were getting CS0165 error when removing the = 0 because you were trying to use an unassigned value in a method, now that the methods are moved after you assigned a value to userInput you shouldn't get this error anymore.

Body:
Good Morning/Afternoon,

I'm would love some clarification on passing by reference and value. The program being posted works if I set the variable value to "0" but does not override after user input. So I believe the issue is passing, however my professor said everything should be static in this program.

Short: How to pass an input variable without the use of void?

I am very new. This is only chapter 3 so any assistance would be wonderful.

namespace Lesson3
{

class Program
{
    public static void Main(string[] args)
    {

        // declarations
        // 12 inches to a foot
        // 36 inches to a yard
        // 63360 inches per 1 mile
        double userInput= 0; // if "0" is removed the program will not function CS0165 error
        double feet = 12;
        double yards = 36;
        double miles = 63360;
        double ansFeet = userDivFeet(ref feet, ref userInput);
        double ansYards = userDivYards(ref yards, ref userInput);
        double ansMiles = userDivMiles(ref miles, ref userInput);

        Console.WriteLine("Please enter the number of inches to convert: ");
        userInput = Convert.ToInt32(Console.ReadLine());

        // output each calculation and display with console to hold the results
        WriteLine(userInput + " inches converts into " + ansFeet + " feet.");
        WriteLine(userInput + " inches converts into " + ansYards + " yards.");
        WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
        Console.ReadKey();
    }

        public static double userDivFeet(ref double userInput, ref double feet)
    {
        return userInput / feet;
    }
    public static double userDivYards(ref double userInput, ref double yards)
    {
        return userInput / yards;
    }
    public static double userDivMiles(ref double userInput, ref double miles)

    {
        return userInput / miles;
    }

    }

}

Body:
The reason you don't see any changes is because you're calling your methods before getting the input of the user so userInput will always be equal to 0 you should move them after the

userInput = Convert.ToInt32(Console.ReadLine());

So it would look like this

public static void Main(string[] args)
{
    // declarations
    // 12 inches to a foot
    // 36 inches to a yard
    // 63360 inches per 1 mile
    double userInput = 0; // if "0" is removed the program will not function CS0165 error
    double feet = 12;
    double yards = 36;
    double miles = 63360;

    Console.WriteLine("Please enter the number of inches to convert: ");
    userInput = Convert.ToInt32(Console.ReadLine());

    double ansFeet = userDivFeet(ref feet, ref userInput);
    double ansYards = userDivYards(ref yards, ref userInput);
    double ansMiles = userDivMiles(ref miles, ref userInput);

    // output each calculation and display with console to hold the results
    WriteLine(userInput + " inches converts into " + ansFeet + " feet.");
    WriteLine(userInput + " inches converts into " + ansYards + " yards.");
    WriteLine(userInput + " inches converts into " + ansMiles + " miles.");
    Console.ReadKey();
}

And as Polyfun stated you don't need to use ref, Also the reason your teacher said it must all be static is because you're calling those methods directly from the main.

If you want the user to be able to enter number with decimals like 1.25 you should change the Convert.ToInt32 to a Convert.ToDouble

You were getting CS0165 error when removing the = 0 because you were trying to use an unassigned value in a method, now that the methods are moved after you assigned a value to userInput you shouldn't get this error anymore.


问:
Get Dotfuscated settings from framework 3.5 into framework 4.5?
I was using Dotfuscator Version: 4.2.5000.27915 in my Visual Studio Dot NET framework 3.5. I am having huge amount of settings based on this version of Dotfuscator.

Now, There is a compulsion need for me to move on framework 4.5. But the issue here is that this version of Dotfuscator does not support in framework 4.5.

Is there any way to get my settings in framework 4.5 without losing them?

答:
Dotfuscator operates on Dotfuscator config files, which store settings about an obfuscation build.
You should be able to open your config files with newer versions of Dotfuscator and preserve your obfuscation configuration.

I should mention that Dotfuscator version 4.2.5000 was released in two editions: the free Community Edition (CE) included with Visual Studio 2008, and the fully-supported Professional Edition.
The newer versions of Community Edition are versioned at 5.x, while the Professional Edition remains versioned at 4.x, but both should be backward compatible with config files from 4.2.
You can always get the latest versions of Dotfuscator from the Dotfuscator Downloads page on PreEmptive's website.

Note that if you are using Community Edition, the latest releases do not support Visual Studio 2012 and 2013, as mentioned in the question tags.
While these releases of Visual Studio include older versions of Community Edition, I strongly discourage using them, because they don't have the latest updates to address current reverse engineering threats.
You should either use the latest Community Edition with a newer version of Visual Studio, or the latest Professional Edition (which is installed separately from Visual Studio, and therefore can be used with older Visual Studio versions).

Disclaimer: I work for PreEmptive Solutions, on the Dotfuscator team.


问:
Recognition of changed data in a multi user database
I've got a database which will be accessed by multiple users.
For example User 1 retrieves a list of all available datasets in the table "Test". User 2 does the same thing and both users afterwards got the same datasets.

So now, if User 1 wants to write ABC to dataset with Index 1, he can do so and the dataset is persistent.
But if User 2 NOW wants to write ABB to dataset with Index 1, how can he know, that the dataset has already been updated?

Is there a pattern for multi user database access or can I just use hashing algorithms to obtain if there is an updated dataset?

Or are there any other approaches?

答:
There are a number of possible answers here and a lot depends on your application architecture.

Are two users going to be working on the same row at the same time? And if so, if they have different ideas about what data should be there, this sounds like a business problem that needs to be considered and resolved.

That said, if you have a front end that is receiving data and then trying to write back, using either a time stamp or a checksum as part of validation is a common and useful way of handling this solution.

If I were implementing this I would use a stored procedure and force my application to pass the checksum back to the proc. The procedure would check to see if the checksum is still accurate and the write would fail if it wasn't.


问:
Remove duplicate attribute from HTMLString through regex
I am having a HtmlString where the some tag is having multiple "href" attribute. I have to remove one of them. If href attribute is more then 1 then have to remove blank href attribute through regex. </p>

```<code><p>
  Contrary to popular belief, Lorem Ipsum is not simply random text.It has
  <a title="Test PDF for RTF" href="" title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
     Test PDF
  </a>
  roots in a piece of classical Latin literature from 45 BC, making
  <a title="Learn More" href="test.html" title="Learn More" >
    Learn More
  </a>
  it over 2000 years old. Richard McClintock,
  <a title="Test Page" href="" >
    Test Page
  </a>
  Latin professor at Hampden-Sydney College in Virginia,
  <a title="Test PDF for RTF" href="" title="Test PDF for RTF" href="Test%20PDF%20for%20rtf.pdf">
    Test PDF
  </a>
  looked up one of the more obscure Latin words, consectetur
</p>
</code>```

答:
A possible solution (removes duplicates and href=blank):

```<code> (\w+=".*?")(?=[^>]+\1)|href="" //replace with nothing
</code>```

Assumes that a > not occurring yet means that we're in the same tag, which is perhaps naive but maybe safe enough for your purposes.

Body:
I am having a HtmlString where the some tag is having multiple "href" attribute. I have to remove one of them. If href attribute is more then 1 then have to remove blank href attribute through regex.

  Contrary to popular belief, Lorem Ipsum is not simply random text.It has

     Test PDF

  roots in a piece of classical Latin literature from 45 BC, making

    Learn More

  it over 2000 years old. Richard McClintock,

    Test Page

  Latin professor at Hampden-Sydney College in Virginia,

    Test PDF

  looked up one of the more obscure Latin words, consectetur

Body:
A possible solution (removes duplicates and href=blank):

 (\w+=".*?")(?=[^>]+\1)|href="" //replace with nothing

Assumes that a > not occurring yet means that we're in the same tag, which is perhaps naive but maybe safe enough for your purposes.


问:
C++ - Setting a node to NULL doesn't work
```<code>#include <iostream>
using namespace std;
struct node{
  int val;
  node* left, *right;
};

void _delete(node *root)
{
  root = NULL;
}
void change(node *root)
{
  root->val = 6;
}
int main()
{
  node * root = new node;
  root->val = 5;
  change(root);
  _delete(root);
  cout<<root->val<<endl;
  return 0;
}
</code>```

The output of the above program is 6. It seems as if the _delete function has no effect on the root node but change function has an effect on the root node. It is almost as if delete treats the argument passed as a local variable but change treats the argument as a global variable. Is there anything that I am missing out or is this normal? If it is normal, please explain.

答:
Since you pass the pointer by value in your _delete function, the value in the caller is not changed.

The quickest fix is to write

void _delete(node*& root)

i.e. pass the pointer by reference: note the &; you might also want to call delete on the pointer there too else you leak memory. The function change works as it is since you are using the pointer to member operator ->.

Body:
#include <iostream>
using namespace std;
struct node{
  int val;
  node* left, *right;
};

void _delete(node *root)
{
  root = NULL;
}
void change(node *root)
{
  root->val = 6;
}
int main()
{
  node * root = new node;
  root->val = 5;
  change(root);
  _delete(root);
  cout<<root->val<<endl;
  return 0;
}

The output of the above program is 6. It seems as if the _delete function has no effect on the root node but change function has an effect on the root node. It is almost as if delete treats the argument passed as a local variable but change treats the argument as a global variable. Is there anything that I am missing out or is this normal? If it is normal, please explain.


问:
How to open Master page by clicking my own button in the datail page in Xamarin.Forms
Usually when creating a MasterDetailPage, a toobar with hamburger button are created automatically, I need to create a normal button in middle of the screen and the master page would open and swipe automatically from the left without seeing the toolbar with its hamburger button, I wanna hide the toolbar entirly. Is there anyway to achieve that?</p>

答:
I have set the following code in the buttonClick function which is located in the detail page

```<code>MessagingCenter.Send<MainPage>(this, "OpenMenu");
</code>```

Then I used the follwing code in the Master page

```<code>MessagingCenter.Subscribe<MainPage>(this, "OpenMenu", (sender) => {
            IsPresented = true;
        });
</code>```

and to hide the toolbar in the detail page I used :

```<code>NavigationPage.SetHasNavigationBar(this, false);
</code>```

Body:
I have set the following code in the buttonClick function which is located in the detail page

MessagingCenter.Send<MainPage>(this, "OpenMenu");

Then I used the follwing code in the Master page

MessagingCenter.Subscribe<MainPage>(this, "OpenMenu", (sender) => {
            IsPresented = true;
        });

and to hide the toolbar in the detail page I used :

NavigationPage.SetHasNavigationBar(this, false);


问:
determining if a Class object is an instance of an abstract class
I'm trying to determine if a generic class object is an instance of an abstract class.  So far I'm not having much luck.  Below is the code I'm trying to use. AbstractActivity is the name of a parent class I extend some of my activities from.</p>

```<code>public void startActivity(Intent intent)
{
    ComponentName name = intent.getComponent();

    if(name != null)
    {
        Class<?> cls = null;
        try {
            cls = Class.forName(name.getClassName());

            if(cls.isInstance(AbstractActivity));
            {
                //do something
            }
            else
            {
                super.startActivity(intent);
            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    super.startActivity(intent);
}
</code>```

答:
I would try:</p>

```<code>if(AbstractActivity.class.isAssignableFrom(cls)) {
    ....
}
</code>```

Body:
I'm trying to determine if a generic class object is an instance of an abstract class.  So far I'm not having much luck.  Below is the code I'm trying to use. AbstractActivity is the name of a parent class I extend some of my activities from.

public void startActivity(Intent intent)
{
    ComponentName name = intent.getComponent();

    if(name != null)
    {
        Class<?> cls = null;
        try {
            cls = Class.forName(name.getClassName());

            if(cls.isInstance(AbstractActivity));
            {
                //do something
            }
            else
            {
                super.startActivity(intent);
            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    super.startActivity(intent);
}

Body:
I would try:

if(AbstractActivity.class.isAssignableFrom(cls)) {
    ....
}


问:
Image is not existing in document directory if I will run the app again using Swift 3
I am saving a camera image into my document directory. I am creating a document directory in my util class. Here below is my code :-

```<code>//Get Document Directory Path
func getDirectoryPath() -> String {
  let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Phss")
  return paths
}

//Create Directory
func createDirectory(){
  let fileManager = FileManager.default

  let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Phss")

  if !fileManager.fileExists(atPath: paths){
    try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
  }

  else{
    Helper.sharedInstance.Print("Already dictionary created." as AnyObject)
  }
}
</code>```

After that I am saving image by name and some value (docAddedTime) and storing the path(imagePath) in my core data DB.

```<code>func saveImageDocumentDirectory(imageData : Data, docName : String) -> String {
    let fileManager = FileManager.default
    let imagePAth = (getDirectoryPath() as NSString).appendingPathComponent("\(String(describing: docAddedTime!) + "_" + "\(String(describing: docName))").png")

    fileManager.createFile(atPath: imagePAth, contents: imageData, attributes: nil)
    return imagePAth
}.
</code>```

I am fetching image by image path which is saved in my local core data DB.

```<code>let fileManager = FileManager.default
    let imagePAth = doc!.docPath! //Core Data DB Path of image

    if fileManager.fileExists(atPath: imagePAth) {
         imgView.image = UIImage(contentsOfFile: imagePAth
       }
</code>```

The problem is first time I am able to fetch image and is showing in my imageView but after that I will run the app again and I am trying to fetch image by this imagePath which is stored in my core data DB then it's not giving that file exist at this path.

Image is present at same Path but showing is not exits. I am not sure why this is happening.

答:
```<code>let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName")
</code>```

You can try the above snippet. This one don't create a directory though, I would suggest first try to fetch straight from Documents directory, once its a success then create a directory and then store it.Let me know the exact scenario. What is the value of the path showing when running for the next time.

Body:
I am saving a camera image into my document directory. I am creating a document directory in my util class. Here below is my code :-

//Get Document Directory Path
func getDirectoryPath() -> String {
  let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Phss")
  return paths
}

//Create Directory
func createDirectory(){
  let fileManager = FileManager.default

  let paths = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent("Phss")

  if !fileManager.fileExists(atPath: paths){
    try! fileManager.createDirectory(atPath: paths, withIntermediateDirectories: true, attributes: nil)
  }

  else{
    Helper.sharedInstance.Print("Already dictionary created." as AnyObject)
  }
}

After that I am saving image by name and some value (docAddedTime) and storing the path(imagePath) in my core data DB.

func saveImageDocumentDirectory(imageData : Data, docName : String) -> String {
    let fileManager = FileManager.default
    let imagePAth = (getDirectoryPath() as NSString).appendingPathComponent("\(String(describing: docAddedTime!) + "_" + "\(String(describing: docName))").png")

    fileManager.createFile(atPath: imagePAth, contents: imageData, attributes: nil)
    return imagePAth
}.

I am fetching image by image path which is saved in my local core data DB.

let fileManager = FileManager.default
    let imagePAth = doc!.docPath! //Core Data DB Path of image

    if fileManager.fileExists(atPath: imagePAth) {
         imgView.image = UIImage(contentsOfFile: imagePAth
       }

The problem is first time I am able to fetch image and is showing in my imageView but after that I will run the app again and I am trying to fetch image by this imagePath which is stored in my core data DB then it's not giving that file exist at this path.

Image is present at same Path but showing is not exits. I am not sure why this is happening.

Body:
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: paths).appendingPathComponent("fileName")

You can try the above snippet. This one don't create a directory though, I would suggest first try to fetch straight from Documents directory, once its a success then create a directory and then store it.Let me know the exact scenario. What is the value of the path showing when running for the next time.


问:
Selenium driver cannot be found in environment variables
I have been using selenium and everything has been working fine.

I have been including the chromedriver and others in my bin directory so that they can be picked up.

If I move them outside this location then I get the below error message.

Result Message:   OneTimeSetUp:
  OpenQA.Selenium.DriverServiceNotFoundException : The chromedriver.exe
  file does not exist in the current directory or in a directory on the
  PATH environment variable. The driver can be downloaded at
  http://chromedriver.storage.googleapis.com/index.html.

I understand this is due to it not finding the driver exe so the location is needed to be referenced.

If i put it in the code everything works fine

```<code>Instance = new ChromeDriver("C:\\drivers");
</code>```

The issue I have is that hard coded locations are bad practice and I don't want to do this as I am making a reusable component for others who may wish to store drivers on a 2nd HD.

I have added the location in to my path environment variables as the error above suggests however my code then cannot pick up the driver exe

Is there a step I am missing?

答:
You are giving the path till drivers. Should you not give the path till chromedriver.exe.

i.e try replacing your code with

Instance = new ChromeDriver("C:\drivers\chromedriver.exe");

if your chromedriver.exe is in the folder drivers

Body:
I have been using selenium and everything has been working fine.

I have been including the chromedriver and others in my bin directory so that they can be picked up.

If I move them outside this location then I get the below error message.

Result Message:   OneTimeSetUp:
  OpenQA.Selenium.DriverServiceNotFoundException : The chromedriver.exe
  file does not exist in the current directory or in a directory on the
  PATH environment variable. The driver can be downloaded at
  http://chromedriver.storage.googleapis.com/index.html.

I understand this is due to it not finding the driver exe so the location is needed to be referenced.

If i put it in the code everything works fine

Instance = new ChromeDriver("C:\\drivers");

The issue I have is that hard coded locations are bad practice and I don't want to do this as I am making a reusable component for others who may wish to store drivers on a 2nd HD.

I have added the location in to my path environment variables as the error above suggests however my code then cannot pick up the driver exe

Is there a step I am missing?


问:
I am not able to post data to Mysql database using Volley library
Here is the volley code which is throwing following exception
"Attempt to invoke virtual method 'int java.lang.String.hashCode()".

```<code>String url = "http://192.168.60.02/TransportTracking/main.php";

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error
                Log.d("Error.Response", error.getMessage());
            }
        }
) {
    @Override
    protected Map<String, String> getParams()
    {
        Map<String, String>  params = new HashMap<String, String>();
        params.put("long","100");
        params.put("lat", "200");
        params.put("recordtime","acbcbcb");

        return params;
    }
};
    AppController.getInstance().addToRequestQueue(postRequest, "tag_json_obj");
</code>```

and Here is the Log of error:

07-06 08:07:54.315 2837-2837/com.example.jawadtariq.uogtransporttrackingsystem E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.jawadtariq.uogtransporttrackingsystem, PID: 2837

java.lang.NullPointerException: Attempt to invoke virtual method 'int
  java.lang.String.hashCode()' on a null object reference
                                                                                at com.android.volley.Request.(Request.java:136)
                                                                                at
  com.android.volley.toolbox.StringRequest.(StringRequest.java:43)

```<code>                                                                                at com.example.jawadtariq.uogtransporttrackingsystem.LocationService$3.<init>(LocationService.java:98)
                                                                                at com.example.jawadtariq.uogtransporttrackingsystem.LocationService.onConnected(LocationService.java:81)
                                                                                at com.google.android.gms.common.internal.zzac.zzn(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbco.zzm(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcc.zzpY(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcc.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcw.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbbh.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzaa.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzn.zzrj(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zze.zzs(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzi.zzrk(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzh.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
</code>```

One last thing to mention is that I have googled this exception before posting here and most of the problem questions have incorrect URL. But in my case URL is correct.

答:
Declare a instance of volley request-queue and then add a stringRequest in it.
like </p>

```<code>RequestQueue requestQueue =
             Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
        }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error
                Log.d("Error.Response", error.getMessage());
            }
        }
    ){
    @Override
    protected Map<String, String> getParams()
    {
        Map<String, String>  params = new HashMap<String, String>();
        params.put("long","100");
        params.put("lat", "200");
        params.put("recordtime","acbcbcb");
        return params;
    }
};

requestQueue.add(postRequest);
</code>```

<p>This is working code for me. </p>

Body:
Here is the volley code which is throwing following exception
"Attempt to invoke virtual method 'int java.lang.String.hashCode()".

String url = "http://192.168.60.02/TransportTracking/main.php";

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error
                Log.d("Error.Response", error.getMessage());
            }
        }
) {
    @Override
    protected Map<String, String> getParams()
    {
        Map<String, String>  params = new HashMap<String, String>();
        params.put("long","100");
        params.put("lat", "200");
        params.put("recordtime","acbcbcb");

        return params;
    }
};
    AppController.getInstance().addToRequestQueue(postRequest, "tag_json_obj");

and Here is the Log of error:

07-06 08:07:54.315 2837-2837/com.example.jawadtariq.uogtransporttrackingsystem E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.jawadtariq.uogtransporttrackingsystem, PID: 2837

java.lang.NullPointerException: Attempt to invoke virtual method 'int
  java.lang.String.hashCode()' on a null object reference
                                                                                at com.android.volley.Request.(Request.java:136)
                                                                                at
  com.android.volley.toolbox.StringRequest.(StringRequest.java:43)

                                                                                at com.example.jawadtariq.uogtransporttrackingsystem.LocationService$3.<init>(LocationService.java:98)
                                                                                at com.example.jawadtariq.uogtransporttrackingsystem.LocationService.onConnected(LocationService.java:81)
                                                                                at com.google.android.gms.common.internal.zzac.zzn(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbco.zzm(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcc.zzpY(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcc.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbcw.onConnected(Unknown Source)
                                                                                at com.google.android.gms.internal.zzbbh.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzaa.onConnected(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzn.zzrj(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zze.zzs(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzi.zzrk(Unknown Source)
                                                                                at com.google.android.gms.common.internal.zzh.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5221)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

One last thing to mention is that I have googled this exception before posting here and most of the problem questions have incorrect URL. But in my case URL is correct.

Body:
Declare a instance of volley request-queue and then add a stringRequest in it.
like

RequestQueue requestQueue =
             Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
        new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                // response
                Log.d("Response", response);
        }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error
                Log.d("Error.Response", error.getMessage());
            }
        }
    ){
    @Override
    protected Map<String, String> getParams()
    {
        Map<String, String>  params = new HashMap<String, String>();
        params.put("long","100");
        params.put("lat", "200");
        params.put("recordtime","acbcbcb");
        return params;
    }
};

requestQueue.add(postRequest);

This is working code for me.