问:
Apache Spark -- Data Grouping and Execution in worker nodes
We are getting live machine data as json and we get this data from RabbitMQ. below is a sample of the json,

{"DeviceId":"MAC-1001","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:35","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}
{"DeviceId":"MAC-1001","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:36","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}
{"DeviceId":"MAC-1002","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:37","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}
{"DeviceId":"MAC-1002","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:38","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}```
</div>
</div>
</p>

<p>The data is windowed for duration of 'X' minutes and then below is what we want to achieve</p>

<ol>
<li><p>Group the data by deviceId, this is done but not sure if we can get a DataSet</p></li>
<li><p>We want to loop through the above grouped data and execute for aggregation logic for each device using the foreachPartition so that the code is executed within worker nodes.</p></li>
</ol>

<p>Please correct me if my thought process is wrong here.</p>

<p>Our earlier code was collecting the data,looping through the RDD's,convert them to DataSet and applying aggregation logic on the DataSet using Spark SqlContext api's.</p>

<p>When doing load testing we saw 90% of the processing was happening in Master node and after a while the cpu usage spiked to 100% and the process bombed out.</p>

<p>So we are now trying to re-engineer the whole process to execute maximum of logic in worker nodes.</p>

<p>Below is the code so far that actually works in worker node but we are yet to get a DataSet for aggregating Logic</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public static void main(String[] args) {

  try {

   mconf = new SparkConf();
   mconf.setAppName("OnPrem");
   mconf.setMaster("local[*]");

   JavaSparkContext sc = new JavaSparkContext(mconf);

   jssc = new JavaStreamingContext(sc, Durations.seconds(60));

   SparkSession spksess = SparkSession.builder().appName("Onprem").getOrCreate();
   //spksess.sparkContext().setLogLevel("ERROR");

   Map<String, String> rabbitMqConParams = new HashMap<String, String>();
   rabbitMqConParams.put("hosts", "localhost");
   rabbitMqConParams.put("userName", "guest");
   rabbitMqConParams.put("password", "guest");
   rabbitMqConParams.put("vHost", "/");
   rabbitMqConParams.put("durable", "true");

   List<JavaRabbitMQDistributedKey> distributedKeys = new LinkedList<JavaRabbitMQDistributedKey>();
   distributedKeys.add(new JavaRabbitMQDistributedKey(QUEUE_NAME, new ExchangeAndRouting(EXCHANGE_NAME, "fanout", ""), rabbitMqConParams));

   Function<Delivery, String> messageHandler = new Function<Delivery, String>() {

    public String call(Delivery message) {
     return new String(message.getBody());
    }
   };

   JavaInputDStream<String> messages = RabbitMQUtils.createJavaDistributedStream(jssc, String.class, distributedKeys, rabbitMqConParams, messageHandler);

   JavaDStream<String> machineDataRDD = messages.window(Durations.minutes(2),Durations.seconds(60)); //every 60 seconds one RDD is Created
   machineDataRDD.print();

   JavaPairDStream<String, String> pairedData = machineDataRDD.mapToPair(s -> new Tuple2<String, String>(getMap(s).get("DeviceId").toString(), s));

   JavaPairDStream<String, Iterable<String>> groupedData = pairedData.groupByKey();

   groupedData.foreachRDD(new VoidFunction<JavaPairRDD<String,Iterable<String>>>(){

    @Override
    public void call(JavaPairRDD<String, Iterable<String>> data) throws Exception {

     data.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Iterable<String>>>>(){

      @Override
      public void call(Iterator<Tuple2<String, Iterable<String>>> data) throws Exception {

        while(data.hasNext()){
         LOGGER.error("Machine Data == >>"+data.next());
        }
      }

     });

    }

   });
   jssc.start();
   jssc.awaitTermination();

  }
  catch (Exception e)
  {
   e.printStackTrace();
  }</code>```

The below grouping code gives us a Iterable of string for a Device , ideally we would like to get a DataSet

JavaPairDStream<String, String> pairedData = machineDataRDD.mapToPair(s -> new Tuple2<String, String>(getMap(s).get("DeviceId").toString(), s));
JavaPairDStream<String, Iterable<String>> groupedData = pairedData.groupByKey();```

Important thing for me is the looping using foreachPartition so that code executing gets pushed to Worker Nodes.

答: After looking through more code samples and guidelines sqlcontext , sparksession are not serialized and available on the worker nodes , so we will be changing the strategy of not trying to build a dataset withing foreachpartition loop.</p>

Body:
We are getting live machine data as json and we get this data from RabbitMQ. below is a sample of the json,

{"DeviceId":"MAC-1001","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:35","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}
{"DeviceId":"MAC-1001","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:36","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}
{"DeviceId":"MAC-1002","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:37","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}
{"DeviceId":"MAC-1002","DeviceType":"Sim-1","TimeStamp":"05-12-2017 10:25:38","data":{"Rate":10,"speed":2493,"Mode":1,"EMode":2,"Run":1}}

The data is windowed for duration of 'X' minutes and then below is what we want to achieve

Group the data by deviceId, this is done but not sure if we can get a DataSet

We want to loop through the above grouped data and execute for aggregation logic for each device using the foreachPartition so that the code is executed within worker nodes.

Please correct me if my thought process is wrong here.

Our earlier code was collecting the data,looping through the RDD's,convert them to DataSet and applying aggregation logic on the DataSet using Spark SqlContext api's.

When doing load testing we saw 90% of the processing was happening in Master node and after a while the cpu usage spiked to 100% and the process bombed out.

So we are now trying to re-engineer the whole process to execute maximum of logic in worker nodes.

Below is the code so far that actually works in worker node but we are yet to get a DataSet for aggregating Logic

public static void main(String[] args) {

  try {

   mconf = new SparkConf();
   mconf.setAppName("OnPrem");
   mconf.setMaster("local[*]");

   JavaSparkContext sc = new JavaSparkContext(mconf);

   jssc = new JavaStreamingContext(sc, Durations.seconds(60));

   SparkSession spksess = SparkSession.builder().appName("Onprem").getOrCreate();
   //spksess.sparkContext().setLogLevel("ERROR");

   Map<String, String> rabbitMqConParams = new HashMap<String, String>();
   rabbitMqConParams.put("hosts", "localhost");
   rabbitMqConParams.put("userName", "guest");
   rabbitMqConParams.put("password", "guest");
   rabbitMqConParams.put("vHost", "/");
   rabbitMqConParams.put("durable", "true");

   List<JavaRabbitMQDistributedKey> distributedKeys = new LinkedList<JavaRabbitMQDistributedKey>();
   distributedKeys.add(new JavaRabbitMQDistributedKey(QUEUE_NAME, new ExchangeAndRouting(EXCHANGE_NAME, "fanout", ""), rabbitMqConParams));

   Function<Delivery, String> messageHandler = new Function<Delivery, String>() {

    public String call(Delivery message) {
     return new String(message.getBody());
    }
   };

   JavaInputDStream<String> messages = RabbitMQUtils.createJavaDistributedStream(jssc, String.class, distributedKeys, rabbitMqConParams, messageHandler);

   JavaDStream<String> machineDataRDD = messages.window(Durations.minutes(2),Durations.seconds(60)); //every 60 seconds one RDD is Created
   machineDataRDD.print();

   JavaPairDStream<String, String> pairedData = machineDataRDD.mapToPair(s -> new Tuple2<String, String>(getMap(s).get("DeviceId").toString(), s));

   JavaPairDStream<String, Iterable<String>> groupedData = pairedData.groupByKey();

   groupedData.foreachRDD(new VoidFunction<JavaPairRDD<String,Iterable<String>>>(){

    @Override
    public void call(JavaPairRDD<String, Iterable<String>> data) throws Exception {

     data.foreachPartition(new VoidFunction<Iterator<Tuple2<String,Iterable<String>>>>(){

      @Override
      public void call(Iterator<Tuple2<String, Iterable<String>>> data) throws Exception {

        while(data.hasNext()){
         LOGGER.error("Machine Data == >>"+data.next());
        }
      }

     });

    }

   });
   jssc.start();
   jssc.awaitTermination();

  }
  catch (Exception e)
  {
   e.printStackTrace();
  }

The below grouping code gives us a Iterable of string for a Device , ideally we would like to get a DataSet

JavaPairDStream<String, String> pairedData = machineDataRDD.mapToPair(s -> new Tuple2<String, String>(getMap(s).get("DeviceId").toString(), s));
JavaPairDStream<String, Iterable<String>> groupedData = pairedData.groupByKey();

Important thing for me is the looping using foreachPartition so that code executing gets pushed to Worker Nodes.


来源: stackexchange

问:
How to get the old value in a textbox before I submit it in angularjs?

I want to get the old value in a textbox and save it in a temporary variable where I can use it if I click a cancel/reset button

part of the client.html

```<code><input type="text" id="txtage" placeholder="Age" data-ng-model="vm.client.age" />
<button type="submit" data-ng-click="cancel()"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
</code>```

client.js file

```<code>var vm = this;
vm.clients = [];
vm.client = {
        id: '',
        age: ''
    };
vm.cancel = cancel;
 function cancel() {
        clientService.cancel(vm.client);
        getClients();
    }
function getClients() {
        vm.clients = clientService.get();
    }
</code>```

clientService.js

```<code> function cancel(client) {

        newValue[] = clients;
        cancel_lagi = function (newvalue, oldvalue) {
        clients.new = 'New Value :' + clients.newValue;
        clients.old = 'Old Value :' + $scopes.oldValue;
        clients.oldvalue = oldvalue;
        client.newValue = oldvalue;
        }
    }
</code>```

if i click a data from the table and try to change its values in a textfield. After changing it I might change my mind so when I click the cancel button it will return to its old value.

when I click the cancel button the fields that I try to edit will return to its old value.

答:
You could introduce another variable to keep track of the old value when edit is clicked. Then in cancel you can reset the value. In pseudocode:</p>

```<code>editClicked(client) {
   vm.client = angular.copy(client);
   vm.originalClient = client;
}

cancelClicked() {
    vm.client = vm.originalClient;
    vm.originalClient = null;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to get the old value in a textbox and save it in a temporary variable where I can use it if I click a cancel/reset button

part of the client.html

<input type="text" id="txtage" placeholder="Age" data-ng-model="vm.client.age" />
<button type="submit" data-ng-click="cancel()"> Cancel</button>

client.js file

var vm = this;
vm.clients = [];
vm.client = {
        id: '',
        age: ''
    };
vm.cancel = cancel;
 function cancel() {
        clientService.cancel(vm.client);
        getClients();
    }
function getClients() {
        vm.clients = clientService.get();
    }

clientService.js

 function cancel(client) {

        newValue[] = clients;
        cancel_lagi = function (newvalue, oldvalue) {
        clients.new = 'New Value :' + clients.newValue;
        clients.old = 'Old Value :' + $scopes.oldValue;
        clients.oldvalue = oldvalue;
        client.newValue = oldvalue;
        }
    }

if i click a data from the table and try to change its values in a textfield. After changing it I might change my mind so when I click the cancel button it will return to its old value.

when I click the cancel button the fields that I try to edit will return to its old value.

Body:
You could introduce another variable to keep track of the old value when edit is clicked. Then in cancel you can reset the value. In pseudocode:

editClicked(client) {
   vm.client = angular.copy(client);
   vm.originalClient = client;
}

cancelClicked() {
    vm.client = vm.originalClient;
    vm.originalClient = null;
}


问:
Chrome Extension blocking webRequest doesnt seem to be working at all
I am just trying to get the MDN example chrome extension working. here is the manifest.json

```<code>{
  "description": "Altering HTTP responses",
  "manifest_version": 2,
  "name": "http-response-filter",
  "version": "1.0",
  "homepage_url":
    "https://github.com/mdn/webextensions-examples/tree/master/http-response",
  "icons": {
    "48": "SA-48x48.png"
  },

  "background": {
    "scripts": ["background.js"]
  }
}
</code>```

and here is the background.js

```<code>function listener(details) {
  console.log("******listen");
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");
  let encoder = new TextEncoder();

  filter.ondata = event => {
    let str = decoder.decode(event.data, { stream: true });
    // Just change any instance of Example in the HTTP response
    // to WebExtension Example.
    str = str.replace(/Example/g, "WebExtension Example");
    filter.write(encoder.encode(str));
    filter.disconnect();
  };

  return {};
}
console.log("******");
browser.webRequest.onBeforeRequest.addListener(
  listener,
  { urls: ["https://example.com/*"], types: ["main_frame"] },
  ["blocking"]
);
</code>```

So i expect it to

put a couple console.logs out when i load example.com

modify "Example" to "WebExtension Example" as stated by the MDN folks

however, it doesn't work at all for me (I am using Chrome and i added it to my Extensions as an unpacked Extension, i've done other chrome extensions before but this is my first time doing a background script).

Is it possible that something is blocking this background script from running? have i just not configured it in the right way? Please point me in the right direction, thanks very much.

答:
Your Chrome Extension needs to "ask" for permissions to use the webRequest API so that users of the extension will get notified what the extension may be able to do.

Try adding this to your manifest.json:

```<code>"permissions": [
    "webRequest",
    "webRequestBlocking"
]
</code>```

Body:
I am just trying to get the MDN example chrome extension working. here is the manifest.json

{
  "description": "Altering HTTP responses",
  "manifest_version": 2,
  "name": "http-response-filter",
  "version": "1.0",
  "homepage_url":
    "https://github.com/mdn/webextensions-examples/tree/master/http-response",
  "icons": {
    "48": "SA-48x48.png"
  },

  "background": {
    "scripts": ["background.js"]
  }
}

and here is the background.js

function listener(details) {
  console.log("******listen");
  let filter = browser.webRequest.filterResponseData(details.requestId);
  let decoder = new TextDecoder("utf-8");
  let encoder = new TextEncoder();

  filter.ondata = event => {
    let str = decoder.decode(event.data, { stream: true });
    // Just change any instance of Example in the HTTP response
    // to WebExtension Example.
    str = str.replace(/Example/g, "WebExtension Example");
    filter.write(encoder.encode(str));
    filter.disconnect();
  };

  return {};
}
console.log("******");
browser.webRequest.onBeforeRequest.addListener(
  listener,
  { urls: ["https://example.com/*"], types: ["main_frame"] },
  ["blocking"]
);

So i expect it to

put a couple console.logs out when i load example.com

modify "Example" to "WebExtension Example" as stated by the MDN folks

however, it doesn't work at all for me (I am using Chrome and i added it to my Extensions as an unpacked Extension, i've done other chrome extensions before but this is my first time doing a background script).

Is it possible that something is blocking this background script from running? have i just not configured it in the right way? Please point me in the right direction, thanks very much.

Body:
Your Chrome Extension needs to "ask" for permissions to use the webRequest API so that users of the extension will get notified what the extension may be able to do.

Try adding this to your manifest.json:

"permissions": [
    "webRequest",
    "webRequestBlocking"
]


问:
x86 or x64 disassembler lib
I know o some disassemble libs , but what I'm looking for is one that has an api like:

```<code>void * findAddrOfFirstInstructionStartingFrom( void * startAddress , InstructionType instruction);

void* addr = findAddrOfFirstInstructionStartingFrom(startAddress , JMP);
</code>```

and other apis smiler to this one like search for something specific not disassemble all instructions stating from an address and get all sorts of info because it slow if you only want to find something specific not everything.

If you know any pls let me know , if there isn't any pls tell me one that is open source and easy to modify.

答:
You did not tag nor tell the processor architecture, so it is unlikely that you get a real answer.

Commonly native code instructions are with very varying length depending on operands they take  so you have to disassemble the thing before searching. Otherwise you just find first sequence of bytes that matches the pattern of instruction you search for. It is most likely not a real instruction but part of operands of previous instruction.

EDIT: Since you updated title, i can think of choices Borg and PEDasm are open source. If you drop that open-source thing then definitely IDA pro.

ContentLicense: CC BY-SA 2.5

Title: x86 or x64 disassembler lib

Body:
I know o some disassemble libs , but what I'm looking for is one that has an api like:

void * findAddrOfFirstInstructionStartingFrom( void * startAddress , InstructionType instruction);

void* addr = findAddrOfFirstInstructionStartingFrom(startAddress , JMP);

and other apis smiler to this one like search for something specific not disassemble all instructions stating from an address and get all sorts of info because it slow if you only want to find something specific not everything.

If you know any pls let me know , if there isn't any pls tell me one that is open source and easy to modify.


问:
Image click will load specific text in an array
I have an array of images, and an array of text. There are 3 images on the page. I would like to have the user click on an image, and depending on which image they choose, a different text will pop up. I am having trouble getting the click to work on the images and getting to the appropriate text. Clicking image1.jpg will get you item 0 in the transText Array, and so on.

Here are my arrays of images and text

```<code>var images =["image1.jpg","image2.jpg","image3.jpg","image4.jpg","image5.jpg","image6.jpg"];
var picNames =["Double Bacon Cheeseburger", "Fresh Fruit", "Oatmeal", "Hummer SUV", "Subway", "Bicycle"];
var transText = ["Meat produces up to 16 pounds of C02 per 1 lb of meat, and requires 1,847 gallons of water to produce", "Fresh fruit, while requiring less water to produce,\n is often brought in from far away,\n adding to carbon emissions.\n They also can spoil quickly.", "Cereal grains require low water amounts to produce,\n have a long shelf life, \n and are readily available all year round in all parts of the country", "A Hummer SUV will produce 813 grams of C02 per mile.\n The average commuter will travel 30 miles each day round trip. \n That's 24.54 kg of C02. \n Every day.", "Subways emit X amount of C02 per day.", "The best source of energy for travel is yourself.\n Biking or walking is the least harmful way to travel"];
var playTrack = false;
var imageNum = 0;

//Image Loading Loop
for (var i = 0; i < images.length; i++) {
var imageObj = images[i];
imageObj.src = "images/" + images[i];
imageObj.onload= (function(i){
            return function(){

            }
        })(i);
}
</code>```

Here is where I am trying to load the next image on click

```<code>function nextImage() {
    document.getElementById("imageWindow").src = "images/" + images[imageNum];
    imageNum++
    if (imageNum === images.length) imageNum = 0;
        else
        playTrack = true;
        document.getElementById("imageWindow").innerHTML;
}
</code>```

Here is my HTML

```<code></script>
</head>
<body>
<div><a href="#" onclick="nextImage('changeState')"></a></div>
<div>
<img id="imageWindow" src="images/image1.jpg" HEIGHT="300">
</div>
<h3 id = "picNames(0)">Double Bacon Cheeseburger</h1>
<p></p>
<div>
<img id="imageWindow" src="images/image2.jpg" HEIGHT ="300">
<h3 id = "picNames(1)">Fresh Fruit</h1>
<p></p>
<div>
<img id="imageWindow" src="images/image3.jpg" HEIGHT ="300">
</div>
<h3 id = "picNames(2)">Oatmeal</h1>

<script>
</code>```

答:
I added span tags along with your images which have display property set to none. Onclick of an image, the span innerHTML is set to the array text.</p>

```<code>   <div><a href="#" onclick="nextImage('changeState')"></a></div>
    <div>
    <img id="imageWindow" src="images/image1.jpg" HEIGHT="300" onclick="myFunction(0);">
    <span class="popuptext" id="popup0" style="display:none;"></span>
    </div>
    <h3 id = "picNames0">Double Bacon Cheeseburger</h1>
    <p></p>
    <div>
    <img id="imageWindow" src="images/image2.jpg" HEIGHT ="300" onclick="myFunction(1);">
    <h3 id = "picNames1">Fresh Fruit</h3>
    <span class="popuptext" id="popup1" style="display:none;"></span>
    <p></p>
    </div>
    <div>
    <img id="imageWindow" src="images/image3.jpg" HEIGHT ="300" onclick="myFunction(2);">
    </div>
    <h3 id = "picNames2">Oatmeal</h3>
    <span class="popuptext" id="popup2" style="display:none;"></span>

<script>

var images =["images/book2.jpg","images/book3.jpg","images/book4.jpg","image4.jpg","image5.jpg","image6.jpg"];
var picNames =["Double Bacon Cheeseburger", "Fresh Fruit", "Oatmeal", "Hummer SUV", "Subway", "Bicycle"];
var transText = ["Meat produces up to 16 pounds of C02 per 1 lb of meat, and requires 1,847 gallons of water to produce", "Fresh fruit, while requiring less water to produce,\n is often brought in from far away,\n adding to carbon emissions.\n They also can spoil quickly.", "Cereal grains require low water amounts to produce,\n have a long shelf life, \n and are readily available all year round in all parts of the country", "A Hummer SUV will produce 813 grams of C02 per mile.\n The average commuter will travel 30 miles each day round trip. \n That's 24.54 kg of C02. \n Every day.", "Subways emit X amount of C02 per day.", "The best source of energy for travel is yourself.\n Biking or walking is the least harmful way to travel"];
var playTrack = false;
var imageNum = 0;

//Image Loading Loop
for (var i = 0; i < images.length; i++) {
var imageObj = images[i];
imageObj.src = "images/" + images[i];
imageObj.onload= (function(i){
            return function(){

            };
        })(i);
}

function nextImage() {
    document.getElementById("imageWindow").src = "images/" + images[imageNum];
    imageNum++;
    if (imageNum === images.length) imageNum = 0;
        else
        playTrack = true;
        document.getElementById("imageWindow").innerHTML;
}

// When the user clicks on <image>, open the popup
function myFunction(n) {
    // hide already opend popups by class name
    function hideAll() {
        var allPopups = document.getElementsByClassName("popuptext");
        for(var i = 0; i < allPopups.length; i++){
            allPopups[i].style.display = "none";
        }

    }
    hideAll();

    var thisPopup = "popup" + n;
    var popup = document.getElementById(thisPopup);
    popup.innerHTML = transText[n];
    popup.style.display = "block";

    // hide all popups again after a minute
    setTimeout(hideAll, 60000);

}

</script>
</code>```

Body:
I have an array of images, and an array of text. There are 3 images on the page. I would like to have the user click on an image, and depending on which image they choose, a different text will pop up. I am having trouble getting the click to work on the images and getting to the appropriate text. Clicking image1.jpg will get you item 0 in the transText Array, and so on.

Here are my arrays of images and text

var images =["image1.jpg","image2.jpg","image3.jpg","image4.jpg","image5.jpg","image6.jpg"];
var picNames =["Double Bacon Cheeseburger", "Fresh Fruit", "Oatmeal", "Hummer SUV", "Subway", "Bicycle"];
var transText = ["Meat produces up to 16 pounds of C02 per 1 lb of meat, and requires 1,847 gallons of water to produce", "Fresh fruit, while requiring less water to produce,\n is often brought in from far away,\n adding to carbon emissions.\n They also can spoil quickly.", "Cereal grains require low water amounts to produce,\n have a long shelf life, \n and are readily available all year round in all parts of the country", "A Hummer SUV will produce 813 grams of C02 per mile.\n The average commuter will travel 30 miles each day round trip. \n That's 24.54 kg of C02. \n Every day.", "Subways emit X amount of C02 per day.", "The best source of energy for travel is yourself.\n Biking or walking is the least harmful way to travel"];
var playTrack = false;
var imageNum = 0;

//Image Loading Loop
for (var i = 0; i < images.length; i++) {
var imageObj = images[i];
imageObj.src = "images/" + images[i];
imageObj.onload= (function(i){
            return function(){

            }
        })(i);
}

Here is where I am trying to load the next image on click

function nextImage() {
    document.getElementById("imageWindow").src = "images/" + images[imageNum];
    imageNum++
    if (imageNum === images.length) imageNum = 0;
        else
        playTrack = true;
        document.getElementById("imageWindow").innerHTML;
}

Here is my HTML

</script>

Double Bacon Cheeseburger

Fresh Fruit

Oatmeal

Body:
I added span tags along with your images which have display property set to none. Onclick of an image, the span innerHTML is set to the array text.

   <div><a href="#" onclick="nextImage('changeState')"></a></div>
    <div>
    <img id="imageWindow" src="images/image1.jpg" HEIGHT="300" onclick="myFunction(0);">
    <span class="popuptext" id="popup0" style="display:none;"></span>
    </div>
    <h3 id = "picNames0">Double Bacon Cheeseburger</h1>
    <p></p>
    <div>
    <img id="imageWindow" src="images/image2.jpg" HEIGHT ="300" onclick="myFunction(1);">
    <h3 id = "picNames1">Fresh Fruit</h3>
    <span class="popuptext" id="popup1" style="display:none;"></span>
    <p></p>
    </div>
    <div>
    <img id="imageWindow" src="images/image3.jpg" HEIGHT ="300" onclick="myFunction(2);">
    </div>
    <h3 id = "picNames2">Oatmeal</h3>
    <span class="popuptext" id="popup2" style="display:none;"></span>

<script>

var images =["images/book2.jpg","images/book3.jpg","images/book4.jpg","image4.jpg","image5.jpg","image6.jpg"];
var picNames =["Double Bacon Cheeseburger", "Fresh Fruit", "Oatmeal", "Hummer SUV", "Subway", "Bicycle"];
var transText = ["Meat produces up to 16 pounds of C02 per 1 lb of meat, and requires 1,847 gallons of water to produce", "Fresh fruit, while requiring less water to produce,\n is often brought in from far away,\n adding to carbon emissions.\n They also can spoil quickly.", "Cereal grains require low water amounts to produce,\n have a long shelf life, \n and are readily available all year round in all parts of the country", "A Hummer SUV will produce 813 grams of C02 per mile.\n The average commuter will travel 30 miles each day round trip. \n That's 24.54 kg of C02. \n Every day.", "Subways emit X amount of C02 per day.", "The best source of energy for travel is yourself.\n Biking or walking is the least harmful way to travel"];
var playTrack = false;
var imageNum = 0;

//Image Loading Loop
for (var i = 0; i < images.length; i++) {
var imageObj = images[i];
imageObj.src = "images/" + images[i];
imageObj.onload= (function(i){
            return function(){

            };
        })(i);
}

function nextImage() {
    document.getElementById("imageWindow").src = "images/" + images[imageNum];
    imageNum++;
    if (imageNum === images.length) imageNum = 0;
        else
        playTrack = true;
        document.getElementById("imageWindow").innerHTML;
}

// When the user clicks on <image>, open the popup
function myFunction(n) {
    // hide already opend popups by class name
    function hideAll() {
        var allPopups = document.getElementsByClassName("popuptext");
        for(var i = 0; i < allPopups.length; i++){
            allPopups[i].style.display = "none";
        }

    }
    hideAll();

    var thisPopup = "popup" + n;
    var popup = document.getElementById(thisPopup);
    popup.innerHTML = transText[n];
    popup.style.display = "block";

    // hide all popups again after a minute
    setTimeout(hideAll, 60000);

}

</script>


问:
Write listeners for Views getting from OnItemClickListener
List View and Custom Adapter in different classes.
Custom Adapter have 2 textViews

In OnItemClickListener i created listeners for textviews.
TextView listeners some time working some time not working.

```<code>listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int pos, final long id) {

            TextView tv1 = (TextView) view.findViewById(R.id.tv1);

            tv1.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    Toast.makeText(act, "tv1 clicked", 300).show();
                }
            });

            TextView tv2 = (TextView) view.findViewById(R.id.tv2);

            tv2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Toast.makeText(act, "tv2 clicked", 300).show();
                }
            });

            // listViewListeners(parent, view, pos, id);
        }
    });
