问:
Name two portions of a string as variables with Powershell
helpful Stack Overflow community,

I am working with automated report-outs (.txt docs) that contain two pieces of info I need in a larger string. I need to find a way to create variables from each of these and use them to pipe into another command.

Example of Report-Out:

```<code>B072L8FX9H  2017-11-17 14:49:17 -05:00  2017-11-17 14:49:17 -05:00  D1  volenick    amandun                     -   -
</code>```

I need to create two variables, one containing the first bit of text, the file name B072L8FX9H and one variable containing the last bit, the username amandun.

Please note the filename will always be 10 digits, but the username length will vary. Additionally, the spaces at the end prior to the -   - vary. These inconsistencies make me wary of utilizing trim but I am not opposed.

assuming I can get these two variables I believe I can then pipe them into a foreach statement to tag the actual files

Additional examples of Report-Out:

```<code>B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -

B01C5AVSBW  2017-11-17 15:21:40 -05:00  2017-11-17 15:21:40 -05:00  D1  volenick    Gunthorp                        -   -

B076FHS4CZ  2017-11-17 15:23:36 -05:00  2017-11-17 15:23:36 -05:00  D1  volenick    amandun                     -   -
</code>```

I havent been able to build a trim command that works with all the inconsistencies. Perhaps there is a better way to extract these variables.

Thanks

EDIT - This is the solution we ended up using:

```<code>#generate individual file to user relationships
$dailyuserSheet = report.txt
$a=@()
$row = ""|Select file, user
$a +=$row
Foreach ($line in(Get-Content $dailyuserSheet)){
If($line -ne ""){
$file = $line.split("`t")[0]
$user = $line.split("`t")[5]
$a += "$file `t $user"
}
}
</code>```

答:
This is a way to retrieve the information you want.

```<code>$Parse = 'B072L8FX9H  2017-11-17 14:49:17 -05:00  2017-11-17 14:49:17 -05:00  D1  volenick    amandun                     -   -   '
$Parse = $Parse.Trim()

$Parse -match '\w+\s+-\s+-$' >$Null #returns $True

$Username = $Matches[0] -replace '\s+-\s+-'
$FileName = ($Parse -split '\s')[0]
</code>```

Body:
helpful Stack Overflow community,

I am working with automated report-outs (.txt docs) that contain two pieces of info I need in a larger string. I need to find a way to create variables from each of these and use them to pipe into another command.

Example of Report-Out:

B072L8FX9H  2017-11-17 14:49:17 -05:00  2017-11-17 14:49:17 -05:00  D1  volenick    amandun                     -   -

I need to create two variables, one containing the first bit of text, the file name B072L8FX9H and one variable containing the last bit, the username amandun.

Please note the filename will always be 10 digits, but the username length will vary. Additionally, the spaces at the end prior to the -   - vary. These inconsistencies make me wary of utilizing trim but I am not opposed.

assuming I can get these two variables I believe I can then pipe them into a foreach statement to tag the actual files

Additional examples of Report-Out:

B075XR6ZR1  2017-11-17 15:19:22 -05:00  2017-11-17 15:19:22 -05:00  D1  volenick    pascalec                        -   -

B01C5AVSBW  2017-11-17 15:21:40 -05:00  2017-11-17 15:21:40 -05:00  D1  volenick    Gunthorp                        -   -

B076FHS4CZ  2017-11-17 15:23:36 -05:00  2017-11-17 15:23:36 -05:00  D1  volenick    amandun                     -   -

I havent been able to build a trim command that works with all the inconsistencies. Perhaps there is a better way to extract these variables.

Thanks

EDIT - This is the solution we ended up using:

#generate individual file to user relationships
$dailyuserSheet = report.txt
$a=@()
$row = ""|Select file, user
$a +=$row
Foreach ($line in(Get-Content $dailyuserSheet)){
If($line -ne ""){
$file = $line.split("`t")[0]
$user = $line.split("`t")[5]
$a += "$file `t $user"
}
}

Body:
This is a way to retrieve the information you want.

$Parse = 'B072L8FX9H  2017-11-17 14:49:17 -05:00  2017-11-17 14:49:17 -05:00  D1  volenick    amandun                     -   -   '
$Parse = $Parse.Trim()

$Parse -match '\w+\s+-\s+-$' >$Null #returns $True

$Username = $Matches[0] -replace '\s+-\s+-'
$FileName = ($Parse -split '\s')[0]


来源: stackexchange

问:
Use scoped packages with Jest
I am developing an app with react-native and typescript and doing the tests with Jest, but I have a problem when I use scoped packages (@assets), jest can not find the path and gives error.

The directory structure looks like this:

```<code>project/
  assets/
    img/
      foo.png
    package.json
  src/
    Foo.ts
  build/
    Foo.js

// assets/package.json
{
  "name": "@assets" // My @assets scope
}

// build/Foo.js
const image = require('@assets/img/foo.png'); // <- error in Jest
</code>```

So when I run the jest:

npm run jest build/

It can not find '@assets/img/foo.png' and throws the error:

Cannot find module '@assets/img/logo.png' from 'Foo.js'

How can I use scope package in Jest?

Jest version: 20.0.4

thanks

答:
For those that get here that are using private packages under a scoped org, here's how I tackled this:

```<code>"jest": {
  "moduleNameMapper": {
    "^@org-name/(.*)$": "<rootDir>/node_modules/@org-name/$1/dist/$1.es5.js"
  }
}
</code>```

This assumes that all of your scoped packages have a similar path to their exported module.  If they don't, you can specify them individually:

```<code>"jest": {
  "moduleNameMapper": {
    "^@org-name/package-one$": "<rootDir>/node_modules/org-name/package-one/dist/package.js",
    "^@org-name/package-two$": "<rootDir>/node_modules/org-name/package-two/build/index.js"
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Use scoped packages with Jest

Body:
I am developing an app with react-native and typescript and doing the tests with Jest, but I have a problem when I use scoped packages (@assets), jest can not find the path and gives error.

The directory structure looks like this:

project/
  assets/
    img/
      foo.png
    package.json
  src/
    Foo.ts
  build/
    Foo.js

// assets/package.json
{
  "name": "@assets" // My @assets scope
}

// build/Foo.js
const image = require('@assets/img/foo.png'); // <- error in Jest

So when I run the jest:

npm run jest build/

It can not find '@assets/img/foo.png' and throws the error:

Cannot find module '@assets/img/logo.png' from 'Foo.js'

How can I use scope package in Jest?

Jest version: 20.0.4

thanks

Body:
For those that get here that are using private packages under a scoped org, here's how I tackled this:

"jest": {
  "moduleNameMapper": {
    "^@org-name/(.*)$": "<rootDir>/node_modules/@org-name/$1/dist/$1.es5.js"
  }
}

This assumes that all of your scoped packages have a similar path to their exported module.  If they don't, you can specify them individually:

"jest": {
  "moduleNameMapper": {
    "^@org-name/package-one$": "<rootDir>/node_modules/org-name/package-one/dist/package.js",
    "^@org-name/package-two$": "<rootDir>/node_modules/org-name/package-two/build/index.js"
  }
}


问:
Pass data to TabBar Controller
I want pass data between two ViewControllers throw the TabBarController.
Inside the first ViewController I located textField and button.
Inside the second I located Label.
When I write some text in textField and push button, I expect that this text appear in the Label in the second ViewController. But nothing happens.

And my code:

First ViewController:

```<code>import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

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

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

}
</code>```

Second ViewController:

```<code>import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

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

}
</code>```

答:
First i think your view controllers that are representing tabs should be embedded into navigation controllers which would then be linked to the TabBarController.

Secondly, the preferred and recommended way to send data between controllers is through protocols (delegates). Here is a good example you can check out, step by step: https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

However if you're looking for a quick fix of your solution i think that Bruno Phillipe's answer gets it to some extent, but not quite. We can't really be sure what controller is at what index in the view controller list. I think this should work:

```<code>@IBAction func enter(_ sender: Any) {
    if textField.text != "" {
        if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController {

            //check if there are view controllers in the tabBarController
            guard let vcList = tabBarController.viewControllers else {

                return
            }

            for controller in vcList {

                if let second = controller as? SecondViewController {
                    //this will be executed only when a controller is SeconfViewController
                    second.label.text = textField.text
                    tabBarController.selectedIndex = 0
                }
            }

        }
    }
}
</code>```

EDIT:

I tried it myself and the problem is that you were trying to set the label.text when in fact the label component was never initialised. I think if you simply stored the textField value into myString variable in SecondViewController it would work (not sure).

However here's the solution using a protocol (delegate) which is the right way to send data between controllers. Ask any questions you might have. This should work:

FirstViewController:

```<code>import Foundation
import UIKit

protocol LabelChangeDelegate: class {

    func changeLabelWithText(_ text: String?)
}

class FirstViewController: UIViewController {

    weak var delegate: LabelChangeDelegate?

    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: UIButton) {

        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController {

                //check if there are view controllers in the tabBarController
                guard let vcList = tabBarController.viewControllers else {

                    return
                }

                for controller in vcList {

                    if let second = controller as? SecondViewController {
                        //this will be executed only when a controller is SeconfViewController

                        //set the delegate - who needs the data
                        delegate = second
                        //call the delegate function which will commmunicate with the delegate
                        delegate?.changeLabelWithText(textField.text!)
                        //don't know why you need this
                        tabBarController.selectedIndex = 0
                    }
                }

            }
        }
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

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

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

}
</code>```

SecondViewController:

```<code>import Foundation
import UIKit

class SecondViewController: UIViewController, LabelChangeDelegate {

    @IBOutlet weak var label: UILabel!

    //lazy init
    lazy var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        //set label when the view loads, not in the first controller
        label.text = myString

