问:
Parsing Returned JSON
I am trying to print some of the values from the API call to the console, but I am receiving an error I am unfamiliar with:

System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'

I think that I might be incorrectly accessing the values returned to by the API, but I am not 100% sure whats wrong

I've looked at a few other posts about this same issue and tried to implement the fixes suggested, but none of them were able to solve my problem. I think mine is unique as my JSON object is different from others I have seen.

```<code>namespace CarQueryAPI
{
    class CarResult
    {
        public string model_name { get; set; }
    }
}

namespace CarQueryAPI
{
    class Program
    {
        public static void Main(string[] args)
    {
        apiCall();
        Console.ReadKey();
    }

    public static void apiCall()
    {
        //client to invoke the car query api
        WebClient client = new WebClient();

        Task<String> carQueryTask = null;// Task<string> that queries carQuery

        // url for API (no key required)
        string url = "https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&make=toyota&model=camry&year=2005";

        try
        {
           //request info from the api
            carQueryTask = client.DownloadStringTaskAsync(url);

            string result = carQueryTask.Result.Remove(0, 2);
            result = result.Remove(result.Length - 4, 4);

            dynamic json = JsonConvert.DeserializeObject(result);

            string model_name = json.model_name;

            Console.WriteLine(model_name);
        }

        catch (WebException)
        {
            // check whether Task failed
            if (carQueryTask.Status == TaskStatus.Faulted)
            {
                Console.WriteLine("Call Failed");
            }
        }
    }
}
</code>```

}

i need the result to e just the model_name of the car being returned from the call so that I can see how to capture the others as well.

The following is some of the JSON object being returned:

```<code>?({"Trims":[{"model_id":"38988","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 GLi Automatic","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2360","model_engine_cyl":null,"model_engine_type":null,"model_engine_valves_per_cyl":"4","model_engine_power_ps":"152","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"4000","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":null,"model_top_speed_kph":"197","model_0_to_100_kph":"10.6","model_drive":"Front","model_transmission_type":"Automatic","model_seats":"5","model_doors":"4","model_weight_kg":"920","model_length_mm":null,"model_width_mm":null,"model_height_mm":null,"model_wheelbase_mm":"2730","model_lkm_hwy":null,"model_lkm_mixed":null,"model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"},{"model_id":"38999","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 WT-i","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2362","model_engine_cyl":"4","model_engine_type":"in-line","model_engine_valves_per_cyl":"4","model_engine_power_ps":"153","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"3800","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":"Gasoline - Premium","model_top_speed_kph":"210","model_0_to_100_kph":"9.4","model_drive":"Front","model_transmission_type":null,"model_seats":"5","model_doors":"4","model_weight_kg":"1465","model_length_mm":"4820","model_width_mm":"1800","model_height_mm":"1510","model_wheelbase_mm":"2680","model_lkm_hwy":null,"model_lkm_mixed":"8.7","model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"}
</code>```

...etc

EDIT:

Changed some of the code as you all suggested, but now I am receiving this error:

Unexpected end when deserializing object. Path 'Trims[18]', line 1, position 19143

答:
The response you're receiving is JSON, not XML.

First, take the JSON without the leading ?( and trailing ); and paste it into json2csharp.com. It's going to generate C# classes you can use to deserialize your JSON. The results aren't always exactly what you want, but your JSON is straightforward, so you'll get two classes that look like this:

```<code>public class Trim
{
    public string model_id { get; set; }
    public string model_make_id { get; set; }
    public string model_name { get; set; }
    public string model_trim { get; set; }
    // .. lots of other properties
}

public class CarQueryApiTrimsResponse // This was RootObject - I renamed it.
{
    public List<Trim> Trims { get; set; }
}
</code>```

It names the outermost class RootObject because it doesn't know what else to call it. I renamed it CarQueryApiTrimsResponse to indicate where it comes from.

Include those classes in your project.

In your sample the variable with the response is called carQueryTask. To make it a little clearer I'll call it carQueryResponseJson. (I don't know how much better that is, but it says it's JSON.)

You'll need to trim those characters off the beginning and end, so you could create a function like this:

```<code>string TrimWeirdCharactersFromJson(string json)
{
    if (json.StartsWith("?("))
        json = json.Remove(0, 2);
    if (json.EndsWith(");"))
        json = json.Remove(json.Length - 2, 2);
    return json;
}
</code>```

