问:
read a websites html code, then select an element and then make an action on that element
I want to know how Read a websites html code. Then i want to take a specific Element from the html code and make a request to make an action to the Element(e.g. Button,Textfield)

For example i take a websites URL, read the html code,take the element a button and then press the button from my Flutter App.

答:
Web Crawlers/Scrapers only works on mobile clients (or website with CORS enable).

You need to add the following libraries http and html inside your pubspec.yaml:

```<code>html: ^0.14.0+3
http: ^0.12.0+4

// latest versions by Feb 18th 2020
</code>```

to use it, create an async method to fetch the URL you want to "read":

```<code>Future<Response> _initiate(String url) async {
    Response response = await get(url);
    return response;
}
</code>```

and then, use it this way, reading the specific div, a, img, etc you need:

```<code>_initiate(url).then((response) {
      var document = parse(response.body);
      var items = document.querySelector('div.groupHomeHeader-banner');
      var split = items.attributes.values.toList()[1].split('(')[1];
      var image = split.substring(0, split.indexOf(')'));
      var name = document.querySelector('a.groupHomeHeader-groupNameLink');
});
</code>```

Every Element has different attributes. For example, an InputElement has the attribute 'click()' and creates the desire effect.

Example of this will be:

```<code>var openDoc = document.querySelector('div.pdfInput') as InputElement;
openDoc.click();
</code>```

Body:
Web Crawlers/Scrapers only works on mobile clients (or website with CORS enable).

You need to add the following libraries http and html inside your pubspec.yaml:

html: ^0.14.0+3
http: ^0.12.0+4

// latest versions by Feb 18th 2020

to use it, create an async method to fetch the URL you want to "read":

Future<Response> _initiate(String url) async {
    Response response = await get(url);
    return response;
}

and then, use it this way, reading the specific div, a, img, etc you need:

_initiate(url).then((response) {
      var document = parse(response.body);
      var items = document.querySelector('div.groupHomeHeader-banner');
      var split = items.attributes.values.toList()[1].split('(')[1];
      var image = split.substring(0, split.indexOf(')'));
      var name = document.querySelector('a.groupHomeHeader-groupNameLink');
});

Every Element has different attributes. For example, an InputElement has the attribute 'click()' and creates the desire effect.

Example of this will be:

var openDoc = document.querySelector('div.pdfInput') as InputElement;
openDoc.click();


来源: stackexchange

问:
Sticking Elements (Sub Menu) on web page issue
I'm trying to create a sub-menu on my website. I have the menu created, but I want it to stick; its primary purpose would be to link to other parts of the same page, but when I scroll the menu gets left behind.

I built the menu using The Jupiter plugin. We already have a universal navigation bar across all pages, and this sticks to the top always.

My question is: how can I make it stick as I scroll down the page?

I'm using WordPress Bakery aswell. I can provide screenshots or more info if needed.

Thanks!

答:
Have you tried using position:sticky in the CSS?

https://css-tricks.com/position-sticky-2/

ContentLicense: CC BY-SA 4.0


问:
ViewModel onchange gets called multiple times when back from Fragment
I am working with Android architecture components.
What i want is when user type "0" in Edittext and click on Button to replace Fragment with new one , and if type anything else post Toast error message. In  Problem is when i back from new Fragment(BlankFragment) and click on button again and type "0" again and click, onchange() is called multiple times so  Fragment is get created multiple times

FragmentExample.class:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        manager = getActivity().getSupportFragmentManager();
        viewmModel = ViewModelProviders.of(getActivity(), viewModelFactory)
                .get(VModel.class);

        View v = inflater.inflate(R.layout.fragment_list, container, false);
        b = (Button) v.findViewById(R.id.b);
        et = (EditText) v.findViewById(R.id.et);

        viewmModel.observeData().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {

                if(s.equals("0")) {
                    BlankFragment fragment = (BlankFragment) manager.findFragmentByTag(DETAIL_FRAG);
                    if (fragment == null) {
                        fragment = BlankFragment.newInstance();
                    }
                    addFragmentToActivity(manager,
                            fragment,
                            R.id.root_activity_detail,
                            DETAIL_FRAG
                    );
                } else {
                    Toast.makeText(getContext(), "Wrong text", Toast.LENGTH_SHORT).show();
                }
            }
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewmModel.setData(et.getText().toString());
            }
        });
        return v;
    }
    private void addFragmentToActivity(FragmentManager fragmentManager, BlankFragment fragment, int root_activity_detail, String detailFrag) {
        android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(root_activity_detail, fragment, detailFrag).addToBackStack(detailFrag);
        transaction.commit();
    }
```

<p>Repository class:</p>

<pre class="lang-java prettyprint-override"><code>
    public class Repository {
    MutableLiveData<String> dataLive = new MutableLiveData<>();

    public Repository() {

    }

    public void setListData(String data) {
       dataLive.setValue(data);
    }

    public MutableLiveData<String> getData() {
        return dataLive;
    }
}
</code>```

BlankFragment.class:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
                .get(VModel.class);
        listItemViewModel.setData("");
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }
```

答:
Here is an example how i solve this problem .<strong>[TESTED AND WORKING]</strong>   </p>

```<code> viewModel.getLoginResponse().observe(getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(String response) {
            if(getViewLifecycleOwner().getLifecycle().getCurrentState()== Lifecycle.State.RESUMED){
                // your code here ...
            }

        }
    });
</code>```

Body:
I am working with Android architecture components.
What i want is when user type "0" in Edittext and click on Button to replace Fragment with new one , and if type anything else post Toast error message. In  Problem is when i back from new Fragment(BlankFragment) and click on button again and type "0" again and click, onchange() is called multiple times so  Fragment is get created multiple times

FragmentExample.class:

     @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        manager = getActivity().getSupportFragmentManager();
        viewmModel = ViewModelProviders.of(getActivity(), viewModelFactory)
                .get(VModel.class);

        View v = inflater.inflate(R.layout.fragment_list, container, false);
        b = (Button) v.findViewById(R.id.b);
        et = (EditText) v.findViewById(R.id.et);

        viewmModel.observeData().observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {

                if(s.equals("0")) {
                    BlankFragment fragment = (BlankFragment) manager.findFragmentByTag(DETAIL_FRAG);
                    if (fragment == null) {
                        fragment = BlankFragment.newInstance();
                    }
                    addFragmentToActivity(manager,
                            fragment,
                            R.id.root_activity_detail,
                            DETAIL_FRAG
                    );
                } else {
                    Toast.makeText(getContext(), "Wrong text", Toast.LENGTH_SHORT).show();
                }
            }
        });

        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewmModel.setData(et.getText().toString());
            }
        });
        return v;
    }
    private void addFragmentToActivity(FragmentManager fragmentManager, BlankFragment fragment, int root_activity_detail, String detailFrag) {
        android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(root_activity_detail, fragment, detailFrag).addToBackStack(detailFrag);
        transaction.commit();
    }

Repository class:

    public class Repository {
    MutableLiveData<String> dataLive = new MutableLiveData<>();

    public Repository() {

    }

    public void setListData(String data) {
       dataLive.setValue(data);
    }

    public MutableLiveData<String> getData() {
        return dataLive;
    }
}

BlankFragment.class:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        listItemViewModel = ViewModelProviders.of(this, viewModelFactory)
                .get(VModel.class);
        listItemViewModel.setData("");
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

Body:
Here is an example how i solve this problem .[TESTED AND WORKING]

 viewModel.getLoginResponse().observe(getViewLifecycleOwner(), new Observer<String>() {
        @Override
        public void onChanged(String response) {
            if(getViewLifecycleOwner().getLifecycle().getCurrentState()== Lifecycle.State.RESUMED){
                // your code here ...
            }

        }
    });


Title: How to insert a series of numbers into a matrix?

Body:
As an example, I have a 9x9 matrix:

x=[
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
]

and I want to insert a series of numbers like the example:

aux=900000001051200030000980000680740000730000908010058670008100000002007090190004060

I want to be able to put each digit into an individual position of the matrix, but I am a little stuck on attacking this problem.

Body:
The following code by using Python 3.7 will do the job for you:

if __name__ == "__main__":
    # size of the array n x n
    n = 9

    # the n x n array
    x = [[0]*n]*n

    # the input number converted as a string
    aux = "900000001051200030000980000680740000730000908010058670008100000002007090190004060"

    k = 0
    for i in range(0,n):
        for j in range(0,n):
            x[i][j] = aux[k]
            k = k + 1

then for printing the matrix x you do:

import numpy as np

# print the modified array x
print(np.matrix(x))

which gives the output:

[['9' '0' '0' '0' '0' '0' '0' '0' '1']
 ['0' '5' '1' '2' '0' '0' '0' '3' '0']
 ['0' '0' '0' '9' '8' '0' '0' '0' '0']
 ['6' '8' '0' '7' '4' '0' '0' '0' '0']
 ['7' '3' '0' '0' '0' '0' '9' '0' '8']
 ['0' '1' '0' '0' '5' '8' '6' '7' '0']
 ['0' '0' '8' '1' '0' '0' '0' '0' '0']
 ['0' '0' '2' '0' '0' '7' '0' '9' '0']
 ['1' '9' '0' '0' '0' '4' '0' '6' '0']]


问:
How can you find the number of occurrences of a particular character in a string using sql?
How can you find the number of occurrences of a particular character in a string using sql?

Example: I want to find the number of times the letter ‘d’ appears in this string.

```<code>declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'
</code>```

答:
For all you Sybase ASE 15 dinosaurs our there, you will need to replace '' with null, i.e.</p>

```<code>SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count
</code>```

OwnerDisplayName: NImesh

LastEditorDisplayName: xsl

ContentLicense: CC BY-SA 2.5

Body:
How can you find the number of occurrences of a particular character in a string using sql?

Example: I want to find the number of times the letter ‘d’ appears in this string.

declare @string varchar(100)
select @string = 'sfdasadhfasjfdlsajflsadsadsdadsa'

Body:
For all you Sybase ASE 15 dinosaurs our there, you will need to replace '' with null, i.e.

SELECT LEN(@string) - LEN(REPLACE(@string, 'd', null)) AS D_Count


问:
Sparklyr k8s gClouid - Pods aren't running
everybody

As the title says, I would be curious to understand why I can't connect via Sparklyr to gCloud clusters using kubernetes.

The steps to configure the system were as follows:

project creation on gCloud (free version 300dollars)

Cloud SDK installation on MacOS

Installation Kubectl binary with curl on MacOS

Docker installation

By terminal:

configure the cluster

gcloud config set compute/zone us-central1-f
gcloud container clusters create spark-on-gke --machine-type n1-standard-2

bind the cluster admin to email

kubectl create clusterrolebinding user-admin-binding --clusterrole=cluster-admin --user=pesca@gmail.com
kubectl create clusterrolebinding --clusterrole=cluster-admin --serviceaccount=default:default spark-admin

From R connect to the MASTER_IP, importing the public image offered by jluraschi

remotes::install_github("rstudio/sparklyr”); library(sparklyr)
sc <- spark_connect(config = spark_config_kubernetes(
"k8s://https://<k8s-ip>",
account = "default",
image = "docker.io/jluraschi/spark:sparklyr",
version = "2.4"))

And the error that appears is:
Error from server (NotFound): pods "sparklyr-c27317e4b89" not found

答:
Thank you so much for your answer!

At the end of the code you will also find screenshots of the pod configuration made with gcloud. Instead, here are the results from the terminal:

```<code>MBP-di-Simone:~ simone$ kubectl get services
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.3.240.1   <none>        443/TCP   13d

