问:
SICP Ex. 1.17 - "fast-multiply" slower than "multiply"?
The following function as introduction to this exercise illustrates multiplication defined in terms of addition. This is the simplest "easy to write down", recursive definition.

(define (star a b)
  (if (= b 0)
      0
      (+ a (star a (- b 1)))))
```

<p>First thing I did when I saw that, following previous exercises, is write an iterative form which doesn't blow the stack:</p>

<pre class="lang-lisp prettyprint-override"><code>(define (star a b)
  (star-iter a b 0))
(define (star-iter a counter sum)
  (if (= counter 0)
      sum
      (star-iter a (- counter 1) (+ a sum))))
</code>```

Exercise 1.17 then encourages us to find an invariant so as to reduce the problem size, the idea being to get from O(n) to O(logn) number of steps (without, when that particular step is carried out, doing anything to update the result - all we do in that step is to reduce/transform the problem definition - that being what is meant by 'find an invariant') (see line 3 of the first code block below - nothing is being added to the result in that step).

For the fast version, the question says we should use the functions halve and double and seems to imply these would be available as machine operations (constant time?).  I've implemented the "fast" version just spoofing those functions as follows:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? a)      (fast-star (/ a 2) (* 2 b)))
        (else      (+ a (fast-star a       (- b 1))))))
```

<p>And the same thing in iterative form (i.e. O(1) space):</p>

<p>(note how <code>+ a</code> on line 4 above just moves to the accumulator, end of line 6 below, to get this in tail position)</p>

<pre class="lang-lisp prettyprint-override"><code>(define (fast-star b)
  (fast-star-iter a b 0))
(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? a) (fast-star-iter (/ a 2) (* 2 b) sum))
        (else      (fast-star-iter a       (- b 1) (+ a sum)))))
</code>```

So this is kind of a "what's the point" question - these functions are slower than the first two given above. The first of these four functions blows the stack so it's not useful. But the second doesn't. That one is faster than any of these two "fast" versions under my testing.

Am I missing anything here?  Curious if there's a way to implement halve and double so they actually give the log(n) result being suggested here. There must be otherwise there would have been no sense in the question.

Note that the order of a & b matters a lot if they are different sizes - like multiplying 2, 100 times or 100, 2 times, the first being 100 steps, the latter 2 steps. That would be something to add to this function later. But curious about halve and double to start with.

答:
The idea is that instead of using the formula

```<code>a*n = a+a*(n-1)
</code>```

you should use the formula

```<code>a*n = a*(n/2)+a*(n/2)
</code>```

and take care about the cases when n is even and n is odd.  Applying this will give you O(log n) complexity instead of O(n).

Body:
The following function as introduction to this exercise illustrates multiplication defined in terms of addition. This is the simplest "easy to write down", recursive definition.

(define (star a b)
  (if (= b 0)
      0
      (+ a (star a (- b 1)))))

First thing I did when I saw that, following previous exercises, is write an iterative form which doesn't blow the stack:

(define (star a b)
  (star-iter a b 0))
(define (star-iter a counter sum)
  (if (= counter 0)
      sum
      (star-iter a (- counter 1) (+ a sum))))

Exercise 1.17 then encourages us to find an invariant so as to reduce the problem size, the idea being to get from O(n) to O(logn) number of steps (without, when that particular step is carried out, doing anything to update the result - all we do in that step is to reduce/transform the problem definition - that being what is meant by 'find an invariant') (see line 3 of the first code block below - nothing is being added to the result in that step).

For the fast version, the question says we should use the functions halve and double and seems to imply these would be available as machine operations (constant time?).  I've implemented the "fast" version just spoofing those functions as follows:

(define (fast-star a b)
  (cond ((or (= b 0) (= a 0)) 0)
        ((even? a)      (fast-star (/ a 2) (* 2 b)))
        (else      (+ a (fast-star a       (- b 1))))))

And the same thing in iterative form (i.e. O(1) space):

(note how + a on line 4 above just moves to the accumulator, end of line 6 below, to get this in tail position)

(define (fast-star b)
  (fast-star-iter a b 0))
(define (fast-star-iter a b sum)
  (cond ((or (= a 0) (= b 0)) sum)
        ((even? a) (fast-star-iter (/ a 2) (* 2 b) sum))
        (else      (fast-star-iter a       (- b 1) (+ a sum)))))

So this is kind of a "what's the point" question - these functions are slower than the first two given above. The first of these four functions blows the stack so it's not useful. But the second doesn't. That one is faster than any of these two "fast" versions under my testing.

Am I missing anything here?  Curious if there's a way to implement halve and double so they actually give the log(n) result being suggested here. There must be otherwise there would have been no sense in the question.

Note that the order of a & b matters a lot if they are different sizes - like multiplying 2, 100 times or 100, 2 times, the first being 100 steps, the latter 2 steps. That would be something to add to this function later. But curious about halve and double to start with.

Body:
The idea is that instead of using the formula

a*n = a+a*(n-1)

you should use the formula

a*n = a*(n/2)+a*(n/2)

and take care about the cases when n is even and n is odd.  Applying this will give you O(log n) complexity instead of O(n).


来源: stackexchange

问:
How to specify a cluster name for a kubernetes cluster
I'm trying to initialize a Kubernetes cluster using Kubeadm.

I basically have 3 questions. 1 big one and 2 "sub questions" if you will

I am having difficulty in assigning a cluster name to the cluster. When I read the kubeadm docs, it has a flag --config where you can specify the yml file which will be used to initialize the cluster.

There is an example yml file specified on their page but that file has a lot of configurations that I do not know how to set. So therefore I created a config file as below:

```<code>apiVersion: kubeadm.k8s.io/v1beta1
kind: InitConfiguration
advertiseAddress: "10.62.194.4" # is this correct (see below)
bindPort: 6443
---
apiVersion: kubeadm.k8s.io/v1beta1
kind: ClusterConfiguration
networking:
    podSubnet: "10.62.194.0/16" # is this correct (see below)
controlPlaneEndpoint: "10.62.194.4:6443" #is this correct (see below)
clusterName: "dev-cluster"
</code>```

I initialize like this sudo kubeadm init --config=config.yml

However, when I try to initialize the above file, it doesnt work as expected and times out after a while

The error is similar to this:
    Unfortunately, an error has occurred: timed out waiting for the condition
    This error is likely caused by:
        - The kubelet is not running
        - The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

When I do a docker ps I can see kube-system containers all running, with no exited containers. The containers that are running are
kube-scheduler
kube-controller-manager_kube-controller
kube-apiserver
etcd-ubuntu
kube-controller-manager-ubuntu-xenial

Second question: are cluster names important? I want to set a cluster name because I am planning to set up 3 clusters for 3 different environments, which would mean 3 different contexts. If all 3 have the same default cluster name, will there be an issue?

Also a final third part to this question if the IP of the server ( this is also the master ) I am running the commands is 10.62.194.4 are the fields advertiseAddress, podSubnet and controlPlaneEndpoint correct? I am planning to add one more node to this cluster and the IP of that node is 10.62.194.5
Thanks

答: I know it's a little bit late but it seems the podSubnet is overlapping the subnet you have your nodes. I would use a different /16 subnet for this and assign the nodes (VMs or bare metal machines) to another subnet.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to initialize a Kubernetes cluster using Kubeadm.

I basically have 3 questions. 1 big one and 2 "sub questions" if you will

I am having difficulty in assigning a cluster name to the cluster. When I read the kubeadm docs, it has a flag --config where you can specify the yml file which will be used to initialize the cluster.

There is an example yml file specified on their page but that file has a lot of configurations that I do not know how to set. So therefore I created a config file as below:

apiVersion: kubeadm.k8s.io/v1beta1
kind: InitConfiguration
advertiseAddress: "10.62.194.4" # is this correct (see below)
bindPort: 6443
---
apiVersion: kubeadm.k8s.io/v1beta1
kind: ClusterConfiguration
networking:
    podSubnet: "10.62.194.0/16" # is this correct (see below)
controlPlaneEndpoint: "10.62.194.4:6443" #is this correct (see below)
clusterName: "dev-cluster"

I initialize like this sudo kubeadm init --config=config.yml

However, when I try to initialize the above file, it doesnt work as expected and times out after a while

The error is similar to this:
    Unfortunately, an error has occurred: timed out waiting for the condition
    This error is likely caused by:
        - The kubelet is not running
        - The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

When I do a docker ps I can see kube-system containers all running, with no exited containers. The containers that are running are
kube-scheduler
kube-controller-manager_kube-controller
kube-apiserver
etcd-ubuntu
kube-controller-manager-ubuntu-xenial

Second question: are cluster names important? I want to set a cluster name because I am planning to set up 3 clusters for 3 different environments, which would mean 3 different contexts. If all 3 have the same default cluster name, will there be an issue?

Also a final third part to this question if the IP of the server ( this is also the master ) I am running the commands is 10.62.194.4 are the fields advertiseAddress, podSubnet and controlPlaneEndpoint correct? I am planning to add one more node to this cluster and the IP of that node is 10.62.194.5
Thanks


问:
how to set document title of new open window?
I am doing as below code to set document title for new open window

var downloadWindow = window.open("https://www.google.com/", "_blank");
downloadWindow.document.title = "my title";```

If we try to execute above snippet in console in google chrome, we can see while loading, We can see "my title", but same behaviour I want to be in internet explore?

How we can achieve same behaviour in internet explore?

答:
I think that due to security reasons, you will not able to see the modified title on the newly open window.

As a workaround, I suggest you try to display the alert message that informs the user that he is opening the downloading window.

Example:

<!DOCTYPE html>

<title>Test</title>

   Test page

 ```

Let us know if you have any further questions. We will try to provide suggestions for it.

Body:
I am doing as below code to set document title for new open window

var downloadWindow = window.open("https://www.google.com/", "_blank");
downloadWindow.document.title = "my title";

If we try to execute above snippet in console in google chrome, we can see while loading, We can see "my title", but same behaviour I want to be in internet explore?

How we can achieve same behaviour in internet explore?

Body:
I think that due to security reasons, you will not able to see the modified title on the newly open window.

As a workaround, I suggest you try to display the alert message that informs the user that he is opening the downloading window.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
 <script>
    alert("You are moving to download window...");
    var downloadWindow = window.open("https://example.com", "_blank");
 </script>