        // Do any additional setup after loading the view, typically from a nib.
    }

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

    //delegate function
    func changeLabelWithText(_ text: String?) {
        guard let sentText = text else {

            //no text sent
            return
        }

        myString = sentText
    }

}
</code>```

Title: Pass data to TabBar Controller

Body:
I want pass data between two ViewControllers throw the TabBarController.
Inside the first ViewController I located textField and button.
Inside the second I located Label.
When I write some text in textField and push button, I expect that this text appear in the Label in the second ViewController. But nothing happens.

And my code:

First ViewController:

import UIKit

class FirstViewController: UIViewController {
    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: Any) {
        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController, let second = tabBarController.viewControllers?.first as? SecondViewController {
                second.label.text = textField.text
                tabBarController.selectedIndex = 0
            }
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

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

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

}

Second ViewController:

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        label.text = myString
        // Do any additional setup after loading the view, typically from a nib.
    }

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

}

Body:
First i think your view controllers that are representing tabs should be embedded into navigation controllers which would then be linked to the TabBarController.

Secondly, the preferred and recommended way to send data between controllers is through protocols (delegates). Here is a good example you can check out, step by step: https://medium.com/@jamesrochabrun/implementing-delegates-in-swift-step-by-step-d3211cbac3ef

However if you're looking for a quick fix of your solution i think that Bruno Phillipe's answer gets it to some extent, but not quite. We can't really be sure what controller is at what index in the view controller list. I think this should work:

@IBAction func enter(_ sender: Any) {
    if textField.text != "" {
        if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController {

            //check if there are view controllers in the tabBarController
            guard let vcList = tabBarController.viewControllers else {

                return
            }

            for controller in vcList {

                if let second = controller as? SecondViewController {
                    //this will be executed only when a controller is SeconfViewController
                    second.label.text = textField.text
                    tabBarController.selectedIndex = 0
                }
            }

        }
    }
}

EDIT:

I tried it myself and the problem is that you were trying to set the label.text when in fact the label component was never initialised. I think if you simply stored the textField value into myString variable in SecondViewController it would work (not sure).

However here's the solution using a protocol (delegate) which is the right way to send data between controllers. Ask any questions you might have. This should work:

FirstViewController:

import Foundation
import UIKit

protocol LabelChangeDelegate: class {

    func changeLabelWithText(_ text: String?)
}

class FirstViewController: UIViewController {

    weak var delegate: LabelChangeDelegate?

    @IBOutlet weak var textField: UITextField!

    @IBAction func enter(_ sender: UIButton) {

        if textField.text != "" {
            if let window = UIApplication.shared.delegate?.window, let tabBarController = window?.rootViewController as? UITabBarController {

                //check if there are view controllers in the tabBarController
                guard let vcList = tabBarController.viewControllers else {

                    return
                }

                for controller in vcList {

                    if let second = controller as? SecondViewController {
                        //this will be executed only when a controller is SeconfViewController

                        //set the delegate - who needs the data
                        delegate = second
                        //call the delegate function which will commmunicate with the delegate
                        delegate?.changeLabelWithText(textField.text!)
                        //don't know why you need this
                        tabBarController.selectedIndex = 0
                    }
                }

            }
        }
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    }

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

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

}

SecondViewController:

import Foundation
import UIKit

class SecondViewController: UIViewController, LabelChangeDelegate {

    @IBOutlet weak var label: UILabel!

    //lazy init
    lazy var myString = String()

    override func viewDidLoad() {
        super.viewDidLoad()

        //set label when the view loads, not in the first controller
        label.text = myString

        // Do any additional setup after loading the view, typically from a nib.
    }

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

    //delegate function
    func changeLabelWithText(_ text: String?) {
        guard let sentText = text else {

            //no text sent
            return
        }

        myString = sentText
    }

}

ContentLicense: CC BY-SA 4.0


问:
Is it possible to use client side libraries (google.visualization) on server side?
Is it possible to call google.visualization or to get the result of work HtmlService without client side?

For example:
I would like to obtain the result of chart.getImageURI() ( data:image/png;base64) and insert this picture in the spreadsheet when it will be open?

答:
You need to get the range data as DataTable which you then need to pass to the Charts API. I won't recommend to invoke this function when the spreadsheet is opened always. Refer the below code snippet.

```<code>function onOpen(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
  var data = ss.getRange(1, 1, ss.getLastRow(),2).getDataTable();
  var charts = Charts.newLineChart().setDataTable(data).setTitle('My Graph').setXAxisTitle("Time").setDimensions(1000, 450).build().getAs('image/png');
  ss.getRange(2, 4).clearContent(); //In order to delete the old image
  ss.insertImage(charts, 4, 2);
}
</code>```

Body:
You need to get the range data as DataTable which you then need to pass to the Charts API. I won't recommend to invoke this function when the spreadsheet is opened always. Refer the below code snippet.

function onOpen(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
  var data = ss.getRange(1, 1, ss.getLastRow(),2).getDataTable();
  var charts = Charts.newLineChart().setDataTable(data).setTitle('My Graph').setXAxisTitle("Time").setDimensions(1000, 450).build().getAs('image/png');
  ss.getRange(2, 4).clearContent(); //In order to delete the old image
  ss.insertImage(charts, 4, 2);
}


问:
MySql - How to get average data from two tables?
Products Sold Table

Holds records of every single item purchased as an order can have many products.

```<code>+----+------------+---------+----------+-------+
| ID | PAYMENT_ID | PROD_ID | STORE_ID | PRICE |
+----+------------+---------+----------+-------+
|  1 |          1 |       5 |        4 | 3.00  |
|  2 |          1 |       4 |        4 | 4.00  |
|  3 |          2 |       3 |        7 | 5.00  |
|  4 |          3 |       8 |        9 | 10.00 |
+----+------------+---------+----------+-------+
</code>```

Payment Table

Keeps records of the payment for the order.

```<code>+----+-------+------------+----------+
| ID | TOTAL |    DATE    | STORE_ID |
+----+-------+------------+----------+
|  1 | 7.00  | 10/10/2010 |        4 |
|  2 | 5.00  | 01/07/2011 |        7 |
|  3 | 10.00 | 20/02/2012 |        9 |
+----+-------+------------+----------+
</code>```

How can I create query or a function that would give me how many sales were made every month (Jan to Dec) on average in the years 2010/2011/2012 for a given store.

For example, if “Store 4” sold 5 products in January in 2010, in 2011 and in 2012 then the average sales for that store in the month of January would be 5.

I tried:

```<code>SELECT storeid, paymentdate
FROM payment_table
WHERE (YEAR(paymentdate)=2010 OR YEAR(paymentdate)=2011 OR YEAR(paymentdate)=2012)
    AND (storeid=1)
</code>```

This doesnt do much apart from get the dates of all the payments for a given store.

答:
You need to join the tables to get the sales counts for each time period. Put that in a subquery so you can regroup it by month.</p>

```<code>SELECT month, AVG(sales) AS avg_sales
FROM (SELECT MONTH(paymentdate) AS month, YEAR(paymentdate) AS year, COUNT(*) AS sales
      FROM payment_table AS pay
      JOIN products_sold_table AS prod ON pay.id = prod.payment_id AND pay.store_id = prod.store_id
      WHERE YEAR(paymentdate) IN (2010, 2011, 2012) AND pay.store_id = 1
      GROUP BY month, year
) AS x
GROUP BY month
</code>```

Body:
Products Sold Table

Holds records of every single item purchased as an order can have many products.

+----+------------+---------+----------+-------+
| ID | PAYMENT_ID | PROD_ID | STORE_ID | PRICE |
+----+------------+---------+----------+-------+
|  1 |          1 |       5 |        4 | 3.00  |
|  2 |          1 |       4 |        4 | 4.00  |
|  3 |          2 |       3 |        7 | 5.00  |
|  4 |          3 |       8 |        9 | 10.00 |
+----+------------+---------+----------+-------+

Payment Table

Keeps records of the payment for the order.

+----+-------+------------+----------+
| ID | TOTAL |    DATE    | STORE_ID |
+----+-------+------------+----------+
|  1 | 7.00  | 10/10/2010 |        4 |
|  2 | 5.00  | 01/07/2011 |        7 |
|  3 | 10.00 | 20/02/2012 |        9 |
+----+-------+------------+----------+

How can I create query or a function that would give me how many sales were made every month (Jan to Dec) on average in the years 2010/2011/2012 for a given store.

For example, if “Store 4” sold 5 products in January in 2010, in 2011 and in 2012 then the average sales for that store in the month of January would be 5.

I tried:

SELECT storeid, paymentdate
FROM payment_table
WHERE (YEAR(paymentdate)=2010 OR YEAR(paymentdate)=2011 OR YEAR(paymentdate)=2012)
    AND (storeid=1)

This doesnt do much apart from get the dates of all the payments for a given store.

Body:
You need to join the tables to get the sales counts for each time period. Put that in a subquery so you can regroup it by month.

SELECT month, AVG(sales) AS avg_sales
FROM (SELECT MONTH(paymentdate) AS month, YEAR(paymentdate) AS year, COUNT(*) AS sales
      FROM payment_table AS pay
      JOIN products_sold_table AS prod ON pay.id = prod.payment_id AND pay.store_id = prod.store_id
      WHERE YEAR(paymentdate) IN (2010, 2011, 2012) AND pay.store_id = 1
      GROUP BY month, year
) AS x
GROUP BY month


问:
Tensorflow variable initialization error
I am getting the variable initialization error in tensorflow, can someone please help me ? I am using python version(3.5.4) and TF version(1.2.1) on GPU.There seems to be some issue with the gap between the tensorflow and python libraries sync, if I remove the last line from the code then its working fine.</p>

```<code>import numpy as np
import tensorflow as tf

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)

    in_size =  100
    h1_size = 10

    x = tf.placeholder(tf.float32,(None,in_size))
    w = tf.Variable(tf.random_normal([in_size,h1_size]))
    b = tf.Variable(tf.ones([h1_size]))

    xw = tf.matmul(x,w)
    z = tf.add(xw,b)

    a = tf.nn.relu(z)

    yhat = sess.run(a,feed_dict={x:np.random.random([100000,in_size])})

Error:-

