问:
Prolog permutation predicate using insertion of elements
I am trying to write a predicate permutation/2 so that it is true if and only if both arguments are list, one a permutation of the other. To do this, I've written the two helper predicates delete/3 and insert/3. The first is true if and only if the third argument is the second argument, both lists, with the first instance of the element in the first argument removed. The second is true if and only if the third argument equals the second argument with the first argument (element) inserted.

```<code>delete(X,[X|T],T). % Base case, element equals head.
delete(X,[A|B],[A|C]) :- delete(X,B,C). % Else, repeat for the tail.

insert(X,[],[X]). % Base case.
insert(X,[H|T],B) :- delete(H,B,U), insert(X,T,U). % Delete all elements from B.

permutation([],[]). % Base case.
permutation([H|T],P) :- permutation(Q,T), insert(H,Q,P). % P a permutation of T, H inserted.
</code>```

My idea is that the query

```<code>?- insert(A,B,X).
</code>```

For given A, B should return all ways of instantiating X so that it equals the list B with the element A added somewhere. However, it does not do this:

```<code>?- insert(3,[1,2],X).
X = [1, 2, 3] ;
X = [1, 3, 2] ;
ERROR: Out of global stack
</code>```

I think this is because of the way I defined the predicate, checking if the list in the third argument minus every element of the list in the second argument equals the list containing only the first argument, rather than defining it constructively, but I am having a hard time solving this problem another way. The permutation predicate should then check if the list in its second argument is a permutation recursively, by checking if P is a permutation of the tail of the first list with the head randomly inserted. Help is appreciated!

答:
Both insert/3 and delete/3 is the same predicate and it is found in textbooks as select/3. It is also in standard library, for example in SWI-Prolog you can find it as select/3. You can use it to insert or delete, just change the position of the list as necessary.

Delete "b" from "abc":

```<code>?- select(b, [a,b,c], X).
X = [a, c] ;
false.
</code>```

Insert "b" in "ac" in any position:

```<code>?- select(b, X, [a,c]).
X = [b, a, c] ;
X = [a, b, c] ;
X = [a, c, b] ;
false.
</code>```

It is defined exactly as you did define delete/3, if you see the source of lists.pl in SWI-Prolog which is open source you will see it.

```<code>select(X, [X|Tail], Tail).
select(Elem, [Head|Tail], [Head|Rest]) :-
    select(Elem, Tail, Rest).
</code>```

But now you can define permutation just like you described. Because I find also this in the same source file lists.pl I just copy the source here, and it is ok because it is open source:

```<code>perm([], []).
perm(List, [First|Perm]) :-
    select(First, List, Rest),
    perm(Rest, Perm).
</code>```

I use lists:perm because it is "private" but it is not private it is just not exported:

```<code>?- lists:perm([a,b,c], P).
P = [a, b, c] ;
P = [a, c, b] ;
P = [b, a, c] ;
P = [b, c, a] ;
P = [c, a, b] ;
P = [c, b, a] ;
false.

?- lists:perm([a,b,c], [b,a,c]).
true ;
false.
</code>```

I have just one message and it is: read the textbook and read the source because it helps you learn much faster.

Body:
I am trying to write a predicate permutation/2 so that it is true if and only if both arguments are list, one a permutation of the other. To do this, I've written the two helper predicates delete/3 and insert/3. The first is true if and only if the third argument is the second argument, both lists, with the first instance of the element in the first argument removed. The second is true if and only if the third argument equals the second argument with the first argument (element) inserted.

delete(X,[X|T],T). % Base case, element equals head.
delete(X,[A|B],[A|C]) :- delete(X,B,C). % Else, repeat for the tail.

insert(X,[],[X]). % Base case.
insert(X,[H|T],B) :- delete(H,B,U), insert(X,T,U). % Delete all elements from B.

permutation([],[]). % Base case.
permutation([H|T],P) :- permutation(Q,T), insert(H,Q,P). % P a permutation of T, H inserted.

My idea is that the query

?- insert(A,B,X).

For given A, B should return all ways of instantiating X so that it equals the list B with the element A added somewhere. However, it does not do this:

?- insert(3,[1,2],X).
X = [1, 2, 3] ;
X = [1, 3, 2] ;
ERROR: Out of global stack

I think this is because of the way I defined the predicate, checking if the list in the third argument minus every element of the list in the second argument equals the list containing only the first argument, rather than defining it constructively, but I am having a hard time solving this problem another way. The permutation predicate should then check if the list in its second argument is a permutation recursively, by checking if P is a permutation of the tail of the first list with the head randomly inserted. Help is appreciated!

Body:
Both insert/3 and delete/3 is the same predicate and it is found in textbooks as select/3. It is also in standard library, for example in SWI-Prolog you can find it as select/3. You can use it to insert or delete, just change the position of the list as necessary.

Delete "b" from "abc":

?- select(b, [a,b,c], X).
X = [a, c] ;
false.

Insert "b" in "ac" in any position:

?- select(b, X, [a,c]).
X = [b, a, c] ;
X = [a, b, c] ;
X = [a, c, b] ;
false.

It is defined exactly as you did define delete/3, if you see the source of lists.pl in SWI-Prolog which is open source you will see it.

select(X, [X|Tail], Tail).
select(Elem, [Head|Tail], [Head|Rest]) :-
    select(Elem, Tail, Rest).

But now you can define permutation just like you described. Because I find also this in the same source file lists.pl I just copy the source here, and it is ok because it is open source:

perm([], []).
perm(List, [First|Perm]) :-
    select(First, List, Rest),
    perm(Rest, Perm).

I use lists:perm because it is "private" but it is not private it is just not exported:

?- lists:perm([a,b,c], P).
P = [a, b, c] ;
P = [a, c, b] ;
P = [b, a, c] ;
P = [b, c, a] ;
P = [c, a, b] ;
P = [c, b, a] ;
false.

?- lists:perm([a,b,c], [b,a,c]).
true ;
false.

I have just one message and it is: read the textbook and read the source because it helps you learn much faster.


来源: stackexchange

问:
How to iterate over  tags using BS4?
Running into some problems using BS4 to extract specific elements.  This is taken from the Texas Department of Corrections Executed Inmates page.

I've attached a screenshot for better understanding.

Within each tr tag, there are multiple td tags containing text about First Name, Last Name, TDCJ Number, Age, Date, etc.

How can I get BS4 to skip over the first tr tag (the first tr tag are the column names) and for each subsequent tr tag, extract the text from the td tags?

```<code>from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv

def main():
    gettabledata()

lstofinmates = list()

def gettabledata():
    with urlopen('https://www.tdcj.state.tx.us/death_row/dr_executed_offenders.html') as response:

    soup = BeautifulSoup(response, 'html.parser')

    with open('exinmates.csv', 'w', newline='') as output_file:
        inmate_file_writer = csv.DictWriter(output_file,
                                           fieldnames=['First Name', 'Last Name', 'Execution Number',
                                                       'Last Statement', 'TDCJ Number', 'Age', 'Date Executed', 'Race',
                                                       'County'],
                                           extrasaction='ignore',
                                           delimiter=',', quotechar='"')
        inmate_file_writer.writeheader()
        table = soup.find('table').find('tbody')
        print (table)

if __name__ == '__main__':
    main()
</code>```

I'm thinking of creating of LOD structure where each dictionary corresponds to an inmate information, and the text from the td fields are pushed into the dictionary, and each dictionary is appended into a list.  The problem is that I can't find a way to skip the first tr tag and how to iterate over the rest of the tr tags to append them into a dictionary.  Any suggestions/help?  Thanks!

答:
Here is something to get you started:</p>

```<code>from bs4 import BeautifulSoup
html = '''<h1>Executed Offenders</h1>
<table class="os" width="100%">
  <tbody>
      <tr><th scope="col">Execution</th><th scope="col">Link</th><th scope="col">Link</th><th scope="col">Last Name</th><th scope="col">First Name</th><th scope="col">TDCJ Number</th><th scope="col">Age</th><th scope="col">Date</th><th scope="col">Race</th><th scope="col">County</th</tr>
      <tr><td>542</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Bigby</td><td>James</td><td>997</td><td>61</td><td>3/14/2017</td><td>White</td><td>Tarrant</td></tr>
      <tr><td>541</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Ruiz</td><td>Rolando</td><td>999145</td><td>44</td><td>3/07/2017</td><td>Hispanic</td><td>Bexar</td></tr>
      <tr><td>540</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Edwards</td><td>Terry</td><td>999463</td><td>43</td><td>1/26/2017</td><td>Black</td><td>Dallas</td></tr>
      <tr><td>539</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Wilkins</td><td>Christopher</td><td>999533</td><td>48</td><td>01/11/2017</td><td>White</td><td>Tarrant</td></tr>
      <tr><td>538</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Fuller</td><td>Barney</td><td>999481</td><td>58</td><td>10/05/2016</td><td>White</td><td>Houston</td></tr>
  </tbody>
</table>'''

soup = BeautifulSoup(html, 'html.parser')
rows = iter(soup.find('table').find_all('tr'))

# skip first row
next(rows)

for row in rows:
    for cell in row.find_all('td'):
        print(cell)
    print()
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to iterate over <td> tags using BS4?

Body:
Running into some problems using BS4 to extract specific elements.  This is taken from the Texas Department of Corrections Executed Inmates page.

I've attached a screenshot for better understanding.

Within each tr tag, there are multiple td tags containing text about First Name, Last Name, TDCJ Number, Age, Date, etc.

How can I get BS4 to skip over the first tr tag (the first tr tag are the column names) and for each subsequent tr tag, extract the text from the td tags?

from urllib.request import urlopen
from bs4 import BeautifulSoup
import csv

def main():
    gettabledata()

lstofinmates = list()

def gettabledata():
    with urlopen('https://www.tdcj.state.tx.us/death_row/dr_executed_offenders.html') as response:

    soup = BeautifulSoup(response, 'html.parser')

    with open('exinmates.csv', 'w', newline='') as output_file:
        inmate_file_writer = csv.DictWriter(output_file,
                                           fieldnames=['First Name', 'Last Name', 'Execution Number',
                                                       'Last Statement', 'TDCJ Number', 'Age', 'Date Executed', 'Race',
                                                       'County'],
                                           extrasaction='ignore',
                                           delimiter=',', quotechar='"')
        inmate_file_writer.writeheader()
        table = soup.find('table').find('tbody')
        print (table)

if __name__ == '__main__':
    main()

I'm thinking of creating of LOD structure where each dictionary corresponds to an inmate information, and the text from the td fields are pushed into the dictionary, and each dictionary is appended into a list.  The problem is that I can't find a way to skip the first tr tag and how to iterate over the rest of the tr tags to append them into a dictionary.  Any suggestions/help?  Thanks!

Body:
Here is something to get you started:

from bs4 import BeautifulSoup
html = '''<h1>Executed Offenders</h1>
<table class="os" width="100%">
  <tbody>
      <tr><th scope="col">Execution</th><th scope="col">Link</th><th scope="col">Link</th><th scope="col">Last Name</th><th scope="col">First Name</th><th scope="col">TDCJ Number</th><th scope="col">Age</th><th scope="col">Date</th><th scope="col">Race</th><th scope="col">County</th</tr>
      <tr><td>542</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Bigby</td><td>James</td><td>997</td><td>61</td><td>3/14/2017</td><td>White</td><td>Tarrant</td></tr>
      <tr><td>541</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Ruiz</td><td>Rolando</td><td>999145</td><td>44</td><td>3/07/2017</td><td>Hispanic</td><td>Bexar</td></tr>
      <tr><td>540</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Edwards</td><td>Terry</td><td>999463</td><td>43</td><td>1/26/2017</td><td>Black</td><td>Dallas</td></tr>
      <tr><td>539</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Wilkins</td><td>Christopher</td><td>999533</td><td>48</td><td>01/11/2017</td><td>White</td><td>Tarrant</td></tr>
      <tr><td>538</td><td><a href="#">Offender Information</a></td><td><a href="#">Last Statement</a></td><td>Fuller</td><td>Barney</td><td>999481</td><td>58</td><td>10/05/2016</td><td>White</td><td>Houston</td></tr>
  </tbody>
</table>'''

soup = BeautifulSoup(html, 'html.parser')
rows = iter(soup.find('table').find_all('tr'))

# skip first row
next(rows)

for row in rows:
    for cell in row.find_all('td'):
        print(cell)
    print()


问:
Change color component
I'm writing graphic shader program. I wrote everything I need except the color changing. In cycle there is passing some counter variable to the shader and I have to change it's color from white to orange shade. What I have change to achive this?</p>

答:
I'm not sure I've got you right, but my guess is you need something like this:</p>

```<code>uniform float counter; // assumed range 0 .. 1

