问:
Could not parse text error in sheet from double quotes in attachment
I am running an app script in sheets, which usually brings in an attachment from Gmail into google sheets. It works most of the time, but when data contains double quotes it is generating a parse error

my source data is thousands of rows like this:

```<code>",05/02/2019,3:13,151:22,5:30,08:11,Enroute,C000003251,219688X01232019,BIN11,,Item1,08:11,0:05,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:17,OnSite,C000003251,219688X01232019,BIN11,,Item1,,,08:17,0:16,0:30
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:34,Complete,C000003251,219688X01232019,BIN11,,Item1,,,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:42,Enroute,C000003252,219689X01232019,BIN11,,Item1,08:42,0:00,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:42,OnSite,C000003252,219689X01232019,BIN11,,Item1,,,08:42,0:14,0:30
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:56,Complete,C000003252,219689X01232019,BIN11,,Item1,,,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:57,Enroute,C000003253,219690X01232019,BIN11,,Item1,08:57,0:05,,,0:00
</code>```

```<code>  attachment.setContentTypeFromExtension();
  if (attachment.getContentType() === "text/csv") {

    var sheet =
    SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Month1");
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

    sheet.clearContents().clearFormats();
    sheet.getRange(1, 1, csvData.length,

csvData[0].length).setValues(csvData);
}
</code>```

I am getting this error: "Could not parse text" I can't seem to figure out how to either ignore or remove the double quotes in the source data

thanks in advance!

答:
you can use either of these formulas to remove all double quotes from your dataset

```<code>=ARRAYFORMULA(REGEXREPLACE(A1:A, """", ""))
</code>```

```<code>=ARRAYFORMULA(SUBSTITUTE(A1:A, """", ""))
</code>```

or if that is the option you can use CTRL + H and remove them entirely.

Body:
I am running an app script in sheets, which usually brings in an attachment from Gmail into google sheets. It works most of the time, but when data contains double quotes it is generating a parse error

my source data is thousands of rows like this:

",05/02/2019,3:13,151:22,5:30,08:11,Enroute,C000003251,219688X01232019,BIN11,,Item1,08:11,0:05,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:17,OnSite,C000003251,219688X01232019,BIN11,,Item1,,,08:17,0:16,0:30
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:34,Complete,C000003251,219688X01232019,BIN11,,Item1,,,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:42,Enroute,C000003252,219689X01232019,BIN11,,Item1,08:42,0:00,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:42,OnSite,C000003252,219689X01232019,BIN11,,Item1,,,08:42,0:14,0:30
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:56,Complete,C000003252,219689X01232019,BIN11,,Item1,,,,,0:00
Worker2,34:51,869:25,110:00,"Completed: 168
Suspended: 43
Skipped: 41
",05/02/2019,3:13,151:22,5:30,08:57,Enroute,C000003253,219690X01232019,BIN11,,Item1,08:57,0:05,,,0:00

  attachment.setContentTypeFromExtension();
  if (attachment.getContentType() === "text/csv") {

    var sheet =
    SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Month1");
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

    sheet.clearContents().clearFormats();
    sheet.getRange(1, 1, csvData.length,

csvData[0].length).setValues(csvData);
}

I am getting this error: "Could not parse text" I can't seem to figure out how to either ignore or remove the double quotes in the source data

thanks in advance!

Body:
you can use either of these formulas to remove all double quotes from your dataset

=ARRAYFORMULA(REGEXREPLACE(A1:A, """", ""))

=ARRAYFORMULA(SUBSTITUTE(A1:A, """", ""))

or if that is the option you can use CTRL + H and remove them entirely.


来源: stackexchange

问:
How to ping a list of ip and rank result by average time (printing ip and avg time only) timeout at the bottom
I have an ip list file: iplistALL.txt

I want to ping all ip in that list and output a file nemed: iplistAVGT.txt

Inside iplistAVGT.txt I want all pinged ip listed along with average ping only, each on one line in order of average time from lower to higher and those who timed out at the end.

Using bash please.

So far I do this:

for i in `cat iplistALL.txt` ; do ping -c1 $i 2>&1 | tee >> ping-output.txt; done

But I get too many info I just want the ip and time on one line. also for some reason the last one gets truncated. And they are not listed in order by time

答:
Let's say your ping-output.txt looks like this, for example:

```<code>PING 10.0.0.1 (10.0.0.1): 56 data bytes
64 bytes from 10.0.0.1: icmp_seq=0 ttl=49 time=110.183 ms
--- 10.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 110.183/110.183/110.183/0.000 ms
PING 10.0.0.2 (10.0.0.2): 56 data bytes
64 bytes from 10.0.0.2: icmp_seq=0 ttl=48 time=106.966 ms

--- 10.0.0.2 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 106.966/106.966/106.966/0.000 ms
</code>```

You can use awk to pick out the IP and avg round trip time as follows:

```<code>awk '
/ping statistics/ {
  ip=$2
}
 /round-trip/ {
  split( $4, array, "/" )
  print ip,array[2]
}' ping-output.txt
</code>```

to yield:

```<code>10.0.0.1 110.183
10.0.0.2 106.966
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let's say your ping-output.txt looks like this, for example:

PING 10.0.0.1 (10.0.0.1): 56 data bytes
64 bytes from 10.0.0.1: icmp_seq=0 ttl=49 time=110.183 ms
--- 10.0.0.1 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 110.183/110.183/110.183/0.000 ms
PING 10.0.0.2 (10.0.0.2): 56 data bytes
64 bytes from 10.0.0.2: icmp_seq=0 ttl=48 time=106.966 ms

--- 10.0.0.2 ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 106.966/106.966/106.966/0.000 ms

You can use awk to pick out the IP and avg round trip time as follows:

awk '
/ping statistics/ {
  ip=$2
}
 /round-trip/ {
  split( $4, array, "/" )
  print ip,array[2]
}' ping-output.txt

to yield:

10.0.0.1 110.183
10.0.0.2 106.966


问:
Create partial-screen UIPageViewController programmatically
I am trying to create a scrolling pageviewcontroller that only takes up part of my screen. I have successfully done this using Storyboard and a ContainerView object, but I now need to replicate the functionality creating the project programmatically.

It seems that ContainerView is not something that I can create using swift, so I tried to do this using a UIView to act as a container that I tried to do addSubview with a UIPageViewController, but I get the error cannot convert value of type UIPageViewController to expected argument type UIView.

I assume that I must be missing something simple here, since as I said, I've accomplished this with Storyboard/Interface Builder, but how can I get similar functionality while building programmatically with Swift?

答:
UIContainerView is really just a Storyboard convenience. It adds a normal UIView and allows you to connect a View Controller as its "embedded content."

But, under the hood, it is doing exactly what you can do from code:

add a UIView to your main view that you will use as the "container"

instantiate your page view controller

use addChild(_ childController: UIViewController) to add that page view controller as a child controller

add the child VC's view to your "container" view

Here is a complete example:

```<code>//
//  Created by Don Mag on 5/31/19.
//

import UIKit

// simple example view controller
// has a label 90% of the width, centered X and Y
class ExampleViewController: UIViewController {

    let theLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .white
        v.textAlignment = .center
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(theLabel)
        NSLayoutConstraint.activate([
            theLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            theLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            theLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.9),
            ])

    }

}

// example Page View Controller
class MyPageViewController: UIPageViewController {

    let colors: [UIColor] = [
        .red,
        .green,
        .blue,
        .cyan,
        .yellow,
        .orange
    ]

    var pages: [UIViewController] = [UIViewController]()

    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        dataSource = self
        delegate = nil

        // instantiate "pages"
        for i in 0..<colors.count {
            let vc = ExampleViewController()
            vc.theLabel.text = "Page: \(i)"
            vc.view.backgroundColor = colors[i]
            pages.append(vc)
        }

        setViewControllers([pages[0]], direction: .forward, animated: false, completion: nil)
    }

}

// typical Page View Controller Data Source
extension MyPageViewController: UIPageViewControllerDataSource {
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

        guard let viewControllerIndex = pages.index(of: viewController) else { return nil }

        let previousIndex = viewControllerIndex - 1

        guard previousIndex >= 0 else { return pages.last }

        guard pages.count > previousIndex else { return nil }

        return pages[previousIndex]
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = pages.index(of: viewController) else { return nil }

        let nextIndex = viewControllerIndex + 1

        guard nextIndex < pages.count else { return pages.first }

        guard pages.count > nextIndex else { return nil }

        return pages[nextIndex]
    }
}

// typical Page View Controller Delegate
extension MyPageViewController: UIPageViewControllerDelegate {

    // if you do NOT want the built-in PageControl (the "dots"), comment-out these funcs

    func presentationCount(for pageViewController: UIPageViewController) -> Int {
        return pages.count
    }

    func presentationIndex(for pageViewController: UIPageViewController) -> Int {

        guard let firstVC = pageViewController.viewControllers?.first else {
            return 0
        }
        guard let firstVCIndex = pages.index(of: firstVC) else {
            return 0
        }

        return firstVCIndex
    }
}

class MyTestViewController: UIViewController {

