问:
Need to write JUnit test for Scala code
I am new to Scala and Spark. I need to write JUnit for the following word count program:

```<code>import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark._

object SparkWordCount {

  def main(args: Array[String]) {

    meth()

  }

  def meth() {

    //Spark Config object having cluster information
    val sparkConfig = new SparkConf()
      .setAppName("SparkWordCount")
      .setMaster("local")

    val sc = new SparkContext(sparkConfig)

    val input = sc.textFile("C:\\SparkW\\input\\inp.txt")
    val count = input.flatMap(line ⇒ line.split(" "))
      .map(word ⇒ (word, 1))
      .reduceByKey(_ + _)
    count.saveAsTextFile("outfile")
    System.out.println("OK");

  }

}
</code>```

How do I write a test for this using JUnit?

答:
Meanwhile I also found another solution,so thought of sharing it

import java.io.File

import org.junit.{Assert, Test}

/**
  * Created by usharani on 07-07-2017.
  */
class SparkWordCountTest {

@Test
  def test(): Unit = {
    val line1 = new File("outfile/part-00000")
    val line2 = new File("C:/Users/usharani/IdeaProjects/Practice/src/test/scala/inputs.txt")
    val myString = scala.io.Source.fromFile(line1).getLines.mkString
    val myString1 = scala.io.Source.fromFile(line2).getLines.mkString
    println(myString)
    println(myString1)
    Assert.assertEquals(myString, myString1)

}
}

Title: Need to write JUnit test for Scala code

Body:
I am new to Scala and Spark. I need to write JUnit for the following word count program:

import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark._

object SparkWordCount {

  def main(args: Array[String]) {

    meth()

  }

  def meth() {

    //Spark Config object having cluster information
    val sparkConfig = new SparkConf()
      .setAppName("SparkWordCount")
      .setMaster("local")

    val sc = new SparkContext(sparkConfig)

    val input = sc.textFile("C:\\SparkW\\input\\inp.txt")
    val count = input.flatMap(line ⇒ line.split(" "))
      .map(word ⇒ (word, 1))
      .reduceByKey(_ + _)
    count.saveAsTextFile("outfile")
    System.out.println("OK");

  }

}

How do I write a test for this using JUnit?


来源: stackexchange

问:
Image need to be replaced with another image each time with a different button click in html page
I have 3 buttons in a html page and each button is associated with an image.
I need the working as follows,

ButtonA, ButtonB, ButtonC and ImageA, ImageB, Image C.

When ButtonA is clicked, ImageA should be displayed.
When ButtonB is clicked, ImageA should be REPLACED with ImageB.
When ButtonC is clicked, ImageB should be REPLACED with ImageC.
Again when ButtonA is clicked ImageC should be REPLACED with ImageA.

I can use only javascript and html for coding. Is it possible to accomplish it? If yes, Can you give me sample code which i can refer?

答:
Here you go, written in pure JavaScript. As you said, use as reference ;)

Just read the comment lines i provided to each var, function and event

(function() {

  /**
   * In this example i store the image urls inside a javascript object
   */
  var images = {
    a: {'url': 'http://www.markramseymedia.com/wp-content/uploads/2012/02/oneperson.jpg'},
    b: {'url': 'http://kazguu.kz/wp-content/uploads/2016/11/vecher-poe%60zii.jpg'},
    c: {'url': 'http://poskok.info/wp/wp-content/uploads/2015/03/pozija.jpg'},
  }

  /**
   * Get all the buttons
   */
  var buttons = document.querySelectorAll(".button");
  /**
   * Get the image element
   */
  var img = document.getElementById("changeMe");

  /**
   * This function will be called if a button gets clicked
   */
  changeImage = function() {

    /**
     * Get the `data-show` value to determine which image has to be shown
     */
     var image = this.dataset.show;
     /**
      * Change the `style="display: none;"` to `style="display: block;"`
      */
     img.style.display = "block";
     /**
      * Set the `src` attribute, so the image will be loaded dynamicly
      */
     img.src = images[image].url;
  }

  /**
   * Register a click event on each button
   */
  for(var i = 0;i < buttons.length;i++) {
    buttons[i].addEventListener("click", changeImage);
  }

})()```
<pre class="snippet-code-css lang-css prettyprint-override"><code>img {
  max-width: 150px;
  margin: 20px 0;
}</code>```

<button id="buttonA" data-show="a" class="button">Image A</button>
<button id="buttonB" data-show="b" class="button">Image B</button>
<button id="buttonC" data-show="c" class="button">Image C</button>```

ContentLicense: CC BY-SA 3.0

Body:
Here you go, written in pure JavaScript. As you said, use as reference ;)

Just read the comment lines i provided to each var, function and event

(function() {

  /**
   * In this example i store the image urls inside a javascript object
   */
  var images = {
    a: {'url': 'http://www.markramseymedia.com/wp-content/uploads/2012/02/oneperson.jpg'},
    b: {'url': 'http://kazguu.kz/wp-content/uploads/2016/11/vecher-poe%60zii.jpg'},
    c: {'url': 'http://poskok.info/wp/wp-content/uploads/2015/03/pozija.jpg'},
  }

  /**
   * Get all the buttons
   */
  var buttons = document.querySelectorAll(".button");
  /**
   * Get the image element
   */
  var img = document.getElementById("changeMe");

  /**
   * This function will be called if a button gets clicked
   */
  changeImage = function() {

    /**
     * Get the `data-show` value to determine which image has to be shown
     */
     var image = this.dataset.show;
     /**
      * Change the `style="display: none;"` to `style="display: block;"`
      */
     img.style.display = "block";
     /**
      * Set the `src` attribute, so the image will be loaded dynamicly
      */
     img.src = images[image].url;
  }

  /**
   * Register a click event on each button
   */
  for(var i = 0;i < buttons.length;i++) {
    buttons[i].addEventListener("click", changeImage);
  }

})()

img {
  max-width: 150px;
  margin: 20px 0;
}

<img id="changeMe" style="display: none;" />

<button id="buttonA" data-show="a" class="button">Image A</button>
<button id="buttonB" data-show="b" class="button">Image B</button>
<button id="buttonC" data-show="c" class="button">Image C</button>


问:
PLSQL script not working with passing multiple values into IN() caluse
I am very new in PLSQL, i want to pass an array of number into IN() clause value, But Sqldeveloper throw following error messages:

```<code>Error report -
ORA-06550: line 11, column 60:
PLS-00382: expression is of wrong type
ORA-06550: line 11, column 53:
PL/SQL: ORA-22905: cannot access rows from a non-nested table item
ORA-06550: line 10, column 4:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:
</code>```

This is my code :

```<code>DECLARE
   TYPE sc IS TABLE OF transactionhistory.NBSUBCOMPANY%TYPE INDEX BY PLS_INTEGER;
   arr sc;
BEGIN
   arr(0) := 000;
   arr(1) := 111;
   arr(2) := 222;
   arr(3) := 333;

   select count(th.CHCARDNUMBER) as transactions from transactionhistory th INNER JOIN cards ch on ch.NBATTMID=th.NBATTMID where th.dtdate>=to_date('01-oct-2016','dd-mon-yyyy') and th.dtdate<to_date('01-nov-2016','dd-mon-yyyy')
   and ch.NBSUBCOMPANY IN (select column_value from table (arr))
   and ((th.CHTRANSTYPE in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925') and th.NBBASEAMT < 0) or (th.CHTRANSTYPE in ('2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955') and th.NBBASEAMT > 0) or (th.CHTRANSTYPE in ('1101', '1102', '1104', '1105', '1106', '1107', '1109') and th.BASEII_STATUS = 'C') or th.CHTRANSTYPE not in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925', '2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955', '1101', '1102', '1104', '1105', '1106', '1107', '1109'));
END;
</code>```

Please suggest me how can i pass this.

答:
You will need to have a workaround.

SQL doesn't support local collection types to be used in the way you want.

Sample Procedure below which will help in resolving

```<code>CREATE OR REPLACE type TEST_TYPE
IS
    TABLE OF NUMBER;
</code>```

You will need to create a type in the database for this to work. Can be created inside a package, if you have one.

```<code>DECLARE
    TEST_VAR TEST_TYPE := TEST_TYPE();
BEGIN
    TEST_VAR.extend(1);
    TEST_VAR(TEST_VAR.last) := 222;
    TEST_VAR.extend(1);
    TEST_VAR(TEST_VAR.last) := 333;

    FOR rec IN
    (SELECT column_value
    FROM TABLE(TEST_VAR)
    )
    LOOP
        dbms_output.put_line(rec.column_value);

    END LOOP;

