问:
What is the Best practice for try catch blocks to create clean code?

Possible Duplicate:

  Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

```<code>import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 * <p>This is a dummy code.</p>
 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown.
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}
</code>```

EDITED:

What I want to avoid is writing lot of catch cases after each other...

答:
A few suggestions at first glance:

You shouldn't catch Throwable and instead catch as specific of an exception as possible. The trouble with catching Throwable is that will include Error classes like OutOfMemoryError and the like. You want to let those pass through (they're unchecked for a reason).

When you log exceptions always pass the exception and not just its toString(). It's very hard to diagnose problems without the stack trace.

You probably don't want a general exception handling method.

So at places you catch exceptions you want something like this:

```<code>} catch (IOException e) {
    logger.error("some relevant message", e);
    // now handle the exception case
}
</code>```

The message should include some contextual information if possible. Anything that might help tracking down the problem when someone is hunting through logs.

Body:
Possible Duplicate:

  Best practices for exception management in JAVA or C#

I've read a question earlier today on stackoverflow and it made me think about what is the best practice for handling exceptions.

So, my question is what is the best practice to handle exceptions to produce clean and high quality code.

Here is my code, I think it's quiet straight forward but please let me know if I'm wrong or not clear!
I've tried to keep in mind testability and same abstraction level in methods.

Every constructive comment is welcomed. :)

import java.awt.Point;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 *
This is a dummy code.

 * The aim is present the best practice on exception separation and handling.
 */
public class ExceptionHandlingDemo {
    // System.out is not a good practice. Using logger is good for testing too (can be checked if the expected error messages are produced).
    private Logger logger = LoggerFactory.getLogger(ExceptionHandlingDemo.class);

    // instance of cannot work with List<Point>
    private interface PointList extends List<Point> {}

    /**
     * The method that loads a list of points from a file.
     * @param path - The path and the name of the file to be loaded.
     * Precondition: path cannot be {@code null}. In such case {@link NullPointerException} will be thrown.
     * Postcondition: if the file don't exist, some IOException occurs or the file doesn't contain the list the returned object is {@code null}.
     * */
    /* (Google throws NullpointerExceptio) since it is not forbidden for the developers to throw it. I know this is arguable but this is out of topic for now. */
    public List<Point> loadPointList(final String path) {
        Preconditions.checkNotNull(path, "The path of the file cannot be null");

        List<Point> pointListToReturn = null;
        ObjectInputStream in = null;

        try {
            in = openObjectInputStream(path);
            pointListToReturn = readPointList(in);
        } catch (final Throwable throwable) {
            handleException(throwable);
        } finally {
            close(in);
        }

        return pointListToReturn;
    }

    /*======== Private helper methods by now ========*/

    private ObjectInputStream openObjectInputStream(final String filename) throws FileNotFoundException, IOException {
        return new ObjectInputStream(new FileInputStream(filename));
    }

    private List<Point> readPointList(final ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        final Object object = objectInputStream.readObject();

        List<Point> ret = null;

        if (object instanceof PointList) {
            ret = (PointList) object;
        }
        return ret;
    }

    private void handleException(final Throwable throwable) {
        // I don't know the best practice here ...
        logger.error(throwable.toString());
    }

    private void close(final Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("Failed closing: %s", closeable);
            }
        }
    }

    /*======== Getters and setters by now. ========*/

    // ...

    /**
     * @param args
     */
    public static void main(String[] args) {
        ExceptionHandlingDemo test = new ExceptionHandlingDemo();
        test.loadPointList("test-filename.ext");
    }
}

EDITED:

What I want to avoid is writing lot of catch cases after each other...

Body:
A few suggestions at first glance:

You shouldn't catch Throwable and instead catch as specific of an exception as possible. The trouble with catching Throwable is that will include Error classes like OutOfMemoryError and the like. You want to let those pass through (they're unchecked for a reason).

When you log exceptions always pass the exception and not just its toString(). It's very hard to diagnose problems without the stack trace.

You probably don't want a general exception handling method.

So at places you catch exceptions you want something like this:

} catch (IOException e) {
    logger.error("some relevant message", e);
    // now handle the exception case
}

The message should include some contextual information if possible. Anything that might help tracking down the problem when someone is hunting through logs.


来源: stackexchange

问:
How can I change the text of a label in a button event?
Just doing my very first test app with Xamarin.

How can I change (within a button event) the text in the label from "Welcome to Xamarin.Forms!" to "Hello World" ?

I tried to do so with the following XAML script and C# code:

XAMLscript within the Stacklayout and my C# code in mainpage.xaml.cs:

```<code>    <Label Text="Welcome to Xamarin.Forms!"
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />
    <Button Text="click here" Clicked="Button_Clicked" />

private void Button_Clicked(object sender, EventArgs e)
    {
        Label.Text = "Hello World";
    }
</code>```

Somehow the system does not accept .Text as a property of the label.

答:
You are super close! You have to give a name property to your label, it's like a variable name.        </p>

```<code><Label x:Name="label"..../>
</code>```

<p>and then in your function, you can just say </p>

```<code>private void Button_Clicked(object sender, EventArgs e)
{
        label.Text = "Changed";
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Just doing my very first test app with Xamarin.

How can I change (within a button event) the text in the label from "Welcome to Xamarin.Forms!" to "Hello World" ?

I tried to do so with the following XAML script and C# code:

XAMLscript within the Stacklayout and my C# code in mainpage.xaml.cs:

    <Button Text="click here" Clicked="Button_Clicked" />

private void Button_Clicked(object sender, EventArgs e)
    {
        Label.Text = "Hello World";
    }

Somehow the system does not accept .Text as a property of the label.

Body:
You are super close! You have to give a name property to your label, it's like a variable name.

<Label x:Name="label"..../>

and then in your function, you can just say

private void Button_Clicked(object sender, EventArgs e)
{
        label.Text = "Changed";
}


问:
Mysql Filter data using Timestamp stored in table
I have stored bill date in timestamp in mysql.

In reports, i get from and to date in dd-mm-YYYY format.In query I have used like this,

```<code>WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >='06-04-2019' AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= '30-04-2019'
</code>```

But the data 06/05/2019 also fetched. I don't know why it is happening.

答:
You're surprised that the value '06-05-2019' is greater than '06-04-2019'?

You can't use inequalities like >= with dates in %d-%m-%Y format. MySQL prefers the format %Y-%m-%d, and that's the format it assumes when checking sort order for dates, and for inequality comparisons.

You should use FROM_UNIXTIME() with no format argument. Then it will return dates in %Y-%m-%d format, which does support inequality comparisons.

Use date literals in %Y-%m-%d format.

I would write your expression like this:

```<code>WHERE from_unixtime(bill.bill_date) BETWEEN '2019-04-06' AND '2019-04-30'
</code>```

Body:
I have stored bill date in timestamp in mysql.

In reports, i get from and to date in dd-mm-YYYY format.In query I have used like this,

WHERE  (from_unixtime(bill.bill_date,"%d-%m-%Y")) >='06-04-2019' AND (from_unixtime(bill.bill_date,"%d-%m-%Y")) <= '30-04-2019'

But the data 06/05/2019 also fetched. I don't know why it is happening.

Body:
You're surprised that the value '06-05-2019' is greater than '06-04-2019'?

You can't use inequalities like >= with dates in %d-%m-%Y format. MySQL prefers the format %Y-%m-%d, and that's the format it assumes when checking sort order for dates, and for inequality comparisons.

You should use FROM_UNIXTIME() with no format argument. Then it will return dates in %Y-%m-%d format, which does support inequality comparisons.

Use date literals in %Y-%m-%d format.

I would write your expression like this:

WHERE from_unixtime(bill.bill_date) BETWEEN '2019-04-06' AND '2019-04-30'


问:
How can I run an infinity program on heroku (no restart or sleeping)
I have a web instance (python API) on Heroku and I want to start a background process from this API.

The process is base on an infinity loop, and it will be stop from the API as well.

I try to run a subprocess from python and it's work well on my localhost, but not on Heroku.

Heroku seems to stop the process after 30 minutes of inactivity (input or output) and anyway it seems like Heroku restarts the Dynos every 24h.

How can I do to run a process on Heroku server (free version) and be sure that it doesn't stop?

答:
Please see this answer:

Possible to bypass Heroku's free plan's "Sleeps after 30 mins of inactivity" with console.logs?

In short, it's impractical to do this for at least two reasons:

You'll need a way to keep your process alive

You'll run through your free dyno hours


问:
How can I host angular configuration in GitHub Pages?
I've built an angular app from ngx-admin and deployed it to Github Pages.  Now I would like to have it run a specific configuration, e.g. qa, or prod.

When I run npm run build:qa -> "build:qa": "npm run build -- --qa --aot", I get the error:

```<code>Unknown option: '--qa'
</code>```

... even though I have specified qa in angular.json:

```<code>"configurations": {
            "qa": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
              ]
            },