    let myContainerView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .gray
        return v
    }()

    var thePageVC: MyPageViewController!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add myContainerView
        view.addSubview(myContainerView)

        // constrain it - here I am setting it to
        //  40-pts top, leading and trailing
        //  and 200-pts height
        NSLayoutConstraint.activate([
            myContainerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
            myContainerView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
            myContainerView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
            myContainerView.heightAnchor.constraint(equalToConstant: 200.0),
            ])

        // instantiate MyPageViewController and add it as a Child View Controller
        thePageVC = MyPageViewController()
        addChild(thePageVC)

        // we need to re-size the page view controller's view to fit our container view
        thePageVC.view.translatesAutoresizingMaskIntoConstraints = false

        // add the page VC's view to our container view
        myContainerView.addSubview(thePageVC.view)

        // constrain it to all 4 sides
        NSLayoutConstraint.activate([
            thePageVC.view.topAnchor.constraint(equalTo: myContainerView.topAnchor, constant: 0.0),
            thePageVC.view.bottomAnchor.constraint(equalTo: myContainerView.bottomAnchor, constant: 0.0),
            thePageVC.view.leadingAnchor.constraint(equalTo: myContainerView.leadingAnchor, constant: 0.0),
            thePageVC.view.trailingAnchor.constraint(equalTo: myContainerView.trailingAnchor, constant: 0.0),
            ])

        thePageVC.didMove(toParent: self)
    }

}
</code>```

Result:

Body:
UIContainerView is really just a Storyboard convenience. It adds a normal UIView and allows you to connect a View Controller as its "embedded content."

But, under the hood, it is doing exactly what you can do from code:

add a UIView to your main view that you will use as the "container"

instantiate your page view controller

use addChild(_ childController: UIViewController) to add that page view controller as a child controller

add the child VC's view to your "container" view

Here is a complete example:

//
//  Created by Don Mag on 5/31/19.
//

import UIKit

// simple example view controller
// has a label 90% of the width, centered X and Y
class ExampleViewController: UIViewController {

    let theLabel: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .white
        v.textAlignment = .center
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(theLabel)
        NSLayoutConstraint.activate([
            theLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            theLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
            theLabel.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.9),
            ])

    }

}

// example Page View Controller
class MyPageViewController: UIPageViewController {

    let colors: [UIColor] = [
        .red,
        .green,
        .blue,
        .cyan,
        .yellow,
        .orange
    ]

    var pages: [UIViewController] = [UIViewController]()

    override init(transitionStyle style: UIPageViewController.TransitionStyle, navigationOrientation: UIPageViewController.NavigationOrientation, options: [UIPageViewController.OptionsKey : Any]? = nil) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        dataSource = self
        delegate = nil

        // instantiate "pages"
        for i in 0..<colors.count {
            let vc = ExampleViewController()
            vc.theLabel.text = "Page: \(i)"
            vc.view.backgroundColor = colors[i]
            pages.append(vc)
        }

        setViewControllers([pages[0]], direction: .forward, animated: false, completion: nil)
    }

}

// typical Page View Controller Data Source
extension MyPageViewController: UIPageViewControllerDataSource {
    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

        guard let viewControllerIndex = pages.index(of: viewController) else { return nil }

        let previousIndex = viewControllerIndex - 1

        guard previousIndex >= 0 else { return pages.last }

        guard pages.count > previousIndex else { return nil }

        return pages[previousIndex]
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let viewControllerIndex = pages.index(of: viewController) else { return nil }

        let nextIndex = viewControllerIndex + 1

        guard nextIndex < pages.count else { return pages.first }

        guard pages.count > nextIndex else { return nil }

        return pages[nextIndex]
    }
}

// typical Page View Controller Delegate
extension MyPageViewController: UIPageViewControllerDelegate {

    // if you do NOT want the built-in PageControl (the "dots"), comment-out these funcs

    func presentationCount(for pageViewController: UIPageViewController) -> Int {
        return pages.count
    }

    func presentationIndex(for pageViewController: UIPageViewController) -> Int {

        guard let firstVC = pageViewController.viewControllers?.first else {
            return 0
        }
        guard let firstVCIndex = pages.index(of: firstVC) else {
            return 0
        }

        return firstVCIndex
    }
}

class MyTestViewController: UIViewController {

    let myContainerView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .gray
        return v
    }()

    var thePageVC: MyPageViewController!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add myContainerView
        view.addSubview(myContainerView)

        // constrain it - here I am setting it to
        //  40-pts top, leading and trailing
        //  and 200-pts height
        NSLayoutConstraint.activate([
            myContainerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 40.0),
            myContainerView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 40.0),
            myContainerView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -40.0),
            myContainerView.heightAnchor.constraint(equalToConstant: 200.0),
            ])

        // instantiate MyPageViewController and add it as a Child View Controller
        thePageVC = MyPageViewController()
        addChild(thePageVC)

        // we need to re-size the page view controller's view to fit our container view
        thePageVC.view.translatesAutoresizingMaskIntoConstraints = false

        // add the page VC's view to our container view
        myContainerView.addSubview(thePageVC.view)

        // constrain it to all 4 sides
        NSLayoutConstraint.activate([
            thePageVC.view.topAnchor.constraint(equalTo: myContainerView.topAnchor, constant: 0.0),
            thePageVC.view.bottomAnchor.constraint(equalTo: myContainerView.bottomAnchor, constant: 0.0),
            thePageVC.view.leadingAnchor.constraint(equalTo: myContainerView.leadingAnchor, constant: 0.0),
            thePageVC.view.trailingAnchor.constraint(equalTo: myContainerView.trailingAnchor, constant: 0.0),
            ])

        thePageVC.didMove(toParent: self)
    }

}

Result:


问:
How to stop my set interval after a few tries?
I am trying to stop my set interval function to stop after sending the information to my Iframe but clearInterval() isnt actually working.

i ALSO TRIED TO USE

Here's the code:

```

答:
I am not giving you the direct answer, its an approach</p>

```<code>mounted() {
    let tries = 3; // suppose you want to stop after 3 tries
    let interval = setInterval(() => {
        if (!tries--) {
            clearInterval(interval);
        } else {
           // TODO: your stuff
        }
    }, 1000); // interval for 1000 milisec
}
</code>```

Body:
I am not giving you the direct answer, its an approach

mounted() {
    let tries = 3; // suppose you want to stop after 3 tries
    let interval = setInterval(() => {
        if (!tries--) {
            clearInterval(interval);
        } else {
           // TODO: your stuff
        }
    }, 1000); // interval for 1000 milisec
}


问:
How to implement circuit pattern in aws lambda
I am implementing an HTTP client in aws lambda. Client will call third party microservice endpoint and that could be down. I want to implement a circuit breaker pattern for obvious advantages of the pattern.

I searched on the net and found one blog: https://www.jeremydaly.com/serverless-microservice-patterns-for-aws/

According to blog, we can maintain state in Elasticache or dynamoDB. But am not able to visualize the implementation. Can someone point me to the right direction? If the implementation is in JAVA that will be awesome.

答:
you could try using Amazon SQS deadletter queue to simulate a circuit breaker pattern. With Lamda you can specify the dead letter queue then before you make your next call you can check if there is a message in the queue before making another call.

List<Message> messages = sqs.receiveMessage(deadLetterQueueUrl).getMessages();
if (messages.Count > 0) return response;
```


问:
Custom sort order of jira workflow statuses in a filter using JQL
I know you can change the order statuses are displayed by admin > issues > statuses and sort order but I'd prefer to order the results in my jql with certain statuses at the top and a specific order.

Is it possible to order how statuses appear in a query using JQL.

For example:

if you have the following status available:

review,

backlog,

in development,

testing,

and Done

But you don't want to order them alphabetically can you define a customer order?

For example a JQL query for the custom order might be
    ORDER BY Status ("review","backlog","in development").

In this case the statuses would show from top to bottom on the Y axis in this order ("review","backlog","in development")

答:
In theory yes, you can make custom orders.  I'm struggling to make it actually work though.

https://confluence.atlassian.com/jirakb/how-to-re-order-statuses-675385085.html

But your question indicates you already know about this feature.  So I am not sure what you really want.

ContentLicense: CC BY-SA 3.0


问:
Accessing a variable in another object of the same class
I'm trying to access an array in the object "other," but I can't figure out how to access the variable. This is what I have so far:

```<code>public void union(DataSet other)
{
  DataSet temp = new newdataexp();
  temp = other;
}
</code>```

I haven't been able to figure out how to access the variable, even when I create a method in the class that returns the variable and then trying to call it from this method union.

I have this method, and am trying to do: String[][] temp = other.getdata(), but the compiler says that it cannot find symbol: method getdata().

public String[][] getdata()
{

return filedata;

}

答:
replace datatype with String, int, etc for whtever the method returns.</p>

```<code>datatype mynewdata = (datatype)other.getMeMyArray();
</code>```

Body:
I'm trying to access an array in the object "other," but I can't figure out how to access the variable. This is what I have so far:

public void union(DataSet other)
{
  DataSet temp = new newdataexp();
  temp = other;
}

I haven't been able to figure out how to access the variable, even when I create a method in the class that returns the variable and then trying to call it from this method union.

I have this method, and am trying to do: String[][] temp = other.getdata(), but the compiler says that it cannot find symbol: method getdata().

public String[][] getdata()
{

return filedata;

}

Body:
replace datatype with String, int, etc for whtever the method returns.

datatype mynewdata = (datatype)other.getMeMyArray();


问:
Memory game question (organizing the cards to 4x4+on click the game restarts)
I'm trying to implement a memory game. I'm almost done with it, but there are 2 parts that I need help with.
1. I can't figure out how to show my 16 cards in a 4x4 way. (probably something small, but hey i'm a noob)
2. I need a new game button, that resets the cards.

I have not really tried anything, I would like to get help and understand it while i'm implementing the fix.

```<code>  handleClick(name,index){
    if(this.state.openedFrameworks.length === 2){
      setTimeout(() => {
        this.check()
      },750)
    }else {
      let framework = {
        name,
        index
      }
      let finalizedFrameworks = this.state.finalizedFrameworks
      let frameworks = this.state.openedFrameworks
      finalizedFrameworks[index].close = false
      frameworks.push(framework)
      this.setState({
        openedFrameworks: frameworks,
        finalizedFrameworks: finalizedFrameworks
      })
      if(this.state.openedFrameworks.length === 2){
        setTimeout(() => {
          this.check()
        },750)
      }
    }
  }
  check(){
    let finalizedFrameworks = this.state.finalizedFrameworks
    if((this.state.openedFrameworks[0].name === this.state.openedFrameworks[1].name) && (this.state.openedFrameworks[0].index !== this.state.openedFrameworks[1].index)){
      finalizedFrameworks[this.state.openedFrameworks[0].index].complete = true
      finalizedFrameworks[this.state.openedFrameworks[1].index].complete = true
    }else {
      finalizedFrameworks[this.state.openedFrameworks[0].index].close = true
      finalizedFrameworks[this.state.openedFrameworks[1].index].close = true
    }
    this.setState({
      finalizedFrameworks,
      openedFrameworks: []
    })
  }
  start(){
    let finalizedFrameworks = [];
    this.state.duplicatedFrameworks = this.state.frameworks.concat(this.state.frameworks)
    this.state.randomizedFrameworks = this.shuffle(this.state.duplicatedFrameworks)
    this.state.randomizedFrameworks.map((name,index) => {
      finalizedFrameworks.push({
        name,
        close: true,
        complete: false,
        fail: false
      })
    })
    this.state.finalizedFrameworks = finalizedFrameworks
  }
  shuffle(array){
    let currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array
  }
  render(){

    return (
      <React.Fragment>
      <div className="game">
          {
            this.state.finalizedFrameworks.map((framework, index) => {
              return <Card framework={framework.name} click={() => {this.handleClick(framework.name,index)}} close={framework.close} complete={framework.complete}/>
            })
          }
      </div>

      <button onClick={}>
            NEW GAME
      </button>
      </React.Fragment>

    )
  }
