问:
Cannot store Certificate to KeyChain using SecKeyChain in Xamarin
After hours spent reading through what's available online to fix this, I decided to post my question here.
My goal is simple: Store an X509Certficate to KeyChain using Xamarin for iOS. This is a self signed certificate that I generated using BouncyCastle library.
I'm successfuly importing it, but when saving to KeyChain using SecKeyChain.Add, the result is always SecStatusCode.Paramwhich the documentation explains is missing or invalid parameter. Here's the method I use

```<code>public static bool StoreCertInKeyChain(X509Certificate2 certificate, string password)
{
    var data = certificate.Export(X509ContentType.Pkcs12, password);

    var options = NSMutableDictionary.FromObjectAndKey(FromObject(password), SecImportExport.Passphrase);

    var statusCode = SecImportExport.ImportPkcs12(data, options, out NSDictionary[] result);
    if (statusCode != SecStatusCode.Success) return false;

    var certChain = result[0][SecImportExport.CertChain];
    var record = new SecRecord(SecKind.Certificate)
    {
        Label = "MyKey",
        Account = "Certificate",
        ApplicationTag = "MyTag"
    };
    record.SetValueRef(certChain);

    // Using the below code instead, produces the same result
    // var cert = new SecCertificate(certChain.Handle);
    // record.SetValueRef(cert);

    var resultAdd = SecKeyChain.Add(record);
    return resultAdd == SecStatusCode.Success;
}
</code>```

Has anyone ran into this problem? I'm out of ideas what else to try. I followed the examples given on Xamarin documentation site, without success. Thank you

答:
Answering my solution here, in case anyone else runs into the same issue. The problem was that the certificate supplied in the SecRecord wasn't an instance of SecCertificate, so using SecImportExport.ImportPkcs12 was the wrong way to do it. I ended up using SecIdentity.Import instead, which gives a reference to the certificate as well as the private key in it. The certificate and the private key need to be added to key chain separately using an identity. Here's the code that accomplishes this.

```<code>    var identity = SecIdentity.Import(certificate.Export(X509ContentType.Pkcs12, password), password);
    var storedCertificate = SecKeyChain.QueryAsConcreteType(new SecRecord(SecKind.Certificate) { Label = "My Cert" }, out SecStatusCode statusCode);
    if (statusCode != SecStatusCode.Success)
    {
        var record = new SecRecord(SecKind.Certificate);
        record.Label = "My Cert";
        record.SetValueRef(identity.Certificate);
        var result = SecKeyChain.Add(record);

        SecKeyChain.AddIdentity(identity);

        storedCertificate = SecKeyChain.QueryAsConcreteType(new SecRecord(SecKind.Certificate) { Label = "My Cert" }, out statusCode);
    }
    var storedIdentity = SecKeyChain.FindIdentity(storedCertificate as SecCertificate);
</code>```

The certificate can be retrieved using the label, but to get the private key, the identity must be queried using the certificate as parameter in SecKeyChain.FindIdentity. From this point on, access to signing and decryption on the private key is available from the identity instance.

Body:
After hours spent reading through what's available online to fix this, I decided to post my question here.
My goal is simple: Store an X509Certficate to KeyChain using Xamarin for iOS. This is a self signed certificate that I generated using BouncyCastle library.
I'm successfuly importing it, but when saving to KeyChain using SecKeyChain.Add, the result is always SecStatusCode.Paramwhich the documentation explains is missing or invalid parameter. Here's the method I use

public static bool StoreCertInKeyChain(X509Certificate2 certificate, string password)
{
    var data = certificate.Export(X509ContentType.Pkcs12, password);

    var options = NSMutableDictionary.FromObjectAndKey(FromObject(password), SecImportExport.Passphrase);

    var statusCode = SecImportExport.ImportPkcs12(data, options, out NSDictionary[] result);
    if (statusCode != SecStatusCode.Success) return false;

    var certChain = result[0][SecImportExport.CertChain];
    var record = new SecRecord(SecKind.Certificate)
    {
        Label = "MyKey",
        Account = "Certificate",
        ApplicationTag = "MyTag"
    };
    record.SetValueRef(certChain);

    // Using the below code instead, produces the same result
    // var cert = new SecCertificate(certChain.Handle);
    // record.SetValueRef(cert);

    var resultAdd = SecKeyChain.Add(record);
    return resultAdd == SecStatusCode.Success;
}

Has anyone ran into this problem? I'm out of ideas what else to try. I followed the examples given on Xamarin documentation site, without success. Thank you

Body:
Answering my solution here, in case anyone else runs into the same issue. The problem was that the certificate supplied in the SecRecord wasn't an instance of SecCertificate, so using SecImportExport.ImportPkcs12 was the wrong way to do it. I ended up using SecIdentity.Import instead, which gives a reference to the certificate as well as the private key in it. The certificate and the private key need to be added to key chain separately using an identity. Here's the code that accomplishes this.

    var identity = SecIdentity.Import(certificate.Export(X509ContentType.Pkcs12, password), password);
    var storedCertificate = SecKeyChain.QueryAsConcreteType(new SecRecord(SecKind.Certificate) { Label = "My Cert" }, out SecStatusCode statusCode);
    if (statusCode != SecStatusCode.Success)
    {
        var record = new SecRecord(SecKind.Certificate);
        record.Label = "My Cert";
        record.SetValueRef(identity.Certificate);
        var result = SecKeyChain.Add(record);

        SecKeyChain.AddIdentity(identity);

        storedCertificate = SecKeyChain.QueryAsConcreteType(new SecRecord(SecKind.Certificate) { Label = "My Cert" }, out statusCode);
    }
    var storedIdentity = SecKeyChain.FindIdentity(storedCertificate as SecCertificate);

The certificate can be retrieved using the label, but to get the private key, the identity must be queried using the certificate as parameter in SecKeyChain.FindIdentity. From this point on, access to signing and decryption on the private key is available from the identity instance.


来源: stackexchange

问:
Swift 4 NSLayoutConstraint not works properly
have a problem with NSLayoutConstraint and .scaleAspectFill after applying logoView (positioning and scaling) and titleLabel constraints, titleLabel's Y position not sets correctly

titleLabel.topAnchor.constraint(equalTo: logoView.bottomAnchor,
  constant: 20])

here my sample:

```<code>let logoView:UIImageView = {
        let img = UIImage(named: "big_logo")
        let im = UIImageView(image: img)
        im.translatesAutoresizingMaskIntoConstraints = false
        im.contentMode = .scaleAspectFill
        return im
}()

    lazy var titleLabel:UILabel = {
        let title:UILabel = UILabel()
        title.translatesAutoresizingMaskIntoConstraints = false
        title.text = MuiPack.getMuiString(key: "splash_greeting")
        title.font = UIFont.boldSystemFont(ofSize: 18)
        title.textColor = .black
        return title
    }()

 NSLayoutConstraint.activate([logoView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.6),
                                     logoView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
                                     logoView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -20)])

NSLayoutConstraint.activate([titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
                                     titleLabel.topAnchor.constraint(equalTo: logoView.bottomAnchor, constant: 20])
</code>```

答:
Your logoView does not have an intrinsicSize, so it has no height.

If you change your initialization as follows, you'll see what's happening:

```<code>let logoView:UIImageView = {
    let img = UIImage(named: "cross")
    let im = UIImageView(image: img)
    im.translatesAutoresizingMaskIntoConstraints = false
    im.contentMode = .scaleAspectFill
    // set a background color so you can see the image view's frame
    im.backgroundColor = .blue
    // clip the image to the bounds of the view's frame
    im.clipsToBounds = true
    return im
}()
</code>```

You can either set an explicit height constraint, or set it proportional to its width.

This will make it "square":