FailedPreconditionError: Attempting to use uninitialized value Variable_12
     [[Node: Variable_12/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_12"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_12)]]

Caused by op 'Variable_12/read', defined at:
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 245, in <module>
    main()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 241, in main
    kernel.start()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\tornado\ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
</code>```

答:
You need to declare your variables before you initialize them. The following code should work:</p>

```<code>in_size =  100
h1_size = 10

x = tf.placeholder(tf.float32,(None,in_size))
w = tf.Variable(tf.random_normal([in_size,h1_size]))
b = tf.Variable(tf.ones([h1_size]))

xw = tf.matmul(x,w)
z = tf.add(xw,b)
a = tf.nn.relu(z)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    yhat = sess.run(a,feed_dict={x:np.random.random([100000,in_size])})
</code>```

Body:
I am getting the variable initialization error in tensorflow, can someone please help me ? I am using python version(3.5.4) and TF version(1.2.1) on GPU.There seems to be some issue with the gap between the tensorflow and python libraries sync, if I remove the last line from the code then its working fine.

import numpy as np
import tensorflow as tf

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)

    in_size =  100
    h1_size = 10

    x = tf.placeholder(tf.float32,(None,in_size))
    w = tf.Variable(tf.random_normal([in_size,h1_size]))
    b = tf.Variable(tf.ones([h1_size]))

    xw = tf.matmul(x,w)
    z = tf.add(xw,b)

    a = tf.nn.relu(z)

    yhat = sess.run(a,feed_dict={x:np.random.random([100000,in_size])})

Error:-

FailedPreconditionError: Attempting to use uninitialized value Variable_12
     [[Node: Variable_12/read = Identity[T=DT_FLOAT, _class=["loc:@Variable_12"], _device="/job:localhost/replica:0/task:0/cpu:0"](Variable_12)]]

Caused by op 'Variable_12/read', defined at:
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 245, in <module>
    main()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\spyder\utils\ipython\start_kernel.py", line 241, in main
    kernel.start()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
    ioloop.IOLoop.instance().start()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\tornado\ioloop.py", line 888, in start
    handler_func(fd_obj, events)
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "C:\Users\Sachin-PC\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)

Body:
You need to declare your variables before you initialize them. The following code should work:

in_size =  100
h1_size = 10

x = tf.placeholder(tf.float32,(None,in_size))
w = tf.Variable(tf.random_normal([in_size,h1_size]))
b = tf.Variable(tf.ones([h1_size]))

xw = tf.matmul(x,w)
z = tf.add(xw,b)
a = tf.nn.relu(z)

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    yhat = sess.run(a,feed_dict={x:np.random.random([100000,in_size])})


问:
Sort an array with DOM tags and attributes by left and top values
I have got an array with DOM tags (div -> children img -> div closed). Those tags has attributes (left and top values). I added em as nodeLists so i can access elements offsetLeft and offsetTop to determine those values but i cant figurate out how to rearange those tags in the array ascending by left or top values.

HTML

```<code><body>
    <div style="left:40px;top:10px;position:absolute">
        <img src="assets/images/text1.png" />
    </div>
    <div style="left:200px;top:88px;position:absolute">
        <img src="assets/images/text2.png" />
    </div>
    <div style="left:85px;top:166px;position:absolute">
        <img src="assets/images/text3.png" />
    </div>
</body>
</code>```

JavaScript

```<code>var unsortedElements = [];
        var sortedElements = [];

        var elements = document.querySelectorAll("body > div");
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (element != null) {
                unsortedElements.push(element);

                var x = element.offsetLeft;
                var y = element.offsetTop;
                customSort(unsortedElements[i]);
            }
        }

function customSort(element){
var left = element.offsetLeft;

sortedElements.push(left);
console.log(sortedElements); -> will return the left values (40,85,200) BUT i need this array sorted with div tags (like [<div style="left: 40px;">img child</div>, <div style="left: 85px;">img child</div>, <div style="left: 200px;">img child</div>])

}
</code>```

Note

Pure Javascript please!

Thank you :)

答:
With ES6, you get a new bunch of functions to have the job done more elegantly.
For the purpose of that update, i'm just going to sort for the left property.
I guess the replacement of a comparator function is straightforward from now on.

HTML

```<code><caption>Sorting by left offset</caption>
<div id="container" style="position:relative">
    <div class="candidate" style="left:200px;top:88px;position:absolute">
        <span>3 was 1 before sorting</span>
    </div>
    <div class="candidate" style="left:40px;top:10px;position:absolute">
        <span>1 was 2 before sorting</span>
    </div>
    <div class="candidate" style="left:85px;top:166px;position:absolute">
        <span>2 was 3 before sorting</span>
    </div>
</div>
</code>```

Pure JavaScript / EcmaScript 2015

```<code>Array.from(document.querySelectorAll("div.candidate")).sort(function(a, b){
    let aLeft = a.style.left.replace("px","");
    let bLeft = b.style.left.replace("px","");
    return aLeft-bLeft;
}).forEach(function(el){
    document.querySelectorAll("#container")[0].appendChild(el);
});
</code>```

JSFiddle
http://jsfiddle.net/a4e41pmr/

I used appendChild as a trick to move the nodes once sorted.

Body:
I have got an array with DOM tags (div -> children img -> div closed). Those tags has attributes (left and top values). I added em as nodeLists so i can access elements offsetLeft and offsetTop to determine those values but i cant figurate out how to rearange those tags in the array ascending by left or top values.

HTML

JavaScript

var unsortedElements = [];
        var sortedElements = [];

        var elements = document.querySelectorAll("body > div");
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (element != null) {
                unsortedElements.push(element);

                var x = element.offsetLeft;
                var y = element.offsetTop;
                customSort(unsortedElements[i]);
            }
        }

function customSort(element){
var left = element.offsetLeft;

sortedElements.push(left);
console.log(sortedElements); -> will return the left values (40,85,200) BUT i need this array sorted with div tags (like [
img child
,
img child
,
img child
])

}

Note

Pure Javascript please!

Thank you :)

Body:
With ES6, you get a new bunch of functions to have the job done more elegantly.
For the purpose of that update, i'm just going to sort for the left property.
I guess the replacement of a comparator function is straightforward from now on.

HTML

<caption>Sorting by left offset</caption>
<div id="container" style="position:relative">
    <div class="candidate" style="left:200px;top:88px;position:absolute">
        <span>3 was 1 before sorting</span>
    </div>
    <div class="candidate" style="left:40px;top:10px;position:absolute">
        <span>1 was 2 before sorting</span>
    </div>
    <div class="candidate" style="left:85px;top:166px;position:absolute">
        <span>2 was 3 before sorting</span>
    </div>
</div>

Pure JavaScript / EcmaScript 2015

Array.from(document.querySelectorAll("div.candidate")).sort(function(a, b){
    let aLeft = a.style.left.replace("px","");
    let bLeft = b.style.left.replace("px","");
    return aLeft-bLeft;
}).forEach(function(el){
    document.querySelectorAll("#container")[0].appendChild(el);
});

JSFiddle
http://jsfiddle.net/a4e41pmr/

I used appendChild as a trick to move the nodes once sorted.


问:
Logstash does not read csv files from the folder (*.csv)
I'm using logstash to push log data from csv files into elastic search. This is my configuration file to push the csv files into elasticsearch.

```<code> input
  {
    file {
     path => "C:\Projects\Tools\ELK\data\CI_Report\*.csv"
     start_position =>"beginning"
  }
 }

filter {
 csv {
  columns =>["LOG_LEVEL", "TOOL_ID", "ID_ANALYSIS", "ARCH_COMP", "Files",
          "Component Analysed","Date","Tool Version"]
 separator =>","
 }
 }
output {
   elasticsearch {
   hosts => ["localhost"]
   index => "cilog_all"
}
 stdout {
  codec => json
 }
}
</code>```

This is my command to start the logstash, logstash -f logcsv.conf

Note : It works If I use the actual file path to a single csv file. It never works if I use *.csv to load log data from all csv files located in the specified folder.

Is Glob pattern supported by logstash input plugin ? as mentioned here
https://www.elastic.co/guide/en/logstash/current/glob-support.html

答:
Everything looks ok save for your path.
Being windows you need to change the path to this as \ is an escape character</p>

```<code>path => "C:/Projects/Tools/ELK/data/CI_Report/*.csv"
</code>```

Body:
I'm using logstash to push log data from csv files into elastic search. This is my configuration file to push the csv files into elasticsearch.

 input
  {
    file {
     path => "C:\Projects\Tools\ELK\data\CI_Report\*.csv"
     start_position =>"beginning"
  }
 }

filter {
 csv {
  columns =>["LOG_LEVEL", "TOOL_ID", "ID_ANALYSIS", "ARCH_COMP", "Files",
          "Component Analysed","Date","Tool Version"]
 separator =>","
 }
 }
output {
   elasticsearch {
   hosts => ["localhost"]
   index => "cilog_all"
}
 stdout {
  codec => json
 }
}

This is my command to start the logstash, logstash -f logcsv.conf

Note : It works If I use the actual file path to a single csv file. It never works if I use *.csv to load log data from all csv files located in the specified folder.

Is Glob pattern supported by logstash input plugin ? as mentioned here
https://www.elastic.co/guide/en/logstash/current/glob-support.html

Body:
Everything looks ok save for your path.
Being windows you need to change the path to this as \ is an escape character

path => "C:/Projects/Tools/ELK/data/CI_Report/*.csv"


答:
Question 1 Solution using a recursive floodfill algorithm:

See the floodfill algorithm in this JavaScript demonstration I made. GitHub Source.

I created a floodfill function first that works just like a paint program i.e. when given a point in an enclosed region, will fill in that region up to the border with a colour.

Then, all that needed to be done was to go through each red pixel (value 1) and floodfill up to green pixels (value 2) with the colour of what index red dot we are on (so that we can get the regions separately later).

Then, we simply use a version of your red_dots program that I modified to be a bit more generalised to get the result of all the coordinates of the white pixels.

This last step is done in a one-liner. It converts everything to a big list  where each sub-list contains coordinates of a region of white pixels.

Note how we must end with a list at the end as this is not a rectangular shape so cannot use a numpy array (unless we use dtype=object).

Anyway, here is the code:

```<code>import numpy as np

def inArrBounds(arr, c):
    return 0 <= c[0] < arr.shape[1] and 0 <= c[1] < arr.shape[0]

def floodfill(arr, start, fillCol, edgeCol):
    if arr[start[1],start[0]] in (fillCol, edgeCol):
        return
    arr[start[1], start[0]] = fillCol
    for p in ((start[0]+1, start[1]),
              (start[0]-1, start[1]),
              (start[0], start[1]+1),
              (start[0], start[1]-1)):
        if inArrBounds(arr, p):
            floodfill(arr, p, fillCol, edgeCol)

def coordsLtR(arr, val):
    pnts = np.where(arr == val)
    pnts = tuple(g[np.argsort(pnts[-1])] for g in pnts)
    pnts = np.stack(pnts)[::-1].T
    return pnts

red_dots = coordsLtR(np_matrix, 1)
for i, dot in enumerate(red_dots):
    floodfill(np_matrix, dot, i+4, 2)
    np_matrix[dot[1], dot[0]] = 1

regions = [coordsLtR(np_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))]
</code>```

which creates the regions list as:

```<code>[[17, 0], [18, 0], [20, 0], [21, 0], [22, 0], [17, 1], [18, 1], [19, 1], [20, 1], [21, 1], [22, 1], [18, 2], [19, 2], [20, 2], [21, 2]]
[[4, 7], [6, 7], [5, 7], [3, 8], [7, 8], [6, 8], [5, 8], [6, 9], [7, 9], [5, 9], [4, 9], [3, 9], [5, 10], [4, 10], [3, 10], [6, 10], [7, 10], [5, 11], [6, 11], [4, 11]]
[[28, 11], [29, 11], [29, 12], [28, 12], [27, 13], [29, 13], [28, 13], [27, 14], [28, 14], [29, 15], [28, 15], [27, 15], [27, 16], [29, 16], [28, 16], [28, 17], [29, 17], [27, 17], [28, 18], [29, 18]]
[]
[[0, 23], [0, 24], [1, 24], [1, 25], [0, 26], [1, 26], [0, 27], [1, 27], [0, 28], [1, 28], [0, 29], [1, 29], [0, 30], [1, 30], [0, 31], [1, 31]]
[[29, 28], [28, 29], [29, 29], [28, 30], [29, 30], [27, 31], [28, 31]]
</code>```

And to just visualise what the filled regions in np_matrix looks like, here is a screenshot from a matplotlib plot:

Question 2 Solution

The logic remains the same for this second section, just we have to do things in the right order. The way I would go about doing this would be to floodfill to the black borders with one colour and then subtract the white regions and green borders from this.

So, we need to work with a separate np_matrix as to not interfere with the first one. A copy can be made using np.copy.

We then need to fill in to the black border from the red dots and then from this filled in region, subtract all the coordinates that are in the white region or are green.

So, using the same functions from above, here is the code:

```<code>def validBlackCoord(c):
    return not (any(c in s for s in white_regions) or np_matrix[c[0],c[1]] == 2)