</code>```

答:
You are trying to register click event on child views when clicked on parent, so for the first time it won't work as parent will take the touch from user, but based on child element elevation and event listener, it takes clicks from child.

To avoid those use interface

```<code>interface ClickListener{
  void tvOneClicked(int position);
  void tvTwoClicked(int position);
}
</code>```

and while calling your adapter from activity pass above interface as in

```<code>adapter = new CustomAdapter(this,some_layout,somedata, new ClickListener(){
     @Override
     public void tvOneClicked(int position){
        //Toast.makeText(act, "tv1 clicked", 300).show();
     }

     @Override
     public void tvOneClicked(int position){
        //Toast.makeText(act, "tv2 clicked", 300).show();
     }});
</code>```

And in your Adapter, use this to call activity when any of your textview
clicked

```<code>private ClickListener clickListener;
 public CustomAdapter(Activity act,int layout,List<> data, ClickListener listener){
    this.clickListener = listener;
 }

 public void getView(...){

   ...
    tv1.setOnClickListener(new OnClickListener() {
                @override
                public void onClick(View v) {
                     clickListener.onOneClicked(position);
                }
            });
            tv2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    clickListener.onTwoClicked(position);
                }
            });
   ...
  }
</code>```

Body:
List View and Custom Adapter in different classes.
Custom Adapter have 2 textViews

In OnItemClickListener i created listeners for textviews.
TextView listeners some time working some time not working.

listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int pos, final long id) {

            TextView tv1 = (TextView) view.findViewById(R.id.tv1);

            tv1.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    Toast.makeText(act, "tv1 clicked", 300).show();
                }
            });

            TextView tv2 = (TextView) view.findViewById(R.id.tv2);

            tv2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Toast.makeText(act, "tv2 clicked", 300).show();
                }
            });

            // listViewListeners(parent, view, pos, id);
        }
    });

Body:
You are trying to register click event on child views when clicked on parent, so for the first time it won't work as parent will take the touch from user, but based on child element elevation and event listener, it takes clicks from child.

To avoid those use interface

interface ClickListener{
  void tvOneClicked(int position);
  void tvTwoClicked(int position);
}

and while calling your adapter from activity pass above interface as in

adapter = new CustomAdapter(this,some_layout,somedata, new ClickListener(){
     @Override
     public void tvOneClicked(int position){
        //Toast.makeText(act, "tv1 clicked", 300).show();
     }

     @Override
     public void tvOneClicked(int position){
        //Toast.makeText(act, "tv2 clicked", 300).show();
     }});

And in your Adapter, use this to call activity when any of your textview
clicked

private ClickListener clickListener;
 public CustomAdapter(Activity act,int layout,List<> data, ClickListener listener){
    this.clickListener = listener;
 }

 public void getView(...){

   ...
    tv1.setOnClickListener(new OnClickListener() {
                @override
                public void onClick(View v) {
                     clickListener.onOneClicked(position);
                }
            });
            tv2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    clickListener.onTwoClicked(position);
                }
            });
   ...
  }


问:
Error: [ng:areq] Argument 'CartCrtl' is not a function, got undefined
Here I'm trying to add products from the products list to the cart.Products list is in the ProductCrtl. Using CartCrtl I'm trying to get the product values.

How can I fix the above error?

My Code-

```<code><!doctype html>
<html lang="en" ng-app="MyApp4">
<head>
  <meta charset="utf-8">
  <title>Controllers</title>
  <script src="angular.js"></script>
    <script src="app4.js"></script>
  </head>