```<code>    NSLayoutConstraint.activate([
        logoView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.6),
        logoView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        logoView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -20),
        // add proportional height anchor
        logoView.heightAnchor.constraint(equalTo: logoView.widthAnchor, multiplier: 1.0)
        ])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
have a problem with NSLayoutConstraint and .scaleAspectFill after applying logoView (positioning and scaling) and titleLabel constraints, titleLabel's Y position not sets correctly

titleLabel.topAnchor.constraint(equalTo: logoView.bottomAnchor,
  constant: 20])

here my sample:

let logoView:UIImageView = {
        let img = UIImage(named: "big_logo")
        let im = UIImageView(image: img)
        im.translatesAutoresizingMaskIntoConstraints = false
        im.contentMode = .scaleAspectFill
        return im
}()

    lazy var titleLabel:UILabel = {
        let title:UILabel = UILabel()
        title.translatesAutoresizingMaskIntoConstraints = false
        title.text = MuiPack.getMuiString(key: "splash_greeting")
        title.font = UIFont.boldSystemFont(ofSize: 18)
        title.textColor = .black
        return title
    }()

 NSLayoutConstraint.activate([logoView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.6),
                                     logoView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
                                     logoView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -20)])

NSLayoutConstraint.activate([titleLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
                                     titleLabel.topAnchor.constraint(equalTo: logoView.bottomAnchor, constant: 20])

Body:
Your logoView does not have an intrinsicSize, so it has no height.

If you change your initialization as follows, you'll see what's happening:

let logoView:UIImageView = {
    let img = UIImage(named: "cross")
    let im = UIImageView(image: img)
    im.translatesAutoresizingMaskIntoConstraints = false
    im.contentMode = .scaleAspectFill
    // set a background color so you can see the image view's frame
    im.backgroundColor = .blue
    // clip the image to the bounds of the view's frame
    im.clipsToBounds = true
    return im
}()

You can either set an explicit height constraint, or set it proportional to its width.

This will make it "square":

    NSLayoutConstraint.activate([
        logoView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.6),
        logoView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
        logoView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: -20),
        // add proportional height anchor
        logoView.heightAnchor.constraint(equalTo: logoView.widthAnchor, multiplier: 1.0)
        ])


问:
What is Def.task and .taskValue in SBT?
I am reading SBT docs quite thoroughly now and there is a brief mention of Def.task and taskValue but there is no explanation so far.
They say here following:

```<code>You can compute values of some tasks or settings to define or append a value for another task.
It’s done by using Def.task and taskValue as an argument to :=, +=, or ++=.
</code>```

And provide following code snippet:

```<code>sourceGenerators in Compile += Def.task {
  myGenerator(baseDirectory.value, (managedClasspath in Compile).value)
}.taskValue
</code>```

This brings more questions than answers for me. How is that different from regular dependency of some SBT task on another task? When should I use this macro? etc.

I have also tried to check scaladoc but without any success really. That part of code is not documented well.

答:
I think this particular example in the introductory part of documentation is unnecessarily complicated. In this example you have to use .taskValue just because sourceGenerators value type is Seq[Task[Seq[File]]], so you have to add a task to it, not the value of that task.

A simpler example for that "Tasks based on other keys’ values" is

```<code>homepage := Some(
  url(s"https://github.com/${organization.value}/${name.value}")
)
</code>```

In the right part of :=/+=/++=/~= operators you can use other tasks values with simple .value suffix. Writing

```<code>foo := bar.value + 1
</code>```

is the same as

```<code>foo := Def.task { bar.value + 1 }.value
</code>```

In this simple example it's just unnecessary, but Def.task becomes useful when you want to separate task implementation from the task key setting:

```<code>def fooTask(n: Int): Def.Initialize[Task[Int]] = Def.task {
  bar.value + n
}
</code>```

So Def.task allows you to write a task definition and use other tasks/settings inside (with .value). Then you can evaluate this task definition when you set the corresponding task key somewhere else (in your project settings):

```<code>foo := fooTask(5).value
</code>```

But if you need to refer to the task definition itself without evaluating it, you can use .taskValue instead of .value, like in your example. See documentation on generating sources for more information about sourceGenerators.

Here are some other relevant parts of the sbt documentation about tasks:

Tasks

Tasks/Settings: Motivation

Execution semantics of tasks

Sequencing tasks

Title: What is Def.task and .taskValue in SBT?

Body:
I am reading SBT docs quite thoroughly now and there is a brief mention of Def.task and taskValue but there is no explanation so far.
They say here following:

You can compute values of some tasks or settings to define or append a value for another task.
It’s done by using Def.task and taskValue as an argument to :=, +=, or ++=.

And provide following code snippet:

sourceGenerators in Compile += Def.task {
  myGenerator(baseDirectory.value, (managedClasspath in Compile).value)
}.taskValue

This brings more questions than answers for me. How is that different from regular dependency of some SBT task on another task? When should I use this macro? etc.

I have also tried to check scaladoc but without any success really. That part of code is not documented well.

Body:
I think this particular example in the introductory part of documentation is unnecessarily complicated. In this example you have to use .taskValue just because sourceGenerators value type is Seq[Task[Seq[File]]], so you have to add a task to it, not the value of that task.

A simpler example for that "Tasks based on other keys’ values" is

homepage := Some(
  url(s"https://github.com/${organization.value}/${name.value}")
)

In the right part of :=/+=/++=/~= operators you can use other tasks values with simple .value suffix. Writing

foo := bar.value + 1

is the same as

foo := Def.task { bar.value + 1 }.value

In this simple example it's just unnecessary, but Def.task becomes useful when you want to separate task implementation from the task key setting:

def fooTask(n: Int): Def.Initialize[Task[Int]] = Def.task {
  bar.value + n
}

So Def.task allows you to write a task definition and use other tasks/settings inside (with .value). Then you can evaluate this task definition when you set the corresponding task key somewhere else (in your project settings):

foo := fooTask(5).value

But if you need to refer to the task definition itself without evaluating it, you can use .taskValue instead of .value, like in your example. See documentation on generating sources for more information about sourceGenerators.

Here are some other relevant parts of the sbt documentation about tasks:

Tasks

Tasks/Settings: Motivation

Execution semantics of tasks

Sequencing tasks


问:
i need to combine unique keys and their values grouping as list in python
mylist=[{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]

i need like this

Heading

mylist=[{'apple':[1,3],'mango':[2,15],'orange':[0,10]}]

答:
example = [{'apple':1,'mango':2},{'apple':3,'orange':10,'mango':15}]
new ={}

[[ks.update({k:v}) for s in [{listKey:0} for listKey in list(set(list(set(i for key_name in example for i in key_name)))-set(ks.keys()))] for k,v in s.items()] for ks in example]
[new.setdefault(k, []).append(v) for d in example for k,v in d.iteritems()]
print new


问:
How can I obtain which checklist items are checked in php and use them to make a sql query?

I'm trying to create a checklist that acts as a filter for my database. The checklist would be use to enter multiple values to search for. For example, the user should be able to search for the brands AC and Abarth at the same time.

This is what the checklist for brands looks like.

```<code><h3>Brand</h3>
                <?php
                    $query = "select distinct(Brand) from Sheet1 order by Brand ASC";
                    $rs = mysqli_query($conn,$query) or die("Error : ".mysql_error());
                    while($brand_data = mysqli_fetch_assoc($rs)){

                ?>
                    <a href="javascript:void(0);" class="list-group-item">
                    <input type="checkbox" class="item_filter brand" value="<?php echo $brand_data['Brand']; ?>"  >
                       <?php echo $brand_data['Brand']; ?></a>
                <?php } ?>
</code>```

My ajax code.

```<code>var brand;
$(function(){
    $('.item_filter').click(function(){
        $('.product-data').html('<div id="loaderpro" style="" ></div>');

         brand = multiple_values('brand');

        $.ajax({
            url:"ajax.php",
            type:'post',
            data:{brand:brand},
            success:function(result){
                $('.product-data').html(result);
            }
        });
    });

});

function multiple_values(inputclass){
    var val = new Array();
    $("."+inputclass+":checked").each(function() {
        val.push($(this).val());
    });
    return val;
}
</code>```

This is how my php handles the checkbox.

```<code>$brand = isset($_REQUEST['Brand'])?$_REQUEST['Brand']:"";
$query = "select * from Sheet1 where";

                   //filter query start
                      if(!empty($brand)){
                          $branddata =implode("','",$brand);
                          $query  .= " Brand in('$branddata')";
                      }
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn))
</code>```

The result should be $query= select * from Sheet1 where Brand in ('AC', 'Abarth'). This is for my database to show the all car models with the brand AC or Abarth.

The current result I'm getting is that it won't give a value of what is checked in the checklist. So the final result is nothing, it might be because of my ajax code, because $brand doesn't get any value. The value should be an array that is later converted into a single string.

答:
Figured out my own problem. The php was wrong. The php is looking for values for the variable Brand, meanwhile the ajax is sending values to the variable brand.

Fixed by changing

```<code>$brand = isset($_REQUEST['Brand'])?$_REQUEST['Brand']:"";
</code>```

to

```<code>$brand = isset($_REQUEST['brand'])?$_REQUEST['brand']:"";
</code>```

Body:
I'm trying to create a checklist that acts as a filter for my database. The checklist would be use to enter multiple values to search for. For example, the user should be able to search for the brands AC and Abarth at the same time.

This is what the checklist for brands looks like.

Brand

                <?php
                    $query = "select distinct(Brand) from Sheet1 order by Brand ASC";
                    $rs = mysqli_query($conn,$query) or die("Error : ".mysql_error());
                    while($brand_data = mysqli_fetch_assoc($rs)){

                ?>

                    <input type="checkbox" class="item_filter brand" value="<?php echo $brand_data['Brand']; ?>"  >
                       <?php echo $brand_data['Brand']; ?>
                <?php } ?>

My ajax code.

var brand;
$(function(){
    $('.item_filter').click(function(){
        $('.product-data').html('

');

         brand = multiple_values('brand');

        $.ajax({
            url:"ajax.php",
            type:'post',
            data:{brand:brand},
            success:function(result){
                $('.product-data').html(result);
            }
        });
    });

});

function multiple_values(inputclass){
    var val = new Array();
    $("."+inputclass+":checked").each(function() {
        val.push($(this).val());
    });
    return val;
}

This is how my php handles the checkbox.

$brand = isset($_REQUEST['Brand'])?$_REQUEST['Brand']:"";
$query = "select * from Sheet1 where";

                   //filter query start
                      if(!empty($brand)){
                          $branddata =implode("','",$brand);
                          $query  .= " Brand in('$branddata')";
                      }
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn))

The result should be $query= select * from Sheet1 where Brand in ('AC', 'Abarth'). This is for my database to show the all car models with the brand AC or Abarth.

The current result I'm getting is that it won't give a value of what is checked in the checklist. So the final result is nothing, it might be because of my ajax code, because $brand doesn't get any value. The value should be an array that is later converted into a single string.

Body:
Figured out my own problem. The php was wrong. The php is looking for values for the variable Brand, meanwhile the ajax is sending values to the variable brand.

Fixed by changing

$brand = isset($_REQUEST['Brand'])?$_REQUEST['Brand']:"";

to

$brand = isset($_REQUEST['brand'])?$_REQUEST['brand']:"";


问:
Domain rejoin as post imaging task
My Question:

Edit: I'm specifically trying to do this programmatically through Powershell.

How can I check to see if a computer that is not currently joined to the domain (Freshly imaged) has an entry in the domain so that I can delete it prior to re-adding the computer to the domain? i.e. to ensure that as I image computers their old records are removed and only a single Computer object exists for each machine?

I know how to check if a computer is currently connected to a domain, and I know how to reconcile a trust relationship. Have I made a mistake in not using a script to pull the computer out of the domain as a pre-install task? I've already imaged a number of computers but I forgot some software and will be re-imaging again. So I'm hoping to get this implemented to remove all duplicate entries on the next go-around.

Background:

I've recently stepped into a network and domain that has less than 10% documentation available. It was one of those lovely systems that was more duct tape as it was built as-needed using whatever tutorials were available at the time.

In attempting to fix some of the more glaring issues, I've prepared a fresh Windows 10 image.

Now, all the computers are already in the domain, but because of the organizational issues and such, I'm using a powershell script to re-add them and put them into better defined OUs with names that make more sense. Previously devices were named after the individual that used them, but with so many staff changes that system is completely ineffective in tracking devices.

Previous Search Attempts:

I've tried searching for post image tasks for checking if a computer already exists before adding it to a domain, but the only results I've been able to get both through Google and Spiceworks are those that simply go over adding a computer or removing it from the domain, and the ones on repairing the trust relationship.

It may be simply that I'm not aware of the correct phrasing for the question, so if this has been answered before I would be ecstatic for someone to post the link for me.

Thank you for reading!

答:
The solution ended up being to simply add the computers to the domain and then after 90 days I ran a script to purge anything that hadn't reported into Active Directory. I did the same thing with accounts at a 180 day mark.

It meant I had ~10,000 extra items in Active Directory and had a negative impact on speed, but now that everything is properly tracked I won't have to repeat the process next year.

I made certain to back up all items using ldifde in the event that I accidentally deleted a machine that was only used at certain times of the year such as the ISTEP test caching machines. Being able to back them up made me much more willing to bypass reconciling the entries and to simply purge them.

Here is the script in case anyone comes across the same issue:

```<code>#I always set the location at the start of a script in case I forget at the end of a previous script.
Set-Location C:\