</code>```

I expect the following:

The cards are in a 4x4 way.

New game button resets the cards.

Thx a lot!

答:
To restart, I think you just need to setState to the original starting state. Assuming your start() function is responsible to generate the initial state

```<code>  start(){
    let finalizedFrameworks = [];

    this.state.duplicatedFrameworks = this.state.frameworks.concat(this.state.frameworks)
    this.state.randomizedFrameworks = this.shuffle(this.state.duplicatedFrameworks)
    this.state.randomizedFrameworks.map((name,index) => {
      finalizedFrameworks.push({
        name,
        close: true,
        complete: false,
        fail: false
      })
    })

    // this.state.finalizedFrameworks = finalizedFrameworks

    // Instead of just setting the state directly, need to do setState to trigger re-render
    this.setState({finalizedFrameworks})
  }
</code>```

Then your NEW GAME button just need to call start() function to restart

```<code>render(){
    return (
      <React.Fragment>
      <div className="game">
          {
            this.state.finalizedFrameworks.map((framework, index) => {
              return <Card framework={framework.name} click={() => {this.handleClick(framework.name,index)}} close={framework.close} complete={framework.complete}/>
            })
          }
      </div>

      <button onClick={() => this.start()}>
            NEW GAME
      </button>
      </React.Fragment>

    )
  }
</code>```

Body:
I'm trying to implement a memory game. I'm almost done with it, but there are 2 parts that I need help with.
1. I can't figure out how to show my 16 cards in a 4x4 way. (probably something small, but hey i'm a noob)
2. I need a new game button, that resets the cards.

I have not really tried anything, I would like to get help and understand it while i'm implementing the fix.

  handleClick(name,index){
    if(this.state.openedFrameworks.length === 2){
      setTimeout(() => {
        this.check()
      },750)
    }else {
      let framework = {
        name,
        index
      }
      let finalizedFrameworks = this.state.finalizedFrameworks
      let frameworks = this.state.openedFrameworks
      finalizedFrameworks[index].close = false
      frameworks.push(framework)
      this.setState({
        openedFrameworks: frameworks,
        finalizedFrameworks: finalizedFrameworks
      })
      if(this.state.openedFrameworks.length === 2){
        setTimeout(() => {
          this.check()
        },750)
      }
    }
  }
  check(){
    let finalizedFrameworks = this.state.finalizedFrameworks
    if((this.state.openedFrameworks[0].name === this.state.openedFrameworks[1].name) && (this.state.openedFrameworks[0].index !== this.state.openedFrameworks[1].index)){
      finalizedFrameworks[this.state.openedFrameworks[0].index].complete = true
      finalizedFrameworks[this.state.openedFrameworks[1].index].complete = true
    }else {
      finalizedFrameworks[this.state.openedFrameworks[0].index].close = true
      finalizedFrameworks[this.state.openedFrameworks[1].index].close = true
    }
    this.setState({
      finalizedFrameworks,
      openedFrameworks: []
    })
  }
  start(){
    let finalizedFrameworks = [];
    this.state.duplicatedFrameworks = this.state.frameworks.concat(this.state.frameworks)
    this.state.randomizedFrameworks = this.shuffle(this.state.duplicatedFrameworks)
    this.state.randomizedFrameworks.map((name,index) => {
      finalizedFrameworks.push({
        name,
        close: true,
        complete: false,
        fail: false
      })
    })
    this.state.finalizedFrameworks = finalizedFrameworks
  }
  shuffle(array){
    let currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array
  }
  render(){

    return (
      <React.Fragment>

          {
            this.state.finalizedFrameworks.map((framework, index) => {
              return <Card framework={framework.name} click={() => {this.handleClick(framework.name,index)}} close={framework.close} complete={framework.complete}/>
            })
          }

      <button onClick={}>
            NEW GAME
      </button>
      </React.Fragment>

    )
  }

I expect the following:

The cards are in a 4x4 way.

New game button resets the cards.

Thx a lot!

Body:
To restart, I think you just need to setState to the original starting state. Assuming your start() function is responsible to generate the initial state

  start(){
    let finalizedFrameworks = [];

    this.state.duplicatedFrameworks = this.state.frameworks.concat(this.state.frameworks)
    this.state.randomizedFrameworks = this.shuffle(this.state.duplicatedFrameworks)
    this.state.randomizedFrameworks.map((name,index) => {
      finalizedFrameworks.push({
        name,
        close: true,
        complete: false,
        fail: false
      })
    })

    // this.state.finalizedFrameworks = finalizedFrameworks

    // Instead of just setting the state directly, need to do setState to trigger re-render
    this.setState({finalizedFrameworks})
  }

Then your NEW GAME button just need to call start() function to restart

render(){
    return (
      <React.Fragment>
      <div className="game">
          {
            this.state.finalizedFrameworks.map((framework, index) => {
              return <Card framework={framework.name} click={() => {this.handleClick(framework.name,index)}} close={framework.close} complete={framework.complete}/>
            })
          }
      </div>

      <button onClick={() => this.start()}>
            NEW GAME
      </button>
      </React.Fragment>

    )
  }


问:
How to fix for-loop output in python
I have 3 routers on my test lab environment, I'm trying to reach these routers and send some commands using for-loop and send output in the way I type/list them.

I have 3 1841 Cisco routers and running 12.4 IOS:

```<code>    multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
    for ips in multi_ip_addr:
        pass
    len_ip_addr = len(multi_ip_addr)
    for len_ip in range(len_ip_addr):
        device = {'ip': ips,
        'username': 'admin',
        'password': 'password'}
        print(device)