END;
</code>```

Output

```<code>222
333
</code>```

This way, you can use select column_value from table(test_var) for your IN() clause.

Also, you don't necessarily need to follow the extend(i) part. you can simply do the below as well

```<code>TEST_VAR TEST_TYPE := TEST_TYPE(222,333);
</code>```

Have a read - local collection types not allowed in SQL statements

Body:
I am very new in PLSQL, i want to pass an array of number into IN() clause value, But Sqldeveloper throw following error messages:

Error report -
ORA-06550: line 11, column 60:
PLS-00382: expression is of wrong type
ORA-06550: line 11, column 53:
PL/SQL: ORA-22905: cannot access rows from a non-nested table item
ORA-06550: line 10, column 4:
PL/SQL: SQL Statement ignored
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

This is my code :

DECLARE
   TYPE sc IS TABLE OF transactionhistory.NBSUBCOMPANY%TYPE INDEX BY PLS_INTEGER;
   arr sc;
BEGIN
   arr(0) := 000;
   arr(1) := 111;
   arr(2) := 222;
   arr(3) := 333;

   select count(th.CHCARDNUMBER) as transactions from transactionhistory th INNER JOIN cards ch on ch.NBATTMID=th.NBATTMID where th.dtdate>=to_date('01-oct-2016','dd-mon-yyyy') and th.dtdate<to_date('01-nov-2016','dd-mon-yyyy')
   and ch.NBSUBCOMPANY IN (select column_value from table (arr))
   and ((th.CHTRANSTYPE in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925') and th.NBBASEAMT < 0) or (th.CHTRANSTYPE in ('2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955') and th.NBBASEAMT > 0) or (th.CHTRANSTYPE in ('1101', '1102', '1104', '1105', '1106', '1107', '1109') and th.BASEII_STATUS = 'C') or th.CHTRANSTYPE not in ('2940', '2916', '2941', '2942', '2943', '2944', '2945', '2902', '2917', '2925', '2922', '2923', '2926', '2950', '2951', '2952', '2953', '2954', '2955', '1101', '1102', '1104', '1105', '1106', '1107', '1109'));
END;

Please suggest me how can i pass this.

Body:
You will need to have a workaround.

SQL doesn't support local collection types to be used in the way you want.

Sample Procedure below which will help in resolving

CREATE OR REPLACE type TEST_TYPE
IS
    TABLE OF NUMBER;

You will need to create a type in the database for this to work. Can be created inside a package, if you have one.

DECLARE
    TEST_VAR TEST_TYPE := TEST_TYPE();
BEGIN
    TEST_VAR.extend(1);
    TEST_VAR(TEST_VAR.last) := 222;
    TEST_VAR.extend(1);
    TEST_VAR(TEST_VAR.last) := 333;

    FOR rec IN
    (SELECT column_value
    FROM TABLE(TEST_VAR)
    )
    LOOP
        dbms_output.put_line(rec.column_value);

    END LOOP;

END;

Output

222
333

This way, you can use select column_value from table(test_var) for your IN() clause.

Also, you don't necessarily need to follow the extend(i) part. you can simply do the below as well

TEST_VAR TEST_TYPE := TEST_TYPE(222,333);

Have a read - local collection types not allowed in SQL statements


问:
AS3 Automatically move object to another object when dragged
EDIT: My problem seems at first a bit confusing. Look at this SWF, then you will surely understand my problem. http://www.fastswf.com/AL5D5ZA
Try to drag the green object (which is pDRA, the red one is pCOMPLETE) As you can see only pComplete moves, but the green box should be always in the same position as the red one when moved!

I want to create a movable object using Action Script, but only some of the areas of the object should be dragged, so I have now the complete object movieclip (pCOMPLETE) and the object that can be dragged (pDRA)

How can I make "pDRA" automatically move to "pCOMPLETE" when it has been dragged?

Here is the script I already have:

```<code>pDRA.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);

function fl_ClickToDrag(event:MouseEvent):void
{
    pCOMPLETE.startDrag();
}

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
    pCOMPLETE.stopDrag();
}
</code>```

答:
Place both your pDRA and pComplete in another movieClip so they would be dragged together and then drag that combined MovieClip.

Move your drag code to the timeline of that new movieclip (where both of your objects are in):

```<code>pDRA.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);

function fl_ClickToDrag(event:MouseEvent):void
{
    this.startDrag();
}

function fl_ReleaseToDrop(event:MouseEvent):void
{
    this.stopDrag();
}
</code>```

Body:
EDIT: My problem seems at first a bit confusing. Look at this SWF, then you will surely understand my problem. http://www.fastswf.com/AL5D5ZA
Try to drag the green object (which is pDRA, the red one is pCOMPLETE) As you can see only pComplete moves, but the green box should be always in the same position as the red one when moved!

I want to create a movable object using Action Script, but only some of the areas of the object should be dragged, so I have now the complete object movieclip (pCOMPLETE) and the object that can be dragged (pDRA)

How can I make "pDRA" automatically move to "pCOMPLETE" when it has been dragged?

Here is the script I already have:

pDRA.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);

function fl_ClickToDrag(event:MouseEvent):void
{
    pCOMPLETE.startDrag();
}

stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
    pCOMPLETE.stopDrag();
}

Body:
Place both your pDRA and pComplete in another movieClip so they would be dragged together and then drag that combined MovieClip.

Move your drag code to the timeline of that new movieclip (where both of your objects are in):

pDRA.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);

function fl_ClickToDrag(event:MouseEvent):void
{
    this.startDrag();
}

function fl_ReleaseToDrop(event:MouseEvent):void
{
    this.stopDrag();
}


问:
Using numpy masking in cython
I'm trying to convert some of my Python code to Cython and experience some issues when I try to define a function as cdef.

Most of the issues boil down to masking not working as in Python. I wonder if this is a limitation of cdef (works fine if I leave it as def) or whether there's something I could do.

For instance this method

```<code>cdef func(double[:,:,:,:] arg1):
    mask = arg1 > 0
    ...
</code>```

already fails with a compile error:

```<code>Error compiling Cython file:
------------------------------------------------------------ ...
    func (double[:,:,:,:] arg1):
        mask = arg1 > 0
                   ^
------------------------------------------------------------

cythonfile.pyx:43:20: Invalid types for '>' (double[:, :, :, :], long)
</code>```

答:
The docs consistently use np.ndarray[...] in function definitions so I would change your function signature to

```<code>cdef func(np.ndarray[np.float_t, ndim=4] arg1):
</code>```

Also, you are comparing a float array with an long integer constant. Change it to

```<code>mask = arg1 > 0.
</code>```

to compare float with float.

Title: Using numpy masking in cython

Body:
I'm trying to convert some of my Python code to Cython and experience some issues when I try to define a function as cdef.

Most of the issues boil down to masking not working as in Python. I wonder if this is a limitation of cdef (works fine if I leave it as def) or whether there's something I could do.

For instance this method

cdef func(double[:,:,:,:] arg1):
    mask = arg1 > 0
    ...

already fails with a compile error:

Error compiling Cython file:
------------------------------------------------------------ ...
    func (double[:,:,:,:] arg1):
        mask = arg1 > 0
                   ^
------------------------------------------------------------

cythonfile.pyx:43:20: Invalid types for '>' (double[:, :, :, :], long)

Body:
The docs consistently use np.ndarray[...] in function definitions so I would change your function signature to

cdef func(np.ndarray[np.float_t, ndim=4] arg1):

Also, you are comparing a float array with an long integer constant. Change it to

mask = arg1 > 0.

to compare float with float.


问:
Convert character/string vector to dates
I am trying to convert quarterly dates to a  "DATE" object in R

my vector is:

```<code>r <- c("2010-Q4" "2011-Q1" "2011-Q2" "2011-Q3" "2011-Q4" "2012-Q1" "2012-Q2" "2012-Q3" "2012-Q4" "2013-Q1" "2013-Q2" "2013-Q3" "2013-Q4" "2014-Q1" "2014-Q2" "2014-Q3")
</code>```

This is a random date vector

I am trying to apply the solution offered in this post, but unfornaterly the suggested answers does not work, and all I get is NA.

Any ideas please?

Body:
I am trying to convert quarterly dates to a  "DATE" object in R

my vector is:

r <- c("2010-Q4" "2011-Q1" "2011-Q2" "2011-Q3" "2011-Q4" "2012-Q1" "2012-Q2" "2012-Q3" "2012-Q4" "2013-Q1" "2013-Q2" "2013-Q3" "2013-Q4" "2014-Q1" "2014-Q2" "2014-Q3")

This is a random date vector

I am trying to apply the solution offered in this post, but unfornaterly the suggested answers does not work, and all I get is NA.

Any ideas please?

Body:
Reading the documentation for as.yearqtr and setting the appropriate format string works for me:

> as.yearqtr(r,format="%Y-Q%q")
[1] "2010 Q4" "2011 Q1" "2011 Q2" "2011 Q3" "2011 Q4" "2012 Q1"

Side-by-side:

> data.frame(string=r,q=as.yearqtr(r,format="%Y-Q%q"))
   string       q
1 2010-Q4 2010 Q4
2 2011-Q1 2011 Q1
3 2011-Q2 2011 Q2
4 2011-Q3 2011 Q3
5 2011-Q4 2011 Q4
6 2012-Q1 2012 Q1

If you want Date objects based on the first day of the quarter:

> as.Date(as.yearqtr(r,format="%Y-Q%q"))
[1] "2010-10-01" "2011-01-01" "2011-04-01" "2011-07-01" "2011-10-01"
[6] "2012-01-01"


问:
How can I connect two Android device by socket without server
I am trying to develop an android application that can exchange data on peer to peer connection with other devices without server. So please suggest how can I do this. Thank you in advance.</p>

答:
Your design has a big problem : ...

If there is no central server some android devices should act as client and others as server but this will not work in some situations:

When the mobile telephony provider assigns private and non-public IP

When the device is connected to a Wi-Fi network but no NAT rule is defined on the router.

In both cases the problem is that the listening port of the device that must act as server is unreachable.


问:
How do I write a Java adapter for Oracle GoldenGate?
According to this whitepaper [1], Oracle GoldenGate for Big Data

... also includes Oracle GoldenGate for Java,
    which enables customers to easily deliver to additional big data systems and support
    specific use cases that their environment demands.

What is the function signature for these plugins?

[1] http://www.oracle.com/us/products/middleware/data-integration/goldengate-for-big-data-ds-2415102.pdf

答:
If you want to replicate to Java please use one of two GoldenGate modules:

GoldenGate for BigData - has ready to use adapters to replicate directly to HDFS, HBase, Flume, Kafka, Cassandra, MongoDB, JDBC. Details in the documentation

GoldenGate for Application Adapters - allows to write directly to flat file and JMS. Details in the documentation

There are also examples in the documentation.


问:
Stick with generic ErrorHandler.js while allowing custom errormessage handling per request and not have double message boxes
The generic ErrorHandler which is an extension and hooked onto every component's main model request is useful for unexpected errors.
However, when I'm creating new entities I want to report with user friendly messages. These messages are composed in the gateway and passed in the RAISE clause. Currently this causes to seperate message boxes to popup, one from the ErrorHandler, one from my onErrorHanlder that I pass to oModel.create().

How can I keep the generic one, but not use it in this case?

答:
To add to the above response from jpenninkhof, I have a scenario where requestFailed events are being raised (maybe the event was stuck in event queue) even after oViewModel.update (in my case it's an update request) request was completed. So I have come out with a solution for that.
Let me first explain the problem.
I have a dialog box for editing a Sales Order with Save/Cancel button. On Save, oViewModel.update is called with Success and Error handler functions.

```<code>this.getOwnerComponent().getModel().detachRequestFailed(this.getOwnerComponent()._oErrorHandler._requestFailedHandler,this.getOwnerComponent()._oErrorHandler);
oViewModel.update(aObjectPath, aData, {
success: function(oData, oResponse) {
    MessageToast.show("Request created successfully");
    this.getOwnerComponent().getModel().attachRequestFailed(this.getOwnerComponent()._oErrorHandler._requestFailedHandler, this.getOwnerComponent()._oErrorHandler);
},
error: function(oData, oResponse) {
    MessageToast.show("Error updating Sales Order.");
    this.getOwnerComponent().getModel().attachRequestFailed(this.getOwnerComponent()._oErrorHandler._requestFailedHandler, this.getOwnerComponent()._oErrorHandler);
    }});