#ActiveDirectory is the only necessary module for this script.
Import-Module ActiveDirectory

#While this is not 100% secure, I still feel it is better than leaving the credentials in plaintext within the code.
$keyfile = "\\[domain controller]\GPO Deployment Files\Scripts\AES.txt"
[byte[]] $key = ([byte array key])
$secure = Get-Content $keyfile | ConvertTo-SecureString -Key $key
$username = "[domain\admin]"
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $secure

#Establishes the 90 day cutoff based off the current day.
$datecutoff = (Get-Date).AddDays(-90)

#As I wanted to go district-wide, I did not bother adding an OU based filter.
$computers = Get-ADComputer -Filter {LastLogonDate -lt $datecutoff} -Properties * | Sort LastLogonDate | Select DistinguishedName,Name,LastLogonDate

#This is a test CSV - I ran all code up until this line so I could verify the list with a quick visual skim.
$computers | Add-Content -Path "\\[domain controller]\DeletedADItems\test.csv"

#Stepping through the list
Foreach ($computer in $computers) {

#I know there are likely elegant ways to do this, but using the -replace option was the simplest solution I could come up with at the time.
    $computername = $computer.Name -replace '@{name=',''
    $computername = $computername -replace '}',''
    $computerDN = $computer.DistinguishedName -replace '@{DistinguishedName=',''
    $computerDN = $computerDN -replace '}',''
<# I discovered that LDIFDE doesn't always play nicely with PS drives and such, or at least it failed to do so in my case.
So I back up the files to my local drive and then I copy them to the domain controller path that I used with the test.csv file. #>
    $exportFile = "C:\DeletedADItems\$computername.ldf"

#Prior to deletion, export the object to the export file location.
    ldifde -d "$computerDN" -f "$exportFile"

#Finally, remove the item and mark confirm false so you don't have to confirm hundreds of deletions.
    Remove-ADComputer -Identity "$computerDN" -Confirm:$False

}
</code>```

It is mostly self-explanatory, but I added some basic comments just in case.

Title: Domain rejoin as post imaging task

Body:
The solution ended up being to simply add the computers to the domain and then after 90 days I ran a script to purge anything that hadn't reported into Active Directory. I did the same thing with accounts at a 180 day mark.

It meant I had ~10,000 extra items in Active Directory and had a negative impact on speed, but now that everything is properly tracked I won't have to repeat the process next year.

I made certain to back up all items using ldifde in the event that I accidentally deleted a machine that was only used at certain times of the year such as the ISTEP test caching machines. Being able to back them up made me much more willing to bypass reconciling the entries and to simply purge them.

Here is the script in case anyone comes across the same issue:

#I always set the location at the start of a script in case I forget at the end of a previous script.
Set-Location C:\

#ActiveDirectory is the only necessary module for this script.
Import-Module ActiveDirectory

#While this is not 100% secure, I still feel it is better than leaving the credentials in plaintext within the code.
$keyfile = "\\[domain controller]\GPO Deployment Files\Scripts\AES.txt"
[byte[]] $key = ([byte array key])
$secure = Get-Content $keyfile | ConvertTo-SecureString -Key $key
$username = "[domain\admin]"
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $secure

#Establishes the 90 day cutoff based off the current day.
$datecutoff = (Get-Date).AddDays(-90)

#As I wanted to go district-wide, I did not bother adding an OU based filter.
$computers = Get-ADComputer -Filter {LastLogonDate -lt $datecutoff} -Properties * | Sort LastLogonDate | Select DistinguishedName,Name,LastLogonDate

#This is a test CSV - I ran all code up until this line so I could verify the list with a quick visual skim.
$computers | Add-Content -Path "\\[domain controller]\DeletedADItems\test.csv"

#Stepping through the list
Foreach ($computer in $computers) {

#I know there are likely elegant ways to do this, but using the -replace option was the simplest solution I could come up with at the time.
    $computername = $computer.Name -replace '@{name=',''
    $computername = $computername -replace '}',''
    $computerDN = $computer.DistinguishedName -replace '@{DistinguishedName=',''
    $computerDN = $computerDN -replace '}',''
<# I discovered that LDIFDE doesn't always play nicely with PS drives and such, or at least it failed to do so in my case.
So I back up the files to my local drive and then I copy them to the domain controller path that I used with the test.csv file. #>
    $exportFile = "C:\DeletedADItems\$computername.ldf"

#Prior to deletion, export the object to the export file location.
    ldifde -d "$computerDN" -f "$exportFile"

#Finally, remove the item and mark confirm false so you don't have to confirm hundreds of deletions.
    Remove-ADComputer -Identity "$computerDN" -Confirm:$False

}

It is mostly self-explanatory, but I added some basic comments just in case.


问:
Filter aggregation and sorting
I have documents with 2 fields, application_id and location_id.
The combination of those 2 fields maps back to services, as follow (for example):

```<code>application_id  location_id     service_id
             1            1              1
             2            1              2
             1            2              3
             2            2              3
</code>```

I have a lot of those services and for several reasons, the service_id cannot/won't be computed prior to indexing my documents.

Hence, service_id field does not exist, and I can't/won't change that.

I would like to filter the service_id and get the top 5 ones that have the largest amount of documents.

I can easily create filters for my service_ids:

```<code>"aggs": {
  "services": {
    "filters": {
      "filters": {
        "service 1": {
          "query_string": {
            "query": "application_id:1 AND location_id:1"
          }
        },
        "service 2": {
          "query_string": {
            "query": "application_id:2 AND location_id:1"
          }
        }
      }
    }, [...]
  }
}
</code>```

But how can I get my top 5 services, by number of documents? I guess I'll need "size": 5 and "order": { "<metric>": "desc"}, however I don't exactly know how to articulate everything (for example, I don't know what  to put there, or how I can successfully sub-nest a sorting mechanism through a terms aggregation).

答:
You can get top 5 services by size and order doc _count:</p>

```<code>"aggs" : {
    "top_5_service" : {
        "terms" : {
            "field" : "service_id",
            "size" : 5,
            "order" : {
                "_count" : "desc"
            }
        }
    }
}
</code>```

Title: Filter aggregation and sorting

Body:
I have documents with 2 fields, application_id and location_id.
The combination of those 2 fields maps back to services, as follow (for example):

application_id  location_id     service_id
             1            1              1
             2            1              2
             1            2              3
             2            2              3

I have a lot of those services and for several reasons, the service_id cannot/won't be computed prior to indexing my documents.

Hence, service_id field does not exist, and I can't/won't change that.

I would like to filter the service_id and get the top 5 ones that have the largest amount of documents.

I can easily create filters for my service_ids:

"aggs": {
  "services": {
    "filters": {
      "filters": {
        "service 1": {
          "query_string": {
            "query": "application_id:1 AND location_id:1"
          }
        },
        "service 2": {
          "query_string": {
            "query": "application_id:2 AND location_id:1"
          }
        }
      }
    }, [...]
  }
}

But how can I get my top 5 services, by number of documents? I guess I'll need "size": 5 and "order": { "<metric>": "desc"}, however I don't exactly know how to articulate everything (for example, I don't know what  to put there, or how I can successfully sub-nest a sorting mechanism through a terms aggregation).

Body:
You can get top 5 services by size and order doc _count:

"aggs" : {
    "top_5_service" : {
        "terms" : {
            "field" : "service_id",
            "size" : 5,
            "order" : {
                "_count" : "desc"
            }
        }
    }
}


问:
where to put common logic in Flask routes
I have a flask application with many route endpoints. In each of those routes, I need to do some common operations like Authentication check, validation logic for permission, XSS validation and few more common validation logic. I have read few posts which says of using login_required decorator in every methods for the Authentication verification.

Now my question is should I create a decorator for each of the validation type and use them in every method. Please let me know how to handle such cases in Flask application.

```<code>@Login_required()
@Xss_validate()
@permission_check()
def subsribe_service(cs_dict, data_dict):
    Logic to subscribe....

@Login_required()
@Xss_validate()
@permission_check()
def unsubsribe_service(cs_dict, data_dict):
    Logic to unsubscribe....

@Login_required()
@Xss_validate()
@permission_check()
def delete_service(cs_dict, data_dict):
    Logic to delete....

@Login_required()
@Xss_validate()
@permission_check()
def edit_service(cs_dict, data_dict):
    Logic to edit....
</code>```

As you can see I have common logic as a decorator in all the action methods. I have such decorators in all the applications since every action require those 3 logic.

答:
add: you can Pluggable Views similar to class based views:
egg:

```<code>from flask import Flask
from flask.views import MethodView

app = Flask(__name__)

class BaseViews(MethodView):
    decorators = [Login_required, Xss_validate, permission_check]

class SubsribeService(BaseViews):
    def get(self):
        # get Logic

    def post(self):
        # post logic

class EditService(BaseViews):
    def get(self):
        # get Logic

    def post(self):
        # post logic