MBP-di-Simone:~ simone$ kubectl get pods --all-namespaces
NAMESPACE     NAME
READY   STATUS    RESTARTS   AGE
default       alpine                                                   1/1     Running   0          13d
kube-system   event-exporter-v0.2.4-5f88c66fb7-67pb6                   2/2     Running   0          13d
kube-system   fluentd-gcp-scaler-59b7b75cd7-mbgxj                      1/1     Running   0          13d
kube-system   fluentd-gcp-v3.2.0-9dlx8                                 2/2     Running   0          5d8h
kube-system   fluentd-gcp-v3.2.0-9w6t2                                 2/2     Running   0          5d8h
kube-system   fluentd-gcp-v3.2.0-dwrlz                                 2/2     Running   0          5d8h
kube-system   heapster-5f6cdd4bd-qmlhb                                 3/3     Running   0          13d
kube-system   kube-dns-79868f54c5-5sqvb                                4/4     Running   0          13d
kube-system   kube-dns-79868f54c5-g9h4q                                4/4     Running   0          13d
kube-system   kube-dns-autoscaler-bb58c6784-9bbcg                      1/1     Running   0          13d
kube-system   kube-proxy-gke-spark-on-gke-default-pool-7fad1be1-2279   1/1     Running   0          13d
kube-system   kube-proxy-gke-spark-on-gke-default-pool-7fad1be1-70hn   1/1     Running   0          13d
kube-system   kube-proxy-gke-spark-on-gke-default-pool-7fad1be1-pnpj   1/1     Running   0          13d
kube-system   l7-default-backend-fd59995cd-8tzjv                       1/1     Running   0          13d
kube-system   metrics-server-v0.3.1-57c75779f-gz776                    2/2     Running   0          13d
kube-system   prometheus-to-sd-ktvbk                                   2/2     Running   0          13d
kube-system   prometheus-to-sd-tmwkw                                   2/2     Running   0          13d
kube-system   prometheus-to-sd-xxx4p                                   2/2     Running   0          13d

MBP-di-Simone:~ simone$ kubectl describe pods [sparklyr-2e62d04d5dd]
Error from server (NotFound): pods "[sparklyr-2e62d04d5dd]" not found
MBP-di-Simone:~ simone$
</code>```

gCloud Cluster a

gCloud Cluster b

gCloud Cluster permission

gCloud Cluster label

Body:
Thank you so much for your answer!

At the end of the code you will also find screenshots of the pod configuration made with gcloud. Instead, here are the results from the terminal:

MBP-di-Simone:~ simone$ kubectl get services
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.3.240.1   <none>        443/TCP   13d

MBP-di-Simone:~ simone$ kubectl get pods --all-namespaces
NAMESPACE     NAME
READY   STATUS    RESTARTS   AGE
default       alpine                                                   1/1     Running   0          13d
kube-system   event-exporter-v0.2.4-5f88c66fb7-67pb6                   2/2     Running   0          13d
kube-system   fluentd-gcp-scaler-59b7b75cd7-mbgxj                      1/1     Running   0          13d
kube-system   fluentd-gcp-v3.2.0-9dlx8                                 2/2     Running   0          5d8h
kube-system   fluentd-gcp-v3.2.0-9w6t2                                 2/2     Running   0          5d8h
kube-system   fluentd-gcp-v3.2.0-dwrlz                                 2/2     Running   0          5d8h
kube-system   heapster-5f6cdd4bd-qmlhb                                 3/3     Running   0          13d
kube-system   kube-dns-79868f54c5-5sqvb                                4/4     Running   0          13d
kube-system   kube-dns-79868f54c5-g9h4q                                4/4     Running   0          13d
kube-system   kube-dns-autoscaler-bb58c6784-9bbcg                      1/1     Running   0          13d
kube-system   kube-proxy-gke-spark-on-gke-default-pool-7fad1be1-2279   1/1     Running   0          13d
kube-system   kube-proxy-gke-spark-on-gke-default-pool-7fad1be1-70hn   1/1     Running   0          13d
kube-system   kube-proxy-gke-spark-on-gke-default-pool-7fad1be1-pnpj   1/1     Running   0          13d
kube-system   l7-default-backend-fd59995cd-8tzjv                       1/1     Running   0          13d
kube-system   metrics-server-v0.3.1-57c75779f-gz776                    2/2     Running   0          13d
kube-system   prometheus-to-sd-ktvbk                                   2/2     Running   0          13d
kube-system   prometheus-to-sd-tmwkw                                   2/2     Running   0          13d
kube-system   prometheus-to-sd-xxx4p                                   2/2     Running   0          13d

MBP-di-Simone:~ simone$ kubectl describe pods [sparklyr-2e62d04d5dd]
Error from server (NotFound): pods "[sparklyr-2e62d04d5dd]" not found
MBP-di-Simone:~ simone$

gCloud Cluster a

gCloud Cluster b

gCloud Cluster permission

gCloud Cluster label


问:
Grabbing a list of dates from a column and formatting them to MM/dd/yyyy
I'm trying to write a program that will only apply to the rows whose dates match the current day. I know how to format the current date in MM/dd/yyyy but I'm having trouble looping through my list and formatting the dates to the list that I will use for comparing. Any advice helps, thank you!</p>

```<code>function date() {
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "M/dd/yyyy")
  console.log(curDate)

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); // get the sheet
  var columnF = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1); // get all the rows

  var fValues = columnF.getValues(); // get the values
  console.log('fvalues are; ', fValues)
  var format = []
  var datecolumn = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1)

  for (var i = 2; i < 4; i++) {
    var datecolumn = sheet.getRange(i, 5).getValue();
    format.push(datecolumn)
  };
  console.log('date array is: ', format)

  var format2 = []
  for (var i = 0; i < fValues.length; i++) {

    var fmtcell = Utilities.formatDate(fValues, "GMT-5", "MM/dd/yyyy")

    format2.push(fmtcell)
  }
}
</code>```

答:
```<code>function formatDate() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('Sheet1');
  var dt=new Date();
  var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valufOf();
  var colfR=sh.getRange(2,5,sh.getLastRow()-1,1);
  var colfV=colfR.getValues();
  var colfF=colfR.getNumberFormats();
  for (var i=0;i<colfV.length;i++) {
    var dtf=new Date(colfV[i][0]);
    var dtfv=new Date(dtf.getFullYear(),dtf.getMonth(),dtf.getDate()).valueOf();
    if(dtfv===dtv){colfF[i][0]="MM/dd/yyyy";}
  }
  colfR.setNumberFormats(colfF)
}
</code>```

Body:
I'm trying to write a program that will only apply to the rows whose dates match the current day. I know how to format the current date in MM/dd/yyyy but I'm having trouble looping through my list and formatting the dates to the list that I will use for comparing. Any advice helps, thank you!

function date() {
  var curDate = Utilities.formatDate(new Date(), "GMT+1", "M/dd/yyyy")
  console.log(curDate)

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1'); // get the sheet
  var columnF = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1); // get all the rows

  var fValues = columnF.getValues(); // get the values
  console.log('fvalues are; ', fValues)
  var format = []
  var datecolumn = sheet.getRange(2, 5, sheet.getLastRow() - 1, 1)

  for (var i = 2; i < 4; i++) {
    var datecolumn = sheet.getRange(i, 5).getValue();
    format.push(datecolumn)
  };
  console.log('date array is: ', format)

  var format2 = []
  for (var i = 0; i < fValues.length; i++) {

    var fmtcell = Utilities.formatDate(fValues, "GMT-5", "MM/dd/yyyy")

    format2.push(fmtcell)
  }
}


问:
Instance Provisioning with remote-exec in Terraform docs not working on MacOS. Error: timeout
I have been using the terraform docs to learn terraform, but I'm stuck at this step where I need to SSH into an ec2-instance.

I'm constantly getting a timeout error after the default 5mins

```<code>aws_instance.example (remote-exec): Connecting to remote host via SSH...
aws_instance.example (remote-exec):   Host: 63.32.57.5
aws_instance.example (remote-exec):   User: ec2-user
aws_instance.example (remote-exec):   Password: false
aws_instance.example (remote-exec):   Private key: true
aws_instance.example (remote-exec):   Certificate: false
aws_instance.example (remote-exec):   SSH Agent: true
aws_instance.example (remote-exec):   Checking Host Key: false
aws_instance.example: Still creating... [5m10s elapsed]
aws_instance.example: Still creating... [5m20s elapsed]

Error: timeout - last error: dial tcp 63.32.57.5:22: i/o timeout
</code>```

normal ssh into the server returns a timeout.

```<code>ssh -i ~/.ssh/terraform ec2-user@52.215.89.205
</code>```

returns

```<code>ssh: connect to host 52.215.89.205 port 22: Operation timed out
</code>```

it is obvious the issue is because ssh is not allowed in the security group. In terraform how do you get the default vpc?

I have found in some answers online (e.g here) that to make this error go away I need to set up a security group that allows ingress on port 22 into the ec2 instance. But up till this point in the documentation, we've not created or setup any security group, VPC or subnet.

I also tried to research further in the documentation to try to create my own security group. That's where I found out that a security group also depends on creating a VPC resource. And for sure, after creating a VPC you will have to do some extra configurations like creating your own subnet, routing table, elastic IP, etc.

What is the easy way to fix this? Instead of creating a new VPC, can't I use the credentials of the default VPC. If that is possible, then how?

Here's my terraform code up to this point in the doc.

```<code>provider "aws" {
  profile = "default"
  region  = "eu-west-1"
  version = "~> 2.49"
}