</code>```

The ErrorHandler-->_requestFailedHandler is called AFTER the error function thus the generic error popup still appears. I tried ErrorHandler-->attachRequestFailed() in oViewModel.attachRequestCompleted() also but the requestFailed handler was still being called after completion of the oData request (maybe it's a bug/limitation).

So I created another Flag in ErrorHandler.js along with a Callback function. The flag prevents Service message popup (like ErrorHandler-->_bMessageOpen) and calls the Callback to let the caller know that _showServiceError() has been called.

```<code>_showServiceError: function(sDetails) {

        if (this._bServiceErrorOpen){
            this._fnCallback();
            return;
        }

        if (this._bMessageOpen) {
            return;
        }.....
}
</code>```

Define 2 more function, one to set the flag & callback function and other to reset it.

```<code>setServiceErrorFlag: function(fnCallback){
        this._bServiceErrorOpen = true;
        this._fnCallback = fnCallback;
    },

    resetServiceErrorFlag: function(){

        this._bServiceErrorOpen = false;
        this._fnCallback = undefined;
    }
</code>```

Just before calling model update set this flag. Now the ServiceMessage will not be displayed, instead the anonymous callback function will be called which will wait for while condition to be false.

```<code>var that = this;
this._bErrorResponse = false;
this.getOwnerComponent()._oErrorHandler.setServiceErrorFlag(function()
{
    while (that._bErrorResponse === false){}
    that.getOwnerComponent()._oErrorHandler.resetServiceErrorFlag();
});
</code>```

In the error handler of oViewModel.update(), set _bErrorResponse to true so that while loop gets exited and the ErrorHandler flag is reset. This is to make sure that ErrorHandler flag is reset only after Error callback is called.

```<code>error: function(oData, oResponse) {
    MessageToast.show("Error updating Sales Order.");
    that._bErrorResponse = true;
}
</code>```

Thus, the ServiceError message is suppressed and instead you can give your own error message in Error function callback of oViewModel CRUD APIs.

Body:
To add to the above response from jpenninkhof, I have a scenario where requestFailed events are being raised (maybe the event was stuck in event queue) even after oViewModel.update (in my case it's an update request) request was completed. So I have come out with a solution for that.
Let me first explain the problem.
I have a dialog box for editing a Sales Order with Save/Cancel button. On Save, oViewModel.update is called with Success and Error handler functions.

this.getOwnerComponent().getModel().detachRequestFailed(this.getOwnerComponent()._oErrorHandler._requestFailedHandler,this.getOwnerComponent()._oErrorHandler);
oViewModel.update(aObjectPath, aData, {
success: function(oData, oResponse) {
    MessageToast.show("Request created successfully");
    this.getOwnerComponent().getModel().attachRequestFailed(this.getOwnerComponent()._oErrorHandler._requestFailedHandler, this.getOwnerComponent()._oErrorHandler);
},
error: function(oData, oResponse) {
    MessageToast.show("Error updating Sales Order.");
    this.getOwnerComponent().getModel().attachRequestFailed(this.getOwnerComponent()._oErrorHandler._requestFailedHandler, this.getOwnerComponent()._oErrorHandler);
    }});

The ErrorHandler-->_requestFailedHandler is called AFTER the error function thus the generic error popup still appears. I tried ErrorHandler-->attachRequestFailed() in oViewModel.attachRequestCompleted() also but the requestFailed handler was still being called after completion of the oData request (maybe it's a bug/limitation).

So I created another Flag in ErrorHandler.js along with a Callback function. The flag prevents Service message popup (like ErrorHandler-->_bMessageOpen) and calls the Callback to let the caller know that _showServiceError() has been called.

_showServiceError: function(sDetails) {

        if (this._bServiceErrorOpen){
            this._fnCallback();
            return;
        }

        if (this._bMessageOpen) {
            return;
        }.....
}

Define 2 more function, one to set the flag & callback function and other to reset it.

setServiceErrorFlag: function(fnCallback){
        this._bServiceErrorOpen = true;
        this._fnCallback = fnCallback;
    },

    resetServiceErrorFlag: function(){

        this._bServiceErrorOpen = false;
        this._fnCallback = undefined;
    }

Just before calling model update set this flag. Now the ServiceMessage will not be displayed, instead the anonymous callback function will be called which will wait for while condition to be false.

var that = this;
this._bErrorResponse = false;
this.getOwnerComponent()._oErrorHandler.setServiceErrorFlag(function()
{
    while (that._bErrorResponse === false){}
    that.getOwnerComponent()._oErrorHandler.resetServiceErrorFlag();
});

In the error handler of oViewModel.update(), set _bErrorResponse to true so that while loop gets exited and the ErrorHandler flag is reset. This is to make sure that ErrorHandler flag is reset only after Error callback is called.

error: function(oData, oResponse) {
    MessageToast.show("Error updating Sales Order.");
    that._bErrorResponse = true;
}

Thus, the ServiceError message is suppressed and instead you can give your own error message in Error function callback of oViewModel CRUD APIs.


问:
How to count function calls using decorators?
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code:

```<code>def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)
</code>```

What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

答:
As I understand this (correct me if I'm wrong) the order you program executes is:

Register call_counter.

Register succ.

While registering succ function interpreter finds a decorator so it executes call_counter.

Your function returns an object which is a function (helper). And adds to this object field calls.

Now your function succ has been assigned to helper. So when you call your function, you're actually calling helper function, wrapped within a decorator. So every field you add to your helper function is accessible outside by addressing succ because those 2 variables refer to same thing.

So when you call succ() it's basically the same if you would do helper(*args, **argv)

Check this out:

```<code>def helper(x):
    helper.calls += 1
    return 2
helper.calls = 0

def call_counter(func):
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ == helper)  # prints true.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm refreshing my memory about some python features that I didn't get yet, I'm learning from this python tutorial and there's an example that I don't fully understand. It's about a decorator counting calls to a function, here's the code:

def call_counter(func):
    def helper(x):
        helper.calls += 1
        return func(x)
    helper.calls = 0
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ.calls)
    for i in range(10):
        print(succ(i))
    print(succ.calls)

What I don't get here is why do we increment the calls of the function wrapper (helper.calls += 1) instead of the function calls itself, and why does it actually working?