(I have to allow for the possibility that those characters are there for some reason of which I'm ignorant.)

Now, assuming you've added the Newtonsoft.Json package to your project, you can do this, starting with the JSON you've received:

```<code>// fix the weird characters
carQueryResponseJson = TrimWeirdCharactersFromJson(carQueryResponseJson);

// deserialize the JSON, creating an instance of CarQueryApiTrimsResponse
var trims = JsonConvert.DeserializeObject<CarQueryApiTrimsResponse>(carQueryResponseJson);

// Now you've got a strongly-typed object and you can access the contents of the
// collection and properties of each trim.
foreach (var trim in trims.Trims)
{
    var modelName = trim.model_name;
     // do something with it
}
</code>```

Title: Parsing Returned JSON

Body:
I am trying to print some of the values from the API call to the console, but I am receiving an error I am unfamiliar with:

System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'

I think that I might be incorrectly accessing the values returned to by the API, but I am not 100% sure whats wrong

I've looked at a few other posts about this same issue and tried to implement the fixes suggested, but none of them were able to solve my problem. I think mine is unique as my JSON object is different from others I have seen.

namespace CarQueryAPI
{
    class CarResult
    {
        public string model_name { get; set; }
    }
}

namespace CarQueryAPI
{
    class Program
    {
        public static void Main(string[] args)
    {
        apiCall();
        Console.ReadKey();
    }

    public static void apiCall()
    {
        //client to invoke the car query api
        WebClient client = new WebClient();

        Task<String> carQueryTask = null;// Task<string> that queries carQuery

        // url for API (no key required)
        string url = "https://www.carqueryapi.com/api/0.3/?callback=?&cmd=getTrims&make=toyota&model=camry&year=2005";

        try
        {
           //request info from the api
            carQueryTask = client.DownloadStringTaskAsync(url);

            string result = carQueryTask.Result.Remove(0, 2);
            result = result.Remove(result.Length - 4, 4);

            dynamic json = JsonConvert.DeserializeObject(result);

            string model_name = json.model_name;

            Console.WriteLine(model_name);
        }

        catch (WebException)
        {
            // check whether Task failed
            if (carQueryTask.Status == TaskStatus.Faulted)
            {
                Console.WriteLine("Call Failed");
            }
        }
    }
}

}

i need the result to e just the model_name of the car being returned from the call so that I can see how to capture the others as well.

The following is some of the JSON object being returned:

?({"Trims":[{"model_id":"38988","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 GLi Automatic","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2360","model_engine_cyl":null,"model_engine_type":null,"model_engine_valves_per_cyl":"4","model_engine_power_ps":"152","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"4000","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":null,"model_top_speed_kph":"197","model_0_to_100_kph":"10.6","model_drive":"Front","model_transmission_type":"Automatic","model_seats":"5","model_doors":"4","model_weight_kg":"920","model_length_mm":null,"model_width_mm":null,"model_height_mm":null,"model_wheelbase_mm":"2730","model_lkm_hwy":null,"model_lkm_mixed":null,"model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"},{"model_id":"38999","model_make_id":"toyota","model_name":"Camry","model_trim":"2.4 WT-i","model_year":"2005","model_body":"Sedan","model_engine_position":"Front","model_engine_cc":"2362","model_engine_cyl":"4","model_engine_type":"in-line","model_engine_valves_per_cyl":"4","model_engine_power_ps":"153","model_engine_power_rpm":"5600","model_engine_torque_nm":"218","model_engine_torque_rpm":"3800","model_engine_bore_mm":"88.5","model_engine_stroke_mm":"96.0","model_engine_compression":"9.6:1","model_engine_fuel":"Gasoline - Premium","model_top_speed_kph":"210","model_0_to_100_kph":"9.4","model_drive":"Front","model_transmission_type":null,"model_seats":"5","model_doors":"4","model_weight_kg":"1465","model_length_mm":"4820","model_width_mm":"1800","model_height_mm":"1510","model_wheelbase_mm":"2680","model_lkm_hwy":null,"model_lkm_mixed":"8.7","model_lkm_city":null,"model_fuel_cap_l":"70","model_sold_in_us":"1","model_co2":null,"model_make_display":"Toyota","make_display":"Toyota","make_country":"Japan"}

...etc

EDIT:

Changed some of the code as you all suggested, but now I am receiving this error:

Unexpected end when deserializing object. Path 'Trims[18]', line 1, position 19143

Body:
The response you're receiving is JSON, not XML.

First, take the JSON without the leading ?( and trailing ); and paste it into json2csharp.com. It's going to generate C# classes you can use to deserialize your JSON. The results aren't always exactly what you want, but your JSON is straightforward, so you'll get two classes that look like this:

public class Trim
{
    public string model_id { get; set; }
    public string model_make_id { get; set; }
    public string model_name { get; set; }
    public string model_trim { get; set; }
    // .. lots of other properties
}

public class CarQueryApiTrimsResponse // This was RootObject - I renamed it.
{
    public List<Trim> Trims { get; set; }
}

It names the outermost class RootObject because it doesn't know what else to call it. I renamed it CarQueryApiTrimsResponse to indicate where it comes from.

Include those classes in your project.

In your sample the variable with the response is called carQueryTask. To make it a little clearer I'll call it carQueryResponseJson. (I don't know how much better that is, but it says it's JSON.)

You'll need to trim those characters off the beginning and end, so you could create a function like this:

string TrimWeirdCharactersFromJson(string json)
{
    if (json.StartsWith("?("))
        json = json.Remove(0, 2);
    if (json.EndsWith(");"))
        json = json.Remove(json.Length - 2, 2);
    return json;
}

(I have to allow for the possibility that those characters are there for some reason of which I'm ignorant.)

Now, assuming you've added the Newtonsoft.Json package to your project, you can do this, starting with the JSON you've received:

// fix the weird characters
carQueryResponseJson = TrimWeirdCharactersFromJson(carQueryResponseJson);

// deserialize the JSON, creating an instance of CarQueryApiTrimsResponse
var trims = JsonConvert.DeserializeObject<CarQueryApiTrimsResponse>(carQueryResponseJson);

// Now you've got a strongly-typed object and you can access the contents of the
// collection and properties of each trim.
foreach (var trim in trims.Trims)
{
    var modelName = trim.model_name;
     // do something with it
}


来源: stackexchange

问:
JavaScript naming conventions
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.

How do you name your variables, functions, objects and such?

I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.

The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.

答:
As Geoff says, what Crockford says is good.

The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object.  E.g.

var footer = document.getElementById('footer');

var $footer = $('#footer');

ContentLicense: CC BY-SA 4.0

Title: JavaScript naming conventions

ContentLicense: CC BY-SA 3.0


问:
path name contains null byte for image url while existing
I'm using the following code to get the width of image using Dimensions Gem.

```<code>file_path = "http://localhost:3000/uploads/resize/avatar/25/ch05.jpg"
width = Dimensions.width(open(file_path).read)
</code>```

When I put the image url in url bar it renders the image in browser. what I'm trying to do is to get the width of image. so can anyone know what I'm doing wrong?

答:
So your issue is that Dimensions requires a file path to determine the width of the image. open will return a StringIO and open(...).read will return a String both will fail when using File.open.

Dimensions#width

```<code>def width(path)
  io_for(path).width
end
</code>```

Dimensions#io_for

```<code>def io_for(path)
  Dimensions(File.open(path, "rb")).tap do |io|
    io.read
    io.close
  end
end
</code>```

To work around this you can download the image to a Tempfile and then use that path to pass to Dimensions.width like so

```<code> path = "http://localhost:3000/uploads/resize/avatar/25/ch05.jpg"
 t = Tempfile.new                 # you could add a name but it doesn't matter
 t.write(open(path).read)         # write the image to the Tempfile
 t.close                          # must close the file before reading it
 width = Dimensions.width(t.path) # pass the Tempfile path to Dimensions
 t.unlink                         # deletes the Tempfile
</code>```

We can make this look a little cleaner like so:

```<code>def get_width_of_url_image(url)
  t = Tempfile.new.tap do |f|
    f.write(open(url).read)
    f.close
  end
  width = Dimensions.width(t.path)
  t.unlink and width
end

get_width_of_url_image("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png")
#=> 272
</code>```

Body:
I'm using the following code to get the width of image using Dimensions Gem.

file_path = "http://localhost:3000/uploads/resize/avatar/25/ch05.jpg"
width = Dimensions.width(open(file_path).read)

When I put the image url in url bar it renders the image in browser. what I'm trying to do is to get the width of image. so can anyone know what I'm doing wrong?

Body:
So your issue is that Dimensions requires a file path to determine the width of the image. open will return a StringIO and open(...).read will return a String both will fail when using File.open.

Dimensions#width

def width(path)
  io_for(path).width
end

Dimensions#io_for

def io_for(path)
  Dimensions(File.open(path, "rb")).tap do |io|
    io.read
    io.close
  end
end

To work around this you can download the image to a Tempfile and then use that path to pass to Dimensions.width like so

 path = "http://localhost:3000/uploads/resize/avatar/25/ch05.jpg"
 t = Tempfile.new                 # you could add a name but it doesn't matter
 t.write(open(path).read)         # write the image to the Tempfile
 t.close                          # must close the file before reading it
 width = Dimensions.width(t.path) # pass the Tempfile path to Dimensions
 t.unlink                         # deletes the Tempfile

We can make this look a little cleaner like so:

def get_width_of_url_image(url)
  t = Tempfile.new.tap do |f|
    f.write(open(url).read)
    f.close
  end
  width = Dimensions.width(t.path)
  t.unlink and width
end

get_width_of_url_image("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png")
#=> 272


问:
Upload to s3 via PHP fails access denied
I feel a bit stupid to ask this, but is there anything special required to upload something via the current PHP SDK to S3? I can upload via the cli with the same credentials, but when I try the SDK it fails.

Here the code:

```<code><?php
require "awssdk_v3/aws-autoloader.php";

use Aws\S3\S3Client;

function s3_upload($file, $name) {
    $s3 = S3Client::factory(
        array(
            'key' => getenv('AWS_ACCESS_KEY_ID'),
            'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
            'version' => "2006-03-01",
            'region' => getenv('AWS_REGION')
        )
    );
    $result = $s3->putObject(
        array(
            'Bucket' => getenv('AWS_BUCKET'),
            'Key' => $name,
            'SourceFile' => $file,
            'ContentType' => mime_content_type($file),
            'ACL' => 'public-read'
        )
    );
    return true;
}
</code>```

I call it like this

```<code>s3_upload($_FILES['avatarfile']['tmp_name'], "avatar_2.jpg");
</code>```

The user I use has this policy attached:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1480066717000",
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Sid": "Stmt1480066765000",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket"
            ]
        }
    ]
}
</code>```

As mentioned I was able to upload a file from the CLI using that users credentials. The region is Frankfurt, so I specified eu-central-1, correct?

The error I get starts like this:

```<code>Fatal error: Uncaught exception 'Aws\S3\Exception\S3Exception' with message 'Error executing "PutObject" on "https://my-bucket.s3.eu-central-1.amazonaws.com/avatar_2.jpg"; AWS HTTP error: Client error: `PUT https://my-bucket.s3.eu-central-1.amazonaws.com/avatar_2.jpg` resulted in a `403 Forbidden` response
</code>```

答: I ran into this same error message, and it turns out my S3 buckets were created in the wrong region.</p>

Body:
I feel a bit stupid to ask this, but is there anything special required to upload something via the current PHP SDK to S3? I can upload via the cli with the same credentials, but when I try the SDK it fails.

Here the code:

<?php
require "awssdk_v3/aws-autoloader.php";

use Aws\S3\S3Client;

function s3_upload($file, $name) {
    $s3 = S3Client::factory(
        array(
            'key' => getenv('AWS_ACCESS_KEY_ID'),
            'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
            'version' => "2006-03-01",
            'region' => getenv('AWS_REGION')
        )
    );
    $result = $s3->putObject(
        array(
            'Bucket' => getenv('AWS_BUCKET'),
            'Key' => $name,
            'SourceFile' => $file,
            'ContentType' => mime_content_type($file),
            'ACL' => 'public-read'
        )
    );
    return true;
}

I call it like this

s3_upload($_FILES['avatarfile']['tmp_name'], "avatar_2.jpg");

The user I use has this policy attached:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1480066717000",
            "Effect": "Allow",
            "Action": [
                "s3:DeleteObject",
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket/*"
            ]
        },
        {
            "Sid": "Stmt1480066765000",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket"
            ]
        }
    ]
}

As mentioned I was able to upload a file from the CLI using that users credentials. The region is Frankfurt, so I specified eu-central-1, correct?

The error I get starts like this:

Fatal error: Uncaught exception 'Aws\S3\Exception\S3Exception' with message 'Error executing "PutObject" on "https://my-bucket.s3.eu-central-1.amazonaws.com/avatar_2.jpg"; AWS HTTP error: Client error: `PUT https://my-bucket.s3.eu-central-1.amazonaws.com/avatar_2.jpg` resulted in a `403 Forbidden` response


问:
R: Replace last 3 zeroes with K in a column
I am trying to replace last 3 000 with K in a column in the dataframe

eg:

```<code>data <- data.frame(abc = c(1000, 100000, 450000))

abc <- 1000
then abc <- 1K

if
abc <- 100000
then abc <- 100K
</code>```

gsub or regex replaces the first 3 zeroes

I tried this:

```<code>lapply(data$abc, gsub, pattern = "000", replacement = "K", fixed = TRUE)
</code>```

Also, how can I make it work on an interval like :

```<code>data <- data.frame(abc = c("150000-250000", "100000-150000", "250000K+"))
</code>```

答:
Here is a slight modification of your code. format is to turn off the scientific notation. sapply makes the output becomes a vector. 000$ means only match those at the end.

```<code>data <- data.frame(abc = c(1000, 100000, 450000))

data$abc <- format(data$abc, scientific = FALSE)

gsub(pattern = "000$", replacement = "K", data$abc)
# [1] "  1K" "100K" "450K"
</code>```

Body:
I am trying to replace last 3 000 with K in a column in the dataframe

eg:

data <- data.frame(abc = c(1000, 100000, 450000))

abc <- 1000
then abc <- 1K

if
abc <- 100000
then abc <- 100K

gsub or regex replaces the first 3 zeroes

I tried this:

lapply(data$abc, gsub, pattern = "000", replacement = "K", fixed = TRUE)

Also, how can I make it work on an interval like :

data <- data.frame(abc = c("150000-250000", "100000-150000", "250000K+"))

Body:
Here is a slight modification of your code. format is to turn off the scientific notation. sapply makes the output becomes a vector. 000$ means only match those at the end.

data <- data.frame(abc = c(1000, 100000, 450000))

data$abc <- format(data$abc, scientific = FALSE)

gsub(pattern = "000$", replacement = "K", data$abc)
# [1] "  1K" "100K" "450K"


问:
How to create an index signature for an interface
I don't know how I should create an index signature for my interface.

I've just been working as a developer for 2 months and I am stumped about this issue. This is my first question on stack.

My code looks like this.

```<code>handleChangeWithConfirm = (fieldToConfirm: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
    const name = event.target.name;
    const value = event.target.value;
    const {credentials} = this.state;
    credentials[name] = value;

    if (this.state.credentials[fieldToConfirm] !== event.target.value) {
        this.setState({confirmError: 'The Passwords do not match.', credentials});
    } else {
        this.setState({confirmError: '', credentials});
    }

export interface ICredentials {
    email: string,
    password?: string,
    username?: string,
    password_confirmation?: string,
    token?: string
}
</code>```

I then get the following error.

TS7017: Element implicitly has an 'any' type because type 'ICredentials' has no index signature.

答:
In order to use the object[key] syntax, you must inform the typescript compiler that your object can index using a specific type (for instance, using string or numbers).

From the typescript documentation:

Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

A code example (from the documentation as well):

```<code>interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];
</code>```

So, in order to make your credentials object indexable, you should declare it like that:

```<code>export interface ICredentials {
        email: string,
        password?: string,
        username?: string,
        password_confirmation?: string,
        token?: string
        [key: string]: string;
    }
</code>```

Body:
I don't know how I should create an index signature for my interface.

I've just been working as a developer for 2 months and I am stumped about this issue. This is my first question on stack.

My code looks like this.

handleChangeWithConfirm = (fieldToConfirm: string) => (event: React.ChangeEvent<HTMLInputElement>) => {
    const name = event.target.name;
    const value = event.target.value;
    const {credentials} = this.state;
    credentials[name] = value;

    if (this.state.credentials[fieldToConfirm] !== event.target.value) {
        this.setState({confirmError: 'The Passwords do not match.', credentials});
    } else {
        this.setState({confirmError: '', credentials});
    }

export interface ICredentials {
    email: string,
    password?: string,
    username?: string,
    password_confirmation?: string,
    token?: string
}

I then get the following error.

TS7017: Element implicitly has an 'any' type because type 'ICredentials' has no index signature.

Body:
In order to use the object[key] syntax, you must inform the typescript compiler that your object can index using a specific type (for instance, using string or numbers).

From the typescript documentation:

Similarly to how we can use interfaces to describe function types, we can also describe types that we can “index into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing.

A code example (from the documentation as well):

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

So, in order to make your credentials object indexable, you should declare it like that:

export interface ICredentials {
        email: string,
        password?: string,
        username?: string,
        password_confirmation?: string,
        token?: string
        [key: string]: string;
    }


问:
Springboot failed to map properties file to variable
i want to map values between a yaml file with a Map<String, List<String>> in springboot

country.yml file:

```<code>entries:
  map:
     MY:
      - en
      - zh
</code>```

SampleConfig file:

```<code>@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}
</code>```

But the map.size() is always 0, not sure what i do wrong.

答:
There are two problems

1) By default spring will look for application.yml or application.properties in default locations

To solve the above problem you can use application.yml instead of country.yml

2) You can use @PropertySource to load any external properties file but yml is not supported with this annotation

24.7.4 YAML Shortcomings you cannot use @PropertySource with yml file

YAML files cannot be loaded by using the @PropertySource annotation. So, in the case that you need to load values that way, you need to use a properties file.

How to read yml file using Spring @PropertySource

Body:
i want to map values between a yaml file with a Map<String, List<String>> in springboot

country.yml file:

entries:
  map:
     MY:
      - en
      - zh

SampleConfig file:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties("entries")
public class SampleConfig {

    private Map<String, List<String>> map = new HashMap<>();

    @Bean
    public void bean1(){
        System.err.println("map has size: "+map.size());
    }
}

But the map.size() is always 0, not sure what i do wrong.


问:
Is it possible to return a child node and a parent node with JSON PATH in the same queries in javascript
Suppose that we have this JSON:

```<code>{
  "table" :
    [
        {
            "A": "A1",
            "B":
            {
                "BA":"BA1",
                "BB":"BB1"
            }
        },
        {
            "A": "A2",
            "B":
            {
                "BA":"BA2",
                "BB":"BB2"
            }
        }
    ]
}
</code>```

With ONLY ONE query I want to return a set of data composed by 2 type of data: "A" and "BA". For example I can make a request : $.table[<filter>].[A,B.BA]  it doesn't work, but it's the idea. I want to return the value of the parent A and the child BA in ONLY one query. Firstly is it possible and secondly if yes, how ?

答:
It seem that's impossible to retrieve precisely multiple attribute from a JSON Path request. But in certain case, we can do it... But these case are rare and it's risky to use this type of request.
SO there is another way to query JSON objet: JMESPATH. It's FAR better and simplier, and most importantly it solve the problem of retrieving multiple attribute, for my problem the syntax would be: table[<filter>].[A,B.BA] (as I wanted in the initial post). Here's some links:
 - install it: npm page
 - tutorial/official website: website

Body:
Suppose that we have this JSON:

{
  "table" :
    [
        {
            "A": "A1",
            "B":
            {
                "BA":"BA1",
                "BB":"BB1"
            }
        },
        {
            "A": "A2",
            "B":
            {
                "BA":"BA2",
                "BB":"BB2"
            }
        }
    ]
}

With ONLY ONE query I want to return a set of data composed by 2 type of data: "A" and "BA". For example I can make a request : $.table[<filter>].[A,B.BA]  it doesn't work, but it's the idea. I want to return the value of the parent A and the child BA in ONLY one query. Firstly is it possible and secondly if yes, how ?


问:
Reading from google storage gs:// filesystem from local spark instance
The problem is quite simple: You have a local spark instance (either cluster or just running it in local mode) and you want to read from gs://</p>

答:
In my case on Spark 2.4.3 I needed to do the following to enable GCS access from Spark local. I used a JSON keyfile vs. the client.id/secret proposed above.

In $SPARK_HOME/jars/, use the shaded gcs-connector jar from here: http://repo2.maven.org/maven2/com/google/cloud/bigdataoss/gcs-connector/hadoop2-1.9.17/ or else I had various failures with transitive dependencies.

(Optional) To my build.sbt add:

```<code>"com.google.cloud.bigdataoss" % "gcs-connector" % "hadoop2-1.9.17"
    exclude("javax.jms", "jms")
    exclude("com.sun.jdmk", "jmxtools")
    exclude("com.sun.jmx", "jmxri")
</code>```

In $SPARK_HOME/conf/spark-defaults.conf, add:

```<code>spark.hadoop.google.cloud.auth.service.account.enable       true
spark.hadoop.google.cloud.auth.service.account.json.keyfile /path/to/my/keyfile
</code>```

And everything is working.

Body:
In my case on Spark 2.4.3 I needed to do the following to enable GCS access from Spark local. I used a JSON keyfile vs. the client.id/secret proposed above.

In $SPARK_HOME/jars/, use the shaded gcs-connector jar from here: http://repo2.maven.org/maven2/com/google/cloud/bigdataoss/gcs-connector/hadoop2-1.9.17/ or else I had various failures with transitive dependencies.

(Optional) To my build.sbt add:

"com.google.cloud.bigdataoss" % "gcs-connector" % "hadoop2-1.9.17"
    exclude("javax.jms", "jms")
    exclude("com.sun.jdmk", "jmxtools")
    exclude("com.sun.jmx", "jmxri")

In $SPARK_HOME/conf/spark-defaults.conf, add:

spark.hadoop.google.cloud.auth.service.account.enable       true
spark.hadoop.google.cloud.auth.service.account.json.keyfile /path/to/my/keyfile

And everything is working.


问:
Jupyter + rpy2 outputs to command prompt instead of notebook cell

Issue description

Whenever loading rpy2 in a Jupyter notebook, R code executed with a %%Rcell magic gets printed in the command prompt instead of the notebook cell. Plots show up properly in the notebook though.

I also noticed that the %R inline magic works properly, with code printed in the cell as expected.

Installation steps

Python 2.7.11 :: Anaconda 2.5.0 (64-bit)

notebook 4.1.0 installed via pip

R 3.3.1 (x64) located in Program Files

rpy2-2.7.8-cp27-none-win_amd64.whl installed via pip

PATH:

R_USER = C:\Users\myusername

R_HOME = C:\Program Files\R\R-3.3.1

Added C:\Program Files\R\R-3.3.1\bin\i386

答:
You can use the RWinOut Jupyter extension. The following installation instructions are taken from the GitHub page:

You can run the following curl command from a Jupyter notebook cell to download the file to your working directory. You can also download it manually and put it there yourself.

```<code>!curl -O "https://raw.githubusercontent.com/vitorcurtis/RWinOut/master/RWinOut.py"
</code>```

Once it's in your working directory, you can replace %load_ext rpy2.ipython at the top of your script with %load_ext RWinOut. Then you should be able to see the output of cells containing the %%R magic as normal.

This isn't a complete solution, but it's a workaround that might achieve the same effect. I'm not sure if this breaks some functionality, but it seems to work fine for me.

Tested with:

Windows 10 v.1809 Build 17763.503

Python 3.7.2

R 3.6.0

rpy2 2.9.5

One other option is to use the Windows Subsystem for Linux and launch your Jupyter notebook from there. This might not be desirable if you have to reinstall a lot of R and Python packages into a different environment, but will make it so the output will print correctly without requiring this hacky workaround.

Body:
You can use the RWinOut Jupyter extension. The following installation instructions are taken from the GitHub page:

You can run the following curl command from a Jupyter notebook cell to download the file to your working directory. You can also download it manually and put it there yourself.

!curl -O "https://raw.githubusercontent.com/vitorcurtis/RWinOut/master/RWinOut.py"

Once it's in your working directory, you can replace %load_ext rpy2.ipython at the top of your script with %load_ext RWinOut. Then you should be able to see the output of cells containing the %%R magic as normal.

This isn't a complete solution, but it's a workaround that might achieve the same effect. I'm not sure if this breaks some functionality, but it seems to work fine for me.

Tested with:

Windows 10 v.1809 Build 17763.503

Python 3.7.2

R 3.6.0

rpy2 2.9.5

One other option is to use the Windows Subsystem for Linux and launch your Jupyter notebook from there. This might not be desirable if you have to reinstall a lot of R and Python packages into a different environment, but will make it so the output will print correctly without requiring this hacky workaround.


问:
TypeError: update() missing 1 required positional argument: 'self' [discord.Permissions.update()]
Im having problems while updating the role permissions, command is <code>!admin @[user]</code>. The error is in the title </p>

```<code>@client.command(pass_context=True)
async def admin(ctx, *, user = discord.Member):
    rand = random.randint(0, 1024)
    author = ctx.message.author
    role2 = await client.create_role(author.server, name=f"{rand}", colour=discord.Colour(0x010101))
    await client.edit_role(server=author.server, role=role2, permissions=discord.Permissions.update(administrator=True))
    await client.add_roles(user, role2)
</code>```

答:
Your converter should use : instead of =,

Instead of editing the permissions of the role, you can just provide the correct permissions when you make the role:

```<code>@client.command(pass_context=True)
async def admin(ctx, *, user: discord.Member):
    rand = random.randint(0, 1024)
    author = ctx.message.author
    perms = ctx.message.server.default_role.permissions
    perms.update(administrator=True)
    role2 = await client.create_role(author.server, name=f"{rand}", colour=discord.Colour(0x010101), permissions=perms)
    await client.add_roles(user, role2)
</code>```

Body:
Im having problems while updating the role permissions, command is !admin @[user]. The error is in the title

@client.command(pass_context=True)
async def admin(ctx, *, user = discord.Member):
    rand = random.randint(0, 1024)
    author = ctx.message.author
    role2 = await client.create_role(author.server, name=f"{rand}", colour=discord.Colour(0x010101))
    await client.edit_role(server=author.server, role=role2, permissions=discord.Permissions.update(administrator=True))
    await client.add_roles(user, role2)

Body:
Your converter should use : instead of =,

Instead of editing the permissions of the role, you can just provide the correct permissions when you make the role:

@client.command(pass_context=True)
async def admin(ctx, *, user: discord.Member):
    rand = random.randint(0, 1024)
    author = ctx.message.author
    perms = ctx.message.server.default_role.permissions
    perms.update(administrator=True)
    role2 = await client.create_role(author.server, name=f"{rand}", colour=discord.Colour(0x010101), permissions=perms)
    await client.add_roles(user, role2)


问:
R not recognizing if statement in creating new column
I'm trying to create a new column based on if there is a direct character match across 3 columns of the same row. I then want to put a 1 in the new column if there is a match, or a 0 if there is no match. Here's an example of the data:

```<code>   ID    var1   var2  var3
1     1     abc    def   abc
2     2     def    xyz   jkl
3     3     ghi    abc   abc
4     4     jkl    jkl   def
5     4     jkl    jkl   NA
...
</code>```

Here's the code I have:

```<code>   prodprov$var_match <- 0
    for(i in 1:nrow(prodprov)) {
     if(prodprov$var1[i] == prodprov$var2[i] |
     prodprov$var1[i] == prodprov$var3[i] ) {
     prodprov$var_match <- 1
     }
    }
</code>```

But I get this error:
Error in if (prodprov$var1[i] == prodprov$var2[i] |  :
  missing value where TRUE/FALSE needed

The final data frame should look something like this:

```<code>     ID      var1  var2 var3 var_match
1     1     abc    def   abc      1
2     2     def    xyz   jkl      0
3     3     ghi    abc   abc      0
4     4     jkl    jkl   def      1
5     4     jkl    jkl   NA       1
...
</code>```

Any ideas on how to fix this? All of these variables are the same data type (characters). Thanks in advance!

答:
You can take advantage of vectorization in R:

```<code>df$var_match <- df$var1 == df$var2 | df$var1 == df$var3
</code>```

Result:

```<code>df
#   var1 var2 var3 var_match
# 1  abc  def  abc      TRUE
# 2  def  xyz  jkl     FALSE
# 3  ghi  abc  abc     FALSE
# 4  jkl  jkl  def      TRUE
# 5  jkl  jkl <NA>      TRUE
</code>```

Input data frame for completeness:

```<code>df <- data.frame(stringsAsFactors = FALSE,
  var1 = c("abc", "def", "ghi", "jkl", "jkl"),
  var2 = c("def", "xyz", "abc", "jkl", "jkl"),
  var3 = c("abc", "jkl", "abc", "def", NA)
)
</code>```

Body:
I'm trying to create a new column based on if there is a direct character match across 3 columns of the same row. I then want to put a 1 in the new column if there is a match, or a 0 if there is no match. Here's an example of the data:

   ID    var1   var2  var3
1     1     abc    def   abc
2     2     def    xyz   jkl
3     3     ghi    abc   abc
4     4     jkl    jkl   def
5     4     jkl    jkl   NA
...

Here's the code I have:

   prodprov$var_match <- 0
    for(i in 1:nrow(prodprov)) {
     if(prodprov$var1[i] == prodprov$var2[i] |
     prodprov$var1[i] == prodprov$var3[i] ) {
     prodprov$var_match <- 1
     }
    }

But I get this error:
Error in if (prodprov$var1[i] == prodprov$var2[i] |  :
  missing value where TRUE/FALSE needed

The final data frame should look something like this:

     ID      var1  var2 var3 var_match
1     1     abc    def   abc      1
2     2     def    xyz   jkl      0
3     3     ghi    abc   abc      0
4     4     jkl    jkl   def      1
5     4     jkl    jkl   NA       1
...

Any ideas on how to fix this? All of these variables are the same data type (characters). Thanks in advance!

Body:
You can take advantage of vectorization in R:

df$var_match <- df$var1 == df$var2 | df$var1 == df$var3

Result:

df
#   var1 var2 var3 var_match
# 1  abc  def  abc      TRUE
# 2  def  xyz  jkl     FALSE
# 3  ghi  abc  abc     FALSE
# 4  jkl  jkl  def      TRUE
# 5  jkl  jkl <NA>      TRUE

Input data frame for completeness:

df <- data.frame(stringsAsFactors = FALSE,
  var1 = c("abc", "def", "ghi", "jkl", "jkl"),
  var2 = c("def", "xyz", "abc", "jkl", "jkl"),
  var3 = c("abc", "jkl", "abc", "def", NA)
)


问:
switch camera(back/front) in android webrtc
I have used libjingle library for webrtc android application. I have successfully implemented audio video streaming for two way communication.

Till now i was using front camera for video streaming but now i want to put option for users to select front or back camera for video streaming.

How can i archive it? i have no idea about this.

I have tried VideocaptureAndroid switch camera method but not working.

If anyone one knows then help me out for this functionality?

Thanks in advance.

答:
Here is an example using libjingle.

If you want to switch between the front and rear camera you will need to get the name of the device you want to use.  This can be done using VideoCapturerAndroid.getNameOfFrontFacingDevice() or VideoCapturerAndroid.getNameOfRearFacingDevice() depending on whether you want to use the front or rear camera.

Here's a simple example of how to get the correct VideoCapturer using io.pristine.libjingle:9127

```<code>private VideoCapturer getCameraCapturer(boolean useFrontCamera) {
    String deviceName = useFrontCamera ? VideoCapturerAndroid.getNameOfFrontFacingDevice() : VideoCapturerAndroid.getNameOfBackFacingDevice();
    return VideoCapturerAndroid.create(deviceName);
}
</code>```

If you're using a different version of LibJingle or for any reason this doesn't work let me know and I'll be happy to help!

Cheers,

Body:
Here is an example using libjingle.

If you want to switch between the front and rear camera you will need to get the name of the device you want to use.  This can be done using VideoCapturerAndroid.getNameOfFrontFacingDevice() or VideoCapturerAndroid.getNameOfRearFacingDevice() depending on whether you want to use the front or rear camera.

Here's a simple example of how to get the correct VideoCapturer using io.pristine.libjingle:9127

private VideoCapturer getCameraCapturer(boolean useFrontCamera) {
    String deviceName = useFrontCamera ? VideoCapturerAndroid.getNameOfFrontFacingDevice() : VideoCapturerAndroid.getNameOfBackFacingDevice();
    return VideoCapturerAndroid.create(deviceName);
}

If you're using a different version of LibJingle or for any reason this doesn't work let me know and I'll be happy to help!

Cheers,


问:
Invert of a shift operation - determine shift count used to generate value
I have code that generates a value from an initial value of 1 by using a left shift. At a different point in the code, I know the value generated and need to calculate the shift count used to generate the value.

In other words I need to determine the shift count used to generate the result of a shift operation by performing an operation on the value generated.

Is it possible to invert a shift operation of a base two variable without using a dedicated function? I am looking for the value of a shift count variable y when the shifted value, x, and result of the shift operation, z, are known.

Example:

```<code>x << y = z
1 << 6 = 64

z = 64 and x is 1 but what is y???  // how to calculate y, the shift count?
</code>```

There are many solutions including log(64)/log(2), but I would have to use math.h. I am looking for some sort of bitwise operation that is fast and doesn't require a function.

EDIT: Thank you for your answers! My question is answered, there is no way to this with a simple operation, my compiler does not have CTZ. BR

答:
Alternative function ideas can use a switch statement as in:

```<code>int trailing_zero_bits(uint64_t x) {
    int iRetVal = 0;

    switch (x & 0x7f) {
    case 2:
        iRetVal = 1;
        break;
    case 4:
        iRetVal = 2;
        break;
    case 8:
        iRetVal = 3;
        break;
    case 16:
        iRetVal = 4;
        break;
    case 32:
        iRetVal = 5;
        break;
    case 64:
        iRetVal = 6;
        break;
    default:
        iRetVal = 0;
    }

    return iRetVal;
}
</code>```

And this could be condensed down using Duff's Device to:

```<code>int trailing_zero_bits(uint64_t x) {
    int iRetVal = 0;

    switch (x & 0x3f) {
        case 64:  iRetVal++;
        case 32:  iRetVal++;
        case 16:  iRetVal++;
        case 8:  iRetVal++;
        case 4:  iRetVal++;
        case 2:  iRetVal++;
            break;
        default:
            break;
    }

    return iRetVal;
}
</code>```

Or you could take a lookup table approach as in:

```<code>int trailing_zero_bits(uint64_t x) {
    unsigned char  x1[9] = { 0, 0, 1, 0, 2, 0, 0, 0, 3 };
    unsigned char  x2[9] = { 0, 4, 5, 0, 6, 0, 0, 0, 0 };

    return x1[x & 0xf] | x2[(x & 0x70) >> 4];
}
</code>```

Or alternatively

```<code>int trailing_zero_bits(uint64_t x) {
    unsigned short x1[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40 };
    unsigned short xVal = (unsigned short)(x & 0x7f);
    int  i = 0;

    if (xVal) for (i = 0; (x1[i] & xVal) == 0; i++);

    return i;
}
</code>```

Or eliminate the table with:

```<code>int trailing_zero_bits(uint64_t x) {
    unsigned short x1 = 0x01;
    unsigned short xVal = (unsigned short)(x & 0x7f);
    int  i = 0;

    if (xVal) for (i = 0; (x1 & xVal) == 0; i++, (x1 <<= 1));

    return i;
}
</code>```

Or back to using a table but with pointers to eliminate indexing:

```<code>int trailing_zero_bits(uint64_t x) {
    unsigned short x1[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40};
    unsigned short *x2 = x1;
    unsigned short xVal = (unsigned short)(x & 0x7f);

    if (xVal) for ( ; (*x2 & xVal) == 0; x2++);

    return (x2 - x1);
}
</code>```

Body:
I have code that generates a value from an initial value of 1 by using a left shift. At a different point in the code, I know the value generated and need to calculate the shift count used to generate the value.

In other words I need to determine the shift count used to generate the result of a shift operation by performing an operation on the value generated.

Is it possible to invert a shift operation of a base two variable without using a dedicated function? I am looking for the value of a shift count variable y when the shifted value, x, and result of the shift operation, z, are known.

Example:

x << y = z
1 << 6 = 64

z = 64 and x is 1 but what is y???  // how to calculate y, the shift count?

There are many solutions including log(64)/log(2), but I would have to use math.h. I am looking for some sort of bitwise operation that is fast and doesn't require a function.

EDIT: Thank you for your answers! My question is answered, there is no way to this with a simple operation, my compiler does not have CTZ. BR

Body:
Alternative function ideas can use a switch statement as in:

int trailing_zero_bits(uint64_t x) {
    int iRetVal = 0;

    switch (x & 0x7f) {
    case 2:
        iRetVal = 1;
        break;
    case 4:
        iRetVal = 2;
        break;
    case 8:
        iRetVal = 3;
        break;
    case 16:
        iRetVal = 4;
        break;
    case 32:
        iRetVal = 5;
        break;
    case 64:
        iRetVal = 6;
        break;
    default:
        iRetVal = 0;
    }

    return iRetVal;
}

And this could be condensed down using Duff's Device to:

int trailing_zero_bits(uint64_t x) {
    int iRetVal = 0;

    switch (x & 0x3f) {
        case 64:  iRetVal++;
        case 32:  iRetVal++;
        case 16:  iRetVal++;
        case 8:  iRetVal++;
        case 4:  iRetVal++;
        case 2:  iRetVal++;
            break;
        default:
            break;
    }

    return iRetVal;
}

Or you could take a lookup table approach as in:

int trailing_zero_bits(uint64_t x) {
    unsigned char  x1[9] = { 0, 0, 1, 0, 2, 0, 0, 0, 3 };
    unsigned char  x2[9] = { 0, 4, 5, 0, 6, 0, 0, 0, 0 };

    return x1[x & 0xf] | x2[(x & 0x70) >> 4];
}

Or alternatively

int trailing_zero_bits(uint64_t x) {
    unsigned short x1[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40 };
    unsigned short xVal = (unsigned short)(x & 0x7f);
    int  i = 0;

    if (xVal) for (i = 0; (x1[i] & xVal) == 0; i++);

    return i;
}

Or eliminate the table with:

int trailing_zero_bits(uint64_t x) {
    unsigned short x1 = 0x01;
    unsigned short xVal = (unsigned short)(x & 0x7f);
    int  i = 0;

    if (xVal) for (i = 0; (x1 & xVal) == 0; i++, (x1 <<= 1));

    return i;
}

Or back to using a table but with pointers to eliminate indexing:

int trailing_zero_bits(uint64_t x) {
    unsigned short x1[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40};
    unsigned short *x2 = x1;
    unsigned short xVal = (unsigned short)(x & 0x7f);

    if (xVal) for ( ; (*x2 & xVal) == 0; x2++);

    return (x2 - x1);
}


问:
Change O365 script to change job title with user prompts for input?
I have made a script to change an office 365 user's job title.However I want it so there are two user prompt boxes asking for the email address entry and then new job title entry, rather than me changing the users email and title every time.</p>

```<code>$user = Read-Host -Prompt 'Input the users email address'
$job = Read-Host -Prompt 'Enter the new Job Title'
Set-MsolUser -UserPrincipalName $user  -Title $job
</code>```

答:
As always when using user input, either from a Read-Host command or by using an inputbox, you should NEVER rely on it to be correct.

Always put in some kind of check on user input like:

```<code>while ($true) {
    Clear-Host
    $upn = Read-Host -Prompt 'Input the users UserPrincipalName. Type Q to quit.'
    if ($upn -eq 'Q') {break}

    # test if we can find a user with the entered UserPrincipalName
    $user = Get-MsolUser -UserPrincipalName $upn
    if ($user) {
        $job = Read-Host -Prompt 'Enter the new Job Title'
        Write-Host "Updating title for user $($user.DisplayName) from '$($user.Title)' to '$job'"
        $user | Set-MsolUser -Title $job
    }
    else {
        Write-Warning "User with UserPrincipleName $upn not found. Please try again."
    }
    Start-Sleep -Seconds 3
}
</code>```

Body:
I have made a script to change an office 365 user's job title.However I want it so there are two user prompt boxes asking for the email address entry and then new job title entry, rather than me changing the users email and title every time.

$user = Read-Host -Prompt 'Input the users email address'
$job = Read-Host -Prompt 'Enter the new Job Title'
Set-MsolUser -UserPrincipalName $user  -Title $job

Body:
As always when using user input, either from a Read-Host command or by using an inputbox, you should NEVER rely on it to be correct.

Always put in some kind of check on user input like:

while ($true) {
    Clear-Host
    $upn = Read-Host -Prompt 'Input the users UserPrincipalName. Type Q to quit.'
    if ($upn -eq 'Q') {break}

    # test if we can find a user with the entered UserPrincipalName
    $user = Get-MsolUser -UserPrincipalName $upn
    if ($user) {
        $job = Read-Host -Prompt 'Enter the new Job Title'
        Write-Host "Updating title for user $($user.DisplayName) from '$($user.Title)' to '$job'"
        $user | Set-MsolUser -Title $job
    }
    else {
        Write-Warning "User with UserPrincipleName $upn not found. Please try again."
    }
    Start-Sleep -Seconds 3
}


问:
VOC error "ModuleNotFoundError: No module named 'numpy"
"ModuleNotFoundError: No module named 'numpy"  error occurred  when iam trying to generate .class file for my .py code using VOC .........please help...thnx in advance

(VoCProject) C:\Users\User\Desktop\virtualEnvs\VoCProject\actualProject>python RGBtoGray.py
Traceback (most recent call last):
  File "sample.py", line 1, in
    import numpy as np
ModuleNotFoundError: No module named 'numpy'

答:
Try installing NumPy with pip:

```<code>pip install numpy
</code>```

Then you should be able to import without errors.

Body:
Try installing NumPy with pip:

pip install numpy

Then you should be able to import without errors.


问:
Type Checking in Mongoose Maps
If I have the following schema:

```<code>const userSchema = new mongoose.Schema({
  modules: {
    type: Map,
    of: {
      name: {
        type: String,
        required: true
      }
    }
  }
})
</code>```

Theoretically, mongoose should validate the type of each UserModule when I create a new document, ensuring the required name property is present.

However, if I create a user with a module without the name property:

```<code>await User.create({ modules: { example: {} } })
</code>```

No error is thrown. Normally, mongoose is able to correctly validate for required types.

Workarounds I can think of include either hardcoding the keys for each module (and not use a map) or including a validator on the modules map to check all modules have the required keys are present, none of which are ideal.

Is there a better way to check the type of map values?

答:
You are providing a value ... this is a valid Map definition:

```<code>await User.create({
  modules: {
    example: {}   // <-- this is a valid. Key is `example` value is {}
  }
})
</code>```

As far as Map not having validation. Map does validate the values only since the keys are always strings. Consider this schema:

```<code>var AuthorSchema = new Schema({
  books: {
    type: Map,
    of: { type: Number },
    default: { "first book": 100 },  // <-- set default values
    required: true                   // <-- set required
  }
})

// after mongoose.model('Author', AuthorSchema) etc ....

var author1 = new Author({ books: { 'book one': 200 } })
author1.save() // <-- On save this works

var author2 = new Author({ books: { 'book one': "foo" } })
author2.save() // <-- This fails validation with "Cast to number failed ..."

var author1 = new Author()
author1.save() // <-- default would set values and that would pass the `required` validation
</code>```

If you want to require the map make sure you do not have values in the default etc.

You can also review the map tests @ github for more insight

And in those tests you can also see how to do a complex nested map:

```<code>var AuthorSchema = new Schema({
  pages: {
    type: Map,
    of: new mongoose.Schema({   // <-- just nest another schema
      foo: { type: Number },  // <-- set your type, default, required etc
      bar: { type: String, required: true } // <-- required!
    }, { _id: false }),
    default: {
      'baz': {
        foo: 100, bar: 'moo'  // <-- set your defaults
      }
    }
  }
})
</code>```

This would save as expected this:

```<code>{
    "_id" : ObjectId("5cf1cf4b7f67711963e2406d"),
    "pages" : {
        "baz" : {
            "foo" : 100,
            "bar" : "moo"
        }
    }
}
</code>```

Trying to save this would fail since bar is required:

```<code>var author = new Author({
  "pages" : {
    "baz" : { "foo" : 1 }  // <-- no bar!
  }
});
</code>```

Title: Type Checking in Mongoose Maps

Body:
If I have the following schema:

const userSchema = new mongoose.Schema({
  modules: {
    type: Map,
    of: {
      name: {
        type: String,
        required: true
      }
    }
  }
})

Theoretically, mongoose should validate the type of each UserModule when I create a new document, ensuring the required name property is present.

However, if I create a user with a module without the name property:

await User.create({ modules: { example: {} } })

No error is thrown. Normally, mongoose is able to correctly validate for required types.

Workarounds I can think of include either hardcoding the keys for each module (and not use a map) or including a validator on the modules map to check all modules have the required keys are present, none of which are ideal.

Is there a better way to check the type of map values?

Body:
You are providing a value ... this is a valid Map definition:

await User.create({
  modules: {
    example: {}   // <-- this is a valid. Key is `example` value is {}
  }
})

As far as Map not having validation. Map does validate the values only since the keys are always strings. Consider this schema:

var AuthorSchema = new Schema({
  books: {
    type: Map,
    of: { type: Number },
    default: { "first book": 100 },  // <-- set default values
    required: true                   // <-- set required
  }
})

// after mongoose.model('Author', AuthorSchema) etc ....

var author1 = new Author({ books: { 'book one': 200 } })
author1.save() // <-- On save this works

var author2 = new Author({ books: { 'book one': "foo" } })
author2.save() // <-- This fails validation with "Cast to number failed ..."

var author1 = new Author()
author1.save() // <-- default would set values and that would pass the `required` validation

If you want to require the map make sure you do not have values in the default etc.

You can also review the map tests @ github for more insight

And in those tests you can also see how to do a complex nested map:

var AuthorSchema = new Schema({
  pages: {
    type: Map,
    of: new mongoose.Schema({   // <-- just nest another schema
      foo: { type: Number },  // <-- set your type, default, required etc
      bar: { type: String, required: true } // <-- required!
    }, { _id: false }),
    default: {
      'baz': {
        foo: 100, bar: 'moo'  // <-- set your defaults
      }
    }
  }
})

This would save as expected this:

{
    "_id" : ObjectId("5cf1cf4b7f67711963e2406d"),
    "pages" : {
        "baz" : {
            "foo" : 100,
            "bar" : "moo"
        }
    }
}

Trying to save this would fail since bar is required:

var author = new Author({
  "pages" : {
    "baz" : { "foo" : 1 }  // <-- no bar!
  }
});


问:
Cannot import javax.servlet after adding dependency in gradle
I cannot import javax.servlet even though I have already added the package in my gradle dependencies.

Here's my gradle dependency:

```<code>dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api',
    ...
    ...
}
</code>```

I've also tried:

```<code>dependencies {
    compile "javax.servlet:servlet-api:3.0.1"
}
</code>```

But when I import it using:

```<code>import javax.servlet.http.HttpServletResponse;
</code>```

I get the error: Cannot resolve symbol "HttpServletResponse".

答:
It should be like this :

```<code>dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
    ...
    ...
}
</code>```

as i think the comma at the end is causing issues because you dont need commas to separate dependencies so remove it also i suggest you specifying version

Body:
I cannot import javax.servlet even though I have already added the package in my gradle dependencies.

Here's my gradle dependency:

dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api',
    ...
    ...
}

I've also tried:

dependencies {
    compile "javax.servlet:servlet-api:3.0.1"
}

But when I import it using:

import javax.servlet.http.HttpServletResponse;

I get the error: Cannot resolve symbol "HttpServletResponse".

Body:
It should be like this :

dependencies {
    providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.0.1'
    ...
    ...
}

as i think the comma at the end is causing issues because you dont need commas to separate dependencies so remove it also i suggest you specifying version


问:
C pointer problem!
Why does the following C code does not ouput 10

```<code>#include<stdio.h>
#include<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}

void get_length(char *s){
    int count;
for(count = 0 ; *s != '\0' ; s++)
    count++;
printf("count = %d\n",count);
}
</code>```

The input is I am Rohit

The output is

count = 432

Can anyone please explain that.

答:
I think that scanf is reading your string in and setting the last char to '\0', but you are searching for '\n', which I don't think is implicit in the scanf implementation.

That is, check for '\0' instead of '\n'.

Title: C pointer problem!

Body:
Why does the following C code does not ouput 10

#include<stdio.h>
#include<stdlib.h>
void get_length(char s[]);
int main( )
{
char buff[128];
printf("\nEnter buffer data: ");
scanf("%s",buff);
get_length(buff);
}

void get_length(char *s){
    int count;
for(count = 0 ; *s != '\0' ; s++)
    count++;
printf("count = %d\n",count);
}

The input is I am Rohit

The output is

count = 432

Can anyone please explain that.


问:
Unable to pass 2-Dimensional array while using recursion in c++
I saw an answer in stackoverflow regarding how to pass a 2d-array in a function there are 3 or more methods given when I tried one of them it worked just fine. But when I'm trying to use that method in backtracking it is giving me an error.

I tried declaring it globally but I want to learn how to use it this way

```<code>#include<bits/stdc++.h>
using namespace std;

int callAgain(int,int);
int call(int,int);

int call(int arr[][5],int n)
{
  if(n==1)
    return 0;

  cout<<"anything";

  callAgain(arr,n-1);     //getting error here.

  return 0;
 }
int callAgain(int arr[][5],int n)
{
  call(arr,n);
  return 0;
 }
int main(){

int arr[5][5];
memset(arr,0,sizeof(arr));
call(arr,5);

return 0;
}
</code>```

error: invalid conversion from int(*)[5] to int [-fpremissive]

答:
Your forward declarations for call and callAgain promise that the first argument will be an int, but then when you implement them you say the first argument is a 2D array.

Compilers don't appreciate being lied to...

Body:
I saw an answer in stackoverflow regarding how to pass a 2d-array in a function there are 3 or more methods given when I tried one of them it worked just fine. But when I'm trying to use that method in backtracking it is giving me an error.

I tried declaring it globally but I want to learn how to use it this way

#include<bits/stdc++.h>
using namespace std;

int callAgain(int,int);
int call(int,int);

int call(int arr[][5],int n)
{
  if(n==1)
    return 0;

  cout<<"anything";

  callAgain(arr,n-1);     //getting error here.

  return 0;
 }
int callAgain(int arr[][5],int n)
{
  call(arr,n);
  return 0;
 }
int main(){

int arr[5][5];
memset(arr,0,sizeof(arr));
call(arr,5);

return 0;
}

error: invalid conversion from int(*)[5] to int [-fpremissive]


问:
Is there a short-hand for nth root of x in Python?
In maths, if I wish to calculate 3 to the power of 2 then no symbol is required, but I write the 2 small: 3². In Python this operation seems to be represented by the ** syntax.

```<code>>>> 3**2
9
</code>```

If I want to go the other direction and calculate the 2nd root of 9 then in maths I need to use a symbol: 2√9 = 3

Is there a short-hand symbol in Python, similar to ** that achieves this i.e. 2<symbol>9? Or do I need to use the math module?

答:
You may also use some logarithms:

Nth root of x:

```<code>exp(log(x)/n)
</code>```

For example:

```<code>>>> from math import exp, log
>>> x = 8
>>> n = 3
>>> exp(log(x)/n)
2.0
</code>```

Body:
In maths, if I wish to calculate 3 to the power of 2 then no symbol is required, but I write the 2 small: 3². In Python this operation seems to be represented by the ** syntax.

>>> 3**2
9

If I want to go the other direction and calculate the 2nd root of 9 then in maths I need to use a symbol: 2√9 = 3

Is there a short-hand symbol in Python, similar to ** that achieves this i.e. 2<symbol>9? Or do I need to use the math module?

Body:
You may also use some logarithms:

Nth root of x:

exp(log(x)/n)

For example:

>>> from math import exp, log
>>> x = 8
>>> n = 3
>>> exp(log(x)/n)
2.0


问:
conditional calculation based on values from another column
I have 2 tables

Table 1

Table 2

They are connected by pkg and Item. This results in the following

As you can see from the image "Item" has a mix of "BULK" & "PKG" values.

I want to create a new column that uses the cross reference to bring in new values.

The new table I want would look like this

```<code> **ITEM**  **Value**   **BULK**  **PKG**   **NEW COLUMN**
  135          2                                 1
  136          4                                 3
  35           1          135       35           1
  36           3          136       36           3
</code>```

The top 2 items on the left are the associated "BULK" values.  I want to bring in the PKG value that appears.

答:
You can use the same ISBLANK conditional expression as in your other question, but use a lookup instead of just Value.

```<code>New Column =
IF(
    ISBLANK( Table1[Bulk] ),
    LOOKUPVALUE( Table1[Value], Table1[BULK], Table1[ITEM] )
    Table1[Value]
)
</code>```

Note that this will throw an error if you have multiple BULK values corresponding to a single ITEM.

Body:
I have 2 tables

Table 1

Table 2

They are connected by pkg and Item. This results in the following

As you can see from the image "Item" has a mix of "BULK" & "PKG" values.

I want to create a new column that uses the cross reference to bring in new values.

The new table I want would look like this

 **ITEM**  **Value**   **BULK**  **PKG**   **NEW COLUMN**
  135          2                                 1
  136          4                                 3
  35           1          135       35           1
  36           3          136       36           3

The top 2 items on the left are the associated "BULK" values.  I want to bring in the PKG value that appears.

Body:
You can use the same ISBLANK conditional expression as in your other question, but use a lookup instead of just Value.

New Column =
IF(
    ISBLANK( Table1[Bulk] ),
    LOOKUPVALUE( Table1[Value], Table1[BULK], Table1[ITEM] )
    Table1[Value]
)

Note that this will throw an error if you have multiple BULK values corresponding to a single ITEM.


问:
CSS trouble getting elements to center both vertically and horizontally using flex

Sorry for the beginner question but i have been stuck on this for a long time. I have am trying to use flex to center align the div.Homepage elements but i cant seem to get anything but the button to align horizontally.  I also cant get the text TEST to center.  My CSS is below:

```<code>body {
    font-family: 'Recoleta';
    color: #FFF;
    background: #111;

}

html, body {
    height: 100%;

}

.Homepage{
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

.logo-social-image{
    max-width: 20%;
}
</code>```

My React HTML is below

```<code>   return(
            <div className="Homepage">
                <div className="Name-social">
                    {view}
                </div>
                <div className="Pro-button">
                    <OutlinedButtons  isLoading={this.state.isLoading} isLoaded={this.isLoaded} />
                </div>
            </div>
        )
</code>```

答:
Since you did not provide your HTML, I made an example of how to do it https://jsfiddle.net/L29h8oxs/

Add

```<code>  display: flex;
  align-items: center;
  justify-content: center;
</code>```

To the parent div (I think it will be your .Homepage) and it should center the child for you.

Body:
Sorry for the beginner question but i have been stuck on this for a long time. I have am trying to use flex to center align the div.Homepage elements but i cant seem to get anything but the button to align horizontally.  I also cant get the text TEST to center.  My CSS is below:

body {
    font-family: 'Recoleta';
    color: #FFF;
    background: #111;

}

html, body {
    height: 100%;

}

.Homepage{
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
}

.logo-social-image{
    max-width: 20%;
}

My React HTML is below

   return(

                    {view}

                    <OutlinedButtons  isLoading={this.state.isLoading} isLoaded={this.isLoaded} />

        )

Body:
Since you did not provide your HTML, I made an example of how to do it https://jsfiddle.net/L29h8oxs/

Add

  display: flex;
  align-items: center;
  justify-content: center;

To the parent div (I think it will be your .Homepage) and it should center the child for you.


Title: How to delete the top values before there is a change in the value?

Body:
I have a dictionary that has about 5 different dataframes in it and each dataframe has the same columns.

Sample of one dataframe:

ContextID   BacksGas_Flow_sccm  StepID  Time_Elapsed    lof
7308924 1.3671875   25  138.33800000000002              -1
7291161 1.3671875   25  138.767                         -1
7291162 1.3671875   25  138.961                         -1
7311376 1.3671875   25  118.28800000000001              -1
7311377 1.3671875   25  118.28800000000001              -1
7308925 1.3671875   25  138.33800000000002              -1
7298660 1.3671875   25  121.25900000000001              -1
7298661 1.3671875   25  121.09500000000001              -1
7313179 1.46484375  25  135.76500000000001               1
7313180 1.46484375  25  135.995                          1
7315853 1.5625  25  139.357                              1
7315654 1.5625  25  137.93                               1
7315653 1.5625  25  137.716                              1
7315321 1.5625  25  137.721                              -1
7315320 1.5625  25  137.57600000000002                   -1
7315281 1.5625  25  137.738                              -1
7314808 1.5625  25  139.19500000000002                   -1
7314809 1.5625  25  139.19500000000002                   -1

What I would like is to check from top the lof column and the moment the values change from -1 to +1, the -1s must be deleted. Not all the -1s in the lof column must be deleted, but just at the top.

The desired result based on above dataframe must look like:

  ContextID BacksGas_Flow_sccm  StepID  Time_Elapsed    lof
    7313179 1.46484375  25  135.76500000000001               1
    7313180 1.46484375  25  135.995                          1
    7315853 1.5625  25  139.357                              1
    7315654 1.5625  25  137.93                               1
    7315653 1.5625  25  137.716                              1
    7315321 1.5625  25  137.721                              -1
    7315320 1.5625  25  137.57600000000002                   -1
    7315281 1.5625  25  137.738                              -1
    7314808 1.5625  25  139.19500000000002                   -1
    7314809 1.5625  25  139.19500000000002                   -1

Notice that only the -1s at the top are deleted and the -1s at the bottom are not.

The same thing must be applied to all the dataframes in the dictionary. I would like to know how can this be done.

Body:
Try cumsum() on lof==1:

mask = df.lof.eq(1).cumsum()
df[mask.gt(0)]

Output:

      ContextID    BacksGas_Flow_sccm    StepID    Time_Elapsed    lof
--  -----------  --------------------  --------  --------------  -----
 8  7.31318e+06               1.46484        25         135.765      1
 9  7.31318e+06               1.46484        25         135.995      1
10  7.31585e+06               1.5625         25         139.357      1
11  7.31565e+06               1.5625         25         137.93       1
12  7.31565e+06               1.5625         25         137.716      1
13  7.31532e+06               1.5625         25         137.721     -1
14  7.31532e+06               1.5625         25         137.576     -1
15  7.31528e+06               1.5625         25         137.738     -1
16  7.31481e+06               1.5625         25         139.195     -1
17  7.31481e+06               1.5625         25         139.195     -1


问:
Java JUNIT red bar but won't tell me error?
I don't know whats wrong with my test/project. I don't have a compilation errors but when I test it, its just the red bar and it won't tell me whats wrong. Any suggestions? My code and question are below. Thanks in advance

If the calculatePrice method of checkout is called with a basket with one book in, it should return the price of that one book.

```<code>@Test
    public void test_CalculatePrice_ReturnSumOfThePriceOfTwoBooks_BasketMustHaveTwoBooks(){
        //Arrange
        Basket basket1 = new Basket();
        Book book1 = new Book();
        Checkout checkout = new Checkout();
        basket1.addBook(book1);
        basket1.addBook(book1);
        double delta = 0.0;
        double expectedPrice = checkout.calculatePrice();

        //Act
        double actualPrice = checkout.calculatePrice();

        //Assert
        assertEquals(expectedPrice,actualPrice,delta);
</code>```

Checkout class

```<code>public class Checkout {

    public double calculatePrice(Book book1) {
        return calculatePrice();
    }
</code>```

答:
What is your calculatePrice() method doing?
In your Checkout class your method

```<code> public double calculatePrice(Book book1) {
        return calculatePrice();
 }
</code>```

Is not even using the book1 parameter to calculate the price, I suppose what you mean is

```<code>public double calculatePrice(Book book1) {
    return book1.calculatePrice();
}
</code>```

Body:
I don't know whats wrong with my test/project. I don't have a compilation errors but when I test it, its just the red bar and it won't tell me whats wrong. Any suggestions? My code and question are below. Thanks in advance

If the calculatePrice method of checkout is called with a basket with one book in, it should return the price of that one book.

@Test
    public void test_CalculatePrice_ReturnSumOfThePriceOfTwoBooks_BasketMustHaveTwoBooks(){
        //Arrange
        Basket basket1 = new Basket();
        Book book1 = new Book();
        Checkout checkout = new Checkout();
        basket1.addBook(book1);
        basket1.addBook(book1);
        double delta = 0.0;
        double expectedPrice = checkout.calculatePrice();

        //Act
        double actualPrice = checkout.calculatePrice();

        //Assert
        assertEquals(expectedPrice,actualPrice,delta);

Checkout class

public class Checkout {

    public double calculatePrice(Book book1) {
        return calculatePrice();
    }

Body:
What is your calculatePrice() method doing?
In your Checkout class your method

 public double calculatePrice(Book book1) {
        return calculatePrice();
 }

Is not even using the book1 parameter to calculate the price, I suppose what you mean is

public double calculatePrice(Book book1) {
    return book1.calculatePrice();
}


问:
Formula help for multiple conditions in excel conditional fomatting
I have a full case of Excel brain freeze trying to conditionally format cells. </p>

<p>Cell A1 is a number – positive or negative
A2 is the cell I want to conditionally format. Cells that don’t meet any of the following conditions remain white. </p>

```<code>If A1 is positive and A2> (1.2 * A1)  formats Green
If A1 is positive and A2< (0.85 * A1)  formats Red
If A1 is negative and A2>(.85 *A1) formats Green
If A1 is negative and A2<(1.25 *A1) formats red
</code>```

Body:
I have a full case of Excel brain freeze trying to conditionally format cells.

Cell A1 is a number – positive or negative
A2 is the cell I want to conditionally format. Cells that don’t meet any of the following conditions remain white.

If A1 is positive and A2> (1.2 * A1)  formats Green
If A1 is positive and A2< (0.85 * A1)  formats Red
If A1 is negative and A2>(.85 *A1) formats Green
If A1 is negative and A2<(1.25 *A1) formats red

Body:
Green:

=A2>A1*IF(A1>=0,1.2,0.85)

Red:

=A2<A1*IF(A1>=0,0.85,1.25)


问:
Excel shows incorrect polynomial trendline function
I'm trying to create a polynomial function that fits my data in column H.  Column I are the x values, and column J is the function that the charts polynomial trendline shows. So why is my result (see orange line) not equal to the trendline function? What's going on here?

答:
This is due to the way Excel calculates the coefficients for an nth order Polynomial Trendline and the precision used in coming up with the coefficients. The discrepancy is due to the rounding precision of the coefficients and only comes about when one tries to calculate future values manually using the equation.

Due to the rounding precision, the coefficients cannot properly be used to manually calculate y values. However, the Polynomial Trendline shown on the chart is precise and you can make a future prediction just by looking at the chart.

Chart trendline formula is inaccurate in Excel


问:
Java 8 Base64 JWT token into JSON
So, I have done some research on this on the Net and here on StackOverflow, and I have tried many, multiple suggestions that I have found.  The problem is that I am logging into one of our Oauth2 services which is working well.   I get an Oath2 JWT token.   I know this is Base64 encoded, and I can drop the token into jwt.io and www.base64decode.org and both of these sites parse the token correctly.

I am using Java 8 Base64 tools, and the code looks as follows:

```<code>public String getTokenProperty(String token, String propertyName)
{
    byte[] bytes = Base64.getUrlDecoder().decode(token);
    String decodedString = new String(bytes, StandardCharsets.UTF_8);
    System.out.println("Decoded: " + decodedString);
    return (new JSONObject(decodedString)).getString(propertyName);
}
</code>```

The error occurs on the decoder line as follows:

```<code>java.lang.IllegalArgumentException: Illegal base64 character 2e
</code>```

I tried this with a token from my Oauth2 Service, I got a token from Syncope, and I got a token from Auth0 ... all return with JWT Base64 encoded tokens.
With ALL these tokens from these different servers, I get the same error.

I would like to use the Java 8 Base64 which is standard, but I am thinking that I may need to use an external third-party Base64 decoder.

Any help would be great.   Thanks!

The token is as follows:

```<code>eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qSTRRVFEwT1VRNU9VSXlSVEV6TlRBd05UVXpSVVExTlVOR05FVkVORGRDTlRnM016VXdRZyJ9.eyJodHRwczovL2JpdG9vbXRyYWRlci5uZXQvYXV0aG9yaXphdGlvbiI6eyJncm91cHMiOlsiQ29uc3VtZXJzIl0sInJvbGVzIjpbIlVzZXIiXX0sImlzcyI6Imh0dHBzOi8vYml0em9vbS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NWNhNTE5NzZjYzMzZjUxMTBhYWNkYmM0IiwiYXVkIjpbImh0dHBzOi8vYml0em9vbS5hdXRoMC5jb20vYXBpL3YyLyIsImh0dHBzOi8vYml0em9vbS5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTU5MzIzNDI1LCJleHAiOjE1NTk0MDk4MjUsImF6cCI6IlliRGFSelRVQkFtZEFrSExqdjZ0bEI3U05xSTF1RlNtIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCBhZGRyZXNzIHBob25lIHJlYWQ6Y3VycmVudF91c2VyIHVwZGF0ZTpjdXJyZW50X3VzZXJfbWV0YWRhdGEgZGVsZXRlOmN1cnJlbnRfdXNlcl9tZXRhZGF0YSBjcmVhdGU6Y3VycmVudF91c2VyX21ldGFkYXRhIGNyZWF0ZTpjdXJyZW50X3VzZXJfZGV2aWNlX2NyZWRlbnRpYWxzIGRlbGV0ZTpjdXJyZW50X3VzZXJfZGV2aWNlX2NyZWRlbnRpYWxzIHVwZGF0ZTpjdXJyZW50X3VzZXJfaWRlbnRpdGllcyIsImd0eSI6InBhc3N3b3JkIn0.St7097L1ZAlBWcAPrie-8CGV2F3Fr8uNYpSDVKSPVPF4zBZrmm62_UAj7Ssux8AjUy0LhjiF3kLpNph2L7yrpUREw6TyGJwQasfdVtM5VzRYUcy-fOGyRSqPQorbzxJQZzs2pyDJm-2hMQ0McJ37ubKIWrHFD5McMedN6THK7g5TExX47XCRPcOuCEWm3bf3zdWF2LEGhCw_c-lcZDwlb4ePkO721XjSWtrXEBvxc8scFNaHDt7VOnrSze4XK_LO8eE8bHRq6qUrWf1csYucK--aHazBsvfdl-6QDRk-tOBM-LdXJMT7H8Ih6trxVmZofQjr2dQ4j_3DTVoU3eLdog
</code>```

UPDATE:

I switched from java,util.Base64 to org.apache.commons.codec.binary.Base64
and this seems to work somewhat, I don't get an error now.

```<code>String decodedString = new String(bytes, StandardCharsets.UTF_8);
</code>```

gives me back a string of the header, payload, and signature data.  So, when I do:

```<code>JSONObject jsonObject = new JSONObject(decodedString);
    System.out.println("getTokenProperty: jsonObject = " + jsonObject.toString());
</code>```

I am only getting back the header data, and what I really need is the payload.

For the record ... the code I inherited from a "proof of concept" project was:

```<code>public static String getTokenProperty(String token, String propertyName)
{
    return (new JSONObject(new String(Base64.getDecoder().decode(token)))).getString(propertyName);
}
</code>```

and there was no unit testing at all.  So, when I went to unit test it, of course it completely broke.   So, now I have a better understanding of how to parse this token, and I will remember this lesson for a long time.

Thanks very much!

答:
The reason it doesn't parse is because you are trying to Base64URLDecode the ENTIRE token.. But you have to decode PARTS of the token which is separated by a DOT "." character (0x2e in hex, 46 in dec, &#46 in html -- ASCII/UTF8) ..

Example:

```<code>public static void decodeTokenParts(String token)
{
    String[] parts = token.split("\\.", 0);

    for (String part : parts) {
        byte[] bytes = Base64.getUrlDecoder().decode(part);
        String decodedString = new String(bytes, StandardCharsets.UTF_8);

        System.out.println("Decoded: " + decodedString);
    }
}
</code>```

This is because a JWT token is made up of parts:

Base64URLEncode({HeaderJSON}) + "." + Base64URLEncode({PayloadJSON}) + "." + Signature for example..

So to decode it.. you need to split it by "." and decode each part. Note: The signature will usually be binary that is encoded as base64 so once you decode it, don't try printing it.. it'll print bytes. You'd need to verify the signature.

For example, if you go to: https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

You will see how each "part" is encoded. It is colour coded.

Title: Java 8 Base64 JWT token into JSON

Body:
So, I have done some research on this on the Net and here on StackOverflow, and I have tried many, multiple suggestions that I have found.  The problem is that I am logging into one of our Oauth2 services which is working well.   I get an Oath2 JWT token.   I know this is Base64 encoded, and I can drop the token into jwt.io and www.base64decode.org and both of these sites parse the token correctly.

I am using Java 8 Base64 tools, and the code looks as follows:

public String getTokenProperty(String token, String propertyName)
{
    byte[] bytes = Base64.getUrlDecoder().decode(token);
    String decodedString = new String(bytes, StandardCharsets.UTF_8);
    System.out.println("Decoded: " + decodedString);
    return (new JSONObject(decodedString)).getString(propertyName);
}

The error occurs on the decoder line as follows:

java.lang.IllegalArgumentException: Illegal base64 character 2e

I tried this with a token from my Oauth2 Service, I got a token from Syncope, and I got a token from Auth0 ... all return with JWT Base64 encoded tokens.
With ALL these tokens from these different servers, I get the same error.

I would like to use the Java 8 Base64 which is standard, but I am thinking that I may need to use an external third-party Base64 decoder.

Any help would be great.   Thanks!

The token is as follows:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik1qSTRRVFEwT1VRNU9VSXlSVEV6TlRBd05UVXpSVVExTlVOR05FVkVORGRDTlRnM016VXdRZyJ9.eyJodHRwczovL2JpdG9vbXRyYWRlci5uZXQvYXV0aG9yaXphdGlvbiI6eyJncm91cHMiOlsiQ29uc3VtZXJzIl0sInJvbGVzIjpbIlVzZXIiXX0sImlzcyI6Imh0dHBzOi8vYml0em9vbS5hdXRoMC5jb20vIiwic3ViIjoiYXV0aDB8NWNhNTE5NzZjYzMzZjUxMTBhYWNkYmM0IiwiYXVkIjpbImh0dHBzOi8vYml0em9vbS5hdXRoMC5jb20vYXBpL3YyLyIsImh0dHBzOi8vYml0em9vbS5hdXRoMC5jb20vdXNlcmluZm8iXSwiaWF0IjoxNTU5MzIzNDI1LCJleHAiOjE1NTk0MDk4MjUsImF6cCI6IlliRGFSelRVQkFtZEFrSExqdjZ0bEI3U05xSTF1RlNtIiwic2NvcGUiOiJvcGVuaWQgcHJvZmlsZSBlbWFpbCBhZGRyZXNzIHBob25lIHJlYWQ6Y3VycmVudF91c2VyIHVwZGF0ZTpjdXJyZW50X3VzZXJfbWV0YWRhdGEgZGVsZXRlOmN1cnJlbnRfdXNlcl9tZXRhZGF0YSBjcmVhdGU6Y3VycmVudF91c2VyX21ldGFkYXRhIGNyZWF0ZTpjdXJyZW50X3VzZXJfZGV2aWNlX2NyZWRlbnRpYWxzIGRlbGV0ZTpjdXJyZW50X3VzZXJfZGV2aWNlX2NyZWRlbnRpYWxzIHVwZGF0ZTpjdXJyZW50X3VzZXJfaWRlbnRpdGllcyIsImd0eSI6InBhc3N3b3JkIn0.St7097L1ZAlBWcAPrie-8CGV2F3Fr8uNYpSDVKSPVPF4zBZrmm62_UAj7Ssux8AjUy0LhjiF3kLpNph2L7yrpUREw6TyGJwQasfdVtM5VzRYUcy-fOGyRSqPQorbzxJQZzs2pyDJm-2hMQ0McJ37ubKIWrHFD5McMedN6THK7g5TExX47XCRPcOuCEWm3bf3zdWF2LEGhCw_c-lcZDwlb4ePkO721XjSWtrXEBvxc8scFNaHDt7VOnrSze4XK_LO8eE8bHRq6qUrWf1csYucK--aHazBsvfdl-6QDRk-tOBM-LdXJMT7H8Ih6trxVmZofQjr2dQ4j_3DTVoU3eLdog

UPDATE:

I switched from java,util.Base64 to org.apache.commons.codec.binary.Base64
and this seems to work somewhat, I don't get an error now.

String decodedString = new String(bytes, StandardCharsets.UTF_8);

gives me back a string of the header, payload, and signature data.  So, when I do:

JSONObject jsonObject = new JSONObject(decodedString);
    System.out.println("getTokenProperty: jsonObject = " + jsonObject.toString());

I am only getting back the header data, and what I really need is the payload.

For the record ... the code I inherited from a "proof of concept" project was:

public static String getTokenProperty(String token, String propertyName)
{
    return (new JSONObject(new String(Base64.getDecoder().decode(token)))).getString(propertyName);
}

and there was no unit testing at all.  So, when I went to unit test it, of course it completely broke.   So, now I have a better understanding of how to parse this token, and I will remember this lesson for a long time.

Thanks very much!

Body:
The reason it doesn't parse is because you are trying to Base64URLDecode the ENTIRE token.. But you have to decode PARTS of the token which is separated by a DOT "." character (0x2e in hex, 46 in dec, &#46 in html -- ASCII/UTF8) ..

Example:

public static void decodeTokenParts(String token)
{
    String[] parts = token.split("\\.", 0);

    for (String part : parts) {
        byte[] bytes = Base64.getUrlDecoder().decode(part);
        String decodedString = new String(bytes, StandardCharsets.UTF_8);

        System.out.println("Decoded: " + decodedString);
    }
}

This is because a JWT token is made up of parts:

Base64URLEncode({HeaderJSON}) + "." + Base64URLEncode({PayloadJSON}) + "." + Signature for example..

So to decode it.. you need to split it by "." and decode each part. Note: The signature will usually be binary that is encoded as base64 so once you decode it, don't try printing it.. it'll print bytes. You'd need to verify the signature.

For example, if you go to: https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

You will see how each "part" is encoded. It is colour coded.


问:
How do I use Python to trigger the download of a file from a website?
I'm trying to set up a script to pull data from a website on a daily basis and I'm having trouble getting Python to actually read the table - I'm not a professional coder. I've tried two methods:

1) Scrape the table (headers, rows, etc) using Beautiful Soup, and

2) Use the website's export with excel button

Here is the precise website:
https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200

So far my code is:

#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`

#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)
```

<p>I think the easiest method would be to trigger the "export" function with the </p>

```xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a
```

All help is greatly appreciated!

答:
Here is the code I got working:

```<code>## Input parameters
start_date = '5/28/19'
end_date = '5/31/19'

#### Loops through date range and pulls data
## Date Range ##
datelist = pd.date_range(start=start_date, end=end_date,
freq='D',dtype='datetime64[ns]')
print(datelist)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# opens chrome and opens up Gas Envoy
driver =webdriver.Chrome('C:/Users/tmrt/Documents/chromedriver_win32/chromedriver.exe')
</code>```

driver.get('https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200')

```<code># pause to give time to think load
time.sleep(5)

# Loops through the dates
for d in datelist:
     # Finds Date Box and Date Box Go Button
     date_box = driver.find_element_by_xpath('//*[@id="content"]/form/div[2]/table/tbody/tr/td[1]/table/tbody/tr/td[2]/input')
     date_clicker = driver.find_element_by_xpath('//*[@id="content"]/form/div[2]/table/tbody/tr/td[2]/table/tbody/tr/td/a')

    # Input date into datebox
    date_box.clear()
    date_box.send_keys(d.strftime("%m/%d/%Y"))

    # Click date_box
    date_clicker.click()

    # Pause to allow to load
    time.sleep(5)

    # Clicks download
     csv_button = driver.find_element_by_xpath('//*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a')
    csv_button.click()

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

Body:
I'm trying to set up a script to pull data from a website on a daily basis and I'm having trouble getting Python to actually read the table - I'm not a professional coder. I've tried two methods:

1) Scrape the table (headers, rows, etc) using Beautiful Soup, and

2) Use the website's export with excel button