resource "aws_key_pair" "example" {
  key_name = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}

resource "aws_instance" "example" {
  key_name = aws_key_pair.example.key_name
  ami = "ami-0e61341fa75fcaa18"
  instance_type = "t2.micro"
  # vpc_security_group_ids = ["sg-0e8bcd72"]
  # subnet_id = "subnet-6f86e027"

  connection {
    type = "ssh"
    user = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }
}

resource "aws_eip" "ip" {
  vpc = true
  instance = aws_instance.example.id
}
</code>```

How can I make this timeout error go away?

答:
Found a way to add a security group and allow access to ec2 instance from the terraform script. This solution will allow ingress(inbound) and egress(outbound) access into the created ec2 instance.

If all runs successfully, you should see this page when you visit the public IP of the created instance in your browser.

NB: Make sure to use an ami for EC2 instance that supports amazon-linux-extras or add it to the installation in the remote-exec provisioner

Create Security Group

```<code>resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
</code>```

And then add it to the aws_instance resource like so

```<code>resource "aws_instance" "example" {
  key_name = aws_key_pair.example.key_name
  ami = "ami-0e61341fa75fcaa18"
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]
  # subnet_id = "subnet-6f86e027"

  connection {
    type = "ssh"
    user = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }
}
</code>```

My full terraform code now looks like this:

```<code>provider "aws" {
  profile = "default"
  region  = "eu-west-1"
  version = "~> 2.49"
}

resource "aws_key_pair" "example" {
  key_name   = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}

resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress {
    from_port   = 0
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "example" {
  key_name               = aws_key_pair.example.key_name
  ami                    = "ami-099a8245f5daa82bf"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]
  # subnet_id = "subnet-6f86e027"

  # user_data = <<-EOF
  #             #!/bin/bash
  #             echo "Hello, World" > index.html
  #             nohup busybox httpd -f -p 8080 &
  #             EOF

  connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }

  tags = {
    Name = "terraform-example"
  }
}

resource "aws_eip" "ip" {
  vpc      = true
  instance = aws_instance.example.id
}
</code>```

The security group solution is an  Excerpt From: Yevgeniy Brikman. “Terraform: Up & Running, 2nd Edition”. Apple Books.

Body:
I have been using the terraform docs to learn terraform, but I'm stuck at this step where I need to SSH into an ec2-instance.

I'm constantly getting a timeout error after the default 5mins

aws_instance.example (remote-exec): Connecting to remote host via SSH...
aws_instance.example (remote-exec):   Host: 63.32.57.5
aws_instance.example (remote-exec):   User: ec2-user
aws_instance.example (remote-exec):   Password: false
aws_instance.example (remote-exec):   Private key: true
aws_instance.example (remote-exec):   Certificate: false
aws_instance.example (remote-exec):   SSH Agent: true
aws_instance.example (remote-exec):   Checking Host Key: false
aws_instance.example: Still creating... [5m10s elapsed]
aws_instance.example: Still creating... [5m20s elapsed]

Error: timeout - last error: dial tcp 63.32.57.5:22: i/o timeout

normal ssh into the server returns a timeout.

ssh -i ~/.ssh/terraform ec2-user@52.215.89.205

returns

ssh: connect to host 52.215.89.205 port 22: Operation timed out

it is obvious the issue is because ssh is not allowed in the security group. In terraform how do you get the default vpc?

I have found in some answers online (e.g here) that to make this error go away I need to set up a security group that allows ingress on port 22 into the ec2 instance. But up till this point in the documentation, we've not created or setup any security group, VPC or subnet.

I also tried to research further in the documentation to try to create my own security group. That's where I found out that a security group also depends on creating a VPC resource. And for sure, after creating a VPC you will have to do some extra configurations like creating your own subnet, routing table, elastic IP, etc.

What is the easy way to fix this? Instead of creating a new VPC, can't I use the credentials of the default VPC. If that is possible, then how?

Here's my terraform code up to this point in the doc.

provider "aws" {
  profile = "default"
  region  = "eu-west-1"
  version = "~> 2.49"
}

resource "aws_key_pair" "example" {
  key_name = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}

resource "aws_instance" "example" {
  key_name = aws_key_pair.example.key_name
  ami = "ami-0e61341fa75fcaa18"
  instance_type = "t2.micro"
  # vpc_security_group_ids = ["sg-0e8bcd72"]
  # subnet_id = "subnet-6f86e027"

  connection {
    type = "ssh"
    user = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }
}

resource "aws_eip" "ip" {
  vpc = true
  instance = aws_instance.example.id
}

How can I make this timeout error go away?

Body:
Found a way to add a security group and allow access to ec2 instance from the terraform script. This solution will allow ingress(inbound) and egress(outbound) access into the created ec2 instance.

If all runs successfully, you should see this page when you visit the public IP of the created instance in your browser.

NB: Make sure to use an ami for EC2 instance that supports amazon-linux-extras or add it to the installation in the remote-exec provisioner

Create Security Group

resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress {
    from_port   = 8080
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

And then add it to the aws_instance resource like so

resource "aws_instance" "example" {
  key_name = aws_key_pair.example.key_name
  ami = "ami-0e61341fa75fcaa18"
  instance_type = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]
  # subnet_id = "subnet-6f86e027"

  connection {
    type = "ssh"
    user = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }
}

My full terraform code now looks like this:

provider "aws" {
  profile = "default"
  region  = "eu-west-1"
  version = "~> 2.49"
}

resource "aws_key_pair" "example" {
  key_name   = "examplekey"
  public_key = file("~/.ssh/terraform.pub")
}

resource "aws_security_group" "instance" {
  name = "terraform-example-instance"

  ingress {
    from_port   = 0
    to_port     = 8080
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "example" {
  key_name               = aws_key_pair.example.key_name
  ami                    = "ami-099a8245f5daa82bf"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [aws_security_group.instance.id]
  # subnet_id = "subnet-6f86e027"

  # user_data = <<-EOF
  #             #!/bin/bash
  #             echo "Hello, World" > index.html
  #             nohup busybox httpd -f -p 8080 &
  #             EOF

  connection {
    type        = "ssh"
    user        = "ec2-user"
    private_key = file("~/.ssh/terraform")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo amazon-linux-extras enable nginx1.12",
      "sudo yum -y install nginx",
      "sudo systemctl start nginx"
    ]
  }

  tags = {
    Name = "terraform-example"
  }
}

resource "aws_eip" "ip" {
  vpc      = true
  instance = aws_instance.example.id
}

The security group solution is an  Excerpt From: Yevgeniy Brikman. “Terraform: Up & Running, 2nd Edition”. Apple Books.


问:
Minesweeper - Angular
I'm making angular version of MineSweeper, but I've got the problem with event. I mean, I've got my field component like that:

```<code>import {Component, Input, OnInit} from '@angular/core';
import {style} from '@angular/animations';

@Component({
  selector: 'app-pool',
  templateUrl: './field.component.html',
  styleUrls: ['./field.component.sass']
})

export class FieldComponent implements OnInit {
  isBomb = false;
  isInfo = false;
  isClickable = true;
  touchesBombCount = 0;
  isMarkedAsBomb = false;
  isExpanded = false;
  poolID: number;
  isBombExpanded = false;

  @Input() display: string;

  constructor() {
  }

  ngOnInit() {
  }

  expandMe() {
    this.isExpanded = !this.isExpanded;
    if (this.isBomb && this.isExpanded) {
      this.isBombExpanded = !this.isBombExpanded;
    }
    console.log(this);
  }

  onFieldClick(event: any) {
    this.expandMe();
    this.isClickable = false;
    console.log(event);
  }

  onRightClick(event: any) {
    event.preventDefault();
    this.isMarkedAsBomb = !this.isMarkedAsBomb;
  }

}
</code>```

Then I'm creating fields in board component:

```<code>import {Component, Input, OnInit} from '@angular/core';
import {FieldComponent} from '../field/field.component';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.sass']
})
export class BoardComponent implements OnInit {
  fieldList: FieldComponent[] = [];
  bombCount: number = 10;
  poolBombList: FieldComponent[] = [];
  private allBombsPlanted = false;
  isGameOver = false;

  @Input() poolCount: number;

  constructor() {
  }

  ngOnInit() {
    this.createBoardFromPools();
    while (!this.allBombsPlanted) {
      this.plantTheBombs();
    }
    console.log(this);
  }

  createBoardFromPools() {
    for (let i = 0; i < this.poolCount; i++) {
      const pool = new FieldComponent();
      pool.poolID = i;
      this.fieldList.push(pool);
    }
  }

  plantTheBombs() {
    const poolCount = this.fieldList.length - 1;
    const poolToPlant = Math.floor((Math.random() * poolCount));
    if (!this.checkIfHasBomb(poolToPlant)) {
      this.poolBombList.push(this.fieldList[poolToPlant]);
      this.fieldList[poolToPlant].isBomb = true;
    }
    if (this.poolBombList.length === this.bombCount) {
      this.allBombsPlanted = true;
    }
  }

  checkIfHasBomb(poolToPlant): boolean {

    for (let i = 0, iMax = this.poolBombList.length; i < iMax; i++) {
      if (this.poolBombList[i].poolID === poolToPlant.poolID) {
        return true;
      }
    }
    return false;
  }

}
</code>```

My question is:

why when I console.log (this) of field component, then the bomb is marked as false, even, when on my general list of fields in board component (  fieldList: FieldComponent[] = []) shows it is a bomb actually?

I'm moving from vanilla to angular, maybe I've created fields in board component not correctly?

答:
I think a better solution would be to create a model for your Field like:

```<code>export interface FieldModel{
  poolID: number;
  isBomb:boolean;
  isInfo:boolean;
  isClickable:boolean;
  touchesBombCount:boolean;
  isMarkedAsBomb:boolean;
  isExpanded:boolean;
  isBombExpanded:boolean;
}