const vec3 WHITE = vec3(1,1,1);
const vec3 ORANGE = vec3(1,0.6,0.2);

void main() {

    vec3 mixedColor = mix(WHITE,ORANGE,counter);
    // will be white for counter < 0,
    //         orange for counter > 1,
    //         shaded in between
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Change color component

Body:
I'm not sure I've got you right, but my guess is you need something like this:

uniform float counter; // assumed range 0 .. 1

const vec3 WHITE = vec3(1,1,1);
const vec3 ORANGE = vec3(1,0.6,0.2);

void main() {

    vec3 mixedColor = mix(WHITE,ORANGE,counter);
    // will be white for counter < 0,
    //         orange for counter > 1,
    //         shaded in between
}


问:
Chart.js Multiple dataset
I have a problem with Chart.js.

I want an an alert show me the ID value set in the dataset when I click on a point in the chart.

I have tried using getElementsAtEvent(evt);, but it doesn't work as I expected.

Can somebody help me? Thanks!

var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];

var scatterChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
        label: 'Linea A',
        backgroundColor: "transparent",
        borderColor: color[1],
        pointBackgroundColor: color[1],
        pointBorderColor: color[1],
        pointHoverBackgroundColor: color[1],
        pointHoverBorderColor: color[1],
        data: [{
          x: "2014-09-02",
          y: 90,
          id: '1A'
        }, {
          x: "2014-11-02",
          y: 96,
          id: '2A'
        }, {
          x: "2014-12-03",
          y: 97,
          id: '3A'
        }]
      },
      {
        label: 'Linea B',
        backgroundColor: "transparent",
        borderColor: color[2],
        pointBackgroundColor: color[2],
        pointBorderColor: color[2],
        pointHoverBackgroundColor: color[2],
        pointHoverBorderColor: color[2],
        data: [{
          x: "2014-09-01",
          y: 96,
          id: "1B"
        }, {
          x: "2014-10-04",
          y: 95.8,
          id: "2B"
        }, {
          x: "2014-11-06",
          y: 99,
          id: "3B"
        }]
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Polveri',
      fontSize: 18
    },
    legend: {
      display: true,
      position: "bottom"
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'MM/YY',
            'second': 'MM/YY',
            'minute': 'MM/YY',
            'hour': 'MM/YY',
            'day': 'MM/YY',
            'week': 'MM/YY',
            'month': 'MM/YY',
            'quarter': 'MM/YY',
            'year': 'MM/YY',
          },
          tooltipFormat: "DD/MM/YY"
        }
      }]
    }
  }
});

document.getElementById("myChart").onclick = function(evt) {
  var activePoints = scatterChart.getElementsAtEvent(evt);
  var firstPoint = activePoints[1];
  console.log(firstPoint._datasetIndex);
  console.log(firstPoint._index);
  var label = scatterChart.data.labels[firstPoint._index];
  console.log(scatterChart.data.datasets[0].data[0].id);
  var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
  if (firstPoint !== undefined)
    alert(label + ": " + value);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
</script>
<canvas id="myChart" width="400" height="100"></canvas></code>```

答:
You need to use the .getElementAtEvent() prototype method instead of .getElementsAtEvent().  The difference being the first only returns the single point that you clicked whereas the other returns all points at the X axis for that click.

Here is an example.

```<code>document.getElementById("canvas").onclick = function(evt) {
  var activePoint = myLine.getElementAtEvent(event);

  // make sure click was on an actual point
  if (activePoint.length > 0) {
    var clickedDatasetIndex = activePoint[0]._datasetIndex;
    var clickedElementindex = activePoint[0]._index;
    var label = myLine.data.labels[clickedElementindex];
    var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];
    alert("Clicked: " + label + " - " + value);
  }
};
</code>```

You can see a demonstration at this codepen.

ContentLicense: CC BY-SA 4.0

Title: Chart.js Multiple dataset

Body:
I have a problem with Chart.js.

I want an an alert show me the ID value set in the dataset when I click on a point in the chart.

I have tried using getElementsAtEvent(evt);, but it doesn't work as I expected.

Can somebody help me? Thanks!

var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];

var scatterChart = new Chart(ctx, {
  type: 'line',
  data: {
    datasets: [{
        label: 'Linea A',
        backgroundColor: "transparent",
        borderColor: color[1],
        pointBackgroundColor: color[1],
        pointBorderColor: color[1],
        pointHoverBackgroundColor: color[1],
        pointHoverBorderColor: color[1],
        data: [{
          x: "2014-09-02",
          y: 90,
          id: '1A'
        }, {
          x: "2014-11-02",
          y: 96,
          id: '2A'
        }, {
          x: "2014-12-03",
          y: 97,
          id: '3A'
        }]
      },
      {
        label: 'Linea B',
        backgroundColor: "transparent",
        borderColor: color[2],
        pointBackgroundColor: color[2],
        pointBorderColor: color[2],
        pointHoverBackgroundColor: color[2],
        pointHoverBorderColor: color[2],
        data: [{
          x: "2014-09-01",
          y: 96,
          id: "1B"
        }, {
          x: "2014-10-04",
          y: 95.8,
          id: "2B"
        }, {
          x: "2014-11-06",
          y: 99,
          id: "3B"
        }]
      }
    ]
  },
  options: {
    title: {
      display: true,
      text: 'Polveri',
      fontSize: 18
    },
    legend: {
      display: true,
      position: "bottom"
    },
    scales: {
      xAxes: [{
        type: 'time',
        time: {
          displayFormats: {
            'millisecond': 'MM/YY',
            'second': 'MM/YY',
            'minute': 'MM/YY',
            'hour': 'MM/YY',
            'day': 'MM/YY',
            'week': 'MM/YY',
            'month': 'MM/YY',
            'quarter': 'MM/YY',
            'year': 'MM/YY',
          },
          tooltipFormat: "DD/MM/YY"
        }
      }]
    }
  }
});

document.getElementById("myChart").onclick = function(evt) {
  var activePoints = scatterChart.getElementsAtEvent(evt);
  var firstPoint = activePoints[1];
  console.log(firstPoint._datasetIndex);
  console.log(firstPoint._index);
  var label = scatterChart.data.labels[firstPoint._index];
  console.log(scatterChart.data.datasets[0].data[0].id);
  var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
  if (firstPoint !== undefined)
    alert(label + ": " + value);
};

<canvas id="myChart" width="400" height="100"></canvas>

Body:
You need to use the .getElementAtEvent() prototype method instead of .getElementsAtEvent().  The difference being the first only returns the single point that you clicked whereas the other returns all points at the X axis for that click.

Here is an example.

document.getElementById("canvas").onclick = function(evt) {
  var activePoint = myLine.getElementAtEvent(event);

  // make sure click was on an actual point
  if (activePoint.length > 0) {
    var clickedDatasetIndex = activePoint[0]._datasetIndex;
    var clickedElementindex = activePoint[0]._index;
    var label = myLine.data.labels[clickedElementindex];
    var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];
    alert("Clicked: " + label + " - " + value);
  }
};

You can see a demonstration at this codepen.


问:
How to run npm or angular 2 ng serve command from Bash Script?
I am looking to create an interactive bash script for our development team (never did this before) as our project has various needs and due to future growth on the team I want this to be easy as pi.

Normally for my work on the team I would change directory to the angular folder and run ng serve which kicks off the frontend development server. How do I do that in a bash script?

So far I have this:

```<code>#!/bin/bash
echo -e "Hello, "$USER".\nWelcome to the BICE build script!\nVersion 0.1"
echo -e "Which build option do you wish to use?\n1. Frontend (default)\n2. Backend\n3. Database\n4. Production"
echo -n "Enter your choice [1-4] or press [ENTER]:"
read choice
if [choice == 1]; then
  echo "Option 1 selected"
  cd /angular
  #call ng serve
