问:
Unable to Accept/Deny the location permission popup on Android devices while executing the scripts on Amazon Device Farm
link of location popup image I am trying to execute the automation scripts(Appium+Java+TestNG/Junit) on Amazon DeviceFarm but while executing, scripts were unable to perform any action((Access/Deny) on Location permission popup.Couldn't see any error logs in console. I have used normal click() operation as well as alert() function. Nothing works in this case.

Please help me.Below is the piece of code that I have tried..

```<code>        WebDriverWait wait = new WebDriverWait(android, 5);
        wait.until(ExpectedConditions.alertIsPresent());
        driver.switchTo().alert().dismiss();
        }catch(Throwable t) {
            System.out.println("Not an alert popup or alert is not present..");
            driver.findElement(By.id("idofthelocator")).click();
        }
</code>```

答:
With Android Appium tests it should possible to dismiss permissions popups by setting the capability autoGrantPermission to true. This capability will evaluate the application for the permission it need and run and adb command to grant the app access. Here is the code in the Appium project that does that:

https://github.com/appium/appium-android-driver/blob/959e07d84dc9d09a11735872259ac87511d03b85/lib/android-helpers.js#L334

https://github.com/appium/appium-adb/blob/e6bdc234e7dcf61e0252aad3ac7ab47491fe3720/lib/tools/adb-commands.js#L186

Can you try this capability and let us know if that helps?

With iOS Appium tests the capability autoGrantPermission does NOT work with Appium version less then 1.9.1 because there's not way through Apple APIs to predict the permission necessary or accept them. A workaround is to either find the element manually by printing the page source and checking for it on the fly or use the following lines to take advantage of the selenium methods:

```<code>driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
</code>```

In the more recent versions of Appium changes were made to use the autoGrantPermission capability valid with iOS tests. Here is the PR for that request

https://github.com/appium/appium-xcuitest-driver/commit/f5267acab3bc9285161397fa19a8daf60ae0c6ae

Can you let us know which Appium version you're using in this case and provide some of the Appium server logs from the run in Device Farm and your local execution?

Body:
link of location popup image I am trying to execute the automation scripts(Appium+Java+TestNG/Junit) on Amazon DeviceFarm but while executing, scripts were unable to perform any action((Access/Deny) on Location permission popup.Couldn't see any error logs in console. I have used normal click() operation as well as alert() function. Nothing works in this case.

Please help me.Below is the piece of code that I have tried..

        WebDriverWait wait = new WebDriverWait(android, 5);
        wait.until(ExpectedConditions.alertIsPresent());
        driver.switchTo().alert().dismiss();
        }catch(Throwable t) {
            System.out.println("Not an alert popup or alert is not present..");
            driver.findElement(By.id("idofthelocator")).click();
        }

Body:
With Android Appium tests it should possible to dismiss permissions popups by setting the capability autoGrantPermission to true. This capability will evaluate the application for the permission it need and run and adb command to grant the app access. Here is the code in the Appium project that does that:

https://github.com/appium/appium-android-driver/blob/959e07d84dc9d09a11735872259ac87511d03b85/lib/android-helpers.js#L334

https://github.com/appium/appium-adb/blob/e6bdc234e7dcf61e0252aad3ac7ab47491fe3720/lib/tools/adb-commands.js#L186

Can you try this capability and let us know if that helps?

With iOS Appium tests the capability autoGrantPermission does NOT work with Appium version less then 1.9.1 because there's not way through Apple APIs to predict the permission necessary or accept them. A workaround is to either find the element manually by printing the page source and checking for it on the fly or use the following lines to take advantage of the selenium methods:

driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();

In the more recent versions of Appium changes were made to use the autoGrantPermission capability valid with iOS tests. Here is the PR for that request

https://github.com/appium/appium-xcuitest-driver/commit/f5267acab3bc9285161397fa19a8daf60ae0c6ae

Can you let us know which Appium version you're using in this case and provide some of the Appium server logs from the run in Device Farm and your local execution?


来源: stackexchange

问:
Ball is bouncing from the centre not the edge
I have coded a ball to bounce around on a canvas, however, the ball only bounces from the centre, not the edge.

I have already tried putting the radius instead of the x and y but that didn't help at all, as of right now I am out of ideas.

I expect the ball to bounce of the edges of itself rather than the centre of it

```<code><!DOCTYPE>
<html>

<head>
<title>Ball Bounce</title>

<style>

canvas {
border-width: 5px;
border-style: ridge;
border-color: #FF0000;
}

</style>

</head>

<body>

<canvas id="testCanvas" width="700" height="400"></canvas>

<script>

var canvas = document.getElementById("testCanvas");
var ctx = canvas.getContext("2d");

var x = 300;
var y = 300;
var radius = 50;
var circleColour = "green";

var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var dx = 2;
var dy = -2;

function circle(x, y, r, c) {
ctx.beginPath();
ctx.arc(x, y, r, 0, 2 * Math.PI, false);
ctx.fillStyle = c;
ctx.fill()
ctx.closePath();
}

function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
circle(x, y, radius, circleColour)
if (y<0 || y > canvasHeight){
dy = -dy;
}

if (x>canvasWidth || x<0){
dx = -dx;
}

 x = x + dx;
 y = y + dy;
}

setInterval(draw, 5.5);

</script>

</body>

</html>
</code>```

答:
I have already tried putting the radius instead of the x and y but that didn't help at all...

You need to combine the radius with x and y (or the canvas edges) to make sure the ball changes direction at all four borders.

```<code>if (y - radius < 0 || y + radius > canvasHeight) {
    dy = -dy;
}

if (x + radius > canvasWidth || x - radius < 0) {
    dx = -dx;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have coded a ball to bounce around on a canvas, however, the ball only bounces from the centre, not the edge.

I have already tried putting the radius instead of the x and y but that didn't help at all, as of right now I am out of ideas.

I expect the ball to bounce of the edges of itself rather than the centre of it

<!DOCTYPE>

<title>Ball Bounce</title>

<canvas id="testCanvas" width="700" height="400"></canvas>

Body:
I have already tried putting the radius instead of the x and y but that didn't help at all...

You need to combine the radius with x and y (or the canvas edges) to make sure the ball changes direction at all four borders.

if (y - radius < 0 || y + radius > canvasHeight) {
    dy = -dy;
}

if (x + radius > canvasWidth || x - radius < 0) {
    dx = -dx;
}


问:
Swift: What is the difference between casting using as / as? / as! keywords and a C-style cast?
I've noticed that I can cast a closure that has regular arguments to a closure that has its arguments wrapped in a tuple. But only if I use a particular method of casting!

```<code>let myClosure = { (a: Int, b: Float) -> Void in
    print(a, b)
}

// I want to convert the closure to be of this type.
var myClosureWithTupleArgVar: (((Int, Float)) -> Void)? = nil

// Cast A is possible.
myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)
myClosureWithTupleArgVar?((1, 2))

// Cast B will always fail and return nil (as warned by the compiler).
myClosureWithTupleArgVar = myClosure as? (((Int, Float)) -> Void)
myClosureWithTupleArgVar?((3, 4))
</code>```

Outputs:

```<code>1 2.0
</code>```

Why is it possible to cast using cast A but not cast B? What is the difference between using an as Swift-style cast and the C-style function call cast?

(I am not interested in the difference between as, as?, and as!)

答:
First of all, it's worth noting that:

```<code>myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)
</code>```

is not a C-style cast, as casting in Swift is done with the as/as?/as! operators.

Rather, this is syntactic sugar for:

```<code>myClosureWithTupleArgVar = Optional<((Int, Float)) -> Void>(myClosure)
</code>```

which is a call to Optional's initialiser init(_ some: Wrapped).

The reason why a (Int, Float) -> Void function can be converted to a ((Int, Float)) -> Void function through Optional's initialiser is because Swift currently implements a special argument conversion that can transform a function with N parameters to a function that takes a single N-element tuple parameter.

For example:

```<code>typealias TupleTakingFn = ((Int, Float)) -> Void
func giveMeATupleTakingFn(_ fn: @escaping TupleTakingFn) -> TupleTakingFn {
  return fn
}

let myClosure = { (a: Int, b: Float) -> Void in
  print(a, b)
}

let myClosureWithTupleArgVar = giveMeATupleTakingFn(myClosure)
</code>```

This conversion is only done as a special case of an argument conversion, which can only be taken when passing an argument to a parameter. It therefore cannot be used in other cases such as direct assignment or type-casting through as/as/as!, which is why your cast fails.

Okay, but why does this special conversion exist? Well, in Swift 3 you used to be able to freely convert an N-arity function to an N-element tuple taking function (and vice versa), allowing the following to compile:

```<code>func foo(_ x: Int, _ y: Int) {}
func bar(_ x: (Int, Int)) {}

