问:
Method local inner class hides method fields
Given the following class definition

```<code>public class MethodLocalAccess {

    int m = 10;

    String show(){
        final int m = 20;
        final int n = 30;
        class MyClass{
            int m = 40;
            String someOtherMethod(){
                return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
            }
        }

        MyClass object = new MyClass();
        return object.someOtherMethod();
    }

    public static void main(String[] args) {
        System.out.println(new MethodLocalAccess().show());
    }

}
</code>```

Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.

Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.

答:
What are you referring to is called variable shadowing (link).

If a declaration of a type (such as a member variable or a parameter
  name) in a particular scope (such as an inner class or a method
  definition) has the same name as another declaration in the enclosing
  scope, then the declaration shadows the declaration of the enclosing
  scope. You cannot refer to a shadowed declaration by its name alone.

Once you shadowed a variable, it is not accessible anymore without explicitly specifying its scope, if possible. The only solution in this case is to rename either outer or inner variable.

Body:
Given the following class definition

public class MethodLocalAccess {

    int m = 10;

    String show(){
        final int m = 20;
        final int n = 30;
        class MyClass{
            int m = 40;
            String someOtherMethod(){
                return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
            }
        }

        MyClass object = new MyClass();
        return object.someOtherMethod();
    }

    public static void main(String[] args) {
        System.out.println(new MethodLocalAccess().show());
    }

}

Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.

Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.


来源: stackexchange

问:
How to cat two column (float) into a column quick and efficiency in pandas dataframe?
I want to get a new column by cat two column (float or int) as following shows,

So anyone have a better idea?

I think mine is something too complex

```<code>a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
</code>```

答:
how about using apply?

```<code>abc['new'] = abc.apply(lambda x: '{}::{}'.format(x['a'],x['b']), axis=1)
</code>```

it is a simple one-liner this way.

ContentLicense: CC BY-SA 3.0

Body:
I want to get a new column by cat two column (float or int) as following shows,

So anyone have a better idea?

I think mine is something too complex

a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

Body:
how about using apply?

abc['new'] = abc.apply(lambda x: '{}::{}'.format(x['a'],x['b']), axis=1)

it is a simple one-liner this way.


问:
mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement in
/the cart table has 4 fields; id, username, product id, image. I am trying show all the data in a table.  </p>

```<code><?php

$query = "SELECT * FROM cart WHERE user_name='$username'";

if ($stmt = mysqli_prepare($mysqli, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt,$username);

    /* fetch values */
    while ($row=mysqli_stmt_fetch($stmt))

{
</code>```

答:
There are, as far as I can see, two issues here

You're not binding your input - this is the whole point of prepared statements. You need mysqli_stmt_bind_param(). Injecting variables directly in the query is not safe, and is why we prepare our queries.

You're not binding the exact amount of columns selected with mysqli_stmt_bind_result(). This needs to be the exact amount of columns you select.

To make this work, you need to use placeholders ? in the query instead of variables (and use mysqli_stmt_bind_param()). You should also select the specific columns, and not do SELECT *. If you do SELECT *, you can still make it work if you still bind the same amount of results - but the code will break if you add one column at a later time.

This code below has been altered to select the specific columns, and match that with as many results you bind (columns) in mysqli_stmt_bind_result(). A placeholder in the query has been added, and usage of mysqli_stmt_bind_param() implemented.

```<code>$query = "SELECT id, user_name, produc_id, image FROM cart WHERE user_name=?";

if ($stmt = mysqli_prepare($mysqli, $query)) {

    mysqli_stmt_bind_param("s", $username);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $user_id, $username, $product_id, $image);

    /* fetch values */
    while ($row=mysqli_stmt_fetch($stmt)) {
        // Fetch here
    }
}
</code>```

mysqli_stmt::bind_param()

mysqli_stmt::bind_result()

Body:
/the cart table has 4 fields; id, username, product id, image. I am trying show all the data in a table.

<?php

$query = "SELECT * FROM cart WHERE user_name='$username'";

if ($stmt = mysqli_prepare($mysqli, $query)) {

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt,$username);

    /* fetch values */
    while ($row=mysqli_stmt_fetch($stmt))

{

Body:
There are, as far as I can see, two issues here

You're not binding your input - this is the whole point of prepared statements. You need mysqli_stmt_bind_param(). Injecting variables directly in the query is not safe, and is why we prepare our queries.

You're not binding the exact amount of columns selected with mysqli_stmt_bind_result(). This needs to be the exact amount of columns you select.

To make this work, you need to use placeholders ? in the query instead of variables (and use mysqli_stmt_bind_param()). You should also select the specific columns, and not do SELECT *. If you do SELECT *, you can still make it work if you still bind the same amount of results - but the code will break if you add one column at a later time.

This code below has been altered to select the specific columns, and match that with as many results you bind (columns) in mysqli_stmt_bind_result(). A placeholder in the query has been added, and usage of mysqli_stmt_bind_param() implemented.

$query = "SELECT id, user_name, produc_id, image FROM cart WHERE user_name=?";

if ($stmt = mysqli_prepare($mysqli, $query)) {

    mysqli_stmt_bind_param("s", $username);

    /* execute statement */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $user_id, $username, $product_id, $image);

    /* fetch values */
    while ($row=mysqli_stmt_fetch($stmt)) {
        // Fetch here
    }
}

mysqli_stmt::bind_param()

mysqli_stmt::bind_result()


问:
How to close angular strap modal with form on submit
```I am using angular 1.3 with strap modal dialog and the form inside it.
There are 2 buttons: OK and Cancel.
Cancel works as expected - it closes the modal.
But on OK the dialog is not closed; however, the form is processed as expected.
The code below shows the model and the code which instantiates the modal dialog.
I am using button type=submit on OK to process the form.
The $modal.showTemplate has 2 parameters:
 1) HTML (code below)
 2) callback which shall know which button was used: OK or Cancel.

For some reason, this callback is invoked only on Cancel.
I tried to fix it by using  ng-click="$close(true) on OK button
instead type=submit but it does not help.
Question: how to close the modal dialog on OK?
 ```

     <form
            role="form"
            name="detailForm"
            ng-submit="submit()"
     >

         ... some form fields are here ...
        <button class="btn" ng-click="$close(false)">
                  Cancel
        </button>
        <button class="btn"  type="submit">
                  OK
        </button>

   </form>

$modal.showTemplate(htmlTemplate,
 function(confirm) {
    console.log("callback confirm="+confirm);
    if (confirm === true) {
       console.log(" this point never achieved ... and modal dialog is not closed");
    } else {
       console.log(" this works as expected and modal dialog is closed");
    }
  },

);
```

答:
Get rid of the submit type on your 'OK' button. Attach the ng-click directive to this same 'OK' button. On click your button will submit the form via '[externalController].submit()'. If submit() returns a promise then wait for it, otherwise then call the modal controllers 'close()';

```<code> <button class="btn"  ng-click="functionThatSubmitsAndCloses()">
              OK
    </button>
</code>```

And in your 'internal controller' you'll have that function defined on your scope

```<code>$scope.functionThatSubmitsAndCloses = function () {
    [scope of externalController].submit();
    $close(true); // close being defined on the instance of your modal's controller and not this internal controller.
}
</code>```

Is this an older version of angular strap? I do not see showTemplate defined in their API.

Body:
I am using angular 1.3 with strap modal dialog and the form inside it.
There are 2 buttons: OK and Cancel.
Cancel works as expected - it closes the modal.
But on OK the dialog is not closed; however, the form is processed as expected.
The code below shows the model and the code which instantiates the modal dialog.
I am using button type=submit on OK to process the form.
The $modal.showTemplate has 2 parameters:
 1) HTML (code below)
 2) callback which shall know which button was used: OK or Cancel.

For some reason, this callback is invoked only on Cancel.
I tried to fix it by using  ng-click="$close(true) on OK button
instead type=submit but it does not help.
Question: how to close the modal dialog on OK?

     <form
            role="form"
            name="detailForm"
            ng-submit="submit()"
     >

         ... some form fields are here ...
        <button class="btn" ng-click="$close(false)">
                  Cancel
        </button>
        <button class="btn"  type="submit">
                  OK
        </button>

   </form>

$modal.showTemplate(htmlTemplate,
 function(confirm) {
    console.log("callback confirm="+confirm);
    if (confirm === true) {
       console.log(" this point never achieved ... and modal dialog is not closed");
    } else {
       console.log(" this works as expected and modal dialog is closed");
    }
  },

);

Body:
Get rid of the submit type on your 'OK' button. Attach the ng-click directive to this same 'OK' button. On click your button will submit the form via '[externalController].submit()'. If submit() returns a promise then wait for it, otherwise then call the modal controllers 'close()';

 <button class="btn"  ng-click="functionThatSubmitsAndCloses()">
              OK
    </button>

And in your 'internal controller' you'll have that function defined on your scope

$scope.functionThatSubmitsAndCloses = function () {
    [scope of externalController].submit();
    $close(true); // close being defined on the instance of your modal's controller and not this internal controller.
}

Is this an older version of angular strap? I do not see showTemplate defined in their API.


答:
No you can't. The variable inside the function completely shadowed and you can't refer it anymore as Java doesn't have a way to refer function context.

However you can access top level variables with the context this even though they shadowed (infact you are not shadowing and creating a local variable with same name).

Title: Method local inner class hides method fields


问:
Jquery for filtering products
I have this jquery plugin that filter products

 (function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor == 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter('[data-cat = "' + $filterColor + '"]')
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);```
</div>
</div>
</p>