</head>
<body>
   Test page

</body>
</html>

Let us know if you have any further questions. We will try to provide suggestions for it.


问:
iOS On Demand resources download fine - but they cannot be found in the main bundle by the app at the point I need to use them
I've gone through the documentation and all the questions on SO related to On Demand assets in iOS and can't find an answer so I'm hoping you can help. I have an app that was able to access files fine (specifically video mp4 files that were in a group/folder with the name "GameVideos"). The code I used to do this is:

```<code>guard let url = Bundle.main.url(forResource: videoName, withExtension: "mp4") else {
   print("\(videoName) not found")
   return
}

let item = AVPlayerItem(url: url)
self.player1 = AVPlayer(playerItem: item)
self.videoNode1 = SKVideoNode(avPlayer: self.player1)
</code>```

Now that I've switched to making the video 'On demand' I see the 'not found' message get printed. When it's not listed as an on demand resource, I didn't need to reference the subdirectory - it worked fine without it (though I tried adding it in just to see). I'm also happy that I've not misspelt the file name as that also worked fine.

When creating the On Demand resource - I've set this up with tags and use the following code to call the resources (this code is located in the GameViewController.swift and inside the "viewDidLoad" override - I'm building a SpriteKit game so there is only one view controller - all the other logic is handled in the SKScenes.):

```<code>let tags = NSSet(array: [
            "OD2",
            "OD3",
            "OD4",
            "OD5",
            "OD6",
            "OD7",
            "OD8",
        ])

  let resourceRequest = NSBundleResourceRequest(tags: tags as! Set<String>)

  resourceRequest.conditionallyBeginAccessingResources(completionHandler: {(resourcesAvailable: Bool) in
            if !resourcesAvailable  { // if resources not available - start download
                resourceRequest.beginAccessingResources(completionHandler: {(err: Error?) in
                    if let error = err {
                        print("Error getting On Demand Resources: \(error)")
                    }
                })
            }
        })
</code>```

This code seems to work and I can see the On Demand packages being downloaded successfully in the Disk monitor on Xcode.

Other things I've tried:
I've double checked the target membership of the video and it is correctly assigned.

I've tried calling the Bundle.Main.url with a subdirectory of the folder listed (this didn't work either)
I've tried renaming the folder directory (as it had a space in the name)
I've tried cleaning the build many times

None of the above has worked... what am I doing wrong?? Any guesses or pointers would be hugely appreciated.

答: So after lots of trial and error - I placed the variable 'resourceRequest' in the global scope and it works - the message on the XCode disk changes from "downloaded" to "in use". As you can see in my code, I had previously defined 'resourceRequest' within the GameViewController. I had thought this would work for a SpriteKit game as the GameViewController loads and then it controls all the scenes (so I didn't think it went out of scope).  Someone smarter than me will hopefully say why this works - but for the minute - I'm just happy I can move on and launch my app (Apple's documentation on this stuff is terrible)</p>

Body:
I've gone through the documentation and all the questions on SO related to On Demand assets in iOS and can't find an answer so I'm hoping you can help. I have an app that was able to access files fine (specifically video mp4 files that were in a group/folder with the name "GameVideos"). The code I used to do this is:

guard let url = Bundle.main.url(forResource: videoName, withExtension: "mp4") else {
   print("\(videoName) not found")
   return
}

let item = AVPlayerItem(url: url)
self.player1 = AVPlayer(playerItem: item)
self.videoNode1 = SKVideoNode(avPlayer: self.player1)

Now that I've switched to making the video 'On demand' I see the 'not found' message get printed. When it's not listed as an on demand resource, I didn't need to reference the subdirectory - it worked fine without it (though I tried adding it in just to see). I'm also happy that I've not misspelt the file name as that also worked fine.

When creating the On Demand resource - I've set this up with tags and use the following code to call the resources (this code is located in the GameViewController.swift and inside the "viewDidLoad" override - I'm building a SpriteKit game so there is only one view controller - all the other logic is handled in the SKScenes.):

let tags = NSSet(array: [
            "OD2",
            "OD3",
            "OD4",
            "OD5",
            "OD6",
            "OD7",
            "OD8",
        ])

  let resourceRequest = NSBundleResourceRequest(tags: tags as! Set<String>)

  resourceRequest.conditionallyBeginAccessingResources(completionHandler: {(resourcesAvailable: Bool) in
            if !resourcesAvailable  { // if resources not available - start download
                resourceRequest.beginAccessingResources(completionHandler: {(err: Error?) in
                    if let error = err {
                        print("Error getting On Demand Resources: \(error)")
                    }
                })
            }
        })

This code seems to work and I can see the On Demand packages being downloaded successfully in the Disk monitor on Xcode.

Other things I've tried:
I've double checked the target membership of the video and it is correctly assigned.

I've tried calling the Bundle.Main.url with a subdirectory of the folder listed (this didn't work either)
I've tried renaming the folder directory (as it had a space in the name)
I've tried cleaning the build many times

None of the above has worked... what am I doing wrong?? Any guesses or pointers would be hugely appreciated.


问:
I am getting a Sql Syntax error while performing update query in java( java.sql.sqlsyntaxerrorexception you have an error in your sql syntax)
ERROR=(java.sql.SQL.SyntaxErrorException:You have an error in your SQL syntax;check the manual that corresponds to your MySQL server version for the right syntax to use near '?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=aman036' at line 1)

I am beginner in programming so any help will be appreciated. Here is my code:-

```<code>   Connection Con=null;
   PreparedStatement pst=null;
   ResultSet rs=null;

    String query="UPDATE cashier SET First_Name=?, Last_Name=?, Contact=?, Email_ID=?  WHERE Username=?";
    try{
        Class.forName("com.mysql.cj.jdbc.Driver");
        Con=DriverManager.getConnection("jdbc:mysql://localhost/billing","Aman","Amanbhattt");
        pst=Con.prepareStatement(query);
        pst.setString(1,NameField.getText());
        pst.setString(2,LastNameField.getText());
        pst.setString(3,ContactField.getText());
        pst.setString(4,EmailField.getText());
        pst.setString(5,UsernameField.getText());
        pst.executeUpdate(query);
        JOptionPane.showMessageDialog(null,"Data Updated Successfully");
        Con.close();
</code>```

答:
@Aman

I d'not get your full error but from your code i identified you are not handle sql special characters in your code. you need to add escape character for your sql query.

```<code>MySQL server version for the right syntax to use near '?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=aman036'
</code>```

In your Error Message I'm able see username append with  single quotes aman036'  so you need to remove that.

Please use the following code to remove special character in your sql query string

```<code>public String escapeMetaCharacters(String inputString){
    final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};

    for (int i = 0 ; i < metaCharacters.length ; i++){
        if(inputString.contains(metaCharacters[i])){
            inputString = inputString.replace(metaCharacters[i],"\\"+metaCharacters[i]);
        }
    }
    return inputString;
}

String query="UPDATE cashier SET First_Name=?, Last_Name=?, Contact=?, Email_ID=?  WHERE Username=?";
try{
    Class.forName("com.mysql.cj.jdbc.Driver");
    Con=DriverManager.getConnection("jdbc:mysql://localhost/billing","Aman","Amanbhattt");
    pst=Con.prepareStatement(query);
    pst.setString(1,escapeMetaCharacters(NameField.getText()));
    pst.setString(2,escapeMetaCharacters(LastNameField.getText()));
    pst.setString(3,escapeMetaCharacters(ContactField.getText()));
    pst.setString(4,escapeMetaCharacters(EmailField.getText()));
    pst.setString(5,escapeMetaCharacters(UsernameField.getText()));
    pst.executeUpdate(query);
    JOptionPane.showMessageDialog(null,"Data Updated Successfully");
    Con.close();
</code>```

I know prepared Statement no need special character handling. But some times it's happened in prepared statement also. so please try this and let me know the issue resolved or not

I hope it helps you thanks

Body:
ERROR=(java.sql.SQL.SyntaxErrorException:You have an error in your SQL syntax;check the manual that corresponds to your MySQL server version for the right syntax to use near '?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=aman036' at line 1)