</code>```

My expected result is:

```<code>{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.2.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}
</code>```

however I am getting this output:

```<code>{'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}
</code>```

答:
Python determines context with indentation, so if you want to use your ips variable for each entry, you need to do it within the for ips in multi_ip_addr context (where you currently only have pass.) I might also change the name of ips to ip if I were you, just to make things clearer.

Here's how I would rewrite your loop:

```<code>template_dict = {'ip' : None, 'username' : 'admin', 'password' : 'password'}
multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']

for ip in multi_ip_addr:
    print(template_dict.update({'ip' : ip})

</code>```

Comparison with JS:

Using range(len(multi_ip_addr)) will give you a set of index values, but this is unnecessary for what you are trying to accomplish. If you're familiar with JavaScript: the default for loop behavior in python is like the using the for...of pattern:

EX:

```<code>for (let i of <some_iterable>) {
    console.log(i);
}
</code>```

would be equivalent to:

```<code>for i in <some_iterable>:
    print(i)
</code>```

Title: How to fix for-loop output in python

Body:
I have 3 routers on my test lab environment, I'm trying to reach these routers and send some commands using for-loop and send output in the way I type/list them.

I have 3 1841 Cisco routers and running 12.4 IOS:

    multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']
    for ips in multi_ip_addr:
        pass
    len_ip_addr = len(multi_ip_addr)
    for len_ip in range(len_ip_addr):
        device = {'ip': ips,
        'username': 'admin',
        'password': 'password'}
        print(device)

My expected result is:

{'ip': '192.168.1.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.2.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}

however I am getting this output:

{'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'} {'ip': '192.168.3.1', 'username': 'admin', 'password': 'password'}

Body:
Python determines context with indentation, so if you want to use your ips variable for each entry, you need to do it within the for ips in multi_ip_addr context (where you currently only have pass.) I might also change the name of ips to ip if I were you, just to make things clearer.

Here's how I would rewrite your loop:

template_dict = {'ip' : None, 'username' : 'admin', 'password' : 'password'}
multi_ip_addr = ['192.168.1.1', '192.168.2.1', '192.168.3.1']

for ip in multi_ip_addr:
    print(template_dict.update({'ip' : ip})

Comparison with JS:

Using range(len(multi_ip_addr)) will give you a set of index values, but this is unnecessary for what you are trying to accomplish. If you're familiar with JavaScript: the default for loop behavior in python is like the using the for...of pattern:

EX:

for (let i of <some_iterable>) {
    console.log(i);
}

would be equivalent to:

for i in <some_iterable>:
    print(i)


问:
How to use python request to log in via a login page?
I have looked at other examples online, but I cannot seem to figure out how to login in. The page looks something like this:

```<code><div class="Loginbox">
  <form id="login_form" name="login_form" method="post" action="/a/login.seam" enctype="application/x-www-form-urlencoded">
  <input type="hidden" name="login_form" value="login_form" />
    <div>
      <p><label for="login_form:name">
    Username</label><br /><input id="login_form:name" type="text" name="login_form:name"/>
      </p>
    </div>
    <div><label for="login_form:password">
  Password</label><br /><input id="login_form:password" type="password" name="login_form:password" value=""/>
    </div>
    <div><input id="login_form:submit" type="submit" name="login_form:submit" value="Login" class="buttonmed" />
    </div><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-13463453453453:3453445345345345345" autocomplete="off" />
  </form>
</div>
</code>```

I have tried something like this:

```<code>with requests.Session() as sess:
  data = {}
  data['login_form:name'] = user
  data['login_form:password'] = password
  sess.headers = HEADERS
  sess.get(url)
  sess.post(url, data=data)
  h = sess.get(url)
  print(h.text)
</code>```

But the text still shows that I am at the login page.

SOLUTION:

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

with requests.Session() as sess:
  data = {}
  data['login_form'] = 'login_form'
  data['login_form:name'] = user
  data['login_form:password'] = password
  sess.headers = HEADERS
  g = sess.get(url)
  soup = BeautifulSoup(g.text, "lxml")
  val = soup.select_one("input[id='javax.faces.ViewState']")['value']
  data['javax.faces.ViewState'] = val
  h = sess.post(url, data=data)
  print(h.text)
</code>```

答: You can look at browser console what request is send wen you press login button on the page. You need to emulate this request (url and post data). </p>

Body:
I have looked at other examples online, but I cannot seem to figure out how to login in. The page looks something like this:

  <form id="login_form" name="login_form" method="post" action="/a/login.seam" enctype="application/x-www-form-urlencoded">
  <input type="hidden" name="login_form" value="login_form" />

    Username
<input id="login_form:name" type="text" name="login_form:name"/>

  Password
<input id="login_form:password" type="password" name="login_form:password" value=""/>

<input id="login_form:submit" type="submit" name="login_form:submit" value="Login" class="buttonmed" />

<input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="-13463453453453:3453445345345345345" autocomplete="off" />
  </form>

I have tried something like this:

with requests.Session() as sess:
  data = {}
  data['login_form:name'] = user
  data['login_form:password'] = password
  sess.headers = HEADERS
  sess.get(url)
  sess.post(url, data=data)
  h = sess.get(url)
  print(h.text)

But the text still shows that I am at the login page.

SOLUTION:

import requests
from bs4 import BeautifulSoup

with requests.Session() as sess:
  data = {}
  data['login_form'] = 'login_form'
  data['login_form:name'] = user
  data['login_form:password'] = password
  sess.headers = HEADERS
  g = sess.get(url)
  soup = BeautifulSoup(g.text, "lxml")
  val = soup.select_one("input[id='javax.faces.ViewState']")['value']
  data['javax.faces.ViewState'] = val
  h = sess.post(url, data=data)
  print(h.text)


问:
How to get latest file-name or file from S3 bucket using event triggered lambda
I am very new to AWS services and has just a week worth of experience with serverless architecture, My requirement is to trigger an event when a new file is uploaded to a specific bucket, once the event trigger is set my Lambda should get the details of the latest file such as Name, Size, and Date of creation.

The source is uploading this file in a new folder every time and names the folder with the current date.

So far I am able to crack how to create my Lambda function and listen to the event trigger.

Here is my code.

```<code>import boto3
import botocore
import datetime
import logging

def lambda_handler(event, context):
    logging.info('Start function')
    s3 = boto3.resource('s3')
    DATE = datetime.datetime.today().strftime('%Y-%m-%d')
    BUCKET_NAME = 'monkey-banana-dev'
    KEY = '/banana/incoming/daily/{}'.format(DATE)
    logging.info('Getting file from {}'.format(KEY))
    try:
        s3.Bucket(BUCKET_NAME).download_file(KEY, 'name_of_my_file')
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            raise
</code>```

here since I know that it's going to be today's date hence I am using datetime to get the exact KEY but file-name will always be different. although I know that it's going to be a text file with .txt suffix, I am not able to get around on how to get the name of the latest uploaded file and other details from the trigger.

答:
'Key' will contain the whole file path.
example-

```<code>import boto3
import os
s3 = boto3.resource('s3')
bucket=s3.Bucket('hcss-heavyjob-raw-tables')
for key in bucket.objects.all():
    if key.key.startswith('heavyjob/EMPMAST'):
           print(key.key)'
</code>```

Output-

heavyjob/EMPMAST/20190524-165352044.csv

heavyjob/EMPMAST/20190529-153011532.csv

heavyjob/EMPMAST/LOAD00000001.csv

You can get the file name by using basename on key.key
or

```<code>head,tail = os.path.split(key.key)
print(tail)
</code>```

Body:
I am very new to AWS services and has just a week worth of experience with serverless architecture, My requirement is to trigger an event when a new file is uploaded to a specific bucket, once the event trigger is set my Lambda should get the details of the latest file such as Name, Size, and Date of creation.

The source is uploading this file in a new folder every time and names the folder with the current date.

So far I am able to crack how to create my Lambda function and listen to the event trigger.

Here is my code.

import boto3
import botocore
import datetime
import logging

def lambda_handler(event, context):
    logging.info('Start function')
    s3 = boto3.resource('s3')
    DATE = datetime.datetime.today().strftime('%Y-%m-%d')
    BUCKET_NAME = 'monkey-banana-dev'
    KEY = '/banana/incoming/daily/{}'.format(DATE)
    logging.info('Getting file from {}'.format(KEY))
    try:
        s3.Bucket(BUCKET_NAME).download_file(KEY, 'name_of_my_file')
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            raise

here since I know that it's going to be today's date hence I am using datetime to get the exact KEY but file-name will always be different. although I know that it's going to be a text file with .txt suffix, I am not able to get around on how to get the name of the latest uploaded file and other details from the trigger.

Body:
'Key' will contain the whole file path.
example-

import boto3
import os
s3 = boto3.resource('s3')
bucket=s3.Bucket('hcss-heavyjob-raw-tables')
for key in bucket.objects.all():
    if key.key.startswith('heavyjob/EMPMAST'):
           print(key.key)'

Output-

heavyjob/EMPMAST/20190524-165352044.csv

heavyjob/EMPMAST/20190529-153011532.csv

heavyjob/EMPMAST/LOAD00000001.csv

You can get the file name by using basename on key.key
or

head,tail = os.path.split(key.key)
print(tail)


问:
How do I delete Firestore dictionary value?
I have a value in a document which I set like this:

```<code>func uploadMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let updateData = ["medications" : [medication : dosage]]

    docRef.setData(updateData, merge: true) { (err) in
        if err != nil {
            print(err?.localizedDescription as Any)
            self.view.makeToast(err?.localizedDescription as! String)
        } else {
            self.refresh()
            print(" Data Uploaded")
        }
    }
}
</code>```

Now I need to Delete this value, but I can't figure out how:

```<code>func removeMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let data = [[medication : dosage] : FieldValue.delete()]

    docRef.updateData(["medications" : data]) { (err) in
        print("delete")
    }
}
</code>```

This compiles but causes a crash:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_TtGCs26_SwiftDeferredNSDictionarySSSS_$ length]: unrecognized
  selector sent to instance 0x2830ca100'

I've tried many different variations including

```<code> let data = [[medication : dosage]]

    docRef.updateData(["medications" : FieldValue.arrayRemove(data)]) { (err) in
        print("delete")
    }
</code>```

The data in Firestore is set like:

```<code>medications {
   Venlafaxine : 37.5,
   Sertraline : 100
}
</code>```

How can I delete a [Venlafaxine : 37.5] row essentially.

答:
I know you answered your own question but I wanted to suggest there may be a more elegant solution.

There are some missing data points in the question so I will fill in with an example case - this may be of use in the overall thought process.

Let's assume your app allows patents (users) to keep track of their prescriptions. This means there would be multiple users, with each user having a prescription. That prescription has a medication and dosage.

When a user wants to delete a prescription, the code loads them all and iterates until it finds the correct one, and then deletes it. That requires iterating over the data which is really inefficient.

Let propose another method and we'll assume this is for user 0 (uid_0)

Here's what the Firestore Structure will look like

```<code>user_prescriptions
    uid_0
       prescriptions
          prescription_0
             medication: "some med"
             dosage: "some dosage"
          prescription_1
             medication: "some med"
             dosage: "some dosage"
     uid_1
        prescriptions
          prescription_0
             medication: "some med"
             dosage: "some dosage"
          prescription_1
             medication: "some med"
             dosage: "some dosage"
</code>```

when a user wants to add a medication, we call a function uploadPrescription and pass it the med and dosage

```<code>self.uploadPrescription(dosage: "100mg", medication: "Aspirin")
</code>```

and here's the function to write that data to Firestore.

```<code>func uploadPrescription(dosage: String, medication: String) {
    let uid = "uid_0"
    let collectionRef = db.collection("users_prescriptions").document(uid).collection("prescriptions")
    let prescriptionData = ["medication": medication,
                            "dosage": dosage]
    var ref: DocumentReference? = nil
    ref = collectionRef.addDocument(data: prescriptionData) { err in
        if let err = err {
            print(err.localizedDescription)
            return
        } else {
            let docJustAddedRef = ref?.documentID
            print(docJustAddedRef!)
            //maybe create a PrescriptionClass and add it to a tableview
        }

    }
}
</code>```

the interesting thing to note is this function creates a unique child node for each prescription and captures a reference to it (that's where prescription_0 and prescription_1 id's come from).

That reference will have a documentID. This will allow each user to have an infinite number of unique prescriptions.

Then the prescription information could be shown in the UI in perhaps a tableView. The documentID is the identifier of that specific prescription and would from then on be used to remove or change the prescription information. Many times on app start, all of the prescriptions would be loaded into a class and each of those would be stored in an array used as a tableView datasource. When the user swipes to delete, you get the row they want to delete, get that prescription object from the array - remove it from the array, and then using the documentID, remove it from Firestore.

```<code>func removeMedDosage(documentID: String) {
    let uid = "uid_0"
    let docRef = db.collection("users_scripts").document(uid).collection("prescriptions").document(documentID)
    docRef.delete()
}
</code>```

Body:
I have a value in a document which I set like this:

func uploadMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let updateData = ["medications" : [medication : dosage]]

    docRef.setData(updateData, merge: true) { (err) in
        if err != nil {
            print(err?.localizedDescription as Any)
            self.view.makeToast(err?.localizedDescription as! String)
        } else {
            self.refresh()
            print(" Data Uploaded")
        }
    }
}