</code>```

Thanks!

答:
/angular seems weird as a working directory but if angular is a subdirectory of the one holding the script a

```<code>cd ./angular
ng serve
cd ..
</code>```

should work...

Maybe you could look at this question so you can call the script from any working directory.

Also note that you are missing a fi at the end of your if,  there sould be spaces after opening and before closing bracket and choice should be referenced with a $ sign:

```<code>#!/bin/bash
echo -e "Hello, "$USER".\nWelcome to the BICE build script!\nVersion 0.1"
echo -e "Which build option do you wish to use?\n1. Frontend (default)\n2. Backend\n3. Database\n4. Production"
echo -n "Enter your choice [1-4] or press [ENTER]:"
read choice
if [ $choice == 1 ]; then
  echo "Option 1 selected"
  cd ./angular
  ng serve
  cd ..
fi
</code>```

Body:
I am looking to create an interactive bash script for our development team (never did this before) as our project has various needs and due to future growth on the team I want this to be easy as pi.

Normally for my work on the team I would change directory to the angular folder and run ng serve which kicks off the frontend development server. How do I do that in a bash script?

So far I have this:

#!/bin/bash
echo -e "Hello, "$USER".\nWelcome to the BICE build script!\nVersion 0.1"
echo -e "Which build option do you wish to use?\n1. Frontend (default)\n2. Backend\n3. Database\n4. Production"
echo -n "Enter your choice [1-4] or press [ENTER]:"
read choice
if [choice == 1]; then
  echo "Option 1 selected"
  cd /angular
  #call ng serve

Thanks!

Body:
/angular seems weird as a working directory but if angular is a subdirectory of the one holding the script a

cd ./angular
ng serve
cd ..

should work...

Maybe you could look at this question so you can call the script from any working directory.

Also note that you are missing a fi at the end of your if,  there sould be spaces after opening and before closing bracket and choice should be referenced with a $ sign:

#!/bin/bash
echo -e "Hello, "$USER".\nWelcome to the BICE build script!\nVersion 0.1"
echo -e "Which build option do you wish to use?\n1. Frontend (default)\n2. Backend\n3. Database\n4. Production"
echo -n "Enter your choice [1-4] or press [ENTER]:"
read choice
if [ $choice == 1 ]; then
  echo "Option 1 selected"
  cd ./angular
  ng serve
  cd ..
fi


问:
Remove duplicates in dataframe pandas based on values of two columns
I have a dataframe of customers with some items, which looks like this:

```<code>Customer ID     Item
     1         Banana
     1         Apple
     2         Orange
     3         Grape
     4         Banana
     4         Apple
     5         Orange
     5         Grape
     6         Orange
</code>```

What I'm willing to do is to remove all duplicates customers with same items, so the results should look like this:

```<code>Customer ID     Item
     1         Banana
     1         Apple
     2         Orange
     3         Grape
     5         Orange
     5         Grape
</code>```

As customer 4 has the same items as customer 1. Also customer 6  with 2.

Thanks in advance for your help!

答:
Not sure if this is what you means. But if you mean duplicates based on the items, you can collect the items for each customer as a frozenset (if unique), or tuple (if not unique), and then apply drop_duplicates; later on do a filter on the original data frame based on the customer ID.

```<code>df[df["Customer ID"].isin(df.groupby("Customer ID").Item.apply(frozenset).drop_duplicates().index)]
</code>```

Or if items are not unique and order doesn't matter:

```<code>df[df["Customer ID"].isin(df.groupby("Customer ID")
                            .Item.apply(lambda x: tuple(sorted(x)))
                            .drop_duplicates().index)]
</code>```

Body:
I have a dataframe of customers with some items, which looks like this:

Customer ID     Item
     1         Banana
     1         Apple
     2         Orange
     3         Grape
     4         Banana
     4         Apple
     5         Orange
     5         Grape
     6         Orange

What I'm willing to do is to remove all duplicates customers with same items, so the results should look like this:

Customer ID     Item
     1         Banana
     1         Apple
     2         Orange
     3         Grape
     5         Orange
     5         Grape

As customer 4 has the same items as customer 1. Also customer 6  with 2.

Thanks in advance for your help!

Body:
Not sure if this is what you means. But if you mean duplicates based on the items, you can collect the items for each customer as a frozenset (if unique), or tuple (if not unique), and then apply drop_duplicates; later on do a filter on the original data frame based on the customer ID.

df[df["Customer ID"].isin(df.groupby("Customer ID").Item.apply(frozenset).drop_duplicates().index)]

Or if items are not unique and order doesn't matter:

df[df["Customer ID"].isin(df.groupby("Customer ID")
                            .Item.apply(lambda x: tuple(sorted(x)))
                            .drop_duplicates().index)]


问:
How can I Create a Tableview Under Custom Tableview cell
I am just thinking. Suppose, i have a tableview which have custom cell. It's simple. But My idea is that, when i click a tableview cell then another tableview is appear under that tableview cell, and again i click that cell then that sub tableview disappear. Similarly when i click second cell than work same. Is it possible? Please Provide me any idea or reference.</p>

答:
This is entirely possible, you're talking about Expandable cells.

My example here

The general idea is that your custom cell has a tableview at the bottom of the cell, and what you do is just change the cell height to display said tableview, on tap.

It's not easy, I'm not gonna lie it took us a while to do it, but we managed, and I'm telling you, it's very possible.

You can find a lot of help using the Expandable Cell keywords.

Note that you're gonna find yourself handling a lot :

What to do when the expanding cells is shown off screen?

What to do when you're expanding the first/last cells ?

What to do when expanding another cell ?

What to do when scrolling inside that cell (a scrollview inside a scrollview !)

There are many cases where it'll work, but won't work fine, and there is gonna be a lot of fine tuning. Specially in our case where we have rounded corners, but only when the cell is expanded, and not in cases where it's the last or first cell (next to section header).

They look cool and make you feel proud, but don't say to your PM it'll be done in a week, because it's a pain to build.


问:
E-commerce website with c# .Net
Im working on a website but the problem/error is when i click on the add button it should add a Row in my Categories Table but it is giving me an error.

This is my Code: i have made the connection in gridview.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class Category : System.Web.UI.Page
{
    DAL obj = new DAL();
    static DataTable dt = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{

}

protected void add_btn_Click(object sender, EventArgs e)
 {
    DataRow dr = dt.NewRow();
    dr["Cname"] = cat_txt.Text;
    dt.Rows.Add(dr);

    obj.UpdateDataTable(dt);
 }
}
</code>```

and it's giving me this error An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code. Additional information: Column 'Cname' does not belong to table .

on this code "dr["Cname"] = cat_txt.Text"

I have also checked the name of column which is "Cname" as you can see and about the "Cid" it's primary key and auto generated.

i look into the error but i couldn't resolved it and i search it on google too but i couldn't find the exact solution to my error. Im stuck between this line of code so if you guys will help me it'll be really grateful..:)

答:
this is solves your problem

```<code>dt.Columns.Add(new DataColumn("Cname"));
DataRow dr = dt.NewRow();
dr["Cname"] = cat_txt.Text;
dt.Rows.Add(dr);
</code>```

why is this static? The answer is more important.

```<code>static DataTable dt = new DataTable();
</code>```

Title: E-commerce website with c# .Net

Body:
Im working on a website but the problem/error is when i click on the add button it should add a Row in my Categories Table but it is giving me an error.

This is my Code: i have made the connection in gridview.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class Category : System.Web.UI.Page
{
    DAL obj = new DAL();
    static DataTable dt = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{

}

protected void add_btn_Click(object sender, EventArgs e)
 {
    DataRow dr = dt.NewRow();
    dr["Cname"] = cat_txt.Text;
    dt.Rows.Add(dr);

    obj.UpdateDataTable(dt);
 }
}

and it's giving me this error An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code. Additional information: Column 'Cname' does not belong to table .

on this code "dr["Cname"] = cat_txt.Text"

I have also checked the name of column which is "Cname" as you can see and about the "Cid" it's primary key and auto generated.

i look into the error but i couldn't resolved it and i search it on google too but i couldn't find the exact solution to my error. Im stuck between this line of code so if you guys will help me it'll be really grateful..:)

Body:
this is solves your problem

dt.Columns.Add(new DataColumn("Cname"));
DataRow dr = dt.NewRow();
dr["Cname"] = cat_txt.Text;
dt.Rows.Add(dr);

why is this static? The answer is more important.

static DataTable dt = new DataTable();


问:
Works in Jsfiddle - Not on Site/Browser
I have this JavaScript code that works in Jsfiddle. It makes when the user selects YES on the dropdown, the second one automatically selects NO and vice versa. I have formatted it into my HTML page and for some reason it doesn't work.

I use chrome as a browser. I have added the jsfiddle link and also my HTML code with my JS.

Jsfiddle Link: https://jsfiddle.net/rk57hkak/10/

HTML CODE:

<!DOCTYPE html>

Currently:
    <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
 <option value="">Select Option</option>
 <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
 <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
    </select>

Microphone:
    <select id="microphone" class="microphone select2" name = "microphone">
 <option value=" "  selected="selected">Select Option</option>
 <option value="ON. Thank you.">ON</option>
 <option value="OFF. Thank you.">OFF</option>
     </select>

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

<p>JavaScript Code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const cmicrophone = document.querySelector('.select1');
const microphone = document.querySelector('.select2');

function inputHandler(thisSelect, otherSelect) {
  // console.log(thisSelect.selectedIndex)
  if (thisSelect.selectedIndex == 1) {
 otherSelect.selectedIndex = 1;
  } else if (thisSelect.selectedIndex == 2) {
 otherSelect.selectedIndex = 2;
  } else {
 thisSelect.selectedIndex = 0;
 otherSelect.selectedIndex = 0;
  }
}

cmicrophone.addEventListener('input', event => {
  inputHandler(cmicrophone, microphone);
});

microphone.addEventListener('input', event => {
  inputHandler(microphone, cmicrophone);
});</code>```

答:
This is because the script is getting executed before the element is present in DOM . In such case lines const cmicrophone = document.querySelector('.select1');
 & const microphone = document.querySelector('.select2'); will fail because of the non availability of the element

```<code><body>
  //html code
