问:
List subscriptions for a given Azure account
I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-

from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

```

It is supposed to return a list of subscriptions.
However, I see only empty list returned every time I try the above code.
Can anybody help?

答:
Try this code,

```<code>def list_subscriptions():
    try:
        sub_client = get_client_from_cli_profile(SubscriptionClient)
    except CLIError:
        logger.info("Not logged in, running az login")
        _run_az_cli_login()
        sub_client = get_client_from_cli_profile(SubscriptionClient)

    return [["Subscription_name", "Subscription ID"]] + [
        [sub.display_name, sub.subscription_id]
        for sub in sub_client.subscriptions.list()
    ]
</code>```

You can find the handy tool from here

Body:
I'm trying to list the subscriptions in an Azure account using azure-python-sdk.

I have followed this link in documentation.

https://learn.microsoft.com/en-us/python/api/azure-mgmt-subscription/azure.mgmt.subscription.operations.subscriptionsoperations?view=azure-python#list-custom-headers-none--raw-false----operation-config-

from azure.mgmt.subscription import SubscriptionClient
from msrestazure.azure_active_directory import UserPassCredentials

credentials = UserPassCredentials(username='xxxx', password='xxxx')
sub_client = SubscriptionClient(credentials)
subs = [sub.as_dict() for sub in sub_client.subscriptions.list()]
print(subs)

It is supposed to return a list of subscriptions.
However, I see only empty list returned every time I try the above code.
Can anybody help?

Body:
Try this code,

def list_subscriptions():
    try:
        sub_client = get_client_from_cli_profile(SubscriptionClient)
    except CLIError:
        logger.info("Not logged in, running az login")
        _run_az_cli_login()
        sub_client = get_client_from_cli_profile(SubscriptionClient)

    return [["Subscription_name", "Subscription ID"]] + [
        [sub.display_name, sub.subscription_id]
        for sub in sub_client.subscriptions.list()
    ]

You can find the handy tool from here


来源: stackexchange

问:
Swift having image in background not changing with subview
I have a view that displays 1 picture at a time and that picture is supposed to be the background image. I also have other elements on top of that image that are supposed to change on touch  . The view that I have is called VideoView and I have elements on top . All of this works my problem is that when I use insertSubview all the elements on top change (like they are supposed to) but the image stays the same (VideoView) and it is supposed to change . If I replace the InsertSubView with addSubview then the image changes correctly on click but my top elements do not show . I know that what I'm supposed to use is insertSubview and on touch I can see the image URL changing but the screen stays with the first default image .

I think I know what might be going on . On every tap I am adding a new InsertSubview and the new image might be behind the old image . I verified by uploading a video . I first had an image and when I tapped to go to the next screen the image stayed however the video sound came on .

```<code>class BookViewC: UIViewController{
    @IBOutlet weak var VideoView: UIView!

    var imageView: UIImageView?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  // This is how I change images, touchCount number is linked with unique image depending on the number passed in .

    for touch in touches {
        let location = touch.location(in: self.VideoView)

          if location.x <  self.VideoView.layer.frame.size.width / 2 {
            if touchCount == 0 || touchCount < 0 {
                touchCount = 0
            } else {
                touchCount = touchCount - 1

            }
           reloadTable(Offset: touchCount)
        }
        else {
            touchCount = touchCount + 1
            reloadTable(Offset: touchCount)

        }
    }
}