</code>```

Normally, from my local I use Node to serve the content via:

```<code>npm start:qa
</code>```

Which calls the following configuration in package.json...

```<code>"start:qa": "ng serve --host 0.0.0.0 --port 4200 --configuration=qa"
</code>```

When I build the app, I specify:

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

Which calls the following configuration in package.json...

```<code>"build:qa": "npm run build -- --qa --aot"
</code>```

The build fails.

Given that angular-cli.json is deprecated in Angular 7, how can I define my own build configurations, so I can host environment specific configurations without Node?

答:
It appears that Angular 7 now supports --configuration in the declaration:

"build:qa": "npm run build -- --configuration=qa --aot",.

When I run npm run build:qa which calls "build:qa": "npm run build -- --configuration=qa --aot", in the "scripts" section of angular.json, I see the desired environment.qa.ts is properly swapped into place.

I believe what what confusing me is I specified prod in the "configurations" section of angular.json, and calling npm run build -- --prod --aot was failing to find production.  It would seem the key production is hard coded someplace in the Angular packages.

Body:
I've built an angular app from ngx-admin and deployed it to Github Pages.  Now I would like to have it run a specific configuration, e.g. qa, or prod.

When I run npm run build:qa -> "build:qa": "npm run build -- --qa --aot", I get the error:

Unknown option: '--qa'

... even though I have specified qa in angular.json:

"configurations": {
            "qa": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.qa.ts"
                }
              ]
            },

Normally, from my local I use Node to serve the content via:

npm start:qa

Which calls the following configuration in package.json...

"start:qa": "ng serve --host 0.0.0.0 --port 4200 --configuration=qa"

When I build the app, I specify:

npm run build:qa

Which calls the following configuration in package.json...

"build:qa": "npm run build -- --qa --aot"

The build fails.

Given that angular-cli.json is deprecated in Angular 7, how can I define my own build configurations, so I can host environment specific configurations without Node?


问:
how to limit and clamp distance between two points in a Line renderer unity2d
I am making a game which let you click on a ball and drag to draw a line renderer with two points and point it to a specific direction and when release I add force to the ball,
for now, I just want to know how can I limit the distance between those two points like give it a radius.

答:
You can simply clamp it using a Mathf.Min.

Since you didn't provide any example code unfortunately here is some example code I made up with a simple plane with a MeshCollider, a child object with the LineRenderer and a camera set to Orthographic. You probably would have to adopt it somehow.

public class Example : MonoBehaviour
{
    // adjust in the inspector
    public float maxRadius = 2;

    private Vector3 startPosition;

    [SerializeField] private LineRenderer line;
    [SerializeField] private Collider collider;
    [SerializeField] private Camera camera;

    private void Awake()
    {
        line.positionCount = 0;

        line = GetComponentInChildren<LineRenderer>();
        collider = GetComponent<Collider>();
        camera = Camera.main;
    }

    // wherever you dragging starts
    private void OnMouseDown()
    {
        line.positionCount = 2;

        startPosition = collider.ClosestPoint(camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z)));

        var positions = new[] { startPosition, startPosition };

        line.SetPositions(positions);
    }

    // while dragging
    private void OnMouseDrag()
    {
        var currentPosition = GetComponent<Collider>().ClosestPoint(camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z)));

        // get vector between positions
        var difference = currentPosition - startPosition;

        // normalize to only get a direction with magnitude = 1
        var direction = difference.normalized;

        // here you "clamp" use the smaller of either
        // the max radius or the magnitude of the difference vector
        var distance = Mathf.Min(maxRadius, difference.magnitude);

        // and finally apply the end position
        var endPosition = startPosition + direction * distance;

        line.SetPosition(1, endPosition);
    }
}
```

This is how it could look like

Body:
You can simply clamp it using a Mathf.Min.

Since you didn't provide any example code unfortunately here is some example code I made up with a simple plane with a MeshCollider, a child object with the LineRenderer and a camera set to Orthographic. You probably would have to adopt it somehow.

public class Example : MonoBehaviour
{
    // adjust in the inspector
    public float maxRadius = 2;

    private Vector3 startPosition;

    [SerializeField] private LineRenderer line;
    [SerializeField] private Collider collider;
    [SerializeField] private Camera camera;

    private void Awake()
    {
        line.positionCount = 0;

        line = GetComponentInChildren<LineRenderer>();
        collider = GetComponent<Collider>();
        camera = Camera.main;
    }

    // wherever you dragging starts
    private void OnMouseDown()
    {
        line.positionCount = 2;

        startPosition = collider.ClosestPoint(camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z)));

        var positions = new[] { startPosition, startPosition };

        line.SetPositions(positions);
    }

    // while dragging
    private void OnMouseDrag()
    {
        var currentPosition = GetComponent<Collider>().ClosestPoint(camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z)));

        // get vector between positions
        var difference = currentPosition - startPosition;

        // normalize to only get a direction with magnitude = 1
        var direction = difference.normalized;

        // here you "clamp" use the smaller of either
        // the max radius or the magnitude of the difference vector
        var distance = Mathf.Min(maxRadius, difference.magnitude);

        // and finally apply the end position
        var endPosition = startPosition + direction * distance;

        line.SetPosition(1, endPosition);
    }
}

This is how it could look like


问:
Change the sections header background color in UITableView using an array of headers
I have a array of headers that I use

```<code>let sectionHeaderTitleArray = ["test1","test2","test3]
</code>```

and they are showed using

```<code>func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}
</code>```

Now all of this works fine but I would like to modify the background color of the headers so that they are more visible (Darker Color)

any idea if I can do this in a simple line or do I need to use a custom cell to create this

thanks

update

```<code>  //number of sections and names for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sectionHeaderTitleArray.count
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionHeaderTitleArray[section] as String
    }
    func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
        return self.tableView.backgroundColor = UIColor.lightGrayColor()
    }
</code>```

答:
Swift5

Versión updated to iOS 11,12,13,14 with example

change background color and text color:

```<code>func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let tableView = view as? UITableViewHeaderFooterView else { return }
    tableView.textLabel?.textColor = UIColor.white
    tableView.contentView.backgroundColor = UIColor.black
}
</code>```

Full example of viewcontroller:

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    private let array: [String] = ["ab","bc","cd","de","ef","fg","gh","hi","ij","jk"]
    let sectionHeaderTitleArray = ["test1","test2", "test3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 11, *) {}
        else {
            self.edgesForExtendedLayout = []
        }
        configTableview()
    }

    private func configTableview() {
        tableView.registerCell(type: SyncCell.self)
        tableView.separatorColor = #colorLiteral(red: 0, green: 0.3066673801, blue: 1, alpha: 0.19)
        tableView.delegate = self
        tableView.dataSource = self
    }
}

extension ViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        guard let tableView = view as? UITableViewHeaderFooterView else { return }
        tableView.textLabel?.textColor = UIColor.white
        tableView.contentView.backgroundColor = UIColor.black
    }

    func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
        return sectionHeaderTitleArray[section]
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

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

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected cell: \(indexPath)")
    }
}

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = array[indexPath.row]
        let cell = tableView.dequeueReusableCell(type: SyncCell.self, forIndexPath: indexPath)
        cell.configCell(text: item)
        cell.selectionStyle = .none
        return cell
    }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a array of headers that I use

let sectionHeaderTitleArray = ["test1","test2","test3]

and they are showed using

func tableView[tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.sectionHeaderTitleArray[section] as String
}

Now all of this works fine but I would like to modify the background color of the headers so that they are more visible (Darker Color)

any idea if I can do this in a simple line or do I need to use a custom cell to create this

thanks

update

  //number of sections and names for the table

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sectionHeaderTitleArray.count
    }

    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionHeaderTitleArray[section] as String
    }
    func tableView(tableView: UITableView, ViewForHeaderInSection section: Int) -> UIView? {
        return self.tableView.backgroundColor = UIColor.lightGrayColor()
    }

Body:
Swift5

Versión updated to iOS 11,12,13,14 with example

change background color and text color:

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    guard let tableView = view as? UITableViewHeaderFooterView else { return }
    tableView.textLabel?.textColor = UIColor.white
    tableView.contentView.backgroundColor = UIColor.black
}

Full example of viewcontroller:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    private let array: [String] = ["ab","bc","cd","de","ef","fg","gh","hi","ij","jk"]
    let sectionHeaderTitleArray = ["test1","test2", "test3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 11, *) {}
        else {
            self.edgesForExtendedLayout = []
        }
        configTableview()
    }

    private func configTableview() {
        tableView.registerCell(type: SyncCell.self)
        tableView.separatorColor = #colorLiteral(red: 0, green: 0.3066673801, blue: 1, alpha: 0.19)
        tableView.delegate = self
        tableView.dataSource = self
    }
}

extension ViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        guard let tableView = view as? UITableViewHeaderFooterView else { return }
        tableView.textLabel?.textColor = UIColor.white
        tableView.contentView.backgroundColor = UIColor.black
    }

    func tableView(_ tableView: UITableView,titleForHeaderInSection section: Int) -> String? {
        return sectionHeaderTitleArray[section]
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }

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

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

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("selected cell: \(indexPath)")
    }
}

extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let item = array[indexPath.row]
        let cell = tableView.dequeueReusableCell(type: SyncCell.self, forIndexPath: indexPath)
        cell.configCell(text: item)
        cell.selectionStyle = .none
        return cell
    }

}


问:
Spark worker containers terminate with Command exited with code 1 [ not able to connect to local PC]
I have a spark cluster setup on docker. using a openjdk:8-alpine. I am running it on local. Local pc name is DESKTOP-PCH5L6D

I am able to submit jobs but the error I see at the worker docker container is
Caused by: java.net.UnknownHostException: DESKTOP-PCH5L6D

local pc is on Win 10 Pro.

Am new to docker and seeking help as to how to approach to solve for this.
docker compose file am using to create the local spark cluster

```<code>version: "3.7"
services:
  spark-master:
    image: cmishr4/spark:latest
    container_name: spark-master
    hostname: spark-master
    ports:
      - "8080:8080"
      - "7077:7077"
    volumes:
      - ./../share:/share
    privileged: true
    networks:
      - spark-network
    environment:
      - "SPARK_MASTER_PORT=7077"
      - "SPARK_MASTER_WEBUI_PORT=8080"
    command: "sh start-master.sh"
  spark-worker:
    image: cmishr4/spark:latest
    depends_on:
      - spark-master
    ports:
      - 8080
    volumes:
      - ./../share:/share
    privileged: true
    networks:
      - spark-network
    environment:
      - "SPARK_MASTER=spark://spark-master:7077"
      - "SPARK_WORKER_WEBUI_PORT=8080"
    command: "sh start-worker.sh"
networks:
  spark-network:
    driver: bridge
    ipam:
      driver: default
</code>```

scala class main method:

```<code>val spark = SparkSession.builder
  .appName("sample")
  .master("spark://localhost:7077")
  .config("spark.executor.cores", "1")
  .config("spark.executor.memory","1g")
  .getOrCreate()
val csv = spark.sparkContext.textFile("C:/Users/chand/wrkspcs/sparkws/share/input")
val rows = csv.map(line => line.split(",").map(_.trim))
val header = rows.first
val data = rows.filter(_(0) != header(0))
val rdd = data.map(row => Row(row(0), row(1).toInt))

val schema = new StructType()
  .add(StructField("name", StringType, true))
  .add(StructField("age", IntegerType, true))

val df = spark.sqlContext.createDataFrame(rdd, schema)
spark.stop()
</code>```