<body  ng-controller="MyApp4Crtl">
    <table  ng-controller="ProductCtrl">
        <h1>Products</h1>
        <thead>
            <tr>
                <th>#</th>
                <th>Product Name</th>
                <th>Price</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="product in products">
                <td>{{$index+1}}</td>
                <td>{{product.name}}</td>
                <td>{{product.price | currency}}</td>
                <td><button ng-click=addToCart(product)>Add to Cart</button></td>
            </tr>
        </tbody>
    </table>

    <div ng-controller="CartCrtl">
        <h1>Cart</h1>
    Adding products!
    </div>
</body>
</html>
</code>```

app4.js

```<code>name="MyApp4";
requires=[];
app4=angular.module(name,requires);

app4.controller("MyApp4Crtl",function($scope){
$scope.name1="Aluuu!";

});
app4.controller("ProductCtrl",function($scope,$rootScope){
$scope.products=[{name:"Computer",price:233},
                  {name:"Book",price:20},
                  {name:"Pen",price:2000},
                  {name:"Pencil",price:10},
                  {name:"box",price:11},
                  {name:"Laptop",price:10000},
                  {name:"CD",price:34},
                  {name:"DVD",price:3}
  ];
  $scope.addToCart=function(item){
    $rootScope.$broadcast("addProductEvent",item);
  }
});