red_dots = coordsLtR(np_matrix, 1)
white_matrix = np.copy(np_matrix)
for i, dot in enumerate(red_dots):
    floodfill(white_matrix, dot, i+4, 2)
    white_matrix[dot[1], dot[0]] = 1

white_regions = [coordsLtR(white_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))]

black_matrix = np.copy(np_matrix)
for i, dot in enumerate(red_dots):
    floodfill(black_matrix, dot, i+4, 3)
    black_matrix[dot[1], dot[0]] = 1

black_regions = [coordsLtR(black_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))]

black_regions = [list(filter(key=validBlackCoord, r)) for r in black_regions]
</code>```

which creates both lists, white_regions is the same as above and black_regions is:

```<code>[[12, 0], [24, 0], [15, 0], [25, 0], [14, 0], [13, 0], [26, 0], [24, 1], [15, 1], [14, 1], [25, 1], [13, 1], [12, 1], [26, 1], [24, 2], [25, 2], [26, 2], [12, 2], [15, 2], [13, 2], [14, 2], [24, 3], [14, 3], [15, 3], [23, 3], [16, 3], [13, 3], [25, 3], [22, 4], [19, 4], [21, 4], [15, 4], [17, 4], [23, 4], [25, 4], [20, 4], [18, 4], [24, 4], [16, 4], [22, 5], [21, 5], [20, 5], [18, 5], [23, 5], [19, 5]]
[[0, 4], [6, 4], [5, 4], [4, 4], [3, 4], [2, 4], [1, 4], [8, 5], [7, 5], [6, 5], [4, 5], [3, 5], [2, 5], [5, 5], [1, 5], [0, 5], [1, 6], [3, 6], [9, 6], [0, 6], [7, 6], [8, 6], [2, 6], [8, 7], [9, 7], [2, 7], [10, 7], [0, 7], [1, 7], [0, 8], [1, 8], [9, 8], [11, 8], [10, 8], [0, 9], [1, 9], [11, 9], [10, 9], [9, 9], [1, 10], [10, 10], [0, 10], [9, 10], [11, 10], [10, 11], [9, 11], [8, 11], [11, 11], [1, 11], [2, 11], [0, 11], [0, 12], [1, 12], [10, 12], [9, 12], [2, 12], [8, 12], [3, 12], [7, 12], [2, 13], [6, 13], [3, 13], [4, 13], [1, 13], [8, 13], [0, 13], [9, 13], [7, 13], [5, 13], [6, 14], [1, 14], [0, 14], [7, 14], [2, 14], [8, 14], [4, 14], [3, 14], [5, 14], [6, 15], [2, 15], [0, 15], [1, 15], [5, 15], [3, 15], [4, 15]]
[]
[[14, 16], [15, 16], [16, 16], [18, 17], [17, 17], [15, 17], [16, 17], [14, 17], [18, 18], [19, 18], [14, 18], [13, 18], [19, 19], [18, 19], [20, 19], [13, 19], [14, 19], [19, 20], [18, 20], [14, 20], [18, 21], [19, 21], [17, 21], [15, 21], [16, 21], [14, 21], [15, 22], [17, 22], [18, 22], [16, 22], [14, 22]]
[[0, 21], [2, 21], [1, 21], [3, 22], [2, 22], [3, 23], [3, 24], [3, 25], [3, 26], [4, 26], [4, 27], [3, 27], [4, 28], [3, 28], [3, 29], [4, 29], [3, 30], [4, 30], [3, 31], [4, 31]]
[[25, 25], [29, 25], [26, 25], [28, 25], [27, 25], [25, 26], [29, 26], [28, 26], [26, 26], [27, 26], [27, 27], [25, 27], [26, 27], [26, 28], [25, 28], [26, 29], [25, 29], [25, 30], [25, 31]]
</code>```

Title: Get all coordinates points within known boundaries in a numpy matrix for each dot

Body:
Given the following numpy matrix

import numpy as np

np_matrix = np.array(
[[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,0,0,1,0,0,0,0,0,0]
,[0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,3,0,2,2,0,0,0,0,0,0,0,0]
,[0,0,0,3,0,0,0,0,2,2,2,0,0,0,0,0,3,0,0,0,3,0,0,2,2,2,2,2,2,2,2,2]
,[0,0,0,3,0,0,0,2,0,0,0,2,0,0,0,0,3,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,3,0,0,2,0,1,0,0,0,2,0,0,0,3,0,0,0,0,3,3,3,3,3,0,0,0,0,0,0]
,[0,0,0,3,0,0,2,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3]
,[0,0,0,3,0,0,2,0,0,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,0,0,2,0,0,0,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,0,0,0,2,2,2,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,3,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[3,3,3,3,0,0,0,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,3,0,0,0,0,3,3,3,3,0,0,0,0,0,3,3,3,3,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,3,0,0,3,3,3,3,0,0,0,0,0,0,0,0]
,[0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,2,2,2,0,0,3,0,0,0,0,0,0,0,0]
,[2,2,2,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,2,1,2,0,0,3,0,0,0,0,0,0,0,0]
,[0,0,2,2,0,3,3,0,0,0,0,0,0,0,0,3,3,0,2,2,2,0,0,3,0,0,0,0,0,0,0,0]
,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,3,0,0,0,0,0,0,3,0,0,0,0,0,0,0,0]
,[1,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,3,0,0,0,0,0,0,0,0,0]
,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,3,3,0,3,3,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,2,2,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[2,2,2,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
,[0,0,0,0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,3,3,3,3,3,3]
,[0,0,0,0,0,3,0,0,0,0,0,0,3,3,3,3,3,3,3,3,0,0,0,0,3,0,0,0,0,0,0,0]
,[0,0,0,3,3,0,0,0,0,3,3,3,3,2,2,2,2,2,2,3,3,0,0,0,3,0,0,0,0,0,2,2]
,[3,3,3,3,0,0,0,0,0,3,2,2,2,0,0,0,0,0,2,2,3,0,0,0,3,0,0,0,2,2,2,0]
,[0,0,0,0,0,0,0,0,0,3,2,0,0,0,0,0,0,0,0,2,3,0,0,0,3,0,0,2,2,0,0,0]
,[0,0,0,0,0,0,0,0,0,3,2,0,0,0,1,0,0,0,0,2,3,0,0,0,3,0,0,2,0,0,0,1]]
)

Which can be presented visually in a picture like this:

Where the red dots are numbered from left to right and can be identified in the matrix using the following function. Thanks to @DanielF in this answer

def getRedDotsCoordinatesFromLeftToRight(np_matrix, red_dor_number=1):
    red_dots = np.where(np_matrix == red_dor_number)
    red_dots = tuple(g[np.argsort(red_dots[-1])] for g in red_dots)
    red_dots = np.stack(red_dots)[::-1].T
    return red_dots

red_dots = getRedDotsCoordinatesFromLeftToRight(np_matrix)
print(red_dots)

red_dots = np.array(
    [[ 0, 25],
    [ 4,  8],
    [16, 19],
    [19,  0],
    [29, 14],
    [29, 31]]
)

Two questions:

Question 1: How can we identify all the white points coordinates (marked with
0) within the green boundaries (marked with 2) which are located with red dots (marked with 1) ?

Question 2:  How can we identify all the white points coordinates (marked with
0) between black boundaries (marked with 3)  and the green
boundaries (marked with 2) which are located with red dots (marked
with 1) ?

I am looking for this result for this example matrix:

space_within_greenDots = np.array(
    [[[17,  0], [17,  1], [18,  0], [18,  1], [18,  2], [19,  1], [19,  2], [20,  0], [20,  1], [20,  2], [21,  0], [21,  1], [21,  2], [22,  0], [22,  1]],
    [[ 3,  8], [ 3,  9], [ 3, 10], [ 4,  7], [ 4,  9], [ 4, 10], [ 4, 11], [ 5,  7], [ 5,  8], [ 5,  9], [ 5, 10], [ 5, 11], [ 6,  7], [ 6,  8], [ 6,  9], [ 6, 10], [ 6, 11], [ 7,  8], [ 7,  9], [ 7, 10]],
    [[27, 13], [27, 14], [27, 15], [27, 16], [27, 17], [28, 11], [28, 12], [28, 13], [28, 14], [28, 15], [28, 16], [28, 17], [28, 18], [29, 11], [29, 12], [29, 13], [29, 15], [29, 16], [29, 17], [29, 18]],
    [],
    [[ 0, 23], [ 0, 24], [ 0, 26], [ 0, 27], [ 0, 28], [ 0, 29], [ 0, 30], [ 0, 31], [ 1, 24], [ 1, 25], [ 1, 26], [ 1, 27], [ 1, 28], [ 1, 29], [ 1, 30], [ 1, 31]],
    [[27, 31], [28, 29], [28, 30], [28, 31], [29, 28], [29, 29], [29, 30]]],
)

space_between_darkDots_and_greenDots = np.array(
    [ [[12,  0], [12,  1], [12,  2], [13,  0], [13,  1], [13,  2], [13,  3], [14,  0], [14,  1], [14,  2], [14,  3], [15,  0], [15,  1], [15,  2], [15,  3], [15,  4], [16,  3], [16,  4], [17,  4], [18,  4], [18,  5], [19,  4], [19,  5], [20,  4], [20,  5], [21,  4], [21,  5], [22,  4], [22,  5], [23,  3], [23,  4], [23,  5], [24,  0], [24,  1], [24,  2], [24,  3], [24,  4], [25,  0], [25,  1], [25,  2], [25,  3], [25,  4], [26,  0], [26,  1], [26,  2]],
    [[ 0,  4], [ 0,  5], [ 0,  6], [ 0,  7], [ 0,  8], [ 0,  9], [ 0, 10], [ 0, 11], [ 0, 12], [ 0, 13], [ 0, 14], [ 0, 15], [ 1,  4], [ 1,  5], [ 1,  6], [ 1,  7], [ 1,  8], [ 1,  9], [ 1, 10], [ 1, 11], [ 1, 12], [ 1, 13], [ 1, 14], [ 1, 15], [ 2,  4], [ 2,  5], [ 2,  6], [ 2,  7], [ 2, 11], [ 2, 12], [ 2, 13], [ 2, 14], [ 2, 15], [ 3,  4], [ 3,  5], [ 3,  6], [ 3, 12], [ 3, 13], [ 3, 14], [ 3, 15], [ 4,  4], [ 4,  5], [ 4, 13], [ 4, 14], [ 4, 15], [ 5,  4], [ 5,  5], [ 5, 13], [ 5, 14], [ 5, 15], [ 6,  4], [ 6,  5], [ 6, 13], [ 6, 14], [ 6, 15], [ 7,  5], [ 7,  6], [ 7, 12], [ 7, 13], [ 7, 14], [ 8,  5], [ 8,  6], [ 8,  7], [ 8, 11], [ 8, 12], [ 8, 13], [ 8, 14], [ 9,  6], [ 9,  7], [ 9,  8], [ 9,  9], [ 9, 10], [ 9, 11], [ 9, 12], [ 9, 13], [10,  7], [10,  8], [10,  9], [10, 10], [10, 11], [10, 12], [11,  8], [11,  9], [11, 10], [11, 11]],
    [],
    [[13, 18], [13, 19], [14, 16], [14, 17], [14, 18], [14, 19], [14, 20], [14, 21], [14, 22], [15, 16], [15, 17], [15, 21], [15, 22], [16, 16], [16, 17], [16, 21], [16, 22], [17, 17], [17, 21], [17, 22], [18, 17], [18, 18], [18, 19], [18, 20], [18, 21], [18, 22], [19, 18], [19, 19], [19, 20], [19, 21], [20, 19]],
    [[ 0, 21], [ 1, 21], [ 2, 21], [ 2, 22], [ 3, 22], [ 3, 23], [ 3, 24], [ 3, 25], [ 3, 26], [ 3, 27], [ 3, 28], [ 3, 29], [ 3, 30], [ 3, 31], [ 4, 26], [ 4, 27], [ 4, 28], [ 4, 29], [ 4, 30], [ 4, 31]],
    [[25, 25], [25, 26], [25, 27], [25, 28], [25, 29], [25, 30], [25, 31], [26, 25], [26, 26], [26, 27], [26, 28], [26, 29], [27, 25], [27, 26], [27, 27], [28, 25], [28, 26], [29, 25], [29, 26]],
    ]
)

A few assumptions:

The matrix shape can vary. It is not a fixed size.

The number of red dots varies from matrix to matrix. But there is
always at least one red dot in the matrix.¨

Body:
Question 1 Solution using a recursive floodfill algorithm:

See the floodfill algorithm in this JavaScript demonstration I made. GitHub Source.

I created a floodfill function first that works just like a paint program i.e. when given a point in an enclosed region, will fill in that region up to the border with a colour.

Then, all that needed to be done was to go through each red pixel (value 1) and floodfill up to green pixels (value 2) with the colour of what index red dot we are on (so that we can get the regions separately later).

Then, we simply use a version of your red_dots program that I modified to be a bit more generalised to get the result of all the coordinates of the white pixels.

This last step is done in a one-liner. It converts everything to a big list  where each sub-list contains coordinates of a region of white pixels.

Note how we must end with a list at the end as this is not a rectangular shape so cannot use a numpy array (unless we use dtype=object).

Anyway, here is the code:

import numpy as np

def inArrBounds(arr, c):
    return 0 <= c[0] < arr.shape[1] and 0 <= c[1] < arr.shape[0]

def floodfill(arr, start, fillCol, edgeCol):
    if arr[start[1],start[0]] in (fillCol, edgeCol):
        return
    arr[start[1], start[0]] = fillCol
    for p in ((start[0]+1, start[1]),
              (start[0]-1, start[1]),
              (start[0], start[1]+1),
              (start[0], start[1]-1)):
        if inArrBounds(arr, p):
            floodfill(arr, p, fillCol, edgeCol)

def coordsLtR(arr, val):
    pnts = np.where(arr == val)
    pnts = tuple(g[np.argsort(pnts[-1])] for g in pnts)
    pnts = np.stack(pnts)[::-1].T
    return pnts

red_dots = coordsLtR(np_matrix, 1)
for i, dot in enumerate(red_dots):
    floodfill(np_matrix, dot, i+4, 2)
    np_matrix[dot[1], dot[0]] = 1

regions = [coordsLtR(np_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))]

which creates the regions list as:

[[17, 0], [18, 0], [20, 0], [21, 0], [22, 0], [17, 1], [18, 1], [19, 1], [20, 1], [21, 1], [22, 1], [18, 2], [19, 2], [20, 2], [21, 2]]
[[4, 7], [6, 7], [5, 7], [3, 8], [7, 8], [6, 8], [5, 8], [6, 9], [7, 9], [5, 9], [4, 9], [3, 9], [5, 10], [4, 10], [3, 10], [6, 10], [7, 10], [5, 11], [6, 11], [4, 11]]
[[28, 11], [29, 11], [29, 12], [28, 12], [27, 13], [29, 13], [28, 13], [27, 14], [28, 14], [29, 15], [28, 15], [27, 15], [27, 16], [29, 16], [28, 16], [28, 17], [29, 17], [27, 17], [28, 18], [29, 18]]
[]
[[0, 23], [0, 24], [1, 24], [1, 25], [0, 26], [1, 26], [0, 27], [1, 27], [0, 28], [1, 28], [0, 29], [1, 29], [0, 30], [1, 30], [0, 31], [1, 31]]
[[29, 28], [28, 29], [29, 29], [28, 30], [29, 30], [27, 31], [28, 31]]

And to just visualise what the filled regions in np_matrix looks like, here is a screenshot from a matplotlib plot:

Question 2 Solution

The logic remains the same for this second section, just we have to do things in the right order. The way I would go about doing this would be to floodfill to the black borders with one colour and then subtract the white regions and green borders from this.

So, we need to work with a separate np_matrix as to not interfere with the first one. A copy can be made using np.copy.

We then need to fill in to the black border from the red dots and then from this filled in region, subtract all the coordinates that are in the white region or are green.

So, using the same functions from above, here is the code:

def validBlackCoord(c):
    return not (any(c in s for s in white_regions) or np_matrix[c[0],c[1]] == 2)

red_dots = coordsLtR(np_matrix, 1)
white_matrix = np.copy(np_matrix)
for i, dot in enumerate(red_dots):
    floodfill(white_matrix, dot, i+4, 2)
    white_matrix[dot[1], dot[0]] = 1

white_regions = [coordsLtR(white_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))]

black_matrix = np.copy(np_matrix)
for i, dot in enumerate(red_dots):
    floodfill(black_matrix, dot, i+4, 3)
    black_matrix[dot[1], dot[0]] = 1

black_regions = [coordsLtR(black_matrix,i+4)[:,::-1].tolist() for i in range(len(red_dots))]

black_regions = [list(filter(key=validBlackCoord, r)) for r in black_regions]

which creates both lists, white_regions is the same as above and black_regions is:

[[12, 0], [24, 0], [15, 0], [25, 0], [14, 0], [13, 0], [26, 0], [24, 1], [15, 1], [14, 1], [25, 1], [13, 1], [12, 1], [26, 1], [24, 2], [25, 2], [26, 2], [12, 2], [15, 2], [13, 2], [14, 2], [24, 3], [14, 3], [15, 3], [23, 3], [16, 3], [13, 3], [25, 3], [22, 4], [19, 4], [21, 4], [15, 4], [17, 4], [23, 4], [25, 4], [20, 4], [18, 4], [24, 4], [16, 4], [22, 5], [21, 5], [20, 5], [18, 5], [23, 5], [19, 5]]
[[0, 4], [6, 4], [5, 4], [4, 4], [3, 4], [2, 4], [1, 4], [8, 5], [7, 5], [6, 5], [4, 5], [3, 5], [2, 5], [5, 5], [1, 5], [0, 5], [1, 6], [3, 6], [9, 6], [0, 6], [7, 6], [8, 6], [2, 6], [8, 7], [9, 7], [2, 7], [10, 7], [0, 7], [1, 7], [0, 8], [1, 8], [9, 8], [11, 8], [10, 8], [0, 9], [1, 9], [11, 9], [10, 9], [9, 9], [1, 10], [10, 10], [0, 10], [9, 10], [11, 10], [10, 11], [9, 11], [8, 11], [11, 11], [1, 11], [2, 11], [0, 11], [0, 12], [1, 12], [10, 12], [9, 12], [2, 12], [8, 12], [3, 12], [7, 12], [2, 13], [6, 13], [3, 13], [4, 13], [1, 13], [8, 13], [0, 13], [9, 13], [7, 13], [5, 13], [6, 14], [1, 14], [0, 14], [7, 14], [2, 14], [8, 14], [4, 14], [3, 14], [5, 14], [6, 15], [2, 15], [0, 15], [1, 15], [5, 15], [3, 15], [4, 15]]
[]
[[14, 16], [15, 16], [16, 16], [18, 17], [17, 17], [15, 17], [16, 17], [14, 17], [18, 18], [19, 18], [14, 18], [13, 18], [19, 19], [18, 19], [20, 19], [13, 19], [14, 19], [19, 20], [18, 20], [14, 20], [18, 21], [19, 21], [17, 21], [15, 21], [16, 21], [14, 21], [15, 22], [17, 22], [18, 22], [16, 22], [14, 22]]
[[0, 21], [2, 21], [1, 21], [3, 22], [2, 22], [3, 23], [3, 24], [3, 25], [3, 26], [4, 26], [4, 27], [3, 27], [4, 28], [3, 28], [3, 29], [4, 29], [3, 30], [4, 30], [3, 31], [4, 31]]
[[25, 25], [29, 25], [26, 25], [28, 25], [27, 25], [25, 26], [29, 26], [28, 26], [26, 26], [27, 26], [27, 27], [25, 27], [26, 27], [26, 28], [25, 28], [26, 29], [25, 29], [25, 30], [25, 31]]


问:
Filtering rows and columns with respect to one column data
How to select the data (highlighted) based on the values of the first column. I mean I need to select data starting and ending with specific time as I don't know the data in S08, S09 and so on.

After this I will take the mean() of first 100 values of each column and then so on.

```<code>g3=df.loc[(df.timeInterval>=171) & (df.timeInterval<=174) & (df.timeInterval>=181) & (df.timeInterval<=184) & (df.timeInterval>=191) & (df.timeInterval<=194) & (df.timeInterval>=201) & (df.timeInterval<=204),['S08','S09','S41']]
g3
</code>```

答:
I'm having trouble getting pandas indexing to work as expected, but do you mean something like this?</p>

```<code>df = pd.DataFrame(np.array(np.random.rand(10, 2)), columns = ['timeInterval', 'value'])