let fn1: (Int, Int) -> Void = bar   // ✅
let fn2: ((Int, Int)) -> Void = foo // ✅
</code>```

This was a remnant of the tuple splatting behaviour removed by SE-0029, and was therefore removed in Swift 4 by SE-0110, meaning that an N-arity function can now only be used where an N-arity function is expected:

```<code>let fn1: (Int, Int) -> Void = bar   // ❌
let fn2: ((Int, Int)) -> Void = foo // ❌
</code>```

However, this change caused a usability regression, where the following example (amongst others) would no longer compile:

```<code>let dict = [5: ""]
let result = dict.map { key, value in
  (key + 1, value + "hello")
}
</code>```

This is due to the fact that we're attempting to pass a closure with two parameters to the method map(_:) which expects a function of type (Element) -> T, which in the case of Dictionary is ((key: Key, value: Value)) -> T.

To address this regression and keep the above code legal, the conversion from an N-arity function to an N-element tuple taking function was re-introduced, but only a special case for argument conversions:

[W]e will “back out” the SE-0110 change regarding function arguments
  from Swift 4.

Specifically, when passing an argument value of function type
  (including closures) to a parameter of function type, a
  multi-parameter argument function can be passed to a parameter whose
  function type accepts a single tuple (whose tuple elements match the
  parameter types of the argument function).

This therefore allows the above example to remain legal while banning such function conversions in other places. However it also has the unfortunate side-effect of allowing your example of:

```<code>myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)
</code>```

to compile.

Body:
I've noticed that I can cast a closure that has regular arguments to a closure that has its arguments wrapped in a tuple. But only if I use a particular method of casting!

let myClosure = { (a: Int, b: Float) -> Void in
    print(a, b)
}

// I want to convert the closure to be of this type.
var myClosureWithTupleArgVar: (((Int, Float)) -> Void)? = nil

// Cast A is possible.
myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)
myClosureWithTupleArgVar?((1, 2))

// Cast B will always fail and return nil (as warned by the compiler).
myClosureWithTupleArgVar = myClosure as? (((Int, Float)) -> Void)
myClosureWithTupleArgVar?((3, 4))

Outputs:

1 2.0

Why is it possible to cast using cast A but not cast B? What is the difference between using an as Swift-style cast and the C-style function call cast?

(I am not interested in the difference between as, as?, and as!)

Body:
First of all, it's worth noting that:

myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)

is not a C-style cast, as casting in Swift is done with the as/as?/as! operators.

Rather, this is syntactic sugar for:

myClosureWithTupleArgVar = Optional<((Int, Float)) -> Void>(myClosure)

which is a call to Optional's initialiser init(_ some: Wrapped).

The reason why a (Int, Float) -> Void function can be converted to a ((Int, Float)) -> Void function through Optional's initialiser is because Swift currently implements a special argument conversion that can transform a function with N parameters to a function that takes a single N-element tuple parameter.

For example:

typealias TupleTakingFn = ((Int, Float)) -> Void
func giveMeATupleTakingFn(_ fn: @escaping TupleTakingFn) -> TupleTakingFn {
  return fn
}

let myClosure = { (a: Int, b: Float) -> Void in
  print(a, b)
}

let myClosureWithTupleArgVar = giveMeATupleTakingFn(myClosure)

This conversion is only done as a special case of an argument conversion, which can only be taken when passing an argument to a parameter. It therefore cannot be used in other cases such as direct assignment or type-casting through as/as/as!, which is why your cast fails.

Okay, but why does this special conversion exist? Well, in Swift 3 you used to be able to freely convert an N-arity function to an N-element tuple taking function (and vice versa), allowing the following to compile:

func foo(_ x: Int, _ y: Int) {}
func bar(_ x: (Int, Int)) {}

let fn1: (Int, Int) -> Void = bar   // ✅
let fn2: ((Int, Int)) -> Void = foo // ✅

This was a remnant of the tuple splatting behaviour removed by SE-0029, and was therefore removed in Swift 4 by SE-0110, meaning that an N-arity function can now only be used where an N-arity function is expected:

let fn1: (Int, Int) -> Void = bar   // ❌
let fn2: ((Int, Int)) -> Void = foo // ❌

However, this change caused a usability regression, where the following example (amongst others) would no longer compile:

let dict = [5: ""]
let result = dict.map { key, value in
  (key + 1, value + "hello")
}

This is due to the fact that we're attempting to pass a closure with two parameters to the method map(_:) which expects a function of type (Element) -> T, which in the case of Dictionary is ((key: Key, value: Value)) -> T.

To address this regression and keep the above code legal, the conversion from an N-arity function to an N-element tuple taking function was re-introduced, but only a special case for argument conversions:

[W]e will “back out” the SE-0110 change regarding function arguments
  from Swift 4.

Specifically, when passing an argument value of function type
  (including closures) to a parameter of function type, a
  multi-parameter argument function can be passed to a parameter whose
  function type accepts a single tuple (whose tuple elements match the
  parameter types of the argument function).

This therefore allows the above example to remain legal while banning such function conversions in other places. However it also has the unfortunate side-effect of allowing your example of:

myClosureWithTupleArgVar = (((Int, Float)) -> Void)?(myClosure)

to compile.


问:
How to get column width of Jtable after a user changes it
I would like to know how to get the column width after a user changes it so that i may save it off.

after messing around i came up with this method but it's not perfect. if the user doesn't actually select a column by clicking in a row of the column, the selected column is -1 thus throws an error so i prevented that with an if statement.

the next issue is, if i select a column then change the width, it works and prints out the width as i change the column, but if i selected say column 3 but then proceed to change column 2 width without selecting in row in that column 2, it will continue to spit out the width of column 3 as i change column 2.  so its working as expected with a select method, but there has to be a better way to get the width of the column i'm changing.

any ideas?

```<code>jt.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnRemoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnMoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnMarginChanged(ChangeEvent e) {
            int col = jt.getSelectedColumn();
            if (col >= 0) {
                TableColumn tc = jt.getColumnModel().getColumn(col);
                System.out.println(tc.getWidth());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub

        }

    });
</code>```

答:
You could try casting the source of the ChangeEvent to a TableColumn.

When you get a moment, try the following in your TableColumnModelListener...

```<code>jt.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
            // TODO Auto-generated method stub
        }

        public void columnRemoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub
        }

        public void columnMoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub
        }

        public void columnMarginChanged(ChangeEvent e) {

            Object source = e.getSource();
            if (source instanceof TableColumn) {

                TableColumn tableColumn = (TableColumn) source;

                System.out.println(tableColumn.getWidth());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub
        }
    });
</code>```

Body:
I would like to know how to get the column width after a user changes it so that i may save it off.

after messing around i came up with this method but it's not perfect. if the user doesn't actually select a column by clicking in a row of the column, the selected column is -1 thus throws an error so i prevented that with an if statement.

the next issue is, if i select a column then change the width, it works and prints out the width as i change the column, but if i selected say column 3 but then proceed to change column 2 width without selecting in row in that column 2, it will continue to spit out the width of column 3 as i change column 2.  so its working as expected with a select method, but there has to be a better way to get the width of the column i'm changing.

any ideas?

jt.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnRemoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnMoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnMarginChanged(ChangeEvent e) {
            int col = jt.getSelectedColumn();
            if (col >= 0) {
                TableColumn tc = jt.getColumnModel().getColumn(col);
                System.out.println(tc.getWidth());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub

        }

    });

Body:
You could try casting the source of the ChangeEvent to a TableColumn.

When you get a moment, try the following in your TableColumnModelListener...

jt.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
            // TODO Auto-generated method stub
        }

        public void columnRemoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub
        }

        public void columnMoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub
        }

        public void columnMarginChanged(ChangeEvent e) {

            Object source = e.getSource();
            if (source instanceof TableColumn) {

                TableColumn tableColumn = (TableColumn) source;

                System.out.println(tableColumn.getWidth());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub
        }
    });


问:
List of stored procedure which using another stored procedure
We have almost 2100+ stored procedure in database. we are not able to check each stored procedure to find out whether it is using another stored procedure or not.

Any query to find out same?

Thanks,

Dhruval Shah

答:
As long as you don't have dynamic SQL code, you can get the dependencies from SQL Server.

This article explains it pretty well.

ContentLicense: CC BY-SA 3.0


问:
Carousel Slider not changing Images
Image slider not working when i click on the arrows or when i try to manually change the image.

With my limited knowledge, i tried editing the code with no luck

```<code><link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="styles/style.css">

<div class="container" id="slider"><!-- Container Starts -->

  <div class="col-md-12"><!-- col-md-12 Starts -->

  <div id="myCarousel" class="carousel slide" data-ride="carousel"><!-- carousel slide Starts -->

    <ol class="carousel-indicators"><!-- carousel-indicators Starts -->

      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>

      <li data-target="#myCarousel" data-slide-to="1"></li>

      <li data-target="#myCarousel" data-slide-to="2"></li>

      <li data-target="#myCarousel" data-slide-to="3"></li>

    </ol><!-- carousel-indicators Ends -->

  <div class="carousel-inner"><!-- carousel-inner Starts -->

    <div class="item-active">
      <img src="admin_panel/slides_images/1.jpg" alt="slide 1">
    </div>

    <div class="item">
      <img src="admin_panel/slides_images/2.jpg" alt="slide 2">
    </div>

    <div class="item">
      <img src="admin_panel/slides_images/3.jpg" alt="slide 3">
    </div>

    <div class="item">
      <img src="admin_panel/slides_images/4.jpg" alt="slide 4">
    </div>

  </div><!-- carousel-inner Ends -->

  <a class="left carousel-control" href="#myCarousel" data-slide="prev"><!-- left carousel-control Starts -->

  <span class="glyphicon glyphicon-chevron-left"> </span>

  <span class="sr-only"> Previous </span>

  </a><!-- left carousel-control Ends -->

  <a class="right carousel-control" href="#myCarousel" data-slide="next"><!-- right carousel-control Starts -->

  <span class="glyphicon glyphicon-chevron-right"> </span>

  <span class="sr-only"> Next </span>

  </a><!-- right carousel-control Ends -->

</div><!-- carousel slide Ends -->

  </div><!-- col-md-12 Ends -->

  </div><!-- Container Ends -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
  </body>
</html>
</code>```

The slider is supposed to change when i click on the arrow or try and change it manually. No errors appear, just not the expected result.

答:
Use The Below Code

```<code><link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="styles/style.css">
<div class="container">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
     <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
     <li data-target="#myCarousel" data-slide-to="1"></li>
     <li data-target="#myCarousel" data-slide-to="2"></li>
     <li data-target="#myCarousel" data-slide-to="3"></li>
  </ol>
  <!-- Wrapper for slides -->
  <div class="carousel-inner">
     <div class="item active">
        <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" alt="slide 1" style="width:100%;">
     </div>
     <div class="item">
        <img src="https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="slide 2" style="width:100%;">
     </div>
     <div class="item">
        <img src="https://images.pexels.com/photos/326055/pexels-photo-326055.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="slide 3" style="width:100%;">
     </div>
     <div class="item">
        <img src="https://cdn.pixabay.com/photo/2018/10/30/16/06/water-lily-3784022__340.jpg" alt="slide 4">
     </div>
  </div>
  <!-- Left and right controls -->
  <a class="left carousel-control" href="#myCarousel" data-slide="prev">
  <span class="glyphicon glyphicon-chevron-left"></span>
  <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#myCarousel" data-slide="next">
  <span class="glyphicon glyphicon-chevron-right"></span>
  <span class="sr-only">Next</span>
  </a>
  </div>