app4.controller("CartCtrl",function($scope){
$scope.cartItems=[];

$scope.$on("addProductEvent",addingCartFunction);
function addingCartFunction(evt,product){
  $scope.cartItems.push(product);
}

});
</code>```

The Cartctrl is not defined.I have included the ng-app in the html tag also.

答:
I think it is wrong type with  </p>

```<code><div ng-controller="CartCrtl">

<div ng-controller="CartCtrl">
</code>```

Body:
Here I'm trying to add products from the products list to the cart.Products list is in the ProductCrtl. Using CartCrtl I'm trying to get the product values.

How can I fix the above error?

My Code-

<!doctype html>

  <meta charset="utf-8">
  <title>Controllers</title>

Products

                #
                Product Name
                Price

                {{$index+1}}
                {{product.name}}
                {{product.price | currency}}
                <button ng-click=addToCart(product)>Add to Cart</button>

Cart

    Adding products!

app4.js

name="MyApp4";
requires=[];
app4=angular.module(name,requires);

app4.controller("MyApp4Crtl",function($scope){
$scope.name1="Aluuu!";

});
app4.controller("ProductCtrl",function($scope,$rootScope){
$scope.products=[{name:"Computer",price:233},
                  {name:"Book",price:20},
                  {name:"Pen",price:2000},
                  {name:"Pencil",price:10},
                  {name:"box",price:11},
                  {name:"Laptop",price:10000},
                  {name:"CD",price:34},
                  {name:"DVD",price:3}
  ];
  $scope.addToCart=function(item){
    $rootScope.$broadcast("addProductEvent",item);
  }
});

app4.controller("CartCtrl",function($scope){
$scope.cartItems=[];

$scope.$on("addProductEvent",addingCartFunction);
function addingCartFunction(evt,product){
  $scope.cartItems.push(product);
}

});

The Cartctrl is not defined.I have included the ng-app in the html tag also.

Body:
I think it is wrong type with

<div ng-controller="CartCrtl">

<div ng-controller="CartCtrl">


问:
How can I change docker network ip address in Mac
I have met an annoying issue when I run Docker in my Mac and hope to get your help.
The issue is my company's internal git repository is on address 172.17.28.245, and this IP address is in conflicts with default docker network IP address, 172.17.0.0. So whenever I am running below command, I am having this issue

```<code>Ping git.xxx.net
Then I have
PING git.xxx.net (172.17.28.245) 56(84) bytes of data.
From 08be4336c264 (172.17.0.2) icmp_seq=1 Destination Host Unreachable
From 08be4336c264 (172.17.0.2) icmp_seq=2 Destination Host Unreachable
From 08be4336c264 (172.17.0.2) icmp_seq=3 Destination Host Unreachable
</code>```

So, can anyone help me to figure out how I can resolve this issue in mac?

I am using  Docker QuickStart Terminal in Mac to start.

Thanks

答:
In recent versions of Docker for mac, you can change Docker's subnet under Preferences -> Advanced -> Docker subnet.

Set it to 192.168.50.0 for instance.

For even more fine-grained control of subnets used by Docker for mac, go to Preferences -> Daemon -> Advanced and add configuration according to the syntax in this comment:

{
    "bip":"xx.xx.xx.x/xx",
    "dns-search":[" xx.xx.x.xx"],
    "dns": [" xx.xx.x.xx"," xx.xx.x.xx"]
}

Body:
I have met an annoying issue when I run Docker in my Mac and hope to get your help.
The issue is my company's internal git repository is on address 172.17.28.245, and this IP address is in conflicts with default docker network IP address, 172.17.0.0. So whenever I am running below command, I am having this issue

Ping git.xxx.net
Then I have
PING git.xxx.net (172.17.28.245) 56(84) bytes of data.
From 08be4336c264 (172.17.0.2) icmp_seq=1 Destination Host Unreachable
From 08be4336c264 (172.17.0.2) icmp_seq=2 Destination Host Unreachable
From 08be4336c264 (172.17.0.2) icmp_seq=3 Destination Host Unreachable

So, can anyone help me to figure out how I can resolve this issue in mac?

I am using  Docker QuickStart Terminal in Mac to start.

Thanks


问:
Xamarin forms: Listview: Itemtemplate: Datatemplate: I dont have TextCell in xaml
I have a problem. In Datatemplate i cant reach TextCell in xaml. Anybody can help me?

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.MedicationPage"
         Title="Gyógyszerek">
<ContentPage.Content>
    <ListView>
        <ListView.ItemTemplate>
            <DataTemplate>

            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>
</code>```

Update: I reach it but the VS dont show it.
In first answer there is a solution.

答:
```<code><StackLayout>
    <ListView x:Name="Medications" ItemsSource="{Binding Medications}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ImageCell ImageSource="{Binding Icon}" Text="{Binding Name}" Detail="{Binding Type}" Tapped="ImageCell_Tapped"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>
</code>```

Body:
I have a problem. In Datatemplate i cant reach TextCell in xaml. Anybody can help me?

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="Spirocco.MedicationPage"
         Title="Gyógyszerek">
<ContentPage.Content>
    <ListView>
        <ListView.ItemTemplate>
            <DataTemplate>

            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

Update: I reach it but the VS dont show it.
In first answer there is a solution.


问:
How to implement partial inheritance in javascript?
I have gone in an interview yesterday where interviewer asked me about partial inheritance, about which I am clueless. I have mentioned 2 code blocks below as per my understanding. Let me know whatever I am doing is correct or not for partial inheritance.

Code Block 1: Can we call this partial inheritance?

```<code>var Person = function(){}

Person.prototype.getName = function(){
    return this.name;
}

Person.prototype.setName = function(name){
    this.name = name;
}

var Author = function(name, books){
    this.books = books;
    Person.prototype.setName.call(this, name); <<---- Is this a way of doing partial inheritance?
}

Author.prototype.getBooks = function(){
    return this.books;
}

var author = new Author('Auth1', ['b1','b2']);
</code>```

Code Block 2: How to inherit only "setName" function from "Person" constructor? Is it possible?

```<code>var Person = function(){
    this.setName = function(name){
        this.name = name;
    };
}

Person.prototype.getName = function(){
    return this.name;
}

var Author = function(name, books){
    this.books = books;
}

Author.prototype.getBooks = function(){
    return this.books;
}

var author = new Author('Auth1', ['b1','b2']);
</code>```

Do explain the authenticity of above 2 code blocks?