</code>```

Now in your BoardComponent you would simply create FieldModel objects and push them into the list of fields.

In the template of BoardComponent you would create the FieldComponent via the declarative approach in a *ngFor iterating over the FieldModels and passing them as input properties to your FieldComponent.

Other Solution

If you want to dynamically create components, like you want to with your FieldComponent inside the BoardComponent you should use a
ComponentFactory. You will also need a ViewContainerRef where your components can get rendered inside.

In the template of your BoardComponent you need some container for your fields:

```<code><ng-template #boardContainer></ng-template>
</code>```

In BoardComponent you need to get the container with the help of the ViewChild decorator and inject a ComponentFactoryResolver:

```<code>export class BoardComponent implements OnInit {
  ...
  @ViewChild('boardContainer',{read:ViewContainerRef,static:false}) boardContainer:ViewContainerRef;

  constructor(private componentFactoryResolver:ComponentFactoryResolver) {
  }
  ...
}
</code>```

Now you can create FieldComponents like shown below:

```<code>createFieldComponent(){
 const componentFactory = this.componentFactoryResolver.resolveComponentFactory(FieldComponent);
 const componentRef:ComponentRef<FieldComponent> = this.boardContainer.createComponent(componentFactory);
}
</code>```

The componentRef then offers you access to the component instance.

Title: Minesweeper - Angular

Body:
I'm making angular version of MineSweeper, but I've got the problem with event. I mean, I've got my field component like that:

import {Component, Input, OnInit} from '@angular/core';
import {style} from '@angular/animations';

@Component({
  selector: 'app-pool',
  templateUrl: './field.component.html',
  styleUrls: ['./field.component.sass']
})

export class FieldComponent implements OnInit {
  isBomb = false;
  isInfo = false;
  isClickable = true;
  touchesBombCount = 0;
  isMarkedAsBomb = false;
  isExpanded = false;
  poolID: number;
  isBombExpanded = false;

  @Input() display: string;

  constructor() {
  }

  ngOnInit() {
  }

  expandMe() {
    this.isExpanded = !this.isExpanded;
    if (this.isBomb && this.isExpanded) {
      this.isBombExpanded = !this.isBombExpanded;
    }
    console.log(this);
  }

  onFieldClick(event: any) {
    this.expandMe();
    this.isClickable = false;
    console.log(event);
  }

  onRightClick(event: any) {
    event.preventDefault();
    this.isMarkedAsBomb = !this.isMarkedAsBomb;
  }

}

Then I'm creating fields in board component:

import {Component, Input, OnInit} from '@angular/core';
import {FieldComponent} from '../field/field.component';

@Component({
  selector: 'app-board',
  templateUrl: './board.component.html',
  styleUrls: ['./board.component.sass']
})
export class BoardComponent implements OnInit {
  fieldList: FieldComponent[] = [];
  bombCount: number = 10;
  poolBombList: FieldComponent[] = [];
  private allBombsPlanted = false;
  isGameOver = false;

  @Input() poolCount: number;

  constructor() {
  }

  ngOnInit() {
    this.createBoardFromPools();
    while (!this.allBombsPlanted) {
      this.plantTheBombs();
    }
    console.log(this);
  }

  createBoardFromPools() {
    for (let i = 0; i < this.poolCount; i++) {
      const pool = new FieldComponent();
      pool.poolID = i;
      this.fieldList.push(pool);
    }
  }

  plantTheBombs() {
    const poolCount = this.fieldList.length - 1;
    const poolToPlant = Math.floor((Math.random() * poolCount));
    if (!this.checkIfHasBomb(poolToPlant)) {
      this.poolBombList.push(this.fieldList[poolToPlant]);
      this.fieldList[poolToPlant].isBomb = true;
    }
    if (this.poolBombList.length === this.bombCount) {
      this.allBombsPlanted = true;
    }
  }

  checkIfHasBomb(poolToPlant): boolean {

    for (let i = 0, iMax = this.poolBombList.length; i < iMax; i++) {
      if (this.poolBombList[i].poolID === poolToPlant.poolID) {
        return true;
      }
    }
    return false;
  }

}

My question is:

why when I console.log (this) of field component, then the bomb is marked as false, even, when on my general list of fields in board component (  fieldList: FieldComponent[] = []) shows it is a bomb actually?

I'm moving from vanilla to angular, maybe I've created fields in board component not correctly?

Body:
I think a better solution would be to create a model for your Field like:

export interface FieldModel{
  poolID: number;
  isBomb:boolean;
  isInfo:boolean;
  isClickable:boolean;
  touchesBombCount:boolean;
  isMarkedAsBomb:boolean;
  isExpanded:boolean;
  isBombExpanded:boolean;
}

Now in your BoardComponent you would simply create FieldModel objects and push them into the list of fields.

In the template of BoardComponent you would create the FieldComponent via the declarative approach in a *ngFor iterating over the FieldModels and passing them as input properties to your FieldComponent.

Other Solution

If you want to dynamically create components, like you want to with your FieldComponent inside the BoardComponent you should use a
ComponentFactory. You will also need a ViewContainerRef where your components can get rendered inside.

In the template of your BoardComponent you need some container for your fields:

<ng-template #boardContainer></ng-template>

In BoardComponent you need to get the container with the help of the ViewChild decorator and inject a ComponentFactoryResolver:

export class BoardComponent implements OnInit {
  ...
  @ViewChild('boardContainer',{read:ViewContainerRef,static:false}) boardContainer:ViewContainerRef;

  constructor(private componentFactoryResolver:ComponentFactoryResolver) {
  }
  ...
}

Now you can create FieldComponents like shown below:

createFieldComponent(){
 const componentFactory = this.componentFactoryResolver.resolveComponentFactory(FieldComponent);
 const componentRef:ComponentRef<FieldComponent> = this.boardContainer.createComponent(componentFactory);
}

The componentRef then offers you access to the component instance.


问:
How to read information from file to a matrix?
I tried to do this, but this didnt work...

```<code>#include <iostream>
#include <conio.h>
#include <fstream>

using namespace std;

void afisare(int place[9][9]){
    for(int i = 0; i<9;i++){
        for(int j =1; j<9;j++){
            cout << place[i][j] << " ";
        }
        cout << endl;
    }
}

int main(){
    ifstream fin;
    int place[9][9],n,j = 0;
    string s;

    fin.open("file.in");
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                fin >> place[i][j];
            }
        }
    fin.close();

    afisare(place);
    _getch();
    return 0;
}
</code>```

and this show me that
enter image description here
when this need to show that
enter image description here
help me please. :*|

答:
It's most likely that your program was not successful in opening the file.

Add a check to verify that opening the file was successful.

Add a check when reading the contents of the file. If there is an error, add code to deal with it.

```<code>fin.open("file.in");
if ( !fin )
{
   std::cerr << "ERROR: Unable to open file.\n";
   return EXIT_FAILURE;
}

for(int i = 0; i < 9; i++){
   for(int j = 0; j < 9; j++){
      if ( !(fin >> place[i][j]) ) {
         std::cerr << "ERROR: Unable to read number from file.\n";
         return EXIT_FAILURE;
      }
   }
}
</code>```

If you see any of those error messages,

Try running the program from the directory where file.in is located, or

Use absolute path of the file.

Body:
I tried to do this, but this didnt work...

#include <iostream>
#include <conio.h>
#include <fstream>

using namespace std;

void afisare(int place[9][9]){
    for(int i = 0; i<9;i++){
        for(int j =1; j<9;j++){
            cout << place[i][j] << " ";
        }
        cout << endl;
    }
}

int main(){
    ifstream fin;
    int place[9][9],n,j = 0;
    string s;

    fin.open("file.in");
        for(int i = 0; i < 9; i++){
            for(int j = 0; j < 9; j++){
                fin >> place[i][j];
            }
        }
    fin.close();

    afisare(place);
    _getch();
    return 0;
}

and this show me that
enter image description here
when this need to show that
enter image description here
help me please. :*|

Body:
It's most likely that your program was not successful in opening the file.

Add a check to verify that opening the file was successful.

Add a check when reading the contents of the file. If there is an error, add code to deal with it.

fin.open("file.in");
if ( !fin )
{
   std::cerr << "ERROR: Unable to open file.\n";
   return EXIT_FAILURE;
}

for(int i = 0; i < 9; i++){
   for(int j = 0; j < 9; j++){
      if ( !(fin >> place[i][j]) ) {
         std::cerr << "ERROR: Unable to read number from file.\n";
         return EXIT_FAILURE;
      }
   }
}

If you see any of those error messages,

Try running the program from the directory where file.in is located, or

Use absolute path of the file.


问:
How to find mismatch between two tables with respect to each table in SQL?
I have a table TAB_1,TAB_2 which stores the set of some kids with Schema

```<code>KID_ID (Number(2))  SHIRT_COLOR(VARCHAR (10)) PANT_COLOR(VARCHAR (10)) .
</code>```

TAB_1 has details of 50 kids ,while TAB_2 has 60 records in it .
If we have 45 kids in common between TAB_1 and TAB_2 which have same KID_ID ,SHIRT_COLOR & PANT_COLOR ,Then we have to find out the Mismatches between TAB_1 & TAB_2 w.r.t tables TAB_1 & TAB_2 .

Since 45 kids are common , so there are 5 kids-mismatch in TAB_1 and 15 Kids-mismatch in TAB_2 ,Now we have to check if the 5 extra kids in TAB_1 have any attribute common with the kid of TAB_2 Table i.e. say for instance , if out of 5 kids , 3 kids are there whose shirt match with kids of TAB_2 Table , 2 kids are there whose Pant Color match with the kids of TAB_2 Table ,so there is only 1 kid which is purely extra in TAB_1 Table and there are 11 kids which are purely extra in Tab_2 .

Please guide how to approach this ?

答:
We can try using a full outer join here, and then retaining only records from each table which do not intersect between the two tables:

```<code>SELECT
    COALESCE(t1.SHIRT_COLOR, t2.SHIRT_COLOR) AS SHIRT_COLOR,
    COALESCE(t1.PANT_COLOR, t2.PANT_COLOR) AS PANT_COLOR,
    CASE WHEN t2.KID_ID IS NULL THEN 'TAB_1' ELSE 'TAB_2' END AS TABLE_SOURCE
FROM TAB_1 t1
FULL OUTER JOIN TAB_2 t2
    ON t1.SHIRT_COLOR = t2.SHIRT_COLOR AND
       t1.PANT_COLOR = t2.PANT_COLOR
WHERE
    t1.KID_ID IS NULL OR
    t2.KID_ID IS NULL;