</div>
<!-- Container Ends -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</body>
</html>
</code>```

Title: Carousel Slider not changing Images

Body:
Image slider not working when i click on the arrows or when i try to manually change the image.

With my limited knowledge, i tried editing the code with no luck

<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="styles/style.css">

   Previous

   Next

The slider is supposed to change when i click on the arrow or try and change it manually. No errors appear, just not the expected result.

Body:
Use The Below Code

<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="styles/style.css">
<div class="container">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
     <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
     <li data-target="#myCarousel" data-slide-to="1"></li>
     <li data-target="#myCarousel" data-slide-to="2"></li>
     <li data-target="#myCarousel" data-slide-to="3"></li>
  </ol>
  <!-- Wrapper for slides -->
  <div class="carousel-inner">
     <div class="item active">
        <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260" alt="slide 1" style="width:100%;">
     </div>
     <div class="item">
        <img src="https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" alt="slide 2" style="width:100%;">
     </div>
     <div class="item">
        <img src="https://images.pexels.com/photos/326055/pexels-photo-326055.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="slide 3" style="width:100%;">
     </div>
     <div class="item">
        <img src="https://cdn.pixabay.com/photo/2018/10/30/16/06/water-lily-3784022__340.jpg" alt="slide 4">
     </div>
  </div>
  <!-- Left and right controls -->
  <a class="left carousel-control" href="#myCarousel" data-slide="prev">
  <span class="glyphicon glyphicon-chevron-left"></span>
  <span class="sr-only">Previous</span>
  </a>
  <a class="right carousel-control" href="#myCarousel" data-slide="next">
  <span class="glyphicon glyphicon-chevron-right"></span>
  <span class="sr-only">Next</span>
  </a>
  </div>
</div>
<!-- Container Ends -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</body>
</html>


问:
How can I append Text to JTextArea with an own ActionListener Class after pressing Buttons
Hey I want a JFrame which has to Buttons "LeftButton" and "RightButton" and an JTextArea. After I press one of the two I want that the JTextArea writes which Buttons has been pressed in a new Line. In order to do this I want to use a MyActionListener Class with Referens to the JTextArea, which implements Actionlistener.

I´ve tried to give the ActionPerformed the JTextArea and realized I have to create Setters on their own. Then I realized that MyActionListener Class requires also an Object like JTextArea which is the same as in the JFrame Class. Then I found out that I have to update the JTextArea in the JFrame class as well and here I am a little bit stuck right now. I tried to put the Setters into the JFrame Class and call them from MyActionListener with no success and I tried to do something like A_18_c.south = south

package Aufgabe_18;

import javax.swing.*;
import java.awt.*;

public class A_18_c extends JFrame {
    private Button LeftButton;
    private Button RightButton;
    private JScrollPane scroll;
    private JTextArea south;
    private MyActionListener MAL;

    public static void main(String[] args) {
        A_18_c l = new A_18_c("Aufgabe18c");
    }

    public A_18_c(String title) {
        super(title);
        setSize(300, 150);
        this.setLocation(300, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        MAL = new MyActionListener(south);

        south = new JTextArea(5, 20);
        south.setEditable(false);
        JScrollPane sroll = new JScrollPane(south);
        this.add(sroll, BorderLayout.SOUTH);

        LeftButton = new Button("Left Button");
        LeftButton.setOpaque(true);
        LeftButton.addActionListener(MAL);
        this.add(LeftButton, BorderLayout.WEST);

        RightButton = new Button("Right Button");
        RightButton.setOpaque(true);
        RightButton.addActionListener(MAL);
        this.add(RightButton, BorderLayout.EAST);

        setVisible(true);
    }
}
```

<p>MyActionListener:</p>

<pre class="lang-java prettyprint-override"><code>package Aufgabe_18;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyActionListener implements ActionListener{

    private final JTextArea south;

    public MyActionListener(JTextArea south)
    {
        this.south = south;
    }

    private void setTextLeftButton(JTextArea south){
        south.append("Left Button \n");
    }

    private void setTextRightButton(JTextArea south){
        south.append("Right Button \n");
    }

@Override
        public void actionPerformed(ActionEvent e) {
        String a;
        Object src = e.getSource();
        Button b = null;
        b = (Button) src;
        a = b.getString();
        if (a == "LeftButton")
            setTextRightButton(south);
        if (a == "RightButton")
            setTextRightButton(south);
    }
}
</code>```

I expect the JTextArea to write which Button has been pressed, but nothing happens after pressing. No Errors popping up.

答:
I tried compiling your code on JDK8, it gave errors and I can see it has few issues.

First of all this:

```<code>MAL = new MyActionListener(south);

south = new JTextArea(5, 20);
south.setEditable(false);
</code>```

You are passing Null as parameter to your Listener. You have to initialize "south" first before passing it in the constructor to MAL. Also Button didn't have any method as getString. It has getLabel or getText for JButton. Also as @vince has said, add space in the in "LeftButton". I have tweaked a little with your code. Below is the working code. For simplicity I have added the custom Listener in the same file and replaced Button with JButton (You are already using swing's JFrame so its better try to use all swing components). You will get the gist with this:

```<code>import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;

public class Test extends JFrame {
    private JButton LeftButton;
    private JButton RightButton;
    private JScrollPane scroll;
    private JTextArea south;
    private MyActionListener MAL;

    public static void main(String[] args) {
        Test l = new Test("Aufgabe18c");
    }

    public Test(String title) {
        super(title);
        setSize(300, 150);
        this.setLocation(300, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        //initialize south
        south = new JTextArea(5, 20);
        south.setEditable(true);

        //pass it to your Listener
        MAL = new MyActionListener(south);
        JScrollPane scroll = new JScrollPane(south);
        this.add(scroll, BorderLayout.SOUTH);

        LeftButton = new JButton("Left Button");
        LeftButton.setOpaque(true);
        LeftButton.addActionListener(MAL);
        this.add(LeftButton, BorderLayout.WEST);

        RightButton = new JButton("Right Button");
        RightButton.setOpaque(true);
        RightButton.addActionListener(MAL);
        this.add(RightButton, BorderLayout.EAST);

        setVisible(true);
    }

public class MyActionListener implements ActionListener{

    private final JTextArea south;

    public MyActionListener(JTextArea south)
    {
        this.south = south;
    }

    private void setTextLeftButton(JTextArea south){
        south.append("Left Button \n");
    }

    private void setTextRightButton(JTextArea south){
        south.append("Right Button \n");
    }

@Override
        public void actionPerformed(ActionEvent e) {
        String a;
        Object src = e.getSource();
        JButton b = null;
        b = (JButton) src;
        a = b.getText();
        if (a == "Left Button")
            setTextLeftButton(south);
        else
            setTextRightButton(south);
    }
}
}
</code>```

Body:
Hey I want a JFrame which has to Buttons "LeftButton" and "RightButton" and an JTextArea. After I press one of the two I want that the JTextArea writes which Buttons has been pressed in a new Line. In order to do this I want to use a MyActionListener Class with Referens to the JTextArea, which implements Actionlistener.

I´ve tried to give the ActionPerformed the JTextArea and realized I have to create Setters on their own. Then I realized that MyActionListener Class requires also an Object like JTextArea which is the same as in the JFrame Class. Then I found out that I have to update the JTextArea in the JFrame class as well and here I am a little bit stuck right now. I tried to put the Setters into the JFrame Class and call them from MyActionListener with no success and I tried to do something like A_18_c.south = south

package Aufgabe_18;

import javax.swing.*;
import java.awt.*;

public class A_18_c extends JFrame {
    private Button LeftButton;
    private Button RightButton;
    private JScrollPane scroll;
    private JTextArea south;
    private MyActionListener MAL;

    public static void main(String[] args) {
        A_18_c l = new A_18_c("Aufgabe18c");
    }

    public A_18_c(String title) {
        super(title);
        setSize(300, 150);
        this.setLocation(300, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        MAL = new MyActionListener(south);

        south = new JTextArea(5, 20);
        south.setEditable(false);
        JScrollPane sroll = new JScrollPane(south);
        this.add(sroll, BorderLayout.SOUTH);

        LeftButton = new Button("Left Button");
        LeftButton.setOpaque(true);
        LeftButton.addActionListener(MAL);
        this.add(LeftButton, BorderLayout.WEST);

        RightButton = new Button("Right Button");
        RightButton.setOpaque(true);
        RightButton.addActionListener(MAL);
        this.add(RightButton, BorderLayout.EAST);

        setVisible(true);
    }
}

MyActionListener:

package Aufgabe_18;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MyActionListener implements ActionListener{

    private final JTextArea south;

    public MyActionListener(JTextArea south)
    {
        this.south = south;
    }

    private void setTextLeftButton(JTextArea south){
        south.append("Left Button \n");
    }

    private void setTextRightButton(JTextArea south){
        south.append("Right Button \n");
    }

@Override
        public void actionPerformed(ActionEvent e) {
        String a;
        Object src = e.getSource();
        Button b = null;
        b = (Button) src;
        a = b.getString();
        if (a == "LeftButton")
            setTextRightButton(south);
        if (a == "RightButton")
            setTextRightButton(south);
    }
}

I expect the JTextArea to write which Button has been pressed, but nothing happens after pressing. No Errors popping up.

Body:
I tried compiling your code on JDK8, it gave errors and I can see it has few issues.

First of all this:

MAL = new MyActionListener(south);

south = new JTextArea(5, 20);
south.setEditable(false);

You are passing Null as parameter to your Listener. You have to initialize "south" first before passing it in the constructor to MAL. Also Button didn't have any method as getString. It has getLabel or getText for JButton. Also as @vince has said, add space in the in "LeftButton". I have tweaked a little with your code. Below is the working code. For simplicity I have added the custom Listener in the same file and replaced Button with JButton (You are already using swing's JFrame so its better try to use all swing components). You will get the gist with this:

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;

public class Test extends JFrame {
    private JButton LeftButton;
    private JButton RightButton;
    private JScrollPane scroll;
    private JTextArea south;
    private MyActionListener MAL;

    public static void main(String[] args) {
        Test l = new Test("Aufgabe18c");
    }

    public Test(String title) {
        super(title);
        setSize(300, 150);
        this.setLocation(300, 300);
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        //initialize south
        south = new JTextArea(5, 20);
        south.setEditable(true);

        //pass it to your Listener
        MAL = new MyActionListener(south);
        JScrollPane scroll = new JScrollPane(south);
        this.add(scroll, BorderLayout.SOUTH);

        LeftButton = new JButton("Left Button");
        LeftButton.setOpaque(true);
        LeftButton.addActionListener(MAL);
        this.add(LeftButton, BorderLayout.WEST);

        RightButton = new JButton("Right Button");
        RightButton.setOpaque(true);
        RightButton.addActionListener(MAL);
        this.add(RightButton, BorderLayout.EAST);

        setVisible(true);
    }

public class MyActionListener implements ActionListener{

    private final JTextArea south;

    public MyActionListener(JTextArea south)
    {
        this.south = south;
    }

    private void setTextLeftButton(JTextArea south){
        south.append("Left Button \n");
    }

    private void setTextRightButton(JTextArea south){
        south.append("Right Button \n");
    }

@Override
        public void actionPerformed(ActionEvent e) {
        String a;
        Object src = e.getSource();
        JButton b = null;
        b = (JButton) src;
        a = b.getText();
        if (a == "Left Button")
            setTextLeftButton(south);
        else
            setTextRightButton(south);
    }
}
}


问:
Disposing of a BitmapImage after its been frozen
I created an image with this function:

```<code>private BitmapImage LoadImage(byte[] imageData)
{
    if (imageData == null || imageData.Length == 0) return null;
    var image = new BitmapImage();
    using (var mem = new MemoryStream(imageData))
    {
        mem.Position = 0;
        image.BeginInit();
        image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = null;
        image.StreamSource = mem;
        image.EndInit();
    }
    image.Freeze();
    return image;
}
</code>```

When I attempt to dispose it:

```<code>myImage.StreamSource.Close();
myImage.StreamSource.Dispose();

// Throws an exception since its frozen to read only
//myImage.StreamSource = null;

GC.Collect();
</code>```

It isn't collected by the garbage collector. Possibly since I can't set it to null.

How can I dispose this BitmapImage so it doesn't live longer in memory?

答:
In my case, I have need to switch between a bunch of large floor plans stored as byte arrays on a server. Once all of these are loaded into memory and after some switching between them, I was sitting at 3GB and started to get issues with anything being loaded at all. The images themselves range from 600KB to a few megabytes. When they are drawn, they take up a lot more room.

I found a wrapping stream implementation
 here (http://faithlife.codes/blog/2009/05/wrappingstream_implementation/) by Bradley Grainger.

This keeps my memory usage reasonably low; less than 2GB most of the time.

```<code>WrapperStream MasterStream{get;set;}

private void ChangeImage()
{
            SelectedImage = null;
            GC.Collect();
            var stream = new MemoryStream(ImageSource);

            using (MasterStream = new WrappingStream(stream))
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = MasterStream;
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.EndInit();
                bitmap.Freeze();
                SelectedImage = bitmap;
            }