<p>[data-cat] is the category
but some products belong to more than one category and the filter doesn't work with them. It is working if the category is the only one you click the filter button (if the product has 2 categories, for example, airtickets and ferry tickets clicking in airtickets filter button doest show this product at all) and it won't to show the items contain the airtickets in their category, not only the ones that contain only the airtickets</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cta filter">
  All
  Airtickets
  Ferry
</div></code>```

答:
Probably you need something like this:

(function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor == 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter(function(i,el){
              return el.dataset.cat.split(',').indexOf($filterColor)!==-1;
          })
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cta filter">
  All
  Cat1
  Cat2
  Cat3

  <ul class="boxes">
    <li data-cat="cat1,cat2">cat1 & cat2</li>
    <li data-cat="cat2">cat2</li>
    <li data-cat="cat3">cat3</li>
  </ul>
</div></code>```

Title: Jquery for filtering products

Body:
I have this jquery plugin that filter products

 (function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor == 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter('[data-cat = "' + $filterColor + '"]')
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);

[data-cat] is the category
but some products belong to more than one category and the filter doesn't work with them. It is working if the category is the only one you click the filter button (if the product has 2 categories, for example, airtickets and ferry tickets clicking in airtickets filter button doest show this product at all) and it won't to show the items contain the airtickets in their category, not only the ones that contain only the airtickets

  All
  Airtickets
  Ferry

Body:
Probably you need something like this:

(function($) {

  'use strict';

  var $filters = $('.filter [data-filter]'),
    $boxes = $('.boxes [data-cat]');

  $filters.on('click', function(e) {
    e.preventDefault();
    var $this = $(this);

    $filters.removeClass('active');
    $this.addClass('active');

    var $filterColor = $this.attr('data-filter');

    if ($filterColor == 'all') {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.addClass('is-animated').fadeIn();
        });
    } else {
      $boxes.removeClass('is-animated')
        .fadeOut().promise().done(function() {
          $boxes.filter(function(i,el){
              return el.dataset.cat.split(',').indexOf($filterColor)!==-1;
          })
            .addClass('is-animated').fadeIn();
        });
    }
  });

})(jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cta filter">
  <a class="blue-btn btn" data-filter="all" href="#" >All</a>
  <a class="blue-btn btn" data-filter="cat1" href="#" role="button">Cat1</a>
  <a class="blue-btn btn" data-filter="cat2" href="#" role="button">Cat2</a>
  <a class="blue-btn btn" data-filter="cat3" href="#" role="button">Cat3</a>

  <ul class="boxes">
    <li data-cat="cat1,cat2">cat1 & cat2</li>
    <li data-cat="cat2">cat2</li>
    <li data-cat="cat3">cat3</li>
  </ul>
</div>


问:
Applying Behaviors with JS Mixins in Polymer 2
I want a custom element I'm defining to have the Polymer.IronScrollTargetBehavior in Polymer 2.

In Polymer 1, this can be done by adding it to the behaviors array:

```<code>Polymer({
    is: 'my-element',
    behaviors: [Polymer.IronScrollTargetBehavior]
});
</code>```

In the Polymer 2 upgrade guide, it says that you should:

Implement "behaviors" as mixins that return class expressions.

In the linked article, it explains how you can use the following syntax for mixins:

```<code>let MyMixin = (superclass) => class extends superclass {
    foo() {
        console.log('foo from MyMixin');
    }
};

class MyClass extends MyMixin(MyBaseClass) {
    /* ... */
}
</code>```

I mostly get what's going on here (although I find the mixin syntax difficult to wrap my mind around), and I can get sample code to work.

What I haven't been able to do is apply this concept to Polymer.IronScrollTargetBehavior, and create a mixin for it. Since that behavior is already defined as an object, I don't know where to fit it in.

So, how do I implement the proper mixin in this scenario, or if I'm on the wrong path, how to I apply one of the defined Polymer behaviors to my custom element in Polymer 2?

答:
You can use the Polymer 2 hybrid behaviours as mixins by extending
 Polymer.mixinBehaviors(behaviors, klass) where

- behaviors is the Behavior object or array of behaviors

- klass is the Element class.

i.e.

```<code><dom-module id="element-name">
  <template><!-- ... --></template>
  <script>
    class MyElement extends Polymer.mixinBehaviors([MyBehavior, MyBehavior2], Polymer.Element) {
     static get is() { return 'element-name' }
     /* ... */
    }
    customElements.define('element-name', MyElement);
  </script>
</dom-module>
</code>```

For more detailed information search the Polymer source code for mixinBehaviors method: polymer/lib/legacy/class.html

worth reading: https://www.polymer-project.org/2.0/docs/upgrade#mixins

Body:
I want a custom element I'm defining to have the Polymer.IronScrollTargetBehavior in Polymer 2.

In Polymer 1, this can be done by adding it to the behaviors array:

Polymer({
    is: 'my-element',
    behaviors: [Polymer.IronScrollTargetBehavior]
});

In the Polymer 2 upgrade guide, it says that you should:

Implement "behaviors" as mixins that return class expressions.

In the linked article, it explains how you can use the following syntax for mixins:

let MyMixin = (superclass) => class extends superclass {
    foo() {
        console.log('foo from MyMixin');
    }
};

class MyClass extends MyMixin(MyBaseClass) {
    /* ... */
}

I mostly get what's going on here (although I find the mixin syntax difficult to wrap my mind around), and I can get sample code to work.

What I haven't been able to do is apply this concept to Polymer.IronScrollTargetBehavior, and create a mixin for it. Since that behavior is already defined as an object, I don't know where to fit it in.

So, how do I implement the proper mixin in this scenario, or if I'm on the wrong path, how to I apply one of the defined Polymer behaviors to my custom element in Polymer 2?

Body:
You can use the Polymer 2 hybrid behaviours as mixins by extending
 Polymer.mixinBehaviors(behaviors, klass) where

- behaviors is the Behavior object or array of behaviors

- klass is the Element class.

i.e.

<dom-module id="element-name">
  <template><!-- ... --></template>
  <script>
    class MyElement extends Polymer.mixinBehaviors([MyBehavior, MyBehavior2], Polymer.Element) {
     static get is() { return 'element-name' }
     /* ... */
    }
    customElements.define('element-name', MyElement);
  </script>
</dom-module>

For more detailed information search the Polymer source code for mixinBehaviors method: polymer/lib/legacy/class.html

worth reading: https://www.polymer-project.org/2.0/docs/upgrade#mixins


问:
How to submit file in form with HtmlUnit
I have a problem with this form

```<code><form action="/incoming/Upload.cfg" enctype="multipart/form-data" method="post" onsubmit="return doSubmit();">
  <table id="autoWidth" border="0" style="width: 100%;">
    <tbody>
      <tr>
        <td class="h1" colspan="4" id="t_title">
          Резервная копия и Восстановление
        </td>
      </tr>
      <tr>
        <td class="blue" colspan="4"/>
      </tr>
      <tr>
        <td class="Item" id="t_backup">
          Сохранить:
        </td>
        <td colspan="3">
          <input type="button" class="buttonBigL" name="Backup" value="Резервная копия" onclick="location.href='config.bin';"/>
        </td>
      </tr>
      <tr>
        <td class="Item" id="t_file">
          Файл:
        </td>
        <td>
          <input class="text" name="filename" type="file" size="20" onkeydown="return false"/>

        </td>
        <td>
          <input name="Restore" type="submit" class="buttonBigL" id="Submit" value="Восстановить"/>
        </td>
        <td width="100%">

        </td>
      </tr>
      <tr>
        <td class="blue" colspan="4"/>
      </tr>
    </tbody>
  </table>
</form>
</code>```

I want to insert "Backup" file and submit form (in browser click to the "Restore button"). Code.

```<code>private String model = "src/test/resources/config.bin";
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setTimeout(20000);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
  webClient.setConfirmHandler(new ConfirmHandler() {
            public boolean handleConfirm(Page page, String message) {
                System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1123");
                return true;
            }
        });
 final HtmlPage frame = ((HtmlPage) page.getFrameByName("frame").getEnclosedPage());

        List<HtmlForm> forms = mainFrame.getForms();

        HtmlForm htmlForm = forms.get(0);

        htmlForm.<HtmlFileInput>getInputByName("filename").setValueAttribute(model);
        htmlForm.<HtmlFileInput>getInputByName("filename").setContentType("multipart/form-data");
        HtmlPage page = (HtmlPage) mainFrame.executeJavaScript("return doSubmit()").getNewPage();
</code>```

When I execute JS i have Error

StrictErrorReporter: error: message=[invalid return]
  sourceName=[injected script] line=[1] lineSource=[return doSubmit()]
  lineOffset=[7]

When I use

```<code>htmlForm.getInputByName("Restore").click();
</code>```

nothing happens

答:
The code is working, the overload goes. But I ran the tests in the spring container, and for some reason I got this error.

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
</code>```

If you run without springs everything works.

```<code>htmlForm.<HtmlFileInput>getInputByName("filename").setValueAttribute(model);
htmlForm.<HtmlFileInput>getInputByName("filename").setContentType("multipart/form-data");
HtmlPage restore = htmlForm.getInputByName("Restore").click();
</code>```

Refresh

The problem is - "Target server failed to respond exception."
I avoid this across

```<code>        webClient.getOptions().setTimeout(20000);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setUseInsecureSSL(true);
        webClient.getOptions().setRedirectEnabled(true);
</code>```

Decided

Body:
I have a problem with this form

<form action="/incoming/Upload.cfg" enctype="multipart/form-data" method="post" onsubmit="return doSubmit();">

          Резервная копия и Восстановление

          Сохранить:

          <input type="button" class="buttonBigL" name="Backup" value="Резервная копия" onclick="location.href='config.bin';"/>

          Файл:

          <input class="text" name="filename" type="file" size="20" onkeydown="return false"/>

          <input name="Restore" type="submit" class="buttonBigL" id="Submit" value="Восстановить"/>

</form>

I want to insert "Backup" file and submit form (in browser click to the "Restore button"). Code.

private String model = "src/test/resources/config.bin";
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setTimeout(20000);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
  webClient.setConfirmHandler(new ConfirmHandler() {
            public boolean handleConfirm(Page page, String message) {
                System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1123");
                return true;
            }
        });
 final HtmlPage frame = ((HtmlPage) page.getFrameByName("frame").getEnclosedPage());

        List<HtmlForm> forms = mainFrame.getForms();

        HtmlForm htmlForm = forms.get(0);

        htmlForm.<HtmlFileInput>getInputByName("filename").setValueAttribute(model);
        htmlForm.<HtmlFileInput>getInputByName("filename").setContentType("multipart/form-data");
        HtmlPage page = (HtmlPage) mainFrame.executeJavaScript("return doSubmit()").getNewPage();

When I execute JS i have Error

StrictErrorReporter: error: message=[invalid return]
  sourceName=[injected script] line=[1] lineSource=[return doSubmit()]
  lineOffset=[7]

When I use

htmlForm.getInputByName("Restore").click();

nothing happens

Body:
The code is working, the overload goes. But I ran the tests in the spring container, and for some reason I got this error.

@RunWith(SpringRunner.class)
@SpringBootTest

If you run without springs everything works.

htmlForm.<HtmlFileInput>getInputByName("filename").setValueAttribute(model);
htmlForm.<HtmlFileInput>getInputByName("filename").setContentType("multipart/form-data");
HtmlPage restore = htmlForm.getInputByName("Restore").click();

Refresh

The problem is - "Target server failed to respond exception."
I avoid this across

        webClient.getOptions().setTimeout(20000);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setUseInsecureSSL(true);
        webClient.getOptions().setRedirectEnabled(true);

Decided


问:
scala: import functions defined inside implicit class
I want to attach static utilities to those classes that extend a trait called Application.

```<code>trait Application {
    def name: String
}

case class TestApp(name: String) extends Application

object ImplicitConf {
  implicit class AppConfig[T <: Application](val app: T) {

    lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)
  }
}
</code>```

Now the following works fine:

```<code>import Application, TestApp
import ImplicitConf._
import AppUtil._