I even don't know whether examples quoted above are right or not. If they are not correct than please throw some light on partial inheritance in JavaScript.

Question: I just want to inherit only setName method from Person constructor to Author constructor. Is that possible?

答:
From reading your description, I don't think you're familiar with context and the concept of this, which is a wildcard that can represent any object. Also worth noting is that the prototype chain is just a specific place to look if a property appears to be undefined on a class instance. An instance is just a regular object that's returned after running the constructor (via 'new' keyword), where the function class.prototype.asdf is the same function as instance.asdf if instance.asdf isn't defined

```<code>const OtherClass = function () {};
const MyClass = function () {};
      MyClass.prototype.logThis = function () { console.log(this); };

const otherInstance = new OtherClass();
const myInstance = new MyClass();

myInstance.logThis(); // logs myInstance
myInstance.logThis.call(otherInstance, 'param1', 'param2'); // logs otherInstance
myInstance.logThis.apply(otherInstance, ['param1', 'param2']); // logs otherInstance
</code>```

The simple way to remember what 'this' is -- whatever's 'to the left of the dot' at execution or invocation time, not the function scope where it's written. This is why setTimeout and other async things like Promises won't use the 'this' you might expect, unless you bound it already.

You can write a generic, shared function that operates with unknown, and include it in different objects.

```<code>Person.prototype.setName = Author.prototype.setName = function setName () {}
</code>```

Body:
I have gone in an interview yesterday where interviewer asked me about partial inheritance, about which I am clueless. I have mentioned 2 code blocks below as per my understanding. Let me know whatever I am doing is correct or not for partial inheritance.

Code Block 1: Can we call this partial inheritance?

var Person = function(){}

Person.prototype.getName = function(){
    return this.name;
}

Person.prototype.setName = function(name){
    this.name = name;
}

var Author = function(name, books){
    this.books = books;
    Person.prototype.setName.call(this, name); <<---- Is this a way of doing partial inheritance?
}

Author.prototype.getBooks = function(){
    return this.books;
}

var author = new Author('Auth1', ['b1','b2']);

Code Block 2: How to inherit only "setName" function from "Person" constructor? Is it possible?

var Person = function(){
    this.setName = function(name){
        this.name = name;
    };
}

Person.prototype.getName = function(){
    return this.name;
}

var Author = function(name, books){
    this.books = books;
}

Author.prototype.getBooks = function(){
    return this.books;
}

var author = new Author('Auth1', ['b1','b2']);

Do explain the authenticity of above 2 code blocks?

I even don't know whether examples quoted above are right or not. If they are not correct than please throw some light on partial inheritance in JavaScript.

Question: I just want to inherit only setName method from Person constructor to Author constructor. Is that possible?

Body:
From reading your description, I don't think you're familiar with context and the concept of this, which is a wildcard that can represent any object. Also worth noting is that the prototype chain is just a specific place to look if a property appears to be undefined on a class instance. An instance is just a regular object that's returned after running the constructor (via 'new' keyword), where the function class.prototype.asdf is the same function as instance.asdf if instance.asdf isn't defined

const OtherClass = function () {};
const MyClass = function () {};
      MyClass.prototype.logThis = function () { console.log(this); };

const otherInstance = new OtherClass();
const myInstance = new MyClass();

myInstance.logThis(); // logs myInstance
myInstance.logThis.call(otherInstance, 'param1', 'param2'); // logs otherInstance
myInstance.logThis.apply(otherInstance, ['param1', 'param2']); // logs otherInstance

The simple way to remember what 'this' is -- whatever's 'to the left of the dot' at execution or invocation time, not the function scope where it's written. This is why setTimeout and other async things like Promises won't use the 'this' you might expect, unless you bound it already.

You can write a generic, shared function that operates with unknown, and include it in different objects.

Person.prototype.setName = Author.prototype.setName = function setName () {}


问:
How to perform mouseover function in Selenium WebDriver using Java?
I want to do mouseover function over a drop down menu. When we hover over the menu, it will show the new options.
I tried to click the new options using the xpath. But cannot click the menus directly.
So, as the manual way I am trying to hover over the drop down menu and then will click the new options.</p>

```<code>Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).build().perform();
</code>```

答:
You can try:

```<code>WebElement getmenu= driver.findElement(By.xpath("//*[@id='ui-id-2']/span[2]")); //xpath the parent

Actions act = new Actions(driver);
act.moveToElement(getmenu).perform();

Thread.sleep(3000);
WebElement clickElement= driver.findElement(By.linkText("Sofa L"));//xpath the child
act.moveToElement(clickElement).click().perform();
</code>```

If you had case the web have many category, use the first method. For menu you wanted, you just need the second method.

ContentLicense: CC BY-SA 4.0

Body:
I want to do mouseover function over a drop down menu. When we hover over the menu, it will show the new options.
I tried to click the new options using the xpath. But cannot click the menus directly.
So, as the manual way I am trying to hover over the drop down menu and then will click the new options.

Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("//html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).build().perform();

Body:
You can try:

WebElement getmenu= driver.findElement(By.xpath("//*[@id='ui-id-2']/span[2]")); //xpath the parent

Actions act = new Actions(driver);
act.moveToElement(getmenu).perform();

Thread.sleep(3000);
WebElement clickElement= driver.findElement(By.linkText("Sofa L"));//xpath the child
act.moveToElement(clickElement).click().perform();

If you had case the web have many category, use the first method. For menu you wanted, you just need the second method.


问:
MySql: SELECT where a field value contains ' and "?
I want to retrieve a record where the value contains single quote and double quote.

Tried The following:

select * from Table1 where id = '' . ~";:><?/\!@#$%^*()_+|/ \?' ;
`

答: select * from table1 where name like "%'%" OR name like '%"%';


问:
How to uninstall Visual Studio 2017 update 15.3
After upgrading to VS 2017 15.3 my solution compiles, but .NET Framework 4.6.2 projects in the same solution (e.g. Specflow Acceptance tests) have loads of compiler warnings and missing references. When acceptance tests are run they present an error:

```<code>System.IO.FileLoadException: Could not load file or assembly 'System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.
</code>```

I don't have time to fix this now, so how can I rollback the Visual Studio 2017 installation to 15.2?

Other answers (for previous versions of Visual Studio) suggest using the "View installed updates" thing in Control Panel, but I don't see any VS 2017 updates in there.

答:
Microsoft recently introduced breaking changes with version 15.5, so we had to find a way to downgrade from that.

While I'm not sure it's relevant for OP's original problem, this would have been relevant at the time the question was posed, so leaving this for future reference:

Microsoft do provide a way of downgrading to the version before the latest (N-1), in this case version 15.4.5, so you don't have to go all the way to 15.0:

https://www.visualstudio.com/en-us/productinfo/installing-an-earlier-release-of-vs2017

Body:
After upgrading to VS 2017 15.3 my solution compiles, but .NET Framework 4.6.2 projects in the same solution (e.g. Specflow Acceptance tests) have loads of compiler warnings and missing references. When acceptance tests are run they present an error:

System.IO.FileLoadException: Could not load file or assembly 'System.Runtime, Version=4.1.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies.

I don't have time to fix this now, so how can I rollback the Visual Studio 2017 installation to 15.2?

Other answers (for previous versions of Visual Studio) suggest using the "View installed updates" thing in Control Panel, but I don't see any VS 2017 updates in there.


问:
Why pytest calls a duplicate method
why does this happen?
duplicate call because I added "self.log"

code

```<code>import logging, logging.handlers
class TestCase:

    def setup_method(self,test_method):
            self.log = logging.getLogger('test')
            self.log.addHandler( logging.StreamHandler())

    def test_one(self):
            log = self.log
            log.info('one')
    def test_two(self):
            log = self.log
            log.info('two')
</code>```

console out

```<code>$pytest -s
=========================================== test session starts ===========================================
platform darwin -- Python 3.6.2, pytest-3.3.1, py-1.5.2, pluggy-0.6.0
rootdir: /Users/taeun/dev/workspace/test/pytest-test/tests, inifile:
collected 2 items

test_one.py one
.two
two
.                                                                                [100%]
</code>```

anyone help me?

答:
That's because you are adding a StreamHandler to your logger in the setup_method, which will be called once for each test run. What happens if you run both tests:

setup_method is called, one instance of StreamHandler is added to the logger

test_one runs, the logger has one handler that send the message one to stdout

setup_method is called for the second time, adding another instance of StreamHandler to the logger handlers

test_two runs, but now the logger has two handlers, both sending the message two to stdout

To overcome this, you can either clean up handlers in the setup_method to ensure you have one StreamHandler on each test run:

```<code>class TestCase:

    def setup_method(self):
        self.log = logging.getLogger('test')
        self.log.handlers = [h for h in self.log.handlers
                             if not isinstance(h, logging.StreamHandler)]
        self.log.addHandler(logging.StreamHandler())

        ...
</code>```

or you declare the logger configuration as a one-time operation (a much cleaner solution if you ask me):

```<code>class TestCase:

    @classmethod
    def setup_class(cls):
        logging.getLogger('test').addHandler(logging.StreamHandler())

    def setup_method(self,test_method):
        self.log = logging.getLogger('test')

    ...
</code>```

Title: Why pytest calls a duplicate method

Body:
why does this happen?
duplicate call because I added "self.log"

code

import logging, logging.handlers
class TestCase:

    def setup_method(self,test_method):
            self.log = logging.getLogger('test')
            self.log.addHandler( logging.StreamHandler())

    def test_one(self):
            log = self.log
            log.info('one')
    def test_two(self):
            log = self.log
            log.info('two')

console out

$pytest -s
=========================================== test session starts ===========================================
platform darwin -- Python 3.6.2, pytest-3.3.1, py-1.5.2, pluggy-0.6.0
rootdir: /Users/taeun/dev/workspace/test/pytest-test/tests, inifile:
collected 2 items

test_one.py one
.two
two
.                                                                                [100%]

anyone help me?

Body:
That's because you are adding a StreamHandler to your logger in the setup_method, which will be called once for each test run. What happens if you run both tests:

setup_method is called, one instance of StreamHandler is added to the logger

test_one runs, the logger has one handler that send the message one to stdout

setup_method is called for the second time, adding another instance of StreamHandler to the logger handlers

test_two runs, but now the logger has two handlers, both sending the message two to stdout

To overcome this, you can either clean up handlers in the setup_method to ensure you have one StreamHandler on each test run:

class TestCase:

    def setup_method(self):
        self.log = logging.getLogger('test')
        self.log.handlers = [h for h in self.log.handlers
                             if not isinstance(h, logging.StreamHandler)]
        self.log.addHandler(logging.StreamHandler())

        ...

or you declare the logger configuration as a one-time operation (a much cleaner solution if you ask me):

class TestCase:

    @classmethod
    def setup_class(cls):
        logging.getLogger('test').addHandler(logging.StreamHandler())

    def setup_method(self,test_method):
        self.log = logging.getLogger('test')

    ...


问:
why is this behaviour of strtof() changes with respect to the change in stdlib.h?
With <stdlib.h> included the following code gives the output of 123.34.

```<code>#include<stdlib.h>
int main()
{
    char *str="123.34";
    float f= strtof(str,NULL);
    printf("%f",f);
}
</code>```

But without <stdlib.h> it produces the output of 33.000000.

What is the role of <stdlib.h> here and why did the value 33.00000 occur when it is nowhere in the code?

答:
You must take a look at the warning generated by the compiler.

```<code>warning: implicit declaration of function 'strtof' [-Wimplicit-function-declaration]
</code>```

This still yields result, which is not deterministic in any way because the return type expected is float, whereas without the header inclusion, the default is assumed to be int.

If you look into the stdlib header file, there is a declaration,

```<code>float strtof(const char *restrict, char **restrict);
</code>```

With #include<stdlib.h>, we provide this declaration. When missed, compiler assumes to be returning int, and hence the result is not deterministic.
With my system, it produced 0.00000000 as the output, whereas with the necessary inclusions, I got 123.339996 as the output.

As a precaution, make a habit of always compiling the code with -Wall option (Assuming that you are using gcc), or better yet, -Werror option.

Body:
With <stdlib.h> included the following code gives the output of 123.34.

#include<stdlib.h>
int main()
{
    char *str="123.34";
    float f= strtof(str,NULL);
    printf("%f",f);
}

But without <stdlib.h> it produces the output of 33.000000.

What is the role of <stdlib.h> here and why did the value 33.00000 occur when it is nowhere in the code?

Body:
You must take a look at the warning generated by the compiler.

warning: implicit declaration of function 'strtof' [-Wimplicit-function-declaration]

This still yields result, which is not deterministic in any way because the return type expected is float, whereas without the header inclusion, the default is assumed to be int.

If you look into the stdlib header file, there is a declaration,

float strtof(const char *restrict, char **restrict);

With #include<stdlib.h>, we provide this declaration. When missed, compiler assumes to be returning int, and hence the result is not deterministic.
With my system, it produced 0.00000000 as the output, whereas with the necessary inclusions, I got 123.339996 as the output.

As a precaution, make a habit of always compiling the code with -Wall option (Assuming that you are using gcc), or better yet, -Werror option.


问:
Show drop down values of a select option based on another select option
I have two dropdown select option. First is for select State and second is for select city. When any one select from state dropdown then related content should be shown on second select option (that will be related city.). I have some code, but it is not working. </p>

```<code>   <div class="vali-form">
        <div class="col-md-6 form-group2">

        <?php
   include("connection.php");
   $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        echo" <label class='control-label'>Select State</label>";
        echo" <select required name='selectstate'>";
        echo"<option>Select</option>";
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }
        echo" </select>";
       ?>

        </div>
        <div class="col-md-6 form-group2"  id="response">

         <label class='control-label'>City:</label>
     <select>

            <?php
   if(isset($_POST["selectstate"])){
// Capture selected country
$selectstate = $_POST["selectstate"];

// Define country and city array
$query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        $row1=mysql_fetch_array($query1);

    // Display city dropdown based on country name
   if($selectstate !== 'Select'){

    foreach($row1[$selectstate] as $value){
        echo "<option>". $value . "</option>";
    }

   }
   }
   ?>

 </select>

        </div>
        <div class="clearfix"> </div>
        </div>