<script src="committee.js"></script> // Include script here
</body>
</code>```

Title: Works in Jsfiddle - Not on Site/Browser

Body:
I have this JavaScript code that works in Jsfiddle. It makes when the user selects YES on the dropdown, the second one automatically selects NO and vice versa. I have formatted it into my HTML page and for some reason it doesn't work.

I use chrome as a browser. I have added the jsfiddle link and also my HTML code with my JS.

Jsfiddle Link: https://jsfiddle.net/rk57hkak/10/

HTML CODE:

<!DOCTYPE html>

Currently:
    <select id="cmicrophone" class="cmicrophone select1" name="cmicrophone" onchange="">
 <option value="">Select Option</option>
 <option value="'S microphone is currently on. Please remind them to turn it ">OFF</option>
 <option value="'S microphone is currently off. Please remind them to turn it ">ON</option>
    </select>

Microphone:
    <select id="microphone" class="microphone select2" name = "microphone">
 <option value=" "  selected="selected">Select Option</option>
 <option value="ON. Thank you.">ON</option>
 <option value="OFF. Thank you.">OFF</option>
     </select>

JavaScript Code:

const cmicrophone = document.querySelector('.select1');
const microphone = document.querySelector('.select2');

function inputHandler(thisSelect, otherSelect) {
  // console.log(thisSelect.selectedIndex)
  if (thisSelect.selectedIndex == 1) {
 otherSelect.selectedIndex = 1;
  } else if (thisSelect.selectedIndex == 2) {
 otherSelect.selectedIndex = 2;
  } else {
 thisSelect.selectedIndex = 0;
 otherSelect.selectedIndex = 0;
  }
}

cmicrophone.addEventListener('input', event => {
  inputHandler(cmicrophone, microphone);
});

microphone.addEventListener('input', event => {
  inputHandler(microphone, cmicrophone);
});

Body:
This is because the script is getting executed before the element is present in DOM . In such case lines const cmicrophone = document.querySelector('.select1');
 & const microphone = document.querySelector('.select2'); will fail because of the non availability of the element

<body>
  //html code
<script src="committee.js"></script> // Include script here
</body>


问:
Angularjs firebase ng-click loading values after two-three clicks
I have angularjs file

```<code>     <div class="container starter-template">

        <div class="col-md-9" >

        <select ng-model="selectedName" ng-options="x as x.TeamName for x in teams" ng-change="selectedItemChanged()">

        <option value="">Select Team</option>
        </select>

        </div>
        <div class="col-md-3">{{date}} </div>
        <hr>

          <!-- <div ng-repeat="s in user">
            <div ng-repeat="(key, value) in s">
                {{selectedName.FirstName}} : {{value["Date"]}} {{value["TimeStamp"]}} {{value["Status"]}}
            </div>
           </div>-->
         <div class="box box-default" style="width:1100px">
          <div class="box-header with-border">
                  <h3 class="box-title">Employee Details  </h3>
         <div class="row" >

          <br/>
         <div class="col-lg-3 col-xs-6" ng-repeat="name in fullName">
                  <!-- small box -->

                  <div class="small-box bg-aqua" style="height:130px;width:150px;" >
                    <div class="inner">
                      <h3></h3>

                    </div>
                    <div class="icon">
                      <i class="ion ion-person" ></i>
                    </div>

                   <button ng-click="info(name)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">More Info
                 <i class="fa fa-arrow-circle-right"></i>
                    </button><br/><br/>
                    <center><b><p >{{name}}</p></b></center>
                  </div>

          <!-- Modal -->
          <div class="modal fade" id="myModal" role="dialog">
            <div class="modal-dialog">

              <!-- Modal content-->
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal">×</button>
                  <h4 class="modal-title">{{name}}</h4>
                </div>
                <div class="modal-body">
                  <p>Clock In : {{clock_in}}</p>
                  <p>Clock Out : {{clock_out}}</p>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
              </div>

            </div>
          </div>

                </div>
              </div>
            </div>
          </div>

        <div class="box box-default" style="width:1100px">
          <div class="box-header with-border">
                  <h3 class="box-title">Clock In</h3>
                  <div class="row" >

          </div>
        </div>
        </div>
        <div class="box box-default" style="width:1100px">
          <div class="box-header with-border">
                  <h3 class="box-title">Clock Out</h3>
                  <div class="row" >
          </div>
        </div>
        </div>

        <div id="inOut-container">FusionCharts will render here</div>
        <div id="attendance-container">FusionCharts will render here</div>
        </div>
</code>```

and a javascript file:

```<code>           app.controller('organization_drill_down', ['$scope', '$firebaseArray', '$firebaseObject', 'FBURL', function($scope, $firebaseArray, $firebaseObject, FBURL){
  //current date
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1;
  var yyyy = today.getFullYear();
  if(dd<10){dd='0'+dd}
  if(mm<10){mm='0'+mm}
  $scope.date = dd+'/'+mm+'/'+yyyy;

  $scope.all_ins = [];
  $scope.all_outs = [];

  var teams = new Firebase("************");
  var time_stamps = new Firebase("*************")  //collecting team's data
    $scope.teams = $firebaseArray(teams);    //teams for select dropdown
     $scope.team = [];
     $scope.uId = [];
     $scope.in = 0;
     $scope.out = 0;
    $scope.selectedItemChanged = function() {
    console.log($scope.selectedName.TeamName);
  var ref = new Firebase("**************").orderByChild('TeamName')
      .equalTo($scope.selectedName.TeamName) //check if selected team's name matches users
      .on('value', function(snap) {
        $scope.fullName = [];
        $scope.user = snap.val();

         angular.forEach($scope.user, function(user,user_key) {

         $scope.fullName.push(user["FirstName"]+" "+user["LastName"]);

      });

         $scope.$digest();
      });

  };

  //info on clicking more info for a specific user
  $scope.info = function(name) {

   var users = new Firebase("********************");
   var name = name.split(" ");
   console.log(name);

   users.orderByChild('FirstName').equalTo(name[0]) //check if selected team's name matches users
      .on('value', function(snap) {
        $scope.user = snap.val();
        angular.forEach($scope.user, function(user,user_key) {

        if(user["LastName"] == name[1])   //checking if firstname and lastname are equal afterbutton click in user node
         {
        time_stamps.orderByKey()
        .equalTo(user_key) //check if selected name's key is in timestamps
        .on('value', function(snap) {
          $scope.time_stamp = snap.val();

          angular.forEach($scope.time_stamp, function(value, key) {
          angular.forEach(value, function(value1, key) {
          if(value[key]["Date"] == $scope.date ){
           if(value[key]["Status"]== "In"){
           $scope.all_ins.push(value[key]["TimeStamp"]);

           }
          else{
            $scope.all_outs.push(value[key]["TimeStamp"]);

           }

          }

        });
        });
       $scope.clock_in =  $scope.all_ins[0];
      $scope.clock_out =  $scope.all_outs.pop();

        });

         }

      });

      $scope.$digest();
      });

   };
  }]);
</code>```

What I want is: on clicking the button "more info" should open a popup and call the function info(name) and return clock-in and clock out. But what is happening is, on clicking the button ng-click is hitting info(name) but after two-three clicks that is information is not loading directly. I am caught with such unusual error first time, can somebody help?

When clicking first time on button "more info":

after clicking second/third time on the button "more info":

答:
Seems like (from what I could gather with identation and some observation) you are updating your variables outside of the users.orderByChild().equalTo().on part.

Firebase functions (like the one you used) are always promises and, in this case, the promise will end and then on('value', function(snap){ will run.

Since it is an async promise, you might be saving empty values to the variables you wanted to use in the modal. After trying a couple more times it ends up giving the promise enough time to execute so you get your correct values.

Also, bear in mind that using on will add a listener to that firebase node (on the condition of 'value' change) that will run whatever code you put inside it every time the condition is satisfied (not just the first time you call the code).

Body:
I have angularjs file

        <select ng-model="selectedName" ng-options="x as x.TeamName for x in teams" ng-change="selectedItemChanged()">

        <option value="">Select Team</option>
        </select>

{{date}}

Employee Details

                   <button ng-click="info(name)" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">More Info

                    </button>

{{name}}

                  <button type="button" class="close" data-dismiss="modal">×</button>

{{name}}

Clock In : {{clock_in}}

Clock Out : {{clock_out}}

                  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Clock In

Clock Out

FusionCharts will render here

FusionCharts will render here

and a javascript file:

           app.controller('organization_drill_down', ['$scope', '$firebaseArray', '$firebaseObject', 'FBURL', function($scope, $firebaseArray, $firebaseObject, FBURL){
  //current date
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth()+1;
  var yyyy = today.getFullYear();
  if(dd<10){dd='0'+dd}
  if(mm<10){mm='0'+mm}
  $scope.date = dd+'/'+mm+'/'+yyyy;

  $scope.all_ins = [];
  $scope.all_outs = [];

  var teams = new Firebase("************");
  var time_stamps = new Firebase("*************")  //collecting team's data
    $scope.teams = $firebaseArray(teams);    //teams for select dropdown
     $scope.team = [];
     $scope.uId = [];
     $scope.in = 0;
     $scope.out = 0;
    $scope.selectedItemChanged = function() {
    console.log($scope.selectedName.TeamName);
  var ref = new Firebase("**************").orderByChild('TeamName')
      .equalTo($scope.selectedName.TeamName) //check if selected team's name matches users
      .on('value', function(snap) {
        $scope.fullName = [];
        $scope.user = snap.val();

         angular.forEach($scope.user, function(user,user_key) {

         $scope.fullName.push(user["FirstName"]+" "+user["LastName"]);

      });

         $scope.$digest();
      });

  };

  //info on clicking more info for a specific user
  $scope.info = function(name) {

   var users = new Firebase("********************");
   var name = name.split(" ");
   console.log(name);

   users.orderByChild('FirstName').equalTo(name[0]) //check if selected team's name matches users
      .on('value', function(snap) {
        $scope.user = snap.val();
        angular.forEach($scope.user, function(user,user_key) {

        if(user["LastName"] == name[1])   //checking if firstname and lastname are equal afterbutton click in user node
         {
        time_stamps.orderByKey()
        .equalTo(user_key) //check if selected name's key is in timestamps
        .on('value', function(snap) {
          $scope.time_stamp = snap.val();

          angular.forEach($scope.time_stamp, function(value, key) {
          angular.forEach(value, function(value1, key) {
          if(value[key]["Date"] == $scope.date ){
           if(value[key]["Status"]== "In"){
           $scope.all_ins.push(value[key]["TimeStamp"]);

           }
          else{
            $scope.all_outs.push(value[key]["TimeStamp"]);

           }

          }

        });
        });
       $scope.clock_in =  $scope.all_ins[0];
      $scope.clock_out =  $scope.all_outs.pop();

        });

         }

      });

      $scope.$digest();
      });

   };
  }]);

What I want is: on clicking the button "more info" should open a popup and call the function info(name) and return clock-in and clock out. But what is happening is, on clicking the button ng-click is hitting info(name) but after two-three clicks that is information is not loading directly. I am caught with such unusual error first time, can somebody help?

When clicking first time on button "more info":

after clicking second/third time on the button "more info":


问:
On the fabricjs how can you determine if an object already exists at certain coordinates?
I have been working with fabricjs for the last few weeks and I cannot find a solution for an issue I am having.
I have an object and I would like to programmatically determine if the area around it is "empty" (there are no objects ), so if I would add an object there they would not intersect.

I have been playing around with canvas.findTarget and different "virtual" objects but I cannot get anything to work.

This is a solution I found:

```<code>var targetPoint = new fabric.Point(target.left + offset + 1, target.top + 1);
          if (obj.containsPoint(targetPoint)) {
            objectOnRight = obj;
          }