func ShowImage(s_image: String) {
    let imgURL: NSURL = NSURL(string: s_image)!
    let request:NSURLRequest =  NSURLRequest(url: imgURL as URL)
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    bookviewImage.imageView = UIImageView(image: UIImage(named: s_image))
    bookviewImage.imageView?.frame = VideoView.bounds
    bookviewImage.imageView?.contentMode = UIViewContentMode.scaleAspectFill

    let task = session.dataTask(with: request as URLRequest,    completionHandler: {(data, response, error) in
        DispatchQueue.main.async(execute: { () -> Void in

            if data != nil {

                self.bookviewImage.imageView?.image = UIImage(data: data!)
                self.VideoView.insertSubview(self.bookviewImage.imageView!, at: 0)
               // self.VideoView.addSubview(self.bookviewImage.imageView!)

            } else {
                self.bookviewImage.imageView!.image = nil
            }

        })
    });
    task.resume()
}

    func reloadTable(Offset: Int) {

    // send http request

        session.dataTask(with:request, completionHandler: {(data, response, error) in
            if error != nil {

            } else {
                do {

       let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]

   if let Streams = parsedData["Results"] as? [AnyObject]?
       {

     if self.streamsModel.Locations.count >= 0 {
                         // Get Results

                        }

        DispatchQueue.main.async {
          for Stream in Streams! {

if let s_image = Stream["stream_image"] as? String {
self.ShowImage(s_image: s_image)

 }
     }
       }
</code>```

This background Image on InsertSubview does not change on click however when I add AddSubview the background image changes so I know there is something wrong in my code since the InsertSubview background image is not updating

[![ .][2]][2]

答:
I'm not sure how you are changing pictures and might have to see the code to provide a better explanation. In the meantime, you should understand the difference between insertSubview and addSubview.

addSubview:

addSubview adds a view at the end of the list. In the hierarchical structure, this would be the bottom most item. On screen, however, it would be the top most item covering everything underneath it.
The hierarchy would look like

View

Video View

Profile Image

Time

Full Name

Post

Button

imageView

insertSubview:

insertSubview inserts a view at a given position in the list. Your code is inserting at position 0. In the hierarchical structure, this would be the top most item. On screen, however, it would be the bottom most item covered by everything on top of it.
The hierarchy would look like

View

Video View

imageView

Profile Image

Time

Full Name

Post

Button

Hope that helps.

ContentLicense: CC BY-SA 4.0

Body:
I have a view that displays 1 picture at a time and that picture is supposed to be the background image. I also have other elements on top of that image that are supposed to change on touch  . The view that I have is called VideoView and I have elements on top . All of this works my problem is that when I use insertSubview all the elements on top change (like they are supposed to) but the image stays the same (VideoView) and it is supposed to change . If I replace the InsertSubView with addSubview then the image changes correctly on click but my top elements do not show . I know that what I'm supposed to use is insertSubview and on touch I can see the image URL changing but the screen stays with the first default image .

I think I know what might be going on . On every tap I am adding a new InsertSubview and the new image might be behind the old image . I verified by uploading a video . I first had an image and when I tapped to go to the next screen the image stayed however the video sound came on .

class BookViewC: UIViewController{
    @IBOutlet weak var VideoView: UIView!

    var imageView: UIImageView?

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  // This is how I change images, touchCount number is linked with unique image depending on the number passed in .

    for touch in touches {
        let location = touch.location(in: self.VideoView)

          if location.x <  self.VideoView.layer.frame.size.width / 2 {
            if touchCount == 0 || touchCount < 0 {
                touchCount = 0
            } else {
                touchCount = touchCount - 1

            }
           reloadTable(Offset: touchCount)
        }
        else {
            touchCount = touchCount + 1
            reloadTable(Offset: touchCount)

        }
    }
}

func ShowImage(s_image: String) {
    let imgURL: NSURL = NSURL(string: s_image)!
    let request:NSURLRequest =  NSURLRequest(url: imgURL as URL)
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)

    bookviewImage.imageView = UIImageView(image: UIImage(named: s_image))
    bookviewImage.imageView?.frame = VideoView.bounds
    bookviewImage.imageView?.contentMode = UIViewContentMode.scaleAspectFill

    let task = session.dataTask(with: request as URLRequest,    completionHandler: {(data, response, error) in
        DispatchQueue.main.async(execute: { () -> Void in

            if data != nil {

                self.bookviewImage.imageView?.image = UIImage(data: data!)
                self.VideoView.insertSubview(self.bookviewImage.imageView!, at: 0)
               // self.VideoView.addSubview(self.bookviewImage.imageView!)

            } else {
                self.bookviewImage.imageView!.image = nil
            }

        })
    });
    task.resume()
}

    func reloadTable(Offset: Int) {

    // send http request

        session.dataTask(with:request, completionHandler: {(data, response, error) in
            if error != nil {

            } else {
                do {

       let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any]

   if let Streams = parsedData["Results"] as? [AnyObject]?
       {

     if self.streamsModel.Locations.count >= 0 {
                         // Get Results

                        }

        DispatchQueue.main.async {
          for Stream in Streams! {

if let s_image = Stream["stream_image"] as? String {
self.ShowImage(s_image: s_image)

 }
     }
       }

This background Image on InsertSubview does not change on click however when I add AddSubview the background image changes so I know there is something wrong in my code since the InsertSubview background image is not updating

[![ .][2]][2]


问:
I'd like to apply margin-top inside the box
Apply this code and you can see it. The margine-top of the internal box is applied to the outside. How can inBox not affect the box?</p>

```<code><!DOCTYPE html>
<html>
<head>
  <style>
.box{
  width: 400px;
  height: 400px;
  background-color: red;
}
.inBox{
  width: 200px;
  height: 200px;
  background-color: white;

  margin-top: 100px;
}
  </style>
  <meta charset="utf-8">
</head>
<body>
  <div class = "box">
    <div class = "inBox">
  </div>
</body>
</html>
</code>```

答:
You can’t do margins inside an element. You can use padding. If you don’t want the padding to affect the side of the box, also set box-sizing: border-box.

Vertical margins have some unintuitive characteristics, like collapsing. There are ways to prevent vertical margin collapse that may solve your issue.

Body:
Apply this code and you can see it. The margine-top of the internal box is applied to the outside. How can inBox not affect the box?

<!DOCTYPE html>

  <meta charset="utf-8">


问:
Why is most of the output not being redirected to the file?
I have a batch script that opens a PS session as bypass policy and executes whatever the PS script needs to execute

```<code>set "psFile=.\main.ps1"

Powershell.exe -ExecutionPolicy ByPass -Command "&{%psFile% %2 %3 %4 %5 %6 | Tee-Object -FilePath log.txt}"
</code>```

I am getting what I want: output to both console AND file. however, when I opened the file after the execution was finished, it only contained like one line from everything else that was printed on the console. 99% of the output was not redirected to the log file.

Why is that?

Also, one more thing, I would like to use this bat file for any PS script, so I tried doing something like this:

```<code>set psFile="%1"

Powershell.exe -ExecutionPolicy ByPass -Command "&{%psFile% %2 %3 %4 %5 %6 | Tee-Object -FilePath log.txt}"
</code>```

and when i open a CMD and type the following:

```<code>runPS.bat main.ps1 DB1
</code>```

it complains:

The term 'main.ps1' is not recognized as the name of a cmdlet, function, script file, or
      operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
      again.

答:
```<code>@echo off
setlocal

rem Get fullpath of 1st argument.
for %%A in ("%~1") do set "psfile=%%~fA"

rem Save log in same directory of 1st argument.
set "logfile=%~dp1log.txt"

if defined psfile (
    rem Run the PS1 file with remaining arguments and tee the piped stdout stream.
    Powershell.exe -ExecutionPolicy ByPass -Command "&{&'%psFile%' '%~2' '%~3' '%~4' '%~5' '%~6' | Tee-Object -FilePath '%logfile%'}"
)
</code>```

The for loop will get the full path of the 1st argument
if a fullpath was not passed.

The log file is recommended as a fullpath, to insure success,
and the knowing where it is saved.

The single quotes surrrounding the paths helps with any
possible whitespace etc.

Tested with PS1 to show passed arguments:

```<code>$args
</code>```

which seems to show all stdout OK with a test.

To include other streams, view About Redirection

Body:
I have a batch script that opens a PS session as bypass policy and executes whatever the PS script needs to execute

set "psFile=.\main.ps1"

Powershell.exe -ExecutionPolicy ByPass -Command "&{%psFile% %2 %3 %4 %5 %6 | Tee-Object -FilePath log.txt}"

I am getting what I want: output to both console AND file. however, when I opened the file after the execution was finished, it only contained like one line from everything else that was printed on the console. 99% of the output was not redirected to the log file.

Why is that?

Also, one more thing, I would like to use this bat file for any PS script, so I tried doing something like this:

set psFile="%1"

Powershell.exe -ExecutionPolicy ByPass -Command "&{%psFile% %2 %3 %4 %5 %6 | Tee-Object -FilePath log.txt}"

and when i open a CMD and type the following:

runPS.bat main.ps1 DB1

it complains:

The term 'main.ps1' is not recognized as the name of a cmdlet, function, script file, or
      operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
      again.

Body:
@echo off
setlocal

rem Get fullpath of 1st argument.
for %%A in ("%~1") do set "psfile=%%~fA"

rem Save log in same directory of 1st argument.
set "logfile=%~dp1log.txt"

if defined psfile (
    rem Run the PS1 file with remaining arguments and tee the piped stdout stream.
    Powershell.exe -ExecutionPolicy ByPass -Command "&{&'%psFile%' '%~2' '%~3' '%~4' '%~5' '%~6' | Tee-Object -FilePath '%logfile%'}"
)

The for loop will get the full path of the 1st argument
if a fullpath was not passed.

The log file is recommended as a fullpath, to insure success,
and the knowing where it is saved.

The single quotes surrrounding the paths helps with any
possible whitespace etc.

Tested with PS1 to show passed arguments:

$args

which seems to show all stdout OK with a test.

To include other streams, view About Redirection


问:
Clear browser cache in Angular
I have a problem with an Angular application that I update very often.

I would like to avoid the browser cache and I am trying several alternatives but none of them work.

The first thing is that I have very difficult to test if the solution works because when I upload a new version, sometimes I see it without having to do more than refresh the page, and other times I need to open the console and force the refresh emptying cache.

I tried to include in the request header, Cache-Control: no-cache, as you can see in the image, but that does not work for me.

I have also tried, put in the app.component.ts

```<code>templateUrl: './app.component.html? v1'
</code>```

as I have seen in some answers, but neither.

The truth is that I'm desperate because when I give something that I think works, when I check it with my boss he does not refresh it :-( , and the bad thing is that as I say I do not know how to really check that really, every time I enter the web, the latest version is requested from the server.

Thank you for your help

答:
Try [window.]location.reload(true):

```<code>if (localStorage.getItem('refreshed') === null) {
    localStorage['refreshed'] = true;
    window.location.reload(true);
} else {
    localStorage.removeItem('refreshed');
}
</code>```

According to w3schools:

By default, the reload() method reloads the page from the cache, but you can force it to reload the page from the server by setting the forceGet parameter to true: location.reload(true).

Title: Clear browser cache in Angular

Body:
I have a problem with an Angular application that I update very often.

I would like to avoid the browser cache and I am trying several alternatives but none of them work.

The first thing is that I have very difficult to test if the solution works because when I upload a new version, sometimes I see it without having to do more than refresh the page, and other times I need to open the console and force the refresh emptying cache.

I tried to include in the request header, Cache-Control: no-cache, as you can see in the image, but that does not work for me.

I have also tried, put in the app.component.ts

templateUrl: './app.component.html? v1'

as I have seen in some answers, but neither.

The truth is that I'm desperate because when I give something that I think works, when I check it with my boss he does not refresh it :-( , and the bad thing is that as I say I do not know how to really check that really, every time I enter the web, the latest version is requested from the server.

Thank you for your help

Body:
Try [window.]location.reload(true):

if (localStorage.getItem('refreshed') === null) {
    localStorage['refreshed'] = true;
    window.location.reload(true);
} else {
    localStorage.removeItem('refreshed');
}

According to w3schools:

By default, the reload() method reloads the page from the cache, but you can force it to reload the page from the server by setting the forceGet parameter to true: location.reload(true).


问:
How to copy handlebars files to dist folder
I'm using Typescript, which compiles from src/ to lib/ folder, and Babel, which compiles from lib/ to dist/.

The issue I have is that I have .handlebars files within src/email_templates/ that are not being copied over to dist/ when I compile the app. Therefore when I run the app it fails with errors as dist/email_templates/ does not exist.

I'm using nodemailer-handlebars package and have tried moving the email_templates/ folder to the project root directory and setting viewPath to the folder, however this also fails as the app is located in var/www/api.my-domain.com/. It seems that the fact that I have periods in api.my-domain.com folder name causes viewPath to fail with error:

```<code>TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:125:11)
    at Object.resolve (path.js:1080:7)
    at ExpressHandlebars._resolveLayoutPath (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:342:17)
    at ExpressHandlebars.<anonymous> (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:223:35)
</code>```

Here's my package.json script to build the app:

```<code>"build": "tsc && babel ./lib --out-dir ./dist ",
</code>```

How can I change this so that it delete the current contents of dist/email_templates then copies the contents of src/email_templates to dist/email_templates?

答:
Solved using the cpx package: https://www.npmjs.com/package/cpx

```<code>npm install cpx --save-dev
</code>```

Package.json:

```<code>- "build": "tsc && babel ./lib --out-dir ./dist",
+ "build": "tsc && babel ./lib --out-dir ./dist && cpx \"./src/email_templates/**/*\" ./dist/email_templates --clean",
</code>```

```<code>npm run build
</code>```

Body:
I'm using Typescript, which compiles from src/ to lib/ folder, and Babel, which compiles from lib/ to dist/.

The issue I have is that I have .handlebars files within src/email_templates/ that are not being copied over to dist/ when I compile the app. Therefore when I run the app it fails with errors as dist/email_templates/ does not exist.

I'm using nodemailer-handlebars package and have tried moving the email_templates/ folder to the project root directory and setting viewPath to the folder, however this also fails as the app is located in var/www/api.my-domain.com/. It seems that the fact that I have periods in api.my-domain.com folder name causes viewPath to fail with error:

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined
    at validateString (internal/validators.js:125:11)
    at Object.resolve (path.js:1080:7)
    at ExpressHandlebars._resolveLayoutPath (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:342:17)
    at ExpressHandlebars.<anonymous> (/var/www/api.my-domain.com/node_modules/express-handlebars/lib/express-handlebars.js:223:35)

Here's my package.json script to build the app:

"build": "tsc && babel ./lib --out-dir ./dist ",

How can I change this so that it delete the current contents of dist/email_templates then copies the contents of src/email_templates to dist/email_templates?

Body:
Solved using the cpx package: https://www.npmjs.com/package/cpx

npm install cpx --save-dev

Package.json:

- "build": "tsc && babel ./lib --out-dir ./dist",
+ "build": "tsc && babel ./lib --out-dir ./dist && cpx \"./src/email_templates/**/*\" ./dist/email_templates --clean",

npm run build


问:
Images loaded in ImageView disappear on fragment reLoad
I have a Fragment to edit contents. In this Fragment I  have ImageView which displays image picked from gallery or camera This Fragment in turn also opens another fragment. From this fragment when I goes back to Edit fragment displayed image goes disappear and
ImageViews goes blank and every thing else (Edittext,Textviews) remains persistant(filled)

Note that when I goes back to edit fragment its OnCreateView is called not OnCreate method
for example when we replace fragment with another fragment and Pops Back to previous one its OnCreateView method is called first

I can't understand what is happening pls Help.

答:
old, but maybe this can help others.

I solving this by set source path to variable, then call in onResume() method.

```<code>@Override
public void onResume() {
    super.onResume();

    //set again your ImageView source here..
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
old, but maybe this can help others.

I solving this by set source path to variable, then call in onResume() method.

@Override
public void onResume() {
    super.onResume();

    //set again your ImageView source here..
}


问:
How to update Android Textview in an on going loop?
I'm using Kotlin. I have a loop that will continue going. But for some reason, I am unable to update the text view. Here is my simplified example.</p>

```<code>var i = 0
while (!Thread.currentThread().isInterrupted) {
    setString(i.toString())
    i++
    Log.i("Loging value of i === ", i.toString())
}

private fun setString (string : String) {
    tempText.text = string
}
</code>```

答:
View's can only be updated in UI Thread. try something like this : </p>

```<code>while (!Thread.currentThread().isInterrupted) {

 runOnUiThread(
            object : Runnable {
                override fun run() {
                    //do your view update work here
                      setString(i.toString())
                }
            }
    )
    i++
}
</code>```

Body:
I'm using Kotlin. I have a loop that will continue going. But for some reason, I am unable to update the text view. Here is my simplified example.

var i = 0
while (!Thread.currentThread().isInterrupted) {
    setString(i.toString())
    i++
    Log.i("Loging value of i === ", i.toString())
}

private fun setString (string : String) {
    tempText.text = string
}

Body:
View's can only be updated in UI Thread. try something like this :

while (!Thread.currentThread().isInterrupted) {

 runOnUiThread(
            object : Runnable {
                override fun run() {
                    //do your view update work here
                      setString(i.toString())
                }
            }
    )
    i++
}


问:
Code execution issues caused by `volatile` visibility

eg:1

public class Test extends Thread {
    private Boolean stop = false;
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.start();
        TimeUnit.SECONDS.sleep(1);
        test.stop = true;
    }
    @Override
    public void run() {
        while (!this.stop) {
        }
        System.out.println("end");
    }
}
```

<p>The code is written like this, and the thread will execute endlessly. However, add a little something to the while loop and change it to something like this:</p>

<h3>eg:2</h3>

<pre class="lang-java prettyprint-override"><code>public class Test extends Thread {
    private Boolean stop = false;
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.start();
        TimeUnit.SECONDS.sleep(1);
        test.stop = true;
    }
    @Override
    public void run() {
        while (!this.stop) {
            System.out.println(1);  // Add some code
        }
        System.out.println("end");
    }
}

</code>```

Q:

why is this happening? ??? Why can I interrupt it by printing a sentence, and it will not be interrupted without printing. . . . . . . . . . . . . . Note that stop is not added volatile. If added, it can be stopped after 1 second.

答:
Because stop is not volatile, it is not guaranteed when a change in it made by one thread will be seen by another (unless something else provides that guarantee like a lock). So you will get unpredictable results.

There are a huge number of optimization that cannot be made if a change in an object made by one thread needs to be visible in another. But that is only a requirement for a very tiny fraction of realistic code. So the Java implementers wisely decided to make code that relies on that behavior indicate that and allow these significant optimizations to be made in the 99.5% of code that doesn't care about this.

If you want to rely on a change made in one thread being visible to another, you must use one of the mechanisms specified to provide this behavior. Otherwise, results are not guaranteed.

Body:
eg:1

public class Test extends Thread {
    private Boolean stop = false;
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.start();
        TimeUnit.SECONDS.sleep(1);
        test.stop = true;
    }
    @Override
    public void run() {
        while (!this.stop) {
        }
        System.out.println("end");
    }
}

The code is written like this, and the thread will execute endlessly. However, add a little something to the while loop and change it to something like this:

eg:2

public class Test extends Thread {
    private Boolean stop = false;
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        test.start();
        TimeUnit.SECONDS.sleep(1);
        test.stop = true;
    }
    @Override
    public void run() {
        while (!this.stop) {
            System.out.println(1);  // Add some code
        }
        System.out.println("end");
    }
}

Q:

why is this happening? ??? Why can I interrupt it by printing a sentence, and it will not be interrupted without printing. . . . . . . . . . . . . . Note that stop is not added volatile. If added, it can be stopped after 1 second.


问:
Singletons in multi threaded environment
when using singletons, if the class has instance fields should you be careful when several threads might be using the singleton? (And the fields are mutable and their values can be changed)

I havn't tried but in theory it seems like the answer is yes and you would need synchronization (or skip the singleton)

答:
When you access an object (or the same mutable data) from multiple threads (or processes) you will need some kind of synchronization. There is no difference whether it is a singleton or any other "non-singleton" object.

One additional question, in case of singletons is the creation of the singleton though, if this is created the first time it is used, then the first time might be concurrently for different threads, so you will need to synchronize singleton-creation as well.


问:
Request thread interrupt not working on Ios
I create a new thread, and y need to interrupt, I use the thread.interrup(), but when I throw request thread interrupt is not working on ios, works fine on simulator or in Android device.

I Attach code to try it.

My temporal solution is use a Flag to break while, but I want to use the InterruptedException

```<code>package com.kandy.forms;

import com.codename1.io.Log;
import com.codename1.ui.Button;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.layouts.BoxLayout;

public class Interrup extends Form {

    private Form previous;
    private Thread thread = null;

    public Interrup() {

        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        Button newThread = new Button ("Start Thread");
        newThread.addActionListener((e) -> {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(1000);
                            Log.p("thread working");
                        } catch (InterruptedException ie) {
                            Dialog.show("Message", "Interruption received", "Ok", null);
                            break;
                        }
                    }
                }
            });
            //thread start
            thread.start();
        });

        Button interruptTreath = new Button ("Interrupt");
        interruptTreath.addActionListener((e) -> {
            Log.p("Interrupt Sended");
            thread.interrupt();
        });

        add(newThread);
        add(interruptTreath);

    }

    public void show() {
        previous = Display.getInstance().getCurrent();
        super.show();
    }

    public void goBack(){
        previous.showBack();
    }

}

</code>```

答: This isn't supported on iOS. Neither is stop etc. as those are pretty hard to get working consistently across platforms. This is especially true for iOS and the thread implementation in the JavaScript port.</p>

Body:
I create a new thread, and y need to interrupt, I use the thread.interrup(), but when I throw request thread interrupt is not working on ios, works fine on simulator or in Android device.

I Attach code to try it.

My temporal solution is use a Flag to break while, but I want to use the InterruptedException

package com.kandy.forms;

import com.codename1.io.Log;
import com.codename1.ui.Button;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.layouts.BoxLayout;

public class Interrup extends Form {

    private Form previous;
    private Thread thread = null;

    public Interrup() {

        setLayout(new BoxLayout(BoxLayout.Y_AXIS));

        Button newThread = new Button ("Start Thread");
        newThread.addActionListener((e) -> {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(1000);
                            Log.p("thread working");
                        } catch (InterruptedException ie) {
                            Dialog.show("Message", "Interruption received", "Ok", null);
                            break;
                        }
                    }
                }
            });
            //thread start
            thread.start();
        });

        Button interruptTreath = new Button ("Interrupt");
        interruptTreath.addActionListener((e) -> {
            Log.p("Interrupt Sended");
            thread.interrupt();
        });

        add(newThread);
        add(interruptTreath);

    }

    public void show() {
        previous = Display.getInstance().getCurrent();
        super.show();
    }

    public void goBack(){
        previous.showBack();
    }

}


