问:
Multiple Classes Read From Single Class
I am working on a project which requires to start a Timer on load of the Form1 that  increments the TimerCount Property of Class TimeCounter in the tick event.

The Project has also Form2 which when open I want to read the increment updates from TimeCounter class which is being incremented by the Form1 because Form1 is parent and will not close I tried to read from TimeCounter but got default set value which is 0.

Here is code:

Timer Class

```<code>public class TimeCounter
{
    public int timer=0;
    public int TimerCount { get; set; }

    public int  GetTime()
    {
        return timer;
    }
}
</code>```

Form1 Increment TimerCount After 1 Second

```<code>private void Form1_Load(object sender, EventArgs e)
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 1000;
    timer.Elapsed += timer_Elapsed;
    timer.Start();
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    sk++;
    Timer t = new Timer();
    t.TimerCount = sk;

}
</code>```

Form2 Which Receive Counter Continuously(But Not Working)

```<code>  private void Form1_Load(object sender, EventArgs e)
  {
      System.Timers.Timer timer = new System.Timers.Timer();
      timer.Interval = 1000;
      timer.Elapsed += timer_Elapsed;
      timer.Enabled = true;
      timer.Start();
  }

  void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  {
      Timer t1 = new Timer();
      B01CountDown.Text = t1.GetTime().ToString();
  }
</code>```

答:
Actually you don't require TimeCounter Class and also Timer in Form2

see below code

Form1

```<code>public partial class Form1 : Form
{
    int sk = 0;
    Form2 form2 = new Form2();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 1000;
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        form2.Show();
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Do your Stuff
        sk++;
        form2.UpdateLabel(sk.ToString());
    }
}
</code>```

Form2

```<code>public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void UpdateLabel(string Message)
    {
        if (B01CountDown.InvokeRequired)
        {
            B01CountDown.Invoke((MethodInvoker)(() =>
            {
                B01CountDown.Text = Message;
            }));
        }
    }
}
</code>```

Title: Multiple Classes Read From Single Class

Body:
I am working on a project which requires to start a Timer on load of the Form1 that  increments the TimerCount Property of Class TimeCounter in the tick event.

The Project has also Form2 which when open I want to read the increment updates from TimeCounter class which is being incremented by the Form1 because Form1 is parent and will not close I tried to read from TimeCounter but got default set value which is 0.

Here is code:

Timer Class

public class TimeCounter
{
    public int timer=0;
    public int TimerCount { get; set; }

    public int  GetTime()
    {
        return timer;
    }
}

Form1 Increment TimerCount After 1 Second

private void Form1_Load(object sender, EventArgs e)
{
    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Interval = 1000;
    timer.Elapsed += timer_Elapsed;
    timer.Start();
}

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    sk++;
    Timer t = new Timer();
    t.TimerCount = sk;

}

Form2 Which Receive Counter Continuously(But Not Working)

  private void Form1_Load(object sender, EventArgs e)
  {
      System.Timers.Timer timer = new System.Timers.Timer();
      timer.Interval = 1000;
      timer.Elapsed += timer_Elapsed;
      timer.Enabled = true;
      timer.Start();
  }

  void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  {
      Timer t1 = new Timer();
      B01CountDown.Text = t1.GetTime().ToString();
  }

Body:
Actually you don't require TimeCounter Class and also Timer in Form2

see below code

Form1

public partial class Form1 : Form
{
    int sk = 0;
    Form2 form2 = new Form2();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Interval = 1000;
        timer.Elapsed += timer_Elapsed;
        timer.Start();
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        form2.Show();
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        // Do your Stuff
        sk++;
        form2.UpdateLabel(sk.ToString());
    }
}

Form2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public void UpdateLabel(string Message)
    {
        if (B01CountDown.InvokeRequired)
        {
            B01CountDown.Invoke((MethodInvoker)(() =>
            {
                B01CountDown.Text = Message;
            }));
        }
    }
}


来源: stackexchange

问:
Get median of array
I have an array that looks like this:

```<code>let arr = [1,2,3,4,5,6,7,8,9]
</code>```

I know you can get min and max by:

```<code>let min = arr.min()
let max = arr.max()
</code>```

But how do you get the median?

答:
The median is defined as the number in the middle of the sequence. If there is not one middle number, then it's the average of the two middle numbers.</p>

```<code>extension Array where Element == Int {
    func median() -> Double {
        let sortedArray = sorted()
        if count % 2 != 0 {
            return Double(sortedArray[count / 2])
        } else {
            return Double(sortedArray[count / 2] + sortedArray[count / 2 - 1]) / 2.0
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get median of array

Body:
I have an array that looks like this:

let arr = [1,2,3,4,5,6,7,8,9]

I know you can get min and max by:

let min = arr.min()
let max = arr.max()

But how do you get the median?

Body:
The median is defined as the number in the middle of the sequence. If there is not one middle number, then it's the average of the two middle numbers.

extension Array where Element == Int {
    func median() -> Double {
        let sortedArray = sorted()
        if count % 2 != 0 {
            return Double(sortedArray[count / 2])
        } else {
            return Double(sortedArray[count / 2] + sortedArray[count / 2 - 1]) / 2.0
        }
    }
}


问:
Dynamically add multiple instances of the same user control type when button is clicked
Is it possible to add instances of the same user control when an "add" button is clicked and maintain ViewState?

The user interface here is similar to the Gmail file-attachment process, where the user can click "attach another file" and another file upload box appears.

My page is surrounded by an UpdatePanel. I am able to get 1 control to load, but the button's click event fires after the Placeholder_Init method.  I tried storing an integer in the ViewState that kept track of the number of user controls that should be rendered, but the Init method is also fired before the ViewState is restored.

Thanks!

答:
Adding multiple controls dynamically is easy in ASP.NET. Let's say you have a panel named Panel declared in your ASPX file and you have a custom control called MyControl.

In your Page_Load function (or indeed pretty much anywhere), add something like the following:

```<code>for (int i = 0; i < NumberOfAttachments; i++) {
    Panel.Controls.Add(new MyControl());
}
</code>```

This works for UpdatePanels, too, but you'll need to call the .Update() function to get it to update on the client side if you don't have it to update on child postback.

OwnerDisplayName: John Rasch

ContentLicense: CC BY-SA 2.5

Body:
Adding multiple controls dynamically is easy in ASP.NET. Let's say you have a panel named Panel declared in your ASPX file and you have a custom control called MyControl.

In your Page_Load function (or indeed pretty much anywhere), add something like the following:

for (int i = 0; i < NumberOfAttachments; i++) {
    Panel.Controls.Add(new MyControl());
}

This works for UpdatePanels, too, but you'll need to call the .Update() function to get it to update on the client side if you don't have it to update on child postback.


问:
Loading Integer Array from xml
I have an integer array in an xml file as follows

```<code><integer-array name="myArray">
    <item>@drawable/pic1</item>
    <item>@drawable/pic2</item>
    <item>@drawable/pic3</item>
    <item>@drawable/pic4</item>
</integer-array>
</code>```

In the code, I am trying to load this array

```<code>int[] picArray = getResources().getIntArray(R.array.myArray);
</code>```

The expected result is

```<code>R.drawable.pic1, R.drawable.pic2,R.drawable.pic3
</code>```

but instead it is coming with an array with all values as zero

Can anyone tell me what is wrong?

答:
You need to get an array with id's of your images.
Probably this article helps you. And so the code you probably need:</p>

```<code>int[] picArray = new int[4];