Now I need to Delete this value, but I can't figure out how:

func removeMedDosage(dosage: String, medication: String) {
    let docRef = db.collection("users").document(userId!)
    let data = [[medication : dosage] : FieldValue.delete()]

    docRef.updateData(["medications" : data]) { (err) in
        print("delete")
    }
}

This compiles but causes a crash:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason:
  '-[_TtGCs26_SwiftDeferredNSDictionarySSSS_$ length]: unrecognized
  selector sent to instance 0x2830ca100'

I've tried many different variations including

 let data = [[medication : dosage]]

    docRef.updateData(["medications" : FieldValue.arrayRemove(data)]) { (err) in
        print("delete")
    }

The data in Firestore is set like:

medications {
   Venlafaxine : 37.5,
   Sertraline : 100
}

How can I delete a [Venlafaxine : 37.5] row essentially.

Body:
I know you answered your own question but I wanted to suggest there may be a more elegant solution.

There are some missing data points in the question so I will fill in with an example case - this may be of use in the overall thought process.

Let's assume your app allows patents (users) to keep track of their prescriptions. This means there would be multiple users, with each user having a prescription. That prescription has a medication and dosage.

When a user wants to delete a prescription, the code loads them all and iterates until it finds the correct one, and then deletes it. That requires iterating over the data which is really inefficient.

Let propose another method and we'll assume this is for user 0 (uid_0)

Here's what the Firestore Structure will look like

user_prescriptions
    uid_0
       prescriptions
          prescription_0
             medication: "some med"
             dosage: "some dosage"
          prescription_1
             medication: "some med"
             dosage: "some dosage"
     uid_1
        prescriptions
          prescription_0
             medication: "some med"
             dosage: "some dosage"
          prescription_1
             medication: "some med"
             dosage: "some dosage"

when a user wants to add a medication, we call a function uploadPrescription and pass it the med and dosage

self.uploadPrescription(dosage: "100mg", medication: "Aspirin")

and here's the function to write that data to Firestore.

func uploadPrescription(dosage: String, medication: String) {
    let uid = "uid_0"
    let collectionRef = db.collection("users_prescriptions").document(uid).collection("prescriptions")
    let prescriptionData = ["medication": medication,
                            "dosage": dosage]
    var ref: DocumentReference? = nil
    ref = collectionRef.addDocument(data: prescriptionData) { err in
        if let err = err {
            print(err.localizedDescription)
            return
        } else {
            let docJustAddedRef = ref?.documentID
            print(docJustAddedRef!)
            //maybe create a PrescriptionClass and add it to a tableview
        }

    }
}

the interesting thing to note is this function creates a unique child node for each prescription and captures a reference to it (that's where prescription_0 and prescription_1 id's come from).

That reference will have a documentID. This will allow each user to have an infinite number of unique prescriptions.

Then the prescription information could be shown in the UI in perhaps a tableView. The documentID is the identifier of that specific prescription and would from then on be used to remove or change the prescription information. Many times on app start, all of the prescriptions would be loaded into a class and each of those would be stored in an array used as a tableView datasource. When the user swipes to delete, you get the row they want to delete, get that prescription object from the array - remove it from the array, and then using the documentID, remove it from Firestore.

func removeMedDosage(documentID: String) {
    let uid = "uid_0"
    let docRef = db.collection("users_scripts").document(uid).collection("prescriptions").document(documentID)
    docRef.delete()
}


问:
How can I call a constructor properly in this case?
I'm trying to call a constructor properly dealing with 3 different class but I'm not able to do it

```<code>public class B {

private final A a;

public B(A a) {
     this.a = a;
}
private final C c = new C(a);
}
</code>```

I have the error "variable a might not have been initialized", I know a way to do it by putting a second argument in the B constructor and calling it in the main class B but is there any other way ?

答:
Here:

```<code>private final C c = new C(a);
</code>```

There you can avoid that "conflict" of order, by simply assigning c also in your constructor:

```<code>public B(A a) {
     this.a = a;
     this.c = new C(a);
}
</code>```

Sure, when you can define your fields right at the declaration, that simplifies a lot. But sometimes, doing it in the constructor just can't be avoided.

Body:
I'm trying to call a constructor properly dealing with 3 different class but I'm not able to do it

public class B {

private final A a;

public B(A a) {
     this.a = a;
}
private final C c = new C(a);
}

I have the error "variable a might not have been initialized", I know a way to do it by putting a second argument in the B constructor and calling it in the main class B but is there any other way ?

Body:
Here:

private final C c = new C(a);

There you can avoid that "conflict" of order, by simply assigning c also in your constructor:

public B(A a) {
     this.a = a;
     this.c = new C(a);
}

Sure, when you can define your fields right at the declaration, that simplifies a lot. But sometimes, doing it in the constructor just can't be avoided.


问:
ShareThis not display properly when initially hidden
How to make ShareThis buttons show correctly after clicking the 'show' button? After I push the 'show' button, all '.st-btn' has 'display:none' until I resize the window and it becomes 'display:inline-block' automatically... In other words, the ShareThis display properly only after I pushed the 'show' button and resize the window manually. Thank you in advance

$('span').hide();
$('button').click(function(){$('span').show();});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://platform-api.sharethis.com/js/sharethis.js#property=58ff3bc2a9dabe0012b03357&product=inline-share-buttons"></script>

<button>show</button>
<span><div class="sharethis-inline-share-buttons"></div></span></code>```

sample code

答:
In order to solve your issue it's enough to change from:

```<code>$('span').show();
</code>```

to:

```<code>$('span').find(':hidden').addBack().show();
</code>```

Show span element plus all the hidden elements under it.

The code (jsfiddle here):

$('span').hide();
$('button').click(function () {
    $('span').find(':hidden').addBack().show();
});
```

<pre class="lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://platform-api.sharethis.com/js/sharethis.js#property=58ff3bc2a9dabe0012b03357&product=inline-share-buttons"></script>

<button>show</button>

<span><div class="sharethis-inline-share-buttons"></div></span>
</code>```

Body:
How to make ShareThis buttons show correctly after clicking the 'show' button? After I push the 'show' button, all '.st-btn' has 'display:none' until I resize the window and it becomes 'display:inline-block' automatically... In other words, the ShareThis display properly only after I pushed the 'show' button and resize the window manually. Thank you in advance

$('span').hide();
$('button').click(function(){$('span').show();});

<button>show</button>

sample code

Body:
In order to solve your issue it's enough to change from:

$('span').show();

to:

$('span').find(':hidden').addBack().show();

Show span element plus all the hidden elements under it.

The code (jsfiddle here):

$('span').hide();
$('button').click(function () {
    $('span').find(':hidden').addBack().show();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://platform-api.sharethis.com/js/sharethis.js#property=58ff3bc2a9dabe0012b03357&product=inline-share-buttons"></script>

<button>show</button>

<span><div class="sharethis-inline-share-buttons"></div></span>


问:
How to MAX() on any column type at SQL Server
I have a view with many columns and a query builder that will eventually add a MAX statement on the query. Problem is, when the column type is BIT I cannot use MAX on it, so I need to check type before. I cannot check the data type of the column during the query builder, so I need a SQL solution that works fine for any data type.

Here is an example (the SELECT within the CTE represents a VIEW which can have any type of data on mycol, for this first example I'm simulating a BIT. The MAX portion is where I need to work on):

ORIGINAL

```<code>WITH cte (mycol) AS
(
    SELECT CAST(1 as BIT) as mycol
)
SELECT
    MAX(mycol) as mycol_max
FROM cte
</code>```

I got this error:

Operand data type bit is invalid for max operator.

CASTING

If I do the following it will work:

```<code>WITH cte (mycol) AS
(
     SELECT CAST(1 as BIT) as mycol
)
SELECT
    MAX(CAST(mycol as INT)) as mycol_max
FROM cte
</code>```

However, if mycol is a string (SELECT 'test' as mycol), I got this error:

Conversion failed when converting the varchar value 'test' to data type int.

So, I tried to check type using some different approaches:

ISNUMERIC()

```<code>WITH cte (mycol) AS
(
     SELECT 'test' as mycol
)
SELECT
    MAX(CASE
           WHEN 1 = ISNUMERIC(mycol)
              THEN CAST(mycol AS INT)
              ELSE mycol
        END) AS mycol_max
FROM cte
</code>```

NOT LIKE %[^0-9]%

```<code>WITH cte (mycol) AS
(
     SELECT 'test' as mycol
)
SELECT
    MAX(CASE
           WHEN "mycol" NOT LIKE '%[^0-9]%'
              THEN CAST(mycol AS INT)
              ELSE mycol
        END) AS mycol_max
FROM cte;
</code>```

TRY_PARSE

```<code>WITH cte (mycol) AS
(
     SELECT 'test' as mycol
)
SELECT
    MAX(CASE
           WHEN TRY_PARSE(mycol AS INT) IS NOT NULL
              THEN CAST(mycol AS INT)
           ELSE mycol
        END) AS mycol_max