Body:
As I understand this (correct me if I'm wrong) the order you program executes is:

Register call_counter.

Register succ.

While registering succ function interpreter finds a decorator so it executes call_counter.

Your function returns an object which is a function (helper). And adds to this object field calls.

Now your function succ has been assigned to helper. So when you call your function, you're actually calling helper function, wrapped within a decorator. So every field you add to your helper function is accessible outside by addressing succ because those 2 variables refer to same thing.

So when you call succ() it's basically the same if you would do helper(*args, **argv)

Check this out:

def helper(x):
    helper.calls += 1
    return 2
helper.calls = 0

def call_counter(func):
    return helper

@call_counter
def succ(x):
    return x + 1

if __name__ == '__main__':
    print(succ == helper)  # prints true.


问:
Access: selecting multiple values in a multiselect listbox based on a previous selected value
Sorry if this is a question which is ask many times, but im new to access and have no idea how this matter is called.

In Access I have 3 tables. The first one is Projects
Table Projects has many columns, one of them is Project_Name.

Second table is WBS
Table WBS has also many columns, one of them is WBS_Name and other is Project (which is a dropdown based on Project_Name from table 1).

Sample:
WBS table sample

The third is Orders, here is where im stuck.
Table Orders has a column called Order_Name, also in this table I have a column called Project (which is also based on Project_Name from table 1. The last column (WBS_Product) is a multiselect listbox with values from WBS_Name from table 2.

Order table sample

Now in this third table I want to see in the WBS_Product row only the values available for selection based on the Project selected in the second column.

答: You REALLY should be using forms if you want to customize your data entry like this. Because you're entering data directly into the tables, I don't believe this is possible.</p>


问:
How to add a Web Part Zone to a SharePoint wiki page?
I have a team site. I understand that the default home page of a team site is a wiki page. I want to add a web part zone to this page. How can I do that? By default it already has Web Part Zone -.

You can use SharePoint designer to add a web part to this zone and it works fine. But you are not able to add a web part to this zone using SharePoint web UI? Ususally when you have a web part zone in a page, using SharePoint web UI, it allows to you add/remove a web part. But it is not the case with the web part zone on the default home page of a team site.

Also is there any way I can add a web part zone to this page? I do know that you can easily add web parts into wiki page content. But I want to add a new web part zone where users can add/remove web parts.

Thanks, Hitesh

答: You can add a web part to this using the web UI as well just open the page in edit mode click on insert ribbon menu you would get option to add a webpart</p>

ContentLicense: CC BY-SA 2.5


问:
Can I put storyboard files into different physical folders?
I was moving project files around and noticed that by some reason XCode can't locate my storyboard files. I'm also unable to set their paths with File Inspector - files are not highlighted. Am I allowed to move storyboard files to physical folders?

答:
Yes

In your case your logical folder has lost reference from Physical folder for those files. So, remove the file and add again to the logical folder.


问:
how to show popup notification when android device screen off
I will try to send data messages to my application like this format.

```<code>    {
       "to": "token",
       "data": {
           "title":"Title...",
           "body":"Body...",
           "text":"text"
       }
    }
</code>```

Then after this JSON I am getting in my device with below method.

```<code>    @Override
    public void onMessageReceived(RemoteMessage message) {
        Map<String, String> map = message.getData();
        JSONObject obj = new JSONObject();
        for (Object o : map.keySet()) {
            String key = o.toString();
            String value = map.get(key);
            obj.put(key, value);
        }

        Intent resultIntent = new Intent();
        showNotificationMessage(getApplicationContext(), "Test ...", obj.toString(), resultIntent);

    }

    public void showNotificationMessage(String title,
                                    String message,
                                    Intent intent) {
    // Check for empty push message
    if (TextUtils.isEmpty(message) && TextUtils.isEmpty(title)) {
        return;
    }

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(mContext, 0, intent, 0);

    notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    showSmallNotification(title, message, resultPendingIntent, notificationSoundUri);
    playNotificationSound();
}

private void showSmallNotification(String title,
                                   String message,
                                   PendingIntent resultPendingIntent,
                                   Uri alarmSound) {

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.addLine(message);

    Notification notification;

    notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher)
            .setTicker(title)
            .setShowWhen(true)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(new Random().nextInt(10000), notification);
}
</code>```

That time using this title and body I want to show notification popup form my device and my device screen off so how I can popup notification in my device.

答:
```<code>  /Just implement one line/

.setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)

 /******************************/

  notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher)
        .setTicker(title)
        .setShowWhen(true)
        .setAutoCancel(true)
        .setContentTitle(title)
        .setContentIntent(resultPendingIntent)
        .setSound(alarmSound)
        .setStyle(inboxStyle)
        .setWhen(System.currentTimeMillis())
        .setSmallIcon(R.mipmap.ic_launcher)
        .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND).setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
        .setContentText(message)
        .build();

/**Implement below Method***/

/**And call for "wakeUpLock" Method inside onMessageReceived()**/

private void wakeUpLock()
{

    PowerManager pm = (PowerManager)MyGcmListenerService.this.getSystemService(Context.POWER_SERVICE);

    boolean isScreenOn = pm.isScreenOn();

    Log.i(TAG, "screen on: "+ isScreenOn);

    if(isScreenOn==false)
    {
        Log.i(TAG, "screen on if: "+ isScreenOn);

        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MyLock");

        wl.acquire(10000);

        PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyCpuLock");

        wl_cpu.acquire(10000);
    }

}
</code>```

Body:
I will try to send data messages to my application like this format.

    {
       "to": "token",
       "data": {
           "title":"Title...",
           "body":"Body...",
           "text":"text"
       }
    }

Then after this JSON I am getting in my device with below method.

    @Override
    public void onMessageReceived(RemoteMessage message) {
        Map<String, String> map = message.getData();
        JSONObject obj = new JSONObject();
        for (Object o : map.keySet()) {
            String key = o.toString();
            String value = map.get(key);
            obj.put(key, value);
        }

        Intent resultIntent = new Intent();
        showNotificationMessage(getApplicationContext(), "Test ...", obj.toString(), resultIntent);

    }

    public void showNotificationMessage(String title,
                                    String message,
                                    Intent intent) {
    // Check for empty push message
    if (TextUtils.isEmpty(message) && TextUtils.isEmpty(title)) {
        return;
    }

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent resultPendingIntent =
            PendingIntent.getActivity(mContext, 0, intent, 0);

    notificationSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    showSmallNotification(title, message, resultPendingIntent, notificationSoundUri);
    playNotificationSound();
}

private void showSmallNotification(String title,
                                   String message,
                                   PendingIntent resultPendingIntent,
                                   Uri alarmSound) {

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.addLine(message);

    Notification notification;

    notification = mBuilder.setSmallIcon(R.mipmap.ic_launcher)
            .setTicker(title)
            .setShowWhen(true)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(new Random().nextInt(10000), notification);
}

That time using this title and body I want to show notification popup form my device and my device screen off so how I can popup notification in my device.


问:
How does these services get passed into the controller? version 1.0.8
I got a new job, and took over some systems from some people that isn't here anymore. The version is all the way down to 1.0.8 in angular.js though, and the implementations they have been using seems to be what the community has been saying not to do since forever.

My question is, how do the vvscontroller get the services in as arguments?

I have been trying to grep through the project for any reference for the args: ElReport, ElRow, User, PriorReports, Documentation but it seems like they just magically get parsed in, then i searched for dependency injection, looking if i could find any implementations of the different providers the angular.js mentions, but i can only find the routeProvider and maybe something else that didn't look like it was configured.

So there is a lot of code where i don't think its related - but it might be but obviously i cannot post the entire code here. I was thinking it might be configured into the HTML or something but when i grep for ng-controller i don't find anything related to the PlumbingCtrl, but i just can't quite point it out. Can anyone tell me in what direction i should be looking?? what classes are likely to be used in order to achive this?

app.js

```<code>angular.module('housingevaluation', ['ngRoute', 'housingServices', 'ngUpload', 'angucomplete', 'ui.bootstrap.datetimepicker', 'ngResource', 'fcsa-number']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl: 'partials/home.html', controller: HomeCtrl}).when('/vvs/:reportId', {templateUrl: 'partials/plumbing.html', controller: PlumbingCtrl}).
...more controllers + some config that does something with http/https(don't think thats related)
</code>```

services.js

```<code>angular.module('housingServices', ['ngResource']).
        factory('ElReport', function($resource) {
        return $resource('reports/el/:id', {id: '@Id'}, {
            query: {method: 'GET', isArray: false},
            get: {method: 'GET'},
            save: {method: 'POST'},
            completeReport: {method: 'POST', url: 'reports/el/:id/complete'},
            reopenReport: {method: 'POST', url: 'reports/el/:id/reopen'},
            queryPlumbing: {method: 'GET', isArray: false},
            createCopy: {method: 'POST', url: 'reports/el/:id/reevaluation'},
            createRealCopy: {method: 'POST', url: 'reports/el/:id/copy'},
            markBilled: {method: 'POST', url: 'reports/el/:id/markBilled'}
        });
    }).
...some more factories (Documentation, User, etc.)
...some more directives
</code>```

vvscontroller.js

```<code>function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) {
...
}
</code>```

index.html

```<code><html ng-app>
</code>```

Thanks !

答:
Looks like module housingevaluation is your root module of Angularjs application. All your services like ElReport , Documentation etc are part of module housingServices and module housingServices is injected to your root module module housingevaluation. It means all your services from module housingServices are accessible in module housingevaluation. And your all controllers are part of your root module that is module housingevaluation. Thats why all services from module housingServices are accessible in your controller.

One more thing is services.js and vvscontroller.js must be added in index.html before app.js.

EDIT :
Somewhere in your code PlumbingCtrl must have added to your root module housingevaluation. While adding the controller to module you can give order of depedancy injection for PlumbingCtrl. like this...

```<code>angular.module('housingevaluation')
  .controller('PlumbingCtrl', [ '$scope', '$routeParams', '$location', 'ElReport', 'ElRow', 'User', 'PriorReports', 'Documentation', function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) {
    ...
}]);
</code>```

Now while defining your controller you have to follow the same order for injecting the factories/services. like this...

```<code>function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) { ... }
</code>```

It may help you.

Body:
I got a new job, and took over some systems from some people that isn't here anymore. The version is all the way down to 1.0.8 in angular.js though, and the implementations they have been using seems to be what the community has been saying not to do since forever.

My question is, how do the vvscontroller get the services in as arguments?

I have been trying to grep through the project for any reference for the args: ElReport, ElRow, User, PriorReports, Documentation but it seems like they just magically get parsed in, then i searched for dependency injection, looking if i could find any implementations of the different providers the angular.js mentions, but i can only find the routeProvider and maybe something else that didn't look like it was configured.

So there is a lot of code where i don't think its related - but it might be but obviously i cannot post the entire code here. I was thinking it might be configured into the HTML or something but when i grep for ng-controller i don't find anything related to the PlumbingCtrl, but i just can't quite point it out. Can anyone tell me in what direction i should be looking?? what classes are likely to be used in order to achive this?

app.js

angular.module('housingevaluation', ['ngRoute', 'housingServices', 'ngUpload', 'angucomplete', 'ui.bootstrap.datetimepicker', 'ngResource', 'fcsa-number']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl: 'partials/home.html', controller: HomeCtrl}).when('/vvs/:reportId', {templateUrl: 'partials/plumbing.html', controller: PlumbingCtrl}).
...more controllers + some config that does something with http/https(don't think thats related)

services.js

angular.module('housingServices', ['ngResource']).
        factory('ElReport', function($resource) {
        return $resource('reports/el/:id', {id: '@Id'}, {
            query: {method: 'GET', isArray: false},
            get: {method: 'GET'},
            save: {method: 'POST'},
            completeReport: {method: 'POST', url: 'reports/el/:id/complete'},
            reopenReport: {method: 'POST', url: 'reports/el/:id/reopen'},
            queryPlumbing: {method: 'GET', isArray: false},
            createCopy: {method: 'POST', url: 'reports/el/:id/reevaluation'},
            createRealCopy: {method: 'POST', url: 'reports/el/:id/copy'},
            markBilled: {method: 'POST', url: 'reports/el/:id/markBilled'}
        });
    }).
...some more factories (Documentation, User, etc.)
...some more directives

vvscontroller.js

function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) {
...
}

index.html

Thanks !

Body:
Looks like module housingevaluation is your root module of Angularjs application. All your services like ElReport , Documentation etc are part of module housingServices and module housingServices is injected to your root module module housingevaluation. It means all your services from module housingServices are accessible in module housingevaluation. And your all controllers are part of your root module that is module housingevaluation. Thats why all services from module housingServices are accessible in your controller.

One more thing is services.js and vvscontroller.js must be added in index.html before app.js.

EDIT :
Somewhere in your code PlumbingCtrl must have added to your root module housingevaluation. While adding the controller to module you can give order of depedancy injection for PlumbingCtrl. like this...

angular.module('housingevaluation')
  .controller('PlumbingCtrl', [ '$scope', '$routeParams', '$location', 'ElReport', 'ElRow', 'User', 'PriorReports', 'Documentation', function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) {
    ...
}]);

