问:
Evaluate sum of values without clicking a button
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.

However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).

I think change method can be used in the same manner.

@Edit:

Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with  -566,2202888.

function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $('#total').val(total);
}

$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">

  <select id="ilce">
    <option value="0">Choose a state</option>
    <option value="63999.50712318567">Adalar</option>
    <option value="6259.918435398593">Ataşehir</option>
    <option value="46285.35729304834">Beykoz</option>
    <option value="54258.92953697798">Kadıköy</option>
    <option value="-3500.620905653726">Kartal</option>
    <option value="12889.41219909602">Maltepe</option>
    <option value="-33711.83156847153">Pendik</option>
    <option value="-34577.42485251657">Sancaktepe</option>
    <option value="-52183.1608811019">Sultanbeyli</option>
    <option value="-34760.71735007784">Tuzla</option>
    <option value="-27379.87966213786">Çekmeköy</option>
    <option value="-5332.203990418937">Ümraniye</option>
    <option value="26485.33532820411">Üsküdar</option>
    <option value="-18732.62070553167">Şile</option>
  </select>

  <select id="odasalon">
    <option value="0">Choose room number</option>
    <option value="5940.027623576261">1+0</option>
    <option value="-1399.625767475593">1+1</option>
    <option value="-3033.638999060459">2+1</option>
    <option value="11519.83954756076">3+1</option>
    <option value="-7018.52116545078">4+1</option>
    <option value="-6008.081239150166">5+1</option>
  </select>

  m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />

  <br/>
  <br/> Features:

  <br/>
  <br/>
  <input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
  <br/>
  <input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
  <br/>
  <input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
  <br/>
  <input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
  <br/>
  <input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
  <br/>
  <input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
  <br/>
  <input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
  <br/>
  <input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
  <br/>
  <input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
  <br/>
  <input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
  <br/>
  <input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
  <br/>
  <input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
  <br/>
  <input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
  <br/>
  <input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
  <br/>
  <input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
  <br/>
</div>
<input type="text" id="total" value="0" /></code>```

答:
This solution is simple, just the get the list of all the inputs (i.e. checkbox, and dropdown) using the .find() method and the selector 'input:checkbox, input:text, select'. Then verify if  each one of these inputs elements has the attribute checked or select for the checkbox and select input types respectively, or it is a multiplier for the text inputs. This verification ca be done inside of the each() method callback. Finally, just convert then the value to a number, using the parseFloat() method and add it to the total accumulator.

Finally, sum the value to the total input. Like this:

let container;
let inputs;
let total;

function calcAndShowTotal() {
  let sum = 55435.04798; // it is constant value which must be the beginning value.
  let value;
  inputs.each(function() {
    if ($(this).is('input:checkbox:checked')) {
      // If is a checkbox
      value = parseFloat($(this).attr('price')) || 0;
      sum += value;
    } else if ($(this).is('input:text:not(#total)')) {
      // If is a text wait until you move to another element
      let factor = 1;
      if (this.id == 'm2') {
        factor = 3134.204499;
      } else if (this.id == 'binayasi') {
        factor = -566.2202888;
      }

      value = parseFloat($(this).val()) * factor || 0;
      sum += value;
    } else if ($(this).is('select')) {
      // If is a option from the select element
      value = parseFloat($('option:selected', this).val()) || 0;
      sum += value;
    }
  });
  total.val(sum);
}

function initHandlers() {
  inputs.on('keydown', function(e) {
    let focusable, next;
    if (e.keyCode == 13) {
      focusable = inputs.filter(':visible');
      next = focusable.eq(focusable.index(this) + 1);
      if (next.length) {
        next.focus();
      }
      return false;
    }
  });

  inputs.change(calcAndShowTotal);
  calcAndShowTotal();
}

$(function() {
  console.log('ready!');
  total = $('#total');
  container = $('#housepriceguesslist');
  inputs = container.find('input:checkbox, input:text, select');

  initHandlers();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
  Total: <input type="text" id="total" value="0" />
  <br/>
  <br/>
  <select id="ilce">
    <option value="0">Choose a state</option>
    <option value="63999.50712318567">Adalar</option>
    <option value="6259.918435398593">Ataşehir</option>
    <option value="46285.35729304834">Beykoz</option>
    <option value="54258.92953697798">Kadıköy</option>
    <option value="-3500.620905653726">Kartal</option>
    <option value="12889.41219909602">Maltepe</option>
    <option value="-33711.83156847153">Pendik</option>
    <option value="-34577.42485251657">Sancaktepe</option>
    <option value="-52183.1608811019">Sultanbeyli</option>
    <option value="-34760.71735007784">Tuzla</option>
    <option value="-27379.87966213786">Çekmeköy</option>
    <option value="-5332.203990418937">Ümraniye</option>
    <option value="26485.33532820411">Üsküdar</option>
    <option value="-18732.62070553167">Şile</option>
  </select>
  <select id="odasalon">
    <option value="0">Choose room number</option>
    <option value="5940.027623576261">1+0</option>
    <option value="-1399.625767475593">1+1</option>
    <option value="-3033.638999060459">2+1</option>
    <option value="11519.83954756076">3+1</option>
    <option value="-7018.52116545078">4+1</option>
    <option value="-6008.081239150166">5+1</option>
  </select>
  m2: <input type="text" id="m2" />
  Bina Yasi: <input type="text" id="binayasi" />
  <br/>
  <br/> Features:
  <br/>
  <br/>
  <input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
  <br/>
  <input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
  <br/>
  <input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
  <br/>
  <input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
  <br/>
  <input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
  <br/>
  <input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
  <br/>
  <input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
  <br/>
  <input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
  <br/>
  <input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
  <br/>
  <input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
  <br/>
  <input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
  <br/>
  <input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
  <br/>
  <input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
  <br/>
  <input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
  <br/>
  <input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
  <br/>
</div></code>```

Note:

Remember to round the numbers to get more precision. The text modification will apply after you tab, or move to another element. So I added an enter listener so when you press enter is gonna move to the next element like when  you press tab. Also, I moved the total to the top so you can see the results in the preview.

Update:

I recommend you to use the $(function(){}); to get the document when is ready. Inside you can assign the values of your elements. I notice that there was a bug in my code whenever ever you uncheck a checked element the Total should be 55435.04798, but it shows the double it is because total is also a text input.

Body:
I really don't know how to program in Javascript, yet I've tried to do some stuff. I have values to be summed if some are selected. The following function does sum operation and show result at once without clicking a button only for checkbox fields, not for the dropdown list and text fields.

However, I need to involve the selected values as well from the dropdown lists and entered both text fields in the same manner of the checkboxes and their immediate responses(output).

I think change method can be used in the same manner.

@Edit:

Sorry, I forgot the tell but, I need to multiply the m2 entered value by before summing with 3134,204499 and Bina Yasi with  -566,2202888.

function calcAndShowTotal() {
  var total = 55435.04798; // it is constant value which must be the beginning value.
  $('#housepriceguesslist :checkbox:checked').each(function() {
    total += parseFloat($(this).attr('price')) || 0;
  });
  $('#total').val(total);
}

$('#housepriceguesslist :checkbox').change(calcAndShowTotal).change();

  <select id="ilce">
    <option value="0">Choose a state</option>
    <option value="63999.50712318567">Adalar</option>
    <option value="6259.918435398593">Ataşehir</option>
    <option value="46285.35729304834">Beykoz</option>
    <option value="54258.92953697798">Kadıköy</option>
    <option value="-3500.620905653726">Kartal</option>
    <option value="12889.41219909602">Maltepe</option>
    <option value="-33711.83156847153">Pendik</option>
    <option value="-34577.42485251657">Sancaktepe</option>
    <option value="-52183.1608811019">Sultanbeyli</option>
    <option value="-34760.71735007784">Tuzla</option>
    <option value="-27379.87966213786">Çekmeköy</option>
    <option value="-5332.203990418937">Ümraniye</option>
    <option value="26485.33532820411">Üsküdar</option>
    <option value="-18732.62070553167">Şile</option>
  </select>

  <select id="odasalon">
    <option value="0">Choose room number</option>
    <option value="5940.027623576261">1+0</option>
    <option value="-1399.625767475593">1+1</option>
    <option value="-3033.638999060459">2+1</option>
    <option value="11519.83954756076">3+1</option>
    <option value="-7018.52116545078">4+1</option>
    <option value="-6008.081239150166">5+1</option>
  </select>

  m2: <input type="text" id="m2" /> Bina Yasi: <input type="text" id="binayasi" />

 Features:

  <input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> Bati

  <input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> Dogu

  <input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> Guney

  <input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> Kuzey

  <input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> Amerikan Mutfak

  <input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> Dusakabin

  <input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> Akilli Ev

  <input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> Ebeveyn Banyosu

  <input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> Kiler

  <input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> Kuvet

  <input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> Parke Zemin

  <input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> Seramik Zemin

  <input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> Sauna

  <input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> Spor Salonu

  <input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> Tenis Kortu

<input type="text" id="total" value="0" />

Body:
This solution is simple, just the get the list of all the inputs (i.e. checkbox, and dropdown) using the .find() method and the selector 'input:checkbox, input:text, select'. Then verify if  each one of these inputs elements has the attribute checked or select for the checkbox and select input types respectively, or it is a multiplier for the text inputs. This verification ca be done inside of the each() method callback. Finally, just convert then the value to a number, using the parseFloat() method and add it to the total accumulator.

Finally, sum the value to the total input. Like this:

let container;
let inputs;
let total;

function calcAndShowTotal() {
  let sum = 55435.04798; // it is constant value which must be the beginning value.
  let value;
  inputs.each(function() {
    if ($(this).is('input:checkbox:checked')) {
      // If is a checkbox
      value = parseFloat($(this).attr('price')) || 0;
      sum += value;
    } else if ($(this).is('input:text:not(#total)')) {
      // If is a text wait until you move to another element
      let factor = 1;
      if (this.id == 'm2') {
        factor = 3134.204499;
      } else if (this.id == 'binayasi') {
        factor = -566.2202888;
      }

      value = parseFloat($(this).val()) * factor || 0;
      sum += value;
    } else if ($(this).is('select')) {
      // If is a option from the select element
      value = parseFloat($('option:selected', this).val()) || 0;
      sum += value;
    }
  });
  total.val(sum);
}