</code>```

<p>jQuery-AJAX code is below.         </p>

```<code>     <script type="text/javascript" src="http://code.jquery.com/jquery.js">
  </script>
  <script type="text/javascript">
  $(document).ready(function(){
   $("select.selectstate").change(function(){
    var selectedstate = $(".selectstate option:selected").val();
    $.ajax({
        type: "POST",
        url: "locpac.php",
        data: { selectstate : selectedstate }
    }).done(function(data){
        $("#response").html(data);
    });
   });
   });
   </script>
</code>```

答:
```<code>$("select.selectstate").change(function(){...
</code>```

You are trying to get select with class - "selectstate", but you haven`t it. You can try to add class to select:

```<code>echo" <select required name='selectstate' class='selectstate'>";
</code>```

And ajax request:

```<code>$.ajax({
    type: "POST",
    url: "locpac.php",
    dataType: "html",
    data: { selectstate : selectedstate }
}).success(function(data){
    $("#response").html(data);
});
</code>```

Body:
I have two dropdown select option. First is for select State and second is for select city. When any one select from state dropdown then related content should be shown on second select option (that will be related city.). I have some code, but it is not working.

        <?php
   include("connection.php");
   $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        echo" Select State";
        echo" <select required name='selectstate'>";
        echo"<option>Select</option>";
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }
        echo" </select>";
       ?>

         City:
     <select>

            <?php
   if(isset($_POST["selectstate"])){
// Capture selected country
$selectstate = $_POST["selectstate"];

// Define country and city array
$query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        $row1=mysql_fetch_array($query1);

    // Display city dropdown based on country name
   if($selectstate !== 'Select'){

    foreach($row1[$selectstate] as $value){
        echo "<option>". $value . "</option>";
    }

   }
   }
   ?>

 </select>

jQuery-AJAX code is below.

Body:
$("select.selectstate").change(function(){...

You are trying to get select with class - "selectstate", but you haven`t it. You can try to add class to select:

echo" <select required name='selectstate' class='selectstate'>";

And ajax request:

$.ajax({
    type: "POST",
    url: "locpac.php",
    dataType: "html",
    data: { selectstate : selectedstate }
}).success(function(data){
    $("#response").html(data);
});


问:
Spring Boot App Terminating at Startup
I am  trying out a simple spring boot application it always shuts down automatically

```<code> :: Spring Boot ::        (v1.4.1.RELEASE)
2016-10-23 13:05:21.681  INFO 16532 --- [           main] com.example.RestBootApplication          : No active profile set, falling back to default profiles: default
2016-10-23 13:05:21.766  INFO 16532 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e20b53a: startup date [Sun Oct 23 13:05:21 EDT 2016]; root of context hierarchy
2016-10-23 13:05:23.682  INFO 16532 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-10-23 13:05:23.704  INFO 16532 --- [           main] com.example.RestBootApplication          : Started RestBootApplication in 2.632 seconds (JVM running for 5.168)
2016-10-23 13:05:23.705  INFO 16532 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e20b53a: startup date [Sun Oct 23 13:05:21 EDT 2016]; root of context hierarchy
2016-10-23 13:05:23.708  INFO 16532 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
</code>```

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>rest-boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Main Class

```<code>@SpringBootApplication
public class RestBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestBootApplication.class, args);
    }
}
</code>```

Controller

```<code>@Controller
public class HelloController {