app.add_url_rule('/subsribe_service/', view_func=SubsribeService.as_view('subsribe_service'), methods=['GET', 'POST'])
app.add_url_rule('/edit_service/', view_func=EditService.as_view('edit_service'), methods=['GET', 'POST'])
</code>```

simple easy and beautiful..!

Body:
I have a flask application with many route endpoints. In each of those routes, I need to do some common operations like Authentication check, validation logic for permission, XSS validation and few more common validation logic. I have read few posts which says of using login_required decorator in every methods for the Authentication verification.

Now my question is should I create a decorator for each of the validation type and use them in every method. Please let me know how to handle such cases in Flask application.

@Login_required()
@Xss_validate()
@permission_check()
def subsribe_service(cs_dict, data_dict):
    Logic to subscribe....

@Login_required()
@Xss_validate()
@permission_check()
def unsubsribe_service(cs_dict, data_dict):
    Logic to unsubscribe....

@Login_required()
@Xss_validate()
@permission_check()
def delete_service(cs_dict, data_dict):
    Logic to delete....

@Login_required()
@Xss_validate()
@permission_check()
def edit_service(cs_dict, data_dict):
    Logic to edit....

As you can see I have common logic as a decorator in all the action methods. I have such decorators in all the applications since every action require those 3 logic.

Body:
add: you can Pluggable Views similar to class based views:
egg:

from flask import Flask
from flask.views import MethodView

app = Flask(__name__)

class BaseViews(MethodView):
    decorators = [Login_required, Xss_validate, permission_check]

class SubsribeService(BaseViews):
    def get(self):
        # get Logic

    def post(self):
        # post logic

class EditService(BaseViews):
    def get(self):
        # get Logic

    def post(self):
        # post logic

app.add_url_rule('/subsribe_service/', view_func=SubsribeService.as_view('subsribe_service'), methods=['GET', 'POST'])
app.add_url_rule('/edit_service/', view_func=EditService.as_view('edit_service'), methods=['GET', 'POST'])

simple easy and beautiful..!


问:
JSON.parse is an “undefined” object
I created json with php. Data coming with ajax. But JSON.parse is  giving an “undefined” object. Why ?

Php CODE

```<code> $emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode($emparray);
</code>```

Ajax CODE

```<code>   $.ajax({
        type: "GET",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= JSON.parse(msg);
            alert(obj.name);// giving undefined
        },
        error: function (error) {
        }
    });
</code>```

json

```<code>[{"name":"eng","a":"sdf"}]
</code>```

答:
You should obj[0].name

Because you are accessing the name property of the of the first element of the array.

Title: JSON.parse is an “undefined” object

Body:
I created json with php. Data coming with ajax. But JSON.parse is  giving an “undefined” object. Why ?

Php CODE

 $emparray = array();
 while($row =mysqli_fetch_assoc($result))
 {
     $emparray[] = $row;
 }

 echo json_encode($emparray);

Ajax CODE

   $.ajax({
        type: "GET",
        url: "http://localhost:8080/xxx.php/",
        success: function (msg, result, status, xhr) {
            var obj= JSON.parse(msg);
            alert(obj.name);// giving undefined
        },
        error: function (error) {
        }
    });

json

[{"name":"eng","a":"sdf"}]


问:
VC++ 2008 compiling problem with boost
All of a sudden a two project solution started to fail to compile. I don't remember making any change that could compromise the build. One project is a lib and the other is exe. The lib is still compiling without issues, but the exe fails. I isolated the issue at a point when some boost files are loaded. Here is a the stdafx.cpp that is enough to show the error:

```<code>#include "stdafx.h"
#include <boost/thread.hpp>
</code>```

And these are the errors reported:

```<code>1>Compiling...
1>stdafx.cpp
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\stdlib.h(525) : see declaration of '_ultoa'
1>c:\libs\boost_1_44_0\boost\mpl\size_t_fwd.hpp(23) : error C2143: syntax error : missing ',' before 'constant'
1>c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(42) : error C2143: syntax error : missing ',' before 'constant'
1>c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(84) : error C2143: syntax error : missing ',' before 'constant'
1>c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(84) : error C3211: 'boost::mpl::size_t<__formal>::value' : explicit specialization is using partial specialization syntax, use template <> instead
1>        with
1>        [
1>            __formal=1135
1>        ]
1>        c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(45) : see declaration of 'boost::mpl::size_t<__formal>::value'
1>        with
1>        [
1>            __formal=1135
1>        ]
</code>```

I noticed that if I change the include line to:

```<code>#include "stdafx.h"
#include <boost/thread/thread.hpp>
</code>```

it works, but then I have other includes in the code as:

```<code>#include <boost/bind.hpp>
#include <boost/function.hpp>
</code>```

and they also give the same 4 error lines.

Anyone have any idea what could be wrong? I am restating that this code worked for months and the error first came yesterday.

答: Hard to guess, but I think there might be some macro defined in stdafx.h that collides with Boost (i.e. Boost uses a variable/function/template/whatever with the same name as your macro). Remember that macros span over scopes. A quick check - does the problem vanish if you change the order of includes?</p>

ContentLicense: CC BY-SA 2.5

Title: VC++ 2008 compiling problem with boost

Body:
All of a sudden a two project solution started to fail to compile. I don't remember making any change that could compromise the build. One project is a lib and the other is exe. The lib is still compiling without issues, but the exe fails. I isolated the issue at a point when some boost files are loaded. Here is a the stdafx.cpp that is enough to show the error:

#include "stdafx.h"
#include <boost/thread.hpp>

And these are the errors reported:

1>Compiling...
1>stdafx.cpp
1>        c:\program files (x86)\microsoft visual studio 9.0\vc\include\stdlib.h(525) : see declaration of '_ultoa'
1>c:\libs\boost_1_44_0\boost\mpl\size_t_fwd.hpp(23) : error C2143: syntax error : missing ',' before 'constant'
1>c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(42) : error C2143: syntax error : missing ',' before 'constant'
1>c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(84) : error C2143: syntax error : missing ',' before 'constant'
1>c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(84) : error C3211: 'boost::mpl::size_t<__formal>::value' : explicit specialization is using partial specialization syntax, use template <> instead
1>        with
1>        [
1>            __formal=1135
1>        ]
1>        c:\libs\boost_1_44_0\boost\mpl\aux_\integral_wrapper.hpp(45) : see declaration of 'boost::mpl::size_t<__formal>::value'
1>        with
1>        [
1>            __formal=1135
1>        ]

I noticed that if I change the include line to:

#include "stdafx.h"
#include <boost/thread/thread.hpp>

it works, but then I have other includes in the code as:

#include <boost/bind.hpp>
#include <boost/function.hpp>

and they also give the same 4 error lines.

Anyone have any idea what could be wrong? I am restating that this code worked for months and the error first came yesterday.


问:
Using purrr::invoke() to supply different arguments to function.
I want to run the kmeans() function in R with different values of k (kmeans(x = iris[1:4], centers = k)). I know how to do this with dplyr or the do.call() function, however I can't get it to work with purrr::invoke() (I'm quite sure that invoke is the right function for this task). I could of course just use the dplyr approach (see this link), but it annoys me that I can't get it to work with purrr.

In the purrr::invoke() function reference, the following code-example is included:

```<code># Or the same function with different inputs:
invoke_map("runif", list(list(n = 5), list(n = 10)))
#> [[1]]
#> [1] 0.67176682 0.05861411 0.99706914 0.14903547 0.51855664
#>
#> [[2]]
#>  [1] 0.84612005 0.71826972 0.24131402 0.54704337 0.83480182 0.02795603
#>  [7] 0.46938430 0.80568003 0.81405131 0.40391100
#>
</code>```

When i try to do this with kmeans i get the following

```<code>> invoke(kmeans, list(list(centers = 1), list(centers = 2)), x = iris[1:4])
Error in sample.int(m, k) : invalid 'size' argument
</code>```

I have also tried

```<code>> invoke(kmeans, list(centers = 1:5), x = iris[1:4])
Error in (function (x, centers, iter.max = 10L, nstart = 1L,
algorithm = c("Hartigan-Wong",  : must have same number of columns in 'x' and 'centers'
</code>```

as a reality-check, i also tried doing a similar thing with paste

```<code>> invoke(paste, list(list(sep = "a"), list(sep = "b")), "word1", "word2")
[1] "a b word1 word2"
</code>```

where i would've expected word1aword2 and word1bword2. I have been reading all the function references and I'm currently not sure how to solve this problem.

答:
I've figured out what went wrong. First of all, the correct function to use in this case is invoke_map() and not invoke(). When using this function (as also specified in the function reference -.-), the problem can be solved with the following code:

```<code>invoke_map(kmeans, list(list(centers = 1), list(centers = 2)), x = iris[1:4])
</code>```

This can however be quite tedious to write if you want multiple centers, so i came up with the following solution which im quite happy with. Hope this can help someone else!

```<code>invoke_map(kmeans, transpose(list(centers = 1:10)), x = iris[1:4])
</code>```

Body:
I want to run the kmeans() function in R with different values of k (kmeans(x = iris[1:4], centers = k)). I know how to do this with dplyr or the do.call() function, however I can't get it to work with purrr::invoke() (I'm quite sure that invoke is the right function for this task). I could of course just use the dplyr approach (see this link), but it annoys me that I can't get it to work with purrr.

In the purrr::invoke() function reference, the following code-example is included:

# Or the same function with different inputs:
invoke_map("runif", list(list(n = 5), list(n = 10)))
#> [[1]]
#> [1] 0.67176682 0.05861411 0.99706914 0.14903547 0.51855664
#>
#> [[2]]
#>  [1] 0.84612005 0.71826972 0.24131402 0.54704337 0.83480182 0.02795603
#>  [7] 0.46938430 0.80568003 0.81405131 0.40391100
#>

When i try to do this with kmeans i get the following

> invoke(kmeans, list(list(centers = 1), list(centers = 2)), x = iris[1:4])
Error in sample.int(m, k) : invalid 'size' argument

I have also tried

> invoke(kmeans, list(centers = 1:5), x = iris[1:4])
Error in (function (x, centers, iter.max = 10L, nstart = 1L,
algorithm = c("Hartigan-Wong",  : must have same number of columns in 'x' and 'centers'

as a reality-check, i also tried doing a similar thing with paste

> invoke(paste, list(list(sep = "a"), list(sep = "b")), "word1", "word2")
[1] "a b word1 word2"

where i would've expected word1aword2 and word1bword2. I have been reading all the function references and I'm currently not sure how to solve this problem.

Body:
I've figured out what went wrong. First of all, the correct function to use in this case is invoke_map() and not invoke(). When using this function (as also specified in the function reference -.-), the problem can be solved with the following code:

invoke_map(kmeans, list(list(centers = 1), list(centers = 2)), x = iris[1:4])

This can however be quite tedious to write if you want multiple centers, so i came up with the following solution which im quite happy with. Hope this can help someone else!

invoke_map(kmeans, transpose(list(centers = 1:10)), x = iris[1:4])


问:
aws cloud formation idenitfy ami id based on tags and create instance
I have a usecase where the cloud formation has to identify AMI-ID based on tags (passed as inputs to cloud formation template) and likewise create an ec2 instance.

Can I run a script to identify (aws ec2 describe-images  --filters "Name=tag:Name,Values=value1" --query 'Images[*].{ID:ImageId}' --output text) AMI-ID via cloud formation and pass it for ec2 instance creation..

Any thoughts or example on how to do this ?

答:
You cannot run the script as part of your CloudFormation template.

You will need to execute the command before creating the CloudFormation stack to determine the AMI ID. Then pass the final AMI ID into the CloudFormation stack by way of an input parameter.

So it will be a 2-step process. But you can create a script to do it.


问:
How can I launch the splash screen only when the app is killed or started for the first time ?
I don't know why but the splashscreen always starts. I would like it to start only when the app is killed or runs for the first time.

Here is my code :

```<code>public class SplashScreenActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash_screen);

        Thread splashscreen = new Thread() {
            public void run(){
                try{
                    int sp = 0;
                    while(sp < 1000){
                        sleep(100);
                        sp = sp +100;
                    };

                }

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

                finally{
                    finish();
                    startActivity(new Intent(SplashScreenActivity.this, TutoActivity.class));
                }
            }
        };

        splashscreen.start();
    }
</code>```

答:
Okay, so the trick is to first call

```<code>finish()
</code>```

and then

```<code>startActivity()
</code>```

on your SplashScreenActivity, so it won't appear until you kill the app.

Body:
I don't know why but the splashscreen always starts. I would like it to start only when the app is killed or runs for the first time.

Here is my code :

public class SplashScreenActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash_screen);

        Thread splashscreen = new Thread() {
            public void run(){
                try{
                    int sp = 0;
                    while(sp < 1000){
                        sleep(100);
                        sp = sp +100;
                    };

                }

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

                finally{
                    finish();
                    startActivity(new Intent(SplashScreenActivity.this, TutoActivity.class));
                }
            }
        };

        splashscreen.start();
    }

Body:
Okay, so the trick is to first call

finish()

and then

startActivity()

on your SplashScreenActivity, so it won't appear until you kill the app.


问:
Copied the sample ag-grid example and have cells rendering on top of each other
I am experimenting with ag-grid and trying to get some very simple examples working. So far I am not having much luck.

I created a brand new app using ng new gridTest then I tried to follow these instructions.

The sample site I created is here.

My resulting grid looks like this:

app.component.html:

```<code><ag-grid-angular style="width: 500px; height: 115px;" class="ag-theme-fresh"
[rowData]="rowData"
[columnDefs]="columnDefs">
</ag-grid-angular>
</code>```

app.component.ts:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  public rowData = [
    { make: "Toyota", model: "Celica", price: 35000 },
    { make: "Ford", model: "Mondeo", price: 32000 },
    { make: "Porsche", model: "Boxter", price: 72000 }
  ]

  public columnDefs = [
    { headerName: "Make", field: "make" },
    { headerName: "Model", field: "model" },
    { headerName: "Price", field: "price" }
  ]
}
</code>```

app.module.ts:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { AgGridModule } from 'ag-grid-angular/main';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

What am I doing wrong? I can't see how I messed up styles or anything with this very simple example...

答:
It turns out that the problems here were mostly style related. The fixed app can be seen here.

To get the grid I had to add the correct ag-grid styles into the angular-cli.json file:

```<code>  "styles": [
    "../node_modules/ag-grid/dist/styles/ag-grid.css",
    "../node_modules/ag-grid/dist/styles/theme-fresh.css"
  ]
</code>```

I had to change the grid div to point to the correct style name:

```<code><ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
[rowData]="rowData"
[columnDefs]="columnDefs"
</ag-grid-angular>
</code>```

and to get the columns to display nicely I had to add an event listener:

```<code><ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
[rowData]="rowData"
[columnDefs]="columnDefs"
(gridReady)="onGridReady($event)">
</ag-grid-angular>
</code>```

and a handler:

```<code>  public onGridReady(params: any){
    params.api.sizeColumnsToFit();
  }
</code>```

The ag-grid documentation mostly relies on you cloning a git-hub repo and running that. Where I work we can't access github and we only have limited access to npm so I had to try and add the grid to an existing project. There is no documentation that has what steps you need to do when you take this approach.

Body:
I am experimenting with ag-grid and trying to get some very simple examples working. So far I am not having much luck.

I created a brand new app using ng new gridTest then I tried to follow these instructions.

The sample site I created is here.

My resulting grid looks like this:

app.component.html:

<ag-grid-angular style="width: 500px; height: 115px;" class="ag-theme-fresh"
[rowData]="rowData"
[columnDefs]="columnDefs">
</ag-grid-angular>

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';

  public rowData = [
    { make: "Toyota", model: "Celica", price: 35000 },
    { make: "Ford", model: "Mondeo", price: 32000 },
    { make: "Porsche", model: "Boxter", price: 72000 }
  ]

  public columnDefs = [
    { headerName: "Make", field: "make" },
    { headerName: "Model", field: "model" },
    { headerName: "Price", field: "price" }
  ]
}

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';