log from the main class

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
19/05/27 02:25:55 INFO SparkContext: Running Spark version 2.4.3
19/05/27 02:25:55 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
19/05/27 02:25:55 INFO SparkContext: Submitted application: sample
19/05/27 02:25:56 INFO SecurityManager: Changing view acls to: chand
19/05/27 02:25:56 INFO SecurityManager: Changing modify acls to: chand
19/05/27 02:25:56 INFO SecurityManager: Changing view acls groups to:
19/05/27 02:25:56 INFO SecurityManager: Changing modify acls groups to:
19/05/27 02:25:56 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(chand); groups with view permissions: Set(); users  with modify permissions: Set(chand); groups with modify permissions: Set()
<b>19/05/27 02:25:57 INFO Utils: Successfully started service 'sparkDriver' on port 53511.</b>
19/05/27 02:25:57 INFO SparkEnv: Registering MapOutputTracker
19/05/27 02:25:57 INFO SparkEnv: Registering BlockManagerMaster
19/05/27 02:25:57 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
19/05/27 02:25:57 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
19/05/27 02:25:57 INFO DiskBlockManager: Created local directory at C:\Users\chand\AppData\Local\Temp\blockmgr-c4f6d60f-c867-4c52-895d-111030c92193
19/05/27 02:25:57 INFO MemoryStore: MemoryStore started with capacity 4.1 GB
19/05/27 02:25:57 INFO SparkEnv: Registering OutputCommitCoordinator
19/05/27 02:25:57 INFO Utils: Successfully started service 'SparkUI' on port 4040.
19/05/27 02:25:57 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://DESKTOP-PCH5L6D:4040
19/05/27 02:25:57 INFO StandaloneAppClient$ClientEndpoint: Connecting to master spark://localhost:7077...
19/05/27 02:25:57 INFO TransportClientFactory: Successfully created connection to localhost/127.0.0.1:7077 after 27 ms (0 ms spent in bootstraps)
19/05/27 02:25:57 INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20190527062557-0000
19/05/27 02:25:57 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 53553.
19/05/27 02:25:57 INFO NettyBlockTransferService: Server created on DESKTOP-PCH5L6D:53553
19/05/27 02:25:57 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
19/05/27 02:25:57 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20190527062557-0000/0 on worker-20190527062533-172.18.0.3-44351 (172.18.0.3:44351) with 1 core(s)
19/05/27 02:25:57 INFO StandaloneSchedulerBackend: Granted executor ID app-20190527062557-0000/0 on hostPort 172.18.0.3:44351 with 1 core(s), 1024.0 MB RAM
19/05/27 02:25:57 INFO BlockManagerMasterEndpoint: Registering block manager DESKTOP-PCH5L6D:53553 with 4.1 GB RAM, BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/0 is now RUNNING
19/05/27 02:25:57 INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 214.6 KB, free 4.1 GB)
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 20.4 KB, free 4.1 GB)
19/05/27 02:25:58 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on DESKTOP-PCH5L6D:53553 (size: 20.4 KB, free: 4.1 GB)
19/05/27 02:25:58 INFO SparkContext: Created broadcast 0 from textFile at App.scala:24
19/05/27 02:25:58 INFO FileInputFormat: Total input paths to process : 2
19/05/27 02:25:58 INFO SparkContext: Starting job: first at App.scala:26
19/05/27 02:25:58 INFO DAGScheduler: Got job 0 (first at App.scala:26) with 1 output partitions
19/05/27 02:25:58 INFO DAGScheduler: Final stage: ResultStage 0 (first at App.scala:26)
19/05/27 02:25:58 INFO DAGScheduler: Parents of final stage: List()
19/05/27 02:25:58 INFO DAGScheduler: Missing parents: List()
19/05/27 02:25:58 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[2] at map at App.scala:25), which has no missing parents
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 3.6 KB, free 4.1 GB)
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 2.2 KB, free 4.1 GB)
19/05/27 02:25:58 INFO BlockManagerInfo: Added broadcast_1_piece0 in memory on DESKTOP-PCH5L6D:53553 (size: 2.2 KB, free: 4.1 GB)
19/05/27 02:25:58 INFO SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1161
19/05/27 02:25:58 INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 0 (MapPartitionsRDD[2] at map at App.scala:25) (first 15 tasks are for partitions Vector(0))
19/05/27 02:25:58 INFO TaskSchedulerImpl: Adding task set 0.0 with 1 tasks
19/05/27 02:25:59 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/0 is now EXITED (Command exited with code 1)
19/05/27 02:25:59 INFO StandaloneSchedulerBackend: Executor app-20190527062557-0000/0 removed: Command exited with code 1
19/05/27 02:25:59 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20190527062557-0000/1 on worker-20190527062533-172.18.0.3-44351 (172.18.0.3:44351) with 1 core(s)
19/05/27 02:25:59 INFO StandaloneSchedulerBackend: Granted executor ID app-20190527062557-0000/1 on hostPort 172.18.0.3:44351 with 1 core(s), 1024.0 MB RAM
19/05/27 02:25:59 INFO BlockManagerMaster: Removal of executor 0 requested
19/05/27 02:25:59 INFO CoarseGrainedSchedulerBackend$DriverEndpoint: Asked to remove non-existent executor 0
19/05/27 02:25:59 INFO BlockManagerMasterEndpoint: Trying to remove executor 0 from BlockManagerMaster.
19/05/27 02:25:59 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/1 is now RUNNING
19/05/27 02:26:01 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/1 is now EXITED (Command exited with code 1)
19/05/27 02:26:01 INFO StandaloneSchedulerBackend: Executor app-20190527062557-0000/1 removed: Command exited with code 1
19/05/27 02:26:01 INFO BlockManagerMasterEndpoint: Trying to remove executor 1 from BlockManagerMaster.
19/05/27 02:26:01 INFO BlockManagerMaster: Removal of executor 1 requested
19/05/27 02:26:01 INFO CoarseGrainedSchedulerBackend$DriverEndpoint: Asked to remove non-existent executor 1
19/05/27 02:26:01 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20190527062557-0000/2 on worker-20190527062533-172.18.0.3-44351 (172.18.0.3:44351) with 1 core(s)
19/05/27 02:26:01 INFO StandaloneSchedulerBackend: Granted executor ID app-20190527062557-0000/2 on hostPort 172.18.0.3:44351 with 1 core(s), 1024.0 MB RAM
19/05/27 02:26:01 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/2 is now RUNNING
19/05/27 02:26:03 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/2 is now EXITED (Command exited with code 1)
</code>```

from the worker container I see the job fails with the following exception

```<code>Caused by: java.io.IOException: Failed to connect to DESKTOP-PCH5L6D:53511
        at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:245)
        at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:187)
        at org.apache.spark.rpc.netty.NettyRpcEnv.createClient(NettyRpcEnv.scala:198)
        at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:194)
        at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:190)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.UnknownHostException: DESKTOP-PCH5L6D
        at java.net.InetAddress.getAllByName0(InetAddress.java:1281)
        at java.net.InetAddress.getAllByName(InetAddress.java:1193)
        at java.net.InetAddress.getAllByName(InetAddress.java:1127)
        at java.net.InetAddress.getByName(InetAddress.java:1077)
</code>```

答:
added the additional parameter extra_hosts to fix the issue as shown below</p>

```<code>version: "3.7"
services:
  spark-master:
    image: cmishr4/spark:latest
    container_name: spark-master
    hostname: spark-master
    ports:
      - "8080:8080"
      - "7077:7077"
    volumes:
      - ./../share:/share

    privileged: true
    networks:
      - spark-network
    environment:
      - "SPARK_MASTER_PORT=7077"
      - "SPARK_MASTER_WEBUI_PORT=8080"
    command: "sh start-master.sh"
  spark-worker:
    image: cmishr4/spark:latest
    depends_on:
      - spark-master
    ports:
      - 8080
    volumes:
      - ./../share:/share

    privileged: true
    networks:
      - spark-network
    extra_hosts:
        - "DESKTOP-PCH5L6D:10.0.75.1"
    environment:
      - "SPARK_MASTER=spark://spark-master:7077"
      - "SPARK_WORKER_WEBUI_PORT=8080"
    command: "sh start-worker.sh"
networks:
  spark-network:
    driver: bridge
    ipam:
      driver: default