问:
deepCss is failing to identify an element inside the shadow root in Protractor
Can not identify button which inside the ShadowRoot in protractor.

I have tried using deepCss as follows,

this.startNowButton = element(by.deepCss('button[class="apply-now"]'));

But I am getting

NoSuchElementError: No element found using locator: By(css selector, * /deep/ button[class="apply-now"])

Is this the correct way to identify the elements inside the ShadowRoot for Protractor? Thanks

my HTML page is similar to as follows,

```<code><div id="modal">
<div class="push-wrap">
   <header id ="site-header">
      <hmy-cms-header class="hydrated">
         #shadow-root (open)
           <header>
               <div class=notification-banner> ... </div>
               <div class="ca">
                  <button class="apply-now">"Apply"<span>now</span>
</code>```

答: The pull request https://github.com/angular/protractor/pull/4786 is not yet merged. I have implemented the suggested workaround (https://github.com/angular/protractor/issues/4367) and then it worked. </p>

Body:
Can not identify button which inside the ShadowRoot in protractor.

I have tried using deepCss as follows,

this.startNowButton = element(by.deepCss('button[class="apply-now"]'));

But I am getting

NoSuchElementError: No element found using locator: By(css selector, * /deep/ button[class="apply-now"])

Is this the correct way to identify the elements inside the ShadowRoot for Protractor? Thanks

my HTML page is similar to as follows,

      <hmy-cms-header class="hydrated">
         #shadow-root (open)

 ...

                  <button class="apply-now">"Apply"now


问:
How to extract one file with commit history from a Git repo with index-filter & co?
I have a Git repo converted from SVN to Mercurial to Git, and I wanted to extract just one source file. I also had weird characters like aÌ (an encoding mismatch corrupted Unicode ä) and spaces in the filenames.

How can I extract one file from a repository and place it at the root of the new repo?

答:
The following will rewrite the history and keep only commits that touch the list of files you give. You probably want to do that in a clone of your repository to avoid losing the original history.

FILES='path/to/file1 other-path/to/file2 file3'
git filter-branch --prune-empty --index-filter "
                        git read-tree --empty
                        git reset \$GIT_COMMIT -- $FILES
                " \
        -- --all -- $FILES
```

Then you can merge that new branch into your target repository, via normal merge or rebase commands according to your use-case.

Body:
The following will rewrite the history and keep only commits that touch the list of files you give. You probably want to do that in a clone of your repository to avoid losing the original history.

FILES='path/to/file1 other-path/to/file2 file3'
git filter-branch --prune-empty --index-filter "
                        git read-tree --empty
                        git reset \$GIT_COMMIT -- $FILES
                " \
        -- --all -- $FILES

Then you can merge that new branch into your target repository, via normal merge or rebase commands according to your use-case.


问:
Hyperledger fabric 1.2 capabilities error
I am trying to use hyperledger fabric sample network with my own chaincode.
I am using balance-transfer but my chaincode requires collections config file because It is using private data. I added to sendInstantiateProposal request but, I keep getting the error while instantiating the chaincode;

```<code>{"success":false,"message":"Failed to instantiate the chaincode. cause:instantiate proposal resulted in an error :: Error: as V1_2 or later capability is not enabled, private channel collections and data are not available"}
</code>```

I added capabilities section to artifacts/channel/configtx.yaml file but error still continue. You can see that file from this link.

So, how can I solve this error and make this network work with private channels ?

答:
This error occurs when Application and channels are not enabled with the V1.2 or above capabilities.

Solution:

Add Capabilities in configtx.yaml file

```<code>Capabilities:
    # Channel capabilities apply to both the orderers and the peers and must be
    # supported by both.
    # Set the value of the capability to true to require it.
    Channel: &ChannelCapabilities
        # V1.3 for Channel is a catchall flag for behavior which has been
        # determined to be desired for all orderers and peers running at the v1.3.x
        # level, but which would be incompatible with orderers and peers from
        # prior releases.
        # Prior to enabling V1.3 channel capabilities, ensure that all
        # orderers and peers on a channel are at v1.3.0 or later.
        V1_3: true

    # Orderer capabilities apply only to the orderers, and may be safely
    # used with prior release peers.
    # Set the value of the capability to true to require it.
    Orderer: &OrdererCapabilities
        # V1.1 for Orderer is a catchall flag for behavior which has been
        # determined to be desired for all orderers running at the v1.1.x
        # level, but which would be incompatible with orderers from prior releases.
        # Prior to enabling V1.1 orderer capabilities, ensure that all
        # orderers on a channel are at v1.1.0 or later.
        V1_1: true

    # Application capabilities apply only to the peer network, and may be safely
    # used with prior release orderers.
    # Set the value of the capability to true to require it.
    Application: &ApplicationCapabilities
        # V1.3 for Application enables the new non-backwards compatible
        # features and fixes of fabric v1.3.
        V1_3: true
        V1_2: false
        V1_1: false