I am beginner in programming so any help will be appreciated. Here is my code:-

   Connection Con=null;
   PreparedStatement pst=null;
   ResultSet rs=null;

    String query="UPDATE cashier SET First_Name=?, Last_Name=?, Contact=?, Email_ID=?  WHERE Username=?";
    try{
        Class.forName("com.mysql.cj.jdbc.Driver");
        Con=DriverManager.getConnection("jdbc:mysql://localhost/billing","Aman","Amanbhattt");
        pst=Con.prepareStatement(query);
        pst.setString(1,NameField.getText());
        pst.setString(2,LastNameField.getText());
        pst.setString(3,ContactField.getText());
        pst.setString(4,EmailField.getText());
        pst.setString(5,UsernameField.getText());
        pst.executeUpdate(query);
        JOptionPane.showMessageDialog(null,"Data Updated Successfully");
        Con.close();

Body:
@Aman

I d'not get your full error but from your code i identified you are not handle sql special characters in your code. you need to add escape character for your sql query.

MySQL server version for the right syntax to use near '?, Last_Name=?, Contact=?, Email_ID=? WHERE Username=aman036'

In your Error Message I'm able see username append with  single quotes aman036'  so you need to remove that.

Please use the following code to remove special character in your sql query string

public String escapeMetaCharacters(String inputString){
    final String[] metaCharacters = {"\\","^","$","{","}","[","]","(",")",".","*","+","?","|","<",">","-","&","%"};

    for (int i = 0 ; i < metaCharacters.length ; i++){
        if(inputString.contains(metaCharacters[i])){
            inputString = inputString.replace(metaCharacters[i],"\\"+metaCharacters[i]);
        }
    }
    return inputString;
}

String query="UPDATE cashier SET First_Name=?, Last_Name=?, Contact=?, Email_ID=?  WHERE Username=?";
try{
    Class.forName("com.mysql.cj.jdbc.Driver");
    Con=DriverManager.getConnection("jdbc:mysql://localhost/billing","Aman","Amanbhattt");
    pst=Con.prepareStatement(query);
    pst.setString(1,escapeMetaCharacters(NameField.getText()));
    pst.setString(2,escapeMetaCharacters(LastNameField.getText()));
    pst.setString(3,escapeMetaCharacters(ContactField.getText()));
    pst.setString(4,escapeMetaCharacters(EmailField.getText()));
    pst.setString(5,escapeMetaCharacters(UsernameField.getText()));
    pst.executeUpdate(query);
    JOptionPane.showMessageDialog(null,"Data Updated Successfully");
    Con.close();

I know prepared Statement no need special character handling. But some times it's happened in prepared statement also. so please try this and let me know the issue resolved or not

I hope it helps you thanks


问:
Xamarin save image from imageButton
I have a page with an image button that displays a blank profile pic. The user can tap on it and it opens up a file dialog to select a picture from their gallery. After selecting a picture, the user sees the image displayed on the image button on the page. I set the image source like this:

```<code>private async void ImgStudentImage_Clicked(object sender, EventArgs e)
{
    Stream stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
    if (stream != null)
    {
        imgButton.Source = ImageSource.FromStream(() => stream);
    }

}
</code>```

This is all good, but when the save button is clicked/tapped how do I save the image? I was thinking that upon clicking the save button I could access the image using something like

```<code>string pth = imgButton.Source.ToString();
std.Picture = File.ReadAllBytes(pth);
</code>```

Then I could save the image as a byte array, but .Source.ToString() returns "Xamarin.Forms.StreamingImageSource" and it throws this error:

```<code>System.IO.FileNotFoundException
Could not find file 'C:\Xamarin\DJB\DJB\DJB.UWP\bin\x86\Debug\AppX\Xamarin.Forms.StreamImageSource'.
</code>```

Is there a way to retrieve the image from the imageButton?

答:
As of now, this cannot be done with pure XF what you have to do is convert this image to its respective native type and then convert them to your desired type.

For instance, in Android, you would do something like :

```<code>public static async Task<Bitmap> GetBitmapFromImageSourceAsync(ImageSource source, Context context)
{
    var handler = GetHandler(source);
    var returnValue = (Bitmap)null;
    returnValue = await handler.LoadImageAsync(source, context);
    return returnValue;
}
</code>```

You can check my blog here for a full-fledged solution.

Note that the blog does not have byte[] conversion from the native types, But is easily available on Stack and Xamarin Forums.

Feel free to get back if you have queries

Good luck.

Title: Xamarin save image from imageButton

Body:
I have a page with an image button that displays a blank profile pic. The user can tap on it and it opens up a file dialog to select a picture from their gallery. After selecting a picture, the user sees the image displayed on the image button on the page. I set the image source like this:

private async void ImgStudentImage_Clicked(object sender, EventArgs e)
{
    Stream stream = await DependencyService.Get<IPhotoPickerService>().GetImageStreamAsync();
    if (stream != null)
    {
        imgButton.Source = ImageSource.FromStream(() => stream);
    }

}

This is all good, but when the save button is clicked/tapped how do I save the image? I was thinking that upon clicking the save button I could access the image using something like

string pth = imgButton.Source.ToString();
std.Picture = File.ReadAllBytes(pth);

Then I could save the image as a byte array, but .Source.ToString() returns "Xamarin.Forms.StreamingImageSource" and it throws this error:

System.IO.FileNotFoundException
Could not find file 'C:\Xamarin\DJB\DJB\DJB.UWP\bin\x86\Debug\AppX\Xamarin.Forms.StreamImageSource'.

Is there a way to retrieve the image from the imageButton?

Body:
As of now, this cannot be done with pure XF what you have to do is convert this image to its respective native type and then convert them to your desired type.

For instance, in Android, you would do something like :

public static async Task<Bitmap> GetBitmapFromImageSourceAsync(ImageSource source, Context context)
{
    var handler = GetHandler(source);
    var returnValue = (Bitmap)null;
    returnValue = await handler.LoadImageAsync(source, context);
    return returnValue;
}

You can check my blog here for a full-fledged solution.

Note that the blog does not have byte[] conversion from the native types, But is easily available on Stack and Xamarin Forums.

Feel free to get back if you have queries

Good luck.


问:
rename a directory or a file
I'm using Laravel 5.0 Facades Storage

use Illuminate\Support\Facades\Storage;

and I can use it like

```<code>Storage::..
</code>```

In the Laravel 5.0 Docs,there's nothing like rename a file or folder from the storage.

Any help, ideas, clues, suggestions, recommendations on how to rename a file or folder using the Storage?

答:
You can rename directories using</p>

```<code>Storage::rename('oldFolder/', 'newFolder/');
</code>```

ContentLicense: CC BY-SA 3.0

Title: rename a directory or a file

Body:
I'm using Laravel 5.0 Facades Storage

use Illuminate\Support\Facades\Storage;

and I can use it like

Storage::..

In the Laravel 5.0 Docs,there's nothing like rename a file or folder from the storage.

Any help, ideas, clues, suggestions, recommendations on how to rename a file or folder using the Storage?

Body:
You can rename directories using

Storage::rename('oldFolder/', 'newFolder/');


问:
Xamarin Android install flags
I'm building an Xamarin android admin app meaning that the app will be the device admin but in order to be able to uninstall the app while developing I need to add to the android manifest android:testOnly="true"
but then it fails at deployment I get the following error

```<code>Mono.AndroidTools.InstallFailedException: Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]
</code>```

and to avoid that error I need to pass an install flag with adb as written this stack overflow answer

how do I do that in VS.

答:
First of all, please archive your application then export the xxx.apk file. Note: when you archive your application, please notice following settings.

unselect following settings

select following settings.

For example, I archive my application to root path of F desk like following screenshot.

Then, open the adb command to click the icon like following screenshot.

Enter the F: in the adb console. Then enter the adb install -t -r com.companyname.app25.apk like following screenshot(please make sure your android emulator is running).

In the end, you will found your apk file was installed.

Title: Xamarin Android install flags

Body:
I'm building an Xamarin android admin app meaning that the app will be the device admin but in order to be able to uninstall the app while developing I need to add to the android manifest android:testOnly="true"
but then it fails at deployment I get the following error

Mono.AndroidTools.InstallFailedException: Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]

and to avoid that error I need to pass an install flag with adb as written this stack overflow answer

how do I do that in VS.


问:
How to scrape data from flexbox element/container with Python and Beautiful Soup
I am trying to scrape data from a utility website using python, beautiful soup and selenium. The data that I am trying to scrape is stuff like: time, cause, status, etc. When I run a typical page request, parse the page, and parse the data that I am looking for (data in id="OutageListTable"), and print it, the divs and strings are nowhere to be found. When I inspect the page element, the data is there, but it is in a flex container.

This is the code that I am using:

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import urllib3
from selenium import webdriver

my_url = 'https://www.pse.com/outage/outage-map'

browser = webdriver.Firefox()
browser.get(my_url)

html = browser.page_source
page_soup = soup(html, features='lxml')

outage_list = page_soup.find(id='OutageListTable')
print(outage_list)

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

How do you retrieve information that is in a flex/flexbox container? I am not finding any resources online to help me figure it out.

答:
You are overthinking the problem. First there is no flexboard container. It's a simple case of assigning the right div class. You should be looking at div class_=col-xs-12 col-sm-6 col-md-4 listView-container

```<code>from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from time import sleep

# create object for chrome options
chrome_options = Options()
base_url = 'https://www.pse.com/outage/outage-map'

chrome_options.add_argument('disable-notifications')
chrome_options.add_argument('--disable-infobars')
chrome_options.add_argument('start-maximized')
chrome_options.add_argument('user-data-dir=C:\\Users\\username\\AppData\\Local\\Google\\Chrome\\User Data\\Default')
# To disable the message, "Chrome is being controlled by automated test software"
chrome_options.add_argument("disable-infobars")
# Pass the argument 1 to allow and 2 to block
chrome_options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 2
    })
# invoke the webdriver
browser = webdriver.Chrome(executable_path = r'C:/Users/username/Documents/playground_python/chromedriver.exe',
                          options = chrome_options)
browser.get(base_url)
delay = 5 #secods

while True:
    try:
        WebDriverWait(browser, delay)
        print ("Page is ready")
        sleep(5)
        html = browser.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
        #print(html)
        soup = BeautifulSoup(html, "html.parser")
        for item_n in soup.find_all('div', class_='col-xs-12 col-sm-6 col-md-4 listView-container'):
            for item_n_text in item_n.find_all(name="span"):
                print(item_n_text.text)
    except TimeoutException:
        print ("Loading took too much time!-Try again")
# close the automated browser
browser.close()

Cause:
Accident
Status:
Crew assigned
Last updated:
06/02 11:00 PM
9. Woodinville
Start time:
06/02 08:29 PM
Est. restoration time:
06/03 03:30 AM
Customers impacted:
2
Cause:
Under Investigation
Status:
Crew assigned
Last updated:
06/03 12:15 AM
Page is ready
1. Bellingham
Start time:
06/02 06:09 PM
Est. restoration time:
06/03 06:30 AM
Customers impacted:
1
Cause:
Trees/Vegetation
Status:
Crew assigned
Last updated:
06/02 11:50 PM
2. Deming
Start time:
06/02 07:10 PM
Est. restoration time:
06/03 03:30 AM
</code>```

Body:
I am trying to scrape data from a utility website using python, beautiful soup and selenium. The data that I am trying to scrape is stuff like: time, cause, status, etc. When I run a typical page request, parse the page, and parse the data that I am looking for (data in id="OutageListTable"), and print it, the divs and strings are nowhere to be found. When I inspect the page element, the data is there, but it is in a flex container.

This is the code that I am using:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import urllib3
from selenium import webdriver

my_url = 'https://www.pse.com/outage/outage-map'

browser = webdriver.Firefox()
browser.get(my_url)

html = browser.page_source
page_soup = soup(html, features='lxml')

outage_list = page_soup.find(id='OutageListTable')
print(outage_list)

browser.quit()

How do you retrieve information that is in a flex/flexbox container? I am not finding any resources online to help me figure it out.

Body:
You are overthinking the problem. First there is no flexboard container. It's a simple case of assigning the right div class. You should be looking at div class_=col-xs-12 col-sm-6 col-md-4 listView-container

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from time import sleep

# create object for chrome options
chrome_options = Options()
base_url = 'https://www.pse.com/outage/outage-map'

chrome_options.add_argument('disable-notifications')
chrome_options.add_argument('--disable-infobars')
chrome_options.add_argument('start-maximized')
chrome_options.add_argument('user-data-dir=C:\\Users\\username\\AppData\\Local\\Google\\Chrome\\User Data\\Default')
# To disable the message, "Chrome is being controlled by automated test software"
chrome_options.add_argument("disable-infobars")
# Pass the argument 1 to allow and 2 to block
chrome_options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 2
    })