            GC.Collect();

 }
</code>```

Body:
I created an image with this function:

private BitmapImage LoadImage(byte[] imageData)
{
    if (imageData == null || imageData.Length == 0) return null;
    var image = new BitmapImage();
    using (var mem = new MemoryStream(imageData))
    {
        mem.Position = 0;
        image.BeginInit();
        image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.UriSource = null;
        image.StreamSource = mem;
        image.EndInit();
    }
    image.Freeze();
    return image;
}

When I attempt to dispose it:

myImage.StreamSource.Close();
myImage.StreamSource.Dispose();

// Throws an exception since its frozen to read only
//myImage.StreamSource = null;

GC.Collect();

It isn't collected by the garbage collector. Possibly since I can't set it to null.

How can I dispose this BitmapImage so it doesn't live longer in memory?

Body:
In my case, I have need to switch between a bunch of large floor plans stored as byte arrays on a server. Once all of these are loaded into memory and after some switching between them, I was sitting at 3GB and started to get issues with anything being loaded at all. The images themselves range from 600KB to a few megabytes. When they are drawn, they take up a lot more room.

I found a wrapping stream implementation
 here (http://faithlife.codes/blog/2009/05/wrappingstream_implementation/) by Bradley Grainger.

This keeps my memory usage reasonably low; less than 2GB most of the time.

WrapperStream MasterStream{get;set;}

private void ChangeImage()
{
            SelectedImage = null;
            GC.Collect();
            var stream = new MemoryStream(ImageSource);

            using (MasterStream = new WrappingStream(stream))
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.StreamSource = MasterStream;
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.EndInit();
                bitmap.Freeze();
                SelectedImage = bitmap;
            }

            GC.Collect();

 }


问:
How to check if a string contains all characters (in any order) from other string?
I am going to try to give an example of what I am trying to solve. I think it's the best way to explain the problem.

I have 'for' cycle that generates numbers from X to Y. X is the lower value of the range that I enter in a textbox and Y is the upper value from that range.
For example:
1234 to 4321

So, the software generates values from 1234 to 4321 -> 1234,1235,1236,...,4320,4321.
    For I = 1234 to 4321

I want to add to a listbox only the generated values that contains all the numbers in the lower value textbox.
For example:

```<code>Lower value textbox = 12344
Generated values:
12344 -> valid because it contains 12344
12395 -> not valid because '5' is not contained in 12344
...
44231 -> valid because it contains 12344
41243 -> valid because it contains 12344
</code>```

I have wrote some code, but I am not coding it well because it's accepting non valid values when the original string (lower value textbox) contains repeated numbers. It works good when there are not repeated values.

I have tried different codes and I have found a link that seems to solve the problem to my question but I have not idea about how it works.
Check if a string contains all other strings

The code I have tried is:

```<code>

        Dim StartNumber As Integer = TextBox_InitialDigit.Text
        Dim FinalNumber As Integer = TextBox_FinalDigit.Text

        Dim AmountOfResults As Integer

        Dim StringOriginal As String = TextBox_InitialDigit.Text

        Dim ArraySubstrings As Char() = StringOriginal.ToCharArray()

        Dim ContainsAll = False

        For I = Convert.ToInt32(TextBox_InitialDigit.Text) To Convert.ToInt32(TextBox_FinalDigit.Text)

            For Each Character In ArraySubstrings
                If I.ToString.Contains(Character) Then
                    ContainsAll = True
                ElseIf Not I.ToString.Contains(Character) Then
                    ContainsAll = False
                    Exit For
                End If
            Next

            If ContainsAll = True Then
                ListBox1.Items.Add(I)
                AmountOfResults += 1
            End If

        Next

        Label_AmountOfResults.Text = "Total results: " & AmountOfResults
</code>```

The above code, as I explained, works ok if the original string (the one I type in textbox) does not contains repeated numbers.

I feel what I'm trying to do is extremely simple to implement but I'm just missing it. Any help will be greatly appreciated.

答:
You could verify whether the ordered sequence of numbers that compose the starting value has a correspondance in any of the numbers in the range [StartNumber] - [EndNumber].

Given this range of values:

```<code>Dim startNum As Integer = 21434
Dim endNum As Integer = 41350
</code>```

Compare the sequence of each generated value in the range and add it to a List(Of Integer) if it's a match.

All the matches found will be added to a ListBox in the end.

```<code>Dim startNChars As Char() = startNum.ToString().ToCharArray().OrderBy(Function(n) n).ToArray()
Dim validResults As New List(Of Integer)()
For i As Integer = startNum + 1 To endNum
    If i.ToString().ToCharArray().OrderBy(Function(n) n).SequenceEqual(startNChars) Then
        validResults.Add(i)
    End If
Next

ListBox1.DataSource = validResults
</code>```

Body:
I am going to try to give an example of what I am trying to solve. I think it's the best way to explain the problem.

I have 'for' cycle that generates numbers from X to Y. X is the lower value of the range that I enter in a textbox and Y is the upper value from that range.
For example:
1234 to 4321

So, the software generates values from 1234 to 4321 -> 1234,1235,1236,...,4320,4321.
    For I = 1234 to 4321

I want to add to a listbox only the generated values that contains all the numbers in the lower value textbox.
For example:

Lower value textbox = 12344
Generated values:
12344 -> valid because it contains 12344
12395 -> not valid because '5' is not contained in 12344
...
44231 -> valid because it contains 12344
41243 -> valid because it contains 12344

I have wrote some code, but I am not coding it well because it's accepting non valid values when the original string (lower value textbox) contains repeated numbers. It works good when there are not repeated values.

I have tried different codes and I have found a link that seems to solve the problem to my question but I have not idea about how it works.
Check if a string contains all other strings

The code I have tried is:

        Dim StartNumber As Integer = TextBox_InitialDigit.Text
        Dim FinalNumber As Integer = TextBox_FinalDigit.Text

        Dim AmountOfResults As Integer

        Dim StringOriginal As String = TextBox_InitialDigit.Text

        Dim ArraySubstrings As Char() = StringOriginal.ToCharArray()

        Dim ContainsAll = False

        For I = Convert.ToInt32(TextBox_InitialDigit.Text) To Convert.ToInt32(TextBox_FinalDigit.Text)

            For Each Character In ArraySubstrings
                If I.ToString.Contains(Character) Then
                    ContainsAll = True
                ElseIf Not I.ToString.Contains(Character) Then
                    ContainsAll = False
                    Exit For
                End If
            Next

            If ContainsAll = True Then
                ListBox1.Items.Add(I)
                AmountOfResults += 1
            End If

        Next

        Label_AmountOfResults.Text = "Total results: " & AmountOfResults

The above code, as I explained, works ok if the original string (the one I type in textbox) does not contains repeated numbers.

I feel what I'm trying to do is extremely simple to implement but I'm just missing it. Any help will be greatly appreciated.

Body:
You could verify whether the ordered sequence of numbers that compose the starting value has a correspondance in any of the numbers in the range [StartNumber] - [EndNumber].

Given this range of values:

Dim startNum As Integer = 21434
Dim endNum As Integer = 41350

Compare the sequence of each generated value in the range and add it to a List(Of Integer) if it's a match.

All the matches found will be added to a ListBox in the end.

Dim startNChars As Char() = startNum.ToString().ToCharArray().OrderBy(Function(n) n).ToArray()
Dim validResults As New List(Of Integer)()
For i As Integer = startNum + 1 To endNum
    If i.ToString().ToCharArray().OrderBy(Function(n) n).SequenceEqual(startNChars) Then
        validResults.Add(i)
    End If
Next

ListBox1.DataSource = validResults


问:
Problem with function to determine the winner of multiple rounds in a dice game
We have an assignment to determine the ultimately winner in a dice game. Here's the complete rules:

You will be pitted against two other computer players in this game. There are three rounds. At the beginning of each round a player rolls two dice. The total of your dice roll for that round is added to your points. Your points always start at zero. Each consecutive round the points are added to the total. At the end of the third round, whoever has the most points wins the game.

REQUIREMENTS
————————
Each player has two dice
The player rolls each die once per round
Display each players score at the end of each round
Display the leader of the round at the end of each round
Prompt the user to roll to begin the next around
After three rounds the game is over
The players score persists until the end of the game
Once the game ends, a winner is declared
Once a winner is declared you have the option to restart or quit

I've gotten everything to work, except how to determine the ultimate winner of the game. I've tried making a new method called "gameWinner", using if/elsif statements, grabbing the total scores from each round and adding each up respectively. However, the program breaks once it reaches that. I can't think of how else to solve this problems, but nothing I type seems to function right.

```<code>def welcome
    puts ""
    puts "Let's roll some die! You will be competing against 2 computers in 3 rounds, each player having 2 die."
    puts "Please enter your name and press 'Enter'"
    puts ""
    @userName = gets.chomp
    puts ("Welcome, " + @userName + ". Let's roll those die!")
    puts ""