</code>```

And then apply them in Profile section

```<code>ThreeOrgsOrdererGenesis:
        <<: *ChannelDefaults
        Capabilities:
            <<: *ChannelCapabilities
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                    - *OrdererOrg
            Capabilities:
                <<: *OrdererCapabilities
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *Org1
                    - *Org2
                    - *Org3

    ThreeOrgsChannel:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org1
                - *Org2
                - *Org3
            Capabilities:
                <<: *ApplicationCapabilities
</code>```

Refer fabric-samples/first-network configtx.yaml file for more details.

Body:
I am trying to use hyperledger fabric sample network with my own chaincode.
I am using balance-transfer but my chaincode requires collections config file because It is using private data. I added to sendInstantiateProposal request but, I keep getting the error while instantiating the chaincode;

{"success":false,"message":"Failed to instantiate the chaincode. cause:instantiate proposal resulted in an error :: Error: as V1_2 or later capability is not enabled, private channel collections and data are not available"}

I added capabilities section to artifacts/channel/configtx.yaml file but error still continue. You can see that file from this link.

So, how can I solve this error and make this network work with private channels ?

Body:
This error occurs when Application and channels are not enabled with the V1.2 or above capabilities.

Solution:

Add Capabilities in configtx.yaml file

Capabilities:
    # Channel capabilities apply to both the orderers and the peers and must be
    # supported by both.
    # Set the value of the capability to true to require it.
    Channel: &ChannelCapabilities
        # V1.3 for Channel is a catchall flag for behavior which has been
        # determined to be desired for all orderers and peers running at the v1.3.x
        # level, but which would be incompatible with orderers and peers from
        # prior releases.
        # Prior to enabling V1.3 channel capabilities, ensure that all
        # orderers and peers on a channel are at v1.3.0 or later.
        V1_3: true

    # Orderer capabilities apply only to the orderers, and may be safely
    # used with prior release peers.
    # Set the value of the capability to true to require it.
    Orderer: &OrdererCapabilities
        # V1.1 for Orderer is a catchall flag for behavior which has been
        # determined to be desired for all orderers running at the v1.1.x
        # level, but which would be incompatible with orderers from prior releases.
        # Prior to enabling V1.1 orderer capabilities, ensure that all
        # orderers on a channel are at v1.1.0 or later.
        V1_1: true

    # Application capabilities apply only to the peer network, and may be safely
    # used with prior release orderers.
    # Set the value of the capability to true to require it.
    Application: &ApplicationCapabilities
        # V1.3 for Application enables the new non-backwards compatible
        # features and fixes of fabric v1.3.
        V1_3: true
        V1_2: false
        V1_1: false

And then apply them in Profile section

ThreeOrgsOrdererGenesis:
        <<: *ChannelDefaults
        Capabilities:
            <<: *ChannelCapabilities
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                    - *OrdererOrg
            Capabilities:
                <<: *OrdererCapabilities
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *Org1
                    - *Org2
                    - *Org3

    ThreeOrgsChannel:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *Org1
                - *Org2
                - *Org3
            Capabilities:
                <<: *ApplicationCapabilities

Refer fabric-samples/first-network configtx.yaml file for more details.


问:
jQuery each function not working need to replace each attribute
I have this html

```<code><form method="POST" action="" id="order" class="forms">
    <div>
        <span class="col1">Ref.</span>
        <span class="col2">Number</span>
        <span class="col3">Color</span>
        <span class="col4">Remarks</span>
        <span class="col5">Prijs</span>
    </div>
    <div class="order">
        <input type="text" name="ref-1" class="col1" />
        <input type="text" name="num-1" class="col2" />
        <input type="text" name="color-1" class="col3" />
        <input type="text" name="remark-1" class="col4" />
        <input type="text" name="price-1" class="col5" />
    </div>
    <a id="add" href="#">+</a>
</form>
</code>```

And this jquery

```<code>$("#add").click(function() {
    $("#order").children(":eq(1)").clone().each(function() {
            var index = $("#order").children().length - 1;
            alert(index);

        $(this).children().find(":input").each(function() {

                alert(index);

                    $(this).attr("[name]", function(i, v) {

                        return v.substr(0, v.lastIndexOf("-") + 1) + index;

                    }).val("");

                });
    }).insertBefore("#add");
});
</code>```

I need to replace the -1 part of each input name to the incremented value.
But the js never gets to the $(this).attr() function
When I run this code it doesn't show the second alert box when I click #add

答:
I haven't checked the whole of  your code but there is a glaring error in that

```<code>.attr("[name]"
</code>```

should be

```<code>.attr("name"
</code>```

You also need to remove the .children() from the line

```<code>$(this).children().find(":input")
</code>```

and make it

```<code>$(this).find(":input")
</code>```

This is because this refers to the div element that contains the inputs. By running .children() on that it returns the input elements, and by doing find() on that it returns nothing, because find looks inside the selected elements, not-including the elements it runs on.

updated jsfiddle at http://jsfiddle.net/gaby/TpmdP/

Body:
I have this html

<form method="POST" action="" id="order" class="forms">

        Ref.
        Number
        Color
        Remarks
        Prijs

        <input type="text" name="ref-1" class="col1" />
        <input type="text" name="num-1" class="col2" />
        <input type="text" name="color-1" class="col3" />
        <input type="text" name="remark-1" class="col4" />
        <input type="text" name="price-1" class="col5" />

    +
</form>

And this jquery

$("#add").click(function() {
    $("#order").children(":eq(1)").clone().each(function() {
            var index = $("#order").children().length - 1;
            alert(index);

        $(this).children().find(":input").each(function() {

                alert(index);

                    $(this).attr("[name]", function(i, v) {

                        return v.substr(0, v.lastIndexOf("-") + 1) + index;

                    }).val("");

                });
    }).insertBefore("#add");
});

I need to replace the -1 part of each input name to the incremented value.
But the js never gets to the $(this).attr() function
When I run this code it doesn't show the second alert box when I click #add

Body:
I haven't checked the whole of  your code but there is a glaring error in that

.attr("[name]"

should be

.attr("name"

You also need to remove the .children() from the line

$(this).children().find(":input")

and make it

$(this).find(":input")

This is because this refers to the div element that contains the inputs. By running .children() on that it returns the input elements, and by doing find() on that it returns nothing, because find looks inside the selected elements, not-including the elements it runs on.

updated jsfiddle at http://jsfiddle.net/gaby/TpmdP/


问:
Printing random data from list into file
I have 3 lists

```<code>x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]
</code>```

I need to write into a file with a random from x, y, and z on to a new line each time.

```<code>Keyword = input("Directory to list")

with open(Keyword) as f:
        content = f.readlines()

    content = [x.strip() for x in content]

    with open("test.txt") as w:
        w.write(PageFormat + )
</code>```

Output should look like this:

```<code>2 // 6 // 8

3 // 4 // 9

1 // 5 // 9

2 // 5 // 9

1 // 4 // 7
</code>```

("/" included)

答:
TRY:-

```<code>import random

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

file = open("new.txt",'w')

for a in range(0, 10):
    file.write(x[random.randrange(0,3)] + " // " + y[random.randrange(0,3)] + " // " + z[random.randrange(0,3)] + "\n")

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

SAMPLE OUTPUT:-

```<code>2 // 4 // 9
1 // 6 // 9
2 // 5 // 9
1 // 6 // 8
1 // 5 // 8
3 // 5 // 9
3 // 4 // 7
2 // 6 // 7
1 // 5 // 7
2 // 4 // 8
</code>```

You can control the number of iterations by changing the second argument of range(). This program will write 10 lines into a new file.

Body:
I have 3 lists

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

I need to write into a file with a random from x, y, and z on to a new line each time.

Keyword = input("Directory to list")

with open(Keyword) as f:
        content = f.readlines()

    content = [x.strip() for x in content]

    with open("test.txt") as w:
        w.write(PageFormat + )

Output should look like this:

2 // 6 // 8

3 // 4 // 9

1 // 5 // 9

2 // 5 // 9

1 // 4 // 7

("/" included)

Body:
TRY:-

import random

x = ["1", "2", "3"]

y = ["4", "5", "6"]

z = ["7", "8", "9"]

file = open("new.txt",'w')

for a in range(0, 10):
    file.write(x[random.randrange(0,3)] + " // " + y[random.randrange(0,3)] + " // " + z[random.randrange(0,3)] + "\n")

file.close()

SAMPLE OUTPUT:-

2 // 4 // 9
1 // 6 // 9
2 // 5 // 9
1 // 6 // 8
1 // 5 // 8
3 // 5 // 9
3 // 4 // 7
2 // 6 // 7
1 // 5 // 7
2 // 4 // 8

You can control the number of iterations by changing the second argument of range(). This program will write 10 lines into a new file.


问:
How to customise pandas box and whisker plot with additional percentiles?
I am trying to produce the following plot, that was made in excel, by using pandas.

A lot of plotting at at work is done using excel and it is fiddly and tedious to get the data into the required format.  I want to use pandas, but my bosses want to see the exact same (or very close) plots being produced.

I normally use seaborn for box plots and find it very convenient but I need to show more percentiles (5th, 10th, 25th, 50th, 75th, 90th, and 95th) as shown on the figure legend.

I know that seaborn/matplotlib lets me change the whiskers extent using whis=[10,90], and I can use showmean=True, but that leaves the other markers (95th and 5th percentiles) to add to each plot. How to overlay those?

I have my data grouped as I want, and I can extract the percentiles using .describe() as below
pcntls=assay.groupby(['LocalSTRAT']).describe(percentiles=[0.1,0.05,0.25,0.5,0.75,0.9,0.95])

and transform which gives me this:

```<code>LocalSTRAT  AB  CBC     CLB     LAB     LBB     LBL     MS  TB  TBL     UAB     UBB
count   982.000000  234.000000  159.000000  530.000000  1136.000000     72.000000   267.000000  1741.000000     16.000000   1641.000000     2099.000000
mean    0.687658    1.410962    0.118302    0.211321    0.110251    0.077917    0.766124    0.262648    0.191875    0.119174    1.320357
std     0.814027    0.855342    0.148397    0.286574    0.146550    0.088921    0.647259    0.309134    0.125497    0.207197    1.393613
min     0.005000    0.005000    0.020000    0.005000    0.005000    0.010000    0.005000    0.005000    0.060000    0.005000    0.005000
5%  0.030000    0.196500    0.030000    0.020000    0.020000    0.020000    0.060000    0.020000    0.067500    0.005000    0.170000
10%     0.050000    0.363000    0.038000    0.020000    0.020000    0.021000    0.096000    0.030000    0.070000    0.020000    0.230000
25%     0.130000    0.825000    0.045000    0.050000    0.030000    0.030000    0.225000    0.050000    0.077500    0.030000    0.450000
50%     0.400000    1.260000    0.070000    0.120000    0.050000    0.050000    0.610000    0.150000    0.175000    0.060000    0.940000
75%     0.950000    1.947500    0.140000    0.250000    0.120000    0.072500    1.120000    0.350000    0.257500    0.130000    1.570000
90%     1.720000    2.411000    0.262000    0.520000    0.265000    0.149000    1.624000    0.640000    0.340000    0.250000    2.770000
95%     2.370000    2.967500    0.322000    0.685500    0.390000    0.237000    2.037000    0.880000    0.390000    0.410000    4.322000
max     7.040000    5.070000    1.510000    2.620000    1.450000    0.580000    3.530000    2.390000    0.480000    4.190000    11.600000

</code>```

I am stuck with how to begin to construct boxplots from scratch using this output.

I think it's easier to construct some boxplots in the normal way, and then add the extra couple of data points (5th and 95th percentile markers) over the top but can't figure out how to do this.

(Bonus points for a way to make a legend like the one shown or how to insert an image file of this into my plot, and get the log-style gridlines, and include the counts in the x axis!)

答:
Just overlay a scatter plot using the percentiles extracted from the .describe() output, remembering to sort both to make sure the order doesn't get mixed up.
The legend was made as an image externally and inserted separately.

Counts were calculated and added using plt.text().

Logarithmic gridlines applied using plt.grid(True, which='both') and setting the axis to log.

code and result below.

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt

pathx = r"C:\boxplots2.xlsx"

pathx =  pathx.replace( "\\", "/")#avoid escape character issues
#print pathx
#pathx = pathx[1:len(pathx)-1]
df=pd.read_excel(pathx)

#this line removes missing data rows (where the strat is not specified)
df=df[df["STRAT"]!=0]

assay=df

factor_to_plot='Total %S'
f=factor_to_plot

x_axis_factor='STRAT'
g=x_axis_factor

pcntls=assay.groupby([g]).describe(percentiles=[0.05,0.1,0.25,0.5,0.75,0.9,0.95])
sumry= pcntls[f].T
#print sumry
ordered=sorted(assay[g].dropna().unique())

#set figure size and scale text
plt.rcParams['figure.figsize']=(15,10)
text_scaling=1.9
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=text_scaling)