</code>```

Body:
I have a spark cluster setup on docker. using a openjdk:8-alpine. I am running it on local. Local pc name is DESKTOP-PCH5L6D

I am able to submit jobs but the error I see at the worker docker container is
Caused by: java.net.UnknownHostException: DESKTOP-PCH5L6D

local pc is on Win 10 Pro.

Am new to docker and seeking help as to how to approach to solve for this.
docker compose file am using to create the local spark cluster

version: "3.7"
services:
  spark-master:
    image: cmishr4/spark:latest
    container_name: spark-master
    hostname: spark-master
    ports:
      - "8080:8080"
      - "7077:7077"
    volumes:
      - ./../share:/share
    privileged: true
    networks:
      - spark-network
    environment:
      - "SPARK_MASTER_PORT=7077"
      - "SPARK_MASTER_WEBUI_PORT=8080"
    command: "sh start-master.sh"
  spark-worker:
    image: cmishr4/spark:latest
    depends_on:
      - spark-master
    ports:
      - 8080
    volumes:
      - ./../share:/share
    privileged: true
    networks:
      - spark-network
    environment:
      - "SPARK_MASTER=spark://spark-master:7077"
      - "SPARK_WORKER_WEBUI_PORT=8080"
    command: "sh start-worker.sh"
networks:
  spark-network:
    driver: bridge
    ipam:
      driver: default

scala class main method:

val spark = SparkSession.builder
  .appName("sample")
  .master("spark://localhost:7077")
  .config("spark.executor.cores", "1")
  .config("spark.executor.memory","1g")
  .getOrCreate()
val csv = spark.sparkContext.textFile("C:/Users/chand/wrkspcs/sparkws/share/input")
val rows = csv.map(line => line.split(",").map(_.trim))
val header = rows.first
val data = rows.filter(_(0) != header(0))
val rdd = data.map(row => Row(row(0), row(1).toInt))

val schema = new StructType()
  .add(StructField("name", StringType, true))
  .add(StructField("age", IntegerType, true))

val df = spark.sqlContext.createDataFrame(rdd, schema)
spark.stop()

log from the main class

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
19/05/27 02:25:55 INFO SparkContext: Running Spark version 2.4.3
19/05/27 02:25:55 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
19/05/27 02:25:55 INFO SparkContext: Submitted application: sample
19/05/27 02:25:56 INFO SecurityManager: Changing view acls to: chand
19/05/27 02:25:56 INFO SecurityManager: Changing modify acls to: chand
19/05/27 02:25:56 INFO SecurityManager: Changing view acls groups to:
19/05/27 02:25:56 INFO SecurityManager: Changing modify acls groups to:
19/05/27 02:25:56 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users  with view permissions: Set(chand); groups with view permissions: Set(); users  with modify permissions: Set(chand); groups with modify permissions: Set()
19/05/27 02:25:57 INFO Utils: Successfully started service 'sparkDriver' on port 53511.
19/05/27 02:25:57 INFO SparkEnv: Registering MapOutputTracker
19/05/27 02:25:57 INFO SparkEnv: Registering BlockManagerMaster
19/05/27 02:25:57 INFO BlockManagerMasterEndpoint: Using org.apache.spark.storage.DefaultTopologyMapper for getting topology information
19/05/27 02:25:57 INFO BlockManagerMasterEndpoint: BlockManagerMasterEndpoint up
19/05/27 02:25:57 INFO DiskBlockManager: Created local directory at C:\Users\chand\AppData\Local\Temp\blockmgr-c4f6d60f-c867-4c52-895d-111030c92193
19/05/27 02:25:57 INFO MemoryStore: MemoryStore started with capacity 4.1 GB
19/05/27 02:25:57 INFO SparkEnv: Registering OutputCommitCoordinator
19/05/27 02:25:57 INFO Utils: Successfully started service 'SparkUI' on port 4040.
19/05/27 02:25:57 INFO SparkUI: Bound SparkUI to 0.0.0.0, and started at http://DESKTOP-PCH5L6D:4040
19/05/27 02:25:57 INFO StandaloneAppClient$ClientEndpoint: Connecting to master spark://localhost:7077...
19/05/27 02:25:57 INFO TransportClientFactory: Successfully created connection to localhost/127.0.0.1:7077 after 27 ms (0 ms spent in bootstraps)
19/05/27 02:25:57 INFO StandaloneSchedulerBackend: Connected to Spark cluster with app ID app-20190527062557-0000
19/05/27 02:25:57 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 53553.
19/05/27 02:25:57 INFO NettyBlockTransferService: Server created on DESKTOP-PCH5L6D:53553
19/05/27 02:25:57 INFO BlockManager: Using org.apache.spark.storage.RandomBlockReplicationPolicy for block replication policy
19/05/27 02:25:57 INFO BlockManagerMaster: Registering BlockManager BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20190527062557-0000/0 on worker-20190527062533-172.18.0.3-44351 (172.18.0.3:44351) with 1 core(s)
19/05/27 02:25:57 INFO StandaloneSchedulerBackend: Granted executor ID app-20190527062557-0000/0 on hostPort 172.18.0.3:44351 with 1 core(s), 1024.0 MB RAM
19/05/27 02:25:57 INFO BlockManagerMasterEndpoint: Registering block manager DESKTOP-PCH5L6D:53553 with 4.1 GB RAM, BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO BlockManagerMaster: Registered BlockManager BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO BlockManager: Initialized BlockManager: BlockManagerId(driver, DESKTOP-PCH5L6D, 53553, None)
19/05/27 02:25:57 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/0 is now RUNNING
19/05/27 02:25:57 INFO StandaloneSchedulerBackend: SchedulerBackend is ready for scheduling beginning after reached minRegisteredResourcesRatio: 0.0
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 214.6 KB, free 4.1 GB)
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 20.4 KB, free 4.1 GB)
19/05/27 02:25:58 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on DESKTOP-PCH5L6D:53553 (size: 20.4 KB, free: 4.1 GB)
19/05/27 02:25:58 INFO SparkContext: Created broadcast 0 from textFile at App.scala:24
19/05/27 02:25:58 INFO FileInputFormat: Total input paths to process : 2
19/05/27 02:25:58 INFO SparkContext: Starting job: first at App.scala:26
19/05/27 02:25:58 INFO DAGScheduler: Got job 0 (first at App.scala:26) with 1 output partitions
19/05/27 02:25:58 INFO DAGScheduler: Final stage: ResultStage 0 (first at App.scala:26)
19/05/27 02:25:58 INFO DAGScheduler: Parents of final stage: List()
19/05/27 02:25:58 INFO DAGScheduler: Missing parents: List()
19/05/27 02:25:58 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[2] at map at App.scala:25), which has no missing parents
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 3.6 KB, free 4.1 GB)
19/05/27 02:25:58 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 2.2 KB, free 4.1 GB)
19/05/27 02:25:58 INFO BlockManagerInfo: Added broadcast_1_piece0 in memory on DESKTOP-PCH5L6D:53553 (size: 2.2 KB, free: 4.1 GB)
19/05/27 02:25:58 INFO SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1161
19/05/27 02:25:58 INFO DAGScheduler: Submitting 1 missing tasks from ResultStage 0 (MapPartitionsRDD[2] at map at App.scala:25) (first 15 tasks are for partitions Vector(0))
19/05/27 02:25:58 INFO TaskSchedulerImpl: Adding task set 0.0 with 1 tasks
19/05/27 02:25:59 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/0 is now EXITED (Command exited with code 1)
19/05/27 02:25:59 INFO StandaloneSchedulerBackend: Executor app-20190527062557-0000/0 removed: Command exited with code 1
19/05/27 02:25:59 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20190527062557-0000/1 on worker-20190527062533-172.18.0.3-44351 (172.18.0.3:44351) with 1 core(s)
19/05/27 02:25:59 INFO StandaloneSchedulerBackend: Granted executor ID app-20190527062557-0000/1 on hostPort 172.18.0.3:44351 with 1 core(s), 1024.0 MB RAM
19/05/27 02:25:59 INFO BlockManagerMaster: Removal of executor 0 requested
19/05/27 02:25:59 INFO CoarseGrainedSchedulerBackend$DriverEndpoint: Asked to remove non-existent executor 0
19/05/27 02:25:59 INFO BlockManagerMasterEndpoint: Trying to remove executor 0 from BlockManagerMaster.
19/05/27 02:25:59 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/1 is now RUNNING
19/05/27 02:26:01 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/1 is now EXITED (Command exited with code 1)
19/05/27 02:26:01 INFO StandaloneSchedulerBackend: Executor app-20190527062557-0000/1 removed: Command exited with code 1
19/05/27 02:26:01 INFO BlockManagerMasterEndpoint: Trying to remove executor 1 from BlockManagerMaster.
19/05/27 02:26:01 INFO BlockManagerMaster: Removal of executor 1 requested
19/05/27 02:26:01 INFO CoarseGrainedSchedulerBackend$DriverEndpoint: Asked to remove non-existent executor 1
19/05/27 02:26:01 INFO StandaloneAppClient$ClientEndpoint: Executor added: app-20190527062557-0000/2 on worker-20190527062533-172.18.0.3-44351 (172.18.0.3:44351) with 1 core(s)
19/05/27 02:26:01 INFO StandaloneSchedulerBackend: Granted executor ID app-20190527062557-0000/2 on hostPort 172.18.0.3:44351 with 1 core(s), 1024.0 MB RAM
19/05/27 02:26:01 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/2 is now RUNNING
19/05/27 02:26:03 INFO StandaloneAppClient$ClientEndpoint: Executor updated: app-20190527062557-0000/2 is now EXITED (Command exited with code 1)

from the worker container I see the job fails with the following exception

Caused by: java.io.IOException: Failed to connect to DESKTOP-PCH5L6D:53511
        at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:245)
        at org.apache.spark.network.client.TransportClientFactory.createClient(TransportClientFactory.java:187)
        at org.apache.spark.rpc.netty.NettyRpcEnv.createClient(NettyRpcEnv.scala:198)
        at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:194)
        at org.apache.spark.rpc.netty.Outbox$$anon$1.call(Outbox.scala:190)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.UnknownHostException: DESKTOP-PCH5L6D
        at java.net.InetAddress.getAllByName0(InetAddress.java:1281)
        at java.net.InetAddress.getAllByName(InetAddress.java:1193)
        at java.net.InetAddress.getAllByName(InetAddress.java:1127)
        at java.net.InetAddress.getByName(InetAddress.java:1077)

Body:
added the additional parameter extra_hosts to fix the issue as shown below

version: "3.7"
services:
  spark-master:
    image: cmishr4/spark:latest
    container_name: spark-master
    hostname: spark-master
    ports:
      - "8080:8080"
      - "7077:7077"
    volumes:
      - ./../share:/share

    privileged: true
    networks:
      - spark-network
    environment:
      - "SPARK_MASTER_PORT=7077"
      - "SPARK_MASTER_WEBUI_PORT=8080"
    command: "sh start-master.sh"
  spark-worker:
    image: cmishr4/spark:latest
    depends_on:
      - spark-master
    ports:
      - 8080
    volumes:
      - ./../share:/share

    privileged: true
    networks:
      - spark-network
    extra_hosts:
        - "DESKTOP-PCH5L6D:10.0.75.1"
    environment:
      - "SPARK_MASTER=spark://spark-master:7077"
      - "SPARK_WORKER_WEBUI_PORT=8080"
    command: "sh start-worker.sh"
networks:
  spark-network:
    driver: bridge
    ipam:
      driver: default


问:
How can I find the position of an object (not an int) inside a c++ 2d vector?
I need to track the position of objects (Boxes) in a grid for a candycrush-like game I am developing.

The easiest way I found to keep track of their positions in the grid would be to add them to a 2d vector, move them inside the vector according to the game logic. That is easy.

The hard part, and where I’m actually stuck is to get their current position on the grid at any given time, or in this case, the position inside the 2d vector.
In short, if I had and easy way to periodically check the position of my Box object inside its 2d array, that would solve the problem.

I've been messing around with std:find and std: count, but I am a bit of a newbie and I’m having a hard time. Same of the code below:

```<code>#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