object TestAppConf extends App {

  val app: Application = TestApp("TestAppConf")
  val test = app.getString("hello")
  println(s"The Config value is $test")

}
</code>```

But I am too greedy, how do I covert the call

```<code>val test = app.getString("hello")
</code>```

Into

```<code>val test = getString("hello")
</code>```

答:
You can explicitly convert the app:Application to appWithConfig:AppConfig and import all methods of the appWithConfig:AppConfig</p>

```<code>   val appWithConfig = new AppConfig(app)
   import appWithConfig._
</code>```

Body:
I want to attach static utilities to those classes that extend a trait called Application.

trait Application {
    def name: String
}

case class TestApp(name: String) extends Application

object ImplicitConf {
  implicit class AppConfig[T <: Application](val app: T) {

    lazy val conf = loadConfig

    def loadConfig = {
      ConfigFactory.load(app.name)
    }

    def getString(path: String): String = conf.getString(path)
  }
}

Now the following works fine:

import Application, TestApp
import ImplicitConf._
import AppUtil._

object TestAppConf extends App {

  val app: Application = TestApp("TestAppConf")
  val test = app.getString("hello")
  println(s"The Config value is $test")

}

But I am too greedy, how do I covert the call

val test = app.getString("hello")

Into

val test = getString("hello")

Body:
You can explicitly convert the app:Application to appWithConfig:AppConfig and import all methods of the appWithConfig:AppConfig

   val appWithConfig = new AppConfig(app)
   import appWithConfig._


问:
Validate email address in PHP

Possible Duplicate:

  How to validate an emailaddress in PHP

I was wondering what everyone is doing in regards to validating email addresses and how extensive the validation needs to be.

For example, of those methods, which one is preferred and why?

Extensive check: http://www.linuxjournal.com/article/9585?page=0,3

PHP filter: http://php.net/manual/en/filter.filters.validate.php

Eregi: http://www.totallyphp.co.uk/code/validate_an_email_address_using_regular_expressions.htm

Preg match with DNS check: http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/

My goal is to find a good and solid solution for the average project, so when the time comes to validate an email address, I know exactly what I'm going to use.

Any feedback much appreciated!

-Ryan

答:
I don't think there's a foolproof solution, other than sending an email to that address and requesting a response. Regexps and the like are a pain to implement properly.

Your solution will depend on how valuable that email address is. Are you sending a newsletter ? A sales confirmation ? A critical alert ? Some trivial regexp solution may suffice for the first. Getting some sort of confirmation would be valuable for the second. Repeated confirmations of validity (e.g. monthly checks) may be required for the third.

ContentLicense: CC BY-SA 2.5

Title: Validate email address in PHP


问:
Can we integrate Paypal Payment Gateway with IONIC 1 or 2 app if yes then how...?
I have developed a mobile application for Android & iOS using IONIC framework. Now I want to integrate Payment Gateway with the same app.

I have gone through multiple links, but didn't get a final answer it is it possible to integrate Paypal with IONIC or not.

答:
You can use PayPal-Cordova-Plugin.

The PayPal SDK Cordova/Phonegap Plugin adds support for the PayPal SDK on iOS and Android platforms. It uses the native PayPal Mobile SDK libraries, which you must also download


问:
argument of type const char* is incompatible with parameter of type "LPCWSTR"
I am trying to make  a simple Message Box in C in Visual Studio 2012, but I am getting
the following error messages

```<code>argument of type const char* is incompatible with parameter of type "LPCWSTR"

err LNK2019:unresolved external symbol_main referenced in function_tmainCRTStartup
</code>```

Here is the source code

```<code>#include<Windows.h>

int _stdcall WinMain(HINSTANCE hinstance,HINSTANCE hPrevinstance,LPSTR lpszCmdline,int nCmdShow)
{

    MessageBox(0,"Hello","Title",0);

    return(0);
}
</code>```

Please Help

Thanks and Regards

答:
To compile your code in Visual C++ you need to use Multi-Byte char WinAPI functions instead of Wide char ones.

Set Project -> Properties -> General -> Character Set option to Use Multi-Byte Character Set

I found it here https://stackoverflow.com/a/33001454/5646315

Body:
I am trying to make  a simple Message Box in C in Visual Studio 2012, but I am getting
the following error messages

argument of type const char* is incompatible with parameter of type "LPCWSTR"

err LNK2019:unresolved external symbol_main referenced in function_tmainCRTStartup

Here is the source code

#include<Windows.h>

int _stdcall WinMain(HINSTANCE hinstance,HINSTANCE hPrevinstance,LPSTR lpszCmdline,int nCmdShow)
{

    MessageBox(0,"Hello","Title",0);

    return(0);
}

Please Help

Thanks and Regards


问:
Detect Device to Near or away from Ear Android code
I need to know whether device is near to ear or not by using sensors

I tried using proximity, I want to combine accelerator and gyroscope sensors to exactly find the device is near or far from Ear.

Code for Proximity

@Override
    public void onSensorChanged(SensorEvent event) {

```<code>    float distance = event.values[0];

    if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        if (distance < mProximity.getMaximumRange()) {
            iv.setText("Near");
        } else {
            iv.setText("far");
        }
    }
}
</code>```

答:
This is what I got from Android Documentation, I am sure you can dig more to get some answers to your problem, but this should be enough to get you started. You can also do some research about position sensors in android. The documentation is quite useful </p>

```<code>// Create a constant to convert nanoseconds to seconds.
private static final float NS2S = 1.0f / 1000000000.0f;
private final float[] deltaRotationVector = new float[4]();
private float timestamp;

public void onSensorChanged(SensorEvent event) {
// This timestep's delta rotation to be multiplied by the current rotation
// after computing it from the gyro sample data.
if (timestamp != 0) {
    final float dT = (event.timestamp - timestamp) * NS2S;
    // Axis of the rotation sample, not normalized yet.
    float axisX = event.values[0];
    float axisY = event.values[1];
    float axisZ = event.values[2];

    // Calculate the angular speed of the sample
    float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);

    // Normalize the rotation vector if it's big enough to get the axis
    // (that is, EPSILON should represent your maximum allowable margin of error)
    if (omegaMagnitude > EPSILON) {
      axisX /= omegaMagnitude;
      axisY /= omegaMagnitude;
      axisZ /= omegaMagnitude;
    }

    // Integrate around this axis with the angular speed by the timestep
    // in order to get a delta rotation from this sample over the timestep
    // We will convert this axis-angle representation of the delta rotation
    // into a quaternion before turning it into the rotation matrix.
    float thetaOverTwo = omegaMagnitude * dT / 2.0f;
    float sinThetaOverTwo = sin(thetaOverTwo);
    float cosThetaOverTwo = cos(thetaOverTwo);
    deltaRotationVector[0] = sinThetaOverTwo * axisX;
    deltaRotationVector[1] = sinThetaOverTwo * axisY;
    deltaRotationVector[2] = sinThetaOverTwo * axisZ;
    deltaRotationVector[3] = cosThetaOverTwo;
  }
  timestamp = event.timestamp;
  float[] deltaRotationMatrix = new float[9];
  SensorManager.getRotationMatrixFromVector(deltaRotationMatrix,
                              deltaRotationVector);