</code>```

Follow the link below to see a running demo in Oracle.

Demo

Body:
I have a table TAB_1,TAB_2 which stores the set of some kids with Schema

KID_ID (Number(2))  SHIRT_COLOR(VARCHAR (10)) PANT_COLOR(VARCHAR (10)) .

TAB_1 has details of 50 kids ,while TAB_2 has 60 records in it .
If we have 45 kids in common between TAB_1 and TAB_2 which have same KID_ID ,SHIRT_COLOR & PANT_COLOR ,Then we have to find out the Mismatches between TAB_1 & TAB_2 w.r.t tables TAB_1 & TAB_2 .

Since 45 kids are common , so there are 5 kids-mismatch in TAB_1 and 15 Kids-mismatch in TAB_2 ,Now we have to check if the 5 extra kids in TAB_1 have any attribute common with the kid of TAB_2 Table i.e. say for instance , if out of 5 kids , 3 kids are there whose shirt match with kids of TAB_2 Table , 2 kids are there whose Pant Color match with the kids of TAB_2 Table ,so there is only 1 kid which is purely extra in TAB_1 Table and there are 11 kids which are purely extra in Tab_2 .

Please guide how to approach this ?

Body:
We can try using a full outer join here, and then retaining only records from each table which do not intersect between the two tables:

SELECT
    COALESCE(t1.SHIRT_COLOR, t2.SHIRT_COLOR) AS SHIRT_COLOR,
    COALESCE(t1.PANT_COLOR, t2.PANT_COLOR) AS PANT_COLOR,
    CASE WHEN t2.KID_ID IS NULL THEN 'TAB_1' ELSE 'TAB_2' END AS TABLE_SOURCE
FROM TAB_1 t1
FULL OUTER JOIN TAB_2 t2
    ON t1.SHIRT_COLOR = t2.SHIRT_COLOR AND
       t1.PANT_COLOR = t2.PANT_COLOR
WHERE
    t1.KID_ID IS NULL OR
    t2.KID_ID IS NULL;

Follow the link below to see a running demo in Oracle.

Demo


问:
Cannot open SSIS package (.dtproj file) after reinstalling Visual Studio 2015
I have made an SSIS-package in Visual Studio 2015. A bit after, I had to reinstall VS because there was some trouble with an unrelated package. Now when I try to open the SSIS-package, I first get the following popup:

```<code>The 'ResourceManagerPackage' package did not load correctly.

The problem may have been caused by a configuration change or by the installation of another extension. You can get more information by examining the file 'C:\Users\xxx\Appdata\Roaming\Microsoft\VisualStudio\14.0\ActivityLog.xml'.

Restarting Visual Studio could help resolve this issue.

Continue to show this error message?
</code>```

The popup pops up even when I just start VS.

After I click ok, the project does not load. In Solution Explorer, it says 'incompatible', and when I hover over it it says 'The application is not installed'.

How do I fix this?

edit I have run a repair of VS, and added the SSDT manually, no improvement. I have also opened the ActivityLog as suggested in the popup and searched for errors. I found this:

```<code>Could not load file or assembly 'Microsoft.AnalysisServices.Project, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Could not load file or assembly 'Microsoft.ReportingServices.Designer, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.
</code>```

This might be it, but since I cannot even open the solution, I do not know how to fix it anyway.

答: Go to Tools - Manage Extensions - Install- All . And checked SQL Server Integration Server Project is Enable. Visual studio not responding some times result in disabling SSIS project plugin. </p>

ContentLicense: CC BY-SA 3.0

Body:
I have made an SSIS-package in Visual Studio 2015. A bit after, I had to reinstall VS because there was some trouble with an unrelated package. Now when I try to open the SSIS-package, I first get the following popup:

The 'ResourceManagerPackage' package did not load correctly.

The problem may have been caused by a configuration change or by the installation of another extension. You can get more information by examining the file 'C:\Users\xxx\Appdata\Roaming\Microsoft\VisualStudio\14.0\ActivityLog.xml'.

Restarting Visual Studio could help resolve this issue.

Continue to show this error message?

The popup pops up even when I just start VS.

After I click ok, the project does not load. In Solution Explorer, it says 'incompatible', and when I hover over it it says 'The application is not installed'.

How do I fix this?

edit I have run a repair of VS, and added the SSDT manually, no improvement. I have also opened the ActivityLog as suggested in the popup and searched for errors. I found this:

Could not load file or assembly 'Microsoft.AnalysisServices.Project, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

Could not load file or assembly 'Microsoft.ReportingServices.Designer, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot find the file specified.

This might be it, but since I cannot even open the solution, I do not know how to fix it anyway.


问:
How can I safely make a float *x into a const float *const *y?
I have a function audioReceived (float * input, int bufferSize, int nChannels) inside of which I want to call a function from a library that needs const float *const *inputBuffers.

Obviously casting const float *const *inputBuffers = (const float* const*)input; compiles but is a terrible idea, crashes the program, kills kittens, etc. Nobody ever needs to modify the original float* input, it's incoming audio data that's being processed.

How do I do it the right way?

EDIT: Here's some more code. audioReceived is:

```<code>void testApp::audioReceived (float * input, int bufferSize, int nChannels){

     Vamp::RealTime rt = Vamp::RealTime::fromMilliseconds(ofGetSystemTime());
     float const *const tmp[] = { input, 0 };
     Vamp::Plugin::FeatureSet fs = myPlugin->process(tmp, rt);
 }
</code>```

Library function process is virtually defined in base class:

```<code> /**
 * Process a single block of input data.
 *
 * If the plugin's inputDomain is TimeDomain, inputBuffers will
 * point to one array of floats per input channel, and each of
 * these arrays will contain blockSize consecutive audio samples
 * (the host will zero-pad as necessary).  The timestamp in this
 * case will be the real time in seconds of the start of the
 * supplied block of samples.
 *
 * If the plugin's inputDomain is FrequencyDomain, inputBuffers
 * will point to one array of floats per input channel, and each
 * of these arrays will contain blockSize/2+1 consecutive pairs of
 * real and imaginary component floats corresponding to bins
 * 0..(blockSize/2) of the FFT output.  That is, bin 0 (the first
 * pair of floats) contains the DC output, up to bin blockSize/2
 * which contains the Nyquist-frequency output.  There will
 * therefore be blockSize+2 floats per channel in total.  The
 * timestamp will be the real time in seconds of the centre of the
 * FFT input window (i.e. the very first block passed to process
 * might contain the FFT of half a block of zero samples and the
 * first half-block of the actual data, with a timestamp of zero).
 *
 * Return any features that have become available after this
 * process call.  (These do not necessarily have to fall within
 * the process block, except for OneSamplePerStep outputs.)
 */
virtual FeatureSet process(const float *const *inputBuffers,
               RealTime timestamp) = 0;
</code>```

and here in the actual header:

```<code>FeatureSet process(const float *const *inputBuffers, Vamp::RealTime timestamp);
</code>```

I think the EXC_BAD_ACCESS may be stemming from the library function wanting a zero-padded array, and my not giving it one. (a) Does that sound reasonable, and (b) If so, is it time to ask a different SO question?

Thanks all for your help so far, it's very enlightening/clarifying/educational/interesting.

答:
Doing &input should be enough for the cast itself. Note that the argument of the internal function is a pointer to pointer.

Edit:

To get a null terminated list of input buffers as required in your comments to the original question, you may use:

```<code>float const * const buffers[] = {input, 0};
</code>```

Body:
I have a function audioReceived (float * input, int bufferSize, int nChannels) inside of which I want to call a function from a library that needs const float *const *inputBuffers.

Obviously casting const float *const *inputBuffers = (const float* const*)input; compiles but is a terrible idea, crashes the program, kills kittens, etc. Nobody ever needs to modify the original float* input, it's incoming audio data that's being processed.

How do I do it the right way?

EDIT: Here's some more code. audioReceived is:

void testApp::audioReceived (float * input, int bufferSize, int nChannels){

     Vamp::RealTime rt = Vamp::RealTime::fromMilliseconds(ofGetSystemTime());
     float const *const tmp[] = { input, 0 };
     Vamp::Plugin::FeatureSet fs = myPlugin->process(tmp, rt);
 }

Library function process is virtually defined in base class:

 /**
 * Process a single block of input data.
 *
 * If the plugin's inputDomain is TimeDomain, inputBuffers will
 * point to one array of floats per input channel, and each of
 * these arrays will contain blockSize consecutive audio samples
 * (the host will zero-pad as necessary).  The timestamp in this
 * case will be the real time in seconds of the start of the
 * supplied block of samples.
 *
 * If the plugin's inputDomain is FrequencyDomain, inputBuffers
 * will point to one array of floats per input channel, and each
 * of these arrays will contain blockSize/2+1 consecutive pairs of
 * real and imaginary component floats corresponding to bins
 * 0..(blockSize/2) of the FFT output.  That is, bin 0 (the first
 * pair of floats) contains the DC output, up to bin blockSize/2
 * which contains the Nyquist-frequency output.  There will
 * therefore be blockSize+2 floats per channel in total.  The
 * timestamp will be the real time in seconds of the centre of the
 * FFT input window (i.e. the very first block passed to process
 * might contain the FFT of half a block of zero samples and the
 * first half-block of the actual data, with a timestamp of zero).
 *
 * Return any features that have become available after this
 * process call.  (These do not necessarily have to fall within
 * the process block, except for OneSamplePerStep outputs.)
 */
virtual FeatureSet process(const float *const *inputBuffers,
               RealTime timestamp) = 0;

and here in the actual header:

FeatureSet process(const float *const *inputBuffers, Vamp::RealTime timestamp);

I think the EXC_BAD_ACCESS may be stemming from the library function wanting a zero-padded array, and my not giving it one. (a) Does that sound reasonable, and (b) If so, is it time to ask a different SO question?

Thanks all for your help so far, it's very enlightening/clarifying/educational/interesting.

Body:
Doing &input should be enough for the cast itself. Note that the argument of the internal function is a pointer to pointer.

Edit:

To get a null terminated list of input buffers as required in your comments to the original question, you may use:

float const * const buffers[] = {input, 0};


问:
How can I make this demo drawing game update drawing the circles faster with Pygame?
I am trying to make my drawing game draw a circle where I drag my mouse, but the circles won't update often enough to create a smooth line. How can I fix this?

```<code>import pygame
from random import randint
width=800
height=600
pygame.init() #As necessary as import, initalizes pygame
global gameDisplay
gameDisplay = pygame.display.set_mode((width,height))#Makes window
pygame.display.set_caption('Demo')#Titles window
clock = pygame.time.Clock()#Keeps time for pygame