Here is the precise website:
https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200

So far my code is:

#Imports
import requests
import urllib.request
import pandas as pd
from lxml import html
import lxml.html as lh
from bs4 import BeautifulSoup
`URL ='https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200'`

#Create a handle, page, to handle the contents of the website
requests.packages.urllib3.disable_warnings()
page = requests.get(URL, verify=False)

I think the easiest method would be to trigger the "export" function with the

xpath //*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a

All help is greatly appreciated!

Body:
Here is the code I got working:

## Input parameters
start_date = '5/28/19'
end_date = '5/31/19'

#### Loops through date range and pulls data
## Date Range ##
datelist = pd.date_range(start=start_date, end=end_date,
freq='D',dtype='datetime64[ns]')
print(datelist)

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

# opens chrome and opens up Gas Envoy
driver =webdriver.Chrome('C:/Users/tmrt/Documents/chromedriver_win32/chromedriver.exe')

driver.get('https://scgenvoy.sempra.com/index.html#nav=/Public/ViewExternalLowOFO.getLowOFO%3Frand%3D200')

# pause to give time to think load
time.sleep(5)

# Loops through the dates
for d in datelist:
     # Finds Date Box and Date Box Go Button
     date_box = driver.find_element_by_xpath('//*[@id="content"]/form/div[2]/table/tbody/tr/td[1]/table/tbody/tr/td[2]/input')
     date_clicker = driver.find_element_by_xpath('//*[@id="content"]/form/div[2]/table/tbody/tr/td[2]/table/tbody/tr/td/a')

    # Input date into datebox
    date_box.clear()
    date_box.send_keys(d.strftime("%m/%d/%Y"))

    # Click date_box
    date_clicker.click()

    # Pause to allow to load
    time.sleep(5)

    # Clicks download
     csv_button = driver.find_element_by_xpath('//*[@id="content"]/form/div[2]/div/table/tbody/tr/td[4]/table/tbody/tr/td[1]/a')
    csv_button.click()