#plot boxplot
ax=sns.boxplot(x=assay[g],y=assay[f],width=0.5,order=ordered, whis=[10,90],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"x","markersize":12,"markerfacecolor":"white", "markeredgecolor":"black"})

plt.axhline(0.3, color='green',linestyle='dashed', label="S%=0.3")

#this line sets the scale to logarithmic
ax.set_yscale('log')

leg= plt.legend(markerscale=1.5,bbox_to_anchor=(1.0, 0.5) )#,bbox_to_anchor=(1.0, 0.5)
#plt.title("Assay data")
plt.grid(True, which='both')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'],s=120,color='white',edgecolor='black')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'],s=120,color='white',edgecolor='black')

#add legend image
img = plt.imread("legend.jpg")
plt.figimage(img, 1900,900, zorder=1, alpha=1)

#next line is important, select a column that has no blanks or nans as the total items are counted.
assay['value']=assay['From']

vals=assay.groupby([g])['value'].count()
j=vals

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
#print ymax

#put n= values at top of plot
x=0
for i in range(len(j)):

    plt.text(x = x , y = ymax+0.2, s = "N=\n" +str(int(j[i])),horizontalalignment='center')
    #plt.text(x = x , y = 102.75, s = "n=",horizontalalignment='center')
    x+=1