FROM cte
</code>```

All of these returned the error

Conversion failed when converting the varchar value 'test' to data type int.

Also, if mycol is an integer:

```<code>WITH cte (mycol) AS
(
     SELECT 1 as mycol
)
...
</code>```

I got

Argument data type int is invalid for argument 1 of parse function.

So, all I need is to allow anything into the MAX() statement. I tried checking and converting, but didn't get any satisfactory solution. How can I do it?

Thanks

Using SQL Server 2017.

答:
BIT Won't behave as int so MAX won't really work unless you just choose max LEN which is still not optimal. You might try ORDER BY DESC but I doubt it will help. You might as well add another column that will specify what exactly MAX you're looking for.</p>

```<code>SELECT TOP 1 CAST(1 as BIT) as mycol
FROM TB1
ORDER BY mycol DESC
</code>```

Body:
I have a view with many columns and a query builder that will eventually add a MAX statement on the query. Problem is, when the column type is BIT I cannot use MAX on it, so I need to check type before. I cannot check the data type of the column during the query builder, so I need a SQL solution that works fine for any data type.

Here is an example (the SELECT within the CTE represents a VIEW which can have any type of data on mycol, for this first example I'm simulating a BIT. The MAX portion is where I need to work on):

ORIGINAL

WITH cte (mycol) AS
(
    SELECT CAST(1 as BIT) as mycol
)
SELECT
    MAX(mycol) as mycol_max
FROM cte

I got this error:

Operand data type bit is invalid for max operator.

CASTING

If I do the following it will work:

WITH cte (mycol) AS
(
     SELECT CAST(1 as BIT) as mycol
)
SELECT
    MAX(CAST(mycol as INT)) as mycol_max
FROM cte

However, if mycol is a string (SELECT 'test' as mycol), I got this error:

Conversion failed when converting the varchar value 'test' to data type int.

So, I tried to check type using some different approaches:

ISNUMERIC()

WITH cte (mycol) AS
(
     SELECT 'test' as mycol
)
SELECT
    MAX(CASE
           WHEN 1 = ISNUMERIC(mycol)
              THEN CAST(mycol AS INT)
              ELSE mycol
        END) AS mycol_max
FROM cte

NOT LIKE %[^0-9]%

WITH cte (mycol) AS
(
     SELECT 'test' as mycol
)
SELECT
    MAX(CASE
           WHEN "mycol" NOT LIKE '%[^0-9]%'
              THEN CAST(mycol AS INT)
              ELSE mycol
        END) AS mycol_max
FROM cte;

TRY_PARSE

WITH cte (mycol) AS
(
     SELECT 'test' as mycol
)
SELECT
    MAX(CASE
           WHEN TRY_PARSE(mycol AS INT) IS NOT NULL
              THEN CAST(mycol AS INT)
           ELSE mycol
        END) AS mycol_max
FROM cte

All of these returned the error

Conversion failed when converting the varchar value 'test' to data type int.

Also, if mycol is an integer:

WITH cte (mycol) AS
(
     SELECT 1 as mycol
)
...

I got

Argument data type int is invalid for argument 1 of parse function.

So, all I need is to allow anything into the MAX() statement. I tried checking and converting, but didn't get any satisfactory solution. How can I do it?

Thanks

Using SQL Server 2017.

Body:
BIT Won't behave as int so MAX won't really work unless you just choose max LEN which is still not optimal. You might try ORDER BY DESC but I doubt it will help. You might as well add another column that will specify what exactly MAX you're looking for.

SELECT TOP 1 CAST(1 as BIT) as mycol
FROM TB1
ORDER BY mycol DESC


答:
Sure.

```<code>public class B {

    private final A a;

    public B(A a) {
        this.a = a;
        c = new C(a);
    }
    private final C c;
}
</code>```

The reason yours doesn't work is that initializers at declaration are executed before constructors.

Title: How can I call a constructor properly in this case?

Body:
Sure.

public class B {

    private final A a;

    public B(A a) {
        this.a = a;
        c = new C(a);
    }
    private final C c;
}

The reason yours doesn't work is that initializers at declaration are executed before constructors.


答:
Initialize the value in the ctor</p>

```<code>public class B {
    private final A a;
    private final C c;

    public B(final A a) {
         this.a = a;
         this.c = new C(a)
    }
}
</code>```

Body:
Initialize the value in the ctor

public class B {
    private final A a;
    private final C c;

    public B(final A a) {
         this.a = a;
         this.c = new C(a)
    }
}


问:
Why Do i get null value in the following code concerning java inheritence
I will provide the code and the output given by the compiler for better understanding of the problem. You will notice a null value for Registration Number...there is the problem.
You will notice at the output that i get null value for Registration number...i don't get it because it all seemed right, until it wasn't.

public class Student {
    private String regNo;
    //Student student = new Test();

    public String getRegNo() {
        return regNo;
    }

    public void setRegNo(String number) {
        this.regNo = regNo;
    }

    public void displayRegistrationNumber(){
        System.out.println("Registration number: "+ getRegNo());
    }

}

-----------------------------------------------------------------'
public class Test extends Student{
    private double sub1, sub2;

    public double getSub1() {
        return sub1;
    }

    public void setSub1(double sub1) {
        this.sub1 = sub1;
    }

    public double getSub2() {
        return sub2;
    }

    public void setSub2(double sub2) {
        this.sub2 = sub2;
    }

    public void displayScore(){
        System.out.printf("Scores: Subject1 = %.0f, Subject2 = %.0f \n",getSub1(), getSub2());
    }
}

-----------------------------------------------------------------------
public class Results extends Test {
    private double total;

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public void displayTotalScores(){
        setTotal(getSub1()+getSub2());
        System.out.printf("Total marks: %.0f \n", getTotal());
    }

}
---------------------------------------------------------------------

public class Main_method {
    public static void main(String[] args){
        Results results = new Results();

        results.setRegNo("2017-04-06859");
        results.setSub1(75.47);
        results.setSub2(89);

        results.displayRegistrationNumber();
        results.displayScore();
        results.displayTotalScores();

    }
}

```

<p>Here's the output. Notice the null</p>

```Registration number: null
Scores: Subject1 = 75, Subject2 = 89
Total marks: 164 `
```

答:
This is an expected behavior, the argument you passed to   public void setRegNo(String number) is never used.

```<code> this.regNo = regNo;
</code>```

reassigns the the regNo  declared in Student class (which in this case is null ) back to the Object which calls it.

change the argument or the assignment statement

i.e

```<code> public void setRegNo(String regNo)
</code>```

or

```<code>this.regNo = number;
</code>```

Body:
I will provide the code and the output given by the compiler for better understanding of the problem. You will notice a null value for Registration Number...there is the problem.
You will notice at the output that i get null value for Registration number...i don't get it because it all seemed right, until it wasn't.

public class Student {
    private String regNo;
    //Student student = new Test();

    public String getRegNo() {
        return regNo;
    }

    public void setRegNo(String number) {
        this.regNo = regNo;
    }

    public void displayRegistrationNumber(){
        System.out.println("Registration number: "+ getRegNo());
    }

}

-----------------------------------------------------------------'
public class Test extends Student{
    private double sub1, sub2;

    public double getSub1() {
        return sub1;
    }

    public void setSub1(double sub1) {
        this.sub1 = sub1;
    }

    public double getSub2() {
        return sub2;
    }

    public void setSub2(double sub2) {
        this.sub2 = sub2;
    }

    public void displayScore(){
        System.out.printf("Scores: Subject1 = %.0f, Subject2 = %.0f \n",getSub1(), getSub2());
    }
}

-----------------------------------------------------------------------
public class Results extends Test {
    private double total;

    public double getTotal() {
        return total;
    }

    public void setTotal(double total) {
        this.total = total;
    }

    public void displayTotalScores(){
        setTotal(getSub1()+getSub2());
        System.out.printf("Total marks: %.0f \n", getTotal());
    }

}
---------------------------------------------------------------------

public class Main_method {
    public static void main(String[] args){
        Results results = new Results();

        results.setRegNo("2017-04-06859");
        results.setSub1(75.47);
        results.setSub2(89);

        results.displayRegistrationNumber();
        results.displayScore();
        results.displayTotalScores();

    }
}

Here's the output. Notice the null

Registration number: null
Scores: Subject1 = 75, Subject2 = 89
Total marks: 164 `

Body:
This is an expected behavior, the argument you passed to   public void setRegNo(String number) is never used.

 this.regNo = regNo;

reassigns the the regNo  declared in Student class (which in this case is null ) back to the Object which calls it.

change the argument or the assignment statement

i.e

 public void setRegNo(String regNo)

or

this.regNo = number;


问:
Referencing resources directory from project object model variables
If I can use ${project.build.sourceDirectory} to reference the source directory, what do I use to reference the "resources" directory?

Looking at the super pom, it would seem that ${project.build.resources.resource.directory} would work, but it does not . . .

答:
Extending @chiebaud's answer, using the maven help plugin, I think the correct option today is

```<code>${project.resources[0].directory}
</code>```

(without the ".build" part).

Body:
Extending @chiebaud's answer, using the maven help plugin, I think the correct option today is

${project.resources[0].directory}

(without the ".build" part).


问:
Make string into arraylist with individual characters Java
I have a String called new_alpha which contains only characters (no whitespace). How do I split it so that each character is a different element in a new ArrayList?


问:
Cannot see local class variables while debugging DLL in Visual Studio..?
I'm trying to debug a DLL that I've written in VB.Net. When the external program starts, it loads the DLL and everything runs fine...but I cannot see the class variables in the Locals pane. They show up blank as shown below.

Also, some lines of code generate the error "There is no source code available for the current location", but I think I understand why. Whenever it tries to step into class members of any of the Microsoft DLLs, it would of course have no information for those. But any lines which deal only in code that I've written, it works fine.

This is a COM DLL AddIn for Microsoft Access 2007, but I'm assuming the issue is roughly the same regardless of the type of DLL. The Shared COM Addin Wizard was used to get started, and then customization proceeded from there with satisfactory results...except for the invisible variables in the Locals window.