</code>```

Best regards,
Alex

答:
This should get you fairly close (some code I've used, in the past, to display a context menu):

```<code>fabric.util.addListener(document.getElementsByClassName('upper-canvas')[0], 'contextmenu', function (env) {
    var x = env.offsetX;
    var y = env.offsetY;
    var itemIndex = -1;
    $.each(canvas.getObjects(), function (i, e) {
        // e.left and e.top are the middle of the object use some "math" to find the outer edges
        if (e.selectable && e.id != 'canvasNumbers') {
            var d = e.width * e.scaleX / 2;
            var h = e.height * e.scaleY / 2;
            if (x >= (e.left - d) && x <= (e.left + d)) {
                if (y >= (e.top - h) && y <= (e.top + h)) {
                    itemIndex = i;
                }
            }
        }
    });
    if (itemIndex > -1) {
        canvas.setActiveObject(canvas.getObjects()[itemIndex]);
        canvasSelectedItem = canvas.getObjects()[itemIndex];
        $('.contextmenu').css({
            top: env.pageY + 'px',
            left: env.pageX + 'px'
        }).show();
    }
    env.preventDefault();
    return false; //stops the event propigation
});
</code>```

Let me know if you have any further questions.  Happy to help more!

Body:
I have been working with fabricjs for the last few weeks and I cannot find a solution for an issue I am having.
I have an object and I would like to programmatically determine if the area around it is "empty" (there are no objects ), so if I would add an object there they would not intersect.

I have been playing around with canvas.findTarget and different "virtual" objects but I cannot get anything to work.

This is a solution I found:

var targetPoint = new fabric.Point(target.left + offset + 1, target.top + 1);
          if (obj.containsPoint(targetPoint)) {
            objectOnRight = obj;
          }

Best regards,
Alex

Body:
This should get you fairly close (some code I've used, in the past, to display a context menu):

fabric.util.addListener(document.getElementsByClassName('upper-canvas')[0], 'contextmenu', function (env) {
    var x = env.offsetX;
    var y = env.offsetY;
    var itemIndex = -1;
    $.each(canvas.getObjects(), function (i, e) {
        // e.left and e.top are the middle of the object use some "math" to find the outer edges
        if (e.selectable && e.id != 'canvasNumbers') {
            var d = e.width * e.scaleX / 2;
            var h = e.height * e.scaleY / 2;
            if (x >= (e.left - d) && x <= (e.left + d)) {
                if (y >= (e.top - h) && y <= (e.top + h)) {
                    itemIndex = i;
                }
            }
        }
    });
    if (itemIndex > -1) {
        canvas.setActiveObject(canvas.getObjects()[itemIndex]);
        canvasSelectedItem = canvas.getObjects()[itemIndex];
        $('.contextmenu').css({
            top: env.pageY + 'px',
            left: env.pageX + 'px'
        }).show();
    }
    env.preventDefault();
    return false; //stops the event propigation
});

Let me know if you have any further questions.  Happy to help more!


问:
Dragger with collider on Unity 3D
I´m making a simple CAD application on Unity 3D using C# to configure closets. I'm trying to limit the movement of the shelves so you can move them only on the hole, so I have a dragger attached to every piece of the closet I want to move, but obviously they can cross with each other.

I thought I could use the collider system that Unity has to limit this movement but since I never worked with Unity before I´m kinda lost. This is my dragger so far:

```<code>mousePosition = new Vector3(Input.mousePosition.x, cubo_tmp.transform.position.y, distance);
        objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
        objPosition.Set(objPosition.x, cubo_tmp.transform.position.y, cubo_tmp.transform.position.z);
</code>```

I keep y and z components so it can move only in one direction.

答:
Box Colliders are best for cuboid shaped objects.

In the editor, if you click GameObject > 3d Object > Cube, Unity will add a cube with a Box Collider to your scene:

If you want to add a Box Collider to a GameObject that doesn't have one, click Add Component in the Inspector panel and type in "Box Collider" to find it. It looks like this:

Note: If the IsTrigger box is checked, the Collider acts as a Trigger rather than  a Collider.

A GameObject with a Collider will "collide" with any other GameObject that also has a Collider, with a small exception involving 2 Mesh Colliders that are both set to Convex.

EDIT: I think you are able to intersect the objects because you are modifying Transform.position directly in your code. This might override the collision behaviour.

Also Go to Edit > Project Settings > Physics and make sure your layer collision matrix allows collisions for the layers on which your objects are placed.

Title: Dragger with collider on Unity 3D

Body:
I´m making a simple CAD application on Unity 3D using C# to configure closets. I'm trying to limit the movement of the shelves so you can move them only on the hole, so I have a dragger attached to every piece of the closet I want to move, but obviously they can cross with each other.

I thought I could use the collider system that Unity has to limit this movement but since I never worked with Unity before I´m kinda lost. This is my dragger so far:

mousePosition = new Vector3(Input.mousePosition.x, cubo_tmp.transform.position.y, distance);
        objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
        objPosition.Set(objPosition.x, cubo_tmp.transform.position.y, cubo_tmp.transform.position.z);

I keep y and z components so it can move only in one direction.


问:
Frequency counts for unique values in a NumPy array
How do I efficiently obtain the frequency count for each unique value in a NumPy array?</p>
```<code>>>> x = np.array([1,1,1,2,2,2,5,25,1,1])
>>> freq_count(x)
[(1, 5), (2, 3), (5, 1), (25, 1)]
</code>```

答:
I was also interested in this, so I did a little performance comparison (using perfplot, a pet project of mine). Result:

y = np.bincount(a)
ii = np.nonzero(y)[0]
out = np.vstack((ii, y[ii])).T
```
<p>is by far the fastest. (Note the log-scaling.)</p>
<p><img src="https://i.stack.imgur.com/mjDiR.png" alt="enter image description here" /></p>
<hr />
<p>Code to generate the plot:</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
import pandas as pd
import perfplot
from scipy.stats import itemfreq

def bincount(a):
    y = np.bincount(a)
    ii = np.nonzero(y)[0]
    return np.vstack((ii, y[ii])).T

def unique(a):
    unique, counts = np.unique(a, return_counts=True)
    return np.asarray((unique, counts)).T

def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), dtype=int)
    np.add.at(count, inverse, 1)
    return np.vstack((unique, count)).T

def pandas_value_counts(a):
    out = pd.value_counts(pd.Series(a))
    out.sort_index(inplace=True)
    out = np.stack([out.keys().values, out.values]).T
    return out

b = perfplot.bench(
    setup=lambda n: np.random.randint(0, 1000, n),
    kernels=[bincount, unique, itemfreq, unique_count, pandas_value_counts],
    n_range=[2 ** k for k in range(26)],
    xlabel="len(a)",
)
b.save("out.png")
b.show()
</code>```

Body:
How do I efficiently obtain the frequency count for each unique value in a NumPy array?

>>> x = np.array([1,1,1,2,2,2,5,25,1,1])
>>> freq_count(x)
[(1, 5), (2, 3), (5, 1), (25, 1)]

Body:
I was also interested in this, so I did a little performance comparison (using perfplot, a pet project of mine). Result:

y = np.bincount(a)
ii = np.nonzero(y)[0]
out = np.vstack((ii, y[ii])).T

is by far the fastest. (Note the log-scaling.)

Code to generate the plot:

import numpy as np
import pandas as pd
import perfplot
from scipy.stats import itemfreq

def bincount(a):
    y = np.bincount(a)
    ii = np.nonzero(y)[0]
    return np.vstack((ii, y[ii])).T

def unique(a):
    unique, counts = np.unique(a, return_counts=True)
    return np.asarray((unique, counts)).T

def unique_count(a):
    unique, inverse = np.unique(a, return_inverse=True)
    count = np.zeros(len(unique), dtype=int)
    np.add.at(count, inverse, 1)
    return np.vstack((unique, count)).T

def pandas_value_counts(a):
    out = pd.value_counts(pd.Series(a))
    out.sort_index(inplace=True)
    out = np.stack([out.keys().values, out.values]).T
    return out

b = perfplot.bench(
    setup=lambda n: np.random.randint(0, 1000, n),
    kernels=[bincount, unique, itemfreq, unique_count, pandas_value_counts],
    n_range=[2 ** k for k in range(26)],
    xlabel="len(a)",
)
b.save("out.png")
b.show()


问:
C# - Communicate with WinUSB device with LIBUSB
I am trying to communicate with a Nokia Lumia phone(RM-917), over USB using LIBUSING and C#. LIBUSB is able to see the device's information(pid,vid,etc). However, I am not able to successfully write to ANY endpoint, even sending the exact command as the Windows Device Recovery Tool.

According to WinUSB, the write endpoint is EP07, however, this endpoint just times out. I have tried every other endpoint, and all of these fail.

```<code>`
public void initDevice()
{

    if(this.lumiaDevice == null)
    {
        throw new Exception("LumiaPhoneManager does not have a selected device");
    }

    UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0421, 0x0661);
    MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

    IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
    if (!ReferenceEquals(wholeUsbDevice, null))
    {
        // This is a "whole" USB device. Before it can be used,
        // the desired configuration and interface must be selected.

        // Select config #1
        wholeUsbDevice.SetConfiguration(1);

        // Claim interface #0.
        wholeUsbDevice.ClaimInterface(1);
    }

    if (this.writer == null)
    {
        writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep07);
    }

}

    public void readPCode()

{
    currentID++;
    var _x = new jsonPkt();
    ErrorCode ec = ErrorCode.None;
    int bytesWritten;
    _x.id = this.currentID + 1;
    _x.method = "ReadProductCode";

    string value = @"{""jsonrpc"":""<JSONRPC>"",""id"":<ID>,""method"":""<METHOD>"",""params"":null}";
    value = value.Replace("<JSONRPC>", "2.0");
    value = value.Replace("<ID>", currentID.ToString());
    value = value.Replace("<METHOD>", _x.method.ToString());

ec = writer.Write(Encoding.Default.GetBytes(value), 8000, out bytesWritten);
    currentID++;

    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

    byte[] readBuffer = new byte[1024];
    while (ec == ErrorCode.None)
    {
        int bytesRead;

        // If the device hasn't sent data in the last 100 milliseconds,
        // a timeout error (ec = IoTimedOut) will occur.
        ec = reader.Read(readBuffer, 100, out bytesRead);

     //   if (bytesRead == 0) throw new Exception("No more bytes!");

        // Write that output to the console.
        this.rtb.Text += Encoding.Default.GetString(readBuffer, 0, bytesRead).ToString() + "\n";

    }
}
</code>```