for (int i = 1; i <=4; i++)
{
  try
  {
    Class res = R.drawable.class;
    Field field = res.getField("pic"+i);
    picArray[i-1] = field.getInt(null);
  }
  catch (Exception e)
  {
    Log.e("MyTag", "Failure to get drawable id.", e);
  }
}
</code>```

Title: Loading Integer Array from xml

Body:
I have an integer array in an xml file as follows

<integer-array name="myArray">
    <item>@drawable/pic1</item>
    <item>@drawable/pic2</item>
    <item>@drawable/pic3</item>
    <item>@drawable/pic4</item>
</integer-array>

In the code, I am trying to load this array

int[] picArray = getResources().getIntArray(R.array.myArray);

The expected result is

R.drawable.pic1, R.drawable.pic2,R.drawable.pic3

but instead it is coming with an array with all values as zero

Can anyone tell me what is wrong?

Body:
You need to get an array with id's of your images.
Probably this article helps you. And so the code you probably need:

int[] picArray = new int[4];

for (int i = 1; i <=4; i++)
{
  try
  {
    Class res = R.drawable.class;
    Field field = res.getField("pic"+i);
    picArray[i-1] = field.getInt(null);
  }
  catch (Exception e)
  {
    Log.e("MyTag", "Failure to get drawable id.", e);
  }
}


问:
Issues with existing from the navigation bar in android
I have a user login activity once the user logs in he is redirected to navigation bar activity.

Problem : When the user is on the navigation bar activity and press back button - in this case the login screen pops ups again.

What I want : When the user clicks on the back button in the navigation screen the app should exit and it should not open the login screen.

答:
When you navigate the user to Navigation bar activity from login screen. then call finish() in login screen.

For example, do the following in your LoginActivity

```<code>Intent intent = new Intent(LoginActivity.this, NavigationBarActivity.class);
startActivity(intent);
finish();
</code>```

It is happening because you haven't closed the Login Activity when you navigate the user to the Navigation bar activity. The Login Activity remains in the backstack and pops up on pressing the back button.

Body:
When you navigate the user to Navigation bar activity from login screen. then call finish() in login screen.

For example, do the following in your LoginActivity

Intent intent = new Intent(LoginActivity.this, NavigationBarActivity.class);
startActivity(intent);
finish();

It is happening because you haven't closed the Login Activity when you navigate the user to the Navigation bar activity. The Login Activity remains in the backstack and pops up on pressing the back button.


问:
PHP consecutive occurrence of characters replace with other parameter
I have a string like

```<code>sadd*sadasdsdsad*sdadsdasdad*asdsadsadsadasdsdsd*asdasdsadasdasdasdasdasdasd*asdasdadasdsdasd*asdsaddasdasdas*
</code>```

now i want all consecutive *'s to be replaced with  &  respectively. Above string will become

```<code>sadd<b>sadasdsdsad</b>sdadsdasdad<b>asdsadsadsadasdsdsd</b>asdasdsadasdasdasdasdasdasd<b>asdasdadasdsdasd</b>asdsaddasdasdas*sdfdsfsd
</code>```

the last * is not replaced because there is no consecutive pair of star left.

答:
Seems like you could simply do

```<code>\*(.+?)((?=$)|\*)
# match a star
# anything else lazily afterwards
# the end of the string
# or another star
</code>```

And replace this with $1, see a demo on regex101.com.

Body:
I have a string like

sadd*sadasdsdsad*sdadsdasdad*asdsadsadsadasdsdsd*asdasdsadasdasdasdasdasdasd*asdasdadasdsdasd*asdsaddasdasdas*

now i want all consecutive *'s to be replaced with  &  respectively. Above string will become

saddsadasdsdsadsdadsdasdadasdsadsadsadasdsdsdasdasdsadasdasdasdasdasdasdasdasdadasdsdasdasdsaddasdasdas*sdfdsfsd

the last * is not replaced because there is no consecutive pair of star left.

Body:
Seems like you could simply do

\*(.+?)((?=$)|\*)
# match a star
# anything else lazily afterwards
# the end of the string
# or another star

And replace this with <b>$1</b>, see a demo on regex101.com.


问:
Android progressBar doesn't set progress after call Retrofit
im trying to simulate a progress of the retrofit's call, so before of execute the call i start the progress in this way:

```<code>public void runSimulateProgress(final CustomDialogLoad d){
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (d != null){
                int progress = 0;
                while (d.getProgress() < 99){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    progress = progress+10;
                    d.setProgress(progress);
                }

            }
        }
    }).start();

}
</code>```

The CustomDialogLoad is a Dialog with a progress and TextView.

So, when the call ends, i want to set progress to 100, but the progressBar doesn't change, i have tried to make any change of progress in a manual way but the progressBar doesn't want to update.

Here's the code of retrofit's call

```<code>dialogProgress.runSimulateProgress(dialogProgress);
final SaveRutaVisitaService saveRutaVisitaService =       restAdapter.create(SaveRutaVisitaService.class);
saveRutaVisitaService.saveRutaVisita(multipartTypedOutput, new        Callback<Response>() {
        @Override
        public void success(Response result, Response response) {
       dialogProgress.setProgress(100)

    }   @Override
        public void failure(RetrofitError retrofitError) {
       dialogProgress.setProgress(100)}
    }
</code>```

I tried to make real progress based on this question

Android Retrofit - onProgressUpdate for showing Progress Notification

but doesn't work to me with multiPart

I appreciate any help

regards

EDIT: i added the "post" to update the progress but still not working

```<code>public void setProgress(final int p){
    mRingProgressBar.post(new Runnable() {
        @Override
        public void run() {
            mRingProgressBar.setProgress(p);
        }
    });

}
</code>```

that method is inside of CustomDialogLoad class

答:
change your code like this

```<code>public void runSimulateProgress(final CustomDialogLoad d){
new Thread(new Runnable() {
    @Override
    public void run() {
        if (d != null){
            int progress = 0;
            while (d.getProgress() < 99){
                try {
         ((Activity) ctx).runOnUiThread(new Runnable() {
            public void run() {
                progress = progress+10;
              d.setProgress(progress);
            }
        }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }
}).start();
</code>```

}

Body:
im trying to simulate a progress of the retrofit's call, so before of execute the call i start the progress in this way:

public void runSimulateProgress(final CustomDialogLoad d){
    new Thread(new Runnable() {
        @Override
        public void run() {
            if (d != null){
                int progress = 0;
                while (d.getProgress() < 99){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    progress = progress+10;
                    d.setProgress(progress);
                }

            }
        }
    }).start();

}

The CustomDialogLoad is a Dialog with a progress and TextView.

So, when the call ends, i want to set progress to 100, but the progressBar doesn't change, i have tried to make any change of progress in a manual way but the progressBar doesn't want to update.

Here's the code of retrofit's call

dialogProgress.runSimulateProgress(dialogProgress);
final SaveRutaVisitaService saveRutaVisitaService =       restAdapter.create(SaveRutaVisitaService.class);
saveRutaVisitaService.saveRutaVisita(multipartTypedOutput, new        Callback<Response>() {
        @Override
        public void success(Response result, Response response) {
       dialogProgress.setProgress(100)

    }   @Override
        public void failure(RetrofitError retrofitError) {
       dialogProgress.setProgress(100)}
    }

I tried to make real progress based on this question

Android Retrofit - onProgressUpdate for showing Progress Notification

but doesn't work to me with multiPart

I appreciate any help

regards

EDIT: i added the "post" to update the progress but still not working

public void setProgress(final int p){
    mRingProgressBar.post(new Runnable() {
        @Override
        public void run() {
            mRingProgressBar.setProgress(p);
        }
    });

}

that method is inside of CustomDialogLoad class

Body:
change your code like this

public void runSimulateProgress(final CustomDialogLoad d){
new Thread(new Runnable() {
    @Override
    public void run() {
        if (d != null){
            int progress = 0;
            while (d.getProgress() < 99){
                try {
         ((Activity) ctx).runOnUiThread(new Runnable() {
            public void run() {
                progress = progress+10;
              d.setProgress(progress);
            }
        }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }
}).start();

}


问:
Overriding Java System Library with newer class on Mac
I'm trying to compile and run a Java3D project on my mac and having some trouble. I'm using Eclipse. The program depends on an old version of Java3D, but even after I add the correct Jars in Eclipse it still is looking in the default system location instead.

When running my program in Eclipse, I get this issue:

Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: javax.media.j3d.BranchGroup.pickAllSorted(IILjavax/media/j3d/PickShape;)[Ljavax/media/j3d/PickInfo;
 at com.sun.j3d.utils.pickfast.PickTool.pickAllSorted(PickTool.java:410)

BranchGroup.pickAllSorted does not exist in the Mac Default JRE System Library (JVM 1.6.0), but it does exist in the correct JAVA3D jars that I have included. I've added them to my buildpath, AND they are referenced above the JRE system library in Properties-Java Build Path-Order and Export. This seems like it should be the solution but it doesn't work.

I've been trying for a while and cannot get it to work. One possible lead I had was to try putting the .jars in /Library/Java/Extensions. When I do this, I instead get an OpenGL error and my program doesn't open at all, but its doing something I guess.

Thanks for the help.

答: In Eclipse, go to Run > Run Configurations > Your Main > Arguments > VM Arguments and add -Xbootclasspath/p:newjava3d.jar. This prepends newjava3d.jar to your bootclasspath, so the relevant classes will be loaded from it.


问:
PHP code snippet doesn't execute properly after another code snippet in Sublime text 3
I have a PHP class and constructor snippet that I have created in sublime 3.

Class

```<code>snippet>
<content><![CDATA[
class ${1}
{
    ${2}
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet
-->
<tabTrigger>cla</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger --
>
<scope>source.php</scope>
</snippet>
</code>```

Constructor

```<code><snippet>
<content><![CDATA[
public function __construct(${1})
{
    ${2}
}
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>_c</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.php</scope>
</snippet>
</code>```

Here's what I am trying to accomplish when the code snippet is triggered:

```<code>class Person
{
    public function __construct()
    {

    }
}
</code>```

Instead after I use the class snippet the constructor snippet doesn't trigger and the cursor moves to the end of the classes curly brace like so:

```<code>class Person
{
    _c
}//cursor is now here
</code>```

Then I can go back through, go back delete the _c and hit the constructor trigger again and everything works just fine.

答: Just set "auto_complete_with_fields": true, in your ST preferences, or manually trigger autocomplete after typing _c and then press Tab.

Body:
I have a PHP class and constructor snippet that I have created in sublime 3.

Class

snippet>
<content><![CDATA[
class ${1}
{
    ${2}
}
]]></content>

<tabTrigger>cla</tabTrigger>

    <tabTrigger>_c</tabTrigger>

    <scope>source.php</scope>
</snippet>

Here's what I am trying to accomplish when the code snippet is triggered:

class Person
{
    public function __construct()
    {

    }
}

Instead after I use the class snippet the constructor snippet doesn't trigger and the cursor moves to the end of the classes curly brace like so:

class Person
{
    _c
}//cursor is now here

Then I can go back through, go back delete the _c and hit the constructor trigger again and everything works just fine.


问:
Swift: Rounded Corners on Camera View
I want to implement rounded corners on my RecordingViewController(which has the camera view).I tried going into the app delegate and changing the corner radius of the window however, it seemed to not work. I believe the issue is with this method (AVLayerVideoGravityResizeAspectFill), it seems to fill the entire screen and takes no consideration to changing the window corner radius. Any ideas?</p>

答:
```<code>  var captureSession:AVCaptureSession?
  var videoPreviewLayer:AVCaptureVideoPreviewLayer?
</code>```

First of all create a UIView and give it corner radius.
After that add AVCaptureVideoPreviewLayer as sublayer to that view.

```<code>    myView.layer.masksToBounds = true

    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.frame = myView.layer.bounds
    myView.layer.addSublayer(videoPreviewLayer!)
</code>```

Hope this helps.

Title: Swift: Rounded Corners on Camera View

Body:
  var captureSession:AVCaptureSession?
  var videoPreviewLayer:AVCaptureVideoPreviewLayer?

First of all create a UIView and give it corner radius.
After that add AVCaptureVideoPreviewLayer as sublayer to that view.

    myView.layer.masksToBounds = true

    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.frame = myView.layer.bounds
    myView.layer.addSublayer(videoPreviewLayer!)

Hope this helps.


问:
Error: Unable to resolve path to module `js/http`, `js/tree` etc on running `./Scripts/bootstrap.sh`
Getting error while running command ./Scripts/bootstrap.sh under directory: /usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent

```<code>EggCloudMachine-1:WebDriverAgent admin$ ./Scripts/bootstrap.sh
Fetching dependencies
Building Inspector
Creating bundle directory...
Fetching Inspector dependencies...
npm WARN web-driver-inspector@1.0.0 No repository field.

up to date in 5.731s
Validating Inspector
No errors!

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/app.js
  12:18  error  Unable to resolve path to module 'js/http'                import/no-unresolved
  13:20  error  Unable to resolve path to module 'js/screen'              import/no-unresolved
  14:31  error  Unable to resolve path to module 'js/screenshot_factory'  import/no-unresolved
  15:18  error  Unable to resolve path to module 'js/tree'                import/no-unresolved
  16:22  error  Unable to resolve path to module 'js/tree_node'           import/no-unresolved
  17:25  error  Unable to resolve path to module 'js/tree_context'        import/no-unresolved
  18:23  error  Unable to resolve path to module 'js/inspector'           import/no-unresolved
  27:14  error  Missing space before function parentheses                 space-before-function-paren
  32:13  error  Missing space before function parentheses                 space-before-function-paren
  37:20  error  Missing space before function parentheses                 space-before-function-paren
  41:18  error  Missing space before function parentheses                 space-before-function-paren
  48:13  error  Expected property shorthand                               object-shorthand
  55:12  error  Missing space before function parentheses                 space-before-function-paren
  64:9   error  Missing space before function parentheses                 space-before-function-paren

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/http.js
  13:13  error    Missing space before function parentheses  space-before-function-paren
  13:20  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  19:7   error    Unexpected var, use let or const instead   no-var
  20:7   warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  25:14  error    Missing space before function parentheses  space-before-function-paren
  25:27  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  29:7   error    Expected property shorthand                object-shorthand
  32:7   error    Unexpected var, use let or const instead   no-var
  33:7   warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/image_utils.js
  11:34  error    Missing space before function parentheses  space-before-function-paren
  11:55  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  15:40  error    Missing space before function parentheses  space-before-function-paren
  15:69  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  16:5   error    Unexpected var, use let or const instead   no-var
  20:5   error    Unexpected var, use let or const instead   no-var
  28:45  error    Missing space before function parentheses  space-before-function-paren
  28:79  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  29:5   error    Unexpected var, use let or const instead   no-var
  33:5   error    Unexpected var, use let or const instead   no-var
  41:22  error    Missing space before function parentheses  space-before-function-paren
  41:31  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  42:5   error    Unexpected var, use let or const instead   no-var
  44:28  error    Missing space before function parentheses  space-before-function-paren
  45:7   warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/inspector.js
  13:18  error  Unable to resolve path to module 'js/http'  import/no-unresolved
  14:1   error  Unexpected var, use let or const instead    no-var
  18:22  error  Missing space before function parentheses   space-before-function-paren
  23:9   error  Missing space before function parentheses   space-before-function-paren
  38:18  error  Missing space before function parentheses   space-before-function-paren
  64:14  error  Missing space before function parentheses   space-before-function-paren
  68:5   error  Unexpected var, use let or const instead    no-var
  86:6   error  Missing space before function parentheses   space-before-function-paren
  89:9   error  Unexpected var, use let or const instead    no-var
  97:13  error  Unexpected var, use let or const instead    no-var
  98:13  error  Unexpected var, use let or const instead    no-var

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/screen.js
   13:18  error  Unable to resolve path to module 'js/http'    import/no-unresolved
   15:1   error  Unexpected var, use let or const instead      no-var
   20:9   error  Missing space before function parentheses     space-before-function-paren
   45:22  error  Missing space before function parentheses     space-before-function-paren
   46:5   error  Unexpected var, use let or const instead      no-var
   53:13  error  Missing space before function parentheses     space-before-function-paren
   57:20  error  Missing space before function parentheses     space-before-function-paren
   58:5   error  Unexpected var, use let or const instead      no-var
   59:5   error  Unexpected var, use let or const instead      no-var
   61:5   error  Unexpected var, use let or const instead      no-var
   63:5   error  Unexpected var, use let or const instead      no-var
   73:9   error  Unexpected var, use let or const instead      no-var
   77:13  error  Expected property shorthand                   object-shorthand
   78:13  error  Expected property shorthand                   object-shorthand
   88:7   error  Missing space before function parentheses     space-before-function-paren
   98:19  error  Missing space before function parentheses     space-before-function-paren
  111:24  error  Missing space before function parentheses     space-before-function-paren
  124:34  error  Missing space before function parentheses     space-before-function-paren
  125:5   error  Unexpected var, use let or const instead      no-var
  130:5   error  Unexpected var, use let or const instead      no-var
  133:5   error  Unexpected var, use let or const instead      no-var
  137:75  error  Missing space before opening brace            space-before-blocks
  138:9   error  Expected indentation of 6 spaces but found 8  indent

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/screenshot_factory.js
  10:24  error    Unable to resolve path to module 'js/image_utils'  import/no-unresolved
  12:30  error    Missing space before function parentheses          space-before-function-paren
  13:3   error    Unexpected var, use let or const instead           no-var
  14:3   error    Unexpected var, use let or const instead           no-var
  15:3   error    Unexpected var, use let or const instead           no-var
  17:3   error    Unexpected var, use let or const instead           no-var
  18:3   error    Unexpected var, use let or const instead           no-var
  23:26  error    Missing space before function parentheses          space-before-function-paren
  23:60  warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks
  33:28  error    Missing space before function parentheses          space-before-function-paren
  37:22  error    Missing space before function parentheses          space-before-function-paren
  37:43  warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks
  51:34  error    Missing space before function parentheses          space-before-function-paren
  51:42  warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks
  52:5   error    Unexpected var, use let or const instead           no-var
  58:5   warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/tree.js
   23:9   error  Missing space before function parentheses  space-before-function-paren
   42:16  error  Missing space before function parentheses  space-before-function-paren
   46:21  error  Missing space before function parentheses  space-before-function-paren
   52:13  error  Missing space before function parentheses  space-before-function-paren
   64:13  error  Missing space before function parentheses  space-before-function-paren
   84:5   error  Unexpected var, use let or const instead   no-var
  101:14  error  Missing space before function parentheses  space-before-function-paren
  107:19  error  Missing space before function parentheses  space-before-function-paren
  113:19  error  Missing space before function parentheses  space-before-function-paren

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/tree_context.js
  11:14  error  Missing space before function parentheses  space-before-function-paren
  16:21  error  Missing space before function parentheses  space-before-function-paren

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/tree_node.js
  11:19  error  Missing space before function parentheses  space-before-function-paren
  18:23  error  Missing space before function parentheses  space-before-function-paren
  19:5   error  Unexpected var, use let or const instead   no-var
  26:23  error  Missing space before function parentheses  space-before-function-paren
  27:5   error  Unexpected var, use let or const instead   no-var
  36:19  error  Missing space before function parentheses  space-before-function-paren
  49:14  error  Missing space before function parentheses  space-before-function-paren

✖ 106 problems (93 errors, 13 warnings)
</code>```

答:
This error will not effect your xcode build or browser launch on ios.
Try running the above command with -d
./Scripts/bootstrap.sh -d
or
sh ./Scripts/bootstrap.sh -d

If still your build fails then this should be some other issue.

Body:
Getting error while running command ./Scripts/bootstrap.sh under directory: /usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent

EggCloudMachine-1:WebDriverAgent admin$ ./Scripts/bootstrap.sh
Fetching dependencies
Building Inspector
Creating bundle directory...
Fetching Inspector dependencies...
npm WARN web-driver-inspector@1.0.0 No repository field.

up to date in 5.731s
Validating Inspector
No errors!

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/app.js
  12:18  error  Unable to resolve path to module 'js/http'                import/no-unresolved
  13:20  error  Unable to resolve path to module 'js/screen'              import/no-unresolved
  14:31  error  Unable to resolve path to module 'js/screenshot_factory'  import/no-unresolved
  15:18  error  Unable to resolve path to module 'js/tree'                import/no-unresolved
  16:22  error  Unable to resolve path to module 'js/tree_node'           import/no-unresolved
  17:25  error  Unable to resolve path to module 'js/tree_context'        import/no-unresolved
  18:23  error  Unable to resolve path to module 'js/inspector'           import/no-unresolved
  27:14  error  Missing space before function parentheses                 space-before-function-paren
  32:13  error  Missing space before function parentheses                 space-before-function-paren
  37:20  error  Missing space before function parentheses                 space-before-function-paren
  41:18  error  Missing space before function parentheses                 space-before-function-paren
  48:13  error  Expected property shorthand                               object-shorthand
  55:12  error  Missing space before function parentheses                 space-before-function-paren
  64:9   error  Missing space before function parentheses                 space-before-function-paren

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/http.js
  13:13  error    Missing space before function parentheses  space-before-function-paren
  13:20  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  19:7   error    Unexpected var, use let or const instead   no-var
  20:7   warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  25:14  error    Missing space before function parentheses  space-before-function-paren
  25:27  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  29:7   error    Expected property shorthand                object-shorthand
  32:7   error    Unexpected var, use let or const instead   no-var
  33:7   warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/image_utils.js
  11:34  error    Missing space before function parentheses  space-before-function-paren
  11:55  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  15:40  error    Missing space before function parentheses  space-before-function-paren
  15:69  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  16:5   error    Unexpected var, use let or const instead   no-var
  20:5   error    Unexpected var, use let or const instead   no-var
  28:45  error    Missing space before function parentheses  space-before-function-paren
  28:79  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  29:5   error    Unexpected var, use let or const instead   no-var
  33:5   error    Unexpected var, use let or const instead   no-var
  41:22  error    Missing space before function parentheses  space-before-function-paren
  41:31  warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks
  42:5   error    Unexpected var, use let or const instead   no-var
  44:28  error    Missing space before function parentheses  space-before-function-paren
  45:7   warning  Avoid callbacks. Prefer Async/Await        promise/prefer-await-to-callbacks

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/inspector.js
  13:18  error  Unable to resolve path to module 'js/http'  import/no-unresolved
  14:1   error  Unexpected var, use let or const instead    no-var
  18:22  error  Missing space before function parentheses   space-before-function-paren
  23:9   error  Missing space before function parentheses   space-before-function-paren
  38:18  error  Missing space before function parentheses   space-before-function-paren
  64:14  error  Missing space before function parentheses   space-before-function-paren
  68:5   error  Unexpected var, use let or const instead    no-var
  86:6   error  Missing space before function parentheses   space-before-function-paren
  89:9   error  Unexpected var, use let or const instead    no-var
  97:13  error  Unexpected var, use let or const instead    no-var
  98:13  error  Unexpected var, use let or const instead    no-var

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/screen.js
   13:18  error  Unable to resolve path to module 'js/http'    import/no-unresolved
   15:1   error  Unexpected var, use let or const instead      no-var
   20:9   error  Missing space before function parentheses     space-before-function-paren
   45:22  error  Missing space before function parentheses     space-before-function-paren
   46:5   error  Unexpected var, use let or const instead      no-var
   53:13  error  Missing space before function parentheses     space-before-function-paren
   57:20  error  Missing space before function parentheses     space-before-function-paren
   58:5   error  Unexpected var, use let or const instead      no-var
   59:5   error  Unexpected var, use let or const instead      no-var
   61:5   error  Unexpected var, use let or const instead      no-var
   63:5   error  Unexpected var, use let or const instead      no-var
   73:9   error  Unexpected var, use let or const instead      no-var
   77:13  error  Expected property shorthand                   object-shorthand
   78:13  error  Expected property shorthand                   object-shorthand
   88:7   error  Missing space before function parentheses     space-before-function-paren
   98:19  error  Missing space before function parentheses     space-before-function-paren
  111:24  error  Missing space before function parentheses     space-before-function-paren
  124:34  error  Missing space before function parentheses     space-before-function-paren
  125:5   error  Unexpected var, use let or const instead      no-var
  130:5   error  Unexpected var, use let or const instead      no-var
  133:5   error  Unexpected var, use let or const instead      no-var
  137:75  error  Missing space before opening brace            space-before-blocks
  138:9   error  Expected indentation of 6 spaces but found 8  indent

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/screenshot_factory.js
  10:24  error    Unable to resolve path to module 'js/image_utils'  import/no-unresolved
  12:30  error    Missing space before function parentheses          space-before-function-paren
  13:3   error    Unexpected var, use let or const instead           no-var
  14:3   error    Unexpected var, use let or const instead           no-var
  15:3   error    Unexpected var, use let or const instead           no-var
  17:3   error    Unexpected var, use let or const instead           no-var
  18:3   error    Unexpected var, use let or const instead           no-var
  23:26  error    Missing space before function parentheses          space-before-function-paren
  23:60  warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks
  33:28  error    Missing space before function parentheses          space-before-function-paren
  37:22  error    Missing space before function parentheses          space-before-function-paren
  37:43  warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks
  51:34  error    Missing space before function parentheses          space-before-function-paren
  51:42  warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks
  52:5   error    Unexpected var, use let or const instead           no-var
  58:5   warning  Avoid callbacks. Prefer Async/Await                promise/prefer-await-to-callbacks

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/tree.js
   23:9   error  Missing space before function parentheses  space-before-function-paren
   42:16  error  Missing space before function parentheses  space-before-function-paren
   46:21  error  Missing space before function parentheses  space-before-function-paren
   52:13  error  Missing space before function parentheses  space-before-function-paren
   64:13  error  Missing space before function parentheses  space-before-function-paren
   84:5   error  Unexpected var, use let or const instead   no-var
  101:14  error  Missing space before function parentheses  space-before-function-paren
  107:19  error  Missing space before function parentheses  space-before-function-paren
  113:19  error  Missing space before function parentheses  space-before-function-paren

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/tree_context.js
  11:14  error  Missing space before function parentheses  space-before-function-paren
  16:21  error  Missing space before function parentheses  space-before-function-paren

/usr/local/lib/node_modules/appium/node_modules/appium-xcuitest-driver/WebDriverAgent/Inspector/js/tree_node.js
  11:19  error  Missing space before function parentheses  space-before-function-paren
  18:23  error  Missing space before function parentheses  space-before-function-paren
  19:5   error  Unexpected var, use let or const instead   no-var
  26:23  error  Missing space before function parentheses  space-before-function-paren
  27:5   error  Unexpected var, use let or const instead   no-var
  36:19  error  Missing space before function parentheses  space-before-function-paren
  49:14  error  Missing space before function parentheses  space-before-function-paren

✖ 106 problems (93 errors, 13 warnings)


问:
Mocha - running and resolving two async/await calls
I am having a tough time getting this working.  I'm not able to get the second async call to run:

```<code>it.only('can delete an S3 bucket for a given PR', async() => {
  let result
  const options = { branch: '11'}
    // this runs and completes just fine (as you can see in the webstorm pic)
    await Deploy.createPRBucket(options, (error, stdout, stderr) => {
      console.log(`created error: ${error}`)
      console.log(`created stdout: ${stdout}`)
      console.log(`created stderr: ${stderr}`)
      result = JSON.parse(stdout)
      console.log("added")
    })

    // it never hits my console log and bombs before that right after the createPRBucket call resolves
    console.log("deleting...")
    await Deploy.deletePRBucket(options.branch, (error, stdout, stderr) => {
      console.log(`deleted error: ${error}`)
      console.log(`deleted stdout: ${stdout}`)
      console.log(`deleted stderr: ${stderr}`)
      expect(stdout).to.exist
    })
})
</code>```

The Code:

```<code>export async function createPRBucket (options, callback){
  try {
    await exec(`aws s3api create-bucket --bucket ${options.branch} --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2`,
      (error, stdout, stderr) => {
      console.error(`exec error: ${error}`);
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);

      callback(error, stdout, stderr)
      // process.exit(0)
    })
    let error, stdout, stderr

  }
  catch(err) {
    console.log(`there was a problem creating this bucket: ${err}`)
    // process.exit(1)
  }
}

export async function deletePRBucket(branch, callback){

    await exec(`aws s3 rb s3://xxx-${branch} --force`,
      (error, stdout, stderr) => {
        console.error(`exec error: ${error}`);
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);

        callback(error, stdout, stderr)
        // process.exit(0)
      })
}
</code>```

Here's what I see in WebStorm:

Note: The picture shows that I have (done) => and done() but took those out since I'm using async () =>.  Either way I arrive at the same problem, same error regardless.

Also Note that I can put a breakpoint inside the callback of the first await call (createPRBranch) in my test and it gets it just fine.  But if I put a breakpoint in the second call (await for deletePRBranch), the second never gets hit, nor does that call resolve.

答:
given that exec is a util.promisifed child_process.exec

```<code>it.only('can delete an S3 bucket for a given PR', async() => {
    let result;
    const options = { branch: '11' };
        // this runs and completes just fine (as you can see in the webstorm pic)
    let {stdout, stderr} = await Deploy.createPRBucket(options);
    console.log(`created error: ${error}`);
    console.log(`created stdout: ${stdout}`);
    console.log(`created stderr: ${stderr}`);
    result = JSON.parse(stdout);
    console.log("added");
    console.log("deleting...");

    ({stdout, stderr} = await Deploy.deletePRBucket(options.branch));
    console.log(`deleted error: ${error}`);
    console.log(`deleted stdout: ${stdout}`);
    console.log(`deleted stderr: ${stderr}`);
    expect(stdout).to.exist
})
</code>```

The exported functions can simply be - note, no need for async as they return a Promise already

```<code>export function createPRBucket(options) {
    return exec(`aws s3api create-bucket --bucket ${options.branch} --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2`);
}

export function deletePRBucket(branch) {
    return exec(`aws s3 rb s3://xxx-${branch} --force`);
}
</code>```

The promise returned by the promisified exec resolves to

```<code>{ stdout: "...", stderr: "..." }
</code>```

Note: I haven't tested for error condition of exec - the error object is

```<code>{
  killed: true or false,
  code: a number?,
  signal: null (not sure what else can be here,
  cmd: "the original command line that was run"
}
</code>```

explanation of

```<code>({stdout, stderr} = await Deploy.deletePRBucket(options.branch));
</code>```

The ( .. ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ..) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

source: MDN Docs

Body:
I am having a tough time getting this working.  I'm not able to get the second async call to run:

it.only('can delete an S3 bucket for a given PR', async() => {
  let result
  const options = { branch: '11'}
    // this runs and completes just fine (as you can see in the webstorm pic)
    await Deploy.createPRBucket(options, (error, stdout, stderr) => {
      console.log(`created error: ${error}`)
      console.log(`created stdout: ${stdout}`)
      console.log(`created stderr: ${stderr}`)
      result = JSON.parse(stdout)
      console.log("added")
    })

    // it never hits my console log and bombs before that right after the createPRBucket call resolves
    console.log("deleting...")
    await Deploy.deletePRBucket(options.branch, (error, stdout, stderr) => {
      console.log(`deleted error: ${error}`)
      console.log(`deleted stdout: ${stdout}`)
      console.log(`deleted stderr: ${stderr}`)
      expect(stdout).to.exist
    })
})

The Code:

export async function createPRBucket (options, callback){
  try {
    await exec(`aws s3api create-bucket --bucket ${options.branch} --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2`,
      (error, stdout, stderr) => {
      console.error(`exec error: ${error}`);
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);

      callback(error, stdout, stderr)
      // process.exit(0)
    })
    let error, stdout, stderr

  }
  catch(err) {
    console.log(`there was a problem creating this bucket: ${err}`)
    // process.exit(1)
  }
}

export async function deletePRBucket(branch, callback){

    await exec(`aws s3 rb s3://xxx-${branch} --force`,
      (error, stdout, stderr) => {
        console.error(`exec error: ${error}`);
        console.log(`stdout: ${stdout}`);
        console.log(`stderr: ${stderr}`);

        callback(error, stdout, stderr)
        // process.exit(0)
      })
}

Here's what I see in WebStorm:

Note: The picture shows that I have (done) => and done() but took those out since I'm using async () =>.  Either way I arrive at the same problem, same error regardless.

Also Note that I can put a breakpoint inside the callback of the first await call (createPRBranch) in my test and it gets it just fine.  But if I put a breakpoint in the second call (await for deletePRBranch), the second never gets hit, nor does that call resolve.

Body:
given that exec is a util.promisifed child_process.exec

it.only('can delete an S3 bucket for a given PR', async() => {
    let result;
    const options = { branch: '11' };
        // this runs and completes just fine (as you can see in the webstorm pic)
    let {stdout, stderr} = await Deploy.createPRBucket(options);
    console.log(`created error: ${error}`);
    console.log(`created stdout: ${stdout}`);
    console.log(`created stderr: ${stderr}`);
    result = JSON.parse(stdout);
    console.log("added");
    console.log("deleting...");

    ({stdout, stderr} = await Deploy.deletePRBucket(options.branch));
    console.log(`deleted error: ${error}`);
    console.log(`deleted stdout: ${stdout}`);
    console.log(`deleted stderr: ${stderr}`);
    expect(stdout).to.exist
})

The exported functions can simply be - note, no need for async as they return a Promise already

export function createPRBucket(options) {
    return exec(`aws s3api create-bucket --bucket ${options.branch} --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2`);
}

export function deletePRBucket(branch) {
    return exec(`aws s3 rb s3://xxx-${branch} --force`);
}

The promise returned by the promisified exec resolves to

{ stdout: "...", stderr: "..." }

Note: I haven't tested for error condition of exec - the error object is

{
  killed: true or false,
  code: a number?,
  signal: null (not sure what else can be here,
  cmd: "the original command line that was run"
}

explanation of

({stdout, stderr} = await Deploy.deletePRBucket(options.branch));

The ( .. ) around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ..) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

source: MDN Docs


问:
Cannot find symbol using BigDecimal
I'm doing my first attempts to use BigDecimal. It seems tricky.i am running into an issue and i would like to understand what is causing it.

```<code>public static String nominator(String nbrPeople)
{
    BigDecimal nom = new BigDecimal("365") ;
    BigDecimal days = new BigDecimal("365") ;
    int limit = Integer.parseInt(nbrPeople);
    for (int i = 0 ; i < limit ; i++ )
    {
        days = days.substract(i) ;
        nom = nom.multiply(days) ;
    }
    return  nbrPeople ;
}
</code>```

this is part of a larger program. it is a method that should compute something like this:

365 x (365-1) x (365-2) x (365-3) etc depending on the value of nbrPeople passed in.

i would like to understand why i get the following error message:

cannot find symbol

method substract(int)

not looking for a discussion on factorials but rather on the use of BigDecimal (or BigInteger). I'm using BigDecimal because at a later stage i will need to divide, resulting in floating point.

EDIT

EDIT 2

first edit removed (code) to make the post more readable- the correct code has been posted below by a kind programmer

答:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal

```<code>import java.math.BigDecimal;
import java.util.Scanner;

public class BigDecimal_SumExample {

    public static void main(String args[]) {

        BigDecimal  number1;
        BigDecimal  number2;
        BigDecimal  sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of number 1");
        number1 = sc.nextBigDecimal();
        System.out.println("Enter the value of number 2");
        number2 = sc.nextBigDecimal();

        BigDecimal a = new BigDecimal(""+number1);
        BigDecimal b = new BigDecimal(""+number2);
        BigDecimal result = a.add(b);

        System.out.println("Sum is Two numbers : -> ");
        System.out.println(result);

    }
}

**Output is**

Enter the value of number 1
68237161328632187132612387312687321678312612387.31276781237812

Enter the value of number 2
31232178631276123786321712369812369823162319862.32789129819299

Sum is Two Big Decimal numbers : ->
99469339959908310918934099682499691501474932249.64065911057111
</code>```

Title: Cannot find symbol using BigDecimal

Body:
I'm doing my first attempts to use BigDecimal. It seems tricky.i am running into an issue and i would like to understand what is causing it.

public static String nominator(String nbrPeople)
{
    BigDecimal nom = new BigDecimal("365") ;
    BigDecimal days = new BigDecimal("365") ;
    int limit = Integer.parseInt(nbrPeople);
    for (int i = 0 ; i < limit ; i++ )
    {
        days = days.substract(i) ;
        nom = nom.multiply(days) ;
    }
    return  nbrPeople ;
}

this is part of a larger program. it is a method that should compute something like this:

365 x (365-1) x (365-2) x (365-3) etc depending on the value of nbrPeople passed in.

i would like to understand why i get the following error message:

cannot find symbol

method substract(int)

not looking for a discussion on factorials but rather on the use of BigDecimal (or BigInteger). I'm using BigDecimal because at a later stage i will need to divide, resulting in floating point.

EDIT

EDIT 2

first edit removed (code) to make the post more readable- the correct code has been posted below by a kind programmer

Body:
http://download.oracle.com/javase/6/docs/api/java/math/BigDecimal.html#subtract(java.math.BigDecimal

import java.math.BigDecimal;
import java.util.Scanner;

public class BigDecimal_SumExample {

    public static void main(String args[]) {

        BigDecimal  number1;
        BigDecimal  number2;
        BigDecimal  sum;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the value of number 1");
        number1 = sc.nextBigDecimal();
        System.out.println("Enter the value of number 2");
        number2 = sc.nextBigDecimal();

        BigDecimal a = new BigDecimal(""+number1);
        BigDecimal b = new BigDecimal(""+number2);
        BigDecimal result = a.add(b);

        System.out.println("Sum is Two numbers : -> ");
        System.out.println(result);

    }
}

**Output is**

Enter the value of number 1
68237161328632187132612387312687321678312612387.31276781237812

Enter the value of number 2
31232178631276123786321712369812369823162319862.32789129819299

Sum is Two Big Decimal numbers : ->
99469339959908310918934099682499691501474932249.64065911057111


问:
2665 - Invalid Date Error in Teradata
I'm trying to complete an insert into statement but keep getting a "Invalid Date" error as a result.

My create statement:

```<code>CREATE MULTISET TABLE Date_Table,
    NO FALLBACK ,
    NO BEFORE JOURNAL,
    NO AFTER JOURNAL,
    CHECKSUM = DEFAULT,
    DEFAULT MERGEBLOCKRATIO
     (
      customer_field,
      date_field DATE FORMAT 'YYYY-MM-DD',
      other_fields
     )
PRIMARY INDEX ( date_field );
</code>```

My insert statement:

```<code>INSERT INTO Date_Table
select
  a.customer_field,
  a.CAST (date_field AS DATE FORMAT 'yyyy-mm-dd'),
  a.other_fields
from a
</code>```

What I've tried so far:

Making the date_field null by cast(null as date) as date_field

checking each date in the date_field against sys_calendar.calendar to make sure they're valid dates

Checking the type by SELECT TYPE (date_field) FROM date_table GROUP BY 1, they all turn out to be the 'date' type

Any thoughts?

答:
When you created Date_Table , the datatype you specified is date. May be the datatype of table a is is VARCHAR, which is  not matching with Date_Table. That is the reason you are unable run INSERT statement. We can go for CAST.

```<code>INSERT INTO Date_Table
select
  a.customer_field,
  a.CAST (cast(date_field as varchar(8)) AS DATE FORMAT 'yyyy-mm-dd'),
  a.other_fields
from a
</code>```

Title: 2665 - Invalid Date Error in Teradata

Body:
I'm trying to complete an insert into statement but keep getting a "Invalid Date" error as a result.

My create statement:

CREATE MULTISET TABLE Date_Table,
    NO FALLBACK ,
    NO BEFORE JOURNAL,
    NO AFTER JOURNAL,
    CHECKSUM = DEFAULT,
    DEFAULT MERGEBLOCKRATIO
     (
      customer_field,
      date_field DATE FORMAT 'YYYY-MM-DD',
      other_fields
     )
PRIMARY INDEX ( date_field );

My insert statement:

INSERT INTO Date_Table
select
  a.customer_field,
  a.CAST (date_field AS DATE FORMAT 'yyyy-mm-dd'),
  a.other_fields
from a

What I've tried so far:

Making the date_field null by cast(null as date) as date_field

checking each date in the date_field against sys_calendar.calendar to make sure they're valid dates

Checking the type by SELECT TYPE (date_field) FROM date_table GROUP BY 1, they all turn out to be the 'date' type

Any thoughts?

Body:
When you created Date_Table , the datatype you specified is date. May be the datatype of table a is is VARCHAR, which is  not matching with Date_Table. That is the reason you are unable run INSERT statement. We can go for CAST.

INSERT INTO Date_Table
select
  a.customer_field,
  a.CAST (cast(date_field as varchar(8)) AS DATE FORMAT 'yyyy-mm-dd'),
  a.other_fields
from a


问:
Why JavaMail connection timeout is too long
In my application I connect to server to  authenticate users. This is code:

```<code>try {
        Properties prop = new Properties();
        prop.put("mail.smtp.starttls.enable","true");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.connectiontimeout", 1000);

        Session session = Session.getInstance(prop, null);
        Transport transport = session.getTransport("smtp");
        transport.connect("mion.elka.pw.edu.pl", 587, registerLog, registerPass);
        transport.close();
        return true;
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch(AuthenticationFailedException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (MessagingException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }
</code>```

I set connection timeout to 1000 ms = 1s but it's ignore. When i debug and set wrong username and password i catch

```<code>javax.mail.MessagingException: java.net.SocketTimeoutException: Read timed out
</code>```

not after 1000 ms, but after 5000*60 ms = 5 min

What is wrong ? How can i reduce timeoute ?

答:
I had the same problem. It worked with the String instead of integer.       </p>

```<code>prop.put("mail.smtp.timeout", "1000");
prop.put("mail.smtp.connectiontimeout", "1000");
</code>```

Body:
In my application I connect to server to  authenticate users. This is code:

try {
        Properties prop = new Properties();
        prop.put("mail.smtp.starttls.enable","true");
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.connectiontimeout", 1000);

        Session session = Session.getInstance(prop, null);
        Transport transport = session.getTransport("smtp");
        transport.connect("mion.elka.pw.edu.pl", 587, registerLog, registerPass);
        transport.close();
        return true;
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch(AuthenticationFailedException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (MessagingException ex) {
        Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    }

I set connection timeout to 1000 ms = 1s but it's ignore. When i debug and set wrong username and password i catch

javax.mail.MessagingException: java.net.SocketTimeoutException: Read timed out

not after 1000 ms, but after 5000*60 ms = 5 min

What is wrong ? How can i reduce timeoute ?

Body:
I had the same problem. It worked with the String instead of integer.

prop.put("mail.smtp.timeout", "1000");
prop.put("mail.smtp.connectiontimeout", "1000");


问:
Use Angular ng-repeat to iterate over multi-tiered array
I am struggling to get an array to appear how I would like.

I have:

```<code>$scope.array = [["one", "two", "three", "four"], "five"],["six", "seven", "three", "four"], "two"]];
</code>```

And I want to iterate through and display the strings in the first array. I would like to display:

one two three four
six seven three four

Currently I have the below:

{{a[0]}}

But it is coming out as:

```<code>["one", "two", "three", "four"]

["six", "seven", "three", "four"]
</code>```

I've tried a filter to remove the quotes etc, but it keeps pulling up the other array.

答:
Try like this

```<code><div ng-repeat="item in array">
  <div ng-repeat="a in item[0]">
    {{a}}
    </div>
</div>
</code>```

and the array should be like this

```<code> $scope.array =
 [
   [["one", "two", "three", "four"], "five"],
   [["six", "seven", "three", "four"], "two"]
 ];
</code>```

var app = angular.module('app', []);
app.controller('main', ['$scope', function($scope) {
  $scope.array = [
    [
      ["one", "two", "three", "four"], "five"
    ],
    [
      ["six", "seven", "three", "four"], "two"
    ]
  ];
}]);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller=main>
  <div ng-repeat="item in array">
    <div ng-repeat="a in item[0]">
      {{a}}
    </div>
  </div>
</div></code>```

Body:
I am struggling to get an array to appear how I would like.

I have:

$scope.array = [["one", "two", "three", "four"], "five"],["six", "seven", "three", "four"], "two"]];

And I want to iterate through and display the strings in the first array. I would like to display:

one two three four
six seven three four

Currently I have the below:

{{a[0]}}

But it is coming out as:

["one", "two", "three", "four"]

["six", "seven", "three", "four"]

I've tried a filter to remove the quotes etc, but it keeps pulling up the other array.

Body:
Try like this

<div ng-repeat="item in array">
  <div ng-repeat="a in item[0]">
    {{a}}
    </div>
</div>

and the array should be like this

 $scope.array =
 [
   [["one", "two", "three", "four"], "five"],
   [["six", "seven", "three", "four"], "two"]
 ];

var app = angular.module('app', []);
app.controller('main', ['$scope', function($scope) {
  $scope.array = [
    [
      ["one", "two", "three", "four"], "five"
    ],
    [
      ["six", "seven", "three", "four"], "two"
    ]
  ];
}]);

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller=main>
  <div ng-repeat="item in array">
    <div ng-repeat="a in item[0]">
      {{a}}
    </div>
  </div>
</div>


问:
Angular2 + Protractor test running with no result
I'm starting simple Protractor test for an Angular 2 app which looks like this:

```<code>    import { browser, element, by } from 'protractor';

    describe('My Page', function() {
      it('should load news block', () => {
        browser.get('/my/page');

        element(by.id('news')).getText().then(function(text) {
          expect(text.length > 0).toBeTruthy();
        });
    });
});
</code>```

as a result system runs the browser, goes to the required page and I can't see a result - if test executed successfully. In console I always see 'Spec started' message.

What I do wrong?

Protractor config file:

```<code>exports.config = {
    allScriptsTimeout: 2500000,
    specs: [
        './e2e/**/*.e2e-spec.ts'
    ],
    capabilities: {
        'browserName': 'chrome'
    },
    directConnect: true,
    baseUrl: 'http://localhost:4200/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 2500000,
        print: function() {}
    },
    useAllAngular2AppRoots: true,
    beforeLaunch: function() {
        require('ts-node').register({
            project: 'e2e'
        });
    },
    onPrepare: function() {
        jasmine.getEnv().addReporter(new SpecReporter());
    }
};
</code>```

答:
I believe it should have logged a period for a passed test; however, since you are using a SpecReporter, this may override the default reporter to console. There are two ways you can debug this:

You can use the cool and new BlockingProxy feature. This feature should highlight the element before getting the text. You can read about how to do it here: how to debug the protractor files?

I believe there are a few cases where BlockingProxy will not highlight the element. If that is the case, you could try a couple of things to debug:

(updating answer for more logging):

```<code>  console.log('we are going to find the news id');
  element(by.id('news')).getText().then(text => {
    // If we do have text, let's log it so we know we got to this block of code.
    console.log('Pass! We have text: ' + text);
    expect(text.length > 0).toBeTruthy();
  }).catch(err => {
    // Else we could not fid the 'news' id, so we should log an error.
    console.log('The id for news could not be found.);
    console.log(err);
  });
</code>```

Body:
I'm starting simple Protractor test for an Angular 2 app which looks like this:

    import { browser, element, by } from 'protractor';

    describe('My Page', function() {
      it('should load news block', () => {
        browser.get('/my/page');

        element(by.id('news')).getText().then(function(text) {
          expect(text.length > 0).toBeTruthy();
        });
    });
});

as a result system runs the browser, goes to the required page and I can't see a result - if test executed successfully. In console I always see 'Spec started' message.

What I do wrong?

Protractor config file:

exports.config = {
    allScriptsTimeout: 2500000,
    specs: [
        './e2e/**/*.e2e-spec.ts'
    ],
    capabilities: {
        'browserName': 'chrome'
    },
    directConnect: true,
    baseUrl: 'http://localhost:4200/',
    framework: 'jasmine',
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 2500000,
        print: function() {}
    },
    useAllAngular2AppRoots: true,
    beforeLaunch: function() {
        require('ts-node').register({
            project: 'e2e'
        });
    },
    onPrepare: function() {
        jasmine.getEnv().addReporter(new SpecReporter());
    }
};

Body:
I believe it should have logged a period for a passed test; however, since you are using a SpecReporter, this may override the default reporter to console. There are two ways you can debug this:

You can use the cool and new BlockingProxy feature. This feature should highlight the element before getting the text. You can read about how to do it here: how to debug the protractor files?

I believe there are a few cases where BlockingProxy will not highlight the element. If that is the case, you could try a couple of things to debug:

(updating answer for more logging):

  console.log('we are going to find the news id');
  element(by.id('news')).getText().then(text => {
    // If we do have text, let's log it so we know we got to this block of code.
    console.log('Pass! We have text: ' + text);
    expect(text.length > 0).toBeTruthy();
  }).catch(err => {
    // Else we could not fid the 'news' id, so we should log an error.
    console.log('The id for news could not be found.);
    console.log(err);
  });


问:
SQLAlchemy query using list of elements
I have set up a SQLAlchemy database that looks roughly like this:

```<code>class ChangelogEntry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    apps = db.relationship('App', secondary=app_changelogEntry)
    appGroups = db.relationship('AppGroup', secondary=appGroup_changelogEntry)

class App(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True, index=True)
    appGroups = db.relationship('AppGroup', secondary=app_appGroup)

class AppGroup(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True, index=True)
    apps = db.relationship('App', secondary=app_appGroup)
</code>```

UPDATE:

```<code>app_changelogEntry = db.Table('App_ChangelogEntry',
    db.Column('app_id', db.Integer, db.ForeignKey('app.id')),
    db.Column('changelog_id', db.Integer, db.ForeignKey('changelog_entry.id'))
)

appGroup_changelogEntry = db.Table('AppGroup_ChangelogEntry',
    db.Column('appGroup_id', db.Integer, db.ForeignKey('app_group.id')),
    db.Column('changelogEntry_id', db.Integer, db.ForeignKey('changelog_entry.id'))
)

app_appGroup = db.Table('App_AppGroup',
    db.Column('app_id', db.Integer, db.ForeignKey('app.id')),
    db.Column('appGroup_id', db.Integer, db.ForeignKey('app_group.id'))
)
</code>```

An App can be part of several AppGroups and users can create ChangelogEntries and can select what App/Apps and/or AppGroups this ChangelogEntry belongs to.

It looks like this:

Alright. I just want to get all ChangelogEntries that belong to e.g. App3 (App3 is part of AppGroups Group1 and Group2) and in this case Group1 and Group2.

I hope you can help me with that!

答:
A union might be a good match for the task at hand: find the union of changelog entries with direct app relationship and through groups. Using inner joins:

```<code>direct = db.session.query(ChangelogEntry).\
    join("apps").\
    filter(App.name == "App3")

groups = db.session.query(ChangelogEntry).\
    join("appGroups", "apps").\
    filter(App.name == "App3")

direct.union(groups).all()
</code>```

Because of the many to many relationships the group joins might produce multiple rows for a changelog entry, but using a UNION instead of UNION ALL takes care of that. In order to avoid duplicate rows to begin with you could use semijoins/EXISTS:

```<code>direct = db.session.query(ChangelogEntry).\
    filter(ChangelogEntry.apps.any(App.name == "App3"))

groups = db.session.query(ChangelogEntry).\
    filter(ChangelogEntry.appGroups.any(
        AppGroup.apps.any(App.name == "App3")))

direct.union(groups).all()
</code>```

Title: SQLAlchemy query using list of elements

Body:
I have set up a SQLAlchemy database that looks roughly like this:

class ChangelogEntry(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    apps = db.relationship('App', secondary=app_changelogEntry)
    appGroups = db.relationship('AppGroup', secondary=appGroup_changelogEntry)

class App(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True, index=True)
    appGroups = db.relationship('AppGroup', secondary=app_appGroup)

class AppGroup(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(32), unique=True, index=True)
    apps = db.relationship('App', secondary=app_appGroup)

UPDATE:

app_changelogEntry = db.Table('App_ChangelogEntry',
    db.Column('app_id', db.Integer, db.ForeignKey('app.id')),
    db.Column('changelog_id', db.Integer, db.ForeignKey('changelog_entry.id'))
)

appGroup_changelogEntry = db.Table('AppGroup_ChangelogEntry',
    db.Column('appGroup_id', db.Integer, db.ForeignKey('app_group.id')),
    db.Column('changelogEntry_id', db.Integer, db.ForeignKey('changelog_entry.id'))
)

app_appGroup = db.Table('App_AppGroup',
    db.Column('app_id', db.Integer, db.ForeignKey('app.id')),
    db.Column('appGroup_id', db.Integer, db.ForeignKey('app_group.id'))
)

An App can be part of several AppGroups and users can create ChangelogEntries and can select what App/Apps and/or AppGroups this ChangelogEntry belongs to.

It looks like this:

Alright. I just want to get all ChangelogEntries that belong to e.g. App3 (App3 is part of AppGroups Group1 and Group2) and in this case Group1 and Group2.

I hope you can help me with that!

Body:
A union might be a good match for the task at hand: find the union of changelog entries with direct app relationship and through groups. Using inner joins:

direct = db.session.query(ChangelogEntry).\
    join("apps").\
    filter(App.name == "App3")

groups = db.session.query(ChangelogEntry).\
    join("appGroups", "apps").\
    filter(App.name == "App3")

direct.union(groups).all()

Because of the many to many relationships the group joins might produce multiple rows for a changelog entry, but using a UNION instead of UNION ALL takes care of that. In order to avoid duplicate rows to begin with you could use semijoins/EXISTS:

direct = db.session.query(ChangelogEntry).\
    filter(ChangelogEntry.apps.any(App.name == "App3"))

groups = db.session.query(ChangelogEntry).\
    filter(ChangelogEntry.appGroups.any(
        AppGroup.apps.any(App.name == "App3")))

direct.union(groups).all()


问:
Reference to an instance method of a particular object breaks the type-safety in Java?
Does the notion of a reference to an instance method of a particular object break the type-safety in Java?

According to

https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

you can have a custom class ComparisonProvider  that DOES not implement the Comparator  interface, and still use an instance of this class as the second argument of the method

Arrays.sort(T[] a, Comparator c)

Sure, the implementation of your ComparisonProvider MUST have a method whose signature exactly matches the Comparator.compare() method, but that is still not an instance of Comparator, isn't it?

In essence, Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not.

This means, that we are loosing Type-safety in Java, do we?

答:
Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not

Not exactly, it allows you to use a single method of some instance of a class as if it were implementing some functional interface.

And it doesn't add any functionality that didn't exist in Java 7 - it just gives you a short cut to writing that functionality.

For example, instead of:

```<code>Arrays.sort(someArray, someInstance::someMethod);
</code>```

In Java 7 you could use anonymous class instance to write:

```<code>Arrays.sort(someArray, new Comparator<SomeType> () {
                public int compare (SomeType one, SomeTypeTwo) {
                    return someInstance.someMethod(one,two);
                }
            });
</code>```

As long as the instance method is accessible (i.e. public), you can use it as you see fit.

Body:
Java 8 allows us to use instances of classes as if they were implementing a particular interface, while actually they are not

Not exactly, it allows you to use a single method of some instance of a class as if it were implementing some functional interface.

And it doesn't add any functionality that didn't exist in Java 7 - it just gives you a short cut to writing that functionality.

For example, instead of:

Arrays.sort(someArray, someInstance::someMethod);

In Java 7 you could use anonymous class instance to write:

Arrays.sort(someArray, new Comparator<SomeType> () {
                public int compare (SomeType one, SomeTypeTwo) {
                    return someInstance.someMethod(one,two);
                }
            });

As long as the instance method is accessible (i.e. public), you can use it as you see fit.


问:
How to set a javascript file in chrome,when ever I open a new window it will automatically get execute?
My js file contains some userid and password.I want to set as a prompt for new tab.</p>

答:
You can use bookmark,

press ctrl+D in the name section, javascript: #your script

refer this Bookmarklet

I used to load script in this way for eg: Tatkal ticket booking, etc...


问:
Laravel 5 - How do I handle MethodNotAllowedHttpException
Where can I catch a MethodNotAllowedHttpException in Laravel 5+?

In Laravel 4 I was able to do this in start/global.php.

答:
In Laravel 5.4, I did it like this:

File location: app/Exceptions/Handler.php

Add this code at the top of the file:

```<code>use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
</code>```

And modify the method code as belows:

```<code>/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof MethodNotAllowedHttpException)
        {
            return response()->json( [
                                        'success' => 0,
                                        'message' => 'Method is not allowed for the requested route',
                                    ], 405 );
        }

        return parent::render($request, $exception);
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In Laravel 5.4, I did it like this:

File location: app/Exceptions/Handler.php

Add this code at the top of the file:

use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;

And modify the method code as belows:

/**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof MethodNotAllowedHttpException)
        {
            return response()->json( [
                                        'success' => 0,
                                        'message' => 'Method is not allowed for the requested route',
                                    ], 405 );
        }

        return parent::render($request, $exception);
    }


问:
How to avoid Generics in this case?
```<code>class Attribute<T>{
   private T attr;
   public Attribute(T attr){
      this.attr = attr;
   }
}

Class Matrix<T>{
   private String name;
   List<Attribute<T>> list;

   public Matrix(String name, T t){
     this.name = name;
     list = new ArrayList<>();
     list.add(new Attribute<T>(t));
  }
}

 interface Extractor<T> {
    public List<Matrix<T>> extract();
}

InfoExtractor implements Extractor<String>{

    public List<Matrix<String>> extract(){
       List<Matrix<String>> matrixList = new ArrayList<>();

        // The problem is here!!!!
        matrixList.add(new Matrix<String>("abc"));
    }
 }

 Document<T>{
      Map<String, List<Matrix<T>>> matrixMap;

        public void process(){
        ...
         Extractor<T> extractor = (Extractor<T>) new StringExtractor(sent);
        List<Matrix<T>> matrix = extractor.extract(...);
   }
</code>```

My question is, is there a way to avoid defining Matrix as a generic type ? The reason I want to avoid is that the "List<Attribute<T>> " is used in multiple other classes, either as private member variables, or method return types. Due to Attribute, it seems I have to define some other related classes as generic types too, which causes my problem.

In this case, is there a way to not define Matrix as generic, but keep the  "list" variable as a generic type?

答:
It depends on what you would like to do.

If you intend to use Matrix to hold a single type of attribute, that is T then the best approach seems to be the one you posted as you get to have compile time type checking.

If you remove the generic type T from Matrix then you cannot know the type of each attribute. You can completely remove T from Matrix declaration and use the wildcard for the Attribute variable. While this would allow you to store attributes of different T types in the same Matrix object, it will remove the compile type checking. In other words, the classes using the Matrix would have to know what class to expect and perhaps cast each attribute to the class expected.

```<code>Class Matrix{
   private String name;
   List<Attribute<?>> list;

   public Matrix(String name, T t){
     this.name = name;
     list = new ArrayList<>();
     list.add(new Attribute<>(t));
  }
}
</code>```

Adding a Class variable and saving the Class object inside the attribute, could help you retain some information in runtime to identify the class of the objects inside the attribute.

```<code>class Attribute<T>{
   private T attr;
   private final Class<T> clazz;

   public Attribute(T attr, Class<T> clazz){
      this.attr = attr;
      this.clazz=clazz;
   }

    public Attribute(T attr){
      this.attr = attr;
      Objects.requireNonNull(attr);
      this.clazz= (Class<T>) attr.getClass();
   }
}
</code>```

Using this approach the original constructor can be used only for non null values, otherwise the class object should be provided by the programmer.

Title: How to avoid Generics in this case?

Body:
class Attribute<T>{
   private T attr;
   public Attribute(T attr){
      this.attr = attr;
   }
}

Class Matrix<T>{
   private String name;
   List<Attribute<T>> list;

   public Matrix(String name, T t){
     this.name = name;
     list = new ArrayList<>();
     list.add(new Attribute<T>(t));
  }
}

 interface Extractor<T> {
    public List<Matrix<T>> extract();
}

InfoExtractor implements Extractor<String>{

    public List<Matrix<String>> extract(){
       List<Matrix<String>> matrixList = new ArrayList<>();

        // The problem is here!!!!
        matrixList.add(new Matrix<String>("abc"));
    }
 }

 Document<T>{
      Map<String, List<Matrix<T>>> matrixMap;

        public void process(){
        ...
         Extractor<T> extractor = (Extractor<T>) new StringExtractor(sent);
        List<Matrix<T>> matrix = extractor.extract(...);
   }

My question is, is there a way to avoid defining Matrix as a generic type ? The reason I want to avoid is that the "List<Attribute<T>> " is used in multiple other classes, either as private member variables, or method return types. Due to Attribute, it seems I have to define some other related classes as generic types too, which causes my problem.

In this case, is there a way to not define Matrix as generic, but keep the  "list" variable as a generic type?

Body:
It depends on what you would like to do.

If you intend to use Matrix to hold a single type of attribute, that is T then the best approach seems to be the one you posted as you get to have compile time type checking.

If you remove the generic type T from Matrix then you cannot know the type of each attribute. You can completely remove T from Matrix declaration and use the wildcard for the Attribute variable. While this would allow you to store attributes of different T types in the same Matrix object, it will remove the compile type checking. In other words, the classes using the Matrix would have to know what class to expect and perhaps cast each attribute to the class expected.

Class Matrix{
   private String name;
   List<Attribute<?>> list;

   public Matrix(String name, T t){
     this.name = name;
     list = new ArrayList<>();
     list.add(new Attribute<>(t));
  }
}

Adding a Class variable and saving the Class object inside the attribute, could help you retain some information in runtime to identify the class of the objects inside the attribute.

class Attribute<T>{
   private T attr;
   private final Class<T> clazz;

   public Attribute(T attr, Class<T> clazz){
      this.attr = attr;
      this.clazz=clazz;
   }

    public Attribute(T attr){
      this.attr = attr;
      Objects.requireNonNull(attr);
      this.clazz= (Class<T>) attr.getClass();
   }
}

Using this approach the original constructor can be used only for non null values, otherwise the class object should be provided by the programmer.


问:
PHP - get object parent
I have a function that is called like this:

```<code>foo($object->ID);
</code>```

and in the function I need to somehow select $object if $object->ID is passed as a variable.

```<code>function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}
</code>```

How can I do this?

答: You need to pass the object in as an argument instead of the ID.</p>

Title: PHP - get object parent

Body:
I have a function that is called like this:

foo($object->ID);

and in the function I need to somehow select $object if $object->ID is passed as a variable.

function foo($id = NULL){
  if($id != NULL) ... // here I want to get $object
  else ...
}

How can I do this?


问:
Azure blob versioning
Is there a way I can version the blobs being stored in Azure storage account, so that the blobs can be picked up using their version or the latest blob can be picked up?</p>

答:
Versioning for blobs is accomplished by taking a snapshot of a blob which creates a read-only copy of the blob based on the blob's contents when snapshot was taken.

When a snapshot for a blob is taken, Azure Storage returns a date/time value when the snapshot was taken. You can access that blob by appending this value to the blob's URL e.g. https://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot=2017-06-09T00:00:00.0000000Z

However this snapshot date/time value is not stored anywhere in Azure.

What you could do is store this date/time value in your database and whenever you need to present this version of the blob in your application, you can simply append this value to the blob's URL.

Please note that snapshot exist along with blob i.e. if you delete the base blob, all snapshots for the blob will also be deleted.

Title: Azure blob versioning


问:
postgresql postgis If point inside circle
I'm using postgresql as db , i have the table named car_wash  with field "point geometry"(use postgis) so in application I'm getting lon lat from user using GOOGLE API, next step I need to create circle around user and check if car_wash inside this circle I use

```<code>  select *
 from car_wash cw
where
ST_DWithin (
   cw.lon_lat,
   ST_GeomFromText('POINT(54.21 22.54)')
)=false
AND
not cw.was_deleted
</code>```

Is it corect way? IF you need my srid is 0 according to this query

```<code> Select Find_SRID('public',  'car_wash',  'lon_lat')
</code>```

答:
While using ST_DWithin function, your third parameter must be distance.
You can also define srid in ST_GeomFromText

there are two simple example so you can see difference:

```<code>select ST_DWithin(
st_geomfromtext('POINT(54.51 22.54)',4326),
st_geomfromtext('POINT(54.21 22.54)',4326),0.5
)
result is true

select ST_DWithin(
st_geomfromtext('POINT(54.51 22.54)',4326),
st_geomfromtext('POINT(54.21 22.54)',4326),0.1
)
result is false
</code>```

Source:

https://postgis.net/docs/ST_DWithin.html

https://postgis.net/docs/ST_GeomFromText.html

Body:
I'm using postgresql as db , i have the table named car_wash  with field "point geometry"(use postgis) so in application I'm getting lon lat from user using GOOGLE API, next step I need to create circle around user and check if car_wash inside this circle I use

  select *
 from car_wash cw
where
ST_DWithin (
   cw.lon_lat,
   ST_GeomFromText('POINT(54.21 22.54)')
)=false
AND
not cw.was_deleted

Is it corect way? IF you need my srid is 0 according to this query

 Select Find_SRID('public',  'car_wash',  'lon_lat')

Body:
While using ST_DWithin function, your third parameter must be distance.
You can also define srid in ST_GeomFromText

there are two simple example so you can see difference:

select ST_DWithin(
st_geomfromtext('POINT(54.51 22.54)',4326),
st_geomfromtext('POINT(54.21 22.54)',4326),0.5
)
result is true

select ST_DWithin(
st_geomfromtext('POINT(54.51 22.54)',4326),
st_geomfromtext('POINT(54.21 22.54)',4326),0.1
)
result is false

Source:

https://postgis.net/docs/ST_DWithin.html

https://postgis.net/docs/ST_GeomFromText.html


问:
Gives ORA-01841: (full) year must be between -4713 and +9999, and not be 0 on Oracle select statement from on .net application
```<code>string vDate="2017/06/08";
OracleCommand cmd= new OracleCommand();
OracleParamater pDate= new OracleParameter("pDate",OracleDbType.Varchar2);
pDate.Direction=ParameterDirection.Input;
pDate.Value= vDate;
cmd.Parameters.Add(pDate);
cmd.CommandText="select * from testtable where joinDate<=to_date(:pDate, 'YYYY/MM/DD')";
cmd.CommandType=CommandType.Text;
DataSet ds= new DataSet();
OracleDataAdapter adp= new OracleDataAdapter(); //Please assume that db is connected successfully.
adp.fill(ds);
</code>```

joinDate type is of Date.

When application execute the query it is giving ora-01841 error. I tried with  OracleDBType.Date too, assigning vDate as DateTime type. How do I fix this issue?

Your help would be highly appreciated.

答:
You should better use it like this:</p>

```<code>DateTime vDate = new DateTime(2017, 6, 8);
OracleCommand cmd= new OracleCommand();
cmd.CommandText="select * from testtable where joinDate <= :pDate";
OracleParamater pDate= new OracleParameter("pDate",OracleDbType.Date);
pDate.Direction=ParameterDirection.Input;
pDate.Value= vDate;
cmd.Parameters.Add(pDate);
</code>```

Body:
string vDate="2017/06/08";
OracleCommand cmd= new OracleCommand();
OracleParamater pDate= new OracleParameter("pDate",OracleDbType.Varchar2);
pDate.Direction=ParameterDirection.Input;
pDate.Value= vDate;
cmd.Parameters.Add(pDate);
cmd.CommandText="select * from testtable where joinDate<=to_date(:pDate, 'YYYY/MM/DD')";
cmd.CommandType=CommandType.Text;
DataSet ds= new DataSet();
OracleDataAdapter adp= new OracleDataAdapter(); //Please assume that db is connected successfully.
adp.fill(ds);

joinDate type is of Date.

When application execute the query it is giving ora-01841 error. I tried with  OracleDBType.Date too, assigning vDate as DateTime type. How do I fix this issue?

Your help would be highly appreciated.

Body:
You should better use it like this:

DateTime vDate = new DateTime(2017, 6, 8);
OracleCommand cmd= new OracleCommand();
cmd.CommandText="select * from testtable where joinDate <= :pDate";
OracleParamater pDate= new OracleParameter("pDate",OracleDbType.Date);
pDate.Direction=ParameterDirection.Input;
pDate.Value= vDate;
cmd.Parameters.Add(pDate);


问:
Hygieia Specific,UI, Gulp - How To
Query related to opensource tool Hygieia. On the Gulp scripts https://github.com/capitalone/Hygieia/blob/v2.0.0/UI/gulpfile.js
Gulp serve serves the application. here are few queries i need help with

In version 1.5.0 gulp task runner had gulp serve:dist, which served only minified content, 2.0 does not seem to do that

gulp serve starts the app @ port 3000, how do i control it for each instance, as i intend to run couple of instances(diff versions) on the same vm.

When UI is served @ localhost:3000/ , all the content is served from
localhost:3000/# and localhost:3000/bower_components .. etc..
i want to move the content to be served under localhost:3000/WebApp/
So that all the URLs are under a specific Virt Directory.

Any pointers are greatly appreciated.

TIA,

Tx

答:
your question not much clear. still if i understand your question correctly-
your current hygieia configuration working correctly. you just want to run multiple instances of same application. </p>

<p>for that you have to make changes in UI>gulpfile.js </p>

Title: Hygieia Specific,UI, Gulp - How To

Body:
your question not much clear. still if i understand your question correctly-
your current hygieia configuration working correctly. you just want to run multiple instances of same application.

for that you have to make changes in UI>gulpfile.js