df2 = df['value'][df.timeInterval >= 0.3][df.timeInterval <= 0.7]
df2
</code>```

Body:
How to select the data (highlighted) based on the values of the first column. I mean I need to select data starting and ending with specific time as I don't know the data in S08, S09 and so on.

After this I will take the mean() of first 100 values of each column and then so on.

g3=df.loc[(df.timeInterval>=171) & (df.timeInterval<=174) & (df.timeInterval>=181) & (df.timeInterval<=184) & (df.timeInterval>=191) & (df.timeInterval<=194) & (df.timeInterval>=201) & (df.timeInterval<=204),['S08','S09','S41']]
g3

Body:
I'm having trouble getting pandas indexing to work as expected, but do you mean something like this?

df = pd.DataFrame(np.array(np.random.rand(10, 2)), columns = ['timeInterval', 'value'])

df2 = df['value'][df.timeInterval >= 0.3][df.timeInterval <= 0.7]
df2


问:
React-native Fetch with dynamic params
I need to make a request where I pass parameters in the URL that are dynamic. First I display a list of stores and when the user clicks on an I show the details of it, for this I am using the code below, but even after trying too much I can not get the id.

TypeError: undefined is not an object (evaluating '_this.props.navigation')

This is my service:

import api from '../../../config/api';

export const fetchGetById = () => {
  return (
    fetch(`${api.API_URL}stores/v1/getById?id=${this.props.navigation.state.params.id}`, {
      method: 'get',
      headers: {
        mall: api.API_MALL,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then(res => res.json())
      .then(data => data.result.store)
      .catch(err => err)
  );
}

export default fetchGetById;```
</div>
</div>
</p>