    @RequestMapping("/hello")
    String helloWorld(){
        return "helloWorld";
    }

}
</code>```

Trying to run in spring tool suite.  it always stops after starting. I even added "spring-boot-starter-web" after looking at some stackoverflow  questions, but still facing the issue.

Please can you someone point out the issue.

答:
For me the embed tomcat was corrupted. I have done a mvn build and found below line as a WARNING.

[WARNING] error reading /home/syam/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.23/tomcat-embed-core-8.5.23.jar; invalid LOC header (bad signature)

So deleted the tomcat embed directory and did a maven clean, things started working.

Title: Spring Boot App Terminating at Startup

Body:
I am  trying out a simple spring boot application it always shuts down automatically

 :: Spring Boot ::        (v1.4.1.RELEASE)
2016-10-23 13:05:21.681  INFO 16532 --- [           main] com.example.RestBootApplication          : No active profile set, falling back to default profiles: default
2016-10-23 13:05:21.766  INFO 16532 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e20b53a: startup date [Sun Oct 23 13:05:21 EDT 2016]; root of context hierarchy
2016-10-23 13:05:23.682  INFO 16532 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-10-23 13:05:23.704  INFO 16532 --- [           main] com.example.RestBootApplication          : Started RestBootApplication in 2.632 seconds (JVM running for 5.168)
2016-10-23 13:05:23.705  INFO 16532 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6e20b53a: startup date [Sun Oct 23 13:05:21 EDT 2016]; root of context hierarchy
2016-10-23 13:05:23.708  INFO 16532 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>rest-boot</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.1.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Main Class

@SpringBootApplication
public class RestBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestBootApplication.class, args);
    }
}

Controller

@Controller
public class HelloController {

    @RequestMapping("/hello")
    String helloWorld(){
        return "helloWorld";
    }

}

Trying to run in spring tool suite.  it always stops after starting. I even added "spring-boot-starter-web" after looking at some stackoverflow  questions, but still facing the issue.

Please can you someone point out the issue.


问:
Docusign webhook message does not have way to differentiate different compositetemplate
I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row.

This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row

```<code>{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}
</code>```

And once I finished signing, the webhook event notification is triggered and called my api with this response message

```<code>{
  "EnvelopeStatus": {
    "EnvelopeID": "EnvelopeIDGivenByDocusign",
    "Status": "Completed",
    "CustomFields": [
      {
        "Name": "ContactID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "OpportunityID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "AccountID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "DocuInfoId",
        "Show": "False",
        "Required": "True",
        "Value": "88"
      },
      {
        "Name": "OpportunityId",
        "Show": "False",
        "Required": "True",
        "Value": "1"
      },
      {
        "Name": "LQAID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      }
    ],
    "DocumentStatuses": [
      {
        "ID": 1,
        "Name": "Document - TX - 1001.pdf",
        "TemplateName": "Document - TX",
        "Sequence": 1
      },
      {
        "ID": 2,
        "Name": "Rejection.pdf",
        "TemplateName": "Rejection Form",
        "Sequence": 2
      }
    ]
  },
  "DocumentPDFs": [
    {
      "Name": "Document - TX - 1001.pdf",
      "DocumentID": "1",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "Rejection.pdf",
      "DocumentID": "2",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf",
      "DocumentID": null,
      "DocumentType": "SUMMARY"
    }
  ]
}
</code>```

Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf).

Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly?

答:
Instead of using the values from the CustomFields section of the XML, use the values contained in the TabStatuses elements.

You'll need to do a bit more parsing, but it gives you all the context info.

Body:
I have created 1 envelope with 2 composite templates with embedded signing and I can hook it up with the webhook event notification to receive a message once users finish signing, so I can try to update my db and download the file. However, the webhook response does not have the custom fields that I need to identify which file belong to which for me to update the db row.

This is my json serialized envelope example. Notice the custom field on each inline template, that have the property of DocuInfoId. I will need the value of those to update my db row

{
  "status": "sent",
  "emailSubject": "DocuSign API - Template Example",
  "eventNotification": {
    "url": "https:\/\/mytestsite.net\/api\/documentstuff\/docusign\/available",
    "loggingEnabled": "false",
    "requireAcknowledgment": "true",
    "useSoapInterface": "false",
    "soapNameSpace": "",
    "includeCertificateWithSoap": "false",
    "signMessageWithX509Cert": "false",
    "includeDocuments": "false",
    "includeEnvelopeVoidReason": "false",
    "includeTimeZone": "true",
    "includeSenderAccountAsCustomField": "false",
    "includeDocumentFields": "false",
    "includeCertificateOfCompletion": "true",
    "envelopeEvents": [
      {
        "envelopeEventStatusCode": "Sent",
        "includeDocuments": null
      },
      {
        "envelopeEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ],
    "recipientEvents": [
      {
        "recipientEventStatusCode": "Completed",
        "includeDocuments": "true"
      }
    ]
  },
  "compositeTemplates": [
    {
      "inlineTemplates": [
        {
          "sequence": "1",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just a bunch of text tabs, radio group, etc"
                }
              },
              {
                "clientUserId": "2",
                "recipientId": "2",
                "email": "testemail@test.com",
                "name": "Owner Name",
                "roleName": "Owner",
                "tabs": null
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "77",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "1",
          "templateId": "TemplateIDNumber1"
        }
      ]
    },
    {
      "inlineTemplates": [
        {
          "sequence": "2",
          "recipients": {
            "signers": [
              {
                "clientUserId": "1",
                "recipientId": "1",
                "email": "testemail@test.com",
                "name": "Client Name",
                "roleName": "Client",
                "tabs": {
                  "TextTabs": "Just another bunch of text tabs, radio group tab, etc"
                }
              }
            ]
          },
          "customFields": {
            "ListCustomFields": [
              {
                "name": "DocuInfoId",
                "required": "True",
                "show": "False",
                "value": "88",
                "listItems": null
              },
              {
                "name": "OpportunityId",
                "required": "True",
                "show": "False",
                "value": "1",
                "listItems": null
              }
            ]
          }
        }
      ],
      "serverTemplates": [
        {
          "sequence": "2",
          "templateId": "TemplateIDNumber2"
        }
      ]
    }
  ]
}

And once I finished signing, the webhook event notification is triggered and called my api with this response message

{
  "EnvelopeStatus": {
    "EnvelopeID": "EnvelopeIDGivenByDocusign",
    "Status": "Completed",
    "CustomFields": [
      {
        "Name": "ContactID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "OpportunityID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "AccountID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      },
      {
        "Name": "DocuInfoId",
        "Show": "False",
        "Required": "True",
        "Value": "88"
      },
      {
        "Name": "OpportunityId",
        "Show": "False",
        "Required": "True",
        "Value": "1"
      },
      {
        "Name": "LQAID",
        "Show": "True",
        "Required": "False",
        "Value": ""
      }
    ],
    "DocumentStatuses": [
      {
        "ID": 1,
        "Name": "Document - TX - 1001.pdf",
        "TemplateName": "Document - TX",
        "Sequence": 1
      },
      {
        "ID": 2,
        "Name": "Rejection.pdf",
        "TemplateName": "Rejection Form",
        "Sequence": 2
      }
    ]
  },
  "DocumentPDFs": [
    {
      "Name": "Document - TX - 1001.pdf",
      "DocumentID": "1",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "Rejection.pdf",
      "DocumentID": "2",
      "DocumentType": "CONTENT"
    },
    {
      "Name": "CertificateOfCompletion_78sd89fuas89sadf.pdf",
      "DocumentID": null,
      "DocumentType": "SUMMARY"
    }
  ]
}

Looking at the response, there's only 1 docuinfoid with the value of 88, I'm also not sure where is the rest of custom field coming from e.g: "LQAID". Now, I'm not sure which docuinfoid is this belong to, the first pdf file (Document - TX - 1001.pdf) or the second pdf file (Rejection.pdf).

Is there anyway to know which pdf document belong to which docuinfoid, so that I can attach it to my database correctly?


问:
undefined method "reflect_on_association" on using "nested_form" gem. Rails 5
In my project I have API and its associated front end part. I am using rails version 5 . I am creating two models. One is user and another one is qualifications. Associations are given below.

```<code>class User
  include Her::Model
  include Her::FileUpload
  has_file_upload :image_url

  has_many :videos
  has_many :qualifications
  attributes :name, :email, :phone, :image_url, :contact_email, :about, :password, :password_confirmation

  custom_post :sign_in, :refresh
  custom_get :me

  accepts_nested_attributes_for :qualifications
end
</code>```

And, qualification model is

```<code>class Qualification
  include Her::Model

  belongs_to :user
  attributes :school, :degree, :grade, :start_year, :end_year
end
</code>```

My strong params in users controller is

```<code>def user_params
      user: params.require(:user).permit(:id, :name, :email, :phone, :contact_email, :about,:image_url,
        {specialization_ids: []},
        qualifications_attributes: [:id, :school, :degree, :grade, :start_year, :end_year, :_destroy]
    end
</code>```

My user form, where i have provided nested_form is

```<code><div class="row">
  <div class="container">
    <div class="signup-bg col-md-12">
      <h3 style="color:white;"> General Info </h3>
      <hr>
      <%= simple_nested_form_for @user do |f| %>
          <%= f.input :email, input_html: {class: "input-user-form"} %>
          <%= f.input :name, input_html: {class: "input-user-form"} %>
          <%= f.input :phone , input_html: {class: "input-user-form"}%>
          <%= f.input :contact_email, input_html: {class: "input-user-form"} %>
          <%= f.input :about, as: :text, input_html: {class: "input-user-form"}%>
          <label class="control-label">Selected Specializations</label>
          <ul class="list-group">
            <% @user.specializations.each do |sp| %>
              <li class="list-group-item tags">
                <%= check_box_tag "user[specialization_ids][]", sp["id"], true%>
                <%= sp["name"] %>
              </li>
            <% end %>
          </ul>
        <h4 style="color:white;"><center>Select Your Specializations</center></h4>
        <div class="row">
          <div class="col-md-12">
            <div class="input-group">
                <input id="searchText" type="text" class="input-signup" placeholder="Search Specialization" style="z-index:0;">
                <span class="input-group-btn">
                  <button class="btn btn-default btn-go" type="button">Go!</button>
                </span>
              </div>
            <div class="col-md-12 col-sm-12 col-lg-12" id="specializationHolder" style="min-height:85px;"></div>
          </div>
        </div>
        <h3 style="color:white;"> Qualification Info </h3>
        <hr>
        <div id="qualification_holder">
          <%= f.simple_fields_for :qualifications, @qualification do |g| %>
            <%= g.input :school,input_html: {class: "input-user-form"} %>
            <%= g.input :degree, input_html: {class: "input-user-form"} %>
            <%= g.input :grade, as: :integer, input_html: {class: "input-user-form"} %>
            <%= g.input :start_year, required: false, as: :string, input_html: {type: :date, class: "datepicker input-user-form"} %>
            <%= g.input :end_year, required: false, as: :string, input_html: {type: :date, class: "datepicker input-user-form"} %>
          <% end %>
        </div>
        </br>
        <div class="col-md-4">
          <%= f.link_to_add :qualifications, data: {target: "#qualification_holder"}, class: "btn-signup-submit"  do %>
            <b> + </b> Add Qualifications
          <% end %>
        </div>
        <div id="wrapper">
          <label class="control-label file optional" for="user_image_url">Profile Picture</label>
          <input class="file optional"  type="file" name="user[image_url]" id="fileUpload">
        </div>
        <div class="form-group text-center">
          <button type="submit" class="btn-signup-submit">Save Changes</button>
        </div>
      <% end %>
    </div>
  </div>
</div>
</code>```

But, I am getting an error undefined error "reflect_on_association", pointing towards "link_to_add". I am Stuck here for a week. Is there any solutions for it.. If so, please help me.

Thanks in advance.

答:
I had the same error. The solution is to add the class_name option on your problematic association, with no nesting on the class name.

In your case, you can try:

```<code>class User
  include Her::Model
  include Her::FileUpload
  has_file_upload :image_url

  has_many :videos
  has_many :qualifications, class_name: "::Qualification"
  attributes :name, :email, :phone, :image_url, :contact_email, :about, :password, :password_confirmation

  custom_post :sign_in, :refresh
  custom_get :me

  accepts_nested_attributes_for :qualifications
end
</code>```

Body:
In my project I have API and its associated front end part. I am using rails version 5 . I am creating two models. One is user and another one is qualifications. Associations are given below.

class User
  include Her::Model
  include Her::FileUpload
  has_file_upload :image_url

  has_many :videos
  has_many :qualifications
  attributes :name, :email, :phone, :image_url, :contact_email, :about, :password, :password_confirmation

  custom_post :sign_in, :refresh
  custom_get :me

  accepts_nested_attributes_for :qualifications
end

And, qualification model is

class Qualification
  include Her::Model

  belongs_to :user
  attributes :school, :degree, :grade, :start_year, :end_year
end

My strong params in users controller is

def user_params
      user: params.require(:user).permit(:id, :name, :email, :phone, :contact_email, :about,:image_url,
        {specialization_ids: []},
        qualifications_attributes: [:id, :school, :degree, :grade, :start_year, :end_year, :_destroy]
    end

My user form, where i have provided nested_form is

 General Info

      <%= simple_nested_form_for @user do |f| %>
          <%= f.input :email, input_html: {class: "input-user-form"} %>
          <%= f.input :name, input_html: {class: "input-user-form"} %>
          <%= f.input :phone , input_html: {class: "input-user-form"}%>
          <%= f.input :contact_email, input_html: {class: "input-user-form"} %>
          <%= f.input :about, as: :text, input_html: {class: "input-user-form"}%>
          Selected Specializations

            <% @user.specializations.each do |sp| %>

                <%= check_box_tag "user[specialization_ids][]", sp["id"], true%>
                <%= sp["name"] %>

            <% end %>

Select Your Specializations

                <input id="searchText" type="text" class="input-signup" placeholder="Search Specialization" style="z-index:0;">

                  <button class="btn btn-default btn-go" type="button">Go!</button>

 Qualification Info

          <%= f.simple_fields_for :qualifications, @qualification do |g| %>
            <%= g.input :school,input_html: {class: "input-user-form"} %>
            <%= g.input :degree, input_html: {class: "input-user-form"} %>
            <%= g.input :grade, as: :integer, input_html: {class: "input-user-form"} %>
            <%= g.input :start_year, required: false, as: :string, input_html: {type: :date, class: "datepicker input-user-form"} %>
            <%= g.input :end_year, required: false, as: :string, input_html: {type: :date, class: "datepicker input-user-form"} %>
          <% end %>

          <%= f.link_to_add :qualifications, data: {target: "#qualification_holder"}, class: "btn-signup-submit"  do %>
             +  Add Qualifications
          <% end %>

          Profile Picture
          <input class="file optional"  type="file" name="user[image_url]" id="fileUpload">

          <button type="submit" class="btn-signup-submit">Save Changes</button>

      <% end %>

But, I am getting an error undefined error "reflect_on_association", pointing towards "link_to_add". I am Stuck here for a week. Is there any solutions for it.. If so, please help me.

Thanks in advance.

Body:
I had the same error. The solution is to add the class_name option on your problematic association, with no nesting on the class name.

In your case, you can try:

class User
  include Her::Model
  include Her::FileUpload
  has_file_upload :image_url

  has_many :videos
  has_many :qualifications, class_name: "::Qualification"
  attributes :name, :email, :phone, :image_url, :contact_email, :about, :password, :password_confirmation

  custom_post :sign_in, :refresh
  custom_get :me

  accepts_nested_attributes_for :qualifications
end


问:
How to get number of rows and columns from a matplotlib plot?
I have a function that dynamically creates figures of different columns and rows:

```<code>import random

import matplotlib.pyplot as plt

def build_dynamic_plot():
    """Return a figure with random rows and columns."""
    nrows = random.randrange(1, 10)
    ncols = random.randrange(1, 10)

    fig, ax = plt.subplots(nrows, ncols)

    return fig.tight_layout()

plot = build_dynamic_plot()
</code>```

Using the matplotlib API, how do I get the number of rows and columns from the figure, which are dynamically generated, e.g. plot.get_rows and plot.get_cols?  I ultimately need to verify that the row by column dimensions are accurate.  Thank you.

答:
Although HYRY's answer was helpful and it might work sometimes (or worked before), the true solution should be:</p>

```<code>fig.axes[0].get_subplotspec().get_topmost_subplotspec().get_gridspec().get_geometry()
</code>```

Body:
I have a function that dynamically creates figures of different columns and rows:

import random

import matplotlib.pyplot as plt

def build_dynamic_plot():
    """Return a figure with random rows and columns."""
    nrows = random.randrange(1, 10)
    ncols = random.randrange(1, 10)

    fig, ax = plt.subplots(nrows, ncols)

    return fig.tight_layout()

plot = build_dynamic_plot()

Using the matplotlib API, how do I get the number of rows and columns from the figure, which are dynamically generated, e.g. plot.get_rows and plot.get_cols?  I ultimately need to verify that the row by column dimensions are accurate.  Thank you.

Body:
Although HYRY's answer was helpful and it might work sometimes (or worked before), the true solution should be:

fig.axes[0].get_subplotspec().get_topmost_subplotspec().get_gridspec().get_geometry()


问:
ValidFormBuilder prepopulate fields and preset checkboxes
What's the correct way to prepopulate fields when loading a form that is meant to edit preexisting data, such as a user profile?  Also, bonus points to the answer that also includes setting the checked status of check boxes or radio buttons.</p>

答:
Initial values for a form field in ValidForm Builder can be set using the "default" key of the "meta" array like this:

```<code>$objForm = new ValidForm("test");

$objCat = $objForm->addField(
    "name",
    "Name",
    ValidForm::VFORM_STRING,
    [
        "required" => true
    ],
    [
        "required" => "Don't leave me empty"
    ],
    [
        "default" => "Arthur Dent" // <= This key sets the initial value
    ]
);
</code>```

This works for ALL fields in VFB, also check boxes, radio buttons and select fields.

For list type fields like check boxes, radio buttons and select fields the initial value can also be set using the third parameter of the addField method.

```<code>$objForm = new ValidForm("test");

$objSelect = $objForm->addField(
    "rating",
    "Rate ValidForm Builder",
    ValidForm::VFORM_SELECT_LIST
);

$objSelect->addField("Awesome", 1);
$objSelect->addField("Great", 2);
$objSelect->addField("Super Cool", 3, true); // This item is selected by default
$objSelect->addField("Splendid", 4);
$objSelect->addField("Best thing ever happened", 5);
</code>```

The above code snippet is from the examples on Github.
https://github.com/validformbuilder/validformbuilder/blob/master/examples/select-default.php

There is also an example on how to set multiple initial values on a multi select field.
https://github.com/validformbuilder/validformbuilder/blob/master/examples/meta/checklist-with-multiple-default-values.php

Body:
Initial values for a form field in ValidForm Builder can be set using the "default" key of the "meta" array like this:

$objForm = new ValidForm("test");

$objCat = $objForm->addField(
    "name",
    "Name",
    ValidForm::VFORM_STRING,
    [
        "required" => true
    ],
    [
        "required" => "Don't leave me empty"
    ],
    [
        "default" => "Arthur Dent" // <= This key sets the initial value
    ]
);

This works for ALL fields in VFB, also check boxes, radio buttons and select fields.

For list type fields like check boxes, radio buttons and select fields the initial value can also be set using the third parameter of the addField method.

$objForm = new ValidForm("test");

$objSelect = $objForm->addField(
    "rating",
    "Rate ValidForm Builder",
    ValidForm::VFORM_SELECT_LIST
);

$objSelect->addField("Awesome", 1);
$objSelect->addField("Great", 2);
$objSelect->addField("Super Cool", 3, true); // This item is selected by default
$objSelect->addField("Splendid", 4);
$objSelect->addField("Best thing ever happened", 5);

The above code snippet is from the examples on Github.
https://github.com/validformbuilder/validformbuilder/blob/master/examples/select-default.php

There is also an example on how to set multiple initial values on a multi select field.
https://github.com/validformbuilder/validformbuilder/blob/master/examples/meta/checklist-with-multiple-default-values.php


问:
bash/cygwin: on login cd to directory i was on last "exit"

On cygwin start I'd like to be back in the same dir I was when left cygwin (by exit) last time.

So I think i need to store the current dir on exit in a file and use this to come back on next login in .bashrc.  Is there a default script called on exit or logout?

答:
Put this in your .bashrc:

```<code>trap 'pwd > ~/.lastdir' EXIT
if [[ -f ~/.lastdir ]]; then
    cd "$(< ~/.lastdir)"
fi
</code>```

Body:
Put this in your .bashrc:

trap 'pwd > ~/.lastdir' EXIT
if [[ -f ~/.lastdir ]]; then
    cd "$(< ~/.lastdir)"
fi


问:
Checking if object is a DOM-element
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.

What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?

piece of the usage:

```<code>var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);

s //<--should not be a DOM object
</code>```

答: Check s instanceof Node. Every DOM object is a Node.

Title: Checking if object is a DOM-element

Body:
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.

What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?

piece of the usage:

var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);

s //<--should not be a DOM object