Now while defining your controller you have to follow the same order for injecting the factories/services. like this...

function PlumbingCtrl($scope, $routeParams, $location, ElReport, ElRow, User, PriorReports, Documentation) { ... }

It may help you.


问:
Magento 2.1.7 moved website redirecting to old url
i have installed latest magento 2.1.7 version on my server and installed a theme. I have installed magento in a folder(http://example.com/site/) everything is working fine there. Now i have moved it to root directory (http://example.com/) as a main website, but there it is not working, it redirecting to old url with SID var. http://example.com/site/?sid=8374urh347yr7w4ry

I have tried the following changes:

Changed base_url in core_config_data table,

Deleted all cache/ everything in var/

Deleted browser cache/cookies

I tried on localhost but yet redirecting to http://example.com/site/?sid=8374urh347yr7w4ry

Deleted system tmp files

I checked env.php file but there is nothing

All permission set

Is magento store base_url in any file also? so that i could change.

Any help will be appreciated

答:
As my comment solved your problem I will post it as an answer.

According to magento takes all config data from cache folder you have to clear the magentodir/var/cache - including all subfolders - to be sure the new config is taken.

You said you allready cleared the cache, my advice is to check this point again. (Maybe you cleared the cache before you did the necessary changes?)


问:
Printing pdf using Node js and Google Chrome
Tried creating a pdf using chrome-remote-interface Node js module. When I try to pass arguments to printToPDF function, I get the same output as the one with not arguments.

Page Ref: https://chromedevtools.github.io/devtools-protocol/tot/Page/

Look into printToPDF function.

My code for printing pdf.

```<code>const pdf = await Page.printToPDF({landscape: 'true',displayHeaderFooter: 'true',printBackground: 'true',scale: '1.0',paperWidth: '8.5',paperHeight: '11',marginTop: '0.4',marginBottom: '0.4',marginLeft: '0.5',marginRight: '0.5',pageRanges: ""});
</code>```

答: The issue is that, print to pdf supports parameters only from version 60. That's why it didn't work</p>

Body:
Tried creating a pdf using chrome-remote-interface Node js module. When I try to pass arguments to printToPDF function, I get the same output as the one with not arguments.

Page Ref: https://chromedevtools.github.io/devtools-protocol/tot/Page/

Look into printToPDF function.

My code for printing pdf.

const pdf = await Page.printToPDF({landscape: 'true',displayHeaderFooter: 'true',printBackground: 'true',scale: '1.0',paperWidth: '8.5',paperHeight: '11',marginTop: '0.4',marginBottom: '0.4',marginLeft: '0.5',marginRight: '0.5',pageRanges: ""});


问:
Android layouts for different screen sizes
I am struggling for layouts for an Android app. I have defined different layouts for different screen sizes and the current layout directory structure is something like this:

layout

layout-land

layout-small

layout-xlarge

layout-xlarge-land

Problem

The main layout directory files are being displayed for 3.7 to 7.0 which is a very broad range. And text overlap on small screens and if I adjust on small; it becomes very tiny on the large screen.

According to me, the layout small files should be rendered for smaller screens but those files are only rendered for android wear devices.

layout-xlarge seems to work for Nexus 9 to Nexus 10

I want to know, how can I define the different layout for 3.7-5.0 and 5.0-7.0 screen sizes.

答: Dear you don't need to declare layout for various screen. just make single layout for every screen and don't fix the width and height of layout. you have to keep height either match parent and wrap content as well as for width.</p>


答:
The important thing to remember about decorators is that a decorator is a function that takes a function as an argument, and returns yet another function. The returned value - yet another function - is what will be called when the name of the original function is invoked.

This model can be very simple:

```<code>def my_decorator(fn):
    print("Decorator was called")
    return fn
</code>```

In this case, the returned function is the same as the passed-in function. But that's usually not what you do. Usually, you return either a completely different function, or you return a function that somehow chains or wraps the original function.

In your example, which is a very common model, you have an inner function that is returned:

```<code>def helper(x):
    helper.calls += 1
    return func(x)
</code>```

This inner function calls the original function (return func(x)) but it also increments the calls counter.

This inner function is being inserted as a "replacement" for whatever function is being decorated. So when your module foo.succ() function is looked up, the result is a reference to the inner helper function returned by the decorator. That function increments the call counter and then calls the originally-defined succ function.

Title: How to count function calls using decorators?

Body:
The important thing to remember about decorators is that a decorator is a function that takes a function as an argument, and returns yet another function. The returned value - yet another function - is what will be called when the name of the original function is invoked.

This model can be very simple:

def my_decorator(fn):
    print("Decorator was called")
    return fn

In this case, the returned function is the same as the passed-in function. But that's usually not what you do. Usually, you return either a completely different function, or you return a function that somehow chains or wraps the original function.

In your example, which is a very common model, you have an inner function that is returned:

def helper(x):
    helper.calls += 1
    return func(x)

This inner function calls the original function (return func(x)) but it also increments the calls counter.

This inner function is being inserted as a "replacement" for whatever function is being decorated. So when your module foo.succ() function is looked up, the result is a reference to the inner helper function returned by the decorator. That function increments the call counter and then calls the originally-defined succ function.


问:
Exporting aws management console settings
When using the aws web management console it's very handy to add favourite services and switch between different roles. However when using a different browser or different computer with the same login it's not showing up.

How to export these settings so they can be imported or synced between computers?

答:
If you are referring to things like 'favourite' services at the top of the screen and Switch Role settings, they are stored in cookies on your local computer.

You could possibly synchronize cookies between computers using a browser plugin, but the AWS Management Console won't do it for you.


问:
How to make model class for following JSON response in swift iOS
Hi i am beginner  for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please

JsonResponse:-

```<code>[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]
</code>```

mapping:

Club:-

```<code>class Club {

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}
</code>```

Location:-

```<code>class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}
</code>```

NSURlSession code:-

```<code>class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}
</code>```

答:
Step1: Create your model like below.

```<code>class Club {
        var id: String = ""
        var name: String = ""
        var imageUrl: String = ""
        var hasVip: Bool = false
        var desc: String = ""
        var location = Location()

        init?(dictionary:[String:Any],location: Location) {
            guard let id = dictionary["_id"],
                let name = dictionary["name"],
                let imageUrl = dictionary["imageUrl"],
                let hasVip = dictionary["hasVippler"]
            else {
                return nil
            }
     self.id = id
     self.name = name
     self.imageUrl = imageUrl
     self.hasVip = hasVip
     self.location = location
  }
 }
}
class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""

   init?(dictionary:[String:Any]) {
            guard let country = dictionary["country"],
                let city = dictionary["city"],
                let address = dictionary["address"],
                let zip = dictionary["zip"]
            else {
                return nil
            }
     self.country = country
     self.city = city
     self.address = address
     self.zip = zip
  }
 }
}
</code>```

Step2: Declare your array as below.

```<code>var myTargetArray = [Club]()
</code>```

Step3: Json Parsing.

```<code>    do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                print("Response: \(json)")

            for club in json {
                   if let clubDictionary = club as? NSDictionary {
                     if let locationDict = clubDictionary["location"] as? NSDictionary{
                         if let location = Location(dictionary: locationDict) {

                           if let clubObj = Club(dictionary: clubDictionary, location:location) {
                            myTargetArray.append(clubObj)
                       }
                   }
                }
            }
        }
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)// Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
</code>```

Note: I removed underground array from location model since your json data does not contain it.
Finally you can use your target array as your tableview source. Happy coding...

Body:
Hi i am beginner  for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please

JsonResponse:-

[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]

mapping:

Club:-

class Club {

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}

Location:-

class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}