# invoke the webdriver
browser = webdriver.Chrome(executable_path = r'C:/Users/username/Documents/playground_python/chromedriver.exe',
                          options = chrome_options)
browser.get(base_url)
delay = 5 #secods

while True:
    try:
        WebDriverWait(browser, delay)
        print ("Page is ready")
        sleep(5)
        html = browser.execute_script("return document.getElementsByTagName('html')[0].innerHTML")
        #print(html)
        soup = BeautifulSoup(html, "html.parser")
        for item_n in soup.find_all('div', class_='col-xs-12 col-sm-6 col-md-4 listView-container'):
            for item_n_text in item_n.find_all(name="span"):
                print(item_n_text.text)
    except TimeoutException:
        print ("Loading took too much time!-Try again")
# close the automated browser
browser.close()

Cause:
Accident
Status:
Crew assigned
Last updated:
06/02 11:00 PM
9. Woodinville
Start time:
06/02 08:29 PM
Est. restoration time:
06/03 03:30 AM
Customers impacted:
2
Cause:
Under Investigation
Status:
Crew assigned
Last updated:
06/03 12:15 AM
Page is ready
1. Bellingham
Start time:
06/02 06:09 PM
Est. restoration time:
06/03 06:30 AM
Customers impacted:
1
Cause:
Trees/Vegetation
Status:
Crew assigned
Last updated:
06/02 11:50 PM
2. Deming
Start time:
06/02 07:10 PM
Est. restoration time:
06/03 03:30 AM


问:
Pass command line arg to react-native run-ios through Xcode
I am trying to set up different .env files depending on the scheme which is being built through Xcode. I am using react-native-config.

If I run the following command through terminal, it works as expected

```<code>ENVFILE=.env.production react-native run-ios
</code>```

However, I am trying to pass the ENVFILE via Xcode.

I have added an Argument as shown in the picture, however it does not work.

This is a React Native project and my config files sit one level above the ios directory. This could potentially be the problem. However, modifying the arg to ENVFILE=../config/.env.production does not resolve the issue.

答:
Your question is about how to switch react-native-config environments for iOS and it is answered in docs - https://github.com/luggit/react-native-config#ios-1 .

Arguments passed on Launch is different thing and intended to be used only for debug and this arguments apply on built binary app.

Body:
I am trying to set up different .env files depending on the scheme which is being built through Xcode. I am using react-native-config.

If I run the following command through terminal, it works as expected

ENVFILE=.env.production react-native run-ios

However, I am trying to pass the ENVFILE via Xcode.

I have added an Argument as shown in the picture, however it does not work.

This is a React Native project and my config files sit one level above the ios directory. This could potentially be the problem. However, modifying the arg to ENVFILE=../config/.env.production does not resolve the issue.


问:
SonarQube 5 Service account permissions
We are currently running SonarQube 5.2 and are performing a test upgrade to SonarQube 5.6, we have had this issue with Sonar 5.4 as well, but never upgraded in production.

When we use the same service account on the same server in the same root directory, the service is unable to start. It claims it is unable to get a node lock, always on the same file and directory, node 49, which is the last one of the nodes. The file and folder are successfully created.

The service account has full permissions on the D:\Sonar folder and all folders below.

I have tested and confirmed that the service does start up when i make it a local administrator, but this is not desired, so i am looking for the required permissions to start up the service. The service also starts if i configure it as local system, but we dont want this either.

What more permissions should i give to the SonarQube Service Account in order to start up ?

Any advise is welcome.

Nico

```<code>2016.06.10 14:42:32 INFO  app[o.s.a.AppFileSystem] Cleaning or creating temp directory D:\Sonar\sonarqube-5.6\temp
2016.06.10 14:42:32 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[es]: C:\Program Files\Java\jre1.8.0_91\bin\java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=D:\Sonar\sonarqube-5.6\temp -javaagent:C:\Program Files\Java\jre1.8.0_91\lib\management-agent.jar -cp ./lib/common/*;./lib/search/* org.sonar.search.SearchServer D:\Sonar\sonarqube-5.6\temp\sq-process3739686975987017449properties
2016.06.10 14:42:34 INFO   es[o.s.p.ProcessEntryPoint]  Starting es
2016.06.10 14:42:34 INFO   es[o.s.s.EsSettings]  Elasticsearch listening on 127.0.0.1:9006
2016.06.10 14:42:34 INFO   es[o.elasticsearch.node]  [sonar-1465562551839] version[1.7.5], pid[29336], build[00f95f4/2016-02-02T09:55:30Z]
2016.06.10 14:42:34 INFO   es[o.elasticsearch.node]  [sonar-1465562551839] initializing ...
2016.06.10 14:42:34 INFO   es[o.e.plugins]  [sonar-1465562551839] loaded [], sites []
2016.06.10 14:42:35 WARN   es[o.s.p.ProcessEntryPoint]  Fail to start es
org.elasticsearch.ElasticsearchIllegalStateException: Failed to obtain node lock, is the following location writable?: [D:\Sonar\sonarqube-5.6\data\es\sonarqube]
    at org.elasticsearch.env.NodeEnvironment.<init>(NodeEnvironment.java:164) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.node.internal.InternalNode.<init>(InternalNode.java:165) ~[elasticsearch-1.7.5.jar:na]
    at org.sonar.search.SearchServer.start(SearchServer.java:45) [sonar-search-5.6.jar:na]
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:102) ~[sonar-process-5.6.jar:na]
    at org.sonar.search.SearchServer.main(SearchServer.java:81) [sonar-search-5.6.jar:na]
Caused by: java.io.IOException: failed to obtain lock on D:\Sonar\sonarqube-5.6\data\es\sonarqube\nodes\49
    at org.elasticsearch.env.NodeEnvironment.<init>(NodeEnvironment.java:151) ~[elasticsearch-1.7.5.jar:na]
    ... 4 common frames omitted
Caused by: java.nio.file.AccessDeniedException: D:\Sonar\sonarqube-5.6\data\es\sonarqube\nodes\49
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsFileStore.create(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsFileSystemProvider.getFileStore(Unknown Source) ~[na:1.8.0_91]
    at java.nio.file.Files.getFileStore(Unknown Source) ~[na:1.8.0_91]
    at org.elasticsearch.env.NodeEnvironment.getFileStore(NodeEnvironment.java:262) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.env.NodeEnvironment.access$000(NodeEnvironment.java:62) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.env.NodeEnvironment$NodePath.<init>(NodeEnvironment.java:75) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.env.NodeEnvironment.<init>(NodeEnvironment.java:140) ~[elasticsearch-1.7.5.jar:na]
    ... 4 common frames omitted
<-- Wrapper Stopped
</code>```

答:
In order to run with service account you need below permissions:

•   Logon as a service via GPO
•   Local Admin permission on server

Also make sure you have permissions for the service account on the Database in order to make it work properly.

Also posted on Site

Title: SonarQube 5 Service account permissions

Body:
We are currently running SonarQube 5.2 and are performing a test upgrade to SonarQube 5.6, we have had this issue with Sonar 5.4 as well, but never upgraded in production.

When we use the same service account on the same server in the same root directory, the service is unable to start. It claims it is unable to get a node lock, always on the same file and directory, node 49, which is the last one of the nodes. The file and folder are successfully created.

The service account has full permissions on the D:\Sonar folder and all folders below.

I have tested and confirmed that the service does start up when i make it a local administrator, but this is not desired, so i am looking for the required permissions to start up the service. The service also starts if i configure it as local system, but we dont want this either.

What more permissions should i give to the SonarQube Service Account in order to start up ?

Any advise is welcome.

Nico