function initHandlers() {
  inputs.on('keydown', function(e) {
    let focusable, next;
    if (e.keyCode == 13) {
      focusable = inputs.filter(':visible');
      next = focusable.eq(focusable.index(this) + 1);
      if (next.length) {
        next.focus();
      }
      return false;
    }
  });

  inputs.change(calcAndShowTotal);
  calcAndShowTotal();
}

$(function() {
  console.log('ready!');
  total = $('#total');
  container = $('#housepriceguesslist');
  inputs = container.find('input:checkbox, input:text, select');

  initHandlers();
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="housepriceguesslist">
  Total: <input type="text" id="total" value="0" />
  <br/>
  <br/>
  <select id="ilce">
    <option value="0">Choose a state</option>
    <option value="63999.50712318567">Adalar</option>
    <option value="6259.918435398593">Ataşehir</option>
    <option value="46285.35729304834">Beykoz</option>
    <option value="54258.92953697798">Kadıköy</option>
    <option value="-3500.620905653726">Kartal</option>
    <option value="12889.41219909602">Maltepe</option>
    <option value="-33711.83156847153">Pendik</option>
    <option value="-34577.42485251657">Sancaktepe</option>
    <option value="-52183.1608811019">Sultanbeyli</option>
    <option value="-34760.71735007784">Tuzla</option>
    <option value="-27379.87966213786">Çekmeköy</option>
    <option value="-5332.203990418937">Ümraniye</option>
    <option value="26485.33532820411">Üsküdar</option>
    <option value="-18732.62070553167">Şile</option>
  </select>
  <select id="odasalon">
    <option value="0">Choose room number</option>
    <option value="5940.027623576261">1+0</option>
    <option value="-1399.625767475593">1+1</option>
    <option value="-3033.638999060459">2+1</option>
    <option value="11519.83954756076">3+1</option>
    <option value="-7018.52116545078">4+1</option>
    <option value="-6008.081239150166">5+1</option>
  </select>
  m2: <input type="text" id="m2" />
  Bina Yasi: <input type="text" id="binayasi" />
  <br/>
  <br/> Features:
  <br/>
  <br/>
  <input type="checkbox" id="Bati" value="Bati" price="-783.4452683566533" /> <label for="Bati">Bati</label>
  <br/>
  <input type="checkbox" id="Dogu" value="Dogu" price="-4895.732009084263" /> <label for="Dogu">Dogu</label>
  <br/>
  <input type="checkbox" id="Guney" value="Guney" price="-2599.001349652765" /> <label for="Guney">Guney</label>
  <br/>
  <input type="checkbox" id="Kuzey" value="Kuzey" price="3832.013070771234" /> <label for="Kuzey">Kuzey</label>
  <br/>
  <input type="checkbox" id="Amerikan Mutfak" value="Amerikan Mutfak" price="2346.347889828301" /> <label for="Amerikan Mutfak">Amerikan Mutfak</label>
  <br/>
  <input type="checkbox" id="Dusakabin" value="Dusakabin" price="-176.5092353740256" /> <label for="Dusakabin">Dusakabin</label>
  <br/>
  <input type="checkbox" id="Akilli Ev" value="Akilli Ev" price="-4756.206384200719" /> <label for="Akilli Ev">Akilli Ev</label>
  <br/>
  <input type="checkbox" id="Ebeveyn Banyosu" value="Ebeveyn Banyosu" price="10135.50644456019" /> <label for="Ebeveyn Banyosu">Ebeveyn Banyosu</label>
  <br/>
  <input type="checkbox" id="Kiler" value="Kiler" price="-10693.49979821809" /> <label for="Kiler">Kiler</label>
  <br/>
  <input type="checkbox" id="Kuvet" value="Kuvet" price="-941.0629741243247" /> <label for="Kuvet">Kuvet</label>
  <br/>
  <input type="checkbox" id="Parke Zemin" value="Parke Zemin" price="-8453.847199707092" /> <label for="Parke Zemin">Parke Zemin</label>
  <br/>
  <input type="checkbox" id="Seramik Zemin" value="Seramik Zemin" price="1545.025601000643" /> <label for="Seramik Zemin">Seramik Zemin</label>
  <br/>
  <input type="checkbox" id="Sauna" value="Sauna" price="8677.708176289747" /> <label for="Sauna">Sauna</label>
  <br/>
  <input type="checkbox" id="Spor Salonu" value="Spor Salonu" price="1159.884679563385" /> <label for="Spor Salonu">Spor Salonu</label>
  <br/>
  <input type="checkbox" id="Tenis Kortu" value="Tenis Kortu" price="16065.26794172257" /> <label for="Tenis Kortu">Tenis Kortu</label>
  <br/>
</div>

Note:

Remember to round the numbers to get more precision. The text modification will apply after you tab, or move to another element. So I added an enter listener so when you press enter is gonna move to the next element like when  you press tab. Also, I moved the total to the top so you can see the results in the preview.

Update:

I recommend you to use the $(function(){}); to get the document when is ready. Inside you can assign the values of your elements. I notice that there was a bug in my code whenever ever you uncheck a checked element the Total should be 55435.04798, but it shows the double it is because total is also a text input.


来源: stackexchange

问:
How to fix constraints for allocation optimisation in PuLP python
Background:

I am trying to allocate customers Ci to financial advisers Pj. Each customer has a policy value xi. I'm assuming that the number of customers (n) allocated to each adviser is the same, and that the same customer cannot be assigned to multiple advisers. Therefore each partner will have an allocation of policy values like so:

P1=[x1,x2,x3] , P2=[x4,x5,x6], P3=[x7,x8,x9]

I am trying to find the optimal allocation to minimise dispersion in fund value between the advisers. I am defining dispersion as  the difference between the adviser with the highest fund value (z_max) and the lowest fund value (z_min).

The formulation for this problem is therefore:

where yij=1 if we allocate customer Ci to adviser Pj, 0 otherwise

The first constraint says that zmax has to be greater than or equal to each policy value; since the objective function encourages smaller values of zmax, this means that zmax will equal the largest policy value. Similarly, the second constraint sets zmin equal to the smallest policy value. The third constraint says that each customer must be assigned to exactly one adviser. The fourth says that each adviser must have n customers assigned to him/her. Credit: @LarrySnyder610

Problem:

When implementing this problem in PulP, I expect 1740 (n x p) customers to be allocated across the 173 advisers based on constraint 3 and 4. However 72036 and no optimal allocation is obtained.

import random
import pandas as pd
import pulp

=============================================================================
# SAMPLE DATA
=============================================================================

n = 10 # number of customers for each financial adviser
c = 414 #number of customers
p = 174 #number of financial adviser
policy_values = random.sample(range(1, 1000000), c)

set_I = range(c)
set_J = range(p)
set_N = range(n)
x = {i: policy_values[i] for i in set_I} #customer policy values
y = {(i,j): random.randint(0, 1) for i in set_I for j in set_J} # allocation dummies

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

# =============================================================================
# DECISION VARIABLES
# =============================================================================

y_vars  = {(i,j): pulp.LpVariable(cat=pulp.LpBinary, name="y_{0}_{1}".format(i,j)) for i in set_I for j in set_J}
z_max = pulp.LpVariable("Max Policy Value", 0)
z_min = pulp.LpVariable("Min Policy Value", 0)

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} <= z_max # constraint 1
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} >= z_min # constraint 2
model += {i: pulp.lpSum(y_vars[i,j] for j in set_J) for i in set_I} == 1 # constraint 3
model += {j: pulp.lpSum(y_vars[i,j] for i in set_I) for j in set_J} == n #constraint 4

# =============================================================================
# SOLVE MODEL
# =============================================================================

model.solve()
print('Optimised model status: '+str(pulp.LpStatus[model.status]))

count=0
for v in model.variables():
    if v.varValue == 1.0:
        count+=1
        #print(v.name, "=", v.varValue)
print(count)
#>>> 72036 # expecting 1740

print('Optimal difference between highest and lowest summed policy_value: ' + str(pulp.value(model.objective)))
```

<p>Do I need to make changes to the objective function/constraints to implement the above equations?</p>

<p>EDIT: Below snippet to try and implement @Erwin Kalvelagen's suggested changes. Still has extremely long durations for higher values of n,p and c:  </p>

<pre class="lang-py prettyprint-override"><code>y_sum = {}

# =============================================================================
# DECISION VARIABLES
# =============================================================================

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

y_vars = pulp.LpVariable.dicts('y_vars',((i,j) for i in set_I for j in set_J), lowBound=0, upBound = 1, cat=pulp.LpInteger)
z_max = pulp.LpVariable("Max Policy Value")
z_min = pulp.LpVariable("Min Policy Value")
for j in set_J:
    y_sum[j] = pulp.lpSum([y_vars[i,j] * x[i] for i in set_I])

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================

for j in set_J:
    model += pulp.lpSum([y_vars[i,j] for i in set_I]) == n
    model += y_sum[j] <= z_max
    model += y_sum[j] >= z_min

for i in set_I:
    model += pulp.lpSum([y_vars[i,j] for j in set_J]) == 1
</code>```

答:
Some hints:

Debug by print(model)

Start with a small data set

The constraints are not correctly formulated. It should be something like

```<code>for j in set_J:
    model += 1.0e-6 * pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) <= z_max # constraint 1
    model += 1.0e-6 * pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) >= z_min # constraint 2
    model += pulp.lpSum(y_vars[i,j] for i in set_I) == n #constraint 4

for i in set_I:
    model += pulp.lpSum(y_vars[i,j] for j in set_J) == 1 # constraint 3
</code>```

The model will be infeasible if n*p <> c

Detail: we should probably rewrite constraints 1 and 2. Repeating long summations will create a large number of nonzero elements.