struct position
{
    int x;
    int y;
};

class Box
{
public:
    position currentPosition;

};

int main(int argc, const char * argv[])
{

    Box box1 = Box();
    Box box2 = Box();
    Box box3 = Box();
    Box box4 = Box();
    Box box5 = Box();
    Box box6 = Box();
    Box box7 = Box();
    Box box8 = Box();
    Box box9 = Box();

   // vector<vector<Box>> boxes2dVector;
//
    vector<vector<Box>> boxes2dVector =
    {
        {box1, box2,box3},
        {box4, box5,box6},
        {box7, box8,box9}

    };

    return 0;
}

position getPositionOfBox (Box box, vector<vector<Box>> vct)
{
    position resultPositon;

    /*
     This is what I need...some code that finds the position in the of a Box object in side a 2d array
     */

    return resultPositon;
};
</code>```

Any ideas or help, anyone?

Many thanks!

答: You could try using an std::unordered_map where the key is the box and the value is it's position in the array. Otherwise, I'd recommend storing its coordinate in the box itself. Iterating through the entire array each time would give O(N) performance. As long as you update the std::unordered_map appropriately, I believe lookup would be O(1).</p>

Body:
I need to track the position of objects (Boxes) in a grid for a candycrush-like game I am developing.

The easiest way I found to keep track of their positions in the grid would be to add them to a 2d vector, move them inside the vector according to the game logic. That is easy.

The hard part, and where I’m actually stuck is to get their current position on the grid at any given time, or in this case, the position inside the 2d vector.
In short, if I had and easy way to periodically check the position of my Box object inside its 2d array, that would solve the problem.

I've been messing around with std:find and std: count, but I am a bit of a newbie and I’m having a hard time. Same of the code below:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

struct position
{
    int x;
    int y;
};

class Box
{
public:
    position currentPosition;

};

int main(int argc, const char * argv[])
{

    Box box1 = Box();
    Box box2 = Box();
    Box box3 = Box();
    Box box4 = Box();
    Box box5 = Box();
    Box box6 = Box();
    Box box7 = Box();
    Box box8 = Box();
    Box box9 = Box();

   // vector<vector<Box>> boxes2dVector;
//
    vector<vector<Box>> boxes2dVector =
    {
        {box1, box2,box3},
        {box4, box5,box6},
        {box7, box8,box9}

    };

    return 0;
}

position getPositionOfBox (Box box, vector<vector<Box>> vct)
{
    position resultPositon;

    /*
     This is what I need...some code that finds the position in the of a Box object in side a 2d array
     */

    return resultPositon;
};

Any ideas or help, anyone?

Many thanks!


问:
DrawImage Blurs Image Despite Same Source/Destination Dimensions
I need to copy a little Bitmap that I generated to a larger object (say PictureBox) so I'm using DrawImage to do that but the result duplicate is blurry as if GDI+ is trying to scale the image except that both PageUnits are identical, the DPI resolution is identical, the source and destination rectangles are the same width and height.

If the source and destination X,Y points are 0,0 then DrawImage works perfectly, but if I change the destination X.Y position to anything else (even though width and height are the same) then the result is blurry.

I've tried every overload of DrawImage and the results are always the same. Unless the origin and destination X,Y positions are identical, the image will be blurry.

private void DrawStringVerticalStackingV4(string text, Graphics g, SizeF sizeMaxArea, PointF startPoint, Font font, Brush brush, StringFormat sf)
        {
            Bitmap bmp = new Bitmap(100, 10, g);
            Graphics gBmp = Graphics.FromImage(bmp);

            gBmp.PageUnit = g.PageUnit;

            // Some stuff being drawn...

            // Draw the bitmap on the original canvas
            RectangleF destRect = new RectangleF(startPoint.X, startPoint.Y, gBmp.VisibleClipBounds.Width, gBmp.VisibleClipBounds.Height);
            RectangleF srcRect = new RectangleF(0, 0, gBmp.VisibleClipBounds.Width, gBmp.VisibleClipBounds.Height);

            g.DrawImage(bmp, destRect, srcRect, g.PageUnit);

            // Housekeeping
         }
```

Unless destRect and srcRect have the same X and Y, the result is ever so slightly distorted as if GDI+ is trying to scale the image.

答:
After playing around with this further, Hans Passant was correct. Setting Graphics.InterpolationMode to NearestNeighbour worked perfectly.

This issue only occurs if your PageUnit is anything else but Pixels. My little brain considers this a logical bug because both source and destination rectangles had the exact same width and height. The only thing that was different was the destination X and Y positions. No distortion should have occurred.

Thank you very much for the help!

Body:
I need to copy a little Bitmap that I generated to a larger object (say PictureBox) so I'm using DrawImage to do that but the result duplicate is blurry as if GDI+ is trying to scale the image except that both PageUnits are identical, the DPI resolution is identical, the source and destination rectangles are the same width and height.

If the source and destination X,Y points are 0,0 then DrawImage works perfectly, but if I change the destination X.Y position to anything else (even though width and height are the same) then the result is blurry.

I've tried every overload of DrawImage and the results are always the same. Unless the origin and destination X,Y positions are identical, the image will be blurry.

private void DrawStringVerticalStackingV4(string text, Graphics g, SizeF sizeMaxArea, PointF startPoint, Font font, Brush brush, StringFormat sf)
        {
            Bitmap bmp = new Bitmap(100, 10, g);
            Graphics gBmp = Graphics.FromImage(bmp);

            gBmp.PageUnit = g.PageUnit;

            // Some stuff being drawn...

            // Draw the bitmap on the original canvas
            RectangleF destRect = new RectangleF(startPoint.X, startPoint.Y, gBmp.VisibleClipBounds.Width, gBmp.VisibleClipBounds.Height);
            RectangleF srcRect = new RectangleF(0, 0, gBmp.VisibleClipBounds.Width, gBmp.VisibleClipBounds.Height);

            g.DrawImage(bmp, destRect, srcRect, g.PageUnit);

            // Housekeeping
         }

Unless destRect and srcRect have the same X and Y, the result is ever so slightly distorted as if GDI+ is trying to scale the image.


问:
Script time zone issue
The script running in the wrong time zone should be GMT+2

I tried changing the spreadsheet settings and project properties.

```<code>    function onEdit(e) {
   var TIME_ZONE = "GMT+2";
  var date = Utilities.formatDate(new Date(),"Africa/Johannesburg", 'hh:mm:ss');

  //if column A has been edited, set date in same row in column B
  if (e.range.getColumn() == 1) {
    var row = e.range.getRow();
    e.source.getSheetByName('validated').getRange(row, 2).setValue(date);
  }
}
</code>```

Even tried this :

```<code>var date = Utilities.formatDate(new Date(), TIME_ZONE, 'hh:mm:ss');
</code>```

Need the time stamp to set to the current time on Edit.

答:
Change your format to hh:mm:ss a, adding a will set format to desired AM/PM range. See the SimpleDateFormat class specification on Oracle for more details on how to correctly format dates with Utilities.formatDate() method.
If there is still a problem, please, refer to my earlier comment.

Title: Script time zone issue

Body:
The script running in the wrong time zone should be GMT+2

I tried changing the spreadsheet settings and project properties.

    function onEdit(e) {
   var TIME_ZONE = "GMT+2";
  var date = Utilities.formatDate(new Date(),"Africa/Johannesburg", 'hh:mm:ss');

  //if column A has been edited, set date in same row in column B
  if (e.range.getColumn() == 1) {
    var row = e.range.getRow();
    e.source.getSheetByName('validated').getRange(row, 2).setValue(date);
  }
}

Even tried this :

var date = Utilities.formatDate(new Date(), TIME_ZONE, 'hh:mm:ss');

Need the time stamp to set to the current time on Edit.


问:
How to convert duration format ( dd HH mm ) to linera minutes in flutter?
my goal is to display a circular progress bar in function of different duration. To simplify my calculation I search to convert duration, for example I have 00days 02hours 30minutes I want 150min</p>

答:
You can try with abs method. e.g.

```<code>var d = Duration(hours: 2,minutes: 30);
print(d.abs().inMinutes); // 150
</code>```

Hope this help.

Body:
You can try with abs method. e.g.

var d = Duration(hours: 2,minutes: 30);
print(d.abs().inMinutes); // 150

Hope this help.


问:
Not all of the elements after an async/await in an Array.map() call get resolved
I have posted a question in this post earlier. It finally shows some output after changing synchronous functions into asynchronous; however, it turns out that in the output array, some of the elements are null. I am not sure why?

the main code looks like this:

```<code>router.post('/form1',  async (req, res, next)=>{

try{
    const emdate = new Date(req.body.emdate);
    const address = req.body.address;
    const stationDataCursor = stationData.filteredData(instantData, emdate);

    stationDataCursor.toArray().then(async (docArr)=>{

            return await Promise.all(docArr.map(async function(val, ind){

                try {
                    const feature = await calcDSV.calcDSV(val);
                    return feature

                } catch (error) {

                    console.log(ind);
                    console.log("Error happened in data array", error);

                }

            }));

    }).then((doc)=>{
        res.json(doc)
    })

} catch(error){
    res.status(400).send(error)
}
})
</code>```

I tried add Promise.resolve(featureJSON) in the return of calcDSV(val)