I'm new to writing & debugging a DLL like this; until now I've only done EXE files. I've researched MSDN, Google, and Stack Overflow, and here are the details that are asked about on other threads...

Visual Studio 2008, .Net 3.0, and Access 2007

Project Properties > Debug > External Program points to MSAccess.exe.

Project configuration is set for Debug.

Optimizations = off.

Generate debug info = Full.

The PDB file is present in the \bin\ folder with the DLL.

Breakpoints are working.

Debug.Print messages are working.

I dug through the registry and found all references to the project, DLL, and its custom UserControl (required since the project creates a CustomTaskPane, and all path paths point to \bin\ folder.

What am I doing wrong?

What am I doing right?

What can I improve?

答:
Alright, after working on this for days in between other projects, I have an answer...of sorts. I think the solution and/or projects had become corrupt. I'll pass along what I can in the hope it may help others.

Yesterday I had a marathon session of "click everything", in the project settings and Options > Debugging, but nothign helped. At some point I stopped fiddling with the debug settings and continued working on the code until I was tired and went home.

This morning with a fresh mind I tried again, and discovered the private class variables were now all visible. And I don't know why. Also, there was a new problem: the Just-In-Time debugger prompt kept popping up, even thought it wasn't enabled in the settings:

Also, the play/stop/step toolbar buttons would become disabled when they shouldn't be, yet the menu selections for the same items functioned normally.

I double-checked all settings again. I played with everything and could NOT get the local class variables to become invisible again, and could not get the JIT dialog to go away.

So I...

Made a copy of the solution folder.

Cleaned the solution.

Rebuilt the solution, including the Setup project.

Uninstalled the Setup project from Windows via Solution Explorer.

Cleaned the solution again.

Deleted the SUO file.

Deleted everything in \bin\ and \debug.

Rebuilt the solution, including the Setup project.

And still the problems persisted.

After the JIT prompt, I clicked Continue (F5), then closed MSAccess. Aafter execution stopped, some IDE panes (such as Explorer, Locals, etc) disappeared, and some flew around to random locations on the screen. It was then I decided something might be corrupt, and started making plans to uninstall/reinstall all of Visual Studio 2008 from scratch, and possibly even a new solution from scratch.

So before reinstalling, I tried creating a new solution from scratch, and found everything worked perfectly, even with all settings as they were from the original solution.

So in the original solution I...

Exported the settings from Tools > Import and Export Settings.

Reset all settings.

Imported the settings I just saved.

At the moment the import dialog closed, I received the error message: "An unexpected error has occurred".

When restarting the VS IDE, I received a dialog that said "Visual Studio is configuring the environment for first time use". That didn't sound good.

Tried importing the settings again, same error.

Rebooted, tried importing again, same error.

Closed the Solution file, tried importing the settings again without any solution open, and it worked....or seemed to.

Then opened the Solution...and same problems were back.

Exported the settings from the new Solution.

Imported those settings into the original solution...and it's fixed..?

There was no import error, and the project started working correctly..!!

The local class variables were visible, and the JIT prompt was gone..!!

So...I guess something was bunged up in the Solution, one of the Projects, the IDE settings, or...something. I hope this helps someone else.


问:
Batch transform job results in "InternalServerError" with data file >100MB
I'm using Sagemaker in order to perform binary classification on time series, each sample being a numpy array of shape [24,11] (24h, 11features). I used a tensorflow model in script mode, my script being very similar to the one I used as reference:
https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/tensorflow_script_mode_training_and_serving/mnist.py

The training reported success and I was able to deploy a model for batch transformation. The transform job works fine when I input just a few samples (say, [10,24,11]), but it returns an InternalServerError when I input more samples for prediction (for example, [30000, 24, 11], which size is >100MB).

Here is the error:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-0c46f7563389> in <module>()
     32
     33 # Then wait until transform job is completed
---> 34 tf_transformer.wait()

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/transformer.py in wait(self)
    133     def wait(self):
    134         self._ensure_last_transform_job()
--> 135         self.latest_transform_job.wait()
    136
    137     def _ensure_last_transform_job(self):

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/transformer.py in wait(self)
    207
    208     def wait(self):
--> 209         self.sagemaker_session.wait_for_transform_job(self.job_name)
    210
    211     @staticmethod

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in wait_for_transform_job(self, job, poll)
    893         """
    894         desc = _wait_until(lambda: _transform_job_status(self.sagemaker_client, job), poll)
--> 895         self._check_job_status(job, desc, 'TransformJobStatus')
    896         return desc
    897

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in _check_job_status(self, job, desc, status_key_name)
    915             reason = desc.get('FailureReason', '(No reason provided)')
    916             job_type = status_key_name.replace('JobStatus', ' job')
--> 917             raise ValueError('Error for {} {}: {} Reason: {}'.format(job_type, job, status, reason))
    918
    919     def wait_for_endpoint(self, endpoint, poll=5):

ValueError: Error for Transform job Tensorflow-batch-transform-2019-05-29-02-56-00-477: Failed Reason: InternalServerError: We encountered an internal error.  Please try again.

</code>```

I tried to use both SingleRecord and MultiRecord parameters when deploying the model but the result was the same, so I decided to keep MultiRecord. My transformer looks like that:

```<code>transformer = tf_estimator.transformer(
    instance_count=1,
    instance_type='ml.m4.xlarge',
    max_payload = 100,
    assemble_with = 'Line',
    strategy='MultiRecord'
)
</code>```

At first I was using a json file as input for the transform job, and it threw the error :

```<code>Too much data for max payload size
</code>```

So next I tried the jsonlines format (the .npy format is not supported as far as I understand), thinking that jsonlines could get split by Line and thus avoid the size error, but that's where I got the InternalServerError. Here is the related code:

```<code>#Convert test_x to jsonlines and save
test_x_list = test_x.tolist()
file_path ='data_cnn_test/test_x.jsonl'
file_name='test_x.jsonl'

with jsonlines.open(file_path, 'w') as writer:
    writer.write(test_x_list)

input_key = 'batch_transform_tf/input/{}'.format(file_name)
output_key = 'batch_transform_tf/output'
test_input_location = 's3://{}/{}'.format(bucket, input_key)
test_output_location = 's3://{}/{}'.format(bucket, output_key)

s3.upload_file(file_path, bucket, input_key)

# Initialize the transformer object
tf_transformer = sagemaker.transformer.Transformer(
    base_transform_job_name='Tensorflow-batch-transform',
    model_name='sagemaker-tensorflow-scriptmode-2019-05-29-02-46-36-162',
    instance_count=1,
    instance_type='ml.c4.2xlarge',
    output_path=test_output_location,
    assemble_with = 'Line'
    )

# Start the transform job
tf_transformer.transform(test_input_location, content_type='application/jsonlines', split_type='Line')
</code>```

The list named test_x_list has a shape [30000, 24, 11], which corresponds to 30000 samples so I would like to return 30000 predictions.

I suspect my jsonlines file isn't being split by Line and is of course too big to be processed in one batch, which throws the error, but I don't understand why it doesn't get split correctly. I am using the default output_fn and input_fn (I did not re-write those functions in my script).

Any insight on what I could be doing wrong would be greatly appreciated.

答:
I assume this is a duplicate of this AWS Forum post: https://forums.aws.amazon.com/thread.jspa?threadID=303810&tstart=0

Anyway, for completeness I'll answer here as well.

The issue is that you are serializing your dataset incorrectly when converting it into jsonlines:

```<code>test_x_list = test_x.tolist()
...
with jsonlines.open(file_path, 'w') as writer:
    writer.write(test_x_list)
</code>```

What the above is doing is creating a very large single-line containing your full dataset which is too big for single inference call to consume.

I suggest you change your code to make each line a single sample so that inference can take place on individual samples instead of the whole dataset:

```<code>test_x_list = test_x.tolist()
...
with jsonlines.open(file_path, 'w') as writer:
    for sample in test_x_list:
        writer.write(sample)
</code>```

If one sample at a time is too slow you can also play around with the max_concurrent_transforms, strategy, and max_payload parameters to be able to batch the data as well as run concurrent transforms if your algorithm can run in parallel - also, of course, you can split the data into multiple files and run transformations with more than just one node. See https://sagemaker.readthedocs.io/en/latest/transformer.html and https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateTransformJob.html for additional detail on what these parameters do.

Body:
I'm using Sagemaker in order to perform binary classification on time series, each sample being a numpy array of shape [24,11] (24h, 11features). I used a tensorflow model in script mode, my script being very similar to the one I used as reference:
https://github.com/awslabs/amazon-sagemaker-examples/blob/master/sagemaker-python-sdk/tensorflow_script_mode_training_and_serving/mnist.py

The training reported success and I was able to deploy a model for batch transformation. The transform job works fine when I input just a few samples (say, [10,24,11]), but it returns an InternalServerError when I input more samples for prediction (for example, [30000, 24, 11], which size is >100MB).

Here is the error:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-0c46f7563389> in <module>()
     32
     33 # Then wait until transform job is completed
---> 34 tf_transformer.wait()

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/transformer.py in wait(self)
    133     def wait(self):
    134         self._ensure_last_transform_job()
--> 135         self.latest_transform_job.wait()
    136
    137     def _ensure_last_transform_job(self):

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/transformer.py in wait(self)
    207
    208     def wait(self):
--> 209         self.sagemaker_session.wait_for_transform_job(self.job_name)
    210
    211     @staticmethod

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in wait_for_transform_job(self, job, poll)
    893         """
    894         desc = _wait_until(lambda: _transform_job_status(self.sagemaker_client, job), poll)
--> 895         self._check_job_status(job, desc, 'TransformJobStatus')
    896         return desc
    897

~/anaconda3/envs/tensorflow_p36/lib/python3.6/site-packages/sagemaker/session.py in _check_job_status(self, job, desc, status_key_name)
    915             reason = desc.get('FailureReason', '(No reason provided)')
    916             job_type = status_key_name.replace('JobStatus', ' job')
--> 917             raise ValueError('Error for {} {}: {} Reason: {}'.format(job_type, job, status, reason))
    918
    919     def wait_for_endpoint(self, endpoint, poll=5):

ValueError: Error for Transform job Tensorflow-batch-transform-2019-05-29-02-56-00-477: Failed Reason: InternalServerError: We encountered an internal error.  Please try again.

I tried to use both SingleRecord and MultiRecord parameters when deploying the model but the result was the same, so I decided to keep MultiRecord. My transformer looks like that:

transformer = tf_estimator.transformer(
    instance_count=1,
    instance_type='ml.m4.xlarge',
    max_payload = 100,
    assemble_with = 'Line',
    strategy='MultiRecord'
)

At first I was using a json file as input for the transform job, and it threw the error :

Too much data for max payload size

So next I tried the jsonlines format (the .npy format is not supported as far as I understand), thinking that jsonlines could get split by Line and thus avoid the size error, but that's where I got the InternalServerError. Here is the related code:

#Convert test_x to jsonlines and save
test_x_list = test_x.tolist()
file_path ='data_cnn_test/test_x.jsonl'
file_name='test_x.jsonl'

with jsonlines.open(file_path, 'w') as writer:
    writer.write(test_x_list)

input_key = 'batch_transform_tf/input/{}'.format(file_name)
output_key = 'batch_transform_tf/output'
test_input_location = 's3://{}/{}'.format(bucket, input_key)
test_output_location = 's3://{}/{}'.format(bucket, output_key)

s3.upload_file(file_path, bucket, input_key)

# Initialize the transformer object
tf_transformer = sagemaker.transformer.Transformer(
    base_transform_job_name='Tensorflow-batch-transform',
    model_name='sagemaker-tensorflow-scriptmode-2019-05-29-02-46-36-162',
    instance_count=1,
    instance_type='ml.c4.2xlarge',
    output_path=test_output_location,
    assemble_with = 'Line'
    )

# Start the transform job
tf_transformer.transform(test_input_location, content_type='application/jsonlines', split_type='Line')

The list named test_x_list has a shape [30000, 24, 11], which corresponds to 30000 samples so I would like to return 30000 predictions.

I suspect my jsonlines file isn't being split by Line and is of course too big to be processed in one batch, which throws the error, but I don't understand why it doesn't get split correctly. I am using the default output_fn and input_fn (I did not re-write those functions in my script).

Any insight on what I could be doing wrong would be greatly appreciated.

Body:
I assume this is a duplicate of this AWS Forum post: https://forums.aws.amazon.com/thread.jspa?threadID=303810&tstart=0

Anyway, for completeness I'll answer here as well.

The issue is that you are serializing your dataset incorrectly when converting it into jsonlines:

test_x_list = test_x.tolist()
...
with jsonlines.open(file_path, 'w') as writer:
    writer.write(test_x_list)

What the above is doing is creating a very large single-line containing your full dataset which is too big for single inference call to consume.

I suggest you change your code to make each line a single sample so that inference can take place on individual samples instead of the whole dataset:

test_x_list = test_x.tolist()
...
with jsonlines.open(file_path, 'w') as writer:
    for sample in test_x_list:
        writer.write(sample)

If one sample at a time is too slow you can also play around with the max_concurrent_transforms, strategy, and max_payload parameters to be able to batch the data as well as run concurrent transforms if your algorithm can run in parallel - also, of course, you can split the data into multiple files and run transformations with more than just one node. See https://sagemaker.readthedocs.io/en/latest/transformer.html and https://docs.aws.amazon.com/sagemaker/latest/dg/API_CreateTransformJob.html for additional detail on what these parameters do.


问:
One line stops script C# Unity
Some part of the code works (hp1 -= damage1;), but the second part doesn't work.
Where did I make a mistake?

Here are parts of two scripts:

Player1.cs

```<code>private Bullet1 b1;

void Start()
{
    b1 = FindObjectOfType<Bullet1>();
}

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Bullet1")
    {
        hp1 -= damage1; // it works, my player loses hp
        Destroy1(); // doesn't work
    }
}

void Destroy1()
{
    b1.hit1 = true; // hit for bullet1.cs
}
</code>```

Bullet1.cs

```<code>public bool hit1;

void Update()
{
    if (hit1)
    {
        hit1 = false;
        Destroy(gameObject);
    }
}
</code>```

If I switch bool hit = true in real time in Unity, destroying works. It means that Bullet1.cs can't recieve hit = true;

If I swap lines hp1 -= damage1; and Destroy1();, my player can't get damage.   So, Destroy1(); stops my code and then can't activate other lines. Also if I change Destroy1(); to b1.hit1 = true; nothing new happens.

答:
Just destroy the bullet through the collision instead of using the boolean. It's creating unnecessary resource usage. Of the given code, this is all you need to do to destroy the bullet using the player script. The parts of the bullet script shown are unnecessary. If you want additional logic handled inside the bullet when destroyed then use a OnDestroy function to handle it.</p>

```<code>void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Bullet1")
    {
        hp1 -= damage1;
        Destroy(col.gameobject);
    }
}
</code>```

Title: One line stops script C# Unity

Body:
Some part of the code works (hp1 -= damage1;), but the second part doesn't work.
Where did I make a mistake?

Here are parts of two scripts:

Player1.cs

private Bullet1 b1;

void Start()
{
    b1 = FindObjectOfType<Bullet1>();
}

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Bullet1")
    {
        hp1 -= damage1; // it works, my player loses hp
        Destroy1(); // doesn't work
    }
}