ContentLicense: CC BY-SA 4.0

Body:
Background:

I am trying to allocate customers Ci to financial advisers Pj. Each customer has a policy value xi. I'm assuming that the number of customers (n) allocated to each adviser is the same, and that the same customer cannot be assigned to multiple advisers. Therefore each partner will have an allocation of policy values like so:

P1=[x1,x2,x3] , P2=[x4,x5,x6], P3=[x7,x8,x9]

I am trying to find the optimal allocation to minimise dispersion in fund value between the advisers. I am defining dispersion as  the difference between the adviser with the highest fund value (z_max) and the lowest fund value (z_min).

The formulation for this problem is therefore:

where yij=1 if we allocate customer Ci to adviser Pj, 0 otherwise

The first constraint says that zmax has to be greater than or equal to each policy value; since the objective function encourages smaller values of zmax, this means that zmax will equal the largest policy value. Similarly, the second constraint sets zmin equal to the smallest policy value. The third constraint says that each customer must be assigned to exactly one adviser. The fourth says that each adviser must have n customers assigned to him/her. Credit: @LarrySnyder610

Problem:

When implementing this problem in PulP, I expect 1740 (n x p) customers to be allocated across the 173 advisers based on constraint 3 and 4. However 72036 and no optimal allocation is obtained.

import random
import pandas as pd
import pulp

=============================================================================
# SAMPLE DATA
=============================================================================

n = 10 # number of customers for each financial adviser
c = 414 #number of customers
p = 174 #number of financial adviser
policy_values = random.sample(range(1, 1000000), c)

set_I = range(c)
set_J = range(p)
set_N = range(n)
x = {i: policy_values[i] for i in set_I} #customer policy values
y = {(i,j): random.randint(0, 1) for i in set_I for j in set_J} # allocation dummies

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

# =============================================================================
# DECISION VARIABLES
# =============================================================================

y_vars  = {(i,j): pulp.LpVariable(cat=pulp.LpBinary, name="y_{0}_{1}".format(i,j)) for i in set_I for j in set_J}
z_max = pulp.LpVariable("Max Policy Value", 0)
z_min = pulp.LpVariable("Min Policy Value", 0)

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} <= z_max # constraint 1
model += {j: pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) for j in set_J} >= z_min # constraint 2
model += {i: pulp.lpSum(y_vars[i,j] for j in set_J) for i in set_I} == 1 # constraint 3
model += {j: pulp.lpSum(y_vars[i,j] for i in set_I) for j in set_J} == n #constraint 4

# =============================================================================
# SOLVE MODEL
# =============================================================================

model.solve()
print('Optimised model status: '+str(pulp.LpStatus[model.status]))

count=0
for v in model.variables():
    if v.varValue == 1.0:
        count+=1
        #print(v.name, "=", v.varValue)
print(count)
#>>> 72036 # expecting 1740

print('Optimal difference between highest and lowest summed policy_value: ' + str(pulp.value(model.objective)))

Do I need to make changes to the objective function/constraints to implement the above equations?

EDIT: Below snippet to try and implement @Erwin Kalvelagen's suggested changes. Still has extremely long durations for higher values of n,p and c:

y_sum = {}

# =============================================================================
# DECISION VARIABLES
# =============================================================================

model = pulp.LpProblem("Allocation Model", pulp.LpMinimize)

y_vars = pulp.LpVariable.dicts('y_vars',((i,j) for i in set_I for j in set_J), lowBound=0, upBound = 1, cat=pulp.LpInteger)
z_max = pulp.LpVariable("Max Policy Value")
z_min = pulp.LpVariable("Min Policy Value")
for j in set_J:
    y_sum[j] = pulp.lpSum([y_vars[i,j] * x[i] for i in set_I])

# =============================================================================
# OBJECTIVE FUNCTION
# =============================================================================

model += z_max - z_min

# =============================================================================
# CONSTRAINTS
# =============================================================================

for j in set_J:
    model += pulp.lpSum([y_vars[i,j] for i in set_I]) == n
    model += y_sum[j] <= z_max
    model += y_sum[j] >= z_min

for i in set_I:
    model += pulp.lpSum([y_vars[i,j] for j in set_J]) == 1

Body:
Some hints:

Debug by print(model)

Start with a small data set

The constraints are not correctly formulated. It should be something like

for j in set_J:
    model += 1.0e-6 * pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) <= z_max # constraint 1
    model += 1.0e-6 * pulp.lpSum(y_vars[i,j] * x[i] for i in set_I) >= z_min # constraint 2
    model += pulp.lpSum(y_vars[i,j] for i in set_I) == n #constraint 4

for i in set_I:
    model += pulp.lpSum(y_vars[i,j] for j in set_J) == 1 # constraint 3

The model will be infeasible if n*p <> c

Detail: we should probably rewrite constraints 1 and 2. Repeating long summations will create a large number of nonzero elements.


问:
Create object hierarchy from Make output?
make -d and make -p provide useful information, but I need this in JSON format, so I can enumerate what libraries came from which source files, recursively.  Is there a way to do this already (approximately close, anyhow)?  Or is there a custom tool available?  I've scoured the Intarwebs, and my search has come up dry.  Thank you for any help!

Note: I'm looking for something that's similar to sysconfig.parse_makefile.  In fact, what that does is pretty close to what I'm looking for, except that it's only useful for the implicit Makefile that is used to build Python.  Any pointers?

答: It's not JSON, but the Perl CPAN module Makefile::GraphViz creates visualizations of the dependency graph from a makefile. If JSON is really what you want, you could probably capture the 'dot' dependency file that is generated and convert it to JSON fairly easily.</p>

ContentLicense: CC BY-SA 3.0


问:
Display Blobs/Photos stored in Azure-storage in Xamarin Mobile Application
Trying to develop a Xamarin Forms mobile application which displays blobs stored in Azure-Storage container through the api.

Current process goes like this
API > Azure-Storage Blob > Displayed in Xamarin mobile application.

Connecting to azure storage using Storage Account Key.

Problem is, blobs are not displaying in the mobile application when public access setting on the container is set to 'private'.
If the container public access setting is set to 'blob' then the photos display in the xamarin Mobile app.

Photo For illustration purposes.Photo of issue

Code is below.

```<code>string storageConnectionString
Environment.GetEnvironmentVariable("storageconnectionstring");

CloudStorageAccount storageAccount;
if (CloudStorageAccount.TryParse(storageConnectionString, out
storageAccount))
{
// If the connection string is valid, proceed with operations against
Blob storage here.
...
}
else
{
//Error
}
[enter image description here][1]CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
</code>```

How can i make the container private whilst still displaying the blobs in the mobile application?

答:
I think you might be using the wrong kind of connection to Azure blob storage.

You need to be using a shared key.

shared key authentication with azure blob storage

You will need to generate a new shared access signature.

create a new SAS

I hope this points you in the right direction.

Body:
Trying to develop a Xamarin Forms mobile application which displays blobs stored in Azure-Storage container through the api.

Current process goes like this
API > Azure-Storage Blob > Displayed in Xamarin mobile application.

Connecting to azure storage using Storage Account Key.

Problem is, blobs are not displaying in the mobile application when public access setting on the container is set to 'private'.
If the container public access setting is set to 'blob' then the photos display in the xamarin Mobile app.

Photo For illustration purposes.Photo of issue

Code is below.

string storageConnectionString
Environment.GetEnvironmentVariable("storageconnectionstring");

CloudStorageAccount storageAccount;
if (CloudStorageAccount.TryParse(storageConnectionString, out
storageAccount))
{
// If the connection string is valid, proceed with operations against
Blob storage here.
...
}
else
{
//Error
}
[enter image description here][1]CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

How can i make the container private whilst still displaying the blobs in the mobile application?


问:
Unexpected token ILLEGAL (ELF) Raspberry Pi Node Webkit Linux v0.31.3
I downloaded the sdk executable from dl.nwjs.io/v031.3, tried 32 and 64 bit version for Linux.

I try to run these on a raspberry pi 3b+,  with
node Desktop/nwjs-sdk-v0.31.3-linux-x64/nw

get this error:

```<code>(function (exports, require, module, __filename, __dirname) { ?ELF???

SyntaxError: Invalid or unexpected token
 at new Script
....... at startup (internal/bootstrap/node.js:240:19)
</code>```

Note I am running the code straight from nwjs.io, not copying any whitespace characters in from stackoverflow or other sources like somerelated questions suggest.

答:
The reason why it is not working is because you are trying to run NW.js compiled for x86 (and x64) platforms but Raspberry Pi uses ARM architecture.

You can find a NW.js binary that will work in all Raspberry Pi versions out of the box here: https://github.com/jalbam/nwjs_rpi

Body:
I downloaded the sdk executable from dl.nwjs.io/v031.3, tried 32 and 64 bit version for Linux.

I try to run these on a raspberry pi 3b+,  with
node Desktop/nwjs-sdk-v0.31.3-linux-x64/nw

get this error:

(function (exports, require, module, __filename, __dirname) { ?ELF???

SyntaxError: Invalid or unexpected token
 at new Script
....... at startup (internal/bootstrap/node.js:240:19)

Note I am running the code straight from nwjs.io, not copying any whitespace characters in from stackoverflow or other sources like somerelated questions suggest.


问:
Folium choropleth example; combining DataFrame with json data
I have a question about the use of the choropleth method in folium.  I have a DataFrame that I want to use a basis for colors, it looks like this:

I also have a json file that contains district boundaries in the city.  At present, my choropleth is not coloring based on the num column of my DataFrame which is what I aim to accomplish.  Here is my code for generating the map:

import json
import requests

url = 'http://data.beta.nyc//dataset/472dda10-79b3-4bfb-9c75-e7bd5332ec0b/resource/d826bbc6-a376-4642-8d8b-3a700d701557/download/88472a1f6fd94fef97b8c06335db60f7nyccommunitydistricts.geojson'

geo_json_data = json.loads(requests.get(url).text)

m = folium.Map([start[0], start[1]], zoom_start=9.5, tiles = 'Stamen Toner')

m.choropleth(geo_json_data, data = noise_plot, columns=['lat', 'long', 'num'], key_on='feature.id', fill_color= 'YlGn')

m
```

where noise_plot is the DataFrame in the image.  Here is what I see.  I think I am using the key_on argument incorrectly but not sure.  Thanks!

答: One approach that solved this was to adjust my GeoJson file to one that contained the zip code information and just map to this in order to color the regions.  Despite this, I imagine there are times when you have to use a lat and lon pair to match -- would be more curious about a solution here.

Body:
I have a question about the use of the choropleth method in folium.  I have a DataFrame that I want to use a basis for colors, it looks like this:

I also have a json file that contains district boundaries in the city.  At present, my choropleth is not coloring based on the num column of my DataFrame which is what I aim to accomplish.  Here is my code for generating the map:

import json
import requests

url = 'http://data.beta.nyc//dataset/472dda10-79b3-4bfb-9c75-e7bd5332ec0b/resource/d826bbc6-a376-4642-8d8b-3a700d701557/download/88472a1f6fd94fef97b8c06335db60f7nyccommunitydistricts.geojson'

geo_json_data = json.loads(requests.get(url).text)

m = folium.Map([start[0], start[1]], zoom_start=9.5, tiles = 'Stamen Toner')

m.choropleth(geo_json_data, data = noise_plot, columns=['lat', 'long', 'num'], key_on='feature.id', fill_color= 'YlGn')

m

where noise_plot is the DataFrame in the image.  Here is what I see.  I think I am using the key_on argument incorrectly but not sure.  Thanks!


问:
Why won't matplotlib draw work in pycharm?
I want to refresh a plot each time a long loop cycles. From my googling the best option seems to be using plt.draw() in the loop, rather than the animation module of matplotlib, because I only want it to update when new data becomes available.

However plt.draw() won't work in pycharm, even though it does work in the same interpreter when I run via an external shell. I don't even get an empty matplotlib window. I've tried with and without interactive mode.

Matplotlib version 3.1.0

Python version 3.6.5

Pycharm 2018.1.1

Below is some code from another post that works as expected outside of pycharm, but in pycharm I just get exit code 0, not even an error.

import matplotlib.pyplot as plt
import numpy as np
# import matplotlib
#
# print(matplotlib.get_backend())

for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()
```

Expect a sequence of random graphs, get nothing but exit code 0

答:
You don't need to use plt.draw(). Try this code:

import matplotlib.pyplot as plt
import numpy as np

for i in range(10):
    y = np.random.random([10, 1])
    plt.plot(y, 'o')
    plt.pause(3)
    plt.close()
```

Body:
I want to refresh a plot each time a long loop cycles. From my googling the best option seems to be using plt.draw() in the loop, rather than the animation module of matplotlib, because I only want it to update when new data becomes available.

However plt.draw() won't work in pycharm, even though it does work in the same interpreter when I run via an external shell. I don't even get an empty matplotlib window. I've tried with and without interactive mode.

Matplotlib version 3.1.0

Python version 3.6.5

Pycharm 2018.1.1

Below is some code from another post that works as expected outside of pycharm, but in pycharm I just get exit code 0, not even an error.

import matplotlib.pyplot as plt
import numpy as np
# import matplotlib
#
# print(matplotlib.get_backend())

for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()

Expect a sequence of random graphs, get nothing but exit code 0


问:
no multithreading benefit with single core
I'm new to concurrrent programming and multithreading.
I can understand the benefits of multithreading with multicore processors, but does those benefit exist on single core processor,

For example, let's say we have a multicore computer and  a program to sum up a very large number as:

```<code>int sum = 0;
for (i=1, i<9999999999, i++)
{
   sum += i;
}

doOtherStuff();  // execute other function that is irrelevant to sum
...
...
//and then finally print the sum
Console.WriteLine(sum);
</code>```

so for the long running sum task, we can create a second thread to calculate the sum and the main thread keeps executing other functions.

But if we run this program on a single core computer, there is no benefits to create multithreads, isn't it? it is even worse with multithreads because of the context switches?

答:
There are two primary benefits to multi-threading.

It allows non-sequential computations to happen simultaneously,
improving execution speed.

It also allows a program to not stall while waiting on blocking
operations.

In your example, there is no increase in execution speed, because the processor must still execute each of the commands in one core. However, if you were waiting for user input during the loop (or performing another blocking application), you would be unable to complete doOtherStuff() if it is in the same thread. By keeping doOtherStuff() and its blocking operations in a separate thread, you would not hold up the execution of the sum operation.

In order to keep multiple applications running with a single core processor, the operating system uses round-robin execution. It moves from one thread/application to another executing a few lines at a time. By separating blocking situations into different threads, you can take advantage of this. This is commonly done with i/o operations.

Now, "is it worse?"

If you are memory constrained, there may be concerns because each thread carries its own stack. However, since the operating system is already switching context between various applications and operations, the downside to execution time by adding to the round-robin is likely to be small.

Body:
I'm new to concurrrent programming and multithreading.
I can understand the benefits of multithreading with multicore processors, but does those benefit exist on single core processor,

For example, let's say we have a multicore computer and  a program to sum up a very large number as:

int sum = 0;
for (i=1, i<9999999999, i++)
{
   sum += i;
}

doOtherStuff();  // execute other function that is irrelevant to sum
...
...
//and then finally print the sum
Console.WriteLine(sum);

so for the long running sum task, we can create a second thread to calculate the sum and the main thread keeps executing other functions.

But if we run this program on a single core computer, there is no benefits to create multithreads, isn't it? it is even worse with multithreads because of the context switches?


问:
MySQL: how to convert SQL file to Workbench mwb file
I have a sql file that creates a database with all tables. But I want to work on the database in MySQL Workbench which provide UI interface. So I think I need to create a MySQL Model from the database that created by the SQL file. Didn't find a way to do it. There must be a way. Searched but all are from mwb to sql. Please help. Thanks</p>

答:
If you already have created your model, you will need to do a reverse engineer, with this you can see the model and then go to file - save model, this will save your model as mwb

Step 1

Step 2 ( Next , next, select your database and click execute)

Step 3 (In your EER view go to File - save model as)


问:
Equivalent to mysql regex
Mysql regex equivalent for this pattern:

```<code><table (.+)width:(.+)px
</code>```

I tried putting this pattern in my query but it will still hit items that doesn't have the pattern.

I use this site to check if the item hits that pattern above:
https://regex101.com/

This is my query:

```<code>select * from wp_posts where post_content regexp '<table (.+)width:(.+)px';
</code>```

This is the my sample post_content that is correct:

営業時間
月
火
水
木
金
土
日
祝

11:00～19:00
○
休
○
○
○
○
○
○

```
</div>
</div>
</p>

<p>This is the other sample post_content that is wrong. That will still hit even though there's no width on the table:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table-schedule">
 <tbody>
 <tr>
 <th>営業時間</th>
 <th>月</th>
 <th>火</th>
 <th>水</th>
 <th>木</th>
 <th>金</th>
 <th class="holiday">土</th>
 <th class="holiday">日</th>
 <th class="holiday">祝</th>
 </tr>
 <tr>
 <td style="text-align: center;">
 <p>11:00～19:00</p>
 </td>
 <td class="weekday maru" style="text-align: center;">○</td>
 <td class="weekday maru" style="text-align: center;">休</td>
 <td class="weekday maru" style="text-align: center;">○</td>
 <td class="weekday maru" style="text-align: center;">休</td>
 <td class="weekday maru" style="text-align: center;">○</td>
 <td class="holiday" style="text-align: center;">休</td>
 <td class="holiday" style="text-align: center;">休</td>
 <td class="holiday" style="text-align: center;">休</td>
 </tr>
 <tr>
 <td style="text-align: center;">
 <p>11:00～17:00</p>
 </td>
 <td style="text-align: center;">休</td>
 <td style="text-align: center;">○</td>
 <td style="text-align: center;">休</td>
 <td style="text-align: center;">○</td>
 <td style="text-align: center;">休</td>
 <td style="text-align: center;">○</td>
 <td style="text-align: center;">休</td>
 <td style="text-align: center;">休</td>
 </tr>
 </tbody>
 </table></code>```

Note: mysql version 5.6

答:
While your current regex pattern is valid, it won't behave the way you want, because the (.+) terms might match across tags.  Try this version:

```<code>SELECT *
FROM wp_posts
WHERE post_content REGEXP '<table [^>]+width: [0-9]+px';
</code>```

Demo

Title: Equivalent to mysql regex

Body:
Mysql regex equivalent for this pattern:

<table (.+)width:(.+)px

I tried putting this pattern in my query but it will still hit items that doesn't have the pattern.

I use this site to check if the item hits that pattern above:
https://regex101.com/

This is my query:

select * from wp_posts where post_content regexp '<table (.+)width:(.+)px';

This is the my sample post_content that is correct:

営業時間
月
火
水
木
金
土
日
祝

11:00～19:00
○
休
○
○
○
○
○
○

This is the other sample post_content that is wrong. That will still hit even though there's no width on the table:

 営業時間
 月
 火
 水
 木
 金
 土
 日
 祝

11:00～19:00

 ○
 休
 ○
 休
 ○
 休
 休
 休

11:00～17:00

 休
 ○
 休
 ○
 休
 ○
 休
 休

Note: mysql version 5.6

Body:
While your current regex pattern is valid, it won't behave the way you want, because the (.+) terms might match across tags.  Try this version:

SELECT *
FROM wp_posts
WHERE post_content REGEXP '<table [^>]+width: [0-9]+px';

Demo


问:
How to pass information from a WPF app to an HTML page
I got a WPF application which finds locations of latitude and longitude, and display them to the user inside the app. The app got a button that when clicked, is supposed to open a map using the Google maps API and display these locations on the map using markers.

I got this below script inside an HTML which as of now just opens a map on a fixed location and displaying just a sample marker.

```<code><script>
  function initMap() {
    let myLatLng = {lat: -25.363, lng: 131.044};

    let map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });

    let marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: 'TITLE!'
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<myKey>&callback=initMap">
</script>
</code>```

So I know that in order to open the page itself all I need to do is:

```<code>System.Diagnostics.Process.Start(pathToHtmlFile);
</code>```

but how exactly can I pass the locations I find in the WPF side to the JS initMap function?

答:
A different approach is to build the html file on the fly. This supports an arbitrarily large number of markers (Maximum of 256 to ~5000+, depending on memory and API constraints).

Split the HTML file into two parts, top and bottom (see the code below), on where the data needs to be inserted between.

Load the "top part" from the file into the variable Output and append the center of the map with the maps closing data tag } );.

Then loop through each marker, adding a new marker Javascript variable marker0, marker1... for each defined marker. This code is then appended to the Output variable.

The "bottom part" is appended to the Output variable and saved to the output file. This "end" file closes the opening function initMap(){ with } and the script tag and includes the load script for the Google Map with callback.

This saved file is then opened by the browser(no data passing required).

Place the top of the html file in a new project file called topTemplate.html(set the Properties: compile options to none and Copy to output directory: copy if newer):

```<code><script>
  function initMap() {

    let map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center:
</code>```

Note: I removed the let myLatLng = {lat: -25.363, lng: 131.044}; from the code, I "hard-coded"(to be defined in C#) it to simplify the division of segments(2 vs 3).

And the last portion in bottomTemplate.html(Same property settings as the above file):

```<code>    }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<myKey>&callback=initMap">
</script>
</code>```

Then in the WPF application:

To make things easier, I define a struct to hold the markers with a helper function to build the Output string.

```<code>public struct Marker
{
    public float Lat;
    public float Lng;
    public string Title;

    public Marker(float lat,float lng, string title)
    {
        Lat = lat;
        Lng = lng;
        Title = title;
    }

    public string BuildHTML(int nameAppend)
    {
        return  String.Format("\n let marker{0} = new google.maps.Marker({{ position: {{lat: {1:###0.0####}, lng: {2:###0.0####}}}, map: map, title: '{3}'}}); \n", nameAppend, Lat, Lng, Title);
    }
}
</code>```

The {{ and }} are the literal form of {}.
The ###0.0### returns an actual number to four decimal places. Without this code, the float could be represented by a scientific notation value or localized to a "," separator, either of which may be incompatible with the API. The "#"'s can be extended to the right of the decimal point to increase precision if needed.

The following code is placed mostly in the Method that opens the file, see comments:

```<code>// at top of file add:
using System.IO;
// rest of namespace, class definition and method opening

// Assumes all of the markers are stored in: List<Markers> markers = new List<Markers>();
// and the center of the map is stored in float lat; and float lng;

string Output = File.ReadAllText("topTemplate.html");
// Since the topTemplate ended with "center: " we must fill in the values and close the request.
Output += String.Format("{{lat: {1:###0.0####}, lng: {2:###0.0####}}} }} );\n",lat, lng);
int index = 0;
foreach(var item in markers)
{
    Output += item.BuildHTML(index++); //adds 1+ to the marker0 to form another variable marker1 ... for each marker variable name.
}
Output += "\n"; //add a vertical space to the Output. Before adding the end:
Output += File.ReadAllText("bottomTemplate.html");

 // we will assume pathToHtmlFile contains a valid filename and is in a writable directory. If not, move the path to %ProgramData% or %temp%.

File.WriteAllText(pathToHtmlFile, Output); // will overwrite the file if it exists.
// start the browser.
System.Diagnostics.Process.Start(pathToHtmlFile);

// The remainder of the file(method remainder and close, class remainder and close...)
</code>```

The starting of the browser may not run on client computers since, "This member(Process.Start) cannot be used by partially trusted code." This is a side note to the actual answer. Be sure to use an installer.

The indentation will be incorrect in the generated file, since Javascript is whitespace independent(all whitepace(newlines, tabs and multiple spaces are reduced to a single space)), this is not an issue.

The list of markers must be declared( List markers = new List();) as either a class level variable or in the top of the method.

Use markers.Add(new Marker(Latitude, Longitude, Title)); where "Latitude, Longitude, and Title" are replaced with their respective values(or variables containing them), to add each of the markers; Prior to calling the "method" above.

Body:
I got a WPF application which finds locations of latitude and longitude, and display them to the user inside the app. The app got a button that when clicked, is supposed to open a map using the Google maps API and display these locations on the map using markers.

I got this below script inside an HTML which as of now just opens a map on a fixed location and displaying just a sample marker.

So I know that in order to open the page itself all I need to do is:

System.Diagnostics.Process.Start(pathToHtmlFile);

but how exactly can I pass the locations I find in the WPF side to the JS initMap function?

Body:
A different approach is to build the html file on the fly. This supports an arbitrarily large number of markers (Maximum of 256 to ~5000+, depending on memory and API constraints).

Split the HTML file into two parts, top and bottom (see the code below), on where the data needs to be inserted between.

Load the "top part" from the file into the variable Output and append the center of the map with the maps closing data tag } );.

Then loop through each marker, adding a new marker Javascript variable marker0, marker1... for each defined marker. This code is then appended to the Output variable.

The "bottom part" is appended to the Output variable and saved to the output file. This "end" file closes the opening function initMap(){ with } and the script tag and includes the load script for the Google Map with callback.

This saved file is then opened by the browser(no data passing required).

Place the top of the html file in a new project file called topTemplate.html(set the Properties: compile options to none and Copy to output directory: copy if newer):

<script>
  function initMap() {

    let map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center:

Note: I removed the let myLatLng = {lat: -25.363, lng: 131.044}; from the code, I "hard-coded"(to be defined in C#) it to simplify the division of segments(2 vs 3).

And the last portion in bottomTemplate.html(Same property settings as the above file):

    }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<myKey>&callback=initMap">
</script>

Then in the WPF application:

To make things easier, I define a struct to hold the markers with a helper function to build the Output string.

public struct Marker
{
    public float Lat;
    public float Lng;
    public string Title;

    public Marker(float lat,float lng, string title)
    {
        Lat = lat;
        Lng = lng;
        Title = title;
    }

    public string BuildHTML(int nameAppend)
    {
        return  String.Format("\n let marker{0} = new google.maps.Marker({{ position: {{lat: {1:###0.0####}, lng: {2:###0.0####}}}, map: map, title: '{3}'}}); \n", nameAppend, Lat, Lng, Title);
    }
}

The {{ and }} are the literal form of {}.
The ###0.0### returns an actual number to four decimal places. Without this code, the float could be represented by a scientific notation value or localized to a "," separator, either of which may be incompatible with the API. The "#"'s can be extended to the right of the decimal point to increase precision if needed.

The following code is placed mostly in the Method that opens the file, see comments:

// at top of file add:
using System.IO;
// rest of namespace, class definition and method opening

// Assumes all of the markers are stored in: List<Markers> markers = new List<Markers>();
// and the center of the map is stored in float lat; and float lng;

string Output = File.ReadAllText("topTemplate.html");
// Since the topTemplate ended with "center: " we must fill in the values and close the request.
Output += String.Format("{{lat: {1:###0.0####}, lng: {2:###0.0####}}} }} );\n",lat, lng);
int index = 0;
foreach(var item in markers)
{
    Output += item.BuildHTML(index++); //adds 1+ to the marker0 to form another variable marker1 ... for each marker variable name.
}
Output += "\n"; //add a vertical space to the Output. Before adding the end:
Output += File.ReadAllText("bottomTemplate.html");

 // we will assume pathToHtmlFile contains a valid filename and is in a writable directory. If not, move the path to %ProgramData% or %temp%.

File.WriteAllText(pathToHtmlFile, Output); // will overwrite the file if it exists.
// start the browser.
System.Diagnostics.Process.Start(pathToHtmlFile);

// The remainder of the file(method remainder and close, class remainder and close...)

The starting of the browser may not run on client computers since, "This member(Process.Start) cannot be used by partially trusted code." This is a side note to the actual answer. Be sure to use an installer.

The indentation will be incorrect in the generated file, since Javascript is whitespace independent(all whitepace(newlines, tabs and multiple spaces are reduced to a single space)), this is not an issue.

The list of markers must be declared( List markers = new List();) as either a class level variable or in the top of the method.

Use markers.Add(new Marker(Latitude, Longitude, Title)); where "Latitude, Longitude, and Title" are replaced with their respective values(or variables containing them), to add each of the markers; Prior to calling the "method" above.


问:
Load a dicom file with cornerstone js from an S3 bucket in AWS
I need to load an image from a dicom file stored in an S3 bucket in AWS. I am using cornerstone js with reactjs.

I know how to load the images from my local directory, but I dont know how to retrieve them from the cloud. I have looked for solutions, but non of them have worked for me.

答:
You should use the cornerstoneWADOImageLoader to load the DICOM image into the cornerstone viewer.

This will allow you to use a URL to load the DICOM file
You can check the example here by directly pasting the link from your AWS S3, just make sure that CORS is enabled and it is accessible in AWS: https://rawgit.com/cornerstonejs/cornerstoneWADOImageLoader/master/examples/wadouri/index.html

The example source code can be found here: https://github.com/cornerstonejs/cornerstoneWADOImageLoader/blob/master/examples/wadouri/index.html


问:
What size should I maintain for %rsp when alloc stack in asm, multiple of 16 or multiple of 16 plus 8
In this answer Segmentation fault on printf - NASM 64bit Linux the first author says when I allock stack  the %rsp must keep multiple of 16 plus 8 because afterwards a function call will push address on stack  , But In ABI ,it says rsp must be multiple of 16 in program entry, And When I really try I found keep rsp multiple of 16 plus 8 cause segmentation fault even when then I call printf@PLT afterwards,but Keep it multiple of 16 works, So what should I do for rsp when alloc stack ?</p>

答:
But In ABI ,it says rsp must be multiple of 16 in program entry

_start is not a function.  It's not called by anything, there is no return address on the stack (just argc and the actual argv[] and envp[] arrays).

Yes, on process entry RSP is already 16-byte aligned, ready for a function call.

I edited Jester's answer again on the question you linked to clarify it.

16-byte aligned before a call is the requirement.  You get back to that with an offset of 16 * n + 8 inside your function before another call, including any pushes.


问:
Problem with picking up a -Dattribute in Maven using Antrun
So I have this snippet in my pom

```<code><configuration>
  <target if="csc" >
    <echo>Unzipping md csc help</echo>
  </target>
  <target unless="csc">
    <echo>Unzipping md help</echo>
  </target>
</configuration>
</code>```

When I run with mvn normally it correctly executes the unless="csc" target. The problem is that when I run it with -Dcsc=true it does not run any of the targets.

What am I doing wrong? :)

Thanks

答: The unpacking can be done via the maven-dependency plugin.</p>

Body:
So I have this snippet in my pom

<configuration>
  <target if="csc" >
    <echo>Unzipping md csc help</echo>
  </target>
  <target unless="csc">
    <echo>Unzipping md help</echo>
  </target>
</configuration>

When I run with mvn normally it correctly executes the unless="csc" target. The problem is that when I run it with -Dcsc=true it does not run any of the targets.

What am I doing wrong? :)

Thanks


问:
React Native, AppStore requests NSLocationAlwaysUsageDescription value
I have an app with React Native. I've been uploading correctly to the app store, but today the app is rejected with the following message:

Missing Info.plist key - This app attempts to access privacy-sensitive
  data without a usage description. The app's Info.plist must contain an
  NSLocationAlwaysUsageDescription key with a string value explaining to
  the user how the app uses this data.

Missing Info.plist key - This app attempts to access privacy-sensitive
  data without a usage description. The app's Info.plist must contain an
  NSLocationWhenInUseUsageDescription key with a string value explaining
  to the user how the app uses this data.

My app doesn't use any kind of location service. The npm packages have not changed since the last version published to the app store neither have been updated, they are the same versions.

So I don't understand why Apple is saying that I am attempting to access the user location.

It is a change in the Apple Store? How can I check where is my app trying to access the user location?

This is my packages.json

```<code>  "dependencies": {
    "axios": "^0.17.1",
    "lodash": "^4.17.4",
    "moment": "^2.18.1",
    "react": "^16.0.0",
    "react-addons-shallow-compare": "^15.5.2",
    "react-native": "0.53.0",
    "react-native-drawer": "^2.3.0",
    "react-native-elements": "^0.19.0",
    "react-native-fetch-blob": "^0.10.5",
    "react-native-fs": "^2.3.3",
    "react-native-linear-gradient": "^2.0.0",
    "react-native-onesignal": "^3.0.7",
    "react-native-orientation": "^3.0.0",
    "react-native-pdf": "^3.0.0",
    "react-native-progress": "^3.4.0",
    "react-native-render-html": "^3.8.1",
    "react-native-router-flux": "^4.0.0-beta.28",
    "react-native-vector-icons": "^4.1.1",
    "react-native-video": "^2.0.0",
    "react-native-video-controls": "^2.0.0",
    "react-redux": "^5.0.4",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0"
  }
</code>```

Thank you.

答: Simply remove RCTGeolocation.xcodeproj from your Libraries folder in the left panel of Xcode, if you are really positive you don't depend on any geo location. Removing .xcodeproj will unlink libs. </p>

Body:
I have an app with React Native. I've been uploading correctly to the app store, but today the app is rejected with the following message:

Missing Info.plist key - This app attempts to access privacy-sensitive
  data without a usage description. The app's Info.plist must contain an
  NSLocationAlwaysUsageDescription key with a string value explaining to
  the user how the app uses this data.

Missing Info.plist key - This app attempts to access privacy-sensitive
  data without a usage description. The app's Info.plist must contain an
  NSLocationWhenInUseUsageDescription key with a string value explaining
  to the user how the app uses this data.

My app doesn't use any kind of location service. The npm packages have not changed since the last version published to the app store neither have been updated, they are the same versions.

So I don't understand why Apple is saying that I am attempting to access the user location.

It is a change in the Apple Store? How can I check where is my app trying to access the user location?

This is my packages.json

  "dependencies": {
    "axios": "^0.17.1",
    "lodash": "^4.17.4",
    "moment": "^2.18.1",
    "react": "^16.0.0",
    "react-addons-shallow-compare": "^15.5.2",
    "react-native": "0.53.0",
    "react-native-drawer": "^2.3.0",
    "react-native-elements": "^0.19.0",
    "react-native-fetch-blob": "^0.10.5",
    "react-native-fs": "^2.3.3",
    "react-native-linear-gradient": "^2.0.0",
    "react-native-onesignal": "^3.0.7",
    "react-native-orientation": "^3.0.0",
    "react-native-pdf": "^3.0.0",
    "react-native-progress": "^3.4.0",
    "react-native-render-html": "^3.8.1",
    "react-native-router-flux": "^4.0.0-beta.28",
    "react-native-vector-icons": "^4.1.1",
    "react-native-video": "^2.0.0",
    "react-native-video-controls": "^2.0.0",
    "react-redux": "^5.0.4",
    "redux": "^3.6.0",
    "redux-thunk": "^2.2.0"
  }

Thank you.


问:
Custom SignIn & SignUp on RESTlet + GAE/J?
I am currently working on a small project using RESTlet on Google App Engine/Java.

I was searching.. searching.. and couldn't find the exact or understandable solutions for my doubts.

My question is that How am I suppose to implement my own SignIn & SignUp module without using google's UserService or Spring Security??

Is there any actual sample code available??

I mean SignUp part is just a simple JDO insert & select module. let's just say I've done it.

How am I supposed to handle each user's request session and authentication??

I am thinking about using HTTPS on every request.

Any suggestions or help would be really appreciated!

Thanks in advance.

答:
In Restlet, you have security support on both client and server sides. On client side, you can specify security hints using the ChallengeResponse entity. This feature is open and you can specify the authentication type you want. In the following code, I use an http basic authentication based on username / password:

```<code>ClientResource cr = new ClientResource(uri);
ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;
ChallengeResponse authentication = new ChallengeResponse(
                          scheme, "username", "password");
cr.setChallengeResponse(authentication);
</code>```

Restlet will automatically build necessary headers in the corresponding request. You can note that Restlet supports a wide range of authentication types through its extensions. I know that some work is done at the moment to support OAuth v2 (see http://wiki.restlet.org/developers/172-restlet/257-restlet/310-restlet.html).

On the server side, you need to secure accesses at routing level using the ChallengeAuthenticator entity, as described below. This can be done within your Restlet application:

```<code>public Restlet createInboundRoot() {
    Router router = new Router(getContext());

    ChallengeAuthenticator guard = new ChallengeAuthenticator(getContext(),
                                         ChallengeScheme.HTTP_BASIC, "realm");
    guard.setVerifier(verifier);
    guard.setEnroler(enroler);

    guard.setNext(router);
    return guard;
}
</code>```

Like for client side, this support is generic and is based on two interfaces that need to be specified on the guard:

The verifier one to check if authentication is successful

The enroler one to fill roles for the authenticated user

You can notice that same security technologies need to be use on both sides...

If you want to manage authentication session for user, you need to implement it by yourself using cookies.

When authentication successes on server side, you can return a cookie containing a security token that allows you checking the user from your database (for example). Some code like below can implement that:

```<code>CookieSetting cookie = new CookieSetting(0,
                 SECURITY_COOKIE_NAME, securityToken);
Series<CookieSetting> cookieSettings = response.getCookieSettings();
cookieSettings.clear();
cookieSettings.add(cookie);
</code>```

You can extend for example the SecretVerifier class of Restlet to add a test on security data received and add this code when receiving the security cookie.

On client side, you need to add hints for authentication the first time and then re send the security cookie following times, as described below:

```<code>ClientResource clientResource = (...)
(...)
Cookie securityCookie = new Cookie(0,
             SECURITY_COOKIE_NAME, securityToken);
clientResource.getRequest().getCookies().clear();
clientResource.getRequest().getCookies().add(securityCookie);
</code>```

Hope it will help you!
Thierry

ContentLicense: CC BY-SA 2.5

Body:
In Restlet, you have security support on both client and server sides. On client side, you can specify security hints using the ChallengeResponse entity. This feature is open and you can specify the authentication type you want. In the following code, I use an http basic authentication based on username / password:

ClientResource cr = new ClientResource(uri);
ChallengeScheme scheme = ChallengeScheme.HTTP_BASIC;
ChallengeResponse authentication = new ChallengeResponse(
                          scheme, "username", "password");
cr.setChallengeResponse(authentication);

Restlet will automatically build necessary headers in the corresponding request. You can note that Restlet supports a wide range of authentication types through its extensions. I know that some work is done at the moment to support OAuth v2 (see http://wiki.restlet.org/developers/172-restlet/257-restlet/310-restlet.html).

On the server side, you need to secure accesses at routing level using the ChallengeAuthenticator entity, as described below. This can be done within your Restlet application:

public Restlet createInboundRoot() {
    Router router = new Router(getContext());

    ChallengeAuthenticator guard = new ChallengeAuthenticator(getContext(),
                                         ChallengeScheme.HTTP_BASIC, "realm");
    guard.setVerifier(verifier);
    guard.setEnroler(enroler);

    guard.setNext(router);
    return guard;
}

Like for client side, this support is generic and is based on two interfaces that need to be specified on the guard:

The verifier one to check if authentication is successful

The enroler one to fill roles for the authenticated user

You can notice that same security technologies need to be use on both sides...

If you want to manage authentication session for user, you need to implement it by yourself using cookies.

When authentication successes on server side, you can return a cookie containing a security token that allows you checking the user from your database (for example). Some code like below can implement that:

CookieSetting cookie = new CookieSetting(0,
                 SECURITY_COOKIE_NAME, securityToken);
Series<CookieSetting> cookieSettings = response.getCookieSettings();
cookieSettings.clear();
cookieSettings.add(cookie);

You can extend for example the SecretVerifier class of Restlet to add a test on security data received and add this code when receiving the security cookie.

On client side, you need to add hints for authentication the first time and then re send the security cookie following times, as described below:

ClientResource clientResource = (...)
(...)
Cookie securityCookie = new Cookie(0,
             SECURITY_COOKIE_NAME, securityToken);
clientResource.getRequest().getCookies().clear();
clientResource.getRequest().getCookies().add(securityCookie);

Hope it will help you!
Thierry


问:
doesn't add img from array to div background
I want to add a background image to a div from an array. It works when I just set the background like this:

```<code>div.style.background = "url(path/to/img.jpg) no-repeat"
</code>```

But if I take it from an array such as this:

```<code>const array=[
    '"url(path/to/img.jpg) no repeat"',
    '"url(path/to/img2.jpg) no repeat"',
    '"url(path/to/img3.jpg) no repeat"'
];
div.style.background = array[1];
</code>```

it does not work.

```<code>const grid = document.getElementById("grid");
const photos = ['"url(img/DSC_0387.JPG) no-repeat"', '"url(img/DSC_0389.JPG) no-repeat"', '"url(img/DSC_0392.JPG) no-repeat"', '"url(img/DSC_0393.JPG) no-repeat"', '"url(img/DSC_0399.JPG) no-repeat"'];

function add() {
  let div = document.createElement('div');
  div.style.background = photos[2];
  div.style.borderRadius = "10px";
  div.style.height = "350px";
  div.style.backgroundSize = "contain";
  grid.appendChild(div);
};
add();
</code>```

答:
welcome to StackOverflow.

Your photos array has double-quotes wrapping the value, you should remove it.

The quotes will be handled automatically, you just need to pass a normal string to div.style.background with the desired value. Currently you're passing a string that starts with ", thus being not a valid value for this attribute, resulting in this not being rendered on DOM.

Body:
I want to add a background image to a div from an array. It works when I just set the background like this:

div.style.background = "url(path/to/img.jpg) no-repeat"

But if I take it from an array such as this:

const array=[
    '"url(path/to/img.jpg) no repeat"',
    '"url(path/to/img2.jpg) no repeat"',
    '"url(path/to/img3.jpg) no repeat"'
];
div.style.background = array[1];

it does not work.

const grid = document.getElementById("grid");
const photos = ['"url(img/DSC_0387.JPG) no-repeat"', '"url(img/DSC_0389.JPG) no-repeat"', '"url(img/DSC_0392.JPG) no-repeat"', '"url(img/DSC_0393.JPG) no-repeat"', '"url(img/DSC_0399.JPG) no-repeat"'];

function add() {
  let div = document.createElement('div');
  div.style.background = photos[2];
  div.style.borderRadius = "10px";
  div.style.height = "350px";
  div.style.backgroundSize = "contain";
  grid.appendChild(div);
};
add();


答:
Remove the double set of quotes in the photos array.

i.e. '"url(img/DSC_0387.JPG) no-repeat"' becomes 'url(img/DSC_0387.JPG) no-repeat'

const grid = document.getElementById("grid");
const photos = ['url(img/DSC_0387.JPG) no-repeat', 'url(img/DSC_0389.JPG) no-repeat','url(img/DSC_0392.JPG) no-repeat','url(img/DSC_0393.JPG) no-repeat','url(img/DSC_0399.JPG) no-repeat'];

function add(){
    let div = document.createElement('div');
    console.log(photos[2]);
    div.style.background = photos[2];
    div.style.borderRadius = "10px";
    div.style.height = "350px";
    div.style.backgroundSize = "contain";

    grid.appendChild(div);
};
add();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="grid"></div></code>```

Title: doesn't add img from array to div background

Body:
Remove the double set of quotes in the photos array.

i.e. '"url(img/DSC_0387.JPG) no-repeat"' becomes 'url(img/DSC_0387.JPG) no-repeat'

const grid = document.getElementById("grid");
const photos = ['url(img/DSC_0387.JPG) no-repeat', 'url(img/DSC_0389.JPG) no-repeat','url(img/DSC_0392.JPG) no-repeat','url(img/DSC_0393.JPG) no-repeat','url(img/DSC_0399.JPG) no-repeat'];

function add(){
    let div = document.createElement('div');
    console.log(photos[2]);
    div.style.background = photos[2];
    div.style.borderRadius = "10px";
    div.style.height = "350px";
    div.style.backgroundSize = "contain";

    grid.appendChild(div);
};
add();

<div id="grid"></div>


问:
Spark Structred Streaming Kafka - how to read from a specific partition of topic and do offset managerment
Me new to spark structured stream and offset management of kafka.
Using spark-streaming-kafka-0-10-2.11.
In consumer, how can I read from specific partition of a topic ?

```<code>comapany_df = sparkSession
                      .readStream()
                      .format("kafka")
                      .option("kafka.bootstrap.servers", applicationProperties.getProperty(BOOTSTRAP_SERVERS_CONFIG))
                      .option("subscribe", topicName)
</code>```

I am using something like above. how to specify a particular partition to read from ?

答:
You can use the following code block to read from a particular Kafka Partition.</p>

```<code>public void processKafka() throws InterruptedException {
    LOG.info("************ SparkStreamingKafka.processKafka start");

   // Create the spark application
    SparkConf sparkConf = new SparkConf();
    sparkConf.set("spark.executor.cores", "5");

    //To express any Spark Streaming computation, a StreamingContext object needs to be created.
    //This object serves as the main entry point for all Spark Streaming functionality.
    //This creates the spark streaming context with a 'numSeconds' second batch size
    jssc = new JavaStreamingContext(sparkConf, Durations.seconds(sparkBatchInterval));

    //List of parameters
    Map<String, Object> kafkaParams = new HashMap<>();
    kafkaParams.put("bootstrap.servers", this.getBrokerList());
    kafkaParams.put("client.id", "SpliceSpark");
    kafkaParams.put("group.id", "mynewgroup");
    kafkaParams.put("auto.offset.reset", "earliest");
    kafkaParams.put("enable.auto.commit", false);
    kafkaParams.put("key.deserializer", StringDeserializer.class);
    kafkaParams.put("value.deserializer", StringDeserializer.class);

    List<TopicPartition> topicPartitions= new ArrayList<TopicPartition>();
    for(int i=0; i<5; i++) {
        topicPartitions.add(new TopicPartition("mytopic", i));
    }

    //List of kafka topics to process
    Collection<String> topics = Arrays.asList(this.getTopicList().split(","));

    JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(
            jssc,
            LocationStrategies.PreferConsistent(),
            ConsumerStrategies.<String, String>Subscribe(topics, kafkaParams)
          );

    //Another version of an attempt
    /*
    JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(
        jssc,
        LocationStrategies.PreferConsistent(),
        ConsumerStrategies.<String, String>Assign(topicPartitions, kafkaParams)
      );
     */

    messages.foreachRDD(new PrintRDDDetails());

    // Start running the job to receive and transform the data
    jssc.start();

    //Allows the current thread to wait for the termination of the context by stop() or by an exception
    jssc.awaitTermination();
}
</code>```

Body:
Me new to spark structured stream and offset management of kafka.
Using spark-streaming-kafka-0-10-2.11.
In consumer, how can I read from specific partition of a topic ?

comapany_df = sparkSession
                      .readStream()
                      .format("kafka")
                      .option("kafka.bootstrap.servers", applicationProperties.getProperty(BOOTSTRAP_SERVERS_CONFIG))
                      .option("subscribe", topicName)

I am using something like above. how to specify a particular partition to read from ?

Body:
You can use the following code block to read from a particular Kafka Partition.

public void processKafka() throws InterruptedException {
    LOG.info("************ SparkStreamingKafka.processKafka start");

   // Create the spark application
    SparkConf sparkConf = new SparkConf();
    sparkConf.set("spark.executor.cores", "5");

    //To express any Spark Streaming computation, a StreamingContext object needs to be created.
    //This object serves as the main entry point for all Spark Streaming functionality.
    //This creates the spark streaming context with a 'numSeconds' second batch size
    jssc = new JavaStreamingContext(sparkConf, Durations.seconds(sparkBatchInterval));

    //List of parameters
    Map<String, Object> kafkaParams = new HashMap<>();
    kafkaParams.put("bootstrap.servers", this.getBrokerList());
    kafkaParams.put("client.id", "SpliceSpark");
    kafkaParams.put("group.id", "mynewgroup");
    kafkaParams.put("auto.offset.reset", "earliest");
    kafkaParams.put("enable.auto.commit", false);
    kafkaParams.put("key.deserializer", StringDeserializer.class);
    kafkaParams.put("value.deserializer", StringDeserializer.class);

    List<TopicPartition> topicPartitions= new ArrayList<TopicPartition>();
    for(int i=0; i<5; i++) {
        topicPartitions.add(new TopicPartition("mytopic", i));
    }

    //List of kafka topics to process
    Collection<String> topics = Arrays.asList(this.getTopicList().split(","));

    JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(
            jssc,
            LocationStrategies.PreferConsistent(),
            ConsumerStrategies.<String, String>Subscribe(topics, kafkaParams)
          );

    //Another version of an attempt
    /*
    JavaInputDStream<ConsumerRecord<String, String>> messages = KafkaUtils.createDirectStream(
        jssc,
        LocationStrategies.PreferConsistent(),
        ConsumerStrategies.<String, String>Assign(topicPartitions, kafkaParams)
      );
     */

    messages.foreachRDD(new PrintRDDDetails());

    // Start running the job to receive and transform the data
    jssc.start();

    //Allows the current thread to wait for the termination of the context by stop() or by an exception
    jssc.awaitTermination();
}


问:
Retry logic and connection pooling for Azure sql Db with nodejs
I have a bot built using botbuilder Sdk V3 that needs to make azure sql Db calls upon user's questions. We have about 10k users who might be accessing this bot in production making concurrent requests (not all 10k but few ) few times per day.

I am thinking to have some Retry logic in my code, connection pooling, connection timeouts that will help to manage database connections gracefully.

I have tried sample here
which doesn't do any retry or pooling.

I have searched all examples here but didn't find nodejs example doing what I need.

I am expecting to do something like this mentioned in the document.

答: I suggest looking into tedious and tedious connection pool.  I've used them for Azure SQL in production for over 3 years and it's worked great (without special retry logic).</p>


问:
How to pass wildcard for XPath to be consumed by Selenium(c#)
I want to FindElements with XPath for my Selenium (C#) webdriver, which iterates through different account numbers in an angular rows. To know the number of rows present I want to get a count by passing wild-card for xpath, replacing the part where account number is passed. However, can't get this to work

Xpath are as below:

```<code>//*[@id="mr-name-1234568"]
//*[@id="mr-name-7895874"]
</code>```

where AccountNumber = 1234568 & 7895874 (and might vary)

I have tried like below, but selenium isn't recognizing it -

```<code>var rows = driver.FindElements(By.XPath("//*[@id='mr-name-*']"));
int Rows = rows.Count();
</code>```

It would be great to know how wild-card is passed above to get number of rows irrespective of what the account number may be.

答:
Using starts-with in your OP case.

Here is the xpath that you can use.

```<code>var rows = driver.FindElements(By.XPath("//*[starts-with(@id,'mr-name-')]"));
</code>```

You have to use starts-with in this scenario as the first part of the id is consistent. Below is the general notation

```<code> //tag[starts-with(@attribute,'first_static_part_in_attribute_value')]
</code>```

ends-with? What to do if the dynamic content is at the beginning of the attribute value.

ends-with is an option in xpath 2.0, but most of the common browsers like chrome, firefox support xpath 1.0. So we have to work around to achieve the outcome similar to ends-with using string-length,substring and =. Below is the example.

Sample HTML:

  <button id="mr-name-7895874">Dynamic content at the end 1</button>
  <button id="7895234-mr-name">Dynamic content at the start 1</button>
  <button id="104-mr-name">Dynamic content at the start 2</button>
  <button id="789523499-mr-name">Dynamic content at the start 3</button>
  <button id="mr-name-74">Dynamic content at the end 2</button>

```
</div>
</div>
</p>

<p>Now you have 3 buttons that are having dynamic number at the starting position, but the static text <code>-mr-name</code> is at the end. So we have to <em>find 3 buttons where id ends-with '-mr-name`</em>.</p>

<p><strong>Xpath 1.0: similar to ends-with in xpath 2.0</strong></p>

```//*[substring(@id, string-length(@id) - string-length('-mr-name') +1) = '-mr-name']
```

Let's see how this worked. Consider 104-mr-name as id value for understanding purpose.

string-length(@id) : This will find the length of the id attribute value (11 chars).

string-length('-mr-name'): This will find the length of the string that we are checking for (8 chars).

substring(@id,starting_position): Here the starting position is (11-8)+1= 4 (we are adding 1 to make sure we don't miss the first char -).

Last step is compare both substring with the expected static string (here -mr-name is the static string) using =.

Screenshot:

Body:
I want to FindElements with XPath for my Selenium (C#) webdriver, which iterates through different account numbers in an angular rows. To know the number of rows present I want to get a count by passing wild-card for xpath, replacing the part where account number is passed. However, can't get this to work

Xpath are as below:

//*[@id="mr-name-1234568"]
//*[@id="mr-name-7895874"]

where AccountNumber = 1234568 & 7895874 (and might vary)

I have tried like below, but selenium isn't recognizing it -

var rows = driver.FindElements(By.XPath("//*[@id='mr-name-*']"));
int Rows = rows.Count();

It would be great to know how wild-card is passed above to get number of rows irrespective of what the account number may be.

Body:
Using starts-with in your OP case.

Here is the xpath that you can use.

var rows = driver.FindElements(By.XPath("//*[starts-with(@id,'mr-name-')]"));

You have to use starts-with in this scenario as the first part of the id is consistent. Below is the general notation

 //tag[starts-with(@attribute,'first_static_part_in_attribute_value')]

ends-with? What to do if the dynamic content is at the beginning of the attribute value.

ends-with is an option in xpath 2.0, but most of the common browsers like chrome, firefox support xpath 1.0. So we have to work around to achieve the outcome similar to ends-with using string-length,substring and =. Below is the example.

Sample HTML:

<html>
   <body>
  <button id="mr-name-7895874">Dynamic content at the end 1</button>
  <button id="7895234-mr-name">Dynamic content at the start 1</button>
  <button id="104-mr-name">Dynamic content at the start 2</button>
  <button id="789523499-mr-name">Dynamic content at the start 3</button>
  <button id="mr-name-74">Dynamic content at the end 2</button>
   </body>
</html>

Now you have 3 buttons that are having dynamic number at the starting position, but the static text -mr-name is at the end. So we have to find 3 buttons where id ends-with '-mr-name`.

Xpath 1.0: similar to ends-with in xpath 2.0

//*[substring(@id, string-length(@id) - string-length('-mr-name') +1) = '-mr-name']

Let's see how this worked. Consider 104-mr-name as id value for understanding purpose.

string-length(@id) : This will find the length of the id attribute value (11 chars).

string-length('-mr-name'): This will find the length of the string that we are checking for (8 chars).

substring(@id,starting_position): Here the starting position is (11-8)+1= 4 (we are adding 1 to make sure we don't miss the first char -).

Last step is compare both substring with the expected static string (here -mr-name is the static string) using =.

Screenshot:


问:
MessageBox is hidden when select different tab page
I am doing a check-in check-out system for equipment and chemical item.
Firstly, I design check-in/checkout only for equipment. Everything works fine.
When I click checkout button, a message box will pop out showing the item is checked out.

Then I add in chemical, which the equipment list and chemical list display on datagridview in different tab page (Using tab control).
1) When I select the equipment list and click the checkout button, a message box will pop out.
2) when I select the chemical list and click the checkout button, a message box will not pop out and the current window is unclickable. Until I use other windows to cover the application and click the application again, then I can see the pop-out message box. After I close the pop-out message box, all the function works well.

The code for message box pop out:

```<code> MessageBox.Show("Item successfully checked out.", "Success");
 DialogResult = DialogResult.OK;
 Close();
</code>```

EDIT

I found out that the datagridview for the chemical list is somehow refreshing all the data inside although no code is called to refresh the dataview.

答: Some other events are running cause the window did not pop out immediately. The problem I am facing is rowprepaint events. It causes the events always running and the window still focuses and activated. That why the new window pop out did not show up.</p>

Body:
I am doing a check-in check-out system for equipment and chemical item.
Firstly, I design check-in/checkout only for equipment. Everything works fine.
When I click checkout button, a message box will pop out showing the item is checked out.

Then I add in chemical, which the equipment list and chemical list display on datagridview in different tab page (Using tab control).
1) When I select the equipment list and click the checkout button, a message box will pop out.
2) when I select the chemical list and click the checkout button, a message box will not pop out and the current window is unclickable. Until I use other windows to cover the application and click the application again, then I can see the pop-out message box. After I close the pop-out message box, all the function works well.

The code for message box pop out:

 MessageBox.Show("Item successfully checked out.", "Success");
 DialogResult = DialogResult.OK;
 Close();

EDIT

I found out that the datagridview for the chemical list is somehow refreshing all the data inside although no code is called to refresh the dataview.


问:
The match in mapbox expression is an exact match,how to use fuzzy match in the expression
I use this method,but the result is exact match,can not fuzzy match</p>

```<code>map.setPaintProperty('building_layeres', 'fill-extrusion-color', [
      'case',
      ['==', ['get', 'NAME'], '腾讯大厦'],
      'red',
      ['==', ['get', 'NAME'], '彩讯科技大厦'],
      'red',
      '#aaa',])
</code>```

答:
Mapbox-GL only supports a very small range of string manipulation operators, which don't include regular expressions or other forms of wildcard.

You can see them here: https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-string

Body:
I use this method,but the result is exact match,can not fuzzy match

map.setPaintProperty('building_layeres', 'fill-extrusion-color', [
      'case',
      ['==', ['get', 'NAME'], '腾讯大厦'],
      'red',
      ['==', ['get', 'NAME'], '彩讯科技大厦'],
      'red',
      '#aaa',])


问:
Check if it is possible to create a Binary Matrix When sum of each row and column is given?
Given sum of each row and each column in a matrix check whether a binary matrix can be created ?

Input :

The first row of input contains two numbers 1≤m,n≤100000000, the number of rows and columns of the matrix. The next row contains m numbers 0≤ri≤n – the sum of each row in the matrix. The third row contains n numbers 0≤cj≤m – the sum of each column in the matrix.

Output:

Output “YES” if there exists an m-by-n matrix A, with each element either being 0 or 1. Else "NO".

I trid the solution posted in Finding if binary matrix exists given the row and column sums

Above Solution works fine for small inputs but when input is of the order of 1 billion then the testing plaforms like codility times out.I need a solution that is better than o(m*n).Can someone please help here?

答:
you can use maxflow algorithm;it is available in different sources such as https://www.geeksforgeeks.org/ford-fulkerson-algorithm-for-maximum-flow-problem/ or somewhere else.

for this problem you have to make a graph with 4 layers;
in first and 4th use just one node,in fact they are source and destination in maxflow algorithm.

and in second and third layer you have to use m and n node and between each node from one layer to another layer is an edge with capacity=1
this is what you named matrix in your question .

as we say before in your second layer we have m node and all is connected to first node(source in maxflow algorithm) and it's weights are what you get as input.
and for third and 4th(destination node) is the same with m node and m input values.

after running your algorithm,
if all the capacity of nodes are used so your answer is yes,and if not your answer is no.
why?
everywhere you used capacity it show the 1 in your matrix and you need all 1s so your answer should have all the flow.
and as you see,between node number a from secnod layer and nember b from third ,if it has flow so in your matrix m, m[a][b]=1.