// User code should concatenate the delta rotation we computed with the current rotation
// in order to get the updated rotation.
// rotationCurrent = rotationCurrent * deltaRotationMatrix;
   }
}
</code>```

Body:
I need to know whether device is near to ear or not by using sensors

I tried using proximity, I want to combine accelerator and gyroscope sensors to exactly find the device is near or far from Ear.

Code for Proximity

@Override
    public void onSensorChanged(SensorEvent event) {

    float distance = event.values[0];

    if (event.sensor.getType() == Sensor.TYPE_PROXIMITY) {
        if (distance < mProximity.getMaximumRange()) {
            iv.setText("Near");
        } else {
            iv.setText("far");
        }
    }
}

Body:
This is what I got from Android Documentation, I am sure you can dig more to get some answers to your problem, but this should be enough to get you started. You can also do some research about position sensors in android. The documentation is quite useful

// Create a constant to convert nanoseconds to seconds.
private static final float NS2S = 1.0f / 1000000000.0f;
private final float[] deltaRotationVector = new float[4]();
private float timestamp;

public void onSensorChanged(SensorEvent event) {
// This timestep's delta rotation to be multiplied by the current rotation
// after computing it from the gyro sample data.
if (timestamp != 0) {
    final float dT = (event.timestamp - timestamp) * NS2S;
    // Axis of the rotation sample, not normalized yet.
    float axisX = event.values[0];
    float axisY = event.values[1];
    float axisZ = event.values[2];

    // Calculate the angular speed of the sample
    float omegaMagnitude = sqrt(axisX*axisX + axisY*axisY + axisZ*axisZ);

    // Normalize the rotation vector if it's big enough to get the axis
    // (that is, EPSILON should represent your maximum allowable margin of error)
    if (omegaMagnitude > EPSILON) {
      axisX /= omegaMagnitude;
      axisY /= omegaMagnitude;
      axisZ /= omegaMagnitude;
    }

    // Integrate around this axis with the angular speed by the timestep
    // in order to get a delta rotation from this sample over the timestep
    // We will convert this axis-angle representation of the delta rotation
    // into a quaternion before turning it into the rotation matrix.
    float thetaOverTwo = omegaMagnitude * dT / 2.0f;
    float sinThetaOverTwo = sin(thetaOverTwo);
    float cosThetaOverTwo = cos(thetaOverTwo);
    deltaRotationVector[0] = sinThetaOverTwo * axisX;
    deltaRotationVector[1] = sinThetaOverTwo * axisY;
    deltaRotationVector[2] = sinThetaOverTwo * axisZ;
    deltaRotationVector[3] = cosThetaOverTwo;
  }
  timestamp = event.timestamp;
  float[] deltaRotationMatrix = new float[9];
  SensorManager.getRotationMatrixFromVector(deltaRotationMatrix,
                              deltaRotationVector);
// User code should concatenate the delta rotation we computed with the current rotation
// in order to get the updated rotation.
// rotationCurrent = rotationCurrent * deltaRotationMatrix;
   }
}


问:
Why CreateDirectoryEx with long folder name is not working?
This is a sample code i have written to check if i am able to create a folder with name length greater than MAX_PATH -

```<code>wstring s = L"D:\\Test";
wstring s2 = L"\\?\D:\\datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000";

int ret = CreateDirectoryEx(s.c_str(), s2.c_str(), NULL);

int error = GetLastError();
</code>```

It did not work, the returned error is ERROR_PATH_NOT_FOUND. Can anyone please tell me whats the problem in the code?

Note: "D:\Test" folder is an existing folder. I am using Windows 7.

答:
need not confuse Maximum file name length (path component) and Maximum path length - see Limits

the Maximum file name length is <= 255 Unicode characters for all file systems

and Maximum path length
32,760 Unicode characters with each path component no more than 255 characters

initial error was by using L"\\?\" prefix - really it must be L"\\\\?\\" because c/c++ translate "\\" to \ - but this already only language specific error.

if fix it - must be error ERROR_INVALID_NAME (converted from NTSTATUS STATUS_OBJECT_NAME_INVALID ) because path component which you use more than 255 characters

Body:
This is a sample code i have written to check if i am able to create a folder with name length greater than MAX_PATH -

wstring s = L"D:\\Test";
wstring s2 = L"\\?\D:\\datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000";

int ret = CreateDirectoryEx(s.c_str(), s2.c_str(), NULL);

int error = GetLastError();

It did not work, the returned error is ERROR_PATH_NOT_FOUND. Can anyone please tell me whats the problem in the code?

Note: "D:\Test" folder is an existing folder. I am using Windows 7.


答:
You can also do something like this using map

```<code>abc['d'] = abc['a'].map(str) +'::'+ abc['b'].map(str)
print(abc)
</code>```

output:

```<code>   a   b   c      d
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10
</code>```

Title: How to cat two column (float) into a column quick and efficiency in pandas dataframe?

Body:
I want to get a new column by cat two column (float or int) as following shows,

So anyone have a better idea?

I think mine is something too complex

a=pandas.Series([1,3,5,7,9])
b=pandas.Series([2,4,6,8,10])
c=pandas.Series([3,5,6,5,10])

abc=pandas.DataFrame({'a':a, 'b':b, 'c':c})

abc
   a   b   c
0  1   2   3
1  3   4   5
2  5   6   6
3  7   8   5
4  9  10  10

abc['new']=pandas.Series(map(str,abc.iloc[:,0])).str.cat(pandas.Series(map(str,abc.iloc[:,1])), sep='::')

abc
   a   b   c    new
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10

Body:
You can also do something like this using map

abc['d'] = abc['a'].map(str) +'::'+ abc['b'].map(str)
print(abc)

output:

   a   b   c      d
0  1   2   3   1::2
1  3   4   5   3::4
2  5   6   6   5::6
3  7   8   5   7::8
4  9  10  10  9::10


问:
Should multiple array/hash lookups be stored in a variable
I've been using Reek lately to refactor my code and one of the smells, DuplicateMethodCall, is being called on array and hash lookups, such as array[1] or hash[:key] when called multiple times.

So I was wondering if multiple array or hash lookups are so expensive, that we should be storing them in a variable rather than calling them directly, which is what everyone does from my experience.

I would not hesitate to store multiple object method calls (especially if it's a DB call) in a variable, but doing that for array and hash lookups feel like an overkill.

For example, I'll get a warning for this piece of code:

```<code>  def sort_params
    return [] if params[:reference_letter_section].nil?

    params[:reference_letter_section].map.with_index(1) do |id, index|
      { id: id, position: index }
    end
  end
</code>```

but I feel like storing params[:reference_letter_section] in its own variable is too much

答:
The duplicate hash lookup represents coupling between those two lines of code. This can increase the time taken to understand the code, and can be a source of friction when changing it. Of course, within a small method like this the cost is relatively low; but if the two lines of code were further apart -- in different classes, for example -- the effects of the coupling would be much more costly.

Here's a version of your method that doesn't have the duplication:

```<code>def sort_params
  reference_letters = params[:reference_letter_section] || []
  reference_letters.map.with_index(1) do |id, index|
    { id: id, position: index }
  end