driver.close()


问:
Sending email from own server to the internets
I have set up an email server on my host. It's basically a SMTP server that listens on port 25.

```<code>const recvServer = new SMTPServer({
  requireTLS: true,
  authOptional: true,
  logger: true,
  onConnect(session, callback) {
    return callback();
  },

  onMailFrom(address, session, callback) {
    console.log('from', address, session);
    return callback();
  },

  onData(stream, session, callback) {
    console.log('new msg');
    let message = '';
    stream.on('data', chunk => {
      message += chunk;
    });

    stream.on('end', () => {

      callback(null, 'Message queued');
      simpleParser(message)
        .then(parsed => {
          console.log(parsed);
          // here I wish to forward the message to outside gmail addresses
        })
        .catch(err => {
          console.log(ee)
        });

    });
  }
});

recvServer.listen(25);

recvServer.on('error', err => {
  console.log(err.message);
});
</code>```

It works fine for receiving emails from outside, like gmail etc.

But I want to be able to send emails outside also, or forward emails that I receive to some gmail addresses.

I know that I can do that using Gmail SMTP servers, but then I need an gmail account and password.

I want to be able to send email with my own server, just like yahoo sends mail to gmail using their own server not gmail accounts :)

答: In order to send email, you need an email client, not a server.  Writing the client is usually easier than writing the server, so you could do that.  If you don't want to write your own, you could use an MTA (like Postfix), which will contain both a client and a server. </p>