end

def round(round)
    result_1 = Random.new.rand(1..6)
    result_2 = Random.new.rand(1..6)
    total_1 = result_1 + result_2

    result_3 = Random.new.rand(1..6)
    result_4 = Random.new.rand(1..6)
    total_2 = result_3 + result_4

    result_5 = Random.new.rand(1..6)
    result_6 = Random.new.rand(1..6)
    total_3 = result_5 + result_6

    winner = [total_1, total_2, total_3].max
    players = {total_1 => @userName, total_2 => "Computer 1", total_3 => "Computer 2"}.max

    puts "Round #{round}"
    puts "#{@userName}, your die are a #{result_1} and a #{result_2}, totaling #{total_1}"
    puts "Computer 1's die are a #{result_3} and a #{result_4}, totaling #{total_2}"
    puts "Computer 2's die are a #{result_5} and a #{result_6}, totaling #{total_3}"
    puts "Round #{round} highest score is: #{winner}"
        if total_1> total_2 && total_3
            puts "#{@userName} is the winner!"
        elsif total_2 > total_1 && total_3
            puts "Computer 1 is the winner!"
        elsif total_3 > total_1 && total_2
            puts "Computer 2 is the winner!"
        else
            puts "It was a tie, there are no winners."
        end
    puts ""
end

def gameWinner(rounds)
    if total_1> total_2 && total_3
        roundWinner1 = 1
    elsif total_2 > total_1 && total_3
        roundWinner2 = 1
    else total_3 > total_1 && total_2
        roundWinner3 = 1
    end

    gameSummary1 = roundWinner1 + roundWinner1 + roundWinner1
    gameSummary2 = roundWinner2 + roundWinner2 + roundWinner2
    gameSummary3 = roundWinner3 + roundWinner3 + roundWinner3
    winnerOA = [gameSummary1, gameSummary2, gameSummary3].max

    puts "The winner of the game is #{winnerOA}"
end

def playAgain
    puts "Would you like to start over? (Y/N)\n"
    answer = gets.chomp.upcase
    if answer == "Y"
        play
    elsif answer == "N"
        puts "Thank you for playing.\n"
    else
        playAgain
    end
  end

def play
    welcome
    round(1)
    round_1 = round(1)
    round(2)
    round(3)
    gameWinner
    playAgain
end

play
</code>```

I've expected the program to report the overall winner, but I'm just blanking on how to grab it.

Here is the error thrown by the gameWinner function:

Traceback (most recent call last): 2: from rollEm2.rb:83:in ' 1: from rollEm2.rb:79:in play' rollEm2.rb:44:in `gameWinner': wrong number of arguments (given 0, expected 1) (ArgumentError)

答:
The method gameWinner is being called without arguments but looks like the argument expected is not used in your method. So try to remove it from the definition:

```<code>def gameWinner
  #... your method code
end
</code>```

Body:
We have an assignment to determine the ultimately winner in a dice game. Here's the complete rules:

You will be pitted against two other computer players in this game. There are three rounds. At the beginning of each round a player rolls two dice. The total of your dice roll for that round is added to your points. Your points always start at zero. Each consecutive round the points are added to the total. At the end of the third round, whoever has the most points wins the game.

REQUIREMENTS
————————
Each player has two dice
The player rolls each die once per round
Display each players score at the end of each round
Display the leader of the round at the end of each round
Prompt the user to roll to begin the next around
After three rounds the game is over
The players score persists until the end of the game
Once the game ends, a winner is declared
Once a winner is declared you have the option to restart or quit

I've gotten everything to work, except how to determine the ultimate winner of the game. I've tried making a new method called "gameWinner", using if/elsif statements, grabbing the total scores from each round and adding each up respectively. However, the program breaks once it reaches that. I can't think of how else to solve this problems, but nothing I type seems to function right.

def welcome
    puts ""
    puts "Let's roll some die! You will be competing against 2 computers in 3 rounds, each player having 2 die."
    puts "Please enter your name and press 'Enter'"
    puts ""
    @userName = gets.chomp
    puts ("Welcome, " + @userName + ". Let's roll those die!")
    puts ""
end

def round(round)
    result_1 = Random.new.rand(1..6)
    result_2 = Random.new.rand(1..6)
    total_1 = result_1 + result_2

    result_3 = Random.new.rand(1..6)
    result_4 = Random.new.rand(1..6)
    total_2 = result_3 + result_4

    result_5 = Random.new.rand(1..6)
    result_6 = Random.new.rand(1..6)
    total_3 = result_5 + result_6

    winner = [total_1, total_2, total_3].max
    players = {total_1 => @userName, total_2 => "Computer 1", total_3 => "Computer 2"}.max

    puts "Round #{round}"
    puts "#{@userName}, your die are a #{result_1} and a #{result_2}, totaling #{total_1}"
    puts "Computer 1's die are a #{result_3} and a #{result_4}, totaling #{total_2}"
    puts "Computer 2's die are a #{result_5} and a #{result_6}, totaling #{total_3}"
    puts "Round #{round} highest score is: #{winner}"
        if total_1> total_2 && total_3
            puts "#{@userName} is the winner!"
        elsif total_2 > total_1 && total_3
            puts "Computer 1 is the winner!"
        elsif total_3 > total_1 && total_2
            puts "Computer 2 is the winner!"
        else
            puts "It was a tie, there are no winners."
        end
    puts ""
end

def gameWinner(rounds)
    if total_1> total_2 && total_3
        roundWinner1 = 1
    elsif total_2 > total_1 && total_3
        roundWinner2 = 1
    else total_3 > total_1 && total_2
        roundWinner3 = 1
    end

    gameSummary1 = roundWinner1 + roundWinner1 + roundWinner1
    gameSummary2 = roundWinner2 + roundWinner2 + roundWinner2
    gameSummary3 = roundWinner3 + roundWinner3 + roundWinner3
    winnerOA = [gameSummary1, gameSummary2, gameSummary3].max

    puts "The winner of the game is #{winnerOA}"
end

def playAgain
    puts "Would you like to start over? (Y/N)\n"
    answer = gets.chomp.upcase
    if answer == "Y"
        play
    elsif answer == "N"
        puts "Thank you for playing.\n"
    else
        playAgain
    end
  end

def play
    welcome
    round(1)
    round_1 = round(1)
    round(2)
    round(3)
    gameWinner
    playAgain
end

play

I've expected the program to report the overall winner, but I'm just blanking on how to grab it.

Here is the error thrown by the gameWinner function:

Traceback (most recent call last): 2: from rollEm2.rb:83:in ' 1: from rollEm2.rb:79:in play' rollEm2.rb:44:in `gameWinner': wrong number of arguments (given 0, expected 1) (ArgumentError)

Body:
The method gameWinner is being called without arguments but looks like the argument expected is not used in your method. So try to remove it from the definition:

def gameWinner
  #... your method code
end


答:
So you can do it using a simple reduceByKey operation on RDD.

INPUT RDD - RDD[STRING, LIST]

Output RDD - input.reduceByKey(x,y -> addFunction(x,y))

addFunction (x,y) iterates over the input lists and add the elements index wise and returns the added list

Title: Addition of elements in multiple list corresponding to a key column of RDD

Body:
I have PythonRDDs. I have to perform addition of elements for multiple lists. Add element 1 of list 1 to element 1 of list 2 then add to element 1 of list 3.
For Canada, add 47,59,77 as element 1, 97,98,63 as second element and so on.

I tried to flatten the list to add them and tried to convert to dataframe but I failed to do so. And I want to do it through all 3 ways

countryCounts = [
('CANADA','47;97;33;94;6'),
('CANADA','59;98;24;83;3'),
('CANADA','77;63;93;86;62'),
('CHINA','86;71;72;23;27'),
('CHINA','74;69;72;93;7'),
('CHINA','58;99;90;93;41'),
('ENGLAND','40;13;85;75;90'),
('ENGLAND','39;13;33;29;14'),
('ENGLAND','99;88;57;69;49'),
('GERMANY','67;93;90;57;3'),
('GERMANY','9;15;20;19'),
('GERMANY','77;64;46;95;48'),
('INDIA','90;49;91;14;70'),
('INDIA','70;83;38;27;16'),
('INDIA','86;21;19;59;4')
]
countryCountsRdd = sc.parallelize(countryCounts)
countryCountsSplit.collect()
countryCountsGroup=countryCountsSplit.groupByKey().mapValues(list)
countryCountsGroup.collect()
CountsSplit=countryCountsRdd.map(lambda x : (x[0], ",".join(x[1].split(';'))))
countryCountsSplit.collect()

Inputs :
Way 1
[('CANADA', [47, 97, 33, 94, 6]), ('CANADA', [59, 98, 24, 83, 3]), ('CANADA', [77, 63, 93, 86, 62]), ('CHINA', [86, 71, 72, 23, 27]), ('CHINA', [74, 69, 72, 93, 7]), ('CHINA', [58, 99, 90, 93, 41]), ('ENGLAND', [40, 13, 85, 75, 90]), ('ENGLAND', [39, 13, 33, 29, 14]), ('ENGLAND', [99, 88, 57, 69, 49]), ('GERMANY', [67, 93, 90, 57, 3]), ('GERMANY', [9, 15, 20, 19]), ('GERMANY', [77, 64, 46, 95, 48]), ('INDIA', [90, 49, 91, 14, 70]), ('INDIA', [70, 83, 38, 27, 16]), ('INDIA', [86, 21, 19, 59, 4])]
Way 2:
[('CANADA', [[47, 97, 33, 94, 6], [59, 98, 24, 83, 3], [77, 63, 93, 86, 62]]), ('CHINA', [[86, 71, 72, 23, 27], [74, 69, 72, 93, 7], [58, 99, 90, 93, 41]]), ('INDIA', [[90, 49, 91, 14, 70], [70, 83, 38, 27, 16], [86, 21, 19, 59, 4]]), ('ENGLAND', [[40, 13, 85, 75, 90], [39, 13, 33, 29, 14], [99, 88, 57, 69, 49]]), ('GERMANY', [[67, 93, 90, 57, 3], [9, 15, 20, 19], [77, 64, 46, 95, 48]])]
Way 3:
[('CANADA', '47 ,97 ,33 ,94 ,6'), ('CANADA', '59 ,98 ,24 ,83 ,3'), ('CANADA', '77 ,63 ,93 ,86 ,62'), ('CHINA', '86 ,71 ,72 ,23 ,27'), ('CHINA', '74 ,69 ,72 ,93 ,7'), ('CHINA', '58 ,99 ,90 ,93 ,41'), ('ENGLAND', '40 ,13 ,85 ,75 ,90'), ('ENGLAND', '39 ,13 ,33 ,29 ,14'), ('ENGLAND', '99 ,88 ,57 ,69 ,49'), ('GERMANY', '67 ,93 ,90 ,57 ,3'), ('GERMANY', '9 ,15 ,20 ,19'), ('GERMANY', '77 ,64 ,46 ,95 ,48'), ('INDIA', '90 ,49 ,91 ,14 ,70'), ('INDIA', '70 ,83 ,38 ,27 ,16'), ('INDIA', '86 ,21 ,19 ,59 ,4')]

Require same output for all 3 :
[('CANADA','183;258;150;263;71)]
[('CHINA','218,239,234,209,75')]
[('ENGLAND','178,114,175,173,153')]
[('GERMANY','144,166,151,172,70')]
[('INDIA','246,153,148,100,90')]


问:
ASP.NET losing connection to SQL Server Express after being published to IIS
I have an ASP.NET application that gets data from a SQL Server Express on the same computer. When I run the ASP.NET project from Visual Studio, the project can reach the database just fine. However, when published to IIS, the project loses the connection. Here is my connection string located in Web.config:

```<code><connectionStrings>
    <add name="conString"
         providerName="System.Data.SqlClient"
         connectionString="Server = DESKTOP-EVAN\SERVER;Database=master;User ID=sa;Password=12345;" />