答:
Its possible that to activate write, you need to send some class specific control request first. You mentioned that windows device recovery tool is able to write.
You can install USB packet sniffer software in your windows PC and then use the device manager to write some data to the device. Packet sniffer tool will be able to capture all the packets sent to the device.
This way you can see the exact device requests which are required to enable write operation.

Analyzer software - http://www.usblyzer.com/

Please try this way to resolve your problem.

PS- I am assuming you do not have a hardware USB packet analyzer like Lecroy advisor or Beagle. Software packet sniffer should be fine since the host is a PC.

Body:
I am trying to communicate with a Nokia Lumia phone(RM-917), over USB using LIBUSING and C#. LIBUSB is able to see the device's information(pid,vid,etc). However, I am not able to successfully write to ANY endpoint, even sending the exact command as the Windows Device Recovery Tool.

According to WinUSB, the write endpoint is EP07, however, this endpoint just times out. I have tried every other endpoint, and all of these fail.

`
public void initDevice()
{

    if(this.lumiaDevice == null)
    {
        throw new Exception("LumiaPhoneManager does not have a selected device");
    }

    UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0421, 0x0661);
    MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);

    IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
    if (!ReferenceEquals(wholeUsbDevice, null))
    {
        // This is a "whole" USB device. Before it can be used,
        // the desired configuration and interface must be selected.

        // Select config #1
        wholeUsbDevice.SetConfiguration(1);

        // Claim interface #0.
        wholeUsbDevice.ClaimInterface(1);
    }

    if (this.writer == null)
    {
        writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep07);
    }

}

    public void readPCode()

{
    currentID++;
    var _x = new jsonPkt();
    ErrorCode ec = ErrorCode.None;
    int bytesWritten;
    _x.id = this.currentID + 1;
    _x.method = "ReadProductCode";

    string value = @"{""jsonrpc"":""<JSONRPC>"",""id"":<ID>,""method"":""<METHOD>"",""params"":null}";
    value = value.Replace("<JSONRPC>", "2.0");
    value = value.Replace("<ID>", currentID.ToString());
    value = value.Replace("<METHOD>", _x.method.ToString());

ec = writer.Write(Encoding.Default.GetBytes(value), 8000, out bytesWritten);
    currentID++;

    if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);

    byte[] readBuffer = new byte[1024];
    while (ec == ErrorCode.None)
    {
        int bytesRead;

        // If the device hasn't sent data in the last 100 milliseconds,
        // a timeout error (ec = IoTimedOut) will occur.
        ec = reader.Read(readBuffer, 100, out bytesRead);

     //   if (bytesRead == 0) throw new Exception("No more bytes!");

        // Write that output to the console.
        this.rtb.Text += Encoding.Default.GetString(readBuffer, 0, bytesRead).ToString() + "\n";

    }
}


问:
Too much space between bars in matplotlib bar chart
I am trying to create a bar chart with matplotlib.

The x-axis data is a list with years: [1950,1960,1970,1980,1990,1995-2015]

The y-axis data is a list with equal amount of numbers as in years.

This is my code:

```<code>import csv
import matplotlib.pyplot as plt

path = "bevoelkerung_entwicklung.csv"

with open(path, 'r') as datei:
    reader = csv.reader(datei, delimiter=';')
    jahr = next(reader)
    population = next(reader)

population_list = []

for p in population:
    population_list.append(str(p).replace("'",""))

population_list = list(map(int, population_list))
jahr = list(map(int, jahr))

datei.close()

plt.bar(jahr,population_list, color='c')

plt.xlabel('Year')
plt.ylabel('Population in 1000')
plt.title('Population growth')
plt.legend()
plt.show()
</code>```

And the outcome is the following:
Too much space between bars

As you can see the gaps between 1950-1960 is huge. How can I make it, so that there is no gap inbetween the bars 1950-1995. I get that it has intervals of 10 years, but it doesn't look good.

Any help would be appreaciated.

答:
You need to plot the population data as a function of increasing integers. This makes the bars have equal spacings. You can then adapt the labels to be the years that each graph represents.

```<code>import matplotlib.pyplot as plt
import numpy as np

jahre = np.append(np.arange(1950,2000,10), np.arange(1995,2017))
bevoelkerung = np.cumsum(np.ones_like(jahre))
x = np.arange(len(jahre))

plt.bar(x, bevoelkerung)
plt.xticks(x, jahre, rotation=90)
plt.show()
</code>```

Body:
I am trying to create a bar chart with matplotlib.

The x-axis data is a list with years: [1950,1960,1970,1980,1990,1995-2015]

The y-axis data is a list with equal amount of numbers as in years.

This is my code:

import csv
import matplotlib.pyplot as plt

path = "bevoelkerung_entwicklung.csv"

with open(path, 'r') as datei:
    reader = csv.reader(datei, delimiter=';')
    jahr = next(reader)
    population = next(reader)

population_list = []

for p in population:
    population_list.append(str(p).replace("'",""))

population_list = list(map(int, population_list))
jahr = list(map(int, jahr))

datei.close()

plt.bar(jahr,population_list, color='c')

plt.xlabel('Year')
plt.ylabel('Population in 1000')
plt.title('Population growth')
plt.legend()
plt.show()

And the outcome is the following:
Too much space between bars

As you can see the gaps between 1950-1960 is huge. How can I make it, so that there is no gap inbetween the bars 1950-1995. I get that it has intervals of 10 years, but it doesn't look good.

Any help would be appreaciated.

Body:
You need to plot the population data as a function of increasing integers. This makes the bars have equal spacings. You can then adapt the labels to be the years that each graph represents.

import matplotlib.pyplot as plt
import numpy as np

jahre = np.append(np.arange(1950,2000,10), np.arange(1995,2017))
bevoelkerung = np.cumsum(np.ones_like(jahre))
x = np.arange(len(jahre))

plt.bar(x, bevoelkerung)
plt.xticks(x, jahre, rotation=90)
plt.show()


问:
What are some good Java web development tools (across the board)
For web development what are some standard/good java tools.  That apply to all aspects of development.

For example, The IDE (Eclipse, RAD, Intellij) is important, but what else is there.

Ant is a good one.
Cygwin, Linux OS possibly.

答:
My infrastructure looks like this for the webapp I'm involved in:

IntelliJ Idea, I just use it for some time now, but I guess any halfway modern IDE will do it, just learn one and learn it well, so read NetBeans, JDeveloper, Eclipse but I never used one of them for longer time

Teamcity, Continous Integration (which I love for the delayed checkin and remote runs, never ever check in a broken branch anymore!)

Maven and Artifactory, Dependency Management for our software stack

Tomcat (or Glassfish)

SVN as SCM

On the lib side I use

Spring

Hibernate

JSF + Trinidad

Spring Webflow

JUnit

Fitness

EasyMock

I guess for development you should also consider something like HSQL or something, don't make yourself depend on big databases and you can't run/test your stuff on the road ;-).

The hard part in the beginning here is to set everything up properly in maven. This is not a task which just takes 5 minutes but I think it's worth it. I have not played around with Ivy yet maybe this might be a good solution too. I do not want to wade through ant scripts anymore, those are getting easily out of hand if your project grows.

Everything works in Windows/Linux/Mac as you would expect from Java and a modern IDE.

OwnerDisplayName: Berlin Brown

OwnerDisplayName: Oliver


问:
I want only all cities of "INDIA" to show through ngAutocomplete..??? which changes I have to make in ngAutocomplete..?
I just want to give all cities of India in options through ngAutocomplete.js...well below code of ngAutocomplete.js           </p>

```<code>    var opts;
    var initOpts = function() {
      opts = {}
      if (scope.options) {
        if (scope.options.types) {
          opts.types = []
          opts.types.push(scope.options.types)
        }
        if (scope.options.bounds) {
          opts.bounds = scope.options.bounds
        }
        if (scope.options.country) {
          opts.componentRestrictions = {
            country: 'IN'
          }
        }
      }
    }
</code>```

答:
Fortunately for you, there is Autocomplete: Restrict the search to a specific country from the Google JS docs. This functionality uses the componentRestrictions option to restrict the autocomplete search to a particular country. Here's a snippet for you:

```<code> var input = document.getElementById('searchTextField');
var options = {
  types: ['(cities)'],
  componentRestrictions: {country: 'in'}
};