Body:
I have set up an email server on my host. It's basically a SMTP server that listens on port 25.

const recvServer = new SMTPServer({
  requireTLS: true,
  authOptional: true,
  logger: true,
  onConnect(session, callback) {
    return callback();
  },

  onMailFrom(address, session, callback) {
    console.log('from', address, session);
    return callback();
  },

  onData(stream, session, callback) {
    console.log('new msg');
    let message = '';
    stream.on('data', chunk => {
      message += chunk;
    });

    stream.on('end', () => {

      callback(null, 'Message queued');
      simpleParser(message)
        .then(parsed => {
          console.log(parsed);
          // here I wish to forward the message to outside gmail addresses
        })
        .catch(err => {
          console.log(ee)
        });

    });
  }
});

recvServer.listen(25);

recvServer.on('error', err => {
  console.log(err.message);
});

It works fine for receiving emails from outside, like gmail etc.

But I want to be able to send emails outside also, or forward emails that I receive to some gmail addresses.

I know that I can do that using Gmail SMTP servers, but then I need an gmail account and password.

I want to be able to send email with my own server, just like yahoo sends mail to gmail using their own server not gmail accounts :)


问:
Nuitka standalone isn't really standalone
I plan on using a Python (3.6) script for a project, though the final user is likely not to have Python on his system. To solve this issue and make everything as smooth as possible, I tried using Nuitka to compile my Python script and make it standalone.