gameDisplay.fill((0,0,255))

class Draw:
    def __init__(self):
        self.color = (255, 0, 0)

    def update(self, x, y):
        self.x = x
        self.y = y
        pygame.draw.circle(gameDisplay, self.color, (self.x, self.y), (5))

end = False
down = False
Line = Draw()
while not end:
    x, y = pygame.mouse.get_pos()
    #drawShape()
    #pygame.draw.rect(gameDisplay, (0,255,0), (10, 10, 4, 4))
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            down = True

        if event.type == pygame.MOUSEBUTTONUP:
            down = False

        if down:
            Line.update(x, y)

        if event.type == pygame.QUIT:
            end = True
    lastx, lasty = pygame.mouse.get_pos()
    pygame.display.update()

    clock.tick(60)

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

This is what my problem looks like

答:
I recommend to draw a line from the previous mouse position to the current mouse position. Additionally draw a dot at the start and the end of the line. That causes a round beginning and end.

Track the previous position of the mouse (lastx, lasty) and draw the line in the main application loop rather than the event loop:

e.g.:

import pygame

width, height = 800, 600
pygame.init() #As necessary as import, initalizes pygame
gameDisplay = pygame.display.set_mode((width,height)) #Makes window
pygame.display.set_caption('Demo') #Titles window
clock = pygame.time.Clock() #Keeps time for pygame
gameDisplay.fill((0,0,255))

class Draw:
    def __init__(self):
        self.color = (255, 0, 0)

    def update(self, from_x, from_y, to_x, to_y):
        pygame.draw.circle(gameDisplay, self.color, (from_x, from_y), 5)
        pygame.draw.line(gameDisplay, self.color, (from_x, from_y), (to_x, to_y), 10)
        pygame.draw.circle(gameDisplay, self.color, (to_x, to_y), 5)

end = False
down = False
line = Draw()
while not end:
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            lastx, lasty = event.pos
            down = True
        if event.type == pygame.MOUSEBUTTONUP:
            down = False
        if event.type == pygame.QUIT:
            end = True

    x, y = pygame.mouse.get_pos()
    if down:
        line.update(lastx, lasty, x, y)
    lastx, lasty = x, y

    pygame.display.update()
    clock.tick(60)

pygame.quit()
```

Body:
I am trying to make my drawing game draw a circle where I drag my mouse, but the circles won't update often enough to create a smooth line. How can I fix this?

import pygame
from random import randint
width=800
height=600
pygame.init() #As necessary as import, initalizes pygame
global gameDisplay
gameDisplay = pygame.display.set_mode((width,height))#Makes window
pygame.display.set_caption('Demo')#Titles window
clock = pygame.time.Clock()#Keeps time for pygame

gameDisplay.fill((0,0,255))

class Draw:
    def __init__(self):
        self.color = (255, 0, 0)

    def update(self, x, y):
        self.x = x
        self.y = y
        pygame.draw.circle(gameDisplay, self.color, (self.x, self.y), (5))

end = False
down = False
Line = Draw()
while not end:
    x, y = pygame.mouse.get_pos()
    #drawShape()
    #pygame.draw.rect(gameDisplay, (0,255,0), (10, 10, 4, 4))
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            down = True

        if event.type == pygame.MOUSEBUTTONUP:
            down = False

        if down:
            Line.update(x, y)

        if event.type == pygame.QUIT:
            end = True
    lastx, lasty = pygame.mouse.get_pos()
    pygame.display.update()

    clock.tick(60)

pygame.quit()

This is what my problem looks like


问:
Any way to cast a table with one value as a scalar type? (Integer, String, etc.)
Here is what I would like to do:

```<code>declare maxNum integer;
maxNum = select MAX(rn) from :ColumnList;
</code>```

The sql statement returns a table with one row/col (one value).

Is there an easy way to assign this value to a scalar variable?

答:
The variable will be stored as an integer with this syntax.

```<code>declare maxNum integer;
select MAX(rn) into maxNum from :ColumnList;
</code>```

Edit: Thanks to Lars Br. for the explanation why this works.

Body:
Here is what I would like to do:

declare maxNum integer;
maxNum = select MAX(rn) from :ColumnList;

The sql statement returns a table with one row/col (one value).

Is there an easy way to assign this value to a scalar variable?

Body:
The variable will be stored as an integer with this syntax.

declare maxNum integer;
select MAX(rn) into maxNum from :ColumnList;

Edit: Thanks to Lars Br. for the explanation why this works.


问:
How to correctly parse field access after function call via parser-combinators (makeExprParser) library?
I want to parse expressions like this: a().x. It should look like EAttrRef (EFuncCall (EVarRef "a") []) "x". Unfortunately my expression parser is stopping too soon, it only parses a() and then stops.

```<code>1:4:
  |
1 | a().x
  |    ^
unexpected '.'
expecting end of input
</code>```

Code:

pExpr :: Parser Expr
pExpr = lexeme p & dbg "pExpr" <?> "expression"
  where
    pTerm = try pVarRef <|> pELit
    p = makeExprParser pTerm exprTable
    exprTable = [[Postfix opIndexRef], [InfixL opAttrRef], [Postfix opFuncCall]]
    opAttrRef :: Parser (Expr -> Expr -> Expr)
    opAttrRef = do
      symbol "." & dbg "opAttrRef symbol \".\""
      return r
      where
        r x (EVarRef y) = EAttrRef x y
        r x y = error [qq|opAttrRef got unexpected right operand $y (left operand was $x)|]
    opFuncCall :: Parser (Expr -> Expr)
    opFuncCall = do
      symbol "("
      args <- sepBy pExpr (symbol ",")
      symbol ")" & dbg "opFuncCall symbol \")\""
      return $ \funcExpr -> EFuncCall funcExpr args
    opIndexRef = do
      symbol "["
      e <- pExpr
      symbol "]" & dbg "opIndexRef symbol \"]\""
      return $ \obj -> EIndexRef obj e
```

<p>Debug output:</p>

```opAttrRef symbol "."> IN: "().x"
opAttrRef symbol "."> MATCH (EERR): <EMPTY>
opAttrRef symbol "."> ERROR:
opAttrRef symbol "."> offset=1:
opAttrRef symbol "."> unexpected '('
opAttrRef symbol "."> expecting '.'

pExpr> IN: ").x"
pExpr> MATCH (EERR): <EMPTY>
pExpr> ERROR:
pExpr> offset=2:
pExpr> unexpected ").x"
pExpr> expecting "false", "null", "true", '"', '+', '-', '[', digit, identifier, or integer

opFuncCall symbol ")"> IN: ").x"
opFuncCall symbol ")"> MATCH (COK): ')'
opFuncCall symbol ")"> VALUE: ")"

pExpr> IN: "a().x"
pExpr> MATCH (COK): "a()"
pExpr> VALUE: EFuncCall (EVarRef "a") []
```

It seems to me that makeExprParser is not calling opFuncCall second time (compared to how index access debug output looks), but I have no idea why not.

It parses when I decrease opAttrRef priority, but then it produces wrong trees (e.g. right operand of x.a() would be a() which is incorrect, it should be a and then the whole think should be in function call), so I can't use that (I am quite sure current priority is correct, since it's based on the reference of that language).

答:
Your current expression parser looks like the following BNF:

expr = funcOp ;
funcOp = attrOp , { "(" , expr, ")" } ;
attrOp = attrOp , "." , indexOp | indexOp ;
indexOp = term , { "[", expr, "]" } ;
```

<p>Once it finishes parsing <code>funcCall</code>, it will not go back up in the operator table and parse any <code>attrRef</code> or <code>indexRef</code>.</p>

<p>The problem with decreasing the priority of <code>opAttrRef</code> is that parses the left and right hand side of the dot separately, when it seems like you want the parser to read from left to right, and be able to mix any of <code>funcCall</code>, <code>attrRef</code>, or <code>indexRef</code>. So if you want to be able to parse something like <code>a[b](c).d(e)[f]</code>, I'd suggest changing <code>opAttrRef</code> from infix to postfix, and flatten the operator table into:</p>

<pre class="lang-hs prettyprint-override"><code>exprTable = [[Postfix opIndexRef, PostFix opAttrRef, Postfix opFuncCall]]
</code>```

At this point, the parser becomes:

```<code>expr = term , { indexRef | attrRef | funcCall } ;
</code>```

If you need multiple postfix operators being allowed, you can rewrite your expression parser like this:

```<code>p = liftM2 (foldl (flip ($))) pTerm (many (opAttrRef <|> opIndexRef <|> opFuncCall))
</code>```

The p parser can be used as a term parser for makeExprParser, if you want to add arithmetic, logic and other common operators.

Body:
I want to parse expressions like this: a().x. It should look like EAttrRef (EFuncCall (EVarRef "a") []) "x". Unfortunately my expression parser is stopping too soon, it only parses a() and then stops.

1:4:
  |
1 | a().x
  |    ^
unexpected '.'
expecting end of input

Code:

pExpr :: Parser Expr
pExpr = lexeme p & dbg "pExpr" <?> "expression"
  where
    pTerm = try pVarRef <|> pELit
    p = makeExprParser pTerm exprTable
    exprTable = [[Postfix opIndexRef], [InfixL opAttrRef], [Postfix opFuncCall]]
    opAttrRef :: Parser (Expr -> Expr -> Expr)
    opAttrRef = do
      symbol "." & dbg "opAttrRef symbol \".\""
      return r
      where
        r x (EVarRef y) = EAttrRef x y
        r x y = error [qq|opAttrRef got unexpected right operand $y (left operand was $x)|]
    opFuncCall :: Parser (Expr -> Expr)
    opFuncCall = do
      symbol "("
      args <- sepBy pExpr (symbol ",")
      symbol ")" & dbg "opFuncCall symbol \")\""
      return $ \funcExpr -> EFuncCall funcExpr args
    opIndexRef = do
      symbol "["
      e <- pExpr
      symbol "]" & dbg "opIndexRef symbol \"]\""
      return $ \obj -> EIndexRef obj e

Debug output:

opAttrRef symbol "."> IN: "().x"
opAttrRef symbol "."> MATCH (EERR): <EMPTY>
opAttrRef symbol "."> ERROR:
opAttrRef symbol "."> offset=1:
opAttrRef symbol "."> unexpected '('
opAttrRef symbol "."> expecting '.'

pExpr> IN: ").x"
pExpr> MATCH (EERR): <EMPTY>
pExpr> ERROR:
pExpr> offset=2:
pExpr> unexpected ").x"
pExpr> expecting "false", "null", "true", '"', '+', '-', '[', digit, identifier, or integer

opFuncCall symbol ")"> IN: ").x"
opFuncCall symbol ")"> MATCH (COK): ')'
opFuncCall symbol ")"> VALUE: ")"

pExpr> IN: "a().x"
pExpr> MATCH (COK): "a()"
pExpr> VALUE: EFuncCall (EVarRef "a") []

It seems to me that makeExprParser is not calling opFuncCall second time (compared to how index access debug output looks), but I have no idea why not.

It parses when I decrease opAttrRef priority, but then it produces wrong trees (e.g. right operand of x.a() would be a() which is incorrect, it should be a and then the whole think should be in function call), so I can't use that (I am quite sure current priority is correct, since it's based on the reference of that language).

Body:
Your current expression parser looks like the following BNF:

expr = funcOp ;
funcOp = attrOp , { "(" , expr, ")" } ;
attrOp = attrOp , "." , indexOp | indexOp ;
indexOp = term , { "[", expr, "]" } ;

Once it finishes parsing funcCall, it will not go back up in the operator table and parse any attrRef or indexRef.

The problem with decreasing the priority of opAttrRef is that parses the left and right hand side of the dot separately, when it seems like you want the parser to read from left to right, and be able to mix any of funcCall, attrRef, or indexRef. So if you want to be able to parse something like a[b](c).d(e)[f], I'd suggest changing opAttrRef from infix to postfix, and flatten the operator table into:

exprTable = [[Postfix opIndexRef, PostFix opAttrRef, Postfix opFuncCall]]

At this point, the parser becomes:

expr = term , { indexRef | attrRef | funcCall } ;

If you need multiple postfix operators being allowed, you can rewrite your expression parser like this:

p = liftM2 (foldl (flip ($))) pTerm (many (opAttrRef <|> opIndexRef <|> opFuncCall))

The p parser can be used as a term parser for makeExprParser, if you want to add arithmetic, logic and other common operators.


问:
In Kafka, If a client alters the partitions of a topic, Would it create a new topic? Does it cause rebalancing?
In Kafka, If a client alters the partitions of a topic, Would it create a new topic? Does it cause rebalancing ?</p>

答:
Adding Partitions doesn't create new topics. It alters the existing one

Data is not rebalanced when expanding cluster or topics partitions


问:
WebDriverException: 'chromedriver.exe' executable may have wrong permissions
I know there are already a couple threads about this, but I've went over them all, and this is my 3rd day trying to break through and haven't made any improvements. Here is the situation:

I'm trying to use this https://github.com/tejavoo/GooglePlayReviewScraper/blob/master/scraper.py to create a google play review scraper for my research, but continue recieving the following error:

Conda3/Python38/Windows10/Spyder 4.0.1

I've made sure that the chromedriver is in the PATH, and I've made sure it as all permissions, along with spyder and python. I also made sure it was the correct version that matches my google chrome.

I've downloaded the chromedriver, unzipped it into the folder I'm working in.

I also didn't have the Permission error (Winerror 5) Until I recently updated to spyder 4.

Please, what am I missing?

```<code>chromedriver = "C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)
</code>```

The Error

```<code>Traceback (most recent call last):

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

*PermissionError: [WinError 5] Access is denied*

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)

WebDriverException: 'chromedriver.exe' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home
</code>```

And if I change the code and place '' around chromedriver like this

```<code>chromedriver = ("C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
</code>```

I get this

```<code>runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:37: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'
</code>```

And a webdriver.py page opens

Any help is much appreciated!

Cheers :)

Update

I tried the raw string idea as mentioned

```<code>chromedriver = "C:/Users/james/Downloads/ML/New folder/PlayReviews.py"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
</code>```

And it seems to maybe pass it? As now I am on to this error :

```<code>runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:39: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 39, in <module>
    driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'
</code>```

However, this error, actually comes from line 64 of the webdriver.py which opens as a result of running the former

```<code> if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())
</code>```

答:
I have seen similar permission errors when the executable path was not a raw string. Have you tried formatting it like this?</p>

```<code>driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options = options)
</code>```

Body:
I know there are already a couple threads about this, but I've went over them all, and this is my 3rd day trying to break through and haven't made any improvements. Here is the situation:

I'm trying to use this https://github.com/tejavoo/GooglePlayReviewScraper/blob/master/scraper.py to create a google play review scraper for my research, but continue recieving the following error:

Conda3/Python38/Windows10/Spyder 4.0.1

I've made sure that the chromedriver is in the PATH, and I've made sure it as all permissions, along with spyder and python. I also made sure it was the correct version that matches my google chrome.

I've downloaded the chromedriver, unzipped it into the folder I'm working in.

I also didn't have the Permission error (Winerror 5) Until I recently updated to spyder 4.

Please, what am I missing?

chromedriver = "C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

The Error

Traceback (most recent call last):

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 76, in start
    stdin=PIPE)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 104, in __init__
    super(SubprocessPopen, self).__init__(*args, **kwargs)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 800, in __init__
    restore_signals, start_new_session)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\subprocess.py", line 1207, in _execute_child
    startupinfo)

*PermissionError: [WinError 5] Access is denied*

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path = chromedriver, chrome_options = options)

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 73, in __init__
    self.service.start()

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\common\service.py", line 88, in start
    os.path.basename(self.path), self.start_error_message)

WebDriverException: 'chromedriver.exe' executable may have wrong permissions. Please see https://sites.google.com/a/chromium.org/chromedriver/home

And if I change the code and place '' around chromedriver like this

chromedriver = ("C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

I get this

runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:37: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 37, in <module>
    driver = webdriver.Chrome(executable_path= 'chromedriver', chrome_options = 'options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'

And a webdriver.py page opens

Any help is much appreciated!

Cheers :)

Update

I tried the raw string idea as mentioned

chromedriver = "C:/Users/james/Downloads/ML/New folder/PlayReviews.py"
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1200x600') # optional
driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

And it seems to maybe pass it? As now I am on to this error :

runcell(0, 'C:/Users/james/Downloads/ML/New folder/PlayReviews.py')
C:\Users\james\Downloads\ML\New folder\PlayReviews.py:39: DeprecationWarning: use options instead of chrome_options
  driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')
Traceback (most recent call last):

  File "C:\Users\james\Downloads\ML\New folder\PlayReviews.py", line 39, in <module>
    driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options='options')

  File "C:\Users\james\.conda\envs\spyder-4.0.0_1\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 64, in __init__
    desired_capabilities = options.to_capabilities()

AttributeError: 'str' object has no attribute 'to_capabilities'

However, this error, actually comes from line 64 of the webdriver.py which opens as a result of running the former

 if chrome_options:
            warnings.warn('use options instead of chrome_options',
                          DeprecationWarning, stacklevel=2)
            options = chrome_options

        if options is None:
            # desired_capabilities stays as passed in
            if desired_capabilities is None:
                desired_capabilities = self.create_options().to_capabilities()
        else:
            if desired_capabilities is None:
                desired_capabilities = options.to_capabilities()
            else:
                desired_capabilities.update(options.to_capabilities())

Body:
I have seen similar permission errors when the executable path was not a raw string. Have you tried formatting it like this?

driver = webdriver.Chrome(executable_path = r'C:\\Users\\james\\Downloads\\ML\\New folder\\chromedriver.exe', chrome_options = options)


问:
Is it allowed to use Task.Run in an ASP.NET Core controller?
Scenario: I have a web service with a "Delete" ASP.NET Core controller action. The implementation consists of two steps: one cheap after which other operations can already no longer see the deleted data, and a long-running second step which performs the actual deletion.

Is it okay to use Task.Run for the second operation and never await it and so return to the caller very soon? I know that this task could be lost due to application shutdown, but is it even allowed to offload work to the background using Task.Run in ASP.NET Core and never await the resulting task?

答:
I know that this task could be lost due to application shutdown, but is it even allowed to offload work to the background using Task.Run in ASP.NET Core and never await the resulting task?

Oh, sure, nothing will prevent this. .NET and ASP.NET allow you to use Task.Run, and the response will be returned to the user without delay (assuming you ignore the task returned from Task.Run).

Is it okay to use Task.Run for the second operation and never await it and so return to the caller very soon?

You say that you're aware that the task could be lost in an app shutdown. And that's true; so it is entirely possible that the second deletion may never happen, and there will be no error or log message informing you of the fact. Furthermore, since the task is ignored, there will be no notification if that task fails, so if there's something wrong with the deletion code, no logs or anything will notify you of regular failures. If you're OK with that, then using fire-and-forget is fine.

On ASP.NET Core, you don't even need Task.Run; you can just call the (asynchronous) method that does the second delete operation and then ignore the task instead of awaiting it.

Simply ignoring tasks will work (with or without Task.Run), but this does have the negative side effect that ASP.NET isn't aware of the offloaded work at all. So I would recommend registering the task and having something delay the app shutdown until the tasks have a chance to complete. With registration, it is still possible to lose tasks, but registering them reduces the chance of losing tasks.


问:
Are there limits to the number of tables that can be joined in Oracle?
I'm writing a fairly large query, and I have 2 tables, inner joined and 15 tables left-outer joined. when I add the 16, I get ORA-03113: end-of-file on communication channel. If I remove a table to add the new one, the query works fine.

The query runs fine for SQL Server, it's just Oracle that seems to be struggling.

答:
ORA-03113 means that your client application has lost communication with the Oracle shadow process. So you might try a different client tool first.

ORA-03113 also occurs when the Oracle executable is killed, terminated or crashed and the client connections are not orderly closed. You didn't mention you've had to restart Oracle after that so I assume it's client- or network-related. Otherwise you'll have to check the logfiles alert.ora etc...

Please be assured that Oracle handles 15+ tables quite well...


问:
How to pulse a sprite using SpriteKit in SWIFT
I am attempting to "pulse" a sprite in SK/SWIFT. My attempts were crude using For-loops and .setScale, but they were not working (no errors - just no animation). I feel that using SKActions would perhaps be more elegant.