NSURlSession code:-

class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}

Body:
Step1: Create your model like below.

class Club {
        var id: String = ""
        var name: String = ""
        var imageUrl: String = ""
        var hasVip: Bool = false
        var desc: String = ""
        var location = Location()

        init?(dictionary:[String:Any],location: Location) {
            guard let id = dictionary["_id"],
                let name = dictionary["name"],
                let imageUrl = dictionary["imageUrl"],
                let hasVip = dictionary["hasVippler"]
            else {
                return nil
            }
     self.id = id
     self.name = name
     self.imageUrl = imageUrl
     self.hasVip = hasVip
     self.location = location
  }
 }
}
class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""

   init?(dictionary:[String:Any]) {
            guard let country = dictionary["country"],
                let city = dictionary["city"],
                let address = dictionary["address"],
                let zip = dictionary["zip"]
            else {
                return nil
            }
     self.country = country
     self.city = city
     self.address = address
     self.zip = zip
  }
 }
}

Step2: Declare your array as below.

var myTargetArray = [Club]()

Step3: Json Parsing.

    do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                print("Response: \(json)")

            for club in json {
                   if let clubDictionary = club as? NSDictionary {
                     if let locationDict = clubDictionary["location"] as? NSDictionary{
                         if let location = Location(dictionary: locationDict) {

                           if let clubObj = Club(dictionary: clubDictionary, location:location) {
                            myTargetArray.append(clubObj)
                       }
                   }
                }
            }
        }
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)// Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }

Note: I removed underground array from location model since your json data does not contain it.
Finally you can use your target array as your tableview source. Happy coding...


问:
Breaking up long strings on multiple lines in Ruby without stripping newlines
We recently decided at my job to a ruby style guide. One of the edicts is that no line should be wider than 80 characters. Since this is a Rails project, we often have strings that are a little bit longer - i.e. "User X wanted to send you a message about Thing Y" that doesn't always fit within the 80 character style limit.

I understand there are three ways to have a long string span multiple lines:

HEREDOC

%Q{}

Actual string concatenation.

However, all of these cases end up taking more computation cycles, which seems silly. String concatenation obviously, but for HEREDOC and %Q I have to strip out the newlines, via something like .gsub(/\n$/, '').

Is there a pure syntax way to do this, that is equivalent to just having the whole string on one line? The goal being, obviously, to not spend any extra cycles just because I want my code to be slightly more readable. (Yes, I realize that you have to make that tradeoff a lot...but for string length, this just seems silly.)

Update:
Backslashes aren't exactly what I want because you lose indentation, which really affects style/readability.

Example:

```<code>if foo
  string = "this is a \
string that spans lines"
end
</code>```

I find the above a bit hard to read.

EDIT: I added an answer below; three years later we now have the squiggly heredoc.

答:
I had this problem when I try to write a very long url, the following works.

```<code>image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join
</code>```

Note, there must not be any newlines, white spaces when the url string is formed.  If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line.  The cost of joining the strings should be negligible.

Body:
We recently decided at my job to a ruby style guide. One of the edicts is that no line should be wider than 80 characters. Since this is a Rails project, we often have strings that are a little bit longer - i.e. "User X wanted to send you a message about Thing Y" that doesn't always fit within the 80 character style limit.

I understand there are three ways to have a long string span multiple lines:

HEREDOC

%Q{}

Actual string concatenation.

However, all of these cases end up taking more computation cycles, which seems silly. String concatenation obviously, but for HEREDOC and %Q I have to strip out the newlines, via something like .gsub(/\n$/, '').

Is there a pure syntax way to do this, that is equivalent to just having the whole string on one line? The goal being, obviously, to not spend any extra cycles just because I want my code to be slightly more readable. (Yes, I realize that you have to make that tradeoff a lot...but for string length, this just seems silly.)

Update:
Backslashes aren't exactly what I want because you lose indentation, which really affects style/readability.

Example:

if foo
  string = "this is a \
string that spans lines"
end

I find the above a bit hard to read.

EDIT: I added an answer below; three years later we now have the squiggly heredoc.

Body:
I had this problem when I try to write a very long url, the following works.

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed.  If you want newlines, then use HEREDOC.

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line.  The cost of joining the strings should be negligible.


问:
Why do changes made to a cell propagate to other cells in this 2 dimensional array created using fill?
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

```<code>>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true
</code>```

答:
The fill function as described in mdn, copies the same value to all array indices. You can use the below utility to create clones of the array. But since i am using the slice operator, this is restricted to cloning arrays.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

```<code>   if (!Array.prototype.clonefill) {
  Object.defineProperty(Array.prototype, 'clonefill', {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value.slice(0);
        k++;
      }

      // Step 13.
      return O;
    }
  });
}
Array(100).clonefill(Array(100))
a[0][0] = true
a[1][0]
false
</code>```

Body:
I have a problem with this 2-dimensional array in JS. When I change a[1][0], a[0][0] changes with it. Is there something wrong in the way I am initializing it? If yes, how can I initialize it properly?

>var a = Array(100).fill(Array(100).fill(false));
>a[0][0]
>false
>a[1][0]
>false
>a[1][0] = true
>true
>a[1][0]
>true
>a[0][0]
>true

Body:
The fill function as described in mdn, copies the same value to all array indices. You can use the below utility to create clones of the array. But since i am using the slice operator, this is restricted to cloning arrays.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/fill

   if (!Array.prototype.clonefill) {
  Object.defineProperty(Array.prototype, 'clonefill', {
    value: function(value) {

      // Steps 1-2.
      if (this == null) {
        throw new TypeError('this is null or not defined');
      }

      var O = Object(this);

      // Steps 3-5.
      var len = O.length >>> 0;

      // Steps 6-7.
      var start = arguments[1];
      var relativeStart = start >> 0;

      // Step 8.
      var k = relativeStart < 0 ?
        Math.max(len + relativeStart, 0) :
        Math.min(relativeStart, len);

      // Steps 9-10.
      var end = arguments[2];
      var relativeEnd = end === undefined ?
        len : end >> 0;

      // Step 11.
      var final = relativeEnd < 0 ?
        Math.max(len + relativeEnd, 0) :
        Math.min(relativeEnd, len);

      // Step 12.
      while (k < final) {
        O[k] = value.slice(0);
        k++;
      }

      // Step 13.
      return O;
    }
  });
}
Array(100).clonefill(Array(100))
a[0][0] = true
a[1][0]
false


问:
Spring Batch - FlatFileItemReader for different delimited files
I have two different files, one delimited by pipe separator "|" and one by comma ",".

I am using Spring Batch to process these files using FlatFileItemReader. I dont want to have two readers and two writers for the files.
Can I have somehow one generic FlatFileItemReader for both files?

Also the objects to which the files will be mapped are different.

答:
You can inject a DelimitedLineTokenizer into the FlatFileItemReader and set the delimiter value to it. Relevant parts of the XML config are as follows

```<code><bean id="pipeDelimitedFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
    ...
    <property name="lineMapper">
        <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
            <property name="lineTokenizer">
                <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                    ...
                    <property name="delimiter" value="|"/>
                </bean>
            </property>
            ...
        </bean>
    </property>
    ...
</bean>
</code>```

You can e.g. similarly configure another, commaDelimitedFileItemReader bean (comma is actually the default delimiter value for DelimitedLineTokenizer)