</connectionStrings>
</code>```

The project can be reached on the published IIS, however no data is there and no error messages show.

I've added the application pool and NT Authority to the SQL login but still no luck connection to the database.

Does anyone have any experience with this? How can I get my published ASP.NET project to connect to my SQL Server Express?

答:
Have you tried removing the spaces for the server like this: </p>

```<code> Server=DESKTOP-EVAN\SERVER
</code>```

Body:
I have an ASP.NET application that gets data from a SQL Server Express on the same computer. When I run the ASP.NET project from Visual Studio, the project can reach the database just fine. However, when published to IIS, the project loses the connection. Here is my connection string located in Web.config:

<connectionStrings>
    <add name="conString"
         providerName="System.Data.SqlClient"
         connectionString="Server = DESKTOP-EVAN\SERVER;Database=master;User ID=sa;Password=12345;" />
</connectionStrings>

The project can be reached on the published IIS, however no data is there and no error messages show.

I've added the application pool and NT Authority to the SQL login but still no luck connection to the database.

Does anyone have any experience with this? How can I get my published ASP.NET project to connect to my SQL Server Express?

Body:
Have you tried removing the spaces for the server like this:

 Server=DESKTOP-EVAN\SERVER


问:
circle with dash lines uiview
I am trying to make a circle with dash lines. I am able to make lines in rectangle but I don't know how to make these in circle. Here is answer I got but it's in Objective-C: UIView Draw Circle with Dotted Line Border

Here is my code which makes a rectangle with dashed lines.

```<code>func addDashedBorder() {
    let color = UIColor.red.cgColor

    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath

    self.layer.addSublayer(shapeLayer)
}
</code>```

答:
Certainly you can just render your circular UIBezierPath with the selected dash pattern:

```<code>class DashedCircleView: UIView {
    private var shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 10
        shapeLayer.lineCap = .round
        shapeLayer.lineDashPattern = [20, 60]
        return shapeLayer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configure()
    }

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

    override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }
}

private extension DashedCircleView {
    func configure() {
        layer.addSublayer(shapeLayer)
    }

    func updatePath() {
        let rect = bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2)
        let radius = min(rect.width, rect.height) / 2
        let center = CGPoint(x: rect.midX, y: rect.midY)
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        shapeLayer.path = path.cgPath
    }
}
</code>```

That yields:

The problem with that approach is that it’s hard to get the dashed pattern to line up (notice the awkward dashing at the “3 o’clock” position). You can fix that by making sure that the two values of lineDashPattern add up to some number that evenly divides into the circumference of the circle (e.g. 2π × radius):

```<code>let circumference: CGFloat = 2 * .pi * radius
let count = 30
let relativeDashLength: CGFloat = 0.25
let dashLength = circumference / CGFloat(count)
shapeLayer.lineDashPattern = [dashLength * relativeDashLength, dashLength * (1 - relativeDashLength)] as [NSNumber]
</code>```

Alternatively, rather than using lineDashPattern at all, you can instead keep a solid stroke and make the path, itself, as a series of small arcs. That way I can achieve the desired dashed effect, but ensuring it’s evenly split into count little arcs as we rotate from 0 to 2π:

```<code>class DashedCircleView: UIView {
    private var shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 10
        shapeLayer.lineCap = .round
        return shapeLayer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configure()
    }

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

    override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }
}

private extension DashedCircleView {
    func configure() {
        layer.addSublayer(shapeLayer)
    }

    func updatePath() {
        let rect = bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2)
        let radius = min(rect.width, rect.height) / 2
        let center = CGPoint(x: rect.midX, y: rect.midY)

        let path = UIBezierPath()
        let count = 30
        let relativeDashLength: CGFloat = 0.25 // a value between 0 and 1
        let increment: CGFloat = .pi * 2 / CGFloat(count)

        for i in 0 ..< count {
            let startAngle = increment * CGFloat(i)
            let endAngle = startAngle + relativeDashLength * increment
            path.move(to: CGPoint(x: center.x + radius * cos(startAngle),
                                  y: center.y + radius * sin(startAngle)))
            path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        }
        shapeLayer.path = path.cgPath
    }
}
</code>```

That yields:

Title: circle with dash lines uiview

Body:
I am trying to make a circle with dash lines. I am able to make lines in rectangle but I don't know how to make these in circle. Here is answer I got but it's in Objective-C: UIView Draw Circle with Dotted Line Border

Here is my code which makes a rectangle with dashed lines.

func addDashedBorder() {
    let color = UIColor.red.cgColor

    let shapeLayer:CAShapeLayer = CAShapeLayer()
    let frameSize = self.frame.size
    let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)

    shapeLayer.bounds = shapeRect
    shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = color
    shapeLayer.lineWidth = 2
    shapeLayer.lineJoin = CAShapeLayerLineJoin.round
    shapeLayer.lineDashPattern = [6,3]
    shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 5).cgPath

    self.layer.addSublayer(shapeLayer)
}

Body:
Certainly you can just render your circular UIBezierPath with the selected dash pattern:

class DashedCircleView: UIView {
    private var shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 10
        shapeLayer.lineCap = .round
        shapeLayer.lineDashPattern = [20, 60]
        return shapeLayer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configure()
    }

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

    override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }
}

private extension DashedCircleView {
    func configure() {
        layer.addSublayer(shapeLayer)
    }

    func updatePath() {
        let rect = bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2)
        let radius = min(rect.width, rect.height) / 2
        let center = CGPoint(x: rect.midX, y: rect.midY)
        let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        shapeLayer.path = path.cgPath
    }
}

That yields:

The problem with that approach is that it’s hard to get the dashed pattern to line up (notice the awkward dashing at the “3 o’clock” position). You can fix that by making sure that the two values of lineDashPattern add up to some number that evenly divides into the circumference of the circle (e.g. 2π × radius):

let circumference: CGFloat = 2 * .pi * radius
let count = 30
let relativeDashLength: CGFloat = 0.25
let dashLength = circumference / CGFloat(count)
shapeLayer.lineDashPattern = [dashLength * relativeDashLength, dashLength * (1 - relativeDashLength)] as [NSNumber]

Alternatively, rather than using lineDashPattern at all, you can instead keep a solid stroke and make the path, itself, as a series of small arcs. That way I can achieve the desired dashed effect, but ensuring it’s evenly split into count little arcs as we rotate from 0 to 2π:

class DashedCircleView: UIView {
    private var shapeLayer: CAShapeLayer = {
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 10
        shapeLayer.lineCap = .round
        return shapeLayer
    }()

    override init(frame: CGRect = .zero) {
        super.init(frame: frame)
        configure()
    }

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

    override func layoutSubviews() {
        super.layoutSubviews()
        updatePath()
    }
}

private extension DashedCircleView {
    func configure() {
        layer.addSublayer(shapeLayer)
    }

    func updatePath() {
        let rect = bounds.insetBy(dx: shapeLayer.lineWidth / 2, dy: shapeLayer.lineWidth / 2)
        let radius = min(rect.width, rect.height) / 2
        let center = CGPoint(x: rect.midX, y: rect.midY)

        let path = UIBezierPath()
        let count = 30
        let relativeDashLength: CGFloat = 0.25 // a value between 0 and 1
        let increment: CGFloat = .pi * 2 / CGFloat(count)

        for i in 0 ..< count {
            let startAngle = increment * CGFloat(i)
            let endAngle = startAngle + relativeDashLength * increment
            path.move(to: CGPoint(x: center.x + radius * cos(startAngle),
                                  y: center.y + radius * sin(startAngle)))
            path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
        }
        shapeLayer.path = path.cgPath
    }
}

That yields:


问:
Conditional on non-instantiated variable
I am new to Bash scripting, having a lot more experience with C-type languages. I have written a few scripts with a conditional that checks the value of a non-instantiated variable and if it doesn't exist or match a value sets the variable. On top of that the whole thing is in a for loop. Something like this:

```<code>for i in ${!my_array[@]}; do
   if [ "${my_array[i]}" = true ]
   then
      #do something
   else
      my_array[i]=true;
   fi