<p>This is my component, in ID: { this.props.navigation.state.params.id } i get params.id correctly:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
import {
  View,
  Text,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Styles from './view-component-styles';
import Theme from '../../../config/theme';

type Props = {
  error: boolean,
  loading: boolean,
  data: Object,
  fetchData: Function,
};

class ViewComponent extends Component<Props> {

  constructor() {
    super();
    this.goToPage = this.goToPage.bind(this);
  }

  componentDidMount() {
    this.props.fetchData();
  }

  goToPage(param, id) {
    this.props.navigation.navigate(param, { id: id });
  }

  render() {
    const hasData = Object.keys(this.props.data).length;

    const errorMessage = () => {
      return (
        <Text>Ops! Ocorreu um erro ao carregar os dados.</Text>
      );
    };

    const renderLoading = () => {
      return (
        <View style={Styles.renderLoading}>
          <ActivityIndicator color={Theme.color.secondary} size="large" />
          <Text style={Theme.text}>Aguarde</Text>
        </View>
      );
    };

    const getData = (data) => {
      return (
        <View>
          <Text>ID: { this.props.navigation.state.params.id }</Text>
          <Text>{ data.fantasy_name }</Text>
        </View>
      );
    };

    return (
      <View style={Styles.container}>
        { this.props.loading ? renderLoading() : null }
        { this.props.error ? errorMessage() : null }
        { hasData ? getData(this.props.data) : null }
      </View>
    );
  }
}

export default ViewComponent;</code>```

答:
You can try used</p>

```<code>export const fetchGetById = ( myid ) => {
  return (
    fetch(`${api.API_URL}stores/v1/getById?id=myid`, {
      method: 'get',
      headers: {
        mall: api.API_MALL,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then(res => res.json())
      .then(data => data.result.store)
      .catch(err => err)
  );
}
</code>```

Title: React-native Fetch with dynamic params

Body:
I need to make a request where I pass parameters in the URL that are dynamic. First I display a list of stores and when the user clicks on an I show the details of it, for this I am using the code below, but even after trying too much I can not get the id.

TypeError: undefined is not an object (evaluating '_this.props.navigation')

This is my service:

import api from '../../../config/api';

export const fetchGetById = () => {
  return (
    fetch(`${api.API_URL}stores/v1/getById?id=${this.props.navigation.state.params.id}`, {
      method: 'get',
      headers: {
        mall: api.API_MALL,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then(res => res.json())
      .then(data => data.result.store)
      .catch(err => err)
  );
}

export default fetchGetById;

This is my component, in ID: { this.props.navigation.state.params.id } i get params.id correctly:

import React, { Component } from 'react';
import {
  View,
  Text,
  ActivityIndicator,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import Styles from './view-component-styles';
import Theme from '../../../config/theme';

type Props = {
  error: boolean,
  loading: boolean,
  data: Object,
  fetchData: Function,
};

class ViewComponent extends Component<Props> {

  constructor() {
    super();
    this.goToPage = this.goToPage.bind(this);
  }

  componentDidMount() {
    this.props.fetchData();
  }

  goToPage(param, id) {
    this.props.navigation.navigate(param, { id: id });
  }

  render() {
    const hasData = Object.keys(this.props.data).length;

    const errorMessage = () => {
      return (
        <Text>Ops! Ocorreu um erro ao carregar os dados.</Text>
      );
    };

    const renderLoading = () => {
      return (
        <View style={Styles.renderLoading}>
          <ActivityIndicator color={Theme.color.secondary} size="large" />
          <Text style={Theme.text}>Aguarde</Text>
        </View>
      );
    };

    const getData = (data) => {
      return (
        <View>
          <Text>ID: { this.props.navigation.state.params.id }</Text>
          <Text>{ data.fantasy_name }</Text>
        </View>
      );
    };

    return (
      <View style={Styles.container}>
        { this.props.loading ? renderLoading() : null }
        { this.props.error ? errorMessage() : null }
        { hasData ? getData(this.props.data) : null }
      </View>
    );
  }
}

export default ViewComponent;

Body:
You can try used

export const fetchGetById = ( myid ) => {
  return (
    fetch(`${api.API_URL}stores/v1/getById?id=myid`, {
      method: 'get',
      headers: {
        mall: api.API_MALL,
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
    })
      .then(res => res.json())
      .then(data => data.result.store)
      .catch(err => err)
  );
}


问:
Ordering a list of lists by lists len
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

```<code> orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else:
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1

 return orderedpaths
</code>```

the error I'm getting is:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax
</code>```

I have no idea why.

答:
As stated in eumiro's answer using sorted() is the way to go.

Note that sorted() (as well as list.sort(key=..)) was only introduced in Python 2.4. If you're in my boat and have to make do with <2.4, you could create your own version. Rough example:

```<code>import inspect
def my_sorted(in_list, key=lambda x:x):

    # basic error checking
    if not is_instance(in_list, list):
        raise ValueError("expecting 1st argument to be a list")

    if not inspect.isroutine(key):
        raise ValueError("key must be a function/method")

    # convert to [ (key(item1), item1), .... ]
    key_map = map(lambda x: (key(x),x), in_list)
    # standard sort, while effectively sort by key(item)
    key_map.sort()

    # convert back original format and return
    return [x for _,x in key_map]
</code>```

You can then use it as such:

```<code>orderedpaths = my_sorted(paths, key=len)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Ordering a list of lists by lists len

Body:
I'm trying to order a list of lists by len size. But I'm getting a weird syntax error. I'm new to python so I'm probably doing something wrong

Relevant part of the code:

 orderedpaths=[]
 if(len(paths)==1):
  orderedpaths=paths
 else:
  c=0
  while(len(paths)!=0):

   if(c==0):
    smallest=(len(paths[c])
    c+=1

   else:
    if(len[paths[c])<smallest):
     smallest=(len(paths[c]))
     orderedpaths.append(paths[c])
     del paths[c]
     c+=1

 return orderedpaths

the error I'm getting is:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 153
    c+=1
    ^
SyntaxError: invalid syntax

I have no idea why.

Body:
As stated in eumiro's answer using sorted() is the way to go.

Note that sorted() (as well as list.sort(key=..)) was only introduced in Python 2.4. If you're in my boat and have to make do with <2.4, you could create your own version. Rough example:

import inspect
def my_sorted(in_list, key=lambda x:x):

    # basic error checking
    if not is_instance(in_list, list):
        raise ValueError("expecting 1st argument to be a list")

    if not inspect.isroutine(key):
        raise ValueError("key must be a function/method")

    # convert to [ (key(item1), item1), .... ]
    key_map = map(lambda x: (key(x),x), in_list)
    # standard sort, while effectively sort by key(item)
    key_map.sort()

    # convert back original format and return
    return [x for _,x in key_map]

You can then use it as such:

orderedpaths = my_sorted(paths, key=len)


问:
Can I file_put_contents to send to an http web address?
I'm trying to have an event trigger that once it does it sends the content to a text file from another web address that I should have access to. I've tried the code below but it will not allow me to do so, the error report reads,

"failed to open stream: HTTP wrapper does not support writeable
  connections in /data/custom/test-alarm-upload.php on line 36"

Is this even possible to do in php?

```<code><?php

if (file_exists($myFile))
{
    $fh = fopen($myFile, 'r');
    $Gas_Seperator = fread($fh, 12);
    fclose($fh);
    $Gas_Seperator = ereg_replace("[^0-9.-]", "", $Gas_Seperator);
    $Gas_Seperator = ($Gas_Seperator * 25) - 12.5;
}

$theday = date (j);
$themonth = date (F);
$theyear = date (Y);
$thetime = date (g);
$theAMPM = date (A);
$thest = date (S);

$entry ="\n" . $themonth . " " . $theday . "" . $thest . " " . $thetime . "" . $theAMPM . "," . $Gas_Seperator;

file_put_contents('http://XXX.XXX.XXX.XXX/data/custom/alarm.txt' , $entry, FILE_APPEND);
?>
</code>```

答:
You cant do so using HTTP protocole. You can do it using FTP.
Here is a sample of code to open and write file overt FTP.

```<code>$content = "Here is my content";
$fp = fopen("ftp://username:password@host/data/custom/alarm.txt","w");
fwrite($fp, $content);
fclose($fp);
</code>```

Host can be IP address or just domain name. Another way is that you can create on the second server a WebService that will do the Job. So when event triggers you just call the WebService that will do the Job.

Body:
I'm trying to have an event trigger that once it does it sends the content to a text file from another web address that I should have access to. I've tried the code below but it will not allow me to do so, the error report reads,

"failed to open stream: HTTP wrapper does not support writeable
  connections in /data/custom/test-alarm-upload.php on line 36"

Is this even possible to do in php?

<?php

if (file_exists($myFile))
{
    $fh = fopen($myFile, 'r');
    $Gas_Seperator = fread($fh, 12);
    fclose($fh);
    $Gas_Seperator = ereg_replace("[^0-9.-]", "", $Gas_Seperator);
    $Gas_Seperator = ($Gas_Seperator * 25) - 12.5;
}

$theday = date (j);
$themonth = date (F);
$theyear = date (Y);
$thetime = date (g);
$theAMPM = date (A);
$thest = date (S);

$entry ="\n" . $themonth . " " . $theday . "" . $thest . " " . $thetime . "" . $theAMPM . "," . $Gas_Seperator;

file_put_contents('http://XXX.XXX.XXX.XXX/data/custom/alarm.txt' , $entry, FILE_APPEND);
?>

Body:
You cant do so using HTTP protocole. You can do it using FTP.
Here is a sample of code to open and write file overt FTP.

$content = "Here is my content";
$fp = fopen("ftp://username:password@host/data/custom/alarm.txt","w");
fwrite($fp, $content);
fclose($fp);

Host can be IP address or just domain name. Another way is that you can create on the second server a WebService that will do the Job. So when event triggers you just call the WebService that will do the Job.


问:
BufferedReader not reading second output
I am developing a client for a small game. Using sockets, I am parsing the request and responses with PrintWriter and BufferedReader classes.

The issue I have is when BufferedReader is used for the second time (second response from server).

Example:

```<code>public class BotClient {

private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;

public BotClient(final String gameId, final String botName) throws IOException {
    this.writer = new PrintWriter(socket.getOutputStream(), true);
    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

//Code that connects client to server. Works successfully.

public void sendGameRequest() {

try {
    //This first is the FIRST request to server. This works SUCCESSFULLY.
    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); // This will output game response successfully.

    //Now the problem occurs below here. I could do the same request but won't get an output.

    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); //EMPTY PRINT

    // The above is EXACTLY the same request however this prints out nothing.
</code>```

What could be the issue here and what is the best way to solve this problem?

答:
As i see, it is a HTTP request:

writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

It could be that after the first request the connection was closed by remote pear. So, each time that you send a request you should open the connections, send the request, wait and receive the response and close the socket.

This is an extractor from the book: Http Definitive Guide by David Gourley and Brian Totty.

Before send the second request check if the socket is open, if not, open it again and repeat the processes to send a request.

Body:
I am developing a client for a small game. Using sockets, I am parsing the request and responses with PrintWriter and BufferedReader classes.

The issue I have is when BufferedReader is used for the second time (second response from server).

Example:

public class BotClient {

private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;

public BotClient(final String gameId, final String botName) throws IOException {
    this.writer = new PrintWriter(socket.getOutputStream(), true);
    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

//Code that connects client to server. Works successfully.

public void sendGameRequest() {

try {
    //This first is the FIRST request to server. This works SUCCESSFULLY.
    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); // This will output game response successfully.

    //Now the problem occurs below here. I could do the same request but won't get an output.

    writer.println("GET " + "/playerInfo/?gameId=" + gameId + "&playerName=" + botName + " HTTP/1.0\r\n");

    reader.lines().forEach(System.out::println); //EMPTY PRINT

    // The above is EXACTLY the same request however this prints out nothing.

What could be the issue here and what is the best way to solve this problem?


问:
Rails - good way to convert string to array if not array rails
I receive a param and want it to be either a string like this :

```<code>"abc,efg"
</code>```

or an Array like this

```<code>["abc","efg"]
</code>```

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

```<code>if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")
</code>```

答:
I think the shortest way would be to use .try.  It saves you from writing out an if-then-else.

```<code>params_id = params[:id].try(:split, ',')
</code>```

Body:
I receive a param and want it to be either a string like this :

"abc,efg"

or an Array like this

["abc","efg"]

In the first case I want to convert it into an Array, what would be the good way ?

Here is what I thought

if params[:ids] && params[:ids].is_a? Array
     ids = params[:ids]
else if params[:ids]
    ids = params[:ids].split(",")

Body:
I think the shortest way would be to use .try.  It saves you from writing out an if-then-else.

params_id = params[:id].try(:split, ',')


问:
AWS cfn resource creation failed for recordset
I wanted to deploy a static website using cloudformation but I am having issues creating the record set. The stack creation was successful until the hosted zone in resource section. I'm not sure why there is an issue creating the record set for a hosted zone.

Error: The following resource(s) failed to create: [RecordSet].

```<code>        ---
AWSTemplateFormatVersion:  '2010-09-09'
Description: 'Assuming that you already have a Hosted Zone registered with Amazon Route 53, this Cfn template is to create a static site'
# Metadata:
#   'AWS::CloudFormation::Interface':
#     ParameterGroups:
#       - Label:
#           default: 'HostedZone name'
#         Parameters:
#           - HostedZoneName
Parameters:
  HostedZoneName:
    Description: "The DNS name of an existing Amazon Route 53 hosted zone"
    Type: String
    AllowedPattern: "(?!-)[a-zA-Z0-9-.]{1,63}(?<!-)"
    Default: "thecloudcrew.net"

Resources:

  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      BucketName: !Ref HostedZoneName
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
      LoggingConfiguration:
        DestinationBucketName: !Ref S3LoggingBucket
        LogFilePrefix: logs

  WWWS3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub
        -  www.${domain}
        - { domain: !Ref HostedZoneName}
      WebsiteConfiguration:
        RedirectAllRequestsTo:
          HostName: !Ref HostedZoneName

  S3LoggingBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub
        - ${domain}.logs
        - { domain: !Ref HostedZoneName}
      AccessControl: LogDeliveryWrite

  HostedZone:
    Type: "AWS::Route53::HostedZone"
    Properties:
      HostedZoneConfig:
        Comment: "My Hosted zone for thecloudcrew.net"
      HostedZoneTags:
        -
          Key: Name
          Value: thecloudcrew
      Name: !Ref HostedZoneName

  RecordSet: #FIXME
    Type: "AWS::Route53::RecordSet"
    Properties:
      AliasTarget:
        DNSName: s3-website.us-east-2.amazonaws.com
        HostedZoneId: Z2O1EMRO9K5GLX
      Comment: "RecordSet for static website"
      HostedZoneId: !Ref HostedZone  #TODO
      Name: !Ref HostedZone
      Type: A
      #Region: 'us-east-2'
      # SetIdentifier: String
      # TTL: String
      # Weight: Integer
</code>```

答: You're missing the Type: A property, you have to replace HosteZoneName by HostedZoneId. Also, remove Region it has no use in Route53 which is global.

Body:
I wanted to deploy a static website using cloudformation but I am having issues creating the record set. The stack creation was successful until the hosted zone in resource section. I'm not sure why there is an issue creating the record set for a hosted zone.

Error: The following resource(s) failed to create: [RecordSet].

        ---
AWSTemplateFormatVersion:  '2010-09-09'
Description: 'Assuming that you already have a Hosted Zone registered with Amazon Route 53, this Cfn template is to create a static site'
# Metadata:
#   'AWS::CloudFormation::Interface':
#     ParameterGroups:
#       - Label:
#           default: 'HostedZone name'
#         Parameters:
#           - HostedZoneName
Parameters:
  HostedZoneName:
    Description: "The DNS name of an existing Amazon Route 53 hosted zone"
    Type: String
    AllowedPattern: "(?!-)[a-zA-Z0-9-.]{1,63}(?<!-)"
    Default: "thecloudcrew.net"

Resources:

  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      BucketName: !Ref HostedZoneName
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
      LoggingConfiguration:
        DestinationBucketName: !Ref S3LoggingBucket
        LogFilePrefix: logs

  WWWS3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub
        -  www.${domain}
        - { domain: !Ref HostedZoneName}
      WebsiteConfiguration:
        RedirectAllRequestsTo:
          HostName: !Ref HostedZoneName

  S3LoggingBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub
        - ${domain}.logs
        - { domain: !Ref HostedZoneName}
      AccessControl: LogDeliveryWrite

  HostedZone:
    Type: "AWS::Route53::HostedZone"
    Properties:
      HostedZoneConfig:
        Comment: "My Hosted zone for thecloudcrew.net"
      HostedZoneTags:
        -
          Key: Name
          Value: thecloudcrew
      Name: !Ref HostedZoneName

  RecordSet: #FIXME
    Type: "AWS::Route53::RecordSet"
    Properties:
      AliasTarget:
        DNSName: s3-website.us-east-2.amazonaws.com
        HostedZoneId: Z2O1EMRO9K5GLX
      Comment: "RecordSet for static website"
      HostedZoneId: !Ref HostedZone  #TODO
      Name: !Ref HostedZone
      Type: A
      #Region: 'us-east-2'
      # SetIdentifier: String
      # TTL: String
      # Weight: Integer


问:
JSTL and authenticated web services
Can I access an authenticated web service using JSTL? (Form-based authentication)

If I can't do it using JSTL, is there any other way I do it from a JSP?

Maybe I need to give a little more information. I'm using the core library:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

and the import tag, as in:

<c:import var="xml" url="http://my.service.com/api/xml"/>

Where http://my.service.com/api/xml is a web service requiring form-based authentication - if I try to access it in a browser, I'm prompted for a username and password in a web form, not a popup window.

sorry, I'm no web services expert as you can tell - fingers crossed for an easy solution :)

答:
JSTL == JSP Standard Tag Library?  If so, I don't see how JSTL and JSP are different.

If you add tokens to HTML or SOAP headers, you're assuming that the web service knows how to get at them and how to consume them.  Form-based authentication uses j_username and j_password for the form element parameter names.

I'd say that security should be a cross-cutting concern.  A filter or aspect should be able to get those values out of the HTTP headers and authenticate for you.

OwnerDisplayName: Brabster

Title: JSTL and authenticated web services

LastEditorDisplayName: Brabster


问:
Unexpected -psn_0_65552 command line argument after mac reboot
When I reboot my mac, if an application that I'm developing was running during reboot, macos starts that application right after restart with "-psn_0_65552" argument. I assume that this is related to "Reopen windows when logging back in" checkbox enabled on restart prompt. I tried to find any documentation about this argument, but failed. So, my questions:

Is this behavior documented somewhere?

Any other weird command-line arguments my application should be able to handle?

Can I avoid my application reopening after mac restart?

答:
Nobody else has offered you anything yet so maybe this will help:

Is this behavior documented somewhere?

The state preservation and restoration mechanism is at least partially documented through the methods you can call to participate in it, e.g. NSWindow's restorable & encodeRestorableStateWithCoder:, NSWindowDelegate's window:willEncodeRestorableState:, NSApplication's restoreWindowWithIdentifier:state:completionHandler: etc. However how the various AppKit classes preserve and restore all the information is not publicly documented (there is a statement to that effect in the docs somewhere).

Any other weird command-line arguments my application should be able to handle?

Anybody's guess.

Can I avoid my application reopening after mac restart?

Maybe. Some apps don't restart on relaunch, whether their authors control this or its happenstance I've no idea.

Here's a suggestion: write yourself a very basic GUI app which just saves the arguments and environment (you can use NSProcessInfo to get them all) at launch time to user defaults. Lunch your app from Xcode, Finder and Terminal. Reboot while its open. Look at the user defaults (look in its sandbox and open the .plist in Xcode). Notice anything? Want to rely on it? Your call.

Can you think of others way to track your app launches and user-initiated quits? Maybe setting and removing a flag in user defaults? Have fun!

HTH


问:
Change Graphql json response Rails
This is simple query:

```<code>query {
   comment(id: 1) {
      id,
      title
   }
}
</code>```

And it result look like this:

```<code>{
   "data": {
      "comment": {
         "id": 1,
         "title": "Hello world"
      }
   }
}
</code>```

Now, i want change json result to:

```<code>{
   "id": 1,
   "title": "Hello world"
}
</code>```

I'm using rails and gem graphql-ruby. Somebody can help me!!!!

答:
If you're using the graphql-ruby gem, you should be able to just add .as_json to the end of the query after retrieving the desired data:</p>

```<code>results = client.query(hello_world_query).data.comment.as_json
</code>```

Title: Change Graphql json response Rails

Body:
This is simple query:

query {
   comment(id: 1) {
      id,
      title
   }
}

And it result look like this:

{
   "data": {
      "comment": {
         "id": 1,
         "title": "Hello world"
      }
   }
}

Now, i want change json result to:

{
   "id": 1,
   "title": "Hello world"
}

I'm using rails and gem graphql-ruby. Somebody can help me!!!!

Body:
If you're using the graphql-ruby gem, you should be able to just add .as_json to the end of the query after retrieving the desired data:

results = client.query(hello_world_query).data.comment.as_json


答:
reader.lines() is just providing a streamed view that is equivalent to calling reader.readLine() repeatedly, until the end of the file is reached.  Once you have read the entire stream, there are no more lines to read.

You will need to store the lines.  The easiest way to do this is to collect them into a List:

```<code>List<String> lines = reader.lines().collect(Collectors.toList());
lines.forEach(System.out::println);
</code>```

A warning about InputStreamReader:  Since you provided no charset, it will use the system’s default charset.  This means your code will run differently on Windows than it does on other operating systems;  a Windows machine probably will not be able to communicate with a non-Windows machine.

To make it run identically on all systems, specify an explicit charset:

```<code>    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
</code>```

Title: BufferedReader not reading second output

Body:
reader.lines() is just providing a streamed view that is equivalent to calling reader.readLine() repeatedly, until the end of the file is reached.  Once you have read the entire stream, there are no more lines to read.

You will need to store the lines.  The easiest way to do this is to collect them into a List:

List<String> lines = reader.lines().collect(Collectors.toList());
lines.forEach(System.out::println);

A warning about InputStreamReader:  Since you provided no charset, it will use the system’s default charset.  This means your code will run differently on Windows than it does on other operating systems;  a Windows machine probably will not be able to communicate with a non-Windows machine.

To make it run identically on all systems, specify an explicit charset:

    this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));


问:
is there any boilerplates for a reactjs and react-native
we are starting a new webapp using reactjs, the main reason why we chose react is because of react-native !, the app will be password protected, so we are not going to utilize and seo or server rendering features.

i find most boilerplates for react focus on universal setup yet in my case i want to structure app to sharing most amount of code possible between web and mobile apps

we started our webapp using https://github.com/mxstbr/react-boilerplate

is there a production ready boilerplate/starter that can be used in such use case ?

答:
Create React App is the best way to start building a new React single page application. It sets up your development environment so that you can use the latest JavaScript features, provides a nice developer experience, and optimizes your app for production.

Create React Native App is the easiest way to start building a new React Native application. It allows you to start a project without installing or configuring any tools to build native code - no Xcode or Android Studio installation required.


问:
Compare User Imputed Data to Pivot Table
I am attempting to use an "IF" function to compare a data value from an inventory list in a pivot table with a user editable cell next to the pivot(for a physical inventory count).

```<code>=IF(GETPIVOTDATA("CurrentInventoryQuantity",B8)=G8,TRUE,FALSE)
</code>```

This code returns an #REF! error.

I have to store the inventory data in a pivot so that it can dynamically add new rows as needed.

Any tips on how to get Excel to compare the data?

答: Try using just the cell reference instead of GetPivotData.</p>

Body:
I am attempting to use an "IF" function to compare a data value from an inventory list in a pivot table with a user editable cell next to the pivot(for a physical inventory count).

=IF(GETPIVOTDATA("CurrentInventoryQuantity",B8)=G8,TRUE,FALSE)

This code returns an #REF! error.

I have to store the inventory data in a pivot so that it can dynamically add new rows as needed.

Any tips on how to get Excel to compare the data?


问:
Why am I getting an error calling instance_eval with to_proc and not with Proc.new?
I'm doing this and it works:

```<code>class B
  def value
    "X"
  end
end

class A
  def initialize(context)
    @context = context
  end

  def m
    Proc.new do
      value
    end
  end

  def execute
    @context.instance_eval(&m)
  end
end

A.new(B.new).execute #=> "X"
</code>```

But calling m.to_proc is not working...

```<code>class B
  def value
    "X"
  end
end

class A
  def initialize(context)
    @context = context
  end

  def m
    value
  end

  def execute
    @context.instance_eval(&m.to_proc)
  end
end

A.new(B.new).execute #=> NameError: undefined local variable or method `value' for #<A:0x007fae2ab02040 @context=#<B:0x007fae2ab02108>>
</code>```

I want to know why these two examples are different and how to make it work with to_proc

答:
In the second snippet, you are calling m, which returns the result of calling value, which is undefined. (And even if if were somehow magically calling B#value, then B#value returns a String and Strings don't respond to to_proc, so you would get a NoMethodError there.) In the first snippet, you call m, which returns a Proc.

It looks like you are trying to pass the method m itself instead of the result of calling it. In Ruby, methods aren't objects, so you can't just grab them and pass them around (and even if methods were objects, then m is still the syntax for calling m, not for referencing it). You have to ask Ruby's reflection API for a reflective proxy for the method first, using the Object#method method, which returns a Method object representing the method:

```<code>@context.instance_eval(&method(:m).to_proc)
</code>```

Note that the call to to_proc is completely redundant here, since & will call to_proc anyway if the argument isn't a Proc already. (You may have seen something like foo.map(&:bar) before, which will invoke Symbol#to_proc.)

```<code>@context.instance_eval(&method(:m))
</code>```

Body:
I'm doing this and it works:

class B
  def value
    "X"
  end
end

class A
  def initialize(context)
    @context = context
  end

  def m
    Proc.new do
      value
    end
  end

  def execute
    @context.instance_eval(&m)
  end
end

A.new(B.new).execute #=> "X"

But calling m.to_proc is not working...

class B
  def value
    "X"
  end
end

class A
  def initialize(context)
    @context = context
  end

  def m
    value
  end

  def execute
    @context.instance_eval(&m.to_proc)
  end
end

A.new(B.new).execute #=> NameError: undefined local variable or method `value' for #<A:0x007fae2ab02040 @context=#>

I want to know why these two examples are different and how to make it work with to_proc

Body:
In the second snippet, you are calling m, which returns the result of calling value, which is undefined. (And even if if were somehow magically calling B#value, then B#value returns a String and Strings don't respond to to_proc, so you would get a NoMethodError there.) In the first snippet, you call m, which returns a Proc.

It looks like you are trying to pass the method m itself instead of the result of calling it. In Ruby, methods aren't objects, so you can't just grab them and pass them around (and even if methods were objects, then m is still the syntax for calling m, not for referencing it). You have to ask Ruby's reflection API for a reflective proxy for the method first, using the Object#method method, which returns a Method object representing the method:

@context.instance_eval(&method(:m).to_proc)

Note that the call to to_proc is completely redundant here, since & will call to_proc anyway if the argument isn't a Proc already. (You may have seen something like foo.map(&:bar) before, which will invoke Symbol#to_proc.)

@context.instance_eval(&method(:m))


问:
docker pull hyperledger/fabric-peer is throwing error
docker pull hyperledger/fabric-peer is throwing error.

When I tried to setup docker locally and "docker-compose up" not up and runnning.

Please suggest.

Thanks in advance.

答:
You can go and grab the version that suits you from here:
https://store.docker.com/community/images/hyperledger/fabric-peer/tags

After that run this command

```<code>docker pull hyperledger/fabric-peer:your_version
</code>```

Body:
You can go and grab the version that suits you from here:
https://store.docker.com/community/images/hyperledger/fabric-peer/tags

After that run this command

docker pull hyperledger/fabric-peer:your_version


问:
Shuffling array in multiple threads
I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array.

Lets say, the first thread shuffles elements from 0 to K, and the second thread shuffles elements from K to N (where 0 < K < N). So, it can look like this:

```<code>//try-catch stuff is ommited
static void shuffle(int[] array) {
   Thread t1 = new ShufflingThread(array, 0, array.length / 2);
   Thread t2 = new ShufflingThread(array, array.length / 2, array.length);
   t1.start();
   t2.start();
   t1.join();
   t2.join();
}

public static void main(String[] args) {
   int array = generateBigSortedArray();
   shuffle(array);
}
</code>```

Are there any guaranties from JVM that I will see changes in the array from the main method after such shuffling?

How should I implement ShufflingThread (or, how should I run it, maybe within a synchronized block or whatever else) in order to get such guaranties?

答:
Well, they can't BOTH be accessing the same array and if you use a lock, or a mutex or any other synchronizing mechanism, you kinda lose the power of the threads (since one will have to wait for another, either to finish the shuffling or finish a bit of the shuffling).
Why don't you just divide the array in half, give each thread its bit of the array and then merge the two arrays?</p>

Title: Shuffling array in multiple threads

Body:
I have an array of size N. I want to shuffle its elements in 2 threads (or more). Each thread should work with it's own part of the array.

Lets say, the first thread shuffles elements from 0 to K, and the second thread shuffles elements from K to N (where 0 < K < N). So, it can look like this:

//try-catch stuff is ommited
static void shuffle(int[] array) {
   Thread t1 = new ShufflingThread(array, 0, array.length / 2);
   Thread t2 = new ShufflingThread(array, array.length / 2, array.length);
   t1.start();
   t2.start();
   t1.join();
   t2.join();
}

public static void main(String[] args) {
   int array = generateBigSortedArray();
   shuffle(array);
}

Are there any guaranties from JVM that I will see changes in the array from the main method after such shuffling?

How should I implement ShufflingThread (or, how should I run it, maybe within a synchronized block or whatever else) in order to get such guaranties?


问:
Make a Y*Z in a matrix and not a line (in Python 2.7.14)
I'm new to python programming and for school I have to make a simulation of the multiplication table from 1 to 10. This needs to be in a matrix.

The code I wrote is:

```<code>for y in range(1, 11):
  for z in range(1, 11):
    print y*z
</code>```

However, when i try to run this, it all comes in one line down and not a matrix... I have looked for an awnser and in python 3.0 or higher they have the "end=" command but I cannot use this so I was wondering how to fix this in 2.7.14.

答:
You can create matrix use python list comprehension like this</p>

```<code>multiplication_table = [
    [y*z for z in range(1, 11)] for y in range(1, 11)
]
</code>```

Body:
I'm new to python programming and for school I have to make a simulation of the multiplication table from 1 to 10. This needs to be in a matrix.

The code I wrote is:

for y in range(1, 11):
  for z in range(1, 11):
    print y*z

However, when i try to run this, it all comes in one line down and not a matrix... I have looked for an awnser and in python 3.0 or higher they have the "end=" command but I cannot use this so I was wondering how to fix this in 2.7.14.

Body:
You can create matrix use python list comprehension like this

multiplication_table = [
    [y*z for z in range(1, 11)] for y in range(1, 11)
]