end
</code>```

Body:
I've been using Reek lately to refactor my code and one of the smells, DuplicateMethodCall, is being called on array and hash lookups, such as array[1] or hash[:key] when called multiple times.

So I was wondering if multiple array or hash lookups are so expensive, that we should be storing them in a variable rather than calling them directly, which is what everyone does from my experience.

I would not hesitate to store multiple object method calls (especially if it's a DB call) in a variable, but doing that for array and hash lookups feel like an overkill.

For example, I'll get a warning for this piece of code:

  def sort_params
    return [] if params[:reference_letter_section].nil?

    params[:reference_letter_section].map.with_index(1) do |id, index|
      { id: id, position: index }
    end
  end

but I feel like storing params[:reference_letter_section] in its own variable is too much

Body:
The duplicate hash lookup represents coupling between those two lines of code. This can increase the time taken to understand the code, and can be a source of friction when changing it. Of course, within a small method like this the cost is relatively low; but if the two lines of code were further apart -- in different classes, for example -- the effects of the coupling would be much more costly.

Here's a version of your method that doesn't have the duplication:

def sort_params
  reference_letters = params[:reference_letter_section] || []
  reference_letters.map.with_index(1) do |id, index|
    { id: id, position: index }
  end
end


问:
What are the best practices to encrypt passwords stored in MySql using PhP?
I am seeking advice on how to securely store passwords in MySQL using PHP.

Overlooking the limitations of PHP itself, I want to know more about salting, hashing, and encrypting these bad boys.

Obviously people will continue to use weak passwords unless forced to do otherwise, but it's how I am storing them that is important to me. My user's passwords are far more important to me than the database itself, and as such I want to keep them in such a way that it will be painstaking and monotonous for any script kiddie trying reverse. Obviously with due diligence just about anything can be defeated, but I wouldn't mind making this particularly bothersome.

There are two scenarios we are looking at.

The kiddie has a complete copy of the database.

The kiddie has a complete copy of the PHP used to craft the password, and the database.

Any and all advice on this topic is graciously appreciated.

答:
Assuming you're using username and password as authentication tokens you can safely store the following to ensure the data can't be compromised.

Username (in plaintext)

Salt (random string)

Salted Hash (sha1(username + salt + password))

Using the scheme, an attacker cannot use rainbow tables against you and the passwords are not recoverable by any (reasonable) means. (That is, as long as your attacker isn't the government)

Even though the attacker has the salt and hash pairs it's not possible to use rainbow tables because all the possible hashes will need to be computed anyway, using the salt that they've been given, so it's a brand new brute force attack for each user.

Even with the source code and attacker won't be able to get hold of the passwords because the strength/security is in the hashing algorithm, not your code.

Combine this with using bcrypt as per Donut's answer and you're really quite safe. That is:

Username (in plaintext)

Salt (random string)

Salted Hash (bcrypt(username + salt + password))


问:
Override Yet Another Related Post Plugin Settings (YARPP)
I set up the plugin to show 10 related posts in the options panel but I don’t want to show 10 posts everywhere; just in some places.

Is there a way to tweak <?php related_posts(); ?> to show a different number of posts aside from what I set in the options panel?

答:
Try adding limit option in the $args array of the related_posts() function.

Update 1:

You also need to figure out how will the number of limit be determined. You could have a default number that is then overriden if some custom field exists with a value, something like:

```<code>  $my_limit=5;
  $get_limit=(int)get_post_meta(get_the_ID(),'RelatedPostsLimit', true);
  if ($get_limit>0)
    $my_limit=$get_limit;
  $my_args = array('limit' => $my_limit);
  related_posts($my_args);