import { AgGridModule } from 'ag-grid-angular/main';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

What am I doing wrong? I can't see how I messed up styles or anything with this very simple example...

Body:
It turns out that the problems here were mostly style related. The fixed app can be seen here.

To get the grid I had to add the correct ag-grid styles into the angular-cli.json file:

  "styles": [
    "../node_modules/ag-grid/dist/styles/ag-grid.css",
    "../node_modules/ag-grid/dist/styles/theme-fresh.css"
  ]

I had to change the grid div to point to the correct style name:

<ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
[rowData]="rowData"
[columnDefs]="columnDefs"
</ag-grid-angular>

and to get the columns to display nicely I had to add an event listener:

<ag-grid-angular style="width: 500px; height: 115px;" class="ag-fresh"
[rowData]="rowData"
[columnDefs]="columnDefs"
(gridReady)="onGridReady($event)">
</ag-grid-angular>

and a handler:

  public onGridReady(params: any){
    params.api.sizeColumnsToFit();
  }

The ag-grid documentation mostly relies on you cloning a git-hub repo and running that. Where I work we can't access github and we only have limited access to npm so I had to try and add the grid to an existing project. There is no documentation that has what steps you need to do when you take this approach.


问:
WebApi 2: Custom HttpResponseMessage after handling OperationCanceledException in Message Handler is not returned to client
I am currently investigating in WebApi 2 Message Handler and how to implement a server side timeout using cancellation tokens. If a cancellation occurs a OperationCanceledException is thrown and handled in my Message Handler. In this case I return a HttpResponseMessage with a adequate HttpStatusCode (HttpStatusCode.RequestTimeout).
I expected that my consuming client (using postman) retrieves this HttpStatusCode, but instead "Could not get any response" is displayed, thus my client aborts without any additional information.  Could someone explain to me whats the deal with this behavior? What am I missing?

See following example code:

```<code>public class RequestTimeoutHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        TimeSpan timeout = TimeSpan.FromSeconds(10.0);
        using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource(timeout))
        using (CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token))
        {
            try
            {
                return await base.SendAsync(request, linkedCancellationTokenSource.Token);
            }
            catch (OperationCanceledException e)
            {
                return new HttpResponseMessage(HttpStatusCode.RequestTimeout);
            }
        }

        return null;
    }
}
</code>```

My Test Controller Method looks as follows:

```<code>    [Route("testTimeoutAsyncHandleException"), HttpPost]
    public IHttpActionResult TestTimeoutAsynchandle(string hugo, CancellationToken ct)
    {
        for (int i = 0; i < 500; i++)
        {
            Thread.Sleep(1000); //sleep 1 sec until exception is thown
            if (ct.IsCancellationRequested)
            {
                ct.ThrowIfCancellationRequested();
            }
        }

        return Ok("yes");
    }
</code>```

答: turns out, using postman was not my best idea. I created a console application using a httpclient and requested my test method. the httpstatus 408 is returned as expected. </p>

Body:
I am currently investigating in WebApi 2 Message Handler and how to implement a server side timeout using cancellation tokens. If a cancellation occurs a OperationCanceledException is thrown and handled in my Message Handler. In this case I return a HttpResponseMessage with a adequate HttpStatusCode (HttpStatusCode.RequestTimeout).
I expected that my consuming client (using postman) retrieves this HttpStatusCode, but instead "Could not get any response" is displayed, thus my client aborts without any additional information.  Could someone explain to me whats the deal with this behavior? What am I missing?

See following example code:

public class RequestTimeoutHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        TimeSpan timeout = TimeSpan.FromSeconds(10.0);
        using (CancellationTokenSource timeoutCancellationTokenSource = new CancellationTokenSource(timeout))
        using (CancellationTokenSource linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token))
        {
            try
            {
                return await base.SendAsync(request, linkedCancellationTokenSource.Token);
            }
            catch (OperationCanceledException e)
            {
                return new HttpResponseMessage(HttpStatusCode.RequestTimeout);
            }
        }

        return null;
    }
}

My Test Controller Method looks as follows:

    [Route("testTimeoutAsyncHandleException"), HttpPost]
    public IHttpActionResult TestTimeoutAsynchandle(string hugo, CancellationToken ct)
    {
        for (int i = 0; i < 500; i++)
        {
            Thread.Sleep(1000); //sleep 1 sec until exception is thown
            if (ct.IsCancellationRequested)
            {
                ct.ThrowIfCancellationRequested();
            }
        }

        return Ok("yes");
    }


答:
Your JSON is an array, meaning you'll have to point to the index of the object before accessing the property.

This code should work:

```<code>console.log(obj[0].name); //Returns "eng"
</code>```

If your JSON array was something like this:

```<code>[{"name":"eng","a":"sdf"}, {"name":"esp", "a":"abc"}]
</code>```

Then obj[1].name would return "esp".

Title: JSON.parse is an “undefined” object

Body:
Your JSON is an array, meaning you'll have to point to the index of the object before accessing the property.

This code should work:

console.log(obj[0].name); //Returns "eng"

If your JSON array was something like this:

[{"name":"eng","a":"sdf"}, {"name":"esp", "a":"abc"}]

Then obj[1].name would return "esp".


问:
Unclear relationship between pointer dereferencing and casting in a specific scenario
I have the following Cpp funtion:

```<code>u_long stringIpV4ToBinary(const char * ipv4)
{
    u_long * buff[1];
    int ret = InetPton(AF_INET, ipv4, &buff);
    if (ret == -1) return 1;
    if (ret == 0) return 1; // more handling needs to be added

// return ntohl(*buff[0]);           // crash, no warning
// return ntohl((*buff)[0]);         // same meaning above (??) crash, no warning
// return ntohl(**buff);             // crash, no warning
// return ntohl(*(buff[0]));         // crash, no warning
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl((u_long)buff[0]);    // works, but produces warnings:: 'type cast': truncation from 'u_long *' to 'u_long'
// return ntohl(*(u_long*)&buff);    // works
// return ntohl(*(u_long*)&buff[0]); // works
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl(*(u_long*)buff);     // works
}
</code>```

I have spent some time trying to extract the value of buff that I need to pass to ntohl() (so you can ignore the first couple of lines). I was playing around with *buff[0] *buff and others, w/o realizing that I need to cast the value of the first element of the array (&buff[0], buff or &buff).

Question: why do I need to cast the retrieved value to (u_long*) and then deference the pointer? Is it ambiguous or unclear to @ runtime that the value held in the buff[0] will be a of type u_long * ?  My expectation was that ntohl(**buff) - (buff is the array name, that decays into a pointer and since the array is of u_long pointers itself) double dereferencing should suffice.

答:
The parameter passed to ntohl should not need casting.

When parsing a IPv4 string address InetPton just needs an address in memory where it can write 4 bytes.

```<code>u_long addr; // 4 bytes on Windows
int ret = InetPton(AF_INET, ipv4, &addr);
if (ret == -1) return 1;
if (ret == 0) return 1; // more handling needs to be added

return ntohl(addr);
</code>```

Ideally you would use the IN_ADDR type instead but if you only care about Windows you can use the long based types directly.

Declaring a variable on the stack as a pointer (*) to something makes no sense when you need to store data in said variable, this is C 101.

Body:
I have the following Cpp funtion:

u_long stringIpV4ToBinary(const char * ipv4)
{
    u_long * buff[1];
    int ret = InetPton(AF_INET, ipv4, &buff);
    if (ret == -1) return 1;
    if (ret == 0) return 1; // more handling needs to be added

// return ntohl(*buff[0]);           // crash, no warning
// return ntohl((*buff)[0]);         // same meaning above (??) crash, no warning
// return ntohl(**buff);             // crash, no warning
// return ntohl(*(buff[0]));         // crash, no warning
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl((u_long)buff[0]);    // works, but produces warnings:: 'type cast': truncation from 'u_long *' to 'u_long'
// return ntohl(*(u_long*)&buff);    // works
// return ntohl(*(u_long*)&buff[0]); // works
// return ntohl(*(u_long*)buff[0]);  // crash, no warning
// return ntohl(*(u_long*)buff);     // works
}

I have spent some time trying to extract the value of buff that I need to pass to ntohl() (so you can ignore the first couple of lines). I was playing around with *buff[0] *buff and others, w/o realizing that I need to cast the value of the first element of the array (&buff[0], buff or &buff).

Question: why do I need to cast the retrieved value to (u_long*) and then deference the pointer? Is it ambiguous or unclear to @ runtime that the value held in the buff[0] will be a of type u_long * ?  My expectation was that ntohl(**buff) - (buff is the array name, that decays into a pointer and since the array is of u_long pointers itself) double dereferencing should suffice.

Body:
The parameter passed to ntohl should not need casting.

When parsing a IPv4 string address InetPton just needs an address in memory where it can write 4 bytes.

u_long addr; // 4 bytes on Windows
int ret = InetPton(AF_INET, ipv4, &addr);
if (ret == -1) return 1;
if (ret == 0) return 1; // more handling needs to be added

return ntohl(addr);

Ideally you would use the IN_ADDR type instead but if you only care about Windows you can use the long based types directly.

Declaring a variable on the stack as a pointer (*) to something makes no sense when you need to store data in said variable, this is C 101.


问:
MS Access Form: Use value of first Combobox to filter options of second Combobox?
As an example, let's use food.

Table: Food

```<code>  ID  ||   Type   ||  Name
   1  ||   Fruit  ||  Apple
   2  ||   Fruit  ||  Orange
   3  ||   Veggie ||  Pea
   4  ||   Veggie ||  Corn
</code>```

Combobox 1: TypeCB

Row Source (SQL):

```<code>SELECT DISTINCT
    Count([Food].ID) AS CountOfID,
    [Food].Type
FROM [Food]
ORDER BY [Food].Type;
</code>```

(The reason I use "CountofID" is the get the unique Type values, otherwise they're repeated since the ID's are unique)

Now this works perfectly for the first, however, when I try to pull the value over to my next ComboBox, it the second combobox remains empty. Refreshing the Form with the first combobox filled doesn't fix it.

Combobox 2: NameCB

Row Source (SQL):

```<code>SELECT
    Count([Food].ID) AS CountOfID,
    [Food].Name
FROM [Food]
HAVING ((([Food].Type)=[Forms]![Food Form]![TypeCB].[SelText]));
</code>```

Is there another/a better way to grab this data?

答:
You don't need Count in the Row Source of your TypeCB because you're only using the Type column. If you leave it in, be sure the Bound Column property of TypeCB is set to 2 so the value of the combo box will pick up from the Type column rather than CountOfID.

Your NameCB Row Source is OK, except for the [SelText] property. Change it:

```<code>  SELECT
      Count([Food].ID) AS CountOfID,
      [Food].Name
  FROM [Food]
  HAVING ((([Food].Type)=[Forms]![Food Form]![TypeCB]));
</code>```

If the Bound Column property of your TypeCB combo box is set to the column with the Type value, you can reference the control itself to get the value.

In the After Update event of the TypeCB combo box, add NameCB.Requery() to refresh the NameCB combo box.

Body:
As an example, let's use food.

Table: Food

  ID  ||   Type   ||  Name
   1  ||   Fruit  ||  Apple
   2  ||   Fruit  ||  Orange
   3  ||   Veggie ||  Pea
   4  ||   Veggie ||  Corn

Combobox 1: TypeCB

Row Source (SQL):

SELECT DISTINCT
    Count([Food].ID) AS CountOfID,
    [Food].Type
FROM [Food]
ORDER BY [Food].Type;

(The reason I use "CountofID" is the get the unique Type values, otherwise they're repeated since the ID's are unique)

Now this works perfectly for the first, however, when I try to pull the value over to my next ComboBox, it the second combobox remains empty. Refreshing the Form with the first combobox filled doesn't fix it.

Combobox 2: NameCB

Row Source (SQL):

SELECT
    Count([Food].ID) AS CountOfID,
    [Food].Name
FROM [Food]
HAVING ((([Food].Type)=[Forms]![Food Form]![TypeCB].[SelText]));

Is there another/a better way to grab this data?

Body:
You don't need Count in the Row Source of your TypeCB because you're only using the Type column. If you leave it in, be sure the Bound Column property of TypeCB is set to 2 so the value of the combo box will pick up from the Type column rather than CountOfID.

Your NameCB Row Source is OK, except for the [SelText] property. Change it:

  SELECT
      Count([Food].ID) AS CountOfID,
      [Food].Name
  FROM [Food]
  HAVING ((([Food].Type)=[Forms]![Food Form]![TypeCB]));

If the Bound Column property of your TypeCB combo box is set to the column with the Type value, you can reference the control itself to get the value.

In the After Update event of the TypeCB combo box, add NameCB.Requery() to refresh the NameCB combo box.


问:
Trying to get a property of a none object on laravel relationship belongsTo and hasMany

I get null when trying to get posts associated with the user.

答:
$user->posts isn't defined. add this to your user Model:

```<code>class User extends Model {
    public function posts(){
        return $this->hasMany(Post::class);
    }
}
</code>```

perhaps you have to load the posts after creating user $user->load('posts');

Body:
$user->posts isn't defined. add this to your user Model:

class User extends Model {
    public function posts(){
        return $this->hasMany(Post::class);
    }
}

perhaps you have to load the posts after creating user $user->load('posts');


问:
How do I programmatically scroll a winforms datagridview control?
I'm implementing some drag drop features in one my controls inheriting from a datagridview. Basically I'm dragging a row from somewhere in the DGV and dropping it somewhere else, reordering the rows. I've run into a problem though. If the DGV is too large such that there's a scrollbar, how can I have the DGV scroll up or down while the user is in the middle of a dragdrop?

I know how to get the current mouse position and also get the position of the dgv rectangle and such. So, I can easily find out if i'm in the top or bottom half of the rectangle... I just need a way to programmatically scroll the dgv. I'd prefer if I don't have to keep changing the selected cell to do this.

Any suggestions?

Thanks

Isaac

答: You need to implement the DragOver event.  Check if the mouse is located close to the top or the bottom of the control (use PointToClient).  When it is, enable a timer with an interval of ~200 msec.  In the Tick event handler scroll the DGV by a row.  Disable the timer when the mouse isn't close and after DoDragDrop returns.  The user can now easily and intuitively scroll the grid just be hovering near the ends.</p>


问:
Use of 'sys.sp_sequence_get_range' in Table Value Function
Situation/Goal:

I have 3 integer sequences from 1 to [INT_MAX] (SEQ_A, SEQ_B, SEQ_C) and I wanted to write a table value function to get a range of numbers from either sequence.

This is the Code I came up with:

```<code>CREATE FUNCTION [dbo].[GetSequenceNumber]
(
    @TabelField VARCHAR(256),
    @Range INT
)
RETURNS @RETVALTABLE TABLE
(
    SEQUENCE_NUMBER INT
)
AS
BEGIN

    IF(ISNULL(@Range, 0) <= 0 OR @TabelField IS NULL)
        RETURN;

    DECLARE @FirstSeqNum sql_variant;
    DECLARE @LastSeqNum sql_variant;
    DECLARE @FirstSequenceNumber as INT;
    DECLARE @LastSequenceNumber as INT;

    IF @TabelField = 'FIELD_A' BEGIN
        EXEC sys.sp_sequence_get_range N'SEQ_A', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT;
        SET @FirstSequenceNumber = CONVERT(INT, @FirstSeqNum);
        SET @LastSequenceNumber = CONVERT(INT, @LastSeqNum);

        WHILE @FirstSequenceNumber <= @LastSequenceNumber BEGIN
            INSERT INTO @RETVALTABLE SELECT @FirstSequenceNumber;
            SET @FirstSequenceNumber += 1;
        END
    END

    ELSE IF @TabelField = 'FIELD_B' BEGIN
        EXEC sys.sp_sequence_get_range N'SEQ_B', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT;
        SET @FirstSequenceNumber = CONVERT(INT, @FirstSeqNum);
        SET @LastSequenceNumber = CONVERT(INT, @LastSeqNum);

        WHILE @FirstSequenceNumber <= @LastSequenceNumber BEGIN
            INSERT INTO @RETVALTABLE SELECT @FirstSequenceNumber;
            SET @FirstSequenceNumber += 1;
        END
    END

    ELSE IF @TabelField = 'FIELD_C' BEGIN
        EXEC sys.sp_sequence_get_range N'SEQ_C', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT;
        SET @FirstSequenceNumber = CONVERT(INT, @FirstSeqNum);
        SET @LastSequenceNumber = CONVERT(INT, @LastSeqNum);

        WHILE @FirstSequenceNumber <= @LastSequenceNumber BEGIN
            INSERT INTO @RETVALTABLE SELECT @FirstSequenceNumber;
            SET @FirstSequenceNumber += 1;
        END
    END

    RETURN
END
</code>```