To do that, I just ran

```<code>nuitka --standalone --recurse-all myscript.py
</code>```

Doing this takes a certain amount of time, but finally results in a folder with a myscript.exe that I can run just like I would run my script.

Though, as soon as I try and run it on another computer, no matter whether it has Python installed, I get an error thrown:

```<code>Traceback (most recent call last):
  File "D:\Users\thoma\Desktop\recuperation.dist\recuperation.py", line 6, in <module>
  File "D:\Users\thoma\Desktop\recuperation.dist\requests\__init__.py", line 43, in requests
  File "D:\Users\thoma\Desktop\recuperation.dist\urllib3\__init__.py", line 8, in urllib3
  File "D:\Users\thoma\Desktop\recuperation.dist\urllib3\connectionpool.py", line 7, in connectionpool
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python36\lib\socket.py", line 49, in <module>
ModuleNotFoundError: No module named '_socket'
</code>```

Also, I had trouble getting it to work in the beginning, because it was missing cacert.pem, but I solved that by copying the certifi folder that I found coming with requests. Don't know if it relates.

My script is using Requests, Dill, BS4 (and also json, base64, os and sys)

答:
The --standalone option does not (yet) produce a single file binary. In order to run myscript.exe on another machine, you have to provide all the files you find in the output directory of nuitka.