```<code>async function calcDSV(featuresJSON){

    // featuresJSON
    const SVscore = [];
    const tuEval = featuresJSON.features.properties.TU90; // array
    const obArr = featuresJSON.features.properties.OB; // array
    const periodObj = await getPeriods(tuEval);// get period position
    const paramObj = await getParams(periodObj, obArr); // get parameters
    const periodDate =  await getPeriodDate(featuresJSON, periodObj);
    const removeTime =  periodDate.beginDate.map(x=>x.split('T')[0]);

    let hourly = paramObj.hourCounts;
    let avgTemps = paramObj.avgTemps;

    for(let i = 0;i<hourly.length; i++){

        let score = await assignScore(avgTemps[i], hourly[i]);
        SVscore.push(score);

    }

    // output sv score for date

    const aggreScore = await accumScore(removeTime, SVscore);

    aggreScore.DSVdate = aggreScore.Date.map(x=>new Date(x));

    featuresJSON.features.properties.periodSV = SVscore;
    featuresJSON.features.properties.Periods = periodDate;
    featuresJSON.features.properties.DSVscore = aggreScore;

    return  Promise.resolve(featuresJSON);
}

module.exports.calcDSV = calcDSV;
</code>```

The error message:

```<code>2
Error happened in data array ReferenceError: error is not defined
at getParams (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/periodFunc.js:145:9)
at Object.calcDSV (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/wallinLogic.js:842:32)
at processTicksAndRejections (internal/process/task_queues.js:86:5)
6
Error happened in data array ReferenceError: error is not defined
at getParams (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/periodFunc.js:145:9)
at Object.calcDSV (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/wallinLogic.js:842:32)
at processTicksAndRejections (internal/process/task_queues.js:86:5)
...
</code>```

I expect every element would be resolved.

答: Thanks to the comments, I was able to find out the source: the throw error() in other functions I defined. It should be throw Error().

Body:
I have posted a question in this post earlier. It finally shows some output after changing synchronous functions into asynchronous; however, it turns out that in the output array, some of the elements are null. I am not sure why?

the main code looks like this:

router.post('/form1',  async (req, res, next)=>{

try{
    const emdate = new Date(req.body.emdate);
    const address = req.body.address;
    const stationDataCursor = stationData.filteredData(instantData, emdate);

    stationDataCursor.toArray().then(async (docArr)=>{

            return await Promise.all(docArr.map(async function(val, ind){

                try {
                    const feature = await calcDSV.calcDSV(val);
                    return feature

                } catch (error) {

                    console.log(ind);
                    console.log("Error happened in data array", error);

                }

            }));

    }).then((doc)=>{
        res.json(doc)
    })

} catch(error){
    res.status(400).send(error)
}
})

I tried add Promise.resolve(featureJSON) in the return of calcDSV(val)

async function calcDSV(featuresJSON){

    // featuresJSON
    const SVscore = [];
    const tuEval = featuresJSON.features.properties.TU90; // array
    const obArr = featuresJSON.features.properties.OB; // array
    const periodObj = await getPeriods(tuEval);// get period position
    const paramObj = await getParams(periodObj, obArr); // get parameters
    const periodDate =  await getPeriodDate(featuresJSON, periodObj);
    const removeTime =  periodDate.beginDate.map(x=>x.split('T')[0]);

    let hourly = paramObj.hourCounts;
    let avgTemps = paramObj.avgTemps;

    for(let i = 0;i<hourly.length; i++){

        let score = await assignScore(avgTemps[i], hourly[i]);
        SVscore.push(score);

    }

    // output sv score for date

    const aggreScore = await accumScore(removeTime, SVscore);

    aggreScore.DSVdate = aggreScore.Date.map(x=>new Date(x));

    featuresJSON.features.properties.periodSV = SVscore;
    featuresJSON.features.properties.Periods = periodDate;
    featuresJSON.features.properties.DSVscore = aggreScore;

    return  Promise.resolve(featuresJSON);
}

module.exports.calcDSV = calcDSV;

The error message:

2
Error happened in data array ReferenceError: error is not defined
at getParams (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/periodFunc.js:145:9)
at Object.calcDSV (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/wallinLogic.js:842:32)
at processTicksAndRejections (internal/process/task_queues.js:86:5)
6
Error happened in data array ReferenceError: error is not defined
at getParams (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/periodFunc.js:145:9)
at Object.calcDSV (/media/swaggyp1985/HDD4T/OSU_Projects_2017-2018/App_Projects/wallin_model/dev/dev_js/wallin-server/src/utils/wallinLogic.js:842:32)
at processTicksAndRejections (internal/process/task_queues.js:86:5)
...

I expect every element would be resolved.


问:
String separation in required format, Pythonic way? (with or w/o Regex)
I have a string in the format:

```<code>t='@abc @def Hello this part is text'
</code>```

I want to get this:

```<code>l=["abc", "def"]
s='Hello this part is text'
</code>```

I did this:

```<code>a=t[t.find(' ',t.rfind('@')):].strip()
s=t[:t.find(' ',t.rfind('@'))].strip()
b=a.split('@')
l=[i.strip() for i in b][1:]
</code>```

It works for the most part, but it fails when the text part has the '@'.
Eg, when:

```<code>t='@abc @def My email is red@hjk.com'
</code>```

it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.

Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.

What is a pythonic way of solving this?

答:
Here's just another variation that uses split() and no regexpes:

```<code>t='@abc @def My email is red@hjk.com'
tags = []
words = iter(t.split())

# iterate over words until first non-tag word
for w in words:
  if not w.startswith("@"):
    # join this word and all the following
    s = w + " " + (" ".join(words))
    break
  tags.append(w[1:])
else:
  s = "" # handle string with only tags

print tags, s
</code>```

Here's a shorter but perhaps a bit cryptic version that uses a regexp to find the first space followed by a non-@ character:

```<code>import re
t = '@abc @def My email is red@hjk.com @extra bye'
m = re.search(r"\s([^@].*)$", t)
tags = [tag[1:] for tag in t[:m.start()].split()]
s = m.group(1)
print tags, s # ['abc', 'def'] My email is red@hjk.com @extra bye
</code>```

This doesn't work properly if there are no tags or no text. The format is underspecified. You'll need to provide more test cases to validate.

OwnerDisplayName: becomingGuru

ContentLicense: CC BY-SA 2.5

Body:
I have a string in the format:

t='@abc @def Hello this part is text'

I want to get this:

l=["abc", "def"]
s='Hello this part is text'

I did this:

a=t[t.find(' ',t.rfind('@')):].strip()
s=t[:t.find(' ',t.rfind('@'))].strip()
b=a.split('@')
l=[i.strip() for i in b][1:]

It works for the most part, but it fails when the text part has the '@'.
Eg, when:

t='@abc @def My email is red@hjk.com'

it fails. The @names are there in the beginning and there can be text after @names, which may possibly contain @.

Clearly I can append initally with a space and find out first word without '@'. But that doesn't seem an elegant solution.

What is a pythonic way of solving this?

Body:
Here's just another variation that uses split() and no regexpes:

t='@abc @def My email is red@hjk.com'
tags = []
words = iter(t.split())

# iterate over words until first non-tag word
for w in words:
  if not w.startswith("@"):
    # join this word and all the following
    s = w + " " + (" ".join(words))
    break
  tags.append(w[1:])
else:
  s = "" # handle string with only tags

print tags, s

Here's a shorter but perhaps a bit cryptic version that uses a regexp to find the first space followed by a non-@ character:

import re
t = '@abc @def My email is red@hjk.com @extra bye'
m = re.search(r"\s([^@].*)$", t)
tags = [tag[1:] for tag in t[:m.start()].split()]
s = m.group(1)
print tags, s # ['abc', 'def'] My email is red@hjk.com @extra bye

This doesn't work properly if there are no tags or no text. The format is underspecified. You'll need to provide more test cases to validate.

OwnerDisplayName: Martin Vilcans

LastEditorDisplayName: Martin Vilcans


问:
decoding with jquery .serialize()
I all. I posted yesterday a question regarding dates not sent with jquery-ajax and found a solution with the .serialize() function.

Unfortunately the serialize() function decodes the date inputs and the result I get is this:

```<code>arrival= 13%2F04%2F2011 &departure= 28%2F04%2F2011 &ap_ID=2
</code>```

I know how use decodeURIComponent() for single fields post like this:

```<code> var arrivalVal = $('#arrival').val();

 arrivalVal = decodeURIComponent(arrival);
</code>```

but how do I use it for the long string made by the .serialize() function?

Sorry if this seems a pretty obvious question but can't get my way around it.

答: For php you can do urldecode function http://php.net/manual/en/function.urldecode.php

Title: decoding with jquery .serialize()

Body:
I all. I posted yesterday a question regarding dates not sent with jquery-ajax and found a solution with the .serialize() function.

Unfortunately the serialize() function decodes the date inputs and the result I get is this:

arrival= 13%2F04%2F2011 &departure= 28%2F04%2F2011 &ap_ID=2

I know how use decodeURIComponent() for single fields post like this:

 var arrivalVal = $('#arrival').val();

 arrivalVal = decodeURIComponent(arrival);

but how do I use it for the long string made by the .serialize() function?

Sorry if this seems a pretty obvious question but can't get my way around it.


问:
Can multiple service perform work parallelly at the same time
I am developing an app which has multiple features which need to perform work in the background.

Each feature needs to run at the same time and perform some work parallelly.

Currently, I am using JobIntentService to perform work but I have noticed that when I try to run multiple JobIntentServices then only one run while others are made to wait and executed one by one.

I am planning to use the Service. I want to know can 5 services run at the same time and perform work parallelly?

If no then is there any alternative?

Any help would be grateful.

答: Yes. It is possible to run services parallelly in Android.


问:
Get identical elements and index from 2 Arrays in Perl
I am new in Perl and I am trying to solve the following comparison.

I have two arrays:

@A = ("Red", "Green", "Yellow");

@B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");

In array A, each element occurs only once.

In array B, each element can occur zero, one or many times.

For every element in A, the code should lists the position at which it is present in B and give the output as following:

> Red at index 3.

> Green is missing.

> Yellow at index 0, 2 and 5.

> Elements from B were detected 4 times in A.

I tried the following but I cannot figure out how to list indexes of elements after comparing two arrays