void Destroy1()
{
    b1.hit1 = true; // hit for bullet1.cs
}

Bullet1.cs

public bool hit1;

void Update()
{
    if (hit1)
    {
        hit1 = false;
        Destroy(gameObject);
    }
}

If I switch bool hit = true in real time in Unity, destroying works. It means that Bullet1.cs can't recieve hit = true;

If I swap lines hp1 -= damage1; and Destroy1();, my player can't get damage.   So, Destroy1(); stops my code and then can't activate other lines. Also if I change Destroy1(); to b1.hit1 = true; nothing new happens.

Body:
Just destroy the bullet through the collision instead of using the boolean. It's creating unnecessary resource usage. Of the given code, this is all you need to do to destroy the bullet using the player script. The parts of the bullet script shown are unnecessary. If you want additional logic handled inside the bullet when destroyed then use a OnDestroy function to handle it.

void OnCollisionEnter2D(Collision2D col)
{
    if (col.gameObject.tag == "Bullet1")
    {
        hp1 -= damage1;
        Destroy(col.gameobject);
    }
}


问:
Reverse the pointers in a linked list
Hello guys could you please help me in writing a procedure to reverse the pointers in a linked list . for example A->B->C->D would become A<-B<-C<-D without using extra linked list .

Edit:
------ okay guys so i have been looking for solution for this problem here is the code in case u want it :

```<code>    void reverse_list(){
    struct node *next, *current,*previous;
    previous = NULL;
    current =head;
    while(current != NULL){
    next = current->next;
    current->next = previous;
    previous=current;
    current = next;
    }
    head = previous;
    }
</code>```

答:
You could think of the list as a stack. Then you could easily reverse such a list by "popping" the nodes and "pushing" them into a new list.

The above could be done both destructively (destroying the old list) and non-destructively (creating the new list as a reversed copy of the original list).

Title: Reverse the pointers in a linked list

Body:
Hello guys could you please help me in writing a procedure to reverse the pointers in a linked list . for example A->B->C->D would become A<-B<-C<-D without using extra linked list .

Edit:
------ okay guys so i have been looking for solution for this problem here is the code in case u want it :

    void reverse_list(){
    struct node *next, *current,*previous;
    previous = NULL;
    current =head;
    while(current != NULL){
    next = current->next;
    current->next = previous;
    previous=current;
    current = next;
    }
    head = previous;
    }


问:
how to specify a variable/parameter in my logic app's arm template?
I am creating an Arm template for a logic app. This logic app needs to delete some old entries in azure table (say 10 or 20 days old).

In my arm template, if I do this, it works.

```<code>"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),-31)}'"
  }
</code>```

But ideally I want to do this:

```<code>"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay'))}'"
   }
</code>```

Basically use a parameter to control the amount of days to check. I define this parameter as:

```<code> "parameters": {
    "RetainDay": {
      "type": "int"
    }
  }
</code>```

When I deploy this, the parameters('RetainDay') isn't replaced to the parameter value. Instead it just stays same as:

```<code>Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay')
</code>```

So I must be using the wrong syntax.

Can someone point it out?

答:
You need to use a concat() function to achieve string concatenation and variable expansion:

```<code>"$filter": "[concat('Timestamp le datetime\'@{addDays(utcNow(),', parameters('RetainDay'), ')}\'')]"
</code>```

i think you can escape ' with \, if not, you can create a variable with the value ' and use that instead.

Body:
I am creating an Arm template for a logic app. This logic app needs to delete some old entries in azure table (say 10 or 20 days old).

In my arm template, if I do this, it works.

"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),-31)}'"
  }

But ideally I want to do this:

"queries": {
            "$filter": "Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay'))}'"
   }

Basically use a parameter to control the amount of days to check. I define this parameter as:

 "parameters": {
    "RetainDay": {
      "type": "int"
    }
  }

When I deploy this, the parameters('RetainDay') isn't replaced to the parameter value. Instead it just stays same as:

Timestamp le datetime'@{addDays(utcNow(),parameters('RetainDay')

So I must be using the wrong syntax.

Can someone point it out?

Body:
You need to use a concat() function to achieve string concatenation and variable expansion:

"$filter": "[concat('Timestamp le datetime\'@{addDays(utcNow(),', parameters('RetainDay'), ')}\'')]"

i think you can escape ' with \, if not, you can create a variable with the value ' and use that instead.