#use the section below to adjust the y axis lable format to avoid default of 10^0 etc for log scale plots.
ylabels = ['{:.1f}'.format(y) for y in ax.get_yticks()]
ax.set_yticklabels(ylabels)
```

Which gives:

Body:
I am trying to produce the following plot, that was made in excel, by using pandas.

A lot of plotting at at work is done using excel and it is fiddly and tedious to get the data into the required format.  I want to use pandas, but my bosses want to see the exact same (or very close) plots being produced.

I normally use seaborn for box plots and find it very convenient but I need to show more percentiles (5th, 10th, 25th, 50th, 75th, 90th, and 95th) as shown on the figure legend.

I know that seaborn/matplotlib lets me change the whiskers extent using whis=[10,90], and I can use showmean=True, but that leaves the other markers (95th and 5th percentiles) to add to each plot. How to overlay those?

I have my data grouped as I want, and I can extract the percentiles using .describe() as below
pcntls=assay.groupby(['LocalSTRAT']).describe(percentiles=[0.1,0.05,0.25,0.5,0.75,0.9,0.95])

and transform which gives me this:

LocalSTRAT  AB  CBC     CLB     LAB     LBB     LBL     MS  TB  TBL     UAB     UBB
count   982.000000  234.000000  159.000000  530.000000  1136.000000     72.000000   267.000000  1741.000000     16.000000   1641.000000     2099.000000
mean    0.687658    1.410962    0.118302    0.211321    0.110251    0.077917    0.766124    0.262648    0.191875    0.119174    1.320357
std     0.814027    0.855342    0.148397    0.286574    0.146550    0.088921    0.647259    0.309134    0.125497    0.207197    1.393613
min     0.005000    0.005000    0.020000    0.005000    0.005000    0.010000    0.005000    0.005000    0.060000    0.005000    0.005000
5%  0.030000    0.196500    0.030000    0.020000    0.020000    0.020000    0.060000    0.020000    0.067500    0.005000    0.170000
10%     0.050000    0.363000    0.038000    0.020000    0.020000    0.021000    0.096000    0.030000    0.070000    0.020000    0.230000
25%     0.130000    0.825000    0.045000    0.050000    0.030000    0.030000    0.225000    0.050000    0.077500    0.030000    0.450000
50%     0.400000    1.260000    0.070000    0.120000    0.050000    0.050000    0.610000    0.150000    0.175000    0.060000    0.940000
75%     0.950000    1.947500    0.140000    0.250000    0.120000    0.072500    1.120000    0.350000    0.257500    0.130000    1.570000
90%     1.720000    2.411000    0.262000    0.520000    0.265000    0.149000    1.624000    0.640000    0.340000    0.250000    2.770000
95%     2.370000    2.967500    0.322000    0.685500    0.390000    0.237000    2.037000    0.880000    0.390000    0.410000    4.322000
max     7.040000    5.070000    1.510000    2.620000    1.450000    0.580000    3.530000    2.390000    0.480000    4.190000    11.600000

I am stuck with how to begin to construct boxplots from scratch using this output.

I think it's easier to construct some boxplots in the normal way, and then add the extra couple of data points (5th and 95th percentile markers) over the top but can't figure out how to do this.

(Bonus points for a way to make a legend like the one shown or how to insert an image file of this into my plot, and get the log-style gridlines, and include the counts in the x axis!)

Body:
Just overlay a scatter plot using the percentiles extracted from the .describe() output, remembering to sort both to make sure the order doesn't get mixed up.
The legend was made as an image externally and inserted separately.

Counts were calculated and added using plt.text().

Logarithmic gridlines applied using plt.grid(True, which='both') and setting the axis to log.

code and result below.

import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt

pathx = r"C:\boxplots2.xlsx"

pathx =  pathx.replace( "\\", "/")#avoid escape character issues
#print pathx
#pathx = pathx[1:len(pathx)-1]
df=pd.read_excel(pathx)

#this line removes missing data rows (where the strat is not specified)
df=df[df["STRAT"]!=0]

assay=df

factor_to_plot='Total %S'
f=factor_to_plot

x_axis_factor='STRAT'
g=x_axis_factor

pcntls=assay.groupby([g]).describe(percentiles=[0.05,0.1,0.25,0.5,0.75,0.9,0.95])
sumry= pcntls[f].T
#print sumry
ordered=sorted(assay[g].dropna().unique())

#set figure size and scale text
plt.rcParams['figure.figsize']=(15,10)
text_scaling=1.9
sns.set(style="whitegrid")
sns.set_context("paper", font_scale=text_scaling)

#plot boxplot
ax=sns.boxplot(x=assay[g],y=assay[f],width=0.5,order=ordered, whis=[10,90],data=assay, showfliers=False,color='lightblue',
            showmeans=True,meanprops={"marker":"x","markersize":12,"markerfacecolor":"white", "markeredgecolor":"black"})

plt.axhline(0.3, color='green',linestyle='dashed', label="S%=0.3")

#this line sets the scale to logarithmic
ax.set_yscale('log')

leg= plt.legend(markerscale=1.5,bbox_to_anchor=(1.0, 0.5) )#,bbox_to_anchor=(1.0, 0.5)
#plt.title("Assay data")
plt.grid(True, which='both')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['5%'],s=120,color='white',edgecolor='black')
ax.scatter(x=sorted(list(sumry.columns.values)),y=sumry.loc['95%'],s=120,color='white',edgecolor='black')

#add legend image
img = plt.imread("legend.jpg")
plt.figimage(img, 1900,900, zorder=1, alpha=1)

#next line is important, select a column that has no blanks or nans as the total items are counted.
assay['value']=assay['From']

vals=assay.groupby([g])['value'].count()
j=vals

ymin, ymax = ax.get_ylim()
xmin, xmax = ax.get_xlim()
#print ymax

#put n= values at top of plot
x=0
for i in range(len(j)):

    plt.text(x = x , y = ymax+0.2, s = "N=\n" +str(int(j[i])),horizontalalignment='center')
    #plt.text(x = x , y = 102.75, s = "n=",horizontalalignment='center')
    x+=1

#use the section below to adjust the y axis lable format to avoid default of 10^0 etc for log scale plots.
ylabels = ['{:.1f}'.format(y) for y in ax.get_yticks()]
ax.set_yticklabels(ylabels)

Which gives:


问:
React-Native how to use KeyboardAvoidingView
Both the header and the chat container move-up when I start typing some message.

I have tried to use KeyboardAvoidingView inside my view container, however, it did not work, I'm not sure if the KeyboardAvoidingView is the best solution to control the keyboard inside the view and not familiar with it.

Below is my code:

```<code>render() {
const { myName, user, nome, message } = this.props;
return (
  <View style={STYLES.main}>

    <Animatable.View
      style={STYLES.container}
      animation={FADEIN}
      easing='ease-in'
      duration={1000}
    >
      <RenderHeader3 press={() => Actions.detalhes()} hcolor={'#298CFF'} color={'#FFF'} text={nome} icon={null} isize={null} />

      <ScrollView contentContainerStyle={{ paddingHorizontal: 10, paddingTop: 5 }}>
        <KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior={null}
          keyboardVerticalOffset={60}
        >
          <ListView
            enableEmptySections
            dataSource={this.dataSource}
            renderRow={this.renderRow}
          />
        </KeyboardAvoidingView>
      </ScrollView>

      <View style={{ flexDirection: 'row', backgroundColor: '#1A1C27', padding: 10 }}>
        <View style={{ flex: 4 }}>
          <TextInput
            style={[STYLES.titleTxt, { color: '#000', backgroundColor: '#FFF', borderRadius: 40, paddingLeft: 13, paddingRight: 10 }]}
            multiline
            value={message}
            onChangeText={(texto) => this.props.modificaMensagem(texto)}
          />
        </View>
        <View style={{ justifyContent: 'center', alignItems: 'center', paddingLeft: 10 }}>
          <TouchableOpacity
            style={{
              height: 40,
              width: 40,
              borderRadius: 40,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#298CFF',
              paddingRight: 2
            }}
            activeOpacity={0.5}
            onPress={() => this.props.createChat(myName, user, nome, message)}
          >
            <CustomIcon
              name='paper-plane'
              size={25}
              color='#FFF'
            />
          </TouchableOpacity>
        </View>
      </View>

    </Animatable.View>

  </View>
);
</code>```

}
}

答:
make this changes

```<code><KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior="height"
          keyboardVerticalOffset={60}
        >

</code>```

source

Body:
Both the header and the chat container move-up when I start typing some message.

I have tried to use KeyboardAvoidingView inside my view container, however, it did not work, I'm not sure if the KeyboardAvoidingView is the best solution to control the keyboard inside the view and not familiar with it.

Below is my code:

render() {
const { myName, user, nome, message } = this.props;
return (
  <View style={STYLES.main}>

    <Animatable.View
      style={STYLES.container}
      animation={FADEIN}
      easing='ease-in'
      duration={1000}
    >
      <RenderHeader3 press={() => Actions.detalhes()} hcolor={'#298CFF'} color={'#FFF'} text={nome} icon={null} isize={null} />

      <ScrollView contentContainerStyle={{ paddingHorizontal: 10, paddingTop: 5 }}>
        <KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior={null}
          keyboardVerticalOffset={60}
        >
          <ListView
            enableEmptySections
            dataSource={this.dataSource}
            renderRow={this.renderRow}
          />
        </KeyboardAvoidingView>
      </ScrollView>

      <View style={{ flexDirection: 'row', backgroundColor: '#1A1C27', padding: 10 }}>
        <View style={{ flex: 4 }}>
          <TextInput
            style={[STYLES.titleTxt, { color: '#000', backgroundColor: '#FFF', borderRadius: 40, paddingLeft: 13, paddingRight: 10 }]}
            multiline
            value={message}
            onChangeText={(texto) => this.props.modificaMensagem(texto)}
          />
        </View>
        <View style={{ justifyContent: 'center', alignItems: 'center', paddingLeft: 10 }}>
          <TouchableOpacity
            style={{
              height: 40,
              width: 40,
              borderRadius: 40,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: '#298CFF',
              paddingRight: 2
            }}
            activeOpacity={0.5}
            onPress={() => this.props.createChat(myName, user, nome, message)}
          >
            <CustomIcon
              name='paper-plane'
              size={25}
              color='#FFF'
            />
          </TouchableOpacity>
        </View>
      </View>

    </Animatable.View>

  </View>
);

}
}

Body:
make this changes

<KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior="height"
          keyboardVerticalOffset={60}
        >

source


问:
Activity class does not exist (Error type 3)
I have a device nexus5x with android O and i develop an app in my laptop and also in another computer. But when i want to start the app in another computer after i have started it in my laptop i always get error described below.

```<code>Error while executing: am start -n "com.safetylink.android.safetylinkheartbeatapp/com.application.aware.safetylink.auth.SplashScreenActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.safetylink.android.safetylinkheartbeatapp/com.application.aware.safetylink.auth.SplashScreenActivity }
Error type 3
Error: Activity class {com.safetylink.android.safetylinkheartbeatapp/com.application.aware.safetylink.auth.SplashScreenActivity} does not exist.

Error while Launching activity
</code>```

It's a magic for me, because i don't have the same problem with another phones (it's just being reinstalled) and with emulator. Application works fine on them.

I think it's related to nexus5x settings, but i don't know exactly.
What should i do, to fix this problem?

P.S.: I have already tryed to clean, rebuild project, rename activity, invalidate cache and restart for several times, also disable instance run, but it doesn't work for me.

答: I have the same issue with my project. I resolve it by navigating to file and clicking on Invalidate Caches/Restart.

Body:
I have a device nexus5x with android O and i develop an app in my laptop and also in another computer. But when i want to start the app in another computer after i have started it in my laptop i always get error described below.

Error while executing: am start -n "com.safetylink.android.safetylinkheartbeatapp/com.application.aware.safetylink.auth.SplashScreenActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.safetylink.android.safetylinkheartbeatapp/com.application.aware.safetylink.auth.SplashScreenActivity }
Error type 3
Error: Activity class {com.safetylink.android.safetylinkheartbeatapp/com.application.aware.safetylink.auth.SplashScreenActivity} does not exist.

Error while Launching activity

It's a magic for me, because i don't have the same problem with another phones (it's just being reinstalled) and with emulator. Application works fine on them.

I think it's related to nexus5x settings, but i don't know exactly.
What should i do, to fix this problem?

P.S.: I have already tryed to clean, rebuild project, rename activity, invalidate cache and restart for several times, also disable instance run, but it doesn't work for me.


问:
Elegant and maintainable way of populating Tree structures in c#
I have a Tree.

```<code>class TreeNode {
    public TreeNode(string name, string description) {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public List<TreeNode> Children = new List<TreeNode>();
}
</code>```

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

Say for illustration purposes my tree has the following structure

```
Parent,desc
  Child 1, desc1
    Grandchild 1, desc1
  Child 2, desc2
```

How would you go about populating the tree in an elegant an maintainable way?

I find this code quite repetitious and error prone:

```<code>var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");

parent.Children.Add(child1);
parent.Children.Add(child2);

child1.Children.Add(grandchild1);
</code>```

EDIT

I ended up doing the DSL approach:

A demo test lives here.

The implementation is here.

It uses a builder and a simple DSL.

答:
You can write a "TreeBuilder" with a state to save some connections mess:

```<code>TreeBuilder builder = new TreeBuilder();

builder.AddNode("Parent", "desc"); // Adds a node, and sets the cursor to it
builder.AddLeaf("Child 1", "desc1"); // Adds a node and leaves the cursor at the Parent
builder.AddNode("Child 2", "desc2");
builder.AddLeaf("Grandchild 1", "desc1");
builder.Up(); // Moves the cursor to the parent
builder.AddNode("Child 3", "desc3");

root = builder.GetRoot()
</code>```

Another way is to invent a simple configuration file/string with some simple format.

Body:
I have a Tree.

class TreeNode {
    public TreeNode(string name, string description) {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public List<TreeNode> Children = new List<TreeNode>();
}

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

Say for illustration purposes my tree has the following structure

Parent,desc
  Child 1, desc1
    Grandchild 1, desc1
  Child 2, desc2

How would you go about populating the tree in an elegant an maintainable way?

I find this code quite repetitious and error prone:

var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");

parent.Children.Add(child1);
parent.Children.Add(child2);

child1.Children.Add(grandchild1);

EDIT

I ended up doing the DSL approach:

A demo test lives here.

The implementation is here.

It uses a builder and a simple DSL.

Body:
You can write a "TreeBuilder" with a state to save some connections mess:

TreeBuilder builder = new TreeBuilder();

builder.AddNode("Parent", "desc"); // Adds a node, and sets the cursor to it
builder.AddLeaf("Child 1", "desc1"); // Adds a node and leaves the cursor at the Parent
builder.AddNode("Child 2", "desc2");
builder.AddLeaf("Grandchild 1", "desc1");
builder.Up(); // Moves the cursor to the parent
builder.AddNode("Child 3", "desc3");

root = builder.GetRoot()

Another way is to invent a simple configuration file/string with some simple format.

OwnerDisplayName: Untrots

ContentLicense: CC BY-SA 2.5


问:
How to pass the 'function value' in api address of thingSpeak.. I am using Arduino and sim900 GSM
I want to upload rain sensor data to thingspeak using HTTP POST method, But while using "Api key= data to be sent .."
The sensor data is not being uploaded to server.. and also as it is in quotes so it is not taking as function may be....
How to solve this problem?? </p>

```<code>Serial.print("api_key=QI8G7PVTC2BVIREC&field1=TellWater()\\r\\n");
</code>```

答:
You need to capture the return value of the TellWater() in a variable.

Here I am assuming TellWater() return float. You need to convert it to string.

```<code>float water_value = TellWater();
String water_value_str;
water_value_str = String(f);
</code>```

After you convert the sensor data to string, you need to perform string concatenation to prepare final output string.

```<code>String output_string = "api_key=QI8G7PVTC2BVIREC&field1=" + water_value_str + "\r\n";
Serial.print(output_string);
</code>```

You should not escape back slash \ in \\r\\n. This will cause compiler to interpret the statement as character \ (0x5c) and character r (0x72) instead as \r (0x0D) (carriage-return). Similarly \\n will be interpreted as character \ (0x5c) and character n (0x6e) instead as \n (0x0A) (line-feed) causing your GSM module to wait for data as it has not received line-ending characters (\r\n).

Body:
I want to upload rain sensor data to thingspeak using HTTP POST method, But while using "Api key= data to be sent .."
The sensor data is not being uploaded to server.. and also as it is in quotes so it is not taking as function may be....
How to solve this problem??

Serial.print("api_key=QI8G7PVTC2BVIREC&field1=TellWater()\\r\\n");

Body:
You need to capture the return value of the TellWater() in a variable.

Here I am assuming TellWater() return float. You need to convert it to string.

float water_value = TellWater();
String water_value_str;
water_value_str = String(f);

After you convert the sensor data to string, you need to perform string concatenation to prepare final output string.

String output_string = "api_key=QI8G7PVTC2BVIREC&field1=" + water_value_str + "\r\n";
Serial.print(output_string);

You should not escape back slash \ in \\r\\n. This will cause compiler to interpret the statement as character \ (0x5c) and character r (0x72) instead as \r (0x0D) (carriage-return). Similarly \\n will be interpreted as character \ (0x5c) and character n (0x6e) instead as \n (0x0A) (line-feed) causing your GSM module to wait for data as it has not received line-ending characters (\r\n).


问:
Swift / how to use UITextView with dynamic height INSIDE UITableViewCell with dynamic height
I'm using the following code to have the UITableViewCell have a dynamic height:

```<code>tableView.estimatedRowHeight = 155
tableView.rowHeight = UITableViewAutomaticDimension
</code>```

And this code to have the UITextView change it's height based on the content.

```<code>extension NewUserTweetTableVC: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        let fixedWidth = textView.frame.size.width
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        textView.frame = newFrame
    }
}
</code>```

Once I change the text of the UITextView during runtime, the height of the UITextView changes, but the height of the UITableViewCell does not. How can I change that? Help is very appreciated.

答:
Update code in Swift 4.2

Credit: http://www.swiftdevcenter.com/the-dynamic-height-of-uitextview-inside-uitableviewcell-swift/

Create a Custom cell with name GrowingCell, add UITextView in the cell and create an Outlet of this. Register this cell in UITableView in your ViewController class.
Your ViewController:

```<code>import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let nib = UINib(nibName: "GrowingCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "GrowingCell")
        self.tableView.tableFooterView = UIView()
        self.tableView.dataSource = self
    }
}

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "GrowingCell", for: indexPath) as! GrowingCell
        cell.cellDelegate = self
        return cell
    }

}