2016.06.10 14:42:32 INFO  app[o.s.a.AppFileSystem] Cleaning or creating temp directory D:\Sonar\sonarqube-5.6\temp
2016.06.10 14:42:32 INFO  app[o.s.p.m.JavaProcessLauncher] Launch process[es]: C:\Program Files\Java\jre1.8.0_91\bin\java -Djava.awt.headless=true -Xmx1G -Xms256m -Xss256k -Djava.net.preferIPv4Stack=true -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -XX:+HeapDumpOnOutOfMemoryError -Djava.io.tmpdir=D:\Sonar\sonarqube-5.6\temp -javaagent:C:\Program Files\Java\jre1.8.0_91\lib\management-agent.jar -cp ./lib/common/*;./lib/search/* org.sonar.search.SearchServer D:\Sonar\sonarqube-5.6\temp\sq-process3739686975987017449properties
2016.06.10 14:42:34 INFO   es[o.s.p.ProcessEntryPoint]  Starting es
2016.06.10 14:42:34 INFO   es[o.s.s.EsSettings]  Elasticsearch listening on 127.0.0.1:9006
2016.06.10 14:42:34 INFO   es[o.elasticsearch.node]  [sonar-1465562551839] version[1.7.5], pid[29336], build[00f95f4/2016-02-02T09:55:30Z]
2016.06.10 14:42:34 INFO   es[o.elasticsearch.node]  [sonar-1465562551839] initializing ...
2016.06.10 14:42:34 INFO   es[o.e.plugins]  [sonar-1465562551839] loaded [], sites []
2016.06.10 14:42:35 WARN   es[o.s.p.ProcessEntryPoint]  Fail to start es
org.elasticsearch.ElasticsearchIllegalStateException: Failed to obtain node lock, is the following location writable?: [D:\Sonar\sonarqube-5.6\data\es\sonarqube]
    at org.elasticsearch.env.NodeEnvironment.<init>(NodeEnvironment.java:164) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.node.internal.InternalNode.<init>(InternalNode.java:165) ~[elasticsearch-1.7.5.jar:na]
    at org.sonar.search.SearchServer.start(SearchServer.java:45) [sonar-search-5.6.jar:na]
    at org.sonar.process.ProcessEntryPoint.launch(ProcessEntryPoint.java:102) ~[sonar-process-5.6.jar:na]
    at org.sonar.search.SearchServer.main(SearchServer.java:81) [sonar-search-5.6.jar:na]
Caused by: java.io.IOException: failed to obtain lock on D:\Sonar\sonarqube-5.6\data\es\sonarqube\nodes\49
    at org.elasticsearch.env.NodeEnvironment.<init>(NodeEnvironment.java:151) ~[elasticsearch-1.7.5.jar:na]
    ... 4 common frames omitted
Caused by: java.nio.file.AccessDeniedException: D:\Sonar\sonarqube-5.6\data\es\sonarqube\nodes\49
    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsFileStore.create(Unknown Source) ~[na:1.8.0_91]
    at sun.nio.fs.WindowsFileSystemProvider.getFileStore(Unknown Source) ~[na:1.8.0_91]
    at java.nio.file.Files.getFileStore(Unknown Source) ~[na:1.8.0_91]
    at org.elasticsearch.env.NodeEnvironment.getFileStore(NodeEnvironment.java:262) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.env.NodeEnvironment.access$000(NodeEnvironment.java:62) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.env.NodeEnvironment$NodePath.<init>(NodeEnvironment.java:75) ~[elasticsearch-1.7.5.jar:na]
    at org.elasticsearch.env.NodeEnvironment.<init>(NodeEnvironment.java:140) ~[elasticsearch-1.7.5.jar:na]
    ... 4 common frames omitted
<-- Wrapper Stopped


问:
Carthage Building scheme makes Bitrise to timeout after 90 minutes
I am using Bitrise and I have updated both my development machine and bitrise stack to Xcode 11.

When running a build, the Carthage dependencies need to be regenerated and since I am using AWS dependencies, even in my Mac book pro, they take a long time to build and they make the Bitrise build to time out.

Here there is an example on how my bitrise.yml is configured:

```<code>...
workflows:
  test:
    steps:
    - gitlab-status:
        run_if: not (enveq "BITRISE_GIT_COMMIT" "")
        inputs:
        - private_token: "$GITLAB_STATUS_TOKEN"
        - preset_status: running
        - api_base_url: https://gitlab.company.cloud/api/v4
    - activate-ssh-key:
        run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}'
    - git-clone: {}
    - cache-pull:
        inputs:
        - is_debug_mode: 'true'
    - certificate-and-profile-installer: {}
    - carthage:
        inputs:
        - verbose_log: 'yes'
        - carthage_options: "--platform ios --no-use-binaries --cache-builds"
    - cocoapods-install: {}
    - xcode-test:
        inputs:
        - scheme: CompanyApp
        - project_path: CompanyApp.xcworkspace
        - simulator_device: iPhone 8
    - xcode-test:
        inputs:
        - project_path: CompanyApp.xcworkspace
        - simulator_device: iPhone 8
        - scheme: CompanyAppUITests
    - gitlab-status:
        run_if: not (enveq "BITRISE_GIT_COMMIT" "")
        inputs:
        - private_token: "$GITLAB_STATUS_TOKEN"
        - api_base_url: https://gitlab.company.cloud/api/v4
    - cache-push:
        is_always_run: true
        inputs:
        - is_debug_mode: 'true'
    - deploy-to-bitrise-io: {}
...
</code>```

Just in case, they are the last 2 lines from the build log

```<code>*** Building scheme "AWSLogs" in AWSiOSSDKv2.xcodeproj
*** Building scheme "AWSMachineLearning" in AWSiOSSDKv2.xcodeproj
</code>```

Any ideas???

答:
Try removing --no-use-binaries.

By selecting to not use binaries, large dependencies can't provide you with pre-compiled binaries to greatly decrease compile times. If you remove that flag you should notice that compilation speeds up.

Body:
I am using Bitrise and I have updated both my development machine and bitrise stack to Xcode 11.

When running a build, the Carthage dependencies need to be regenerated and since I am using AWS dependencies, even in my Mac book pro, they take a long time to build and they make the Bitrise build to time out.

Here there is an example on how my bitrise.yml is configured:

...
workflows:
  test:
    steps:
    - gitlab-status:
        run_if: not (enveq "BITRISE_GIT_COMMIT" "")
        inputs:
        - private_token: "$GITLAB_STATUS_TOKEN"
        - preset_status: running
        - api_base_url: https://gitlab.company.cloud/api/v4
    - activate-ssh-key:
        run_if: '{{getenv "SSH_RSA_PRIVATE_KEY" | ne ""}}'
    - git-clone: {}
    - cache-pull:
        inputs:
        - is_debug_mode: 'true'
    - certificate-and-profile-installer: {}
    - carthage:
        inputs:
        - verbose_log: 'yes'
        - carthage_options: "--platform ios --no-use-binaries --cache-builds"
    - cocoapods-install: {}
    - xcode-test:
        inputs:
        - scheme: CompanyApp
        - project_path: CompanyApp.xcworkspace
        - simulator_device: iPhone 8
    - xcode-test:
        inputs:
        - project_path: CompanyApp.xcworkspace
        - simulator_device: iPhone 8
        - scheme: CompanyAppUITests
    - gitlab-status:
        run_if: not (enveq "BITRISE_GIT_COMMIT" "")
        inputs:
        - private_token: "$GITLAB_STATUS_TOKEN"
        - api_base_url: https://gitlab.company.cloud/api/v4
    - cache-push:
        is_always_run: true
        inputs:
        - is_debug_mode: 'true'
    - deploy-to-bitrise-io: {}
...

Just in case, they are the last 2 lines from the build log

*** Building scheme "AWSLogs" in AWSiOSSDKv2.xcodeproj
*** Building scheme "AWSMachineLearning" in AWSiOSSDKv2.xcodeproj

Any ideas???


问:
Setting text label in UICollectionView
I have a basic collection view that is a colored grid. All I want to do is add a text label inside in grid cell. In my storyboard I have dragged a label inside the content view of the cell. I've created an outlet for this label inside the view controller that controls the whole collection. But somehow I can't set the text of the cells inside this view controller. What do I need to do?</p>

```<code>import UIKit
let reuseIdentifier = "CellIdentifer";

class WordsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet var cellView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //UICollectionViewDelegateFlowLayout methods
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {

        return 4;
    }
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {

        return 1;
    }

    //UICollectionViewDatasource methods
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return 1
    }

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 100
    }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as UICollectionViewCell

        cell.backgroundColor = self.randomColor()

        return cell
    }

    // custom function to generate a random UIColor
    func randomColor() -> UIColor{
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}
</code>```

答:
created an outlet for this label inside the view controller you can't do that if you want to have a text in each cell. What you want to do instead is to subclass UICollectionViewCell (e.g. CustomCollectionViewCell). Set the collectionViewCell in the Storyboard to this Class and connect the label. Now you can set text like this:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as CustomCollectionViewCell

    cell.backgroundColor = self.randomColor()
    cell.myShinyNewTextLabel.text = "myCustomText"
    return cell
}
```

Title: Setting text label in UICollectionView

Body:
I have a basic collection view that is a colored grid. All I want to do is add a text label inside in grid cell. In my storyboard I have dragged a label inside the content view of the cell. I've created an outlet for this label inside the view controller that controls the whole collection. But somehow I can't set the text of the cells inside this view controller. What do I need to do?

import UIKit
let reuseIdentifier = "CellIdentifer";

class WordsViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet var collectionView: UICollectionView!
    @IBOutlet weak var textLabel: UILabel!
    @IBOutlet var cellView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //UICollectionViewDelegateFlowLayout methods
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {

        return 4;
    }
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
    {

        return 1;
    }

    //UICollectionViewDatasource methods
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

        return 1
    }

  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 100
    }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as UICollectionViewCell

        cell.backgroundColor = self.randomColor()

        return cell
    }

    // custom function to generate a random UIColor
    func randomColor() -> UIColor{
        let red = CGFloat(drand48())
        let green = CGFloat(drand48())
        let blue = CGFloat(drand48())
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
    }
}


问:
For which types of problems are genetic algorithms an appropriate choice?
(I've pondered some time over whether this is a good question for a Q&A site. I think it is -- the answers may be partly subjective but I'm hopefully looking for objective criteria in the answers. It may be though that SO is not the best site in the network but let's try here.)

I am asking this question because just recently I have tried to use a genetic algorithm for an optimization problem with a large parameter space, and it failed, i.e. it wasn't improving over time. I switched to simulated annealing and got much better convergence. So either my GA implementation was wrong or it was the wrong tool for the job.

One typical example for an application of a GA is the Travelling Salesman Problem, the genome being the order in which the cities are visited. This makes sense: "Breeding" or "crossover" mixes and rearranges subroutes that are potentially already optimal locally but by changing the order in which these subroutes are visited, the overall efficiency may improve. A similar example would be the knapsack problem.

Another example I have encountered was using a GA to find the maximum of a 2-D function, the genome being the coordinates. This was probably chosen as a simple pedagogical example to focus on how a GA can be implemented, but then again whether a GA is the right choice here in the first place seems less than clear: Breeding just "arbitrarily" swaps coordinates or -- in this implementation -- takes the average of the individual genomes, losing all of the optimization history. Thus to me, this is an example of a problem that is intrinsically not suited for a GA, because mixing genomes (coordinates), which is the core idea of GAs, would not seem beneficial here. And without it, i.e. when reduced to only mutations, a GA is just a random walk in phase space with restarts.

In general, GAs seem to be apt for problems with discrete solution spaces with high combinatorial complexity rather than exploration of continuous phase spaces. What are other aspects to be considered?

答:
It is really difficult to predict the outcome of both SA and GA (just like life itself?).

The mutation of the GA is somehow similar to the neighbour proposal of SA, so a key difference is the breeding part of the GA.

Say x,y are both proposal solutions to your problem.

If it could make sense to take 1 part of x, and 1 part of y to make a better solution, GA has potential.

You have to use a combination of gut feeling and experiments to check if above is true.

For searching through parameter spaces that could indeed make sense, if parameter alpha and beta work well for 1 case, you might want to take the gamma from an other proposal solution that worked well.

For minimising a function in 2D (say 0 is minimum), this usually doesn't make much sense, if (a,b) is close to 0, and (c,d) is close to 0, (a,d) and (c,b) are just as good as any other random guess (in many cases).

Hill climbing based searches would make more sense in the latter. The breeding part of GA's is where its different from hill climbing.


问:
how i just extract the link for class = main-bullet using web craweling
i used this and using this i will extract all the in the web page but i want specific link which are in the main-bullet class.

```<code>import requests
import bs4
res = requests.get('http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF')
print(res)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
h = soup.select('title')
print(h)
    #got all link of the website
all_links = soup.find_all("a")
for link in all_links:
    link.get("href")
    print(link.get("href"))
</code>```

I used this give all the links...

答:
To extract all links under main-bullet class, you can use .select() method.

For example:

```<code>import requests
from bs4 import BeautifulSoup

url = 'http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for a in soup.select('.main-bullet a'):
    print(a.get_text(strip=True), a['href'])
</code>```

Prints:

```<code>चुनी हुई कविताएँ http://www.hindisamay.com/content/714/1/अज्ञेय-कविताएँ-चुनी-हुई-कविताएँ.cspx
उत्तर प्रियदर्शी http://www.hindisamay.com/content/499/1/अज्ञेय-नाटक-उत्तर-प्रियदर्शी.cspx
वसंत का अग्रदूत http://www.hindisamay.com/content/493/1/अज्ञेय-संस्मरण-वसंत-का-अग्रदूत.cspx
संवाद http://www.hindisamay.com/content/521/1/अज्ञेय-संस्मरण-संवाद.cspx
‘अज्ञेय’ : अपनी निगाह में http://www.hindisamay.com/content/496/1/अज्ञेय-आत्मकथा-अज्ञेय-अपनी-निगाह-में.cspx
ऋण-स्वीकारी हूँ http://www.hindisamay.com/content/495/1/अज्ञेय-आत्मकथा-ऋण-स्वीकारी-हूँ.cspx
कला का स्वाभाव और उद्देश्य http://www.hindisamay.com/content/6777/1/अज्ञेय-निबंध-कला-का-स्वाभाव-और-उद्देश्य.cspx
कविता : श्रव्य से पाठ्य तक http://www.hindisamay.com/content/2000/1/अज्ञेय-निबंध-कविता-श्रव्य-से-पाठ्य-तक.cspx
काल का डमरु-नाद http://www.hindisamay.com/content/2001/1/अज्ञेय-निबंध-काल-का-डमरु-नाद.cspx
छाया का जंगल http://www.hindisamay.com/content/2009/1/अज्ञेय-निबंध-छाया-का-जंगल.cspx
ताली तो छूट गयी http://www.hindisamay.com/content/2007/1/अज्ञेय-निबंध-ताली-तो-छूट-गयी.cspx
नई कविता : प्रयोग के आयाम http://www.hindisamay.com/content/2004/1/अज्ञेय-निबंध-नई-कविता-प्रयोग-के-आयाम.cspx
भारतीयता http://www.hindisamay.com/content/6775/1/अज्ञेय-निबंध-भारतीयता.cspx
मरुथल की सीपियाँ http://www.hindisamay.com/content/2008/1/अज्ञेय-निबंध-मरुथल-की-सीपियाँ.cspx
रूढ़ि और मौलिकता http://www.hindisamay.com/content/6778/1/अज्ञेय-निबंध-रूढ़ि-और-मौलिकता.cspx
वैज्ञानिक सत्ता, मिथकीय सत्ता और कवि http://www.hindisamay.com/content/1999/1/अज्ञेय-निबंध-वैज्ञानिक-सत्ता-मिथकीय-सत्ता-और-कवि.cspx
वासुदेव प्याला http://www.hindisamay.com/content/4299/1/अज्ञेय-निबंध-वासुदेव-प्याला.cspx
शब्द, मौन, अस्तित्व http://www.hindisamay.com/content/2005/1/अज्ञेय-निबंध-शब्द-मौन-अस्तित्व.cspx
स्मृति और काल http://www.hindisamay.com/content/2002/1/अज्ञेय-निबंध-स्मृति-और-काल.cspx

... and so on.
</code>```

EDIT (to save to csv):

```<code>import csv
import requests
from bs4 import BeautifulSoup

url = 'http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for a in soup.select('.main-bullet a'):
    all_data.append([a.get_text(strip=True), a['href']])

with open('data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for row in all_data:
        writer.writerow(row)
</code>```

This produces data.csv (screenshot from LibreOffice):

Body:
i used this and using this i will extract all the in the web page but i want specific link which are in the main-bullet class.

import requests
import bs4
res = requests.get('http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF')
print(res)
soup = bs4.BeautifulSoup(res.text, 'html.parser')
h = soup.select('title')
print(h)
    #got all link of the website
all_links = soup.find_all("a")
for link in all_links:
    link.get("href")
    print(link.get("href"))

I used this give all the links...

Body:
To extract all links under main-bullet class, you can use .select() method.

For example:

import requests
from bs4 import BeautifulSoup

url = 'http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

for a in soup.select('.main-bullet a'):
    print(a.get_text(strip=True), a['href'])

Prints:

चुनी हुई कविताएँ http://www.hindisamay.com/content/714/1/अज्ञेय-कविताएँ-चुनी-हुई-कविताएँ.cspx
उत्तर प्रियदर्शी http://www.hindisamay.com/content/499/1/अज्ञेय-नाटक-उत्तर-प्रियदर्शी.cspx
वसंत का अग्रदूत http://www.hindisamay.com/content/493/1/अज्ञेय-संस्मरण-वसंत-का-अग्रदूत.cspx
संवाद http://www.hindisamay.com/content/521/1/अज्ञेय-संस्मरण-संवाद.cspx
‘अज्ञेय’ : अपनी निगाह में http://www.hindisamay.com/content/496/1/अज्ञेय-आत्मकथा-अज्ञेय-अपनी-निगाह-में.cspx
ऋण-स्वीकारी हूँ http://www.hindisamay.com/content/495/1/अज्ञेय-आत्मकथा-ऋण-स्वीकारी-हूँ.cspx
कला का स्वाभाव और उद्देश्य http://www.hindisamay.com/content/6777/1/अज्ञेय-निबंध-कला-का-स्वाभाव-और-उद्देश्य.cspx
कविता : श्रव्य से पाठ्य तक http://www.hindisamay.com/content/2000/1/अज्ञेय-निबंध-कविता-श्रव्य-से-पाठ्य-तक.cspx
काल का डमरु-नाद http://www.hindisamay.com/content/2001/1/अज्ञेय-निबंध-काल-का-डमरु-नाद.cspx
छाया का जंगल http://www.hindisamay.com/content/2009/1/अज्ञेय-निबंध-छाया-का-जंगल.cspx
ताली तो छूट गयी http://www.hindisamay.com/content/2007/1/अज्ञेय-निबंध-ताली-तो-छूट-गयी.cspx
नई कविता : प्रयोग के आयाम http://www.hindisamay.com/content/2004/1/अज्ञेय-निबंध-नई-कविता-प्रयोग-के-आयाम.cspx
भारतीयता http://www.hindisamay.com/content/6775/1/अज्ञेय-निबंध-भारतीयता.cspx
मरुथल की सीपियाँ http://www.hindisamay.com/content/2008/1/अज्ञेय-निबंध-मरुथल-की-सीपियाँ.cspx
रूढ़ि और मौलिकता http://www.hindisamay.com/content/6778/1/अज्ञेय-निबंध-रूढ़ि-और-मौलिकता.cspx
वैज्ञानिक सत्ता, मिथकीय सत्ता और कवि http://www.hindisamay.com/content/1999/1/अज्ञेय-निबंध-वैज्ञानिक-सत्ता-मिथकीय-सत्ता-और-कवि.cspx
वासुदेव प्याला http://www.hindisamay.com/content/4299/1/अज्ञेय-निबंध-वासुदेव-प्याला.cspx
शब्द, मौन, अस्तित्व http://www.hindisamay.com/content/2005/1/अज्ञेय-निबंध-शब्द-मौन-अस्तित्व.cspx
स्मृति और काल http://www.hindisamay.com/content/2002/1/अज्ञेय-निबंध-स्मृति-और-काल.cspx

... and so on.

EDIT (to save to csv):

import csv
import requests
from bs4 import BeautifulSoup

url = 'http://www.hindisamay.com/writer/%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF.cspx?id=1275&name=%E0%A4%85%E0%A4%9C%E0%A5%8D%E0%A4%9E%E0%A5%87%E0%A4%AF'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for a in soup.select('.main-bullet a'):
    all_data.append([a.get_text(strip=True), a['href']])

with open('data.csv', 'w', newline='') as csvfile:
    writer = csv.writer(csvfile, delimiter=',',quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for row in all_data:
        writer.writerow(row)

This produces data.csv (screenshot from LibreOffice):


问:
Intellij Error:Cannot build Artifact 'XXX:war exploded' because it is included into a circular dependency
The project was working well before, but suddenly can not update war file in "target" directory.When I want to "Build Artifacts", error shows:
Error:Cannot build Artifact 'XXX:war exploded' because it is included into a circular dependency

What is the wrong with this?

the artifacts :

答:
If you use Maven than just delete all artifacts and than right click on you project and select Maven -> Reimport

that works for me!


问:
Is Azure role local storage guaranteed to be inaccessible to an application that is next to use the same host?
Suppose my Azure role stores files to the role local filesystem and forgets to delete them. Can another application that uses that host in future possibly get access to those files?

I've read the whitepaper and it's full of marketing style statements but I can't find a definitive statement about how thoroughly the host machine is "cleaned" before a new role is started on it.

Can I be completely sure that another application won't see changes my application does to the filesystem?

答: No, it cannot be used by another VM, even accidentally.  The 'scratch' drive that is mounted by your Windows Azure instance is another VHD - data is not written natively to disk.  So, in order for another instance to read your data, it would have to mount your VHD, which is not possible.</p>


问:
How to activate IDEA's "Run Dashboard" feature
I have a window tool named "Run Dashboard" in Project A, but I can't activate this window in Project B. Does anyone know how to solve this? This feature appeared in IntelliJ IDEA version 2017.3.

This is what I see in Project A:

This is what I see in Project B:

This option is present but not activatable out in Project B:

but it's activatable in Project A:

答:
In Intellij 2020 now Dashboard is by the name of Services see below screenshot and by default, the view is like this

To get back to the old view of the initial version of spring-dashboard.

Right-click on Services -> Enable 'Show Service Tree'


问:
Displaying solutions within a certain range when using sympy solve command
I can be considered pretty much new to python and coding in general so forgive me for my ignorance.

I'm trying to solve a system of trigonometric functions in python, and I'm doing so using the solve command from sympy. However, this method returns only a finite number of solutions, two in this particular case.
I've read through the documentation and it seems that to get an expression for all the solutions solveset is to be used instead. However, I do not want all the solutions to be displayed, but rather only a finite amount which is contained within a certain range.

Here's the example:

```<code>from sympy import *

x, y = symbols('x, y')

eq1 = Eq(y - sin(x), 0)
eq2 = Eq(y - cos(x), 0)

sol = solve([eq1, eq2], [x, y])
print(sol)
</code>```

which only returns the first two solutions in the positive x range.

How could I do to, for example, display all the solutions within the x range [-2pi, 2pi]?

I'd want them in explicit form rather than written in term of some multiplier since I then need to convert them into numerical form.

Thank you in advance.

答:
By using solveset you can restrict the solutions with domain argument. For evaluating numerical results use .evalf() or another similar method.

from sympy import Interval, symbols, solveset, sin, cos, pi

x = symbols('x')
sol = solveset(cos(x) - sin(x), x, domain=Interval(-2*pi, 2*pi))
print(sol)
print(sol.evalf())
```

<h3>Output</h3>

```FiniteSet(-7*pi/4, -3*pi/4, pi/4, 5*pi/4)
FiniteSet(-5.49778714378214, -2.35619449019234, 0.785398163397448, 3.92699081698724)
```

I hope this helps!

Body:
I can be considered pretty much new to python and coding in general so forgive me for my ignorance.

I'm trying to solve a system of trigonometric functions in python, and I'm doing so using the solve command from sympy. However, this method returns only a finite number of solutions, two in this particular case.
I've read through the documentation and it seems that to get an expression for all the solutions solveset is to be used instead. However, I do not want all the solutions to be displayed, but rather only a finite amount which is contained within a certain range.

Here's the example:

from sympy import *

x, y = symbols('x, y')

eq1 = Eq(y - sin(x), 0)
eq2 = Eq(y - cos(x), 0)

sol = solve([eq1, eq2], [x, y])
print(sol)

which only returns the first two solutions in the positive x range.

How could I do to, for example, display all the solutions within the x range [-2pi, 2pi]?

I'd want them in explicit form rather than written in term of some multiplier since I then need to convert them into numerical form.

Thank you in advance.

Body:
By using solveset you can restrict the solutions with domain argument. For evaluating numerical results use .evalf() or another similar method.

from sympy import Interval, symbols, solveset, sin, cos, pi

x = symbols('x')
sol = solveset(cos(x) - sin(x), x, domain=Interval(-2*pi, 2*pi))
print(sol)
print(sol.evalf())

Output

FiniteSet(-7*pi/4, -3*pi/4, pi/4, 5*pi/4)
FiniteSet(-5.49778714378214, -2.35619449019234, 0.785398163397448, 3.92699081698724)

I hope this helps!


问:
Android - Jetpack compose missing references
I am trying to follow the official google Jetpack compose tutorial on this url but Android studio have an issue resolving the modifier Height()

I am 100% sure that I have imported the correct dependencies as per the tutorial, however, this modifier is no where to be found. It is not deprecated as it is still references in the official docs here

```<code>fun NewsStory() {
    val image = +imageResource(R.drawable.header)
        Column(
            modifier = Spacing(16.dp)
            ) {
            Container(modifier = Height(180.dp) wraps Expanded) {
                DrawImage(image)
            }

            HeightSpacer(16.dp)

            Text("A day in Shark Fin Cove")
            Text("Davenport, California")
            Text("December 2018")
        }
}
</code>```

Am I missing something?

答:
As Geoff Langenderfer said changing to dev09 from dev03 worked.

```<code>//app/build.gradle
 dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.72"
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'

    implementation 'androidx.ui:ui-framework:0.1.0-dev09'
    implementation 'androidx.ui:ui-layout:0.1.0-dev09'
    implementation 'androidx.ui:ui-material:0.1.0-dev09'
    implementation 'androidx.ui:ui-tooling:0.1.0-dev09'

    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

Body:
I am trying to follow the official google Jetpack compose tutorial on this url but Android studio have an issue resolving the modifier Height()

I am 100% sure that I have imported the correct dependencies as per the tutorial, however, this modifier is no where to be found. It is not deprecated as it is still references in the official docs here

fun NewsStory() {
    val image = +imageResource(R.drawable.header)
        Column(
            modifier = Spacing(16.dp)
            ) {
            Container(modifier = Height(180.dp) wraps Expanded) {
                DrawImage(image)
            }

            HeightSpacer(16.dp)

            Text("A day in Shark Fin Cove")
            Text("Davenport, California")
            Text("December 2018")
        }
}

Am I missing something?

Body:
As Geoff Langenderfer said changing to dev09 from dev03 worked.

//app/build.gradle
 dependencies {

    implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.72"
    implementation 'androidx.core:core-ktx:1.3.0'
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'

    implementation 'androidx.ui:ui-framework:0.1.0-dev09'
    implementation 'androidx.ui:ui-layout:0.1.0-dev09'
    implementation 'androidx.ui:ui-material:0.1.0-dev09'
    implementation 'androidx.ui:ui-tooling:0.1.0-dev09'

    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}


问:
How to disable CSS Class on particular DIV
I want to disable class automatically applied on div.

```<code><div class="A B">
</code>```

I want to disable Class 'A' but not 'B'. How could I do that ?

答:
This code will act magically....</p>

```<code><script type='text/javascript'>
        jQuery(document).ready(function ($) {
        $( "div" ).removeClass( 'your_class_name' );
      });
</script>
</code>```

Body:
I want to disable class automatically applied on div.

I want to disable Class 'A' but not 'B'. How could I do that ?

Body:
This code will act magically....

<script type='text/javascript'>
        jQuery(document).ready(function ($) {
        $( "div" ).removeClass( 'your_class_name' );
      });
</script>


问:
How can I get everything going threw the device audioPlayer in flutter
I am trying to get every thing going threw the audio player in my flutter app. Exactly the same way than when you are connected in bluetooth in your car. If you are on youtube, your car will display video's name and play it threw the speaker. If you change to spotify, it will also change, even if you go threw local music file.

Does anyone got an idea about how to do this ?

Thanks for reading

答:
What you are looking for is the AVPlayer which is the native player of iOS.

In Flutter you can get the following library: https://pub.dev/packages/flutter_playout

This library provides the Player in notification center and on lockscreen and is hihgly customizable. I recommend you using this and change it to your fits.

P.s: It also provides native android player.


问:
2D image to 3D world coordinate in perspective view
I have been trying to locate detected objects from 2D image in the 3D space for a single fixed camera installed at the height.
I went trough the similar questions, but the perspective view is not mentioned.
What I have:

The height of the camera

Calibration parameters

The exact location of one fixed object in view

答: I've wrote a set of solutions to this kind of problem. 3d points reconstruction from 2d coordinates (yes, "in perspective"), are obtained by means of the extrinsics matrix. See https://github.com/rodolfoap/screen2world-k. Other methods are linked from there.</p>


问:
ofstream error
This is in reference to another question I asked, though it is its own question entirely.

when I compile I get two errors:

1>.\asst4.cpp(73) : error C2065: 'outfile' : undeclared identifier

1>.\asst4.cpp(73) : error C2228: left of '.close' must have class/struct/union

I'm slightly confused as to what I've done incorrectly here? Any reccomendations or ideas? (The actual outfile is near the top of the code.

Here is the full code:

```<code>#include<iostream>
#include<fstream>  //used for reading/writing to files.
#include<string>    //needed for the filename.
#include<stdio.h>   //for goto statement

using namespace std;

int main()
{
    string start;
    char choice;
    char letter;
    int x;
    int y;
    int z;
    string filename;
    int garbage = rand()%('!' - '~' + 1 );
    cout << "Would you like to encrypt or decrypt a file? Please type enc, dec, or stop (case sensitive): " ;
    cin >> start;
    while(start == "enc")
    {
        x = 1;
        y = 1;
        cout << "How many garbage characters would you like between each correct character?: " ;
        cin >> z;
        cout << endl << "Please insert the name of the document you wish to encrypt, make sure you enter the name, and the file type (ie: filename.txt): " ;
        cin >> filename;
        ifstream infile(filename.c_str());
        while(!infile.eof())
        {
            ofstream outfile("encrypted.txt", ios::out);
            infile.get(letter);
            if (x == y)
                {
                outfile << garbage;
                x++;
            }
            else
            {
                if((x - y) == z)
                {
                    outfile << letter;
                    y = x;
                }
                else
                {
                    outfile << garbage;
                    x++;
                }
            }
        }
        cout << endl << "Encryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl;
        infile.close();
        outfile.close();
        cout << "Do you wish to try again? Please press y then enter if yes (case sensitive).";
        cin >> choice;
        if(choice == 'y')
        {
            start = "enc";
        }
        else
        {
            cout << endl << "Do you wish to decrypt a file? Please press y then enter if yes (case sensitive).";
            if(choice = 'y')
            {
                start == "dec";
            }
            else
            {
                start == "no";
            }
        }
    }
    while(start == "dec")
    {

      //lets user choose whether to do another document or not.
      //used to track each character in the document.
        x = 1;    //first counter for tracking correct letter.
        y = 1;    //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
              //third counter (used as a check to see if the first two counters are equal).
        //allows for user to input the filename they wish to use.
        cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
        cin >> filename; //getline(cin, filename);
        cout << endl;
        cout << "'Every nth character is good', what number is n?: ";
        cin >> z;   //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
        cout << endl;
        z = z - 1;  //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
        ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
        if(infile.is_open()) //checks to see if the file is opened.
        {
            while(!infile.eof())    //continues looping until the end of the file.
            {
                    infile.get(letter);  //gets the letters in the order that that they are in the file.
                    if (x == y)          //checks to see if the counters match...
                    {
                        x++;             //...if they do, adds 1 to the x counter.
                    }
                    else
                    {
                        if((x - y) == z)            //for every nth character that is good, x - y = nth - 1.
                        {
                            cout << letter;         //...if they don't, that means that character is one you want, so it prints that character.
                            y = x;                  //sets both counters equal to restart the process of counting.
                        }
                        else                        //only used when more than every other letter is garbage, continues adding 1 to the first
                        {                           //counter until the first and second counters are equal.
                            x++;
                        }
                    }
            }
            cout << endl << "Decryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl;
            infile.close();
            cout << "Do you wish to try again? Please press y then enter if yes (case sensitive).";
            cin >> choice;
            if(choice == 'y')
            {
                start == "dec";
            }
            else
                {
                cout << endl << "Do you wish to encrypt a file? Please press y then enter if yes (case sensitive).";
                if(choice == 'y')
                {
                    start == "enc";
                }
                else
                {
                    start == "no";
                }
            }
        }
        else  //this prints out and program is skipped in case an incorrect file name is used.
        {
            cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
            cout << "IE:" << "     filename.txt" << endl;
            cout << "You input: " << filename << endl;
            cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
            cin >> choice;
            if(choice == 'y')
            {
                start == "dec";
            }
            else
            {
                start == "no";
            }
        }
        getchar();  //because I use visual C++ express.
    }
}
</code>```

Thanks ahead of time!
Jeff

答:
Scoping issue. You are declaring outfile within your while loop, yet are trying to access it outside of said while loop.

Move ofstream outfile("encrypted.txt", ios::out); to the line right after your ifstream infile(filename.c_str()); which is before your while(!infile.eof()).

OwnerDisplayName: Jeff

ContentLicense: CC BY-SA 2.5

Title: ofstream error

Body:
This is in reference to another question I asked, though it is its own question entirely.

when I compile I get two errors:

1>.\asst4.cpp(73) : error C2065: 'outfile' : undeclared identifier

1>.\asst4.cpp(73) : error C2228: left of '.close' must have class/struct/union

I'm slightly confused as to what I've done incorrectly here? Any reccomendations or ideas? (The actual outfile is near the top of the code.

Here is the full code:

#include<iostream>
#include<fstream>  //used for reading/writing to files.
#include<string>    //needed for the filename.
#include<stdio.h>   //for goto statement

using namespace std;

int main()
{
    string start;
    char choice;
    char letter;
    int x;
    int y;
    int z;
    string filename;
    int garbage = rand()%('!' - '~' + 1 );
    cout << "Would you like to encrypt or decrypt a file? Please type enc, dec, or stop (case sensitive): " ;
    cin >> start;
    while(start == "enc")
    {
        x = 1;
        y = 1;
        cout << "How many garbage characters would you like between each correct character?: " ;
        cin >> z;
        cout << endl << "Please insert the name of the document you wish to encrypt, make sure you enter the name, and the file type (ie: filename.txt): " ;
        cin >> filename;
        ifstream infile(filename.c_str());
        while(!infile.eof())
        {
            ofstream outfile("encrypted.txt", ios::out);
            infile.get(letter);
            if (x == y)
                {
                outfile << garbage;
                x++;
            }
            else
            {
                if((x - y) == z)
                {
                    outfile << letter;
                    y = x;
                }
                else
                {
                    outfile << garbage;
                    x++;
                }
            }
        }
        cout << endl << "Encryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl;
        infile.close();
        outfile.close();
        cout << "Do you wish to try again? Please press y then enter if yes (case sensitive).";
        cin >> choice;
        if(choice == 'y')
        {
            start = "enc";
        }
        else
        {
            cout << endl << "Do you wish to decrypt a file? Please press y then enter if yes (case sensitive).";
            if(choice = 'y')
            {
                start == "dec";
            }
            else
            {
                start == "no";
            }
        }
    }
    while(start == "dec")
    {

      //lets user choose whether to do another document or not.
      //used to track each character in the document.
        x = 1;    //first counter for tracking correct letter.
        y = 1;    //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
              //third counter (used as a check to see if the first two counters are equal).
        //allows for user to input the filename they wish to use.
        cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
        cin >> filename; //getline(cin, filename);
        cout << endl;
        cout << "'Every nth character is good', what number is n?: ";
        cin >> z;   //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
        cout << endl;
        z = z - 1;  //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
        ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
        if(infile.is_open()) //checks to see if the file is opened.
        {
            while(!infile.eof())    //continues looping until the end of the file.
            {
                    infile.get(letter);  //gets the letters in the order that that they are in the file.
                    if (x == y)          //checks to see if the counters match...
                    {
                        x++;             //...if they do, adds 1 to the x counter.
                    }
                    else
                    {
                        if((x - y) == z)            //for every nth character that is good, x - y = nth - 1.
                        {
                            cout << letter;         //...if they don't, that means that character is one you want, so it prints that character.
                            y = x;                  //sets both counters equal to restart the process of counting.
                        }
                        else                        //only used when more than every other letter is garbage, continues adding 1 to the first
                        {                           //counter until the first and second counters are equal.
                            x++;
                        }
                    }
            }
            cout << endl << "Decryption complete...please return to directory of program, a new file named encrypted.txt will be there." << endl;
            infile.close();
            cout << "Do you wish to try again? Please press y then enter if yes (case sensitive).";
            cin >> choice;
            if(choice == 'y')
            {
                start == "dec";
            }
            else
                {
                cout << endl << "Do you wish to encrypt a file? Please press y then enter if yes (case sensitive).";
                if(choice == 'y')
                {
                    start == "enc";
                }
                else
                {
                    start == "no";
                }
            }
        }
        else  //this prints out and program is skipped in case an incorrect file name is used.
        {
            cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
            cout << "IE:" << "     filename.txt" << endl;
            cout << "You input: " << filename << endl;
            cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
            cin >> choice;
            if(choice == 'y')
            {
                start == "dec";
            }
            else
            {
                start == "no";
            }
        }
        getchar();  //because I use visual C++ express.
    }
}

Thanks ahead of time!
Jeff

LastEditorDisplayName: Timo Geusch

OwnerDisplayName: X-Istence


问:
Laravel protected $loginView load the default login view
I am trying to login for different types of users

but I have an error starting the login view for a certain type of user

laravel default login view loads and not the one i created and assigned to protected $loginView

I cannot understand what is happening, what is the error that occurs?

Web.php:

```<code>    Route::group(['middleware'=>'web'], function (){
    Route::get('/', function () {
        return view('welcome');

});

Route::get('admins/login','adminController@showLoginForm');
Route::get('admins/login','adminController@login');
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
});
</code>```

adminController:

```<code>    <?php

namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class adminController extends Controller
{

   use AuthenticatesUsers;
   protected $loginView = 'admins.login';

}
</code>```

admins >login.blade.php:

```<code><form method ="POST" action="">

<label for="email">Email:</label>
<input type="email" name="email" id="email">

<label for="pass">password:</label>
<input type="text" name="pass" id="pass">

<button>login</button>

</form>
</code>```

答:
As far as I am aware, there is no $loginView property that Laravel utilizes to determine which view should be used for the login page, so why do you believe that it should work?

Here is the showLoginForm method:

```<code>public function showLoginForm()
{
    return view('auth.login');
}
</code>```

So what I would suggest you do is the following, remove the $loginView property and overwrite the showLoginForm method:

```<code>class adminController extends Controller
{
    use AuthenticatesUsers;

    public function showLoginForm()
    {
        return view('admins.login');
    }
}
</code>```

PS:

Why do you have the route admins/login with the method get twice?

```<code>Route::get('admins/login','adminController@showLoginForm');
Route::get('admins/login','adminController@login');
</code>```

You probably meant to use post for the second one.

Body:
I am trying to login for different types of users

but I have an error starting the login view for a certain type of user

laravel default login view loads and not the one i created and assigned to protected $loginView

I cannot understand what is happening, what is the error that occurs?

Web.php:

    Route::group(['middleware'=>'web'], function (){
    Route::get('/', function () {
        return view('welcome');

});

Route::get('admins/login','adminController@showLoginForm');
Route::get('admins/login','adminController@login');
Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');
});

adminController:

    <?php

namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class adminController extends Controller
{

   use AuthenticatesUsers;
   protected $loginView = 'admins.login';

}

admins >login.blade.php:

<form method ="POST" action="">

Email:
<input type="email" name="email" id="email">

password:
<input type="text" name="pass" id="pass">

<button>login</button>

</form>

Body:
As far as I am aware, there is no $loginView property that Laravel utilizes to determine which view should be used for the login page, so why do you believe that it should work?

Here is the showLoginForm method:

public function showLoginForm()
{
    return view('auth.login');
}

So what I would suggest you do is the following, remove the $loginView property and overwrite the showLoginForm method:

class adminController extends Controller
{
    use AuthenticatesUsers;

    public function showLoginForm()
    {
        return view('admins.login');
    }
}

PS:

Why do you have the route admins/login with the method get twice?

Route::get('admins/login','adminController@showLoginForm');
Route::get('admins/login','adminController@login');

You probably meant to use post for the second one.


问:
Best practice to secure an Electron application
I have an Electron application packaged into an asar file. However, it's mentioned almost everywhere that there's no security at all for that format. Everyone can unpack it with npx asar extract app.asar destfolder and access the source code + resources files (certificates, images, audio, everything).

Which means technically a person can tamper with the code and resources files as much as they want and create fake builds with unwanted code.

So what are the best practices to check your application isn't tampered with? Also, where do you think i should store the private key and the public certificate (i need them to connect to my nodejs server).

Thank you :)

答:
The answer is code signing. For the definition of code signing, check the Wikipedia (https://en.wikipedia.org/wiki/Code_signing). For the documentation of the code signing in Electron, check this link https://www.electronjs.org/docs/latest/tutorial/code-signing.

Second, for the additional question, what is the purpose of the private key, and the public certificate of who? And why are you need those things to connect the nodejs server?

If you want to protect the communication channel between the application and the server, use HTTPS.


问:
Halcon - Extract straight edge from XLD
I have a XLD edge, like the one in red in the sample picture below.

I need to extract start/endpoint of straight lines that reppresent it. Hough lines sort of work for this, but the results are not really replicable. minor changes in the contour produce unexpected results.

How can the contours be extracted as straight lines? (blue) with start and finish coordinates?
lines shorter than a specified length should not be counted as separate line.

答:
Contour needs to be converted to a polygon using the following function:

```<code>gen_polygons_xld (Object, Polygons, 'ramer', 25.0)
</code>```

The only adjustable parameter is the alpha (25.0) which decides the approximation threshold.

Title: Halcon - Extract straight edge from XLD

Body:
Contour needs to be converted to a polygon using the following function:

gen_polygons_xld (Object, Polygons, 'ramer', 25.0)

The only adjustable parameter is the alpha (25.0) which decides the approximation threshold.