</code>```

So in above code, the default limit is 5. If you want the post to have a different value, add a Custom Field RelatedPostsLimit with that value.

Update 2:

You don't insert the code inside related_posts(), you remove the original related_posts() and replace it with the above code. :)

Body:
Try adding limit option in the $args array of the related_posts() function.

Update 1:

You also need to figure out how will the number of limit be determined. You could have a default number that is then overriden if some custom field exists with a value, something like:

  $my_limit=5;
  $get_limit=(int)get_post_meta(get_the_ID(),'RelatedPostsLimit', true);
  if ($get_limit>0)
    $my_limit=$get_limit;
  $my_args = array('limit' => $my_limit);
  related_posts($my_args);

So in above code, the default limit is 5. If you want the post to have a different value, add a Custom Field RelatedPostsLimit with that value.

Update 2:

You don't insert the code inside related_posts(), you remove the original related_posts() and replace it with the above code. :)


问:
Replace content in first set of quotes found in string c#
I am working on a project that involves having to manipulate a bat file based on certain user produced parameters. The bat files themselves are created manually, with a static format. A basic example of a bat file would be:

```<code>cd \some\predefined\bat
start run_some_script "user_generated_argument" [other pre-defined arguments]
</code>```

The "user_generated_argument" bit of the bat file is manipulated in C# by the following code:

```<code>string bat_text = File.ReadAllText(bat_path);
Regex regex = new Regex("(.*?)\".*\"(.*)");
string new_argument = "A new argument";
string new_bat = regex.Replace(bat_text , "$1\"" + new_argument + "\"$2", 1);
</code>```

And that would produce the following:

```<code>cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]
</code>```

which is the expected output.

However, the problem lies when one of the other pre-defined arguments after the first quoted argument is also in quotes when that is the case, it seems that the second quoted argument disappears. For example, if the bat file looks like:

```<code>cd \some\predefined\bat
start run_some_script "user_generated_argument" "a_predefined_quoted_argument" [other pre-defined arguments]
</code>```

Running the same C# code from above would produce the following:

```<code>cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]
</code>```

The "a_predefined_quoted_argument" would no longer be in the string.

I may be doing this completely wrong. How would I make the predefined quoted argument not disappear?

答:
the problem is that your expression
\".*\"
is eager or greedy, taking everything between the first quote and the last quote it finds. To make it lazy or reluctant, put a ? after the *
like so (I used VB, which escapes double quotes by double double quotes)

```<code>Dim batfile As String = "cd \some\predefined\bat" & vbCrLf & "start run_some_script ""user_generated_argument"" ""a_predefined_quoted_argument"" [other pre-defined arguments]"
Dim regex As Regex = New Regex("(.*?)"".*?""(.*)")
Dim new_argument As String = "A new argument"
Dim new_bat As String = regex.Replace(batfile, "$1""" + new_argument + """ $2", 1)
</code>```

It will now take everything between the first quote, and the next quote.

Body:
I am working on a project that involves having to manipulate a bat file based on certain user produced parameters. The bat files themselves are created manually, with a static format. A basic example of a bat file would be:

cd \some\predefined\bat
start run_some_script "user_generated_argument" [other pre-defined arguments]

The "user_generated_argument" bit of the bat file is manipulated in C# by the following code:

string bat_text = File.ReadAllText(bat_path);
Regex regex = new Regex("(.*?)\".*\"(.*)");
string new_argument = "A new argument";
string new_bat = regex.Replace(bat_text , "$1\"" + new_argument + "\"$2", 1);

And that would produce the following:

cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]

which is the expected output.

However, the problem lies when one of the other pre-defined arguments after the first quoted argument is also in quotes when that is the case, it seems that the second quoted argument disappears. For example, if the bat file looks like:

cd \some\predefined\bat
start run_some_script "user_generated_argument" "a_predefined_quoted_argument" [other pre-defined arguments]

Running the same C# code from above would produce the following:

cd \some\predefined\bat
start run_some_script "A new argument" [other pre-defined arguments]

The "a_predefined_quoted_argument" would no longer be in the string.

I may be doing this completely wrong. How would I make the predefined quoted argument not disappear?

Body:
the problem is that your expression
\".*\"
is eager or greedy, taking everything between the first quote and the last quote it finds. To make it lazy or reluctant, put a ? after the *
like so (I used VB, which escapes double quotes by double double quotes)

Dim batfile As String = "cd \some\predefined\bat" & vbCrLf & "start run_some_script ""user_generated_argument"" ""a_predefined_quoted_argument"" [other pre-defined arguments]"
Dim regex As Regex = New Regex("(.*?)"".*?""(.*)")
Dim new_argument As String = "A new argument"
Dim new_bat As String = regex.Replace(batfile, "$1""" + new_argument + """ $2", 1)

It will now take everything between the first quote, and the next quote.


问:
ReactJS: "Uncaught SyntaxError: Unexpected token <"
I am trying to get started building a site in ReactJS. However, when I tried to put my JS in a separate file, I started getting this error: "Uncaught SyntaxError: Unexpected token <".

I tried adding /** @jsx React.DOM */ to the top of the JS file, but it didn't fix anything. Below are the HTML and JS files. Any ideas as to what is going wrong?

HTML

```<code><html>
  <head>
    <title>Page</title>
    <script src="http://fb.me/react-0.12.2.js"></script>
    <script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"> </script>
    <script src="./lander.js"> </script>
  </head>
  <body>
    <div id="content"></div>
    <script type="text/jsx">
        React.render(
            <Lander />,
            document.getElementById('content')
        );
    </script>
  </body>
</html>
</code>```

JS

```<code>/**
 * @jsx React.DOM
 */
var Lander = React.createClass({
    render: function () {
        var info = "Lorem ipsum dolor sit amet... ";
        return(
            <div>
                <div className="info">{info}</div>
            </div>
        );
    }
});
</code>```

EDIT: I realized that I need to add type="text/jsx" to the script tag which includes my lander code. However, after adding this and reloading I get this warning

"You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx"

followed by this error:

"XMLHttpRequest cannot load file:///Users/.../lander.js. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource."

it seems like there is something else that I need to do in order to get in browser jsx transform working, but I'm not sure what it is.

EDIT: OOOOH do I need to host it using MAMP or something?

答:
If you are getting an error like this :

SyntaxError: embedded: Unexpected token (107:9) 105

It could be you are missing a curly bracket

Body:
I am trying to get started building a site in ReactJS. However, when I tried to put my JS in a separate file, I started getting this error: "Uncaught SyntaxError: Unexpected token <".

I tried adding /** @jsx React.DOM */ to the top of the JS file, but it didn't fix anything. Below are the HTML and JS files. Any ideas as to what is going wrong?

HTML

    <title>Page</title>

JS

/**
 * @jsx React.DOM
 */
var Lander = React.createClass({
    render: function () {
        var info = "Lorem ipsum dolor sit amet... ";
        return(

{info}

        );
    }
});

EDIT: I realized that I need to add type="text/jsx" to the script tag which includes my lander code. However, after adding this and reloading I get this warning

"You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx"

followed by this error:

"XMLHttpRequest cannot load file:///Users/.../lander.js. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource."

it seems like there is something else that I need to do in order to get in browser jsx transform working, but I'm not sure what it is.

EDIT: OOOOH do I need to host it using MAMP or something?


问:
AuthorizeAttribute adal signout MVC
I have created a custom Authorize attribute based on AAD groups in MVC. If I return false in the attribute the applications goes into an infinite loop on the login page. How do you signoff the user from an custom authorize attribute when using adal in an MVC application?</p>

答:
```<code>I think I found a solution I am testing as we speak:

protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);

        var allowedGroups = GetAllowedGroups();

        var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
        string callbackUrl = urlHelper.Action("SignOutCallback", "Account", routeValues: null, protocol: httpContext.Request.Url.Scheme);

        httpContext.GetOwinContext().Authentication.SignOut(
            new AuthenticationProperties { RedirectUri = callbackUrl },
            OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);

        return authorized;
    }
</code>```

Title: AuthorizeAttribute adal signout MVC


问:
React native - Change screen after x seconds
I have a problem that I haven't been able to solve.

In my React native application, I would like to display a welcome screen at the start. Then 5 seconds later just close it, and display another one. Both are 2 entirely different screens, no need to keep the "come back" arrow.

I have been searching for hours, but I haven't found out how to do it.

Here is my code for now:

```<code>import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
    componentDidMount(){
        // Start counting when the page is loaded
        this.timeoutHandle = setTimeout(()=>{
            // Add your logic for the transition
            this.props.navigation.navigate('Defis') // what to push here?
        }, 5000);
    }

    componentWillUnmount(){
        clearTimeout(this.timeoutHandle);
    }

    render() {
        return (
            <Quote/>
        );
    }
}
</code>```

Does anybody know how to do it?

I'm not able to use Navigator.push, moreover Navigator seems deprecated.

答:
I was doing almost the same thing with "react-native-router-flux".
Simply render a first screen, in your case the "Quote", and then set in componentDidMount:

```<code>  setTimeout(() => {
     Actions.yourNextSceneName()
  }, milliseconds)
</code>```

Hope this helps.

Body:
I have a problem that I haven't been able to solve.

In my React native application, I would like to display a welcome screen at the start. Then 5 seconds later just close it, and display another one. Both are 2 entirely different screens, no need to keep the "come back" arrow.

I have been searching for hours, but I haven't found out how to do it.

Here is my code for now:

import Defis from './components/defis'
import Quote from './components/quote'

export default class Betty extends Component {
    componentDidMount(){
        // Start counting when the page is loaded
        this.timeoutHandle = setTimeout(()=>{
            // Add your logic for the transition
            this.props.navigation.navigate('Defis') // what to push here?
        }, 5000);
    }

    componentWillUnmount(){
        clearTimeout(this.timeoutHandle);
    }

    render() {
        return (
            <Quote/>
        );
    }
}

Does anybody know how to do it?

I'm not able to use Navigator.push, moreover Navigator seems deprecated.

Body:
I was doing almost the same thing with "react-native-router-flux".
Simply render a first screen, in your case the "Quote", and then set in componentDidMount:

  setTimeout(() => {
     Actions.yourNextSceneName()
  }, milliseconds)

Hope this helps.


问:
How do I take multiple arguments in a closure and print them?
I have a call to env::vars_os and would like to print all of them in a functional manner:

```<code>env::vars_os()
    .map(|(k, v)| println!("k : {:?}, v : {:?} \n", k, v));
</code>```

This prints nothing, but the article Destructuring and Pattern Matching indicates this should be possible.

答:
Looking at the documentation for vars_os(), we see that it is an iterator over tuples, which have the syntax (a, b). So, changing your code to

```<code>env::vars_os()
    .map(|(k, v)| println!("k : {:?}, v : {:?} \n", k, v));
</code>```

should do the trick.

The syntax you are using would destructure into a struct, only you left out the struct's name, which would precede the curly braces.

Iterators in Rust are lazily evaluated, which means none of the code in the map is executed until the iterator is consumed. You can do this by calling collect(). However, the idiomatic way to do it would be to put code that has side-effects (such as printing) in a for loop instead of a map:

```<code>for (k, v) in env::vars_os() {
    println!("k : {:?}, v : {:?} \n", k, v);
}
</code>```

Body:
I have a call to env::vars_os and would like to print all of them in a functional manner:

env::vars_os()
    .map(|(k, v)| println!("k : {:?}, v : {:?} \n", k, v));

This prints nothing, but the article Destructuring and Pattern Matching indicates this should be possible.

Body:
Looking at the documentation for vars_os(), we see that it is an iterator over tuples, which have the syntax (a, b). So, changing your code to

env::vars_os()
    .map(|(k, v)| println!("k : {:?}, v : {:?} \n", k, v));

should do the trick.

The syntax you are using would destructure into a struct, only you left out the struct's name, which would precede the curly braces.

Iterators in Rust are lazily evaluated, which means none of the code in the map is executed until the iterator is consumed. You can do this by calling collect(). However, the idiomatic way to do it would be to put code that has side-effects (such as printing) in a for loop instead of a map:

for (k, v) in env::vars_os() {
    println!("k : {:?}, v : {:?} \n", k, v);
}


答:
Here's a great blog entry about this : http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx

Personnally, I usually use a simple RegExp that will validate most of the addresses you find on the Internet, so the solution in the third link is what I would use.
But the best solution is, I think, to send a e-mail to the specified address (using a simple RegExp before to warn the user) with a link to validate it. So you're sure it's a valid and allocated address.

Title: Validate email address in PHP

Body:
Possible Duplicate:

  How to validate an emailaddress in PHP

I was wondering what everyone is doing in regards to validating email addresses and how extensive the validation needs to be.

For example, of those methods, which one is preferred and why?

Extensive check: http://www.linuxjournal.com/article/9585?page=0,3

PHP filter: http://php.net/manual/en/filter.filters.validate.php

Eregi: http://www.totallyphp.co.uk/code/validate_an_email_address_using_regular_expressions.htm

Preg match with DNS check: http://www.soaptray.com/blog/2008/04/validate-email-addresses-using-php/

My goal is to find a good and solid solution for the average project, so when the time comes to validate an email address, I know exactly what I'm going to use.

Any feedback much appreciated!

-Ryan


问:
Method is defined twice
Why scala REPL does not allow to have several function with same names inside another function?

```<code>  def wrapper(): Unit = {
    def a: Unit = ???
    def a(i: Int): Unit = ???
  }
</code>```

error: method a is defined twice

conflicting symbols both originated in file '< console>'

答:
Looks like you want to use overloading (OOP feature) inside a method what is not proper OOP primitive for that and it is not looks resonable from OOP point of view (and I agree with compiler). To align this with OOP features, just wrap it in object: </p>

```<code>def wrapper(): Unit = {
  object wr {
    def a: Unit = ???
    def a(i: Int): Unit = ???
  }

  wr.a(10)
  wr.a
}
</code>```

Title: Method is defined twice

Body:
Why scala REPL does not allow to have several function with same names inside another function?

  def wrapper(): Unit = {
    def a: Unit = ???
    def a(i: Int): Unit = ???
  }

error: method a is defined twice

conflicting symbols both originated in file '< console>'

Body:
Looks like you want to use overloading (OOP feature) inside a method what is not proper OOP primitive for that and it is not looks resonable from OOP point of view (and I agree with compiler). To align this with OOP features, just wrap it in object:

def wrapper(): Unit = {
  object wr {
    def a: Unit = ???
    def a(i: Int): Unit = ???
  }

  wr.a(10)
  wr.a
}


问:
Creation of Paypal encrypted button returns the error 11945 invalid country and locale combination
I am implementing the creation of encrypted Paypal buttons using their Button Manager API. Despite all my efforts I am facing the error 11945 The button country and language code combination specified is invalid..

First I tried to implement the creation of my own button but while tracing this error, I ended up with their tutorial using curl, which fails for me too with the same error. (Note: I had to change the credentials to mine).

To be specific, this code from their tutorial fails with the error 11945:

```<code>curl https://api-3t.sandbox.paypal.com/nvp \
  -s \
  --insecure \
  -d USER=<my-user-name> \
  -d PWD=<my-password> \
  -d SIGNATURE=<my-signature> \
  -d VERSION=51.0 \
  -d METHOD=BMCreateButton \
  -d BUTTONCODE=ENCRYPTED \
  -d BUTTONTYPE=CART \
  -d BUTTONSUBTYPE=PRODUCTS \
  -d BUTTONCOUNTRY=US \
  -d L_BUTTONVAR1=item_name%3Dshoehorn \
  -d L_BUTTONVAR2=amount%3D1464.46 \
  -d L_BUTTONVAR3=tax=%3D21 \
  -d L_BUTTONVAR4=item_number%3D123456
</code>```

I tried to figure out why is that but I haven't found any relevant sources.

Can anyone explain this issue? The country code is set to US, which should be fine.

All help will be appreciated.

Note: I am using the sandbox right now.

Note: Defining locale through lc attribute does not help. I tried en as well as en_US values.

答:
After a discussion with the Paypal support, there is the conclusion.

Short version: It's a bug.

Long version (by moderator MTS_Ciaran):

Thanks, so this looks like a bug on the sandbox from what I can see.
  The issue is that the account is CZ and for some reason we're not
  allowing the button creation because of that. It doesnt look to be the
  same on the live environment so I would suggest using a US account for
  testing and once live the CZ account shouldn't be an issue.

I'll
  work internally to get the sandbox corrected for this.

Body:
I am implementing the creation of encrypted Paypal buttons using their Button Manager API. Despite all my efforts I am facing the error 11945 The button country and language code combination specified is invalid..

First I tried to implement the creation of my own button but while tracing this error, I ended up with their tutorial using curl, which fails for me too with the same error. (Note: I had to change the credentials to mine).

To be specific, this code from their tutorial fails with the error 11945:

curl https://api-3t.sandbox.paypal.com/nvp \
  -s \
  --insecure \
  -d USER=<my-user-name> \
  -d PWD=<my-password> \
  -d SIGNATURE=<my-signature> \
  -d VERSION=51.0 \
  -d METHOD=BMCreateButton \
  -d BUTTONCODE=ENCRYPTED \
  -d BUTTONTYPE=CART \
  -d BUTTONSUBTYPE=PRODUCTS \
  -d BUTTONCOUNTRY=US \
  -d L_BUTTONVAR1=item_name%3Dshoehorn \
  -d L_BUTTONVAR2=amount%3D1464.46 \
  -d L_BUTTONVAR3=tax=%3D21 \
  -d L_BUTTONVAR4=item_number%3D123456

I tried to figure out why is that but I haven't found any relevant sources.

Can anyone explain this issue? The country code is set to US, which should be fine.

All help will be appreciated.

Note: I am using the sandbox right now.

Note: Defining locale through lc attribute does not help. I tried en as well as en_US values.


问:
understanding IIS Proxy response header rewrite Rule
we have a IIS reverse proxy response rule, which modifies Location HTTP header.. I am trying to decode the logic and planning to write same logic in xslt, can someone explain below logic. how match pattern works and action rewrite and value works and what is R:1, R:2 , R:3 here ?</p>

```<code><rule name="Change Location Header" enabled="true">
                <match serverVariable="RESPONSE_LOCATION" pattern="^http(s)?://([^/]+)/(.*)" />
                <conditions logicalGrouping="MatchAny" trackAllCaptures="true">
                    <add input="{RESPONSE_STATUS}" pattern="^301" />
                    <add input="{RESPONSE_STATUS}" pattern="^302" />
                </conditions>
                <action type="Rewrite" value="http{R:1}://{R:2}/{R:3}" />
            </rule>
</code>```

答:
Your rule is changing the domain in the HTTP location header for redirect responses

How is working match condition and what is R:1,R:2,R:3

RESPONSE_LOCATION variable has full lik url. For example:

```<code>https://demo.cloudimg.io/s/width/300/sample.li/boat.jpg
</code>```

In this case, after match operation with regexp: ^http(s)?://([^/]+)/(.*)
Mathces will be like that:

```<code>{R:0}   https://demo.cloudimg.io/s/width/300/sample.li/boat.jpg
{R:1}   s
{R:2}   demo.cloudimg.io
{R:3}   s/width/300/sample.li/boat.jpg
</code>```

Body:
we have a IIS reverse proxy response rule, which modifies Location HTTP header.. I am trying to decode the logic and planning to write same logic in xslt, can someone explain below logic. how match pattern works and action rewrite and value works and what is R:1, R:2 , R:3 here ?

<rule name="Change Location Header" enabled="true">
                <match serverVariable="RESPONSE_LOCATION" pattern="^http(s)?://([^/]+)/(.*)" />
                <conditions logicalGrouping="MatchAny" trackAllCaptures="true">
                    <add input="{RESPONSE_STATUS}" pattern="^301" />
                    <add input="{RESPONSE_STATUS}" pattern="^302" />
                </conditions>
                <action type="Rewrite" value="http{R:1}://{R:2}/{R:3}" />
            </rule>

Body:
Your rule is changing the domain in the HTTP location header for redirect responses

How is working match condition and what is R:1,R:2,R:3

RESPONSE_LOCATION variable has full lik url. For example:

https://demo.cloudimg.io/s/width/300/sample.li/boat.jpg

In this case, after match operation with regexp: ^http(s)?://([^/]+)/(.*)
Mathces will be like that:

{R:0}   https://demo.cloudimg.io/s/width/300/sample.li/boat.jpg
{R:1}   s
{R:2}   demo.cloudimg.io
{R:3}   s/width/300/sample.li/boat.jpg


问:
How to add a toolbar at the bottom?
I'm trying to have my toolbar at the bottom. I already tried some tips but the toolbar rests at the top.

So: What do I have to change so my toolbar appears at the bottom?

If you need more code - there isn't much more - or other informations, just say so.

My XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

   <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</LinearLayout>
</code>```

And the .java:

```<code>package com.example.testingmapingmarker23;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;

import static com.example.testingmapingmarker23.R.id.map;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        final Toolbar customToolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    }

}
</code>```

Styles.xml:

```<code><resources>

    <!-- Base application theme. -->
    <!--<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!– Customize your theme here. –>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>-->

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar" />

</resources>
</code>```

Android Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.testingmapingmarker23">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <permission android:name="android.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value=" API-Key (I removed mine)" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答:
First of all you need to Add navigationToolBar instead of ToolBar
try this Link

See This

```<code><android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimary"
    app:itemIconTint="@color/nav_item_state_list"
    app:itemTextColor="@color/nav_item_state_list"
    app:menu="@menu/bottom_navigation_items"/>
</code>```

Title: How to add a toolbar at the bottom?

Body:
I'm trying to have my toolbar at the bottom. I already tried some tips but the toolbar rests at the top.

So: What do I have to change so my toolbar appears at the bottom?

If you need more code - there isn't much more - or other informations, just say so.

My XML file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.testingmapingmarker23.MapsActivity"
        />

   <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        android:layout_alignParentBottom="true"
        android:layout_gravity="bottom"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

</LinearLayout>

And the .java:

package com.example.testingmapingmarker23;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;

import static com.example.testingmapingmarker23.R.id.map;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);

        final Toolbar customToolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
        mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

    }

}

Styles.xml:

<resources>

Body:
First of all you need to Add navigationToolBar instead of ToolBar
try this Link

See This

<android.support.design.widget.BottomNavigationView
    android:id="@+id/navigation"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:background="@color/colorPrimary"
    app:itemIconTint="@color/nav_item_state_list"
    app:itemTextColor="@color/nav_item_state_list"
    app:menu="@menu/bottom_navigation_items"/>


答:
Because the syntax is simply wrong. You have to escape the backslash. So the prefix should be L"\\\\?\\".

```<code>wstring s2 = L"\\\\?\\D:\\dataff...";
</code>```

Title: Why CreateDirectoryEx with long folder name is not working?

Body:
This is a sample code i have written to check if i am able to create a folder with name length greater than MAX_PATH -

wstring s = L"D:\\Test";
wstring s2 = L"\\?\D:\\datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000datafffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffr700000000000000";

int ret = CreateDirectoryEx(s.c_str(), s2.c_str(), NULL);

int error = GetLastError();

It did not work, the returned error is ERROR_PATH_NOT_FOUND. Can anyone please tell me whats the problem in the code?

Note: "D:\Test" folder is an existing folder. I am using Windows 7.

Body:
Because the syntax is simply wrong. You have to escape the backslash. So the prefix should be L"\\\\?\\".

wstring s2 = L"\\\\?\\D:\\dataff...";


问:
Method local inner class hides method fields
Given the following class definition

```<code>public class MethodLocalAccess {

    int m = 10;

    String show(){
        final int m = 20;
        final int n = 30;
        class MyClass{
            int m = 40;
            String someOtherMethod(){
                return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
            }
        }

        MyClass object = new MyClass();
        return object.someOtherMethod();
    }

    public static void main(String[] args) {
        System.out.println(new MethodLocalAccess().show());
    }

}
</code>```

Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.

Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.

答:
You can't, because it's shadowed.

You can't even with reflection, because reflection works on the type level, not on the byte-code.

You can, with additional tools, if you play with the generated byte-code.

Body:
Given the following class definition

public class MethodLocalAccess {

    int m = 10;

    String show(){
        final int m = 20;
        final int n = 30;
        class MyClass{
            int m = 40;
            String someOtherMethod(){
                return "" + m + n + this.m + MyClass.this.m + MethodLocalAccess.this.m;
            }
        }

        MyClass object = new MyClass();
        return object.someOtherMethod();
    }

    public static void main(String[] args) {
        System.out.println(new MethodLocalAccess().show());
    }

}

Produces output 4030404010, which is fairly established why. I want to know, if the local-variable final int m = 20; can be accessed inside the inner-class.

Other way around, fields declared in method-local inner-class having same name as that of method-local-variable, will permanently hide the latter.


问:
Add Title For xamarin.forms Master Page Contain TabbedPage as Details page
I using Master Detail page

The Detail page is an tabbed page

```<code><TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" ...... >
    <views:InboxPage    Title="" Icon="tabb_inbox.png" />
    <views:AgendaPage    Title="" Icon="tabb_agenda.png"/>
    <views:AttendancePage    Title="" Icon="tabb_attendance.png"/>
    <page:CalendarPage Title="" Icon="tabb_calendar.png" ></page:CalendarPage>
    <views:MarksPage    Title="" Icon="tabb_marks.png"/>
    <!--<views:CalendarPage Title="" Icon="tabb_calendar.png" />-->

</TabbedPage>
</code>```

The Menu(masterpage) is a Content page :

```<code>     public partial class MasterPageMenu : ContentPage
        {
            public MasterPageMenu()
            {
                InitializeComponent();
                InitializeDataAsync();
}
}
</code>```

in the master Page render using the following

```<code> public partial class MasterPage : MasterDetailPage
    {
  public MasterPage()
        {
Detail = new NavigationPage(bottomBarPage);

        Master = new MasterPageMenu()
        {
            Title = "The Title ",

            Icon = (Device.OS == TargetPlatform.iOS) ? "icon.png" : null
        };
}
}
</code>```

Is There Any way to display page title beside the menu Icon

the result for above code like this

答:
I usually pass the title in program code as follow ( when navigating to the page ).

```<code>new tabbedPafe(){ Title = 'Put title here'};
</code>```

But I think you can also do it in your XAML code if you prefer that (of your tabbed page, give it the Title attribute).

```<code><TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" ...... Title="Title here">

 <views:InboxPage    Title="" Icon="tabb_inbox.png" />
    <views:AgendaPage    Title="" Icon="tabb_agenda.png"/>
    <views:AttendancePage    Title="" Icon="tabb_attendance.png"/>
    <page:CalendarPage Title="" Icon="tabb_calendar.png" ></page:CalendarPage>
    <views:MarksPage    Title="" Icon="tabb_marks.png"/>
    <!--<views:CalendarPage Title="" Icon="tabb_calendar.png" />-->

</TabbedPage>
</code>```

Body:
I using Master Detail page

The Detail page is an tabbed page

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" ...... >
    <views:InboxPage    Title="" Icon="tabb_inbox.png" />
    <views:AgendaPage    Title="" Icon="tabb_agenda.png"/>
    <views:AttendancePage    Title="" Icon="tabb_attendance.png"/>
    <page:CalendarPage Title="" Icon="tabb_calendar.png" ></page:CalendarPage>
    <views:MarksPage    Title="" Icon="tabb_marks.png"/>

</TabbedPage>

The Menu(masterpage) is a Content page :

     public partial class MasterPageMenu : ContentPage
        {
            public MasterPageMenu()
            {
                InitializeComponent();
                InitializeDataAsync();
}
}

in the master Page render using the following

 public partial class MasterPage : MasterDetailPage
    {
  public MasterPage()
        {
Detail = new NavigationPage(bottomBarPage);

        Master = new MasterPageMenu()
        {
            Title = "The Title ",

            Icon = (Device.OS == TargetPlatform.iOS) ? "icon.png" : null
        };
}
}

Is There Any way to display page title beside the menu Icon

the result for above code like this

Body:
I usually pass the title in program code as follow ( when navigating to the page ).

new tabbedPafe(){ Title = 'Put title here'};

But I think you can also do it in your XAML code if you prefer that (of your tabbed page, give it the Title attribute).

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms" ...... Title="Title here">

 <views:InboxPage    Title="" Icon="tabb_inbox.png" />
    <views:AgendaPage    Title="" Icon="tabb_agenda.png"/>
    <views:AttendancePage    Title="" Icon="tabb_attendance.png"/>
    <page:CalendarPage Title="" Icon="tabb_calendar.png" ></page:CalendarPage>
    <views:MarksPage    Title="" Icon="tabb_marks.png"/>
    <!--<views:CalendarPage Title="" Icon="tabb_calendar.png" />-->

</TabbedPage>


问:
how to use a string assigned to a variable as an object key
Using a variable for a key in a JavaScript object literal

I am started learning javascript and have seen the answer(below) for the above question but

```<code>var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top);
</code>```

what if i have

```<code>var date = new Date().getDate();
var value= String(date);
obj ={[value]:100};
console.log(obj.value);
</code>```

I did not find the answer for the above code .As the variable value changes everyday i want to use value while using console.log(obj.value) not the actual date.
Can someone tell me how to do it .

答:
You can read the value property with "[]" instead of ".", like this:

var date = new Date().getDate();
var value= String(date);
obj ={[value]:100};
console.log(obj[value]);```

Body:
Using a variable for a key in a JavaScript object literal

I am started learning javascript and have seen the answer(below) for the above question but

var thetop = "top",
obj = { [thetop]: 10 };
console.log(obj.top);

what if i have

var date = new Date().getDate();
var value= String(date);
obj ={[value]:100};
console.log(obj.value);

I did not find the answer for the above code .As the variable value changes everyday i want to use value while using console.log(obj.value) not the actual date.
Can someone tell me how to do it .


问:
Can I use Write-SqlTableData
Is it possible to use this cmdlet: Write-SqlTableData in sql server 2012 and below?
Its a new thing added to sql 2016. I have some powershell output that needs to be stored into MS SQL 2012 database.

Let me know

答: Initially I thought it only works in SQL 2016 but I realized that you either need to import the module: SqlServer or Install-Module SqlServer. Either 2 ways, it should work. Thanks for your help guys. Powershell is taking over the world.</p>

Title: Can I use Write-SqlTableData


问:
Python - Strip line at either one point or another in the same string
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

```<code>        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())
</code>```

example on how the file with the strings looks

```<code>SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]
</code>```

Basically I want to extract the numbers

答:
try this. see the out put here</p>

```<code>if line.startswith('->'):
    start = '-> '
    end = ':\ '
    end1 = ' [Channel]'
    x=line.strip(start)
    x=x.strip(end)
    x=x.strip(end1)
    data.append(x)
</code>```

Body:
I want to save a phrase that´s between a start and a end point.

The start is start = '->'. The problem is that it can have two different end points (depending on which string I get) end = ':\' or end1 ='[Channel].

So I'm trying to split the string at both ends ':\' and '[channel]' in the same loop. I tried using or, split, strip, striplines and others, but nothing does the trick

How  my code looks now (not working)

        if line.startswith('->'):
                start = '-> '  # take string from
                end = ':\ ' #either end at this character
                end1 = '[Channel]' # or this character
                data.append(line[line.find(start) + 3:line.find(end or end1)].strip())

example on how the file with the strings looks

SEND TEST:
-> 3C 53 25 25 :\TCM_APP_33\MO\NO
-> 32 12 H2 3G [Channel]
-> 43 34 52 4B [Channel]
-> 4C 33 45 24 [Channel]
SEND TEST:
-> 35 32 5V 25 :\ KCM_APP_31\TEST\FIX
-> 3N 21 24 23 [Channel]
SEND TEST:
-> 12 3F 56 7D :\BCM_APP_31\TRY
-> 3N 21 24 23 [Channel]

Basically I want to extract the numbers

Body:
try this. see the out put here

if line.startswith('->'):
    start = '-> '
    end = ':\ '
    end1 = ' [Channel]'
    x=line.strip(start)
    x=x.strip(end)
    x=x.strip(end1)
    data.append(x)


问:
Scala tuple function composition
Let's say we have a 3 functions with Tuple3 result:

```<code>def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}
</code>```

And I can compose them like this:

```<code>val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)
</code>```

But I want something like this:

```<code>val (x, y, z) = foo(bar(buz("1", "2", "3")))
</code>```

How can I achieve this?

答:
I think this is what you want.

```<code>foo _ tupled(bar _ tupled buz("1", "2", "3"))
// res0: (String, String, String) = (foo_bar_buz_1,foo_bar_buz_2,foo_bar_buz_3)
</code>```

First, use eta expansion (the _) to turn the method into a Function. Then you can call its tupled() method, which takes a tuple and turns it into the required arguments.

Title: Scala tuple function composition

Body:
Let's say we have a 3 functions with Tuple3 result:

def foo(a: String, b: String, c: String): (String, String, String) = {
  (s"foo_$a", s"foo_$b", s"foo_$c")
}

def bar(a: String, b: String, c: String): (String, String, String) = {
  (s"bar_$a", s"bar_$b", s"bar_$c")
}

def buz(a: String, b: String, c: String): (String, String, String) = {
  (s"buz_$a", s"buz_$b", s"buz_$c")
}

And I can compose them like this:

val (a, b, c) = foo("1", "2", "3")
val (d, e, f) = bar(a, b, c)
val (g, h, i) = buz(d, e, f)

But I want something like this:

val (x, y, z) = foo(bar(buz("1", "2", "3")))

How can I achieve this?

Body:
I think this is what you want.

foo _ tupled(bar _ tupled buz("1", "2", "3"))
// res0: (String, String, String) = (foo_bar_buz_1,foo_bar_buz_2,foo_bar_buz_3)

First, use eta expansion (the _) to turn the method into a Function. Then you can call its tupled() method, which takes a tuple and turns it into the required arguments.


问:
Wordpress Custom Post Type Category System
I currently have a custom post type Projects that I need to have a categorization system. Basically, I need to have the page heirarchy as such: Projects -> Project Listing -> Main Project Page.

Does anyone know a preferred method of doing this? I currently have a page set up for all projects and that works fine. That pulls in all categories. The next step would be sorting project listings based on category. I need to set custom templates for these as well. Am I on the right track here, or is there a simpler approach that anyone can think of. Also, currently if make a page projects/project-listing it doesn't use my custom template I created. It seems to use the index.php template, which is not what I want. I need to have the url structure to be as listed. projects/project-listing

Any help would be greatly appreciated.

答:
Okay, After Wordpress 4.7 custom templates are also available to custom post types, when defining a template

<p>// your code here
you can add this while making post type projects
'supports'  => array( 'title', 'editor','page-attributes' )</p>

Body:
Okay, After Wordpress 4.7 custom templates are also available to custom post types, when defining a template

// your code here
you can add this while making post type projects
'supports'  => array( 'title', 'editor','page-attributes' )