Luckily there is work in progress to allow compilation to single file binaries: https://github.com/Nuitka/Nuitka/issues/230

Body:
I plan on using a Python (3.6) script for a project, though the final user is likely not to have Python on his system. To solve this issue and make everything as smooth as possible, I tried using Nuitka to compile my Python script and make it standalone.

To do that, I just ran

nuitka --standalone --recurse-all myscript.py

Doing this takes a certain amount of time, but finally results in a folder with a myscript.exe that I can run just like I would run my script.

Though, as soon as I try and run it on another computer, no matter whether it has Python installed, I get an error thrown:

Traceback (most recent call last):
  File "D:\Users\thoma\Desktop\recuperation.dist\recuperation.py", line 6, in <module>
  File "D:\Users\thoma\Desktop\recuperation.dist\requests\__init__.py", line 43, in requests
  File "D:\Users\thoma\Desktop\recuperation.dist\urllib3\__init__.py", line 8, in urllib3
  File "D:\Users\thoma\Desktop\recuperation.dist\urllib3\connectionpool.py", line 7, in connectionpool
  File "C:\Users\Thomas\AppData\Local\Programs\Python\Python36\lib\socket.py", line 49, in <module>
ModuleNotFoundError: No module named '_socket'

Also, I had trouble getting it to work in the beginning, because it was missing cacert.pem, but I solved that by copying the certifi folder that I found coming with requests. Don't know if it relates.

My script is using Requests, Dill, BS4 (and also json, base64, os and sys)