done
</code>```

This would fail through a null pointer in Java since my_array[i] is not instantiated until after it is checked. Is this good practice in Bash? My script is working the way I designed, but I have learned that just because a kluge works now doesn't mean it will work in the future.

Thanks!

答:
You will find this page on parameter expansion helpful, as well as this one on conditionals.

An easy way to test a variable is to check it for nonzero length.

```<code>if [[ -n "$var" ]]
then : do stuff ...
</code>```

I also like to make it fatal to access a nonexisting variable; this means extra work, but better safety.

```<code>set -u # unset vars are fatal to access without exception handling
if [[ -n "${var:-}" ]] # handles unset during check
then : do stuff ...
</code>```

Body:
I am new to Bash scripting, having a lot more experience with C-type languages. I have written a few scripts with a conditional that checks the value of a non-instantiated variable and if it doesn't exist or match a value sets the variable. On top of that the whole thing is in a for loop. Something like this:

for i in ${!my_array[@]}; do
   if [ "${my_array[i]}" = true ]
   then
      #do something
   else
      my_array[i]=true;
   fi
done

This would fail through a null pointer in Java since my_array[i] is not instantiated until after it is checked. Is this good practice in Bash? My script is working the way I designed, but I have learned that just because a kluge works now doesn't mean it will work in the future.

Thanks!

Body:
You will find this page on parameter expansion helpful, as well as this one on conditionals.

An easy way to test a variable is to check it for nonzero length.

if [[ -n "$var" ]]
then : do stuff ...

I also like to make it fatal to access a nonexisting variable; this means extra work, but better safety.

set -u # unset vars are fatal to access without exception handling
if [[ -n "${var:-}" ]] # handles unset during check
then : do stuff ...


问:
Illuminate\Database\QueryException : SQLSTATE[42S02]: Base table or view not found: 1146 Table 'avatr.apps' doesn't exist (SQL: insert into `apps`
I'm trying to test my database with fake data. I wanted to run php artisan db:seed and i get an error. I am not sure how to solve it.</p>

```<code>//App factory.php file
<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use Faker\Generator as Faker;

$factory->define(\App\app::class, function (Faker $faker) {
return [
    //

        'id' => $faker -> randomDigit,
        'UNIQUE_ACCOUNT_IDENTIFIER' => $faker -> randomDigit,
        'ACTIVITY_PERIOD' => $faker -> sentence(10),
        'SALES_CHANNEL' => $faker -> sentence(10),
        'MARKETPLACE' => $faker -> sentence(10),
        'TRANSACTION_TYPE' => $faker -> sentence(10),
        'TRANSACTION_EVENT_ID' =>  $faker-> randomDigit,
        'ACTIVITY-TRANSACTION-ID'=>  $faker-> randomDigit,
        'TAX_CALCULATION_DATE' =>  $faker-> date($format = 'Y-m-d', $max
   = 'now'),
        'TRANSACTION_DEPART_DATE' =>  $faker-> date($format = 'Y-m-d',
   $max = 'now'),
        'TRANSACTION_ARRIVAL_DATE' =>  $faker-> date($format = 'Y-m-d',
   $max = 'now'),
        'TRANSACTION_COMPLETE_DATE' =>  $faker-> date($format = 'Y-m-d',
  $max = 'now'),
        'SELLER_SKU' => $faker -> sentence(10),
        'ASIN' => $faker -> sentence(10),
        'ITEM_DESCRIPTION' => $faker -> sentence(10),
        'ITEM_MANUFACTURE_COUNTRY' =>  $faker-> country,
        'QTY' =>  $faker-> randomDigit,
        'ITEM_WEIGHT' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_WEIGHT' => $faker-> randomDigit,
        'COST_PRICE_OF_ITEMS' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PROMO_PRICE_OF_ITEMS_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_PRICE_OF_ITEMS_AMT_VAT_EXCL' => $faker-> randomDigit,
        'SHIP_CHARGE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PROMO_SHIP_CHARGE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_SHIP_CHARGE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'GIFT_WRAP_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PROMO_GIFT_WRAP_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_GIFT_WRAP_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_VALUE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_VAT_RATE_PERCENT' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_VAT_AMT' => $faker-> randomDigit,
        'PROMO_PRICE_OF_ITEMS_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_PRICE_OF_ITEMS_VAT_AMT' => $faker-> randomDigit,
        'SHIP_CHARGE_VAT_RATE_PERCENT' => $faker-> randomDigit,
        'SHIP_CHARGE_VAT_AMT' => $faker-> randomDigit,
        'PROMO_SHIP_CHARGE_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_SHIP_CHARGE_VAT_AMT' => $faker-> randomDigit,
        'GIFT_WRAP_VAT_RATE_PERCENT' => $faker-> randomDigit,
        'GIFT_WRAP_VAT_AMT' => $faker-> randomDigit,
        'PROMO_GIFT_WRAP_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_GIFT_WRAP_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_VALUE_VAT_AMT' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_AMT_VAT_INCL' => $faker-> randomDigit,
        'PROMO_PRICE_OF_ITEMS_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_PRICE_OF_ITEMS_AMT_VAT_INCL' => $faker-> randomDigit,
        'SHIP_CHARGE_AMT_VAT_INCL' => $faker-> randomDigit,
        'PROMO_SHIP_CHARGE_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_SHIP_CHARGE_AMT_VAT_INCL' => $faker-> randomDigit,
        'GIFT_WRAP_AMT_VAT_INCL' => $faker-> randomDigit,
        'PROMO_GIFT_WRAP_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_GIFT_WRAP_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_VALUE_AMT_VAT_INCL' => $faker-> randomDigit,
        'TRANSACTION_CURRENCY_CODE' => $faker-> randomDigit,
        'COMODITY_CODE' => $faker-> randomDigit,
        'STATISTICAL_CODE_DEPART' => $faker-> randomDigit,
        'STATISTICAL_CODE_ARRIVAL' => $faker-> randomDigit,
        'COMMODITY_CODE_SUPPLEMENTARY_UNIT' => $faker-> randomDigit,
        'ITEM_QTY_SUPPLEMENTARY_UNIT' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_SUPPLEMENTARY_UNIT' => $faker-> randomDigit,
        'PRODUCT_TAX_CODE' => $faker-> randomDigit,
        'DEPARTURE_CITY'  =>  $faker-> city,
        'DEPARTURE_COUNTRY' =>  $faker-> country,
        'DEPARTURE_POST_CODE'  =>  $faker-> postcode,
        'ARRIVAL_CITY' =>  $faker-> city,
        'ARRIVAL_COUNTRY' =>  $faker-> country,
        'ARRIVAL_POST_CODE'  =>  $faker-> postcode,
        'SALE_DEPART_COUNTRY' =>  $faker-> city,
        'SALE_ARRIVAL_COUNTRY' =>  $faker-> country,
        'TRANSPORTATION_MODE'   => $faker -> sentence(10),
        'DELIVERY_CONDITIONS' => $faker -> sentence(10),
        'SELLER_DEPART_VAT_NUMBER_COUNTRY' => $faker-> country,
        'SELLER_DEPART_COUNTRY_VAT_NUMBER' => $faker-> randomDigit,
        'SELLER_ARRIVAL_VAT_NUMBER_COUNTRY' => $faker-> country,
        'SELLER_ARRIVAL_COUNTRY_VAT_NUMBER' => $faker-> randomDigit,
        'TRANSACTION_SELLER_VAT_NUMBER_COUNTRY' => $faker-> country,
        'TRANSACTION_SELLER_VAT_NUMBER' => $faker-> randomDigit,
        'BUYER_VAT_NUMBER_COUNTRY' => $faker-> country,
        'BUYER_VAT_NUMBER' => $faker-> randomDigit,
        'VAT_CALCULATION_IMPUTATION_COUNTRY' => $faker-> country,
        'TAXABLE_JURISDICTIN' => $faker -> sentence(10),
        'TAXABLE_JURISTICTION_LEVEL' => $faker -> sentence(10),
        'VAT_INV_NUMBER' => $faker-> randomDigit,
        'VAT_INV_CONVERTED_AMT' => $faker-> randomDigit,
        'VAT_INV_CURRENCY_CODE' => $faker -> sentence(10),
        'VAT_INV_EXCHANGE_RATE' => $faker -> sentence(10),
        'VAT_INV_EXCHANGE_RATE_DATE' =>  $faker-> date($format = 'Y-m-d', $max = 'now'),
        'EXPORT_OUTSIDE_EU' =>  $faker -> sentence(10),
        'INVOICE_URL' => $faker -> url,
        'BUYER_NAME' => $faker -> sentence(10),
        'ARRIVAL_ADRESS' => $faker -> address
      ];
     });

   // App seeder file

<?php

use Illuminate\Database\Seeder;

class AppSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    //radi za app factory, ovo 10 znači 10 puta
   factory(App\app::class, 10) -> create();
}
}

// app controler

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AppController extends Controller
{
//
public function index () {
    return view('app.index');
}
}

Illuminate\Database\QueryException  : SQLSTATE[42S02]: Base table or view
not found: 1146 Table 'avatr.apps' doesn't exist (SQL: insert into `apps`