```<code>foreach $x (@A){
    foreach $y (@B){
    if ($y eq $x){
    print "$y\n";
    }
    elsif ($x ne$y){
    print "$x";
    }
  }
}
</code>```

Can someone please, help me? Thank you very much in advance!
Rebi

答:
Here is an example:</p>

```<code>my @A = ("Red", "Green", "Yellow");
my @B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my %indices;
for my $i (0..$#B) {
    push @{ $indices{$B[$i]} }, $i;
}
my $count = 0;
for (@A) {
    if (exists $indices{$_} ) {
        my @temp = @{ $indices{$_} };
        $count += (scalar @temp);
        print "$_ is at index: ", @temp, "\n";
    }
    else {
        print "$_ is missing\n";
    }
}
print "Elements from B were detected ", $count, " times in A.\n";
</code>```

Body:
I am new in Perl and I am trying to solve the following comparison.

I have two arrays:

@A = ("Red", "Green", "Yellow");

@B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");

In array A, each element occurs only once.

In array B, each element can occur zero, one or many times.

For every element in A, the code should lists the position at which it is present in B and give the output as following:

> Red at index 3.

> Green is missing.

> Yellow at index 0, 2 and 5.

> Elements from B were detected 4 times in A.

I tried the following but I cannot figure out how to list indexes of elements after comparing two arrays

foreach $x (@A){
    foreach $y (@B){
    if ($y eq $x){
    print "$y\n";
    }
    elsif ($x ne$y){
    print "$x";
    }
  }
}

Can someone please, help me? Thank you very much in advance!
Rebi

Body:
Here is an example:

my @A = ("Red", "Green", "Yellow");
my @B = ("Yellow", "Black","Yellow","Red", "White", "Yellow");
my %indices;
for my $i (0..$#B) {
    push @{ $indices{$B[$i]} }, $i;
}
my $count = 0;
for (@A) {
    if (exists $indices{$_} ) {
        my @temp = @{ $indices{$_} };
        $count += (scalar @temp);
        print "$_ is at index: ", @temp, "\n";
    }
    else {
        print "$_ is missing\n";
    }
}
print "Elements from B were detected ", $count, " times in A.\n";


问:
Problems with deleting messages that were fetched
Trying to delete messages from a certain user, but nothing happens:</p>

```<code>bot.js
client.on("message", (message) => {
            if (message.content === '$deleteuser') {

                message.channel.fetchMessages({limit: 10}).then(collected => { //collected is a Collection
                    collected.forEach(msg => {
                        if (message.author.id === '474851505908875266') {
                            message.delete(0);
                        }

                    });
                });
            }

        });
</code>```

答:
First of all, your issue arises from your mistaken use of message instead of msg inside your forEach() callback (as @Gruntzy has pointed out). As declared, message is the message parameter of your event, while msg is the message of the forEach()'s iteration. Therefore, when you use message inside the callback, you're interacting with the original event message.

Secondly, your code would cause a rate limit to occur because of the separate Message.delete() calls. Use TextChannel.bulkDelete().

Improved code:

client.on('message', async message => {
  if (message.content === '$deleteuser') {
    try {
      const toDelete = [];

      const fetched = await message.channel.fetchMessages({ limit: 10 });
      fetched.forEach(msg => {
        if (msg.author.id === '474851505908875266') toDelete.push(msg.id);
      });

      await message.channel.bulkDelete(toDelete);
    } catch(err) {
      console.error(err);
    }
  }
});
```

Body:
Trying to delete messages from a certain user, but nothing happens:

bot.js
client.on("message", (message) => {
            if (message.content === '$deleteuser') {

                message.channel.fetchMessages({limit: 10}).then(collected => { //collected is a Collection
                    collected.forEach(msg => {
                        if (message.author.id === '474851505908875266') {
                            message.delete(0);
                        }

                    });
                });
            }

        });


问:
How to add a user to app in portal.azure's enterprise applications?
In Azure Portal in my Azure Active Directory in Enterprise Aplications I have an app. Is it possible to add someone to the users group via Microsopht.Graph to this app?</p>

答:
I think you're after the Add Member option

Use this API to add a member to an Office 365 Group, a security group, or a mail-enabled security group through the members navigation property.

You can add users or other groups. Important: You can add only users to Office 365 Groups.

https://learn.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0&tabs=javascript


问:
Deadlock when using fork, exec and pipes in a parallel environment
I am spawning a child process using fork and exec. Using two pipes to provide input and receive output from that process.

It works just fine most of the time but when I use something like openmp to test how it performs in concurrent environments it hangs in the read syscall, or waitpid sometimes.

When I straceed the child process I found that it is also blocked on the read syscall. Which is weird because I only wait on reading in the parent process after I've provided all of my input and closed the write end of the pipe.

I tried to create an MVCE but it is sort of long. I don't know how to make it any shorter. I removed most of the error checking code for the sake of simplicity.

Note that there are no globals in my code. And I'm not trying to read/write from the same file descriptors in multiple threads.

I can't think of what could go wrong. So hopefully you guys can spot what I'm doing wrong.

There goes:

```<code>#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <limits.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

size_t
min(size_t first, size_t second)
{
    if(first < second)
    {
        return first;
    }

    return second;
}

struct RDI_Buffer
{
    char* data;
    size_t size;
};

typedef struct RDI_Buffer RDI_Buffer;

RDI_Buffer
rdi_buffer_init()
{
    RDI_Buffer b = {0};
    return b;
}

RDI_Buffer
rdi_buffer_new(size_t size)
{
    RDI_Buffer b;

    b.data = malloc(size);
    b.size = size;
    return b;
}

void
rdi_buffer_free(RDI_Buffer b)
{
    if(!b.data)
    {
        return;
    }

    free(b.data);
}

RDI_Buffer
rdi_buffer_resize(RDI_Buffer b, size_t new_size)
{
    if(!b.data)
    {
        return rdi_buffer_new(new_size);
    }

    char* new_data = realloc(b.data, new_size);

    if(new_data)
    {
        b.size = new_size;
        b.data = new_data;
        return b;
    }

    RDI_Buffer output = rdi_buffer_new(new_size);
    memcpy(output.data, b.data, output.size);
    rdi_buffer_free(b);
    return output;
}

RDI_Buffer
rdi_buffer_null_terminate(RDI_Buffer b)
{
    b = rdi_buffer_resize(b, b.size + 1);
    b.data[b.size - 1] = '\0';
    return b;
}

static RDI_Buffer
rw_from_fd(int w_fd, int r_fd, RDI_Buffer input)
{
    const size_t CHUNK_SIZE = 4096;

    assert(input.size <= CHUNK_SIZE);

    write(w_fd, input.data, input.size);
    close(w_fd);

    RDI_Buffer output = rdi_buffer_new(CHUNK_SIZE);

    read(r_fd, output.data, CHUNK_SIZE);

    close(r_fd);
    return output;
}

int main()
{
#pragma omp parallel for
    for(size_t i = 0; i < 100; i++)
    {
        char* thing =
                "Hello this is a sort of long text so that we can test how "
                "well this works. It should go with cat and be printed.";

        RDI_Buffer input_buffer;
        input_buffer.data = thing;
        input_buffer.size = strlen(thing);

        int main_to_sub[2];
        int sub_to_main[2];

        pipe(main_to_sub);
        pipe(sub_to_main);

        int pid = fork();

        if(pid == 0)
        {
            dup2(main_to_sub[0], STDIN_FILENO);
            dup2(sub_to_main[1], STDOUT_FILENO);

            close(main_to_sub[1]);
            close(main_to_sub[0]);
            close(sub_to_main[1]);
            close(sub_to_main[0]);

            char* argv[] = {"cat", NULL};

            execvp("cat", argv);
            exit(1);
        }

        close(main_to_sub[0]);
        close(sub_to_main[1]);

        RDI_Buffer output =
                rw_from_fd(main_to_sub[1], sub_to_main[0], input_buffer);

        int *status = NULL;
        waitpid(pid, status, 0);

        if(status)
        {
            printf("%d\n", *status);
        }

        output = rdi_buffer_null_terminate(output);

        if(strcmp(output.data, thing) == 0)
        {
            printf("good\n");
        }
        else
        {
            printf("bad\n");
        }

        rdi_buffer_free(output);
    }
}
</code>```

Make sure you compile and link with -fopenmp. Like so: gcc main.c -fopenmp

答:
Converting comments into an answer.

You could be running out of file descriptors. With parallelism, 100 iterations of a loop that creates 4 file descriptors on each iteration could run into trouble if the limit is about 256 descriptors. Yes, you close some of them fast, but fast enough? That's not clear. And indeterminacy of scheduling would easily account for the varying behaviour.

The way I understand openmp is that it goes into the loop body n times at a time where n is the number of threads (am I wrong?). So at any single time I should never have more than n*2 file descriptors which on my machine should be around 24.

It’s probably n*4 file descriptors, but there may be limits on the parallelism.  I'm not sufficiently familiar with OpenMP to comment authoritatively on that.  Are there pragmas other than the for loop one that should be set?  It isn't clear to me that running the code shown introduced parallelism on a Mac when the code is compiled with Clang — which doesn't complain about the #pragma, unlike GCC 9.1.0 which does warn about the unknown pragma under my default compilation options.

However, with forks and execs as well as threads, life gets tricky. File descriptors may not be being closed that should be being closed because file descriptors are a process-level resource, so thread 1 may create file descriptors that thread 2 doesn’t know about, but which it does share. And then when thread 2 forks, the file descriptors created by thread 1 aren’t closed, preventing the cat from detecting EOF properly, etc.

One way to verify this would be to use a function like this:

```<code>#include <sys/stat.h>