extension ViewController: GrowingCellProtocol {
    // Update height of UITextView based on string height
    func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView) {
        let size = textView.bounds.size
        let newSize = tableView.sizeThatFits(CGSize(width: size.width,
                                                        height: CGFloat.greatestFiniteMagnitude))
        if size.height != newSize.height {
            UIView.setAnimationsEnabled(false)
            tableView?.beginUpdates()
            tableView?.endUpdates()
            UIView.setAnimationsEnabled(true)
            // Scoll up your textview if required
            if let thisIndexPath = tableView.indexPath(for: cell) {
                tableView.scrollToRow(at: thisIndexPath, at: .bottom, animated: false)
            }
        }
    }
}
</code>```

Now move to your Custom GrowingCell cell and add below code:

```<code>import UIKit

protocol GrowingCellProtocol: class {
    func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView)
}

class GrowingCell: UITableViewCell {

    weak var cellDelegate: GrowingCellProtocol?
    @IBOutlet weak var textView: UITextView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        textView.delegate = self
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
}

extension GrowingCell: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        if let deletate = cellDelegate {
            deletate.updateHeightOfRow(self, textView)
        }
    }
}
</code>```

For more detail: visit this full demo

Body:
I'm using the following code to have the UITableViewCell have a dynamic height:

tableView.estimatedRowHeight = 155
tableView.rowHeight = UITableViewAutomaticDimension

And this code to have the UITextView change it's height based on the content.

extension NewUserTweetTableVC: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        let fixedWidth = textView.frame.size.width
        textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max))
        var newFrame = textView.frame
        newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
        textView.frame = newFrame
    }
}

Once I change the text of the UITextView during runtime, the height of the UITextView changes, but the height of the UITableViewCell does not. How can I change that? Help is very appreciated.

Body:
Update code in Swift 4.2

Credit: http://www.swiftdevcenter.com/the-dynamic-height-of-uitextview-inside-uitableviewcell-swift/

Create a Custom cell with name GrowingCell, add UITextView in the cell and create an Outlet of this. Register this cell in UITableView in your ViewController class.
Your ViewController:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let nib = UINib(nibName: "GrowingCell", bundle: nil)
        self.tableView.register(nib, forCellReuseIdentifier: "GrowingCell")
        self.tableView.tableFooterView = UIView()
        self.tableView.dataSource = self
    }
}

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "GrowingCell", for: indexPath) as! GrowingCell
        cell.cellDelegate = self
        return cell
    }

}

extension ViewController: GrowingCellProtocol {
    // Update height of UITextView based on string height
    func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView) {
        let size = textView.bounds.size
        let newSize = tableView.sizeThatFits(CGSize(width: size.width,
                                                        height: CGFloat.greatestFiniteMagnitude))
        if size.height != newSize.height {
            UIView.setAnimationsEnabled(false)
            tableView?.beginUpdates()
            tableView?.endUpdates()
            UIView.setAnimationsEnabled(true)
            // Scoll up your textview if required
            if let thisIndexPath = tableView.indexPath(for: cell) {
                tableView.scrollToRow(at: thisIndexPath, at: .bottom, animated: false)
            }
        }
    }
}

Now move to your Custom GrowingCell cell and add below code:

import UIKit

protocol GrowingCellProtocol: class {
    func updateHeightOfRow(_ cell: GrowingCell, _ textView: UITextView)
}

class GrowingCell: UITableViewCell {

    weak var cellDelegate: GrowingCellProtocol?
    @IBOutlet weak var textView: UITextView!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        textView.delegate = self
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        // Configure the view for the selected state
    }
}

extension GrowingCell: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {
        if let deletate = cellDelegate {
            deletate.updateHeightOfRow(self, textView)
        }
    }
}

For more detail: visit this full demo


答:
KeyboardAvoidingView has 3 types of behavior enum('height','position','padding') but you set it to null in your code.
  Secondly you have not added KeyboardAvoidingView in with TextInput component

```<code><KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior={'height'}
          keyboardVerticalOffset={60}
        >
</code>```

Title: React-Native how to use KeyboardAvoidingView

Body:
KeyboardAvoidingView has 3 types of behavior enum('height','position','padding') but you set it to null in your code.
  Secondly you have not added KeyboardAvoidingView in with TextInput component

<KeyboardAvoidingView
          style={{ flex: 1 }}
          behavior={'height'}
          keyboardVerticalOffset={60}
        >


问:
Find rectangle vertices given its coordinates, width and height
I have a rectangle, that could be rotated. At every rotation, I need to to know its new top, left, right and bottom vertices.

I've tried to loop through the new rectangle coordinates, but I want to calculate vertices without a loop to reduce execution time

At first, I calculate new rotated coordinates and then I find new vertices.

```<code>rotatedRectCorners(element, center, angle) {
    const theta = (Math.PI / 180) * angle
    const ox = center.x
    const oy = center.y
    const xAx = Math.cos(theta)  // x axis x
    const xAy = Math.sin(theta)  // x axis y
    const x = element.left - ox  // move rectangle onto origin
    const y = element.top - oy

    return {
        topLeft: {
            x: x * xAx - y * xAy + ox,   // Get the top left rotated position
            y: x * xAy + y * xAx + oy
        },
        topRight: {
            x: (x + element.width) * xAx - y * xAy + ox,   // Get the top right rotated position
            y: (x + element.width) * xAy + y * xAx + oy
        },
        bottomRight: {
            x: (x + element.width) * xAx - (y + element.height) * xAy + ox,   // Get the bottom right rotated position
            y: (x + element.width) * xAy + (y + element.height) * xAx + oy
        },
        bottomLeft: {
            x: x * xAx - (y + element.height) * xAy + ox,   // Get the bottom left rotated position
            y: x * xAy + (y + element.height) * xAx + oy
        }
    }
}

rectVertices(element, center, angle) {
    const corners = rotatedRectCorners(element, center, angle)
    const vertices = {
        top: {x: 0, y: 0},
        left: {x: 0, y: 0},
        right: {x: 0, y: 0},
        bottom: {x: 0, y: 0}
    }
    let maxX = null
    let minX = null
    let minY = null
    let maxY = null
    each(corners, (corner) => {
        if (maxX === null) {
            maxX = corner.x
            vertices.right = corner
        }
        if (minX === null) {
            minX = corner.x
            vertices.left = corner
        }
        if (minY === null) {
            minY = corner.y
            vertices.top = corner
        }
        if (maxY === null) {
            maxY = corner.y
            vertices.bottom = corner
        }
        if (corner.y > maxY) {
            maxY = corner.y
            vertices.bottom = corner
        }
        if (corner.x > maxX) {
            maxX = corner.x
            vertices.right = corner
        }
        if (corner.x < minX) {
            minX = corner.x
            vertices.left = corner
        }
        if (corner.y < minY) {
            minY = corner.y
            vertices.top = corner
        }
    })

    return vertices
}