Why am I doing this:

I want all the numbers from a specific range, preferably as a table
(unlike sys.sp_sequence_get_range which just gives you the first and
the last number)

I do not care about the name of the sequences, I just "tell" the table function for which field I want numbers

I could do some additional checks before inserting the sequence number in @RETVALTABLE (and skipe some numbers for example).

Problem:

I can create the function, I can alter it, but I can not execute it.
When I am calling the function I always get the error:
"Only functions and certain extended stored procedures can be executed within a function."

Well, the error is very self explaining and the problem probably is the EXEC sys.sp_sequence_get_range N'SEQ_X', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT; part.

Question:

How do I get rid of the error? Is there a better way to achieve the goal than with a table value function?

Top priority here is to get all the numbers from a certain range from a certain sequence (and not just the start and end point).

(Solution should be available for Microsoft SQL Server 2012 and higher)

答:
Without getting into the call to the sproc (which MSSQL started yelling about immediately and didn't stop (OUTPUT keyword, calling proc inside function, something), I think I've got you here.

This code will return you the values in the range without actually incrementing the sequence(though the method is iterative rather than set-based. I'm going to try to set-base it now):

```<code>CREATE FUNCTION dbo.GetSeqRange(@seqname VARCHAR(MAX), @start INT, @end INT)
    RETURNS @ReturnTable TABLE (
        ReturnValue INT
    )
AS
BEGIN
DECLARE @increment INT = (SELECT CONVERT(INT, increment) FROM sys.sequences WHERE [name] = @seqname)
DECLARE @i INT = @start
WHILE @i <= @end
BEGIN
    INSERT @ReturnTable VALUES(@i)
    SET @i += @increment
END
    RETURN
END
</code>```

To increment the sequence, you'd replace the inside of the WHILE block with SELECT NEXT VALUE FOR <seqname> and insert those into the result table. Let me know if that helps! Or if I misunderstood you then I'll modify.

Body:
Situation/Goal:

I have 3 integer sequences from 1 to [INT_MAX] (SEQ_A, SEQ_B, SEQ_C) and I wanted to write a table value function to get a range of numbers from either sequence.

This is the Code I came up with:

CREATE FUNCTION [dbo].[GetSequenceNumber]
(
    @TabelField VARCHAR(256),
    @Range INT
)
RETURNS @RETVALTABLE TABLE
(
    SEQUENCE_NUMBER INT
)
AS
BEGIN

    IF(ISNULL(@Range, 0) <= 0 OR @TabelField IS NULL)
        RETURN;

    DECLARE @FirstSeqNum sql_variant;
    DECLARE @LastSeqNum sql_variant;
    DECLARE @FirstSequenceNumber as INT;
    DECLARE @LastSequenceNumber as INT;

    IF @TabelField = 'FIELD_A' BEGIN
        EXEC sys.sp_sequence_get_range N'SEQ_A', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT;
        SET @FirstSequenceNumber = CONVERT(INT, @FirstSeqNum);
        SET @LastSequenceNumber = CONVERT(INT, @LastSeqNum);

        WHILE @FirstSequenceNumber <= @LastSequenceNumber BEGIN
            INSERT INTO @RETVALTABLE SELECT @FirstSequenceNumber;
            SET @FirstSequenceNumber += 1;
        END
    END

    ELSE IF @TabelField = 'FIELD_B' BEGIN
        EXEC sys.sp_sequence_get_range N'SEQ_B', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT;
        SET @FirstSequenceNumber = CONVERT(INT, @FirstSeqNum);
        SET @LastSequenceNumber = CONVERT(INT, @LastSeqNum);

        WHILE @FirstSequenceNumber <= @LastSequenceNumber BEGIN
            INSERT INTO @RETVALTABLE SELECT @FirstSequenceNumber;
            SET @FirstSequenceNumber += 1;
        END
    END

    ELSE IF @TabelField = 'FIELD_C' BEGIN
        EXEC sys.sp_sequence_get_range N'SEQ_C', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT;
        SET @FirstSequenceNumber = CONVERT(INT, @FirstSeqNum);
        SET @LastSequenceNumber = CONVERT(INT, @LastSeqNum);

        WHILE @FirstSequenceNumber <= @LastSequenceNumber BEGIN
            INSERT INTO @RETVALTABLE SELECT @FirstSequenceNumber;
            SET @FirstSequenceNumber += 1;
        END
    END

    RETURN
END

Why am I doing this:

I want all the numbers from a specific range, preferably as a table
(unlike sys.sp_sequence_get_range which just gives you the first and
the last number)

I do not care about the name of the sequences, I just "tell" the table function for which field I want numbers

I could do some additional checks before inserting the sequence number in @RETVALTABLE (and skipe some numbers for example).

Problem:

I can create the function, I can alter it, but I can not execute it.
When I am calling the function I always get the error:
"Only functions and certain extended stored procedures can be executed within a function."

Well, the error is very self explaining and the problem probably is the EXEC sys.sp_sequence_get_range N'SEQ_X', @Range, @FirstSeqNum OUTPUT, @LastSeqNum OUTPUT; part.

Question:

How do I get rid of the error? Is there a better way to achieve the goal than with a table value function?

Top priority here is to get all the numbers from a certain range from a certain sequence (and not just the start and end point).

(Solution should be available for Microsoft SQL Server 2012 and higher)

Body:
Without getting into the call to the sproc (which MSSQL started yelling about immediately and didn't stop (OUTPUT keyword, calling proc inside function, something), I think I've got you here.

This code will return you the values in the range without actually incrementing the sequence(though the method is iterative rather than set-based. I'm going to try to set-base it now):

CREATE FUNCTION dbo.GetSeqRange(@seqname VARCHAR(MAX), @start INT, @end INT)
    RETURNS @ReturnTable TABLE (
        ReturnValue INT
    )
AS
BEGIN
DECLARE @increment INT = (SELECT CONVERT(INT, increment) FROM sys.sequences WHERE [name] = @seqname)
DECLARE @i INT = @start
WHILE @i <= @end
BEGIN
    INSERT @ReturnTable VALUES(@i)
    SET @i += @increment
END
    RETURN
END

To increment the sequence, you'd replace the inside of the WHILE block with SELECT NEXT VALUE FOR <seqname> and insert those into the result table. Let me know if that helps! Or if I misunderstood you then I'll modify.


问:
Getting Error on StandardScalar Fit_Transform
```<code> import numpy as np
 import matplotlib.pyplot as plt
 import pandas as pd

 dataset = pd.read_csv('Position_Salaries.csv')
 X = dataset.iloc[:, 1:2].values
 y = dataset.iloc[:, 2].values

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)
</code>```

Ok so here is the problem.
both X and y are single feature and have one column. As you can see X is a matrix. and y is a vector
     X = dataset.iloc[:, 1:2].values
     y = dataset.iloc[:, 2].values

Now when I run y = sc_y.fit_transform(y) I get the error that it is a 1D array. And if i change y = dataset.iloc[:, 2:3].values making it a 2D array.
But I want it to stay as 1D array since its the dependent variable and want it to stay that way. Also i solved earlier different examples where I had to rescale similar data, and it did not give me this kind of error. Not sure why it is giving me now. Moreover i am watching a video while coding and in the video everything is the same but he doesn't get any error.

答:
You can use flatten to get a 1D array from the 2D array:

```<code>y.flatten()
</code>```

Body:
 import numpy as np
 import matplotlib.pyplot as plt
 import pandas as pd

 dataset = pd.read_csv('Position_Salaries.csv')
 X = dataset.iloc[:, 1:2].values
 y = dataset.iloc[:, 2].values

from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)

Ok so here is the problem.
both X and y are single feature and have one column. As you can see X is a matrix. and y is a vector
     X = dataset.iloc[:, 1:2].values
     y = dataset.iloc[:, 2].values

Now when I run y = sc_y.fit_transform(y) I get the error that it is a 1D array. And if i change y = dataset.iloc[:, 2:3].values making it a 2D array.
But I want it to stay as 1D array since its the dependent variable and want it to stay that way. Also i solved earlier different examples where I had to rescale similar data, and it did not give me this kind of error. Not sure why it is giving me now. Moreover i am watching a video while coding and in the video everything is the same but he doesn't get any error.

Body:
You can use flatten to get a 1D array from the 2D array:

y.flatten()


问:
Google Font Rendering Issues? Roboto
Has anyone ran into any rendering issues with Roboto?  I'm having an issues on some mobile devices where the "s" and "t" and rendering together.

Any suggestions on how to correct the issue?

答:
just put this on your CSS </p>

```<code>font-variant-ligatures: no-common-ligatures;
</code>```

Title: Google Font Rendering Issues? Roboto

Body:
just put this on your CSS

font-variant-ligatures: no-common-ligatures;


问:
Read / Write only own records on Firestore
I am rather lost with Firestore Rules.

I want authenticated users to be able to read their own records, but cannot manage to achieve that. I am writing the userId into each record. When reading, I expect the user will get all records where field userId == request.auth.uid Here is my code from the Firestore console:

```<code>service cloud.firestore {
  match /databases/{database}/documents {
      match /{document=**} {
          allow read: if resource.data.userId == request.auth.uid;
      }
  }
  match /databases/{database}/documents {
    match /{document=**} {
        allow write: if request.auth.uid != null;
    }
  }
}
</code>```

Writing is OK, but with reading I get "missing or insufficient permissions" exception in my app. I checked that FirebaseAuth.getInstance().getUid() is returning a value matching to my userId field.

答:
According to Todd Kerpelman
Cloud Firestore doesn't have the time to search through every record in your database to ensure that your user has access, so it will reject this query. Instead, you'd need to run a query where Cloud Firestore can "prove" that all documents you'd retrieve will be valid.

Solution:

Try with this query, specifying that you want to receive only the user's documents:

```<code>FirebaseFirestore.getInstance().collection("docs").whereEqualTo("userId", uid )
</code>```

where uid is the uid of your auth user:

```<code>String uid = FirebaseAuth.getInstance().currentUser.getUid()
</code>```

Body:
I am rather lost with Firestore Rules.

I want authenticated users to be able to read their own records, but cannot manage to achieve that. I am writing the userId into each record. When reading, I expect the user will get all records where field userId == request.auth.uid Here is my code from the Firestore console:

service cloud.firestore {
  match /databases/{database}/documents {
      match /{document=**} {
          allow read: if resource.data.userId == request.auth.uid;
      }
  }
  match /databases/{database}/documents {
    match /{document=**} {
        allow write: if request.auth.uid != null;
    }
  }
}

Writing is OK, but with reading I get "missing or insufficient permissions" exception in my app. I checked that FirebaseAuth.getInstance().getUid() is returning a value matching to my userId field.

Body:
According to Todd Kerpelman
Cloud Firestore doesn't have the time to search through every record in your database to ensure that your user has access, so it will reject this query. Instead, you'd need to run a query where Cloud Firestore can "prove" that all documents you'd retrieve will be valid.

Solution:

Try with this query, specifying that you want to receive only the user's documents:

FirebaseFirestore.getInstance().collection("docs").whereEqualTo("userId", uid )

where uid is the uid of your auth user:

String uid = FirebaseAuth.getInstance().currentUser.getUid()


问:
Acumatica Report Designer - join on TOP 1
What would be a good way to join on topmost record in acumatica report designer. I'm thinking in terms of DAC views but it is not helping much. So we have two tables and I would like to join on SELECT TOP 1 * from Table.</p>

答: Create an View in sql ("select top 1 ..."), create a DAC for that view, then join in report designer on that sql view. </p>


问:
Python Matplotlib creating a custom colour scale
I have created a map of precipitation levels in a region based on precipitation data from NetCDF files. I would like to add a custom scale such that if precipitation is less than 800mm it would be one colour, 800-1000mm another, etc. Similar to the map found here: http://www.metmalawi.com/climate/climate.php

At the moment I am using a gradient scale but it isn't showing the detail I need. This is the code for the plot at the moment (where 'Average' is my data that I have already formatted).

```<code>    #load color palette
    colourA = mpl_cm.get_cmap('BuPu')

    #plot map with physical features
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.add_feature(cartopy.feature.BORDERS)
    ax.add_feature(cartopy.feature.LAKES, alpha=0.5)
    ax.add_feature(cartopy.feature.RIVERS)

    #set map boundary
    ax.set_extent([32.5, 36., -9, -17])

    #set axis tick marks
    ax.set_xticks([33, 34, 35])
    ax.set_yticks([-10, -12, -14, -16])
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)

    #plot data and set colour range
    plot = iplt.contourf(Average, cmap=colourA, levels=np.arange(0,15500,500), extend='both')

    #add colour bar index and a label
    plt.colorbar(plot, label='mm per year')

    #give map a title
    plt.title('Pr 1990-2008 - Average_ERAINT ', fontsize=10)

    #save the image of the graph and include full legend
    plt.savefig('ERAINT_Average_Pr_MAP_Annual', bbox_inches='tight')

    plt.show()
</code>```

Anyone know how I can do this?

Thank you!

答:
This is a matplotlib question disguised as an Iris question as the issue has appeared via Iris plotting routines, but to answer this we need only a couple of matplotlib commands. As such, I'm basing this answer on this matplotlib gallery example. These are levels (containing values for the upper bound of each contour) and colors (specifying the colours to shade each contour). It's best if there are the same number of levels and colours.

To demonstrate this, I put the following example together. Given that there's no sample data provided, I made my own trigonometric data. The levels are based on the trigonometric data values, so do not reflect the levels required in the question, but could be changed to the original levels. The colours used are the hex values of the levels specified by image in the link in the question.

The code:

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-25, 25)
y = np.arange(-20, 20)
x2d, y2d = np.meshgrid(x, y)
vals = (3 * np.cos(x2d)) + (2 * np.sin(y2d))

colours = ['#bf8046', '#df9f24', '#e0de30', '#c1de2d', '#1ebf82',
           '#23de27', '#1dbe20', '#11807f', '#24607f', '#22427e']
levels = range(-5, 6)

plt.contourf(vals, levels=levels, colors=colours)
plt.colorbar()
plt.show()
</code>```

The produced image:

Colours could also be selected from a colormap (one way of doing this is shown in this StackOverflow answer). There are also other ways, including in the matplotlib gallery example linked above. Given, though, that the sample map linked in the question had specific colours I chose to use those colours directly.

Body:
I have created a map of precipitation levels in a region based on precipitation data from NetCDF files. I would like to add a custom scale such that if precipitation is less than 800mm it would be one colour, 800-1000mm another, etc. Similar to the map found here: http://www.metmalawi.com/climate/climate.php

At the moment I am using a gradient scale but it isn't showing the detail I need. This is the code for the plot at the moment (where 'Average' is my data that I have already formatted).

    #load color palette
    colourA = mpl_cm.get_cmap('BuPu')

    #plot map with physical features
    ax = plt.axes(projection=cartopy.crs.PlateCarree())
    ax.add_feature(cartopy.feature.COASTLINE)
    ax.add_feature(cartopy.feature.BORDERS)
    ax.add_feature(cartopy.feature.LAKES, alpha=0.5)
    ax.add_feature(cartopy.feature.RIVERS)

    #set map boundary
    ax.set_extent([32.5, 36., -9, -17])

    #set axis tick marks
    ax.set_xticks([33, 34, 35])
    ax.set_yticks([-10, -12, -14, -16])
    lon_formatter = LongitudeFormatter(zero_direction_label=True)
    lat_formatter = LatitudeFormatter()
    ax.xaxis.set_major_formatter(lon_formatter)
    ax.yaxis.set_major_formatter(lat_formatter)

    #plot data and set colour range
    plot = iplt.contourf(Average, cmap=colourA, levels=np.arange(0,15500,500), extend='both')

    #add colour bar index and a label
    plt.colorbar(plot, label='mm per year')

    #give map a title
    plt.title('Pr 1990-2008 - Average_ERAINT ', fontsize=10)

    #save the image of the graph and include full legend
    plt.savefig('ERAINT_Average_Pr_MAP_Annual', bbox_inches='tight')

    plt.show()

Anyone know how I can do this?

Thank you!

Body:
This is a matplotlib question disguised as an Iris question as the issue has appeared via Iris plotting routines, but to answer this we need only a couple of matplotlib commands. As such, I'm basing this answer on this matplotlib gallery example. These are levels (containing values for the upper bound of each contour) and colors (specifying the colours to shade each contour). It's best if there are the same number of levels and colours.

To demonstrate this, I put the following example together. Given that there's no sample data provided, I made my own trigonometric data. The levels are based on the trigonometric data values, so do not reflect the levels required in the question, but could be changed to the original levels. The colours used are the hex values of the levels specified by image in the link in the question.

The code:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-25, 25)
y = np.arange(-20, 20)
x2d, y2d = np.meshgrid(x, y)
vals = (3 * np.cos(x2d)) + (2 * np.sin(y2d))

colours = ['#bf8046', '#df9f24', '#e0de30', '#c1de2d', '#1ebf82',
           '#23de27', '#1dbe20', '#11807f', '#24607f', '#22427e']
levels = range(-5, 6)

plt.contourf(vals, levels=levels, colors=colours)
plt.colorbar()
plt.show()

The produced image:

Colours could also be selected from a colormap (one way of doing this is shown in this StackOverflow answer). There are also other ways, including in the matplotlib gallery example linked above. Given, though, that the sample map linked in the question had specific colours I chose to use those colours directly.


问:
Java NullPointerException Getting Resources
I am writing a simple Android application (which is mainly for me to test whatever I may need to use in a real app) and I need to use a MediaPlayer to play a sound. In this case, I'm using kalimba.mp3 (no capital letters). But when I try to run the app, it instantly crashes because of a null object reference. The error is below, as is my code. The problem is, I don't see a problem with anything, and it gives me no errors while editing my code. How do I stop this from throwing an error? I've never used a MediaPlayer before. Thanks in advance!

Code:

```<code>// Player of "kalimba.mp3"
private MediaPlayer kalimbaPlayer = MediaPlayer.create(this, R.raw.kalimba);

// Play/stop the sound
public void playSound(View view) { kalimbaPlayer.start(); }
public void stopSound(View view) { kalimbaPlayer.stop(); kalimbaPlayer.release(); }
</code>```

Error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
</code>```

答:
create Global variable in your class

```<code> public Resources mRes;
</code>```

After this

```<code> @Override
Oncreate(Bundle saveInstance){
mRes = getActivity().getResources();
}
</code>```

Now user mRes object to get resource....
For example

mRes.getString(R.string.SEARCH);

Body:
I am writing a simple Android application (which is mainly for me to test whatever I may need to use in a real app) and I need to use a MediaPlayer to play a sound. In this case, I'm using kalimba.mp3 (no capital letters). But when I try to run the app, it instantly crashes because of a null object reference. The error is below, as is my code. The problem is, I don't see a problem with anything, and it gives me no errors while editing my code. How do I stop this from throwing an error? I've never used a MediaPlayer before. Thanks in advance!

Code:

// Player of "kalimba.mp3"
private MediaPlayer kalimbaPlayer = MediaPlayer.create(this, R.raw.kalimba);

// Play/stop the sound
public void playSound(View view) { kalimbaPlayer.start(); }
public void stopSound(View view) { kalimbaPlayer.stop(); kalimbaPlayer.release(); }

Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

Body:
create Global variable in your class

 public Resources mRes;

After this

 @Override
Oncreate(Bundle saveInstance){
mRes = getActivity().getResources();
}

Now user mRes object to get resource....
For example

mRes.getString(R.string.SEARCH);