After using some help from below here is my current implementation. However, it is coming up with compile errors;

Expected member name or constructor call after type name &
  Consecutive statement on a line must be separated by a ;

Here is the code I am using:

```<code>SKAction *pulseUp = [SKAction.scaleTo(3.0, duration: 3.0)]
SKAction *pulseDown = [SKAction.scaleTo(1.0, duration: 3.0)]
SKAction *pulse = [SKAction.sequence(pulseUp, pulseDown)]
SKAction *repeat = [SKAction repeatActionForever:pulse]]
[self.playButton runAction: repeat]
</code>```

Any help would be greatly appreciated.

答:
If you want a real pulse effect (ie. once scaled up, instantly get to the original scale and repeat forever, do as follows:</p>
```<code>func addPulseAction(scale: CGFloat = 50, duration: TimeInterval = 0.5) {

    let pulse = SKAction.sequence([
        SKAction.group([
            SKAction.scale(to: scale, duration: duration),
            SKAction.fadeOut(withDuration: duration)
        ]),
        SKAction.group([
            SKAction.scale(to: 1, duration: 0),
            SKAction.fadeIn(withDuration: 0)
        ])
    ])
    let shockwave = SKShapeNode(circleOfRadius: 1)
    node.addChild(shockwave)

    shockwave.run(SKAction.repeatForever(pulse))
}
</code>```

Body:
I am attempting to "pulse" a sprite in SK/SWIFT. My attempts were crude using For-loops and .setScale, but they were not working (no errors - just no animation). I feel that using SKActions would perhaps be more elegant.

After using some help from below here is my current implementation. However, it is coming up with compile errors;

Expected member name or constructor call after type name &
  Consecutive statement on a line must be separated by a ;

Here is the code I am using:

SKAction *pulseUp = [SKAction.scaleTo(3.0, duration: 3.0)]
SKAction *pulseDown = [SKAction.scaleTo(1.0, duration: 3.0)]
SKAction *pulse = [SKAction.sequence(pulseUp, pulseDown)]
SKAction *repeat = [SKAction repeatActionForever:pulse]]
[self.playButton runAction: repeat]

Any help would be greatly appreciated.

Body:
If you want a real pulse effect (ie. once scaled up, instantly get to the original scale and repeat forever, do as follows:

func addPulseAction(scale: CGFloat = 50, duration: TimeInterval = 0.5) {

    let pulse = SKAction.sequence([
        SKAction.group([
            SKAction.scale(to: scale, duration: duration),
            SKAction.fadeOut(withDuration: duration)
        ]),
        SKAction.group([
            SKAction.scale(to: 1, duration: 0),
            SKAction.fadeIn(withDuration: 0)
        ])
    ])
    let shockwave = SKShapeNode(circleOfRadius: 1)
    node.addChild(shockwave)

    shockwave.run(SKAction.repeatForever(pulse))
}


问:
Display 20 records per page in SSRS report
I'm trying to make an ssrs report show 20 rows per page and I've tried using

```<code>=Ceiling(RowNumber(Nothing)/20)
</code>```

THIS DOES NOT WORK.

My rows contain a field that counts a number so it's just making that one field equal 20 for each page. Is there any way to make the tablix object only print a set number of rows per page so it's not reliant on the group by of the dataset?

I've also tried changing that 'nothing' to a field in the dataset but that throws an error.

Here's how my report tablix is set up:

```<code>| Part | Part Description |   Part Qty   | Part Weight |  Total Weight   |

|[Part]|[Part Description]|[SUM(PartQty)]|[Part Weight]|[SUM(TotalWeight)]
</code>```

What I expect to get with the =Ceiling expression:

```<code>| Part | Part Description |   Part Qty   | Part Weight |  Total Weight   |

|PART1 |Part 1 Desc       |12             |5.00        |[60.00]
|PART2 |Part 2 Desc       |3              |5.00        |[15.00]
|PART3 |Part 3 Desc       |5              |5.00        |[25.00]
|PART4 |Part 4 Desc       |7              |5.00        |[35.00]
</code>```

...Continue until 20 rows then page break

This is what I'm getting:

```<code>| Part | Part Description |   Part Qty   | Part Weight |  Total Weight   |

|PART1 |Part 1 Desc       |12            |5.00         |[60.00]
|PART2 |Part 2 Desc       |3             |5.00         |[15.00]
|PART3 |Part 3 Desc       |5             |5.00         |[25.00]
--Page Break
|PART4 |Part 4 Desc       |7             |5.00         |[35.00]
</code>```

The field PartQty will count up to equal 20 then a page break.

答:
You need to do the following:

Add a new row group and the the "group on" option to =CEILING(RowNumber(nothing)/20). This group should be the outermost group so if you only had a details group you could right click the details group and choose "add group => parent group"

Delete the new column if one was just created - we don't need this.

Right-click the new row group you created in hte row gorup panel at the bottom of the screen and click 'Properties'

In the "Page Breaks" section, set the option to 'Between each instance of a group'

Note: Whilst this will do what you want be aware that it won't actually set the number of rows per page, it sets the number of rows per group and then puts a break between each group. If you set the value in CEILING to 100 for instance, each group probably go over several pages.

Body:
I'm trying to make an ssrs report show 20 rows per page and I've tried using

=Ceiling(RowNumber(Nothing)/20)

THIS DOES NOT WORK.

My rows contain a field that counts a number so it's just making that one field equal 20 for each page. Is there any way to make the tablix object only print a set number of rows per page so it's not reliant on the group by of the dataset?

I've also tried changing that 'nothing' to a field in the dataset but that throws an error.

Here's how my report tablix is set up:

| Part | Part Description |   Part Qty   | Part Weight |  Total Weight   |

|[Part]|[Part Description]|[SUM(PartQty)]|[Part Weight]|[SUM(TotalWeight)]

What I expect to get with the =Ceiling expression:

| Part | Part Description |   Part Qty   | Part Weight |  Total Weight   |

|PART1 |Part 1 Desc       |12             |5.00        |[60.00]
|PART2 |Part 2 Desc       |3              |5.00        |[15.00]
|PART3 |Part 3 Desc       |5              |5.00        |[25.00]
|PART4 |Part 4 Desc       |7              |5.00        |[35.00]

...Continue until 20 rows then page break

This is what I'm getting:

| Part | Part Description |   Part Qty   | Part Weight |  Total Weight   |

|PART1 |Part 1 Desc       |12            |5.00         |[60.00]
|PART2 |Part 2 Desc       |3             |5.00         |[15.00]
|PART3 |Part 3 Desc       |5             |5.00         |[25.00]
--Page Break
|PART4 |Part 4 Desc       |7             |5.00         |[35.00]

The field PartQty will count up to equal 20 then a page break.


问:
Is it possible to create a serializer with all histories using django-simple-history?
I'm using django-simple-history to record activities in my models. My idea is having a serializer to aggregate all model's activities and a view to show this information with filters (per model and user).

Something like this  ...api/history/?table=example&user=2, ...api/history/?table=another_example

models

class MyExampleModel(models.Model):
    ...
    history = HistoricalRecords()

class MyAnotherExampleModel(models.Model):
    ...
    history = HistoricalRecords()
```

<p>serializer</p>

<pre class="lang-py prettyprint-override"><code>class HistorySerializer():
    # with all records activities
</code>```

views

class HistoryViewSet():
    # with filter for model and user.
```

答:
You should try django.apps.apps.get_models().
The tables pattern is "Historical MyExampleModel"</p>

```<code>from django.apps import apps

class HistoryListApi(generics.ListAPIView):
    history_managers = []
    for model in apps.get_models():
        if 'Historical' in model._meta.object_name:
            history_managers.append(model)

    history_objects = []
     for manager in history_managers:
          history_objects += list(manager.objects.all())
</code>```

Body:
I'm using django-simple-history to record activities in my models. My idea is having a serializer to aggregate all model's activities and a view to show this information with filters (per model and user).

Something like this  ...api/history/?table=example&user=2, ...api/history/?table=another_example

models

class MyExampleModel(models.Model):
    ...
    history = HistoricalRecords()

class MyAnotherExampleModel(models.Model):
    ...
    history = HistoricalRecords()

serializer

class HistorySerializer():
    # with all records activities

views

class HistoryViewSet():
    # with filter for model and user.

Body:
You should try django.apps.apps.get_models().
The tables pattern is "Historical MyExampleModel"

from django.apps import apps

class HistoryListApi(generics.ListAPIView):
    history_managers = []
    for model in apps.get_models():
        if 'Historical' in model._meta.object_name:
            history_managers.append(model)

    history_objects = []
     for manager in history_managers:
          history_objects += list(manager.objects.all())


问:
Py4J error when creating a spark dataframe using pyspark
I have installed pyspark with python 3.6 and I am using jupyter notebook to initialize a spark session.

```<code>from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("test").enableHieSupport.getOrCreate()
</code>```

which runs without any errors

But I write,

```<code>df = spark.range(10)
df.show()
</code>```

It throws me an error  -->

```<code>Py4JError: An error occurred while calling o54.showString. Trace:
py4j.Py4JException: Method showString([class java.lang.Integer, class java.lang.Integer, class java.lang.Boolean]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
    at py4j.Gateway.invoke(Gateway.java:272)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:745)
</code>```

I dont know why I am facing this issue.

If I do,

```<code>from pyspark import SparkContext
sc = SparkContext()
print(sc.version)

'2.1.0'
</code>```

答:
```<code>import findspark
findspark.init("path of SparkORHadoop ")
from pyspark import SparkContext
</code>```

you need firstly set findspark.init()
and then you can import pyspark

Body:
I have installed pyspark with python 3.6 and I am using jupyter notebook to initialize a spark session.

from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("test").enableHieSupport.getOrCreate()

which runs without any errors

But I write,

df = spark.range(10)
df.show()

It throws me an error  -->

Py4JError: An error occurred while calling o54.showString. Trace:
py4j.Py4JException: Method showString([class java.lang.Integer, class java.lang.Integer, class java.lang.Boolean]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:318)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:326)
    at py4j.Gateway.invoke(Gateway.java:272)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:745)

I dont know why I am facing this issue.

If I do,

from pyspark import SparkContext
sc = SparkContext()
print(sc.version)

'2.1.0'

Body:
import findspark
findspark.init("path of SparkORHadoop ")
from pyspark import SparkContext

you need firstly set findspark.init()
and then you can import pyspark