</code>```

答:
Let number rectangle vertices from top left corner in clockwise direction. We can see that V[0] is the leftmost vertex in angle range 0..Pi/2 (90 degrees, angle in CCW direction), V[1] becomes the leftmost one in angle range Pi/2..Pi and so on.

So we can reconsile two arrays cyclically corresponding to rotation angle

```<code>V[0]    V[1]    V[2]    V[3]
           <==>                      //small angle
left    top     right  bottom

V[2]    V[3]     V[0]    V[1]
           <==>                     //angle in range 180..270 (Pi..3Pi/2)
left    top     right  bottom

left_index = angle / 90   //integer division if possible in JS
top_index = (1 + angle / 90) % 4
right_index = (2 + angle / 90) % 4
bottom_index = (3 + angle / 90) % 4
</code>```

Not that in any case you have to calculate vertices coordinates (much more time)

Body:
I have a rectangle, that could be rotated. At every rotation, I need to to know its new top, left, right and bottom vertices.

I've tried to loop through the new rectangle coordinates, but I want to calculate vertices without a loop to reduce execution time

At first, I calculate new rotated coordinates and then I find new vertices.

rotatedRectCorners(element, center, angle) {
    const theta = (Math.PI / 180) * angle
    const ox = center.x
    const oy = center.y
    const xAx = Math.cos(theta)  // x axis x
    const xAy = Math.sin(theta)  // x axis y
    const x = element.left - ox  // move rectangle onto origin
    const y = element.top - oy

    return {
        topLeft: {
            x: x * xAx - y * xAy + ox,   // Get the top left rotated position
            y: x * xAy + y * xAx + oy
        },
        topRight: {
            x: (x + element.width) * xAx - y * xAy + ox,   // Get the top right rotated position
            y: (x + element.width) * xAy + y * xAx + oy
        },
        bottomRight: {
            x: (x + element.width) * xAx - (y + element.height) * xAy + ox,   // Get the bottom right rotated position
            y: (x + element.width) * xAy + (y + element.height) * xAx + oy
        },
        bottomLeft: {
            x: x * xAx - (y + element.height) * xAy + ox,   // Get the bottom left rotated position
            y: x * xAy + (y + element.height) * xAx + oy
        }
    }
}

rectVertices(element, center, angle) {
    const corners = rotatedRectCorners(element, center, angle)
    const vertices = {
        top: {x: 0, y: 0},
        left: {x: 0, y: 0},
        right: {x: 0, y: 0},
        bottom: {x: 0, y: 0}
    }
    let maxX = null
    let minX = null
    let minY = null
    let maxY = null
    each(corners, (corner) => {
        if (maxX === null) {
            maxX = corner.x
            vertices.right = corner
        }
        if (minX === null) {
            minX = corner.x
            vertices.left = corner
        }
        if (minY === null) {
            minY = corner.y
            vertices.top = corner
        }
        if (maxY === null) {
            maxY = corner.y
            vertices.bottom = corner
        }
        if (corner.y > maxY) {
            maxY = corner.y
            vertices.bottom = corner
        }
        if (corner.x > maxX) {
            maxX = corner.x
            vertices.right = corner
        }
        if (corner.x < minX) {
            minX = corner.x
            vertices.left = corner
        }
        if (corner.y < minY) {
            minY = corner.y
            vertices.top = corner
        }
    })

    return vertices
}

Body:
Let number rectangle vertices from top left corner in clockwise direction. We can see that V[0] is the leftmost vertex in angle range 0..Pi/2 (90 degrees, angle in CCW direction), V[1] becomes the leftmost one in angle range Pi/2..Pi and so on.

So we can reconsile two arrays cyclically corresponding to rotation angle

V[0]    V[1]    V[2]    V[3]
           <==>                      //small angle
left    top     right  bottom

V[2]    V[3]     V[0]    V[1]
           <==>                     //angle in range 180..270 (Pi..3Pi/2)
left    top     right  bottom

left_index = angle / 90   //integer division if possible in JS
top_index = (1 + angle / 90) % 4
right_index = (2 + angle / 90) % 4
bottom_index = (3 + angle / 90) % 4

Not that in any case you have to calculate vertices coordinates (much more time)


问:
Npm error cannot find module
While running npm command I get the error

Error: Cannot find module 'C:\Windows\System32\node_modules\npm\bin\npm-cli.js'.
I tried uninstalling and installing nodejs but with no luck. Also I tried configuring the env vars

答:
I'm not entirely sure about this, but I dont remember having nodejs/npm installed in Windows directory. It should be in your Appdata somewhere. Your install Paths maybe somehow corrupted

But here is a possible solution:
Go here:

Install it and run the following commands:

```<code>nvm list
nvm install [version]
</code>```

for example:

```<code>nvm install v10.15.3
</code>```

The Command should automatically select the installed version as default.
For further information check their Github Readme.

If they don't work right off, be sure to restart the Version Manager OR be sure to follow the instructions led out by the Github Readme.

Version Manager have one big benefit: The Community keeps them updated and because they use different Path architectures they can be installed at places where they weren't originally meant to be from the original installer which lead to a whole different outcome for you because they probably will not install directly into System32.

Other Node Version Manager you could check out (should all be Windows):

https://github.com/hakobera/nvmw

https://github.com/nullivex/nodist

Hope it helps!

Title: Npm error cannot find module

Body:
I'm not entirely sure about this, but I dont remember having nodejs/npm installed in Windows directory. It should be in your Appdata somewhere. Your install Paths maybe somehow corrupted

But here is a possible solution:
Go here:

Install it and run the following commands:

nvm list
nvm install [version]

for example:

nvm install v10.15.3

The Command should automatically select the installed version as default.
For further information check their Github Readme.

If they don't work right off, be sure to restart the Version Manager OR be sure to follow the instructions led out by the Github Readme.

Version Manager have one big benefit: The Community keeps them updated and because they use different Path architectures they can be installed at places where they weren't originally meant to be from the original installer which lead to a whole different outcome for you because they probably will not install directly into System32.

Other Node Version Manager you could check out (should all be Windows):

https://github.com/hakobera/nvmw

https://github.com/nullivex/nodist

Hope it helps!


问:
If an event is fired during throttleTime's timeout, replay last event after timeout completes and begin timeout again
What I'd like to see is this output:

```<code>|---0--0--0-----0---------------> Events
|---0-------0-------0-----------> Output
</code>```

I supply a duration, the stream allows the first event through, waits the duration amount. If an event was triggered during the timeout period, emit and start the timeout again.

The values don't matter in my case, only knowing events happened.

How would I achieve this with RXJS? I started with throttleTime, but throttleTime doesn't emit the trailing event when its timeout finishes.

```<code>subject
    .pipe(
        throttleTime(5000)
    )
    .subscribe(
        event => action()
    )
</code>```

答:
Check out the docs for throttleTime. You can pass in an optional config and specify leading / trailing behavior. What you ran into was this:

config:

```<code>Optional. Default is defaultThrottleConfig.

a configuration object to define leading and trailing behavior. Defaults to {
leading: true, trailing: false }.
</code>```

Body:
What I'd like to see is this output:

|---0--0--0-----0---------------> Events
|---0-------0-------0-----------> Output

I supply a duration, the stream allows the first event through, waits the duration amount. If an event was triggered during the timeout period, emit and start the timeout again.

The values don't matter in my case, only knowing events happened.

How would I achieve this with RXJS? I started with throttleTime, but throttleTime doesn't emit the trailing event when its timeout finishes.

subject
    .pipe(
        throttleTime(5000)
    )
    .subscribe(
        event => action()
    )

Body:
Check out the docs for throttleTime. You can pass in an optional config and specify leading / trailing behavior. What you ran into was this:

config:

Optional. Default is defaultThrottleConfig.

a configuration object to define leading and trailing behavior. Defaults to {
leading: true, trailing: false }.


问:
How To Use Sweet alert
This Is My HTML Code
I Have Two Input Button That I Want To Show Sweet Alert When a user Clicks on any Button

```<code><tr class="examples odd" id="UserId_1" role="row">
   <td class="sorting_1">1</td>
   <td>admin</td><td>Mohammad</td>
   <td>Farzin</td><td class="warning"><input type="button"
   value="Delete" class="sweet-5" id="btn_Delete1"></td>
</tr>
<tr class="examples even" id="UserId_5" role="row">
   <td class="sorting_1">2</td>
   <td>11</td><td>11</td>
   <td>11</td><td class="warning"><input type="button" value="Delete" class="sweet-5"
   id="btn_Delete5"></td>
</tr>
</code>```

Script

```<code>$(document).ready(function () {
document.querySelector('td.warning input').onclick = function () {
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: 'btn-danger',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: "No, cancel plx!",
        closeOnConfirm: false,
        closeOnCancel: false
        },
     function (isConfirm) {
        if (isConfirm) {
            swal("Deleted!", "Your imaginary file has been deleted!", "success");
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error");
            }
        });
    };

});
</code>```

Only The First Input Button Shows Sweet Alert, but
when I click the second button nothing happens

答:
If you want sweet alert on click of any button then change your code like below:</p>

```<code>$(document).ready(function(){
  $(document).on('click', 'button', function(){
    Swal.fire({
       type: 'success',
       title: 'Your work has been done',
       showConfirmButton: false,
       timer: 1500
    })
  });
});
</code>```

Title: How To Use Sweet alert

Body:
This Is My HTML Code
I Have Two Input Button That I Want To Show Sweet Alert When a user Clicks on any Button

   1
   admin	Mohammad
   Farzin	<input type="button"
   value="Delete" class="sweet-5" id="btn_Delete1">

   2
   11	11
   11	<input type="button" value="Delete" class="sweet-5"
   id="btn_Delete5">

Script

$(document).ready(function () {
document.querySelector('td.warning input').onclick = function () {
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonClass: 'btn-danger',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: "No, cancel plx!",
        closeOnConfirm: false,
        closeOnCancel: false
        },
     function (isConfirm) {
        if (isConfirm) {
            swal("Deleted!", "Your imaginary file has been deleted!", "success");
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error");
            }
        });
    };

});

Only The First Input Button Shows Sweet Alert, but
when I click the second button nothing happens

Body:
If you want sweet alert on click of any button then change your code like below:

$(document).ready(function(){
  $(document).on('click', 'button', function(){
    Swal.fire({
       type: 'success',
       title: 'Your work has been done',
       showConfirmButton: false,
       timer: 1500
    })
  });
});