Body:
You can inject a DelimitedLineTokenizer into the FlatFileItemReader and set the delimiter value to it. Relevant parts of the XML config are as follows

<bean id="pipeDelimitedFileItemReader" class="org.springframework.batch.item.file.FlatFileItemReader">
    ...
    <property name="lineMapper">
        <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
            <property name="lineTokenizer">
                <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                    ...
                    <property name="delimiter" value="|"/>
                </bean>
            </property>
            ...
        </bean>
    </property>
    ...
</bean>

You can e.g. similarly configure another, commaDelimitedFileItemReader bean (comma is actually the default delimiter value for DelimitedLineTokenizer)


问:
Setting Gmail up to send emails from Amazon SES SMTP
Very close on this, I'm just missing some small detail.

Here's the error - Diagnostic-Code: smtp; 530 Authentication required

Links I've followed:
- http://docs.aws.amazon.com/ses/latest/DeveloperGuide/receiving-email-getting-started.html
- http://docs.aws.amazon.com/ses/latest/DeveloperGuide/configure-email-client.html
- http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html

Any ideas would be appreciated - thanks!

答:
Sorry, solved it.

For clarity, was trying to compose an email in Gmail and then send with new email address that had been earlier set up in AWS SES.

The problem was the MX record, was pointing to the wrong region.

Thanks!!


问:
How can I put an async function inside a function?
This is the code I'm using. It doesn't work because client.getPosts is async. So my question is, how can I make it work? client.getPosts is from the wordpress npm module so I cannot change it.</p>

```<code>// FUNCTIONS

function getAllPosts() {
    return client
        .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
        return posts
            .map((item) => {
            return item.title
            })
        })
}

// MAIN

console.log(getAllPosts());
</code>```

答:
in .getPosts() method you are using 3 params an object an array and a function referance.

The point is you are sending a referance to that function. You should execute that functon after your process end. but your code line won't wait youır process end.

Body:
This is the code I'm using. It doesn't work because client.getPosts is async. So my question is, how can I make it work? client.getPosts is from the wordpress npm module so I cannot change it.

// FUNCTIONS

function getAllPosts() {
    return client
        .getPosts( {type: 'post', status : 'publish', number : 222} , ['title','id'] , (error, posts) => {
        return posts
            .map((item) => {
            return item.title
            })
        })
}

// MAIN

console.log(getAllPosts());


问:
pass ALL local variables from Jade to JavaScript
I can find solutions to pass local variables from jade to javascript, for example:

```<code>script.
  var myVar = `#{myVar}`;
script(src=src)
</code>```

But since I want to use my jade template for many views, with different sets of variables, I wonder if it is possible to pass ALL available local variables.

答:
Going off the answers to this question it doesn't look like there's a clean way of getting all variables in scope.

In which case you're best off gathering all variables you want to pass to your jade/pug in a single object and then pass that object to the pug file.

```<code>const holder = {};

holder.one = 1;
holder.two = 2;

pug.compile(page, holder);
</code>```

You can then do

```<code>script.
  var one= `#{one}`;
script(src=src)
</code>```

Body:
I can find solutions to pass local variables from jade to javascript, for example:

script.
  var myVar = `#{myVar}`;
script(src=src)

But since I want to use my jade template for many views, with different sets of variables, I wonder if it is possible to pass ALL available local variables.

Body:
Going off the answers to this question it doesn't look like there's a clean way of getting all variables in scope.

In which case you're best off gathering all variables you want to pass to your jade/pug in a single object and then pass that object to the pug file.

const holder = {};

holder.one = 1;
holder.two = 2;

pug.compile(page, holder);

You can then do

script.
  var one= `#{one}`;
script(src=src)


问:
how to iterate elements in reverse order in jquery?
i'm new to jquery.I'd like to know how to iterate form elements in reverse order in jquery using each()?
Any help would be appreciated:)</p>

答:
Better yet</p>

```<code>$.each(  $( $('input').get().reverse() )  , function(){ /* ... */ });
</code>```

Body:
Better yet

$.each(  $( $('input').get().reverse() )  , function(){ /* ... */ });


问:
Convert character/string vector to dates
I am trying to convert quarterly dates to a  "DATE" object in R

my vector is:

```<code>r <- c("2010-Q4" "2011-Q1" "2011-Q2" "2011-Q3" "2011-Q4" "2012-Q1" "2012-Q2" "2012-Q3" "2012-Q4" "2013-Q1" "2013-Q2" "2013-Q3" "2013-Q4" "2014-Q1" "2014-Q2" "2014-Q3")
</code>```

This is a random date vector

I am trying to apply the solution offered in this post, but unfornaterly the suggested answers does not work, and all I get is NA.

Any ideas please?

答:
I believe your formatting is incorrect. The following seems to work:</p>

```<code>library('zoo')
r <- c("2010-Q4", "2011-Q1", "2011-Q2")

# The format string encodes: %Y: 4 digit year, then a hyphen,
# then a capital Q, then %q which refers to the actual quarterly digit.
as.yearqtr(r, format='%Y-Q%q')
# [1] "2010 Q4" "2011 Q1" "2011 Q2"
</code>```

Body:
I am trying to convert quarterly dates to a  "DATE" object in R

my vector is:

r <- c("2010-Q4" "2011-Q1" "2011-Q2" "2011-Q3" "2011-Q4" "2012-Q1" "2012-Q2" "2012-Q3" "2012-Q4" "2013-Q1" "2013-Q2" "2013-Q3" "2013-Q4" "2014-Q1" "2014-Q2" "2014-Q3")

This is a random date vector

I am trying to apply the solution offered in this post, but unfornaterly the suggested answers does not work, and all I get is NA.

Any ideas please?

Body:
I believe your formatting is incorrect. The following seems to work:

library('zoo')
r <- c("2010-Q4", "2011-Q1", "2011-Q2")

# The format string encodes: %Y: 4 digit year, then a hyphen,
# then a capital Q, then %q which refers to the actual quarterly digit.
as.yearqtr(r, format='%Y-Q%q')
# [1] "2010 Q4" "2011 Q1" "2011 Q2"


问:
Is there any way to reduce element locating time in Selenium WebDriver?
I have one select city dropdown and there are around 8000 city presents. My usecase are:

Get the selected city name

If city name is not as expected then select the desired city

Now again get the city name to verify that desired city has been selected

My code is working fine but the issue is to complete these 3 steps it takes around 5-8 minutes. I know its due to the large set of city name available in dropdown

This is the dropdown HTML structure :

```<code><div class="col-md-12">
  <label class="mmk-filter-control">Preferred Source City : </label>
     <div class="pull-right refe-link">
     <div class="mmk-filter-control mmk-select-filter pull-right mr5">
     <select id="ddlPrefferedSourceCity" class="form-control" name="ddlPrefferedSourceCity">
          <option value="-1">- Select -</option>
          <option value="A.S.Peta Bypass">A.S.Peta Bypass</option>
          <option value="aadsar">aadsar</option>
          <option value="aagariya">aagariya</option>
          <option value="aahur">aahur</option>
          <option value="aakadiya">aakadiya</option>
          <option value="Aala">Aala</option>
          <option value="Aanjangaon">Aanjangaon</option>
           .
           .
          around 8000 options
</code>```

And code is:

```<code>if(usersname.size()>0)
{
     Select s = new Select(preferredCity);
     Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
     String cityName  = s.getFirstSelectedOption().getText();
     if(cityName.equals(preferredCityName))
     {
         LogWriter.logger.info("Preferred City is already Selected");
         TakeScreenshot.passedScreenShot();
     }
     else
     {
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("Last Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
         s.selectByVisibleText(preferredCityName);
         setPreferenceButton.click();
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("New Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
     }
}
</code>```

Is there any way to overcome and make the test fast?

答:
I really don't know why it is taking time to get the dropdown value using getFirstSelectedOption

I have tried JavascriptExecutor where i have populated value of the dropdown using jQuery command

```<code>public String getDropdownValue()
{
        JavascriptExecutor e = (JavascriptExecutor) driver;
        return (String) e.executeScript("return $('#ddlPrefferedSourceCity').val();");
}
</code>```

Now I'm able to get the value even change the dropdown value and again find the selected value. And now the time is 5-8 second.

Body:
I have one select city dropdown and there are around 8000 city presents. My usecase are:

Get the selected city name

If city name is not as expected then select the desired city

Now again get the city name to verify that desired city has been selected

My code is working fine but the issue is to complete these 3 steps it takes around 5-8 minutes. I know its due to the large set of city name available in dropdown

This is the dropdown HTML structure :

  Preferred Source City :

     <select id="ddlPrefferedSourceCity" class="form-control" name="ddlPrefferedSourceCity">
          <option value="-1">- Select -</option>
          <option value="A.S.Peta Bypass">A.S.Peta Bypass</option>
          <option value="aadsar">aadsar</option>
          <option value="aagariya">aagariya</option>
          <option value="aahur">aahur</option>
          <option value="aakadiya">aakadiya</option>
          <option value="Aala">Aala</option>
          <option value="Aanjangaon">Aanjangaon</option>
           .
           .
          around 8000 options

And code is:

if(usersname.size()>0)
{
     Select s = new Select(preferredCity);
     Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
     String cityName  = s.getFirstSelectedOption().getText();
     if(cityName.equals(preferredCityName))
     {
         LogWriter.logger.info("Preferred City is already Selected");
         TakeScreenshot.passedScreenShot();
     }
     else
     {
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("Last Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
         s.selectByVisibleText(preferredCityName);
         setPreferenceButton.click();
         Comman.wait.until(ExpectedConditions.invisibilityOf(loader));
         LogWriter.logger.info("New Selected Preferred City is : " + s.getFirstSelectedOption().getText());
         TakeScreenshot.passedScreenShot();
     }
}

Is there any way to overcome and make the test fast?

Body:
I really don't know why it is taking time to get the dropdown value using getFirstSelectedOption

I have tried JavascriptExecutor where i have populated value of the dropdown using jQuery command

public String getDropdownValue()
{
        JavascriptExecutor e = (JavascriptExecutor) driver;
        return (String) e.executeScript("return $('#ddlPrefferedSourceCity').val();");
}

Now I'm able to get the value even change the dropdown value and again find the selected value. And now the time is 5-8 second.


问:
Element in the array such that the sum of the elements on its left is equal to the sum of the elements on its right
I am trying to solve Sherlock and Array algorithm task. I have array and i need to find element in the array such that the sum of the elements on its left side is equal to the elements of it's right side, like i mentioned in the title. My algorithm works for small arrays, but for big arrays it is too slove, what can i do to improve it's speed ?

Just to mention. This algorithm dont accept arrays of size 1 and 2.

```<code>public static boolean isSherlock(int arr[])
{
    int length = arr.length;
    int leftSum = 0;
    int rightSum = 0;

    for(int i=0; i<length-1; i++)
    {
        leftSum = 0;
        rightSum = 0;

        // Left sum for index i
        for(int j=0; j<i; j++)
            leftSum+=arr[j];

        // Right sum for index i
        for(int j=i+1; j<length && leftSum != 0; j++)
            rightSum+=arr[j];

        if(leftSum == rightSum && leftSum != 0 && rightSum != 0)
        {
            return true;
        }
    }
    return false;
}
</code>```

This is O(N^2) is there any way to do it in O(n) ?

答:
try this</p>

```<code>public static boolean isSherlock(int arr[])
{
    if (arr.length > 2) {
        int i = 1;
        for (; i < arr.length - 1; i++) {
            int k = 0;
            int rhs = arr[i + 1];
            int lhs = arr[i - 1];

            int j = arr.length - 1;

            // **In single iteration it is suming from left as well as from right**
            while (k < i - 1 && j > i + 1) {
                rhs += arr[j--];
                lhs += arr[k++];
            }
            // **************

            // If any elements remain
            while (k < i - 1)
                lhs += arr[k++];

            while (j > i + 1)
                rhs += arr[j--];

            // compare
            if (rhs == lhs && lhs != 0 && rhs != 0) {
                return true;
            }
        }
    }
    return false;
}
</code>```

Body:
I am trying to solve Sherlock and Array algorithm task. I have array and i need to find element in the array such that the sum of the elements on its left side is equal to the elements of it's right side, like i mentioned in the title. My algorithm works for small arrays, but for big arrays it is too slove, what can i do to improve it's speed ?

Just to mention. This algorithm dont accept arrays of size 1 and 2.

public static boolean isSherlock(int arr[])
{
    int length = arr.length;
    int leftSum = 0;
    int rightSum = 0;

    for(int i=0; i<length-1; i++)
    {
        leftSum = 0;
        rightSum = 0;

        // Left sum for index i
        for(int j=0; j<i; j++)
            leftSum+=arr[j];

        // Right sum for index i
        for(int j=i+1; j<length && leftSum != 0; j++)
            rightSum+=arr[j];

        if(leftSum == rightSum && leftSum != 0 && rightSum != 0)
        {
            return true;
        }
    }
    return false;
}

This is O(N^2) is there any way to do it in O(n) ?

Body:
try this

public static boolean isSherlock(int arr[])
{
    if (arr.length > 2) {
        int i = 1;
        for (; i < arr.length - 1; i++) {
            int k = 0;
            int rhs = arr[i + 1];
            int lhs = arr[i - 1];

            int j = arr.length - 1;

            // **In single iteration it is suming from left as well as from right**
            while (k < i - 1 && j > i + 1) {
                rhs += arr[j--];
                lhs += arr[k++];
            }
            // **************

            // If any elements remain
            while (k < i - 1)
                lhs += arr[k++];

            while (j > i + 1)
                rhs += arr[j--];

            // compare
            if (rhs == lhs && lhs != 0 && rhs != 0) {
                return true;
            }
        }
    }
    return false;
}


问:
How to save bot data using Bot framework and azure
I'm using Bot Framework to build my bot and language C#. I have deploy my code in Azure. I want to save all the bot conversation in a database.

I was reading a document : https://blog.botframework.com/2017/05/05/Saving-Bot-Actions-On-Azure-Sql-Server/ from microsoft.

But in the step that i have to add a project of  Class Library (.NET Framework) i found in my project only  Class Library (.NET Core). I'm using Visual Studio 2015 .  I made all the steps that this documents propose but i not able to link database created in azure with my project, and make it work.

I try to create a local database...i publish my project , and then my bot cannot start conversations.

Do you have any idea how to save all the conversations of my bot in SQL server database

答: You just have to download and install Microsoft .Net Framework SDK. You can try .Net Framework 4.5.2 from this link</p>


问:
Can I host two separate web servers on a LAN to the outside world through 1 IP address?
I am a web programmer with a home web dev operation. I have multiple web servers in my house on a FIOS connection. I have my own domain pointed to my router through dyndns.org's custom domain service.

My ISP gives me ONE static IP address, which at the moment allows me to configure my router to direct outbound web traffic from one server through port 80 and another server through port 8080. This sucks because many companies block port 8080 these days causing some of my corporate clients to not be able to hit my second web server.

Is there any way for me to direct regular old port 80 web traffic to TWO SEPARATE web servers internally on my network using two separate host names?

For instance. I want http://webserver1.mydomain.com to hit one web server on my network, and http://webserver2.mydomain.com to hit another web server and have both sets of traffic served on port 80.

Is this even possible? If not, can I do a hack by programmatically routing traffic from one web server transparently to another?

For the record I run MS Windows Server 2008 IIS 7.0 stack, a D-link DIR-655 router, and use DynDNS for my domain needs.

答:
You might be able to set up apache with 2 vhosts, and then in each of their blocks put a proxy of the appropriate site on your local network:

In vhost 1:

```<code>ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass / http://192.168.0.49/
ProxyPassReverse / http://192.168.0.49/
</code>```

In vhost 2:

```<code>ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass / http://192.168.0.50/
ProxyPassReverse / http://192.168.0.50/
</code>```

You'd need mod_proxy, and I'm not even sure this would work

OwnerDisplayName: Matias Nino

Body:
You might be able to set up apache with 2 vhosts, and then in each of their blocks put a proxy of the appropriate site on your local network:

In vhost 1:

ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass / http://192.168.0.49/
ProxyPassReverse / http://192.168.0.49/

In vhost 2:

ProxyRequests Off

<Proxy *>
Order deny,allow
Allow from all
</Proxy>

ProxyPass / http://192.168.0.50/
ProxyPassReverse / http://192.168.0.50/

You'd need mod_proxy, and I'm not even sure this would work

OwnerDisplayName: FryGuy


问:
jquery validation working on some browsers, but not on others
Why does this work for some people, and doesn't for others? Others just click the button and it doesn't work. It started doing that after I added the nospaces validation method. Any suggestions would be very much appreciated.

```<code><form method="post" action="#" id="client_form" class="order-form">
<input type="text" id="user_name" name="user_name" class="req nospaces" />
</form>
 <button id="client_next_btn"><?php echo($content->getString('order')); ?></button>
<script type="text/javascript">

$(function ()
{
jQuery.validator.addClassRules('req', { required: function (el) { return $(el).is(':visible') } });

var nums = ['0','1','2','3','4','5','6','7','8','9'];
var letters = ['q','w','e','r','t','y','u','i','o','p','a','s','d','f','g','h','j','k','l','z','x','c','v','b','n','m'];
var alphanumeric = nums.concat(letters);

jQuery.validator.addMethod("nospaces", function(value, element) {
    var val = value.split("");
    var bool = true;
    for (var i in val)
    {
        if (jQuery.inArray(val[i], alphanumeric) == -1)
        {
            bool = false;
            break;
        }
    }
    return bool;
}, "* <?php echo ($content->getString('no_spaces')); ?>");

$('#client_form').validate();
$('#client_next_btn').click(function ()
{
    $('#client_message').empty();

    if ($('#client_form').validate().form())
    {
                alert('works');
            }
    }
</code>```

}

答: Just after I posted the question, I figured out the answer - addMethod has to go together with addClassRules and not by itself</p>

Body:
Why does this work for some people, and doesn't for others? Others just click the button and it doesn't work. It started doing that after I added the nospaces validation method. Any suggestions would be very much appreciated.

<form method="post" action="#" id="client_form" class="order-form">
<input type="text" id="user_name" name="user_name" class="req nospaces" />
</form>
 <button id="client_next_btn"><?php echo($content->getString('order')); ?></button>