at C:\laragon\www\pullus-
app\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660|         // If an exception occurs when attempting to run a query,
we'll format the error
661|         // message to include the bindings with SQL, which will make
this exception a
662|         // lot more helpful to the developer instead of just the
database's errors.
663|         catch (Exception $e) {
664|             throw new QueryException(
665|                 $query, $this->prepareBindings($bindings), $e
666|             );
667|         }
668|

 PDOException::("SQLSTATE[42S02]: Base table or view not found: 1146
 Table 'avatr.apps' doesn't exist")
  C:\laragon\www\pullus-
 app\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452

2   PDO::prepare("insert into `apps`
</code>```

答:
If you want to use factories, first you need to define a model for every table you want to seed: https://laravel.com/docs/5.8/eloquent#defining-models

Next, you define a factory for every model: https://laravel.com/docs/5.8/database-testing#writing-factories

Lastly, you need to make a seeder that will use the factories: https://laravel.com/docs/5.8/seeding

Body:
I'm trying to test my database with fake data. I wanted to run php artisan db:seed and i get an error. I am not sure how to solve it.

//App factory.php file
<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use Faker\Generator as Faker;

$factory->define(\App\app::class, function (Faker $faker) {
return [
    //

        'id' => $faker -> randomDigit,
        'UNIQUE_ACCOUNT_IDENTIFIER' => $faker -> randomDigit,
        'ACTIVITY_PERIOD' => $faker -> sentence(10),
        'SALES_CHANNEL' => $faker -> sentence(10),
        'MARKETPLACE' => $faker -> sentence(10),
        'TRANSACTION_TYPE' => $faker -> sentence(10),
        'TRANSACTION_EVENT_ID' =>  $faker-> randomDigit,
        'ACTIVITY-TRANSACTION-ID'=>  $faker-> randomDigit,
        'TAX_CALCULATION_DATE' =>  $faker-> date($format = 'Y-m-d', $max
   = 'now'),
        'TRANSACTION_DEPART_DATE' =>  $faker-> date($format = 'Y-m-d',
   $max = 'now'),
        'TRANSACTION_ARRIVAL_DATE' =>  $faker-> date($format = 'Y-m-d',
   $max = 'now'),
        'TRANSACTION_COMPLETE_DATE' =>  $faker-> date($format = 'Y-m-d',
  $max = 'now'),
        'SELLER_SKU' => $faker -> sentence(10),
        'ASIN' => $faker -> sentence(10),
        'ITEM_DESCRIPTION' => $faker -> sentence(10),
        'ITEM_MANUFACTURE_COUNTRY' =>  $faker-> country,
        'QTY' =>  $faker-> randomDigit,
        'ITEM_WEIGHT' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_WEIGHT' => $faker-> randomDigit,
        'COST_PRICE_OF_ITEMS' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PROMO_PRICE_OF_ITEMS_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_PRICE_OF_ITEMS_AMT_VAT_EXCL' => $faker-> randomDigit,
        'SHIP_CHARGE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PROMO_SHIP_CHARGE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_SHIP_CHARGE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'GIFT_WRAP_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PROMO_GIFT_WRAP_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_GIFT_WRAP_AMT_VAT_EXCL' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_VALUE_AMT_VAT_EXCL' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_VAT_RATE_PERCENT' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_VAT_AMT' => $faker-> randomDigit,
        'PROMO_PRICE_OF_ITEMS_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_PRICE_OF_ITEMS_VAT_AMT' => $faker-> randomDigit,
        'SHIP_CHARGE_VAT_RATE_PERCENT' => $faker-> randomDigit,
        'SHIP_CHARGE_VAT_AMT' => $faker-> randomDigit,
        'PROMO_SHIP_CHARGE_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_SHIP_CHARGE_VAT_AMT' => $faker-> randomDigit,
        'GIFT_WRAP_VAT_RATE_PERCENT' => $faker-> randomDigit,
        'GIFT_WRAP_VAT_AMT' => $faker-> randomDigit,
        'PROMO_GIFT_WRAP_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_GIFT_WRAP_VAT_AMT' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_VALUE_VAT_AMT' => $faker-> randomDigit,
        'PRICE_OF_ITEMS_AMT_VAT_INCL' => $faker-> randomDigit,
        'PROMO_PRICE_OF_ITEMS_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_PRICE_OF_ITEMS_AMT_VAT_INCL' => $faker-> randomDigit,
        'SHIP_CHARGE_AMT_VAT_INCL' => $faker-> randomDigit,
        'PROMO_SHIP_CHARGE_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_SHIP_CHARGE_AMT_VAT_INCL' => $faker-> randomDigit,
        'GIFT_WRAP_AMT_VAT_INCL' => $faker-> randomDigit,
        'PROMO_GIFT_WRAP_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_GIFT_WRAP_AMT_VAT_INCL' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_VALUE_AMT_VAT_INCL' => $faker-> randomDigit,
        'TRANSACTION_CURRENCY_CODE' => $faker-> randomDigit,
        'COMODITY_CODE' => $faker-> randomDigit,
        'STATISTICAL_CODE_DEPART' => $faker-> randomDigit,
        'STATISTICAL_CODE_ARRIVAL' => $faker-> randomDigit,
        'COMMODITY_CODE_SUPPLEMENTARY_UNIT' => $faker-> randomDigit,
        'ITEM_QTY_SUPPLEMENTARY_UNIT' => $faker-> randomDigit,
        'TOTAL_ACTIVITY_SUPPLEMENTARY_UNIT' => $faker-> randomDigit,
        'PRODUCT_TAX_CODE' => $faker-> randomDigit,
        'DEPARTURE_CITY'  =>  $faker-> city,
        'DEPARTURE_COUNTRY' =>  $faker-> country,
        'DEPARTURE_POST_CODE'  =>  $faker-> postcode,
        'ARRIVAL_CITY' =>  $faker-> city,
        'ARRIVAL_COUNTRY' =>  $faker-> country,
        'ARRIVAL_POST_CODE'  =>  $faker-> postcode,
        'SALE_DEPART_COUNTRY' =>  $faker-> city,
        'SALE_ARRIVAL_COUNTRY' =>  $faker-> country,
        'TRANSPORTATION_MODE'   => $faker -> sentence(10),
        'DELIVERY_CONDITIONS' => $faker -> sentence(10),
        'SELLER_DEPART_VAT_NUMBER_COUNTRY' => $faker-> country,
        'SELLER_DEPART_COUNTRY_VAT_NUMBER' => $faker-> randomDigit,
        'SELLER_ARRIVAL_VAT_NUMBER_COUNTRY' => $faker-> country,
        'SELLER_ARRIVAL_COUNTRY_VAT_NUMBER' => $faker-> randomDigit,
        'TRANSACTION_SELLER_VAT_NUMBER_COUNTRY' => $faker-> country,
        'TRANSACTION_SELLER_VAT_NUMBER' => $faker-> randomDigit,
        'BUYER_VAT_NUMBER_COUNTRY' => $faker-> country,
        'BUYER_VAT_NUMBER' => $faker-> randomDigit,
        'VAT_CALCULATION_IMPUTATION_COUNTRY' => $faker-> country,
        'TAXABLE_JURISDICTIN' => $faker -> sentence(10),
        'TAXABLE_JURISTICTION_LEVEL' => $faker -> sentence(10),
        'VAT_INV_NUMBER' => $faker-> randomDigit,
        'VAT_INV_CONVERTED_AMT' => $faker-> randomDigit,
        'VAT_INV_CURRENCY_CODE' => $faker -> sentence(10),
        'VAT_INV_EXCHANGE_RATE' => $faker -> sentence(10),
        'VAT_INV_EXCHANGE_RATE_DATE' =>  $faker-> date($format = 'Y-m-d', $max = 'now'),
        'EXPORT_OUTSIDE_EU' =>  $faker -> sentence(10),
        'INVOICE_URL' => $faker -> url,
        'BUYER_NAME' => $faker -> sentence(10),
        'ARRIVAL_ADRESS' => $faker -> address
      ];
     });

   // App seeder file

<?php

use Illuminate\Database\Seeder;

class AppSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
    //radi za app factory, ovo 10 znači 10 puta
   factory(App\app::class, 10) -> create();
}
}

// app controler

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AppController extends Controller
{
//
public function index () {
    return view('app.index');
}
}

Illuminate\Database\QueryException  : SQLSTATE[42S02]: Base table or view
not found: 1146 Table 'avatr.apps' doesn't exist (SQL: insert into `apps`

at C:\laragon\www\pullus-
app\vendor\laravel\framework\src\Illuminate\Database\Connection.php:664
660|         // If an exception occurs when attempting to run a query,
we'll format the error
661|         // message to include the bindings with SQL, which will make
this exception a
662|         // lot more helpful to the developer instead of just the
database's errors.
663|         catch (Exception $e) {
664|             throw new QueryException(
665|                 $query, $this->prepareBindings($bindings), $e
666|             );
667|         }
668|

 PDOException::("SQLSTATE[42S02]: Base table or view not found: 1146
 Table 'avatr.apps' doesn't exist")
  C:\laragon\www\pullus-
 app\vendor\laravel\framework\src\Illuminate\Database\Connection.php:452

2   PDO::prepare("insert into `apps`


问:
Dynamic script for submitting a form
How can i write this dynamically to use on a number of forms?</p>

```<code>function submitform()
{
    if(document.hotelfrm.onsubmit &&
    !document.hotelfrm.onsubmit())
    {
        return;
    }
 document.hotelfrm.submit();
}

form name="hotelfrm" id="hotelfrm" method="post" action="page1.asp"
</code>```

答:
Have a look at document.forms.

You might want to tryout something like this:

```<code>function submitforms() {
    for(var i = 0; i < document.forms.length; i++) {
        if(document.forms[i].onsubmit && !document.forms[i].obsubmit()) {
            return;
        }

        document.forms[i].submit();
    }
}
</code>```

Please note I didn't check your code validity and reasonableness.

Title: Dynamic script for submitting a form

Body:
How can i write this dynamically to use on a number of forms?

function submitform()
{
    if(document.hotelfrm.onsubmit &&
    !document.hotelfrm.onsubmit())
    {
        return;
    }
 document.hotelfrm.submit();
}

form name="hotelfrm" id="hotelfrm" method="post" action="page1.asp"

Body:
Have a look at document.forms.

You might want to tryout something like this:

function submitforms() {
    for(var i = 0; i < document.forms.length; i++) {
        if(document.forms[i].onsubmit && !document.forms[i].obsubmit()) {
            return;
        }

        document.forms[i].submit();
    }
}

Please note I didn't check your code validity and reasonableness.


问:
Unable to access localhost/phpmyadmin
I've installed a LAMP stack, MySQL-server, apahe2, PHPMyAdmin, but unable to access is using localhost/PHPMyAdmin. I can access MySQL using the terminal. But not through PHPMyAdmin.

I also checked /var/www/html, no PHPMyAdmin folder is present.
I once deleted it by mistake, I think the issue is from there.

This is the output :

答:
Try this In Terminal :

sudo /etc/init.d/apache2 stop

sudo /opt/lampp/lampp start

if it's not working try to change the port of phpmyadmin to 3306 to 3307

Hoping it will be useful

Title: Unable to access localhost/phpmyadmin