autocomplete = new google.maps.places.Autocomplete(input, options);
</code>```

Here's a full working demo from the Google Maps sample.

Body:
I just want to give all cities of India in options through ngAutocomplete.js...well below code of ngAutocomplete.js

    var opts;
    var initOpts = function() {
      opts = {}
      if (scope.options) {
        if (scope.options.types) {
          opts.types = []
          opts.types.push(scope.options.types)
        }
        if (scope.options.bounds) {
          opts.bounds = scope.options.bounds
        }
        if (scope.options.country) {
          opts.componentRestrictions = {
            country: 'IN'
          }
        }
      }
    }

Body:
Fortunately for you, there is Autocomplete: Restrict the search to a specific country from the Google JS docs. This functionality uses the componentRestrictions option to restrict the autocomplete search to a particular country. Here's a snippet for you:

 var input = document.getElementById('searchTextField');
var options = {
  types: ['(cities)'],
  componentRestrictions: {country: 'in'}
};

autocomplete = new google.maps.places.Autocomplete(input, options);

Here's a full working demo from the Google Maps sample.


问:
How can I add style effect for elements inside of echo using classes?
I have a problem with adding style effect for div elements inside of  echo, here's my code:

```<code><?php
$db= new PDO('mysql:host=localhost;dbname=myDataBase;charset=utf8','user','password');

$response=$db->query('select * from users order by ID desc limit 10');
while($line=$reponse->fetch())
{
    echo
        '<div class="elements" ><h1>'.$line['pseudo'].'</h1></div>
        <div class="elements">'.$line['message'].'</div>
        </div>';

} ?>
</code>```

and the stylesheet:

```<code>.elements{
display: inline-block;
padding: 10px;
    }
</code>```

when I execute it, it doesn't work.

答:
This is pretty easy. Just inline your php as needed into the html code to display on the page. For Example:

```<code><?php

Inlcude your php and queries here in this block

?>

<!DOCTYPE html>
    <html>

    <head>
        <title>Test Page</title>
        <link rel="stylesheet" href="css/styles.css" />
    </head>

    <body>
        <?php echo '<div class="elements">the rest of your php code goes here</div> '; ?>
    </body>

</html>
</code>```

This is just bare bones basic code to show you what I am talking about. So your custom css would live in the styles.css file. Once you echo out what it is you want in php, then it will inherit those styles. You can inline php as much as you want throughout the file. Just name it file.php or whatever you want.

This will allow you to do what it is you are asking. Of course you could reverse this and echo out the html from start to finish if you really wanted too, but it would be easier to just add the relevant connection info for php and query at the top of the page before any html and then echo out the specific information you wish inside the html below the main php code.

Also I noticed you have one too many closing div tags at the bottom of your echo statement. As others have already commented, you have some other errors as well.

Body:
I have a problem with adding style effect for div elements inside of  echo, here's my code:

<?php
$db= new PDO('mysql:host=localhost;dbname=myDataBase;charset=utf8','user','password');

$response=$db->query('select * from users order by ID desc limit 10');
while($line=$reponse->fetch())
{
    echo
        '

'.$line['pseudo'].'

'.$line['message'].'

';

} ?>

and the stylesheet:

.elements{
display: inline-block;
padding: 10px;
    }

when I execute it, it doesn't work.

Body:
This is pretty easy. Just inline your php as needed into the html code to display on the page. For Example:

<?php

Inlcude your php and queries here in this block

?>

<!DOCTYPE html>
    <html>

    <head>
        <title>Test Page</title>
        <link rel="stylesheet" href="css/styles.css" />
    </head>

    <body>
        <?php echo '<div class="elements">the rest of your php code goes here</div> '; ?>
    </body>

</html>

This is just bare bones basic code to show you what I am talking about. So your custom css would live in the styles.css file. Once you echo out what it is you want in php, then it will inherit those styles. You can inline php as much as you want throughout the file. Just name it file.php or whatever you want.

This will allow you to do what it is you are asking. Of course you could reverse this and echo out the html from start to finish if you really wanted too, but it would be easier to just add the relevant connection info for php and query at the top of the page before any html and then echo out the specific information you wish inside the html below the main php code.

Also I noticed you have one too many closing div tags at the bottom of your echo statement. As others have already commented, you have some other errors as well.


答:
you can use tableGrob from package gridExtra

check this post :
Merging Table Header Cells Using tableGrob

Title: Creating a row for table name

Body:
I have a table as such:

    +-----------+----------------+----------+
    |           |     Type 1     | Type 2   |
    +-----------+----------------+----------+
    |    Mean   |     31,2       |    16,0  |
    |   Median  |     51,3       |    16,0  |
    |    Max    |     40,4       |    6,0   |
    |    Min    |     100,0      |    16,0  |
    |    Q1     |     34,6       |    16,0  |
    |    Q3     |     16,0       |    16,0  |
    +---+------------+-----------+----------+

How can I add a title to it, so it becomes:

    +-----------+----------------+----------+
    |        INSERT TABLE TITLE HERE        |
    +-----------+----------------+----------+
    |           |     Type 1     | Type 2   |
    +-----------+----------------+----------+
    |    Mean   |     31,2       |    16,0  |
    |   Median  |     51,3       |    16,0  |
    |    Max    |     40,4       |    6,0   |
    |    Min    |     100,0      |    16,0  |
    |    Q1     |     34,6       |    16,0  |
    |    Q3     |     16,0       |    16,0  |
    +---+------------+-----------+----------+


问:
How to read text from a file, identify adjacent duplicated words, and report their location in the text file?
I am trying to read a quote from a text file and find any duplicated words that appear next to each other. The following is the quote:

```<code>"He that would make his own liberty liberty secure,

must guard even his enemy from oppression;

for for if he violates this duty, he

he establishes a precedent that will reach to himself."
-- Thomas Paine
</code>```

The output should be the following:

Found word: "Liberty" on line 1

Found word: "for" on line 3

Found word: "he" on line 4

I have written the code to read the text from the file but I am having trouble with the code to identify the duplicates. I have tried enumerating each word in the file and checking if the word at one index is equal to the the word at the following index. However, I am getting an index error because the loop continues outside of the index range. Here's what I've come up with so far:

```<code>import string
file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line_str.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)

for idx, word in enumerate(word_list):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)
</code>```

Any help with the current method I'm trying would be appreciated, or suggestions for another method.

答:
This should do the trick OP. In the for loop over the word list it only goes up to the second to last element now. This won't keep track of the line numbers though, I would use Phillip Martin's solution for that.</p>

```<code>import string

file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)
#Here is the change I made         >     <
for idx, word in enumerate(word_list[:-1]):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)
print duplicates
</code>```

Body:
I am trying to read a quote from a text file and find any duplicated words that appear next to each other. The following is the quote:

"He that would make his own liberty liberty secure,

must guard even his enemy from oppression;

for for if he violates this duty, he

he establishes a precedent that will reach to himself."
-- Thomas Paine

The output should be the following:

Found word: "Liberty" on line 1

Found word: "for" on line 3

Found word: "he" on line 4

I have written the code to read the text from the file but I am having trouble with the code to identify the duplicates. I have tried enumerating each word in the file and checking if the word at one index is equal to the the word at the following index. However, I am getting an index error because the loop continues outside of the index range. Here's what I've come up with so far:

import string
file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line_str.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)

for idx, word in enumerate(word_list):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)

Any help with the current method I'm trying would be appreciated, or suggestions for another method.

Body:
This should do the trick OP. In the for loop over the word list it only goes up to the second to last element now. This won't keep track of the line numbers though, I would use Phillip Martin's solution for that.

import string

file_str = input("Enter file name: ")
input_file = open(file_str, 'r')

word_list = []
duplicates = []

for line in input_file:
    line_list = line.split()
    for word in line_list:
        if word != "--":
            word_list.append(word)
#Here is the change I made         >     <
for idx, word in enumerate(word_list[:-1]):
    print(idx, word)
    if word_list[idx] == word_list[idx + 1]:
        duplicates.append(word)
print duplicates


问:
Use CSS to affect an outer element
This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

```<code>a img {
/ * style * /
}
</code>```

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?

答: CSS selectors can not ascend. It is a limitation of the language.</p>

Title: Use CSS to affect an outer element

Body:
This is hard to sum up in a title, so forgive me.

Basically, here is what I have:

a img {
/ * style * /
}

However, I want to affect the a tag in this instance. Is there any way to do so in CSS without resorting to JavaScript wizardry?


问:
Could not bind TCP port 443 LetsEncrypt
Could not bind TCP port 443 because it is already in use by another process on this system (such as a web server). Please stop the program in question and then try again

My operating system is (include version): mac OS Sierra version 10.12

My web server is (include version): apache2-mod-php7.0_7.0.15

My hosting provider, if applicable, is: Linode (Ubuntu 16.04.1 LTS)

I can login to a root shell on my machine (yes or no, or I don't know): not sure

I'm using a control panel to manage my site (no, or provide the name and version of the control panel): I use terminal and filezilla

Question is how do stop the program??? If any more details are required, let me know!

答:
Instead of killing apache, you could use the letsencrypt certbot apache plugin. This way, Let's Encrypt is working with your setup instead of against it. Once you have certbot setup, it will automatically handle renewing the certificates for you as well.

To install certbot with the apache plugin, you will need to run the following commands on your server. In this case, you can use the Linode Shell to access your server.

Installation procedure (from the official docs):

```<code>$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache
</code>```

Once that's installed, you can get the ssl certs automatically, and have them installed with one command:

```<code>certbot --apache
</code>```

Title: Could not bind TCP port 443 LetsEncrypt

Body:
Instead of killing apache, you could use the letsencrypt certbot apache plugin. This way, Let's Encrypt is working with your setup instead of against it. Once you have certbot setup, it will automatically handle renewing the certificates for you as well.

To install certbot with the apache plugin, you will need to run the following commands on your server. In this case, you can use the Linode Shell to access your server.

Installation procedure (from the official docs):

$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt-get update
$ sudo apt-get install python-certbot-apache

Once that's installed, you can get the ssl certs automatically, and have them installed with one command:

certbot --apache


问:
How to abort a MR job inside a mapper (or a reducer)
I tried to throw IOExceptions in the map method but the MR job is not stopped. The job will be stopped after tons of IOException thrown.
Is there any way to stop the whole job by just throwing an exception or some simple calls?
Thanks.</p>

答:
You can skip the getJobID method by simply overriding setup and run functions of the Mapper.</p>

```<code>    public static class LineMapper extends Mapper<Object, Text, Text, Text>{
        boolean myCondition;

        @Override
        public void setup(Context context){
            myCondition = true;
        }

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
        //something happens in your code and you change the condition to false to stop the mapper
            myCondition = false;
        }

        @Override
        public void run(Context context) throws IOException, InterruptedException {

            setup(context);
            while (context.nextKeyValue()) {
                if(linecounter < 50) {
                    map(context.getCurrentKey(), context.getCurrentValue(), context);
                } else {
                    cleanup(context);
                    break;
                }
            }
        }
    }