static void dump_descriptors(int max_fd)
{
    struct stat sb;
    for (int fd = 0; fd <= max_fd; fd++)
        putchar((fstat(fd, &sb) == 0) ? 'o' : '-');
    putchar('\n');
    fflush(stdout);
}
</code>```

and in the child code, call it with a suitable number (64 perhaps — there could be a case for using a number as large as 404).  Although it is tempting to try using flockfile(stdout) and funlockfile(stdout) in the function, it is pointless if it is only called in the child process because the child is single-threaded and therefore there won't be any interference from other threads in the process.  However, it is all too feasible that different processes might interfere with each other's output.

If you're going to use dump_descriptor() from the parent process threads, then add flockfile(stdout); before the loop and funlockfile(stdout); after the fflush() call.  I'm not sure how much that will interfere with the problem; it enforces single threading through that function because none of the other threads can write to stdout while one thread has it locked.

However, when I tested it with a slightly modified version of the code which output the PID before the 'good' and 'bad' lines, and before the dump_descriptors() output, I never saw any interleaving of operations.  I got output like:

```<code>14128: ooooooo----------------------------------------------------------
14128: good
14129: ooooooo----------------------------------------------------------
14129: good
14130: ooooooo----------------------------------------------------------
14130: good
…
14225: ooooooo----------------------------------------------------------
14225: good
14226: ooooooo----------------------------------------------------------
14226: good
14227: ooooooo----------------------------------------------------------
14227: good
</code>```

which strongly suggests there was no parallelism in the code.  And when there is no parallelism, you won't see the trouble.  Each time, there are 4 descriptors for the pipes, and the code carefully closes them.

Consider redirecting the descriptor map to a file (or one file per child) in your scenario, where you may actually be getting serious parallelism.

Note that mixing threads with fork() is inherently difficult (as John Bollinger noted) — you normally use one or the other mechanism, not both.

Body:
I am spawning a child process using fork and exec. Using two pipes to provide input and receive output from that process.

It works just fine most of the time but when I use something like openmp to test how it performs in concurrent environments it hangs in the read syscall, or waitpid sometimes.

When I straceed the child process I found that it is also blocked on the read syscall. Which is weird because I only wait on reading in the parent process after I've provided all of my input and closed the write end of the pipe.

I tried to create an MVCE but it is sort of long. I don't know how to make it any shorter. I removed most of the error checking code for the sake of simplicity.

Note that there are no globals in my code. And I'm not trying to read/write from the same file descriptors in multiple threads.

I can't think of what could go wrong. So hopefully you guys can spot what I'm doing wrong.

There goes:

#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <limits.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>

size_t
min(size_t first, size_t second)
{
    if(first < second)
    {
        return first;
    }

    return second;
}

struct RDI_Buffer
{
    char* data;
    size_t size;
};

typedef struct RDI_Buffer RDI_Buffer;

RDI_Buffer
rdi_buffer_init()
{
    RDI_Buffer b = {0};
    return b;
}

RDI_Buffer
rdi_buffer_new(size_t size)
{
    RDI_Buffer b;

    b.data = malloc(size);
    b.size = size;
    return b;
}

void
rdi_buffer_free(RDI_Buffer b)
{
    if(!b.data)
    {
        return;
    }

    free(b.data);
}

RDI_Buffer
rdi_buffer_resize(RDI_Buffer b, size_t new_size)
{
    if(!b.data)
    {
        return rdi_buffer_new(new_size);
    }

    char* new_data = realloc(b.data, new_size);

    if(new_data)
    {
        b.size = new_size;
        b.data = new_data;
        return b;
    }

    RDI_Buffer output = rdi_buffer_new(new_size);
    memcpy(output.data, b.data, output.size);
    rdi_buffer_free(b);
    return output;
}

RDI_Buffer
rdi_buffer_null_terminate(RDI_Buffer b)
{
    b = rdi_buffer_resize(b, b.size + 1);
    b.data[b.size - 1] = '\0';
    return b;
}

static RDI_Buffer
rw_from_fd(int w_fd, int r_fd, RDI_Buffer input)
{
    const size_t CHUNK_SIZE = 4096;

    assert(input.size <= CHUNK_SIZE);

    write(w_fd, input.data, input.size);
    close(w_fd);

    RDI_Buffer output = rdi_buffer_new(CHUNK_SIZE);

    read(r_fd, output.data, CHUNK_SIZE);

    close(r_fd);
    return output;
}

int main()
{
#pragma omp parallel for
    for(size_t i = 0; i < 100; i++)
    {
        char* thing =
                "Hello this is a sort of long text so that we can test how "
                "well this works. It should go with cat and be printed.";

        RDI_Buffer input_buffer;
        input_buffer.data = thing;
        input_buffer.size = strlen(thing);

        int main_to_sub[2];
        int sub_to_main[2];

        pipe(main_to_sub);
        pipe(sub_to_main);

        int pid = fork();

        if(pid == 0)
        {
            dup2(main_to_sub[0], STDIN_FILENO);
            dup2(sub_to_main[1], STDOUT_FILENO);

            close(main_to_sub[1]);
            close(main_to_sub[0]);
            close(sub_to_main[1]);
            close(sub_to_main[0]);

            char* argv[] = {"cat", NULL};

            execvp("cat", argv);
            exit(1);
        }

        close(main_to_sub[0]);
        close(sub_to_main[1]);

        RDI_Buffer output =
                rw_from_fd(main_to_sub[1], sub_to_main[0], input_buffer);

        int *status = NULL;
        waitpid(pid, status, 0);

        if(status)
        {
            printf("%d\n", *status);
        }

        output = rdi_buffer_null_terminate(output);

        if(strcmp(output.data, thing) == 0)
        {
            printf("good\n");
        }
        else
        {
            printf("bad\n");
        }

        rdi_buffer_free(output);
    }
}

Make sure you compile and link with -fopenmp. Like so: gcc main.c -fopenmp

Body:
Converting comments into an answer.

You could be running out of file descriptors. With parallelism, 100 iterations of a loop that creates 4 file descriptors on each iteration could run into trouble if the limit is about 256 descriptors. Yes, you close some of them fast, but fast enough? That's not clear. And indeterminacy of scheduling would easily account for the varying behaviour.

The way I understand openmp is that it goes into the loop body n times at a time where n is the number of threads (am I wrong?). So at any single time I should never have more than n*2 file descriptors which on my machine should be around 24.

It’s probably n*4 file descriptors, but there may be limits on the parallelism.  I'm not sufficiently familiar with OpenMP to comment authoritatively on that.  Are there pragmas other than the for loop one that should be set?  It isn't clear to me that running the code shown introduced parallelism on a Mac when the code is compiled with Clang — which doesn't complain about the #pragma, unlike GCC 9.1.0 which does warn about the unknown pragma under my default compilation options.

However, with forks and execs as well as threads, life gets tricky. File descriptors may not be being closed that should be being closed because file descriptors are a process-level resource, so thread 1 may create file descriptors that thread 2 doesn’t know about, but which it does share. And then when thread 2 forks, the file descriptors created by thread 1 aren’t closed, preventing the cat from detecting EOF properly, etc.

One way to verify this would be to use a function like this:

#include <sys/stat.h>

static void dump_descriptors(int max_fd)
{
    struct stat sb;
    for (int fd = 0; fd <= max_fd; fd++)
        putchar((fstat(fd, &sb) == 0) ? 'o' : '-');
    putchar('\n');
    fflush(stdout);
}

and in the child code, call it with a suitable number (64 perhaps — there could be a case for using a number as large as 404).  Although it is tempting to try using flockfile(stdout) and funlockfile(stdout) in the function, it is pointless if it is only called in the child process because the child is single-threaded and therefore there won't be any interference from other threads in the process.  However, it is all too feasible that different processes might interfere with each other's output.

If you're going to use dump_descriptor() from the parent process threads, then add flockfile(stdout); before the loop and funlockfile(stdout); after the fflush() call.  I'm not sure how much that will interfere with the problem; it enforces single threading through that function because none of the other threads can write to stdout while one thread has it locked.

However, when I tested it with a slightly modified version of the code which output the PID before the 'good' and 'bad' lines, and before the dump_descriptors() output, I never saw any interleaving of operations.  I got output like:

14128: ooooooo----------------------------------------------------------
14128: good
14129: ooooooo----------------------------------------------------------
14129: good
14130: ooooooo----------------------------------------------------------
14130: good
…
14225: ooooooo----------------------------------------------------------
14225: good
14226: ooooooo----------------------------------------------------------
14226: good
14227: ooooooo----------------------------------------------------------
14227: good

which strongly suggests there was no parallelism in the code.  And when there is no parallelism, you won't see the trouble.  Each time, there are 4 descriptors for the pipes, and the code carefully closes them.

Consider redirecting the descriptor map to a file (or one file per child) in your scenario, where you may actually be getting serious parallelism.

Note that mixing threads with fork() is inherently difficult (as John Bollinger noted) — you normally use one or the other mechanism, not both.


问:
"Cannot GET" error when doing href to file in parent folder
I am trying to link to another html file which is located in a different folder. The files are in the following folders:

Wevdev/DigitalMedia/image1.html

and the other is in:

Webdev/Labs/Directory.html

Hyperlinks are working when linking between files in the same folder but getting an error when trying to link to a file in a different folder.

```<code><img src="arrow-3D-green-left.jpg">
<a href="http://wikipedia.com"><img src="rome1.jpg"></a>
<img src="arrow-3D-green-right.jpg"><br>

<h1>Image 1</h1>

<a href="=../Labs/Directory.html">Link to directory</a>
</code>```

The page opens in chrome with the following error message:

Cannot GET /Labs/Directory.html

答:
This is where the problem is. You must move two directories back:

```<code><a href="../../Labs/Directory.html">Link to directory</a>
</code>```

Moving back once ../ doesn't take you to the parrent directory.

Copy and paste this and try.

Body:
I am trying to link to another html file which is located in a different folder. The files are in the following folders:

Wevdev/DigitalMedia/image1.html

and the other is in:

Webdev/Labs/Directory.html

Hyperlinks are working when linking between files in the same folder but getting an error when trying to link to a file in a different folder.

Image 1

Link to directory

The page opens in chrome with the following error message:

Cannot GET /Labs/Directory.html

Body:
This is where the problem is. You must move two directories back:

<a href="../../Labs/Directory.html">Link to directory</a>

Moving back once ../ doesn't take you to the parrent directory.

Copy and paste this and try.