</code>```

Body:
You can skip the getJobID method by simply overriding setup and run functions of the Mapper.

    public static class LineMapper extends Mapper<Object, Text, Text, Text>{
        boolean myCondition;

        @Override
        public void setup(Context context){
            myCondition = true;
        }

        public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
        //something happens in your code and you change the condition to false to stop the mapper
            myCondition = false;
        }

        @Override
        public void run(Context context) throws IOException, InterruptedException {

            setup(context);
            while (context.nextKeyValue()) {
                if(linecounter < 50) {
                    map(context.getCurrentKey(), context.getCurrentValue(), context);
                } else {
                    cleanup(context);
                    break;
                }
            }
        }
    }


问:
SiteFinity - 9.1.6131 - IIS workder process using 100% of CPU

Server - Windows Server 2012 R2

CPU - AMD Opteron(tm) processor 6174 2.20GHz (12 processors)

RAM - 8.00 GB

System Type - 64-bit OS

IIS - version 8.5.9699.16384

SiteFinity - 9.1.6131

Virtual Server

No Load balancing

Database - not affected/separate server

Periodically our servers IIS worker process that runs the Application pool for our production release of our website, built with SiteFinity, spikes and remains pegged at 100%. Something within the web application is utilizing all the resources available to the machine to just run the IIS worker process.

Our site, with minimal load will all of a sudden start using all the processor that is available and we cannot track this issue down. It doesn't seem to happen at any one point in the day or affected by high load. When this happens, we have to either allocate lots of resources to the machine, which requires a re-boot since we are not cloud hosted OR we have to recycle the application pool and release the resources and flush the requests and hope that we killed the process.

We have been through the optimization document for start up, All our pages are on a "standard" cache, 3 minute cache with a slide. All our images are on a long cache policy with a slide, all our images are also on disk and not being served up through the CMS.

Doing some digging, found some very old articles detailing what sounds like exactly our problem. I understand that these are very old and are in very old SF instances, however the issue sounds identical, High CPU utilization with minimal load:

http://www.sitefinity.com/developer-network/forums/bugs-issues-/sitefinity-down---w3wp-exe-using-95--100-of-cpu

http://www.sitefinity.com/developer-network/forums/bugs-issues/high-cpu-utilization

Anyone experience anything like this with SiteFinity recently and have any tips/tricks/coupons on what you did to resolve or located the rogue process chewing up server resources?

Thanks and look forward to your response.

答:
Here are a few article I found that might help...

http://knowledgebase.progress.com/articles/Article/How-to-isolate-a-performance-problem-in-Sitefinity?q=100%25+cpu&l=en_US&c=Product_Group%3ASitefinity&fs=Search&pn=1

http://knowledgebase.progress.com/articles/Article/How-to-resolve-high-CPU-after-sharing-page-link-on-Facebook?q=100%25+cpu&l=en_US&c=Product_Group%3ASitefinity&fs=Search&pn=1

Also, I would open IIS and click on the server node and then double click on the "Worker Process".  You will need to be on the web server to see this option.

This page may show you any worker processes that have long running pages that could be causing this spike in CPU.  You can keep clicking the REFRESH button in the upper right corner to see updates.

Let me know if this helps narrow down your issue.


问:
How do I change the value of a header for each request inside a datasource loop?
I have a header called RequestID that has a value of a UUID I generated in the groovy script below:

```<code>import static java.util.UUID.randomUUID
import com.eviware.soapui.support.types.StringToStringMap

def uuid = randomUUID() as String
def headers = new StringToStringMap()

headers.put("RequestID", uuid)
testRunner.testCase.getTestStepByName("Get Username").testRequest.setRequestHeaders(headers)
</code>```

I also have a REST request named "Get Username" that is called multiple times via a datasource loop. My groovy script seems to only be generating one UUID for the entirety of the loop and not a new UUID for each hit. Am I missing something in my script or is the order of the steps wrong? I'm also using a grid in my datasource step called SSN to feed data into the request.

Here is the order of my steps in SOAPUI:

SSN

Groovy Script

Get Username,

DataSource Loop (Datasource step: SSN, Target step: Get Username)

Essentially every time a new request is sent, there should be a new requestid. If that makes sense.

答:
When the test reaches the DataSource Loop it gets new data from the DataSource and executes the target test step (in your case - Get Username). So it executes the Groovy script only once.

Change the Target test step in the DataSource Loop to the Groovy Script test step.

Body:
I have a header called RequestID that has a value of a UUID I generated in the groovy script below:

import static java.util.UUID.randomUUID
import com.eviware.soapui.support.types.StringToStringMap

def uuid = randomUUID() as String
def headers = new StringToStringMap()

headers.put("RequestID", uuid)
testRunner.testCase.getTestStepByName("Get Username").testRequest.setRequestHeaders(headers)

I also have a REST request named "Get Username" that is called multiple times via a datasource loop. My groovy script seems to only be generating one UUID for the entirety of the loop and not a new UUID for each hit. Am I missing something in my script or is the order of the steps wrong? I'm also using a grid in my datasource step called SSN to feed data into the request.

Here is the order of my steps in SOAPUI:

SSN

Groovy Script

Get Username,

DataSource Loop (Datasource step: SSN, Target step: Get Username)

Essentially every time a new request is sent, there should be a new requestid. If that makes sense.


问:
Remove Application Insight from application on Visual Studio 2013
On Visual Studio I added application insight to a project which creates a ApplicationInsights.config and not sure what other files were added to the project.

Thing is, doing right click and press Add Application Insight was pretty straight forward. Now I'm looking with no success a way to remove the application insight for that project.

How can I achieve that ?

On production server, using DebugView, I see the telemetry logs, even after shutting down the Application Monitor Services on the server.

Any help is appreciated, I want to completely get rid of application insight on that application.

答:
I would prefer to do this: </p>

```<code>UnInstall-Package Microsoft.ApplicationInsights.Web -RemoveDependencies
</code>```

Body:
I would prefer to do this:

UnInstall-Package Microsoft.ApplicationInsights.Web -RemoveDependencies


问:
What are the chronological steps in building a cross browser compatible site?
I am working on my first project that requires me to worry about cross browser compatibility.  Since this is my first time doing so, I dont know how to go about completing the project.  I am specifically worried about IE.  Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?</p>

答:
Design your site to work in standards complaint browsers first. I always start with Firefox, even when developing on my company Intranet (where everyone uses IE). Doing so will let you focus on getting your markup and CSS correct. This is what is most important.

The important thing to note is that you'll want to "future proof" your site, and concentrating on a standards compliant browser will help you do that.

Then, once you're confident your site is looking correct (validators are your friend!), try it out in the versions of IE you want to support. In order to get your layout to look OK in IE, I strongly suggest using different stylesheets for each version of IE, using conditional comments.

Also, you should note that many others have been in the same scenario as yourself, and there is quite a bit of help available. One popular method of forcing IE to behave is the ie-7.js project.

Lastly, be mindful of the top IE bugs, such as:

IE6 Box Model Bug

IE6 transparent PNG images (I have used this fix in the past)


问:
Load issues with Java App - how to replicate?
I have a java application using oracle DB, running on apache tomcat. During normal day, the java app runs fine. However, the traffic was double on a day, and the app starts to encounter increase in response time and timeouts.

After that, we tried run load test using jmeter with the same amount of load experienced but never encountered any responsive/timeout issues from the testing. BTW, we checked our network monitoring tools, no issues with the infra.

Can I check what should I be looking for if I want to replicate the same issue during testing? Replicating this would help to ensure that the changes we are going to do would works.

Thanks!

答:
The underlying question is: how to make the load test realistic enough to replicate slowness in accessing database observed in production. The thought process in our comments exchange was to review and rule-in or rule-out factors that are often not properly emulated in load tests and give over-optimistic performance result. I reviewed 4 factors:

Does the load test script correctly correlate dynamic values? Yes it does, because the records created by the load test match with the scenario. If this were not be the case, then failed transactions in the load test would be responsible for too fast response. The recommendation would be to correlate your script manually.

Does the load test script correctly emulate multiple authenticated users? Application does not require login. If this were not the case, then running load test with a single user will fail to test system overheads on maintaining multiple user sessions. The recommendation would be to parameterize recorded credentials using dataset with multiple credentials.

Does the load test script correctly emulate anonymous users authenticated through cookies? Application does not use cookie authentication. If this were not the case, then the recommendation would be to clear browser cache before recording to make sure that the stale cookie is not recorded and then make sure that cookie correlation in the script is configured properly.

Does the load test script correctly emulate data in the recorded scenario? Assuming the test scenario recorded some user entry that is used as a criteria for a database query. If you replay multiple iterations emulating the same entry, the database may not be hit for such queries due to application or database caching. If this is the case, then the recommendation is to parameterize user entries using test datasets.

If the last factor is also not the case, then there are more factors to go through. For more about correlation and parameterization load tests check this blog http://www.stresstimulus.com/blog/post/eradicating-load-testing-errors-1


问:
Node package to automatically generate api from database?
I have a MySQLdatabase that was built for a PHP project. I want to migrate from PHP to Node and use an Express (or similar) API to interact with the database. Is there any node package that can generate the endpoints automatically? </p>

答:
See LoopBack:

https://loopback.io/

On the website:

Set up models and create REST APIs in minutes

Easy-to-use CLI wizard Create models based on your schema if you have
  one Create dynamic models if you don't Built-in API Explorer Model
  relation support

Define hasMany, belongsTo, hasAndBelongsToMany relationships
  Automatically generates corresponding relational REST endpoints

Of course it will not make all of the work for you but it may help.


问:
Change message body before sending in outlook 365
It possible to change message body (e.g. add some text at the end) on send button clicking.</p>

答:
Office.js API currently doesn't support events. There are a lot of requests for monitoring "onSend" event. You may up vote it over here: officespdev.uservoice.com.

Meanwhile you may need to consider re-design your application to change message body at the time of add-in invocation by user. To manipulate with the body of the message Office.js API provides plenty of functions: Office.context.mailbox.item.body

EDIT:

On send feature for Outlook add-ins was implemented with lots of limitation, but at least it's there. Outlook add-in on send code sample is available as well.