问:
How could i make a div with rounded borders and make the fa icons inside it centered?
So i want a div with rounded borders (to make a circle) and inside that i want my fa icons which would be aligned to the middle.

So basically i want a Circle containing an fa icon in the middle just to make it simple.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
    </div>
  </div>
</div></code>```

答:
It's very easy. just use flex and it works as charm

```<code>.fa {
    width: 100px;
   height: 100px;
   border: 2px solid #fff;
   border-radius: 100%;
   display: flex;
   justify-content: center;
   align-items: center;
}
</code>```

I have also updated your snippet.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}

/* add these lines */
.fa {
    width: 100px;
    height: 100px;
    border: 2px solid #fff;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
    </div>
  </div>
</div></code>```

Body:
So i want a div with rounded borders (to make a circle) and inside that i want my fa icons which would be aligned to the middle.

So basically i want a Circle containing an fa icon in the middle just to make it simple.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.

          Click here to vote!

Body:
It's very easy. just use flex and it works as charm

.fa {
    width: 100px;
   height: 100px;
   border: 2px solid #fff;
   border-radius: 100%;
   display: flex;
   justify-content: center;
   align-items: center;
}

I have also updated your snippet.

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  color: #ff8800;
  margin-bottom: 20px;
}

.vote-container a {
  cursor: pointer;
}

/* add these lines */
.fa {
    width: 100px;
    height: 100px;
    border: 2px solid #fff;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
    </div>
  </div>
</div>


来源: stackexchange

问:
PyQt: setSpacing in QGridLayout
Can you tell me how to delete spaces between buttons im my Widget? I want to do it by seting command , setSpacing(0), but I don't know where I should set it.

My code:

```<code>import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication, QGridLayout,
QPushButton,QWidget

class Saper(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        grid = QGridLayout()
        self.setLayout(grid)

        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+',
                'f','i','f','i']

        positions = [(i,j) for i in range(6) for j in range(4)]

        for position, name in zip(positions, names):

        if name == '':
            continue
        button = QPushButton(name)
        button.setMinimumSize(20,20)
        button.setMaximumSize(20,20)
        grid.addWidget(button, *position)

    self.setGeometry(300,300,300,300)
    self.setWindowTitle('Title')
    self.move(300, 150)
    self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Saper()
    sys.exit(app.exec_())
</code>```

答:
Ok, I got it. If someone will have this problem here is a solution. I changed my conception, class Saper inherents from QWidget and now table names contains smaller tabels with names. First for counts elements in big table and second for counts elements in smaller tabels. I'm adding each element to one horizontal box and then I'm adding this horizontal box to vertical box, I repeat this action for each row. Important thing is to make new horizontal box after adding old one to vertical box:</p>

```<code>import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication)

class Saper(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        vbox = QVBoxLayout()
        vbox.setSpacing(0)
        vbox.addStretch(1)

        names = [['Cls', 'Bck', 'Ok', 'Close'],
                 ['7', '8', '9', '/'],
                ['4', '5', '6', '*'],
                 ['1', '2', '3', '-'],
                ['0', '.', '=', '+'],
                ['f','i','f','i']]

        for pos in names:
            hbox = QHBoxLayout()
            hbox.addStretch(1)
            hbox.setSpacing(0)
            for name in pos:

                button = QPushButton(name)
                button.setMinimumSize(75,60)
                button.setMaximumSize(75,60)
                hbox.addWidget(button)
            vbox.addLayout(hbox)

        self.setLayout(vbox)
        self.setGeometry(300,300,300,300)
        self.setWindowTitle('Title')
        self.move(300, 150)
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Saper()
    sys.exit(app.exec_())
</code>```

ContentLicense: CC BY-SA 3.0

Title: PyQt: setSpacing in QGridLayout

Body:
Can you tell me how to delete spaces between buttons im my Widget? I want to do it by seting command , setSpacing(0), but I don't know where I should set it.

My code:

import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import QMainWindow, QApplication, QGridLayout,
QPushButton,QWidget

class Saper(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        grid = QGridLayout()
        self.setLayout(grid)

        names = ['Cls', 'Bck', '', 'Close',
                 '7', '8', '9', '/',
                '4', '5', '6', '*',
                 '1', '2', '3', '-',
                '0', '.', '=', '+',
                'f','i','f','i']

        positions = [(i,j) for i in range(6) for j in range(4)]

        for position, name in zip(positions, names):

        if name == '':
            continue
        button = QPushButton(name)
        button.setMinimumSize(20,20)
        button.setMaximumSize(20,20)
        grid.addWidget(button, *position)

    self.setGeometry(300,300,300,300)
    self.setWindowTitle('Title')
    self.move(300, 150)
    self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Saper()
    sys.exit(app.exec_())

Body:
Ok, I got it. If someone will have this problem here is a solution. I changed my conception, class Saper inherents from QWidget and now table names contains smaller tabels with names. First for counts elements in big table and second for counts elements in smaller tabels. I'm adding each element to one horizontal box and then I'm adding this horizontal box to vertical box, I repeat this action for each row. Important thing is to make new horizontal box after adding old one to vertical box:

import sys
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import (QWidget, QPushButton,
QHBoxLayout, QVBoxLayout, QApplication)

class Saper(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        vbox = QVBoxLayout()
        vbox.setSpacing(0)
        vbox.addStretch(1)

        names = [['Cls', 'Bck', 'Ok', 'Close'],
                 ['7', '8', '9', '/'],
                ['4', '5', '6', '*'],
                 ['1', '2', '3', '-'],
                ['0', '.', '=', '+'],
                ['f','i','f','i']]

        for pos in names:
            hbox = QHBoxLayout()
            hbox.addStretch(1)
            hbox.setSpacing(0)
            for name in pos:

                button = QPushButton(name)
                button.setMinimumSize(75,60)
                button.setMaximumSize(75,60)
                hbox.addWidget(button)
            vbox.addLayout(hbox)

        self.setLayout(vbox)
        self.setGeometry(300,300,300,300)
        self.setWindowTitle('Title')
        self.move(300, 150)
        self.show()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Saper()
    sys.exit(app.exec_())


问:
Why the memory usage of Series is about 1.5x of DataFrame with the same data?
Here is the code:

```<code>In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: from itertools import product
In [4]: index = list(map(''.join, product(*['ABCDEFGH']*4)))
In [5]: columns = list(map(''.join, product(*['xyzuvw']*3)))

In [6]: df = pd.DataFrame(np.random.randn(len(index), len(columns)), index=index, columns=columns)
In [7]: ser = df.stack()
In [8]: df.memory_usage().sum()
Out[8]: 7274496

In [10]: ser.memory_usage()
Out[10]: 10651360

In [11]: ser.memory_usage() / df.memory_usage().sum()
Out[11]: 1.4642059051238738

In [12]: df.to_hdf('f:/f1.h5', 'df')
In [13]: ser.to_hdf('f:/f2.h5', 'ser')
In [14]: import os

In [15]: os.stat('f:/f2.h5').st_size / os.stat('f:/f1.h5').st_size
Out[15]: 1.498167701758398
</code>```

And the version info of pandas:

```<code>pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.1.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.20.1
pytest: 3.0.7
pip: 9.0.1
setuptools: 27.2.0
Cython: 0.25.2
numpy: 1.12.1
</code>```

答: Your series is indexed by a MultiIndex, which takes up a lot of space. ser.reset_index(drop = True).memory_usage(deep = True) returns 7077968.

Body:
Here is the code:

In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: from itertools import product
In [4]: index = list(map(''.join, product(*['ABCDEFGH']*4)))
In [5]: columns = list(map(''.join, product(*['xyzuvw']*3)))

In [6]: df = pd.DataFrame(np.random.randn(len(index), len(columns)), index=index, columns=columns)
In [7]: ser = df.stack()
In [8]: df.memory_usage().sum()
Out[8]: 7274496

In [10]: ser.memory_usage()
Out[10]: 10651360

In [11]: ser.memory_usage() / df.memory_usage().sum()
Out[11]: 1.4642059051238738

In [12]: df.to_hdf('f:/f1.h5', 'df')
In [13]: ser.to_hdf('f:/f2.h5', 'ser')
In [14]: import os

In [15]: os.stat('f:/f2.h5').st_size / os.stat('f:/f1.h5').st_size
Out[15]: 1.498167701758398

And the version info of pandas:

pd.show_versions()

INSTALLED VERSIONS
------------------
commit: None
python: 3.6.1.final.0
python-bits: 64
OS: Windows
OS-release: 7
machine: AMD64
processor: Intel64 Family 6 Model 58 Stepping 9, GenuineIntel
byteorder: little
LC_ALL: None
LANG: None
LOCALE: None.None

pandas: 0.20.1
pytest: 3.0.7
pip: 9.0.1
setuptools: 27.2.0
Cython: 0.25.2
numpy: 1.12.1


问:
Python - check if string contains any element from a list
I need to check whether a string contains any element of a list. I'm currently using this method:

```<code>engWords = ["the", "a", "and", "of", "be", "that", "have", "it", "for", "not"]
engSentence = "the dogs fur is black and white"

print("the english sentence is: " + engSentence)

engWords2 = []
isEnglish = 0

for w in engWords:
    if w in engSentence:
        isEnglish = 1
        engWords2.append(w)

if isEnglish == 1:
    print("The sentence is english and contains the words: ")
    print(engWords2)
</code>```

The problem with this is that it gives the output:

```<code>the english sentence is: the dogs fur is black and white
The sentence is english and contains the words:
['the', 'a', 'and', 'it']
>>>
</code>```

As you can see 'a' and 'it' should not be present. How can i search so that it will only list individual words, rather than parts of a word also? I'm open to any ideas using normal python code, or regex(although I'm very new to both python and regex, so please nothing too complicated) Thank you.

答:
You may want to use regex matching. Try something like following

```<code>import re

match_list = ['foo', 'bar', 'eggs', 'lamp', 'owls']
match_str = 'owls are not what they seem'
match_regex = re.compile('^.*({1}).*$'.format('|'.join(match_list)))

if match_regex.match(match_str):
    print('We have a match.')
</code>```

See the re documentation on python.org for details.

Body:
I need to check whether a string contains any element of a list. I'm currently using this method:

engWords = ["the", "a", "and", "of", "be", "that", "have", "it", "for", "not"]
engSentence = "the dogs fur is black and white"

print("the english sentence is: " + engSentence)

engWords2 = []
isEnglish = 0

for w in engWords:
    if w in engSentence:
        isEnglish = 1
        engWords2.append(w)

if isEnglish == 1:
    print("The sentence is english and contains the words: ")
    print(engWords2)

The problem with this is that it gives the output:

the english sentence is: the dogs fur is black and white
The sentence is english and contains the words:
['the', 'a', 'and', 'it']
>>>

As you can see 'a' and 'it' should not be present. How can i search so that it will only list individual words, rather than parts of a word also? I'm open to any ideas using normal python code, or regex(although I'm very new to both python and regex, so please nothing too complicated) Thank you.

Body:
You may want to use regex matching. Try something like following

import re

match_list = ['foo', 'bar', 'eggs', 'lamp', 'owls']
match_str = 'owls are not what they seem'
match_regex = re.compile('^.*({1}).*$'.format('|'.join(match_list)))

if match_regex.match(match_str):
    print('We have a match.')

See the re documentation on python.org for details.


问:
curl to get actual file only seems to get a download link
I run command

```<code>curl https://sw5-test.longboat.com/test1/admin/training/certificate/download?file=test1%2F5620cdf1-9510-407f-8851-eb1b84898a4c%2F4%2F1499333042.pdf
</code>```

But it only returns this.

```<code>download?file=test1%2F5620cdf1-9510-407f-8851-eb1b84898a4c%2F4%2F1499333042.pdf
</code>```

I obviously want the file itself. What am i missing?

答:
Check the response headers (with -v or -I). That's most likely a 30X redirect response with a Location: header to the actual content.

Add -L or --location to the curl command line to make curl automatically follow the redirect and ask for it from the new URL.

Body:
I run command

curl https://sw5-test.longboat.com/test1/admin/training/certificate/download?file=test1%2F5620cdf1-9510-407f-8851-eb1b84898a4c%2F4%2F1499333042.pdf

But it only returns this.

download?file=test1%2F5620cdf1-9510-407f-8851-eb1b84898a4c%2F4%2F1499333042.pdf

I obviously want the file itself. What am i missing?


问:
C# and ASP.NET custom property attributes and determining if properties changed
I am working on a project where we want to keep a history of a particular object. On save I want a method on the object that will determine if it has changed so that I can call a method to save its current state to history. E.g. I populate a form from an object the user makes changes (or possibly not) and submits the from. I want to take my original object and a copy of that object that has been updated from the form and determine if it has changed at all. Additionally I may decide at some point that certain properties don't matter (e.g. if Name changes I won't track it).

I'm thinking the easiest/most flexible way to accomplish this would be if I could give the properties I care about a custom attribute [ChangeTracked] and then I could use reflection to get a list of all properties with that attribute and loop through them comparing A.property == B.property to determine if any have changed.

Would this work? Is there a significantly better/easier way to handle this, like some sort of built in method you can add to an object to determine if the values of any properties have changed? Whatever the solution some psudo code would be appreciated. Just as a point of clarification the solution needs to determine if the value I care about has actually changed not just if it has been assigned since it was created i.e. if I set Name="bob" and it was already "bob" before my assignment this does not count as a change.

答:
One possible method would be to add a deep copy of the object as a private property of the object when it is loaded. (One method of deep copy)

On save you can compare the copy object to your "live" object to see if any changes have occurred.

ContentLicense: CC BY-SA 2.5


问:
How to convert a distance units
I want to convert 4.5 km to mile in depending on the user's location.

Is it possible in Android?

In iOS I can use something like

```<code>fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)
</code>```

答:
Is it possible in Android? YES

1 Km = 0.621371 Miles.

You can make a helper function from the above formula.

```<code>public float convertKmsToMiles(float kms){
    float miles = 0.621371 * kms;
    return miles;
}
</code>```

Pass your Kms value to this function and you will get the Miles value for it. :)

```<code>float miles = convertKmsToMiles(4.5);
</code>```

Title: How to convert a distance units

Body:
I want to convert 4.5 km to mile in depending on the user's location.

Is it possible in Android?

In iOS I can use something like

fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)

Body:
Is it possible in Android? YES

1 Km = 0.621371 Miles.

You can make a helper function from the above formula.

public float convertKmsToMiles(float kms){
    float miles = 0.621371 * kms;
    return miles;
}

Pass your Kms value to this function and you will get the Miles value for it. :)

float miles = convertKmsToMiles(4.5);


问:
VB.net GROUP By Date ignore time
Currently trying to group by date but ignoring the time thats presented it as my dgv groups it by the time aswell, i've looked around and am struggling to adapt to work. This is the original code that works but groups by date/time.

```<code>Dim sql2
    Try

        connect()
        sql2 = "SELECT r_datetime, SUM(r_quantity) FROM [r_repair] WHERE r_location = 'CNV' AND r_line =('" & computer_line & "') AND r_datetime >= @startdata2 AND r_datetime < @enddata2 AND r_area = 'DPMO(T)' GROUP BY r_datetime"
        Dim adapter2 As New SqlDataAdapter(sql2, con)

        With adapter2.SelectCommand.Parameters
            .Clear()

            .Add("@startdata2", SqlDbType.DateTime).Value = monthly_from.Value
            .Add("@enddata2", SqlDbType.DateTime).Value = monthly_to.Value.AddDays(1)
        End With

        Dim table_stencil As New DataTable()
        table_stencil.Locale = System.Globalization.CultureInfo.InvariantCulture
        adapter2.Fill(table_stencil)
        Me.bs_m_t.DataSource = table_stencil

        dgv_m_t.DataSource = bs_m_t

        disconnect()

        dgv_m_t.RowHeadersWidth = "28"

        dgv_m_t.Columns(0).HeaderText = "Date:"
        dgv_m_t.Columns(1).HeaderText = "Quantity:"

        dgv_m_t.EnableHeadersVisualStyles = False

    Catch ex As System.Exception
    End Try
</code>```

Any idea's?

Cheers,
Pete

答:
First, you should always parameterize all your variables.

Second, if you want to group by date, you can't have the datetime in the select list, you'll have to do something like this:

```<code>SELECT cast(r_datetime as date) as r_date,
       SUM(r_quantity) as r_sum_quantity
FROM [r_repair]
WHERE r_location = 'CNV'
AND r_line = @r_line
AND r_datetime >= @startdata2
AND r_datetime < @enddata2
AND r_area = 'DPMO(T)'
GROUP BY CAST(r_datetime as date)
</code>```

Title: VB.net GROUP By Date ignore time

Body:
Currently trying to group by date but ignoring the time thats presented it as my dgv groups it by the time aswell, i've looked around and am struggling to adapt to work. This is the original code that works but groups by date/time.

Dim sql2
    Try

        connect()
        sql2 = "SELECT r_datetime, SUM(r_quantity) FROM [r_repair] WHERE r_location = 'CNV' AND r_line =('" & computer_line & "') AND r_datetime >= @startdata2 AND r_datetime < @enddata2 AND r_area = 'DPMO(T)' GROUP BY r_datetime"
        Dim adapter2 As New SqlDataAdapter(sql2, con)

        With adapter2.SelectCommand.Parameters
            .Clear()

            .Add("@startdata2", SqlDbType.DateTime).Value = monthly_from.Value
            .Add("@enddata2", SqlDbType.DateTime).Value = monthly_to.Value.AddDays(1)
        End With

        Dim table_stencil As New DataTable()
        table_stencil.Locale = System.Globalization.CultureInfo.InvariantCulture
        adapter2.Fill(table_stencil)
        Me.bs_m_t.DataSource = table_stencil

        dgv_m_t.DataSource = bs_m_t

        disconnect()

        dgv_m_t.RowHeadersWidth = "28"

        dgv_m_t.Columns(0).HeaderText = "Date:"
        dgv_m_t.Columns(1).HeaderText = "Quantity:"

        dgv_m_t.EnableHeadersVisualStyles = False

    Catch ex As System.Exception
    End Try

Any idea's?

Cheers,
Pete

Body:
First, you should always parameterize all your variables.

Second, if you want to group by date, you can't have the datetime in the select list, you'll have to do something like this:

SELECT cast(r_datetime as date) as r_date,
       SUM(r_quantity) as r_sum_quantity
FROM [r_repair]
WHERE r_location = 'CNV'
AND r_line = @r_line
AND r_datetime >= @startdata2
AND r_datetime < @enddata2
AND r_area = 'DPMO(T)'
GROUP BY CAST(r_datetime as date)


答:
The basic idea is to set a background-color for the icon element, give it border-radius: 50% (to make the corners circular, or rounded), text-align: center; so the icons are center aligned.

And finally, give the :before psuedo-class a line-height equal to the height of the element to align the icons vertically.

Here's the relevant CSS:

```<code>.vote-fa {
  background-color: #ffffff;
  color: #ff8800;
  height: 80px;
  width: 80px;
  text-align: center;
  border-radius: 50%;
  margin-bottom: 20px;
}

.vote-fa:before {
  line-height: 80px;
}
</code>```

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  background-color: #ffffff;
  color: #ff8800;
  height: 80px;
  width: 80px;
  text-align: center;
  border-radius: 50%;
  margin-bottom: 20px;
}

.vote-fa:before {
  line-height: 80px;
}

.vote-container a {
  cursor: pointer;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          Click here to vote!
        </div>
      </div>
    </div>
  </div>
</div></code>```

Title: How could i make a div with rounded borders and make the fa icons inside it centered?

Body:
The basic idea is to set a background-color for the icon element, give it border-radius: 50% (to make the corners circular, or rounded), text-align: center; so the icons are center aligned.

And finally, give the :before psuedo-class a line-height equal to the height of the element to align the icons vertically.

Here's the relevant CSS:

.vote-fa {
  background-color: #ffffff;
  color: #ff8800;
  height: 80px;
  width: 80px;
  text-align: center;
  border-radius: 50%;
  margin-bottom: 20px;
}

.vote-fa:before {
  line-height: 80px;
}

.normal-page {
  padding-top: 30px;
}

body .normal-page {
  z-index: 998;
  position: relative;
  padding-bottom: 10px;
  background: url(../images/tpbg.jpg) top center no-repeat #141416;
  border: 1px solid #000;
  border-top: 0;
  min-height: 500px;
}

.container {
  padding-right: 15px;
  padding-left: 15px;
  margin-right: auto;
  margin-left: auto;
}

.vote-container {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  color: #fff;
}

.vote-fa {
  background-color: #ffffff;
  color: #ff8800;
  height: 80px;
  width: 80px;
  text-align: center;
  border-radius: 50%;
  margin-bottom: 20px;
}

.vote-fa:before {
  line-height: 80px;
}

.vote-container a {
  cursor: pointer;
}

<link href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="normal-page">
  <div class="container">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-handshake-o fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
      <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
        <div class="vote-container">
          <i class="fa fa-superpowers fa-3x vote-fa" aria-hidden="true"></i>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu risus vitae metus rhoncus tincidunt eu a lorem.</p><br>
          <a href="#">Click here to vote!</a>
        </div>
      </div>
    </div>
  </div>
</div>


问:
What is maybe_convert_objects good for?
I'm profiling the timing of one od my functions and I see that I spent alot of time on pandas DataFrame creation - I'm talking about 2.5 seconds to construct a dataFrame with 1000 columns and 10k rows:

```<code>def test(size):
samples = []
for r in range(10000):
    a,b = np.random.randint(100, size=2)
    data = np.random.beta(a,b ,size = size)
    samples.append(data)
return DataFrame(samples, dtype = np.float64)
</code>```

Running %prun -l 4 test(1000) returns:

Is there anyway I can avoid this check? This really not seems Tried to find out about this method and ways to bypass here but didnt find anything online.

答:
pandas must introspect each row because you are passing it a list of arrays. Here are some more efficient methods in this case.</p>

```<code>In [27]: size=1000

In [28]: samples = []
    ...: for r in range(10000):
    ...:     data = np.random.beta(1,1 ,size = size)
    ...:     samples.append(data)
    ...:

In [29]: np.asarray(samples).shape
Out[29]: (10000, 1000)

# original
In [30]: %timeit DataFrame(samples)
2.29 s ± 91.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# numpy is less flexible on the conversion, but in this case
# it is fine
In [31]: %timeit DataFrame(np.asarray(samples))
30.9 ms ± 426 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# you should probably just do this
In [32]: samples = np.random.beta(1,1, size=(10000, 1000))

In [33]: %timeit DataFrame(samples)
74.4 µs ± 381 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
</code>```

Title: What is maybe_convert_objects good for?

Body:
I'm profiling the timing of one od my functions and I see that I spent alot of time on pandas DataFrame creation - I'm talking about 2.5 seconds to construct a dataFrame with 1000 columns and 10k rows:

def test(size):
samples = []
for r in range(10000):
    a,b = np.random.randint(100, size=2)
    data = np.random.beta(a,b ,size = size)
    samples.append(data)
return DataFrame(samples, dtype = np.float64)

Running %prun -l 4 test(1000) returns:

Is there anyway I can avoid this check? This really not seems Tried to find out about this method and ways to bypass here but didnt find anything online.

Body:
pandas must introspect each row because you are passing it a list of arrays. Here are some more efficient methods in this case.

In [27]: size=1000

In [28]: samples = []
    ...: for r in range(10000):
    ...:     data = np.random.beta(1,1 ,size = size)
    ...:     samples.append(data)
    ...:

In [29]: np.asarray(samples).shape
Out[29]: (10000, 1000)

# original
In [30]: %timeit DataFrame(samples)
2.29 s ± 91.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# numpy is less flexible on the conversion, but in this case
# it is fine
In [31]: %timeit DataFrame(np.asarray(samples))
30.9 ms ± 426 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

# you should probably just do this
In [32]: samples = np.random.beta(1,1, size=(10000, 1000))

In [33]: %timeit DataFrame(samples)
74.4 µs ± 381 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)


问:
Select an element with it's background color is not working in jQuery
Please check my code. The  condition for checking the background color are not working.

https://jsfiddle.net/oL7tdL22/1/

$(function(){

$(".testing").each(function(){
   if($(this).css("background-color")=="rgb(255,193,0)"){
     alert("found");
   }
   else{
     alert("not found");
   }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="parent">
<div class="testing"  style="background-color:rgb(255,193,0)">
Test
</div>
</div>

<div class="parent">
<div class="testing"  style="background-color:rgb(220, 4, 81)">
Test
</div>
</div>

<div class="parent">
<div class="testing"  style="background-color:rgb(0, 186, 76)">
Test
</div>
</div></code>```

When we are alert background color, it's working. But we cannot match the colors.

答:
You need to seperate the rgb values with a space, as JQuery parses the .css("background-color") value this way.

```<code>rgb(X, Y, Z)
      ▲  ▲
</code>```

This is the correct code:

```<code>if($(this).css("background-color")=="rgb(255, 193, 0)"){
   alert("found");
}
</code>```

Code snippet:

$(function(){
     $(".testing").each(function(){
        if($(this).css("background-color")=="rgb(255, 193, 0)")
          alert("found");
        else
          alert("not found");
     });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="parent">
    <div class="testing"  style="background-color:rgb(255,193,0)">Test</div>
</div>
<div class="parent">
    <div class="testing"  style="background-color:rgb(220, 4, 81)">Test</div>
</div>
<div class="parent">
    <div class="testing"  style="background-color:rgb(0, 186, 76)">Test</div>
</div></code>```

Body:
Please check my code. The  condition for checking the background color are not working.

https://jsfiddle.net/oL7tdL22/1/

$(function(){

$(".testing").each(function(){
   if($(this).css("background-color")=="rgb(255,193,0)"){
     alert("found");
   }
   else{
     alert("not found");
   }
  });

});

Test

Test

Test

When we are alert background color, it's working. But we cannot match the colors.

Body:
You need to seperate the rgb values with a space, as JQuery parses the .css("background-color") value this way.

rgb(X, Y, Z)
      ▲  ▲

This is the correct code:

if($(this).css("background-color")=="rgb(255, 193, 0)"){
   alert("found");
}

Code snippet:

$(function(){
     $(".testing").each(function(){
        if($(this).css("background-color")=="rgb(255, 193, 0)")
          alert("found");
        else
          alert("not found");
     });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="parent">
    <div class="testing"  style="background-color:rgb(255,193,0)">Test</div>
</div>
<div class="parent">
    <div class="testing"  style="background-color:rgb(220, 4, 81)">Test</div>
</div>
<div class="parent">
    <div class="testing"  style="background-color:rgb(0, 186, 76)">Test</div>
</div>


问:
Saving Word2Vec for CNN Text Classification
I want to train my own Word2Vec model for my text corpus. I can get the code from TensorFlow's tutorial. What I don't know is how to save this model to use for CNN text classification later? Should I use pickle to save it and then read it later?</p>

答:
No pickling is not the way of saving the model in case of tensorflow.

Tensorflow provides with tensorflow serving for saving the models as proto bufs(for exporting the model). The way to save model would be to save the  tensorflow session as:
             saver.save(sess, 'my_test_model',global_step=1000)

Heres the link for complete answer:
            Tensorflow: how to save/restore a model?


问:
Good Database Solutions for small-medium Traffic Sites and Silverlight
What are some good database solutions that support Silverlight and are solid for a small-medium traffic website

Easy to use/Manage is a very strong plus

edit: Forgot to mention that the database needs to be very smartphone-friendly, it needs to be able to work with devices on iOS, Android, and Windows Phone 7

答:
Silverlight is not bound to a database.
Every database available to ADO.NET is usable within .NET.
MSSQL Express is a good solution (especially in .NET env) as well as any other like MySQL.</p>


问:
How to edit input style by using ng-pattern
I made a small js here

I also add the code to the Stack overflow snippet but for some reason it doesn't work to me

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.my_model = ''
   $scope.my_regex = '/^[A-Za-z]+(\,[A-Za-z]+)*$/';
    $scope.my_placeHolder = 'write something';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid input[name=my_input]{
  border: 2px solid red;
}

input[name=my_input] {
  border: 2px solid blue;
}</code>```

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{ 'invalid': contentForm['my_input'].$invalid }"
         ng-model="my_model"
         ng-pattern="{{my_regex}}"
         placeholder="{{my_placeHolder}}">
  </form>

```

I tried to use the code snippet but weren't working >,<

So, my goal is to edit the input border (let's make it red for purpose) if the input text doesn't pass the regex rule.

The regex should accept any comma separated string.

I tried a bunch of stuff, but I can't figure out what am i doing wrong.

UPDATE: REGEX EDITED

答:
Try with This

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{'invalid': contentForm['my_input'].$error.pattern  }"
         ng-model="my_model"
         ng-pattern="'( )*,( )*[a-zA-Z]+)*'"
         placeholder="{{my_placeHolder}}">
  </form>

```

Body:
I made a small js here

I also add the code to the Stack overflow snippet but for some reason it doesn't work to me

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.my_model = ''
   $scope.my_regex = '/^[A-Za-z]+(\,[A-Za-z]+)*$/';
    $scope.my_placeHolder = 'write something';
}

.invalid input[name=my_input]{
  border: 2px solid red;
}

input[name=my_input] {
  border: 2px solid blue;
}

  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{ 'invalid': contentForm['my_input'].$invalid }"
         ng-model="my_model"
         ng-pattern="{{my_regex}}"
         placeholder="{{my_placeHolder}}">
  </form>

I tried to use the code snippet but weren't working >,<

So, my goal is to edit the input border (let's make it red for purpose) if the input text doesn't pass the regex rule.

The regex should accept any comma separated string.

I tried a bunch of stuff, but I can't figure out what am i doing wrong.

UPDATE: REGEX EDITED

Body:
Try with This

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MyCtrl">
  <form name="contentForm">
    <input type="text"
         name="my_input"
         ng-class="{'invalid': contentForm['my_input'].$error.pattern  }"
         ng-model="my_model"
         ng-pattern="'( )*,( )*[a-zA-Z]+)*'"
         placeholder="{{my_placeHolder}}">
  </form>
</div>


问:
Parsing JSON and extracting URLS for images
I have an issue with my code, I have parsed out my JSON to the level where I get a URL for an image. I'm trying to populate an image view in a collection view cell with the image that the URL is giving me. Here is my code. </p>

```<code>import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var media = NSDictionary()

    @IBAction func SearchBTN(_ sender: AnyObject) {
        getPictures()

    }
    @IBOutlet weak var CollectionView: UICollectionView!
    @IBOutlet weak var searchBoxTF: UITextField!

    func getPictures(){
        let url = URL(string: "http://www.flickr.com/services/feeds/photos_public.gne?tags=baseball&format=json&nojsoncallback=1")
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = URLSession.shared.dataTask(with: url!){(data, response, error) in
            if error != nil
            {
                print("Error")
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? AnyObject
                    //print(myJSON)
                        if let images = myJSON?["items"] as? [[String: AnyObject]]
                        {
                            var media = UIImage()
                            for media in images
                            {
                               // let media = self.media
                                print(media["media"])

                            }

                        }
                    }

                    catch
                    {

                    }
                }
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        CollectionView.delegate = self
        CollectionView.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return media.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell
        cell.imageView.image = media[indexPath.item]as? UIImage
        return cell
    }

}
</code>```

答:
Try this code you will get your expected output

```<code>import UIKit

private let reuseIdentifier = "Cell"

class MCollectionViewController: UICollectionViewController {

    var arraImage: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        self.collectionView!.backgroundColor = UIColor.whiteColor()
        RestAPIManager.sharedInstance.getServerData { (Json) -> Void in
            //print("Response = \(Json)")
            let array = Json["items"].arrayValue
            for item in array {
                print("\(item["media"]["m"])")
                self.arraImage.append(item["media"]["m"].stringValue)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.collectionView!.reloadData()
                })
            }
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return arraImage.count
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let padding =  10
        let collectionViewSize = collectionView.frame.size.width - CGFloat(padding)

        return CGSizeMake(collectionViewSize/2, collectionViewSize/2)

    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        if let url: NSURL = NSURL(string: arraImage[indexPath.row]) {
            cell.imageView.sd_setImageWithURL(url)
        }
        return cell
    }

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {

    }
    */

}
</code>```

I have also attached the link where you will find the project here

Body:
I have an issue with my code, I have parsed out my JSON to the level where I get a URL for an image. I'm trying to populate an image view in a collection view cell with the image that the URL is giving me. Here is my code.

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var media = NSDictionary()

    @IBAction func SearchBTN(_ sender: AnyObject) {
        getPictures()

    }
    @IBOutlet weak var CollectionView: UICollectionView!
    @IBOutlet weak var searchBoxTF: UITextField!

    func getPictures(){
        let url = URL(string: "http://www.flickr.com/services/feeds/photos_public.gne?tags=baseball&format=json&nojsoncallback=1")
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = URLSession.shared.dataTask(with: url!){(data, response, error) in
            if error != nil
            {
                print("Error")
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? AnyObject
                    //print(myJSON)
                        if let images = myJSON?["items"] as? [[String: AnyObject]]
                        {
                            var media = UIImage()
                            for media in images
                            {
                               // let media = self.media
                                print(media["media"])

                            }

                        }
                    }

                    catch
                    {

                    }
                }
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        CollectionView.delegate = self
        CollectionView.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return media.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell
        cell.imageView.image = media[indexPath.item]as? UIImage
        return cell
    }

}

Body:
Try this code you will get your expected output

import UIKit

private let reuseIdentifier = "Cell"

class MCollectionViewController: UICollectionViewController {

    var arraImage: [String] = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        self.collectionView!.backgroundColor = UIColor.whiteColor()
        RestAPIManager.sharedInstance.getServerData { (Json) -> Void in
            //print("Response = \(Json)")
            let array = Json["items"].arrayValue
            for item in array {
                print("\(item["media"]["m"])")
                self.arraImage.append(item["media"]["m"].stringValue)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.collectionView!.reloadData()
                })
            }
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return arraImage.count
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let padding =  10
        let collectionViewSize = collectionView.frame.size.width - CGFloat(padding)

        return CGSizeMake(collectionViewSize/2, collectionViewSize/2)

    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        if let url: NSURL = NSURL(string: arraImage[indexPath.row]) {
            cell.imageView.sd_setImageWithURL(url)
        }
        return cell
    }

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {

    }
    */

}

I have also attached the link where you will find the project here


问:
Interpreting dummy variables created in caret train
I understand from reading various answers 1,2,3, that the train function from caret will create dummy variables to deal with factors that have multiple levels.

Here is an example using mtcars (model is useless other than to show point):

```<code>library(caret)
library(rattle)

df <- mtcars

df$cyl <- factor(df$cyl)
df$mpg_bound <- ifelse(df$mpg > 20, "good", "bad")

tc <- trainControl(classProbs = TRUE, summaryFunction = twoClassSummary)

mod <- as.formula(mpg_bound ~ cyl)

set.seed(666)

m1 <- train(mod, data = df,
            method = "rpart",
            preProcess = c("center", "scale"),
            trControl = tc)

fancyRpartPlot(m1$finalModel)

m1$finalModel

n= 32

node), split, n, loss, yval, (yprob)
      * denotes terminal node

1) root 32 14 bad (0.5625000 0.4375000)
  2) cyl8>=0.124004 14  0 bad (1.0000000 0.0000000) *
  3) cyl8< 0.124004 18  4 good (0.2222222 0.7777778) *
</code>```

I don't understand this part cyl8>=0.124004. I get that cyl8 is the dummy variable for the factor but what does it mean that cyl8>=0.124004?

答:
I'd like to extend the existing answer, because I don't think the conclusion reached in the comments is true. As you say, when using the formula interface, caret's train function will transform factor variables into dummy variables that only take the values 0 or 1, e.g. cyl8 == 1 means 'the car has 8 cylinders'.  Each dummy variable makes a statement about a characteristic that is either true or false for the observation.

Rpart will nevertheless output a numeric value as the split criterion, so that cyl8 >= 0.5, cyl8 >= 0.2 and cyl8 == 1 all mean the same thing "This car has exactly 8 cylinders". By default, rpart will choose the split value cyl8 >= 0.5 for binary dummies to indicate that the dummy is true. The interpretation of cyl8 >= 0.5 is then "Does the car have 8 cylinders?" (and not "Does the car have more than 8 cylinders?")

```<code>df <- mtcars

df$cyl <- factor(df$cyl)
df$mpg_bound <- ifelse(df$mpg > 20, "good", "bad")

library(caret)
tc <- trainControl(classProbs = TRUE, summaryFunction = twoClassSummary)
set.seed(166)
m1 <- train(mod, data = df,
        method = "rpart",
        #preProcess = c("center", "scale"),
        trControl = tc,
        metric = "ROC")

m1$finalModel
   #1) root 32 14 bad (0.5625000 0.4375000)
     #2) cyl8>=0.5 14  0 bad (1.0000000 0.0000000) *
     #3) cyl8< 0.5 18  4 good (0.2222222 0.7777778) *
</code>```

The confusing value in your example is caused because caret apparently applies the preProcessing to the extended dataset where the dummies are numeric variables. The interpretation stays the same, but the (arbitrary) split value is transformed.

```<code># Transform to dummies
mm <- model.matrix(mpg_bound ~ .-1, data = df)

# Do pre-processing
pp <- preProcess(mm, method = c("center", "scale"))
mm.pp <- as.matrix(predict(pp, mm))

# Dummy-Split in the middle
(max(mm.pp[,"cyl8"]) + min(mm.pp[,"cyl8"]) ) / 2
</code>```

Body:
I understand from reading various answers 1,2,3, that the train function from caret will create dummy variables to deal with factors that have multiple levels.

Here is an example using mtcars (model is useless other than to show point):

library(caret)
library(rattle)

df <- mtcars

df$cyl <- factor(df$cyl)
df$mpg_bound <- ifelse(df$mpg > 20, "good", "bad")

tc <- trainControl(classProbs = TRUE, summaryFunction = twoClassSummary)

mod <- as.formula(mpg_bound ~ cyl)

set.seed(666)

m1 <- train(mod, data = df,
            method = "rpart",
            preProcess = c("center", "scale"),
            trControl = tc)

fancyRpartPlot(m1$finalModel)

m1$finalModel

n= 32

node), split, n, loss, yval, (yprob)
      * denotes terminal node

1) root 32 14 bad (0.5625000 0.4375000)
  2) cyl8>=0.124004 14  0 bad (1.0000000 0.0000000) *
  3) cyl8< 0.124004 18  4 good (0.2222222 0.7777778) *

I don't understand this part cyl8>=0.124004. I get that cyl8 is the dummy variable for the factor but what does it mean that cyl8>=0.124004?

Body:
I'd like to extend the existing answer, because I don't think the conclusion reached in the comments is true. As you say, when using the formula interface, caret's train function will transform factor variables into dummy variables that only take the values 0 or 1, e.g. cyl8 == 1 means 'the car has 8 cylinders'.  Each dummy variable makes a statement about a characteristic that is either true or false for the observation.

Rpart will nevertheless output a numeric value as the split criterion, so that cyl8 >= 0.5, cyl8 >= 0.2 and cyl8 == 1 all mean the same thing "This car has exactly 8 cylinders". By default, rpart will choose the split value cyl8 >= 0.5 for binary dummies to indicate that the dummy is true. The interpretation of cyl8 >= 0.5 is then "Does the car have 8 cylinders?" (and not "Does the car have more than 8 cylinders?")

df <- mtcars

df$cyl <- factor(df$cyl)
df$mpg_bound <- ifelse(df$mpg > 20, "good", "bad")

library(caret)
tc <- trainControl(classProbs = TRUE, summaryFunction = twoClassSummary)
set.seed(166)
m1 <- train(mod, data = df,
        method = "rpart",
        #preProcess = c("center", "scale"),
        trControl = tc,
        metric = "ROC")

m1$finalModel
   #1) root 32 14 bad (0.5625000 0.4375000)
     #2) cyl8>=0.5 14  0 bad (1.0000000 0.0000000) *
     #3) cyl8< 0.5 18  4 good (0.2222222 0.7777778) *

The confusing value in your example is caused because caret apparently applies the preProcessing to the extended dataset where the dummies are numeric variables. The interpretation stays the same, but the (arbitrary) split value is transformed.

# Transform to dummies
mm <- model.matrix(mpg_bound ~ .-1, data = df)

# Do pre-processing
pp <- preProcess(mm, method = c("center", "scale"))
mm.pp <- as.matrix(predict(pp, mm))

# Dummy-Split in the middle
(max(mm.pp[,"cyl8"]) + min(mm.pp[,"cyl8"]) ) / 2


问:
Hive - select data from group with at least one row containing
Suppose i have a table in hive like so:

```<code>|Id|Data |Data2 |Groupkey|
|1 |One  |      |Group1  |
|2 |Two  |Stuff |Group1  |
|3 |Shoes|Some  |Group2  |
|4 |four |Stuff |Group2  |
|5 |Three|Notme |Group3  |
</code>```

For each group  that contains 'Stuff' in Data2 i want to get the row that has Groupkey and Data from the row other than the Stuff, and Data2 from 'Stuff' row.

So resulting data set would look something like

```<code>|Group |Data |Data2|
|Group1|One  |Two  |
|Group2|Shoes|four |
</code>```

I was hoping to get something going with a GROUP BY, i started going with

SELECT Data, Groupkey FROM (SELECT Data, GroupKey FROM MyTable GROUP BY Groupkey) WHERE Data2 <> 'Stuff' but this fails suggesting i need to include Data in the group by but that is not what i want to group by?

And i'm not sure how to select just the groups containing one row with certain data.

答:
```<code>SELECT DISTINCT Groupkey, t1.Data, t2.Data as Data2
FROM t t1
INNER JOIN t t2
ON t1.Groupkey = t2.Groupkey
AND t1.Data2 <> t2.Data2
WHERE t2.Data2 = 'Stuff'
</code>```

Body:
Suppose i have a table in hive like so:

|Id|Data |Data2 |Groupkey|
|1 |One  |      |Group1  |
|2 |Two  |Stuff |Group1  |
|3 |Shoes|Some  |Group2  |
|4 |four |Stuff |Group2  |
|5 |Three|Notme |Group3  |

For each group  that contains 'Stuff' in Data2 i want to get the row that has Groupkey and Data from the row other than the Stuff, and Data2 from 'Stuff' row.

So resulting data set would look something like

|Group |Data |Data2|
|Group1|One  |Two  |
|Group2|Shoes|four |

I was hoping to get something going with a GROUP BY, i started going with

SELECT Data, Groupkey FROM (SELECT Data, GroupKey FROM MyTable GROUP BY Groupkey) WHERE Data2 <> 'Stuff' but this fails suggesting i need to include Data in the group by but that is not what i want to group by?

And i'm not sure how to select just the groups containing one row with certain data.


问:
how to use ng-show to display specific divs inside an ng-repeat?
I have an ng-repeat div to dynamically display a set of div tags based on a dynamic list of items, that each have a unique Id , a type and a "title" value which are both strings and I have a click function assigned to each of them. When I want to click on one of these divs , I want to display an separate div associated to that clicked div and I want to do that using an ng-show which at the moment has a condition where the id of this item/div should be equal/equivalent to a
scope variable I've defined in a controller associated with the html for this new div to be displayed.

The problem I'm getting is that every one of these separate divs is showing and assuming that all the ng-shows are true which shouldn't be the case and I'm not sure why this is happening as all the id's for the items are unique. I've printed out to the console and can't see anything wrong with the assigning of the variable but not sure if I've missed something with regards to the ng-show condition.

Here is what I have so far  in html with 2 div examples (don't worry about replicating all the styling, i just want to figure out what is going on with the html/angular stuff):

```<code><div class="col-md-12 col-sm-12 col-xs-12  " ng-repeat="item in items track by item.id"  ng-click="onClick(item.id)">

  //first type div that is clickable
  <div class="row">
    <div>
      <header class="text">
        <h1 data-ng-if="item.title" ng-bind-html="item.title"></h1>
      </header>
    </div>
  </div>

  //div to be displayed after associated first div type is clicked
  <div class=" col-sm-11 row"  ng-show="displayMessage===item.id"   >
      <header class="col-sm-12 text">
          <h1  data-ng-if="item.title" ng-bind-html="item.title"></h1>
      </header>
      <p class="col-sm-12" > text about {{item.id]} </p>
  </div>

  //2nd type of  div
  <div class="row"  style=" background: linear-gradient(135deg, #156570, #1e9d8b);">
      <h1 data-ng-if="item.title" ng-bind-html="item.title"></h1>
      <i class="ms-icon ms-icon-heart-rate"></i>
      <div class="clearfix"></div>
  </div>

  //div to be displayed after associated second div is clicked
  <div class="col-md-11 col-sm-11 col-xs-11"  ng-show="displayMessage===item.id">

    <div style="background: linear-gradient(135deg, #156570, #1e9d8b);"></div>

    <h1 class="col-sm-12 col-xs-12"  data-ng-if="item.title" ng-bind-html="item.title" style="color:#000"></h1>

    <p class="col-sm-12 col-xs-12 "> text associated with {{item.id}}
    </p>

  </div>

</div>
</code>```

And here is the simple click function I have . $scope.displayMessage is defined earlier on during the controller setup where its set to an empty string:

```<code>$scope.onClick = function (itemId) {
    $scope.displayMessage = itemId;
}
</code>```

Let me know if I need to add more code.

答:
It could be done in a simpler way without adding property to the items varible you have in scope.

Let the Controller be

```<code>app.controller('MainCtrl', function($scope) {
  $scope.div_=[];

  $scope.items = [
  {
    id: 1,
    title: "first item"
   },
  {
    id: 2,
    title: "second item",
   },
  {
    id: 3,
    title: "third item",
   }
];

  $scope.onClick=function(index,row){
     $scope.div_[index+'_'+row]=true;
   }
  });
</code>```

HTML will be like

```<code><body ng-controller="MainCtrl">
    <div ng-repeat="item in items">
    <div style="color:red" ng-click="onClick($index,0)">DIV {{$index}}.0---click to show DIV {{$index}}.0_CHILD</div>
    <div style="color:blue" ng-show="div_[$index+'_0']">DIV {{$index}}.0_CLILD</div>
    <br>
    <div style="color:red" ng-click="onClick($index,1)">DIV {{$index}}.1---click to show DIV {{$index}}.1_CHILD</div>
    <div style="color:blue" ng-show="div_[$index+'_1']">DIV {{$index}}.1_CLILD</div>
    <hr>
    </div>
  </body>
</code>```

Here an array named 'div_' is maintained to trace all ng-show value of all div.

Working plunker https://plnkr.co/edit/uhFdCXkmS4gB95c9bjTR?p=preview

Body:
I have an ng-repeat div to dynamically display a set of div tags based on a dynamic list of items, that each have a unique Id , a type and a "title" value which are both strings and I have a click function assigned to each of them. When I want to click on one of these divs , I want to display an separate div associated to that clicked div and I want to do that using an ng-show which at the moment has a condition where the id of this item/div should be equal/equivalent to a
scope variable I've defined in a controller associated with the html for this new div to be displayed.

The problem I'm getting is that every one of these separate divs is showing and assuming that all the ng-shows are true which shouldn't be the case and I'm not sure why this is happening as all the id's for the items are unique. I've printed out to the console and can't see anything wrong with the assigning of the variable but not sure if I've missed something with regards to the ng-show condition.

Here is what I have so far  in html with 2 div examples (don't worry about replicating all the styling, i just want to figure out what is going on with the html/angular stuff):

  //first type div that is clickable

  //div to be displayed after associated first div type is clicked

 text about {{item.id]}

  //2nd type of  div

  //div to be displayed after associated second div is clicked

 text associated with {{item.id}}

And here is the simple click function I have . $scope.displayMessage is defined earlier on during the controller setup where its set to an empty string:

$scope.onClick = function (itemId) {
    $scope.displayMessage = itemId;
}

Let me know if I need to add more code.

Body:
It could be done in a simpler way without adding property to the items varible you have in scope.

Let the Controller be

app.controller('MainCtrl', function($scope) {
  $scope.div_=[];

  $scope.items = [
  {
    id: 1,
    title: "first item"
   },
  {
    id: 2,
    title: "second item",
   },
  {
    id: 3,
    title: "third item",
   }
];

  $scope.onClick=function(index,row){
     $scope.div_[index+'_'+row]=true;
   }
  });

HTML will be like

<body ng-controller="MainCtrl">
    <div ng-repeat="item in items">
    <div style="color:red" ng-click="onClick($index,0)">DIV {{$index}}.0---click to show DIV {{$index}}.0_CHILD</div>
    <div style="color:blue" ng-show="div_[$index+'_0']">DIV {{$index}}.0_CLILD</div>
    <br>
    <div style="color:red" ng-click="onClick($index,1)">DIV {{$index}}.1---click to show DIV {{$index}}.1_CHILD</div>
    <div style="color:blue" ng-show="div_[$index+'_1']">DIV {{$index}}.1_CLILD</div>
    <hr>
    </div>
  </body>

Here an array named 'div_' is maintained to trace all ng-show value of all div.

Working plunker https://plnkr.co/edit/uhFdCXkmS4gB95c9bjTR?p=preview


问:
Remove element from vector of maps
I have a vector of maps:

```<code>typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;
</code>```

How can I remove some elements from rows?

The following code does not work.

```<code>struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());
</code>```

I got the following error.

```<code>error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'
</code>```

Thanks.

答: remove_if is what you want, not remove.

Title: Remove element from vector of maps

Body:
I have a vector of maps:

typedef map<string, string> aMap;
typedef vector<aMap> rVec;
rVec rows;

How can I remove some elements from rows?

The following code does not work.

struct remove_it
{
  bool operator() (rVec& rows)
  {
    // Validation code here!

  }
};

rVec::iterator it = remove(rows.begin(), rows.end(), remove_it());
rows.erase(it, rows.end());

I got the following error.

error: no matching function for call to 'remove(std::vector<s
td::map<std::basic_string<char>, std::basic_string<char> > >::iterator, std::vec
tor<std::map<std::basic_string<char>, std::basic_string<char> > >::iterator, mai
n(int, char**)::remove_it)'

Thanks.

Body: remove_if is what you want, not remove.


问:
Script that moves files from a NAS to clients, executed on a server
I got the following problem: at work, I have to code a script that copies the files from a NAS onto a few clients, using Remote PSSessions. The script is getting executed on a domain controller.

I think something is wrong with the remote session and the "copy the files" part. But I don't know what.

#SRC=Source Data to copy
$src1 = "\\NAS01\adm\sw\CAD\Dateien_fuer_SUPPORT_Verz\def_KOPA_Linie.lin"
$src2 = "\\NAS01\adm\sw\CAD\Dateien_fuer_SUPPORT_VerzSchlinie2.shx"
$src3 = "\\NAS01\adm\sw\CAD\Dateien_fuer_SUPPORT_Verz\Schlinie2.shp"

#PowerShell Check for AD-Service
Get-Service ad*
Get-Module

#Searching through AD for PC's called "WS"
$pc = Get-ADComputer -Filter 'name -like "WS" '

#New Powershell-Remotesession with the $pc
$session = New-PSSession -ComputerName $pc

#Check if the Directory exists, if it exists, copy the files inside
$Dir = "C:\Program Files\Autodesk\AutoCAD 2015\Support\"
if (Test-Path $Dir)
{
    Copy-Items -FromSession $session -Path $src1 + src2 + src3 -Destination "C:\Program Files\Autodesk\AutoCAD 2015\Support\"
}
else
{
    echo "tohuwabohu"
}
```

答:
This will only bring back computers with the name WS:

```<code>$pc = Get-ADComputer -Filter 'name -like "WS" '
</code>```

You need to use wild cards with -like
Example: if your computernames are "WS-1234-abc",WS-2345-afgt.
Use:

```<code>$pc = Get-ADComputer -Filter 'name -like "WS*"'
</code>```

Your currentlly trying to open a remote session with no computer name

You need to run each Line of your script to see if you get the output you expect.

Copy-item (no s) does not require you to first open a remote session.
The path Parameter will take commas seperated values.
See help Copy-item

```<code>[-path] <string[]>
</code>```

the [] tells use we can use comma seperated values
Example:

```<code>Copy-Item -Path $src1,$src2,$crs3 -Destination "C:\Program Files\Autodesk\AutoCAD 2015\Support\"
</code>```

Body:
This will only bring back computers with the name WS:

$pc = Get-ADComputer -Filter 'name -like "WS" '

You need to use wild cards with -like
Example: if your computernames are "WS-1234-abc",WS-2345-afgt.
Use:

$pc = Get-ADComputer -Filter 'name -like "WS*"'

Your currentlly trying to open a remote session with no computer name

You need to run each Line of your script to see if you get the output you expect.

Copy-item (no s) does not require you to first open a remote session.
The path Parameter will take commas seperated values.
See help Copy-item

[-path] <string[]>

the [] tells use we can use comma seperated values
Example:

Copy-Item -Path $src1,$src2,$crs3 -Destination "C:\Program Files\Autodesk\AutoCAD 2015\Support\"


问:
Asp.Net Core v1.1 Get Inherited Class Names From another project in same solution
I m working with different inherited classes i want get this class names inherited from same interface

```<code>public class CollectorA : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}
public class CollectorB : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}
</code>```

I want to do like :

```<code>public void Init(IServiceCollection serviceCollection)
{

    var types  = AppDomain.CurrentDomain.GetAssemblies()
                          .SelectMany(assembly => assembly.GetTypes())
                          .Where(type => type.IsInstanceOfType(typeof(ICollector)));
</code>```

Getting types returns null I tried AppContext but still not works.

```<code>foreach(var item in types)
{
    serviceCollection.AddTransient<ICollector,item.Name>();
}
</code>```

答:
You can also add it like this

```<code>foreach(var item in types)
{
    serviceCollection.AddTransient(typeof(ICollector), item);
}
</code>```

Also in looking for the types try the following.

```<code>//get collectors
var types = typeof(CollectorA).Assembly
    .GetTypes()
    .Where(t => typeof(ICollector).IsAssignableFrom(t));

//add to service
foreach(var item in types)
{
    serviceCollection.AddTransient(typeof(ICollector), item);
}
</code>```

Body:
I m working with different inherited classes i want get this class names inherited from same interface

public class CollectorA : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}
public class CollectorB : ICollector
{
    public string CollectSomething()
    {
        //DO Something
    }
}

I want to do like :

public void Init(IServiceCollection serviceCollection)
{

    var types  = AppDomain.CurrentDomain.GetAssemblies()
                          .SelectMany(assembly => assembly.GetTypes())
                          .Where(type => type.IsInstanceOfType(typeof(ICollector)));

Getting types returns null I tried AppContext but still not works.

foreach(var item in types)
{
    serviceCollection.AddTransient<ICollector,item.Name>();
}

Body:
You can also add it like this

foreach(var item in types)
{
    serviceCollection.AddTransient(typeof(ICollector), item);
}

Also in looking for the types try the following.

//get collectors
var types = typeof(CollectorA).Assembly
    .GetTypes()
    .Where(t => typeof(ICollector).IsAssignableFrom(t));

//add to service
foreach(var item in types)
{
    serviceCollection.AddTransient(typeof(ICollector), item);
}


答:
I don't think there's necessarily a correct answer for all locales. For example, in the UK they generally use miles for large distances like a car journey, feet and inches for people's height but may use meters to describe the dimensions of a room.

You can try to do something like this:
Using locale settings to detect wheter to use imperial units

or you can just give the user the option to choose a preferred unit in a settings menu.

Hope it helps.

Title: How to convert a distance units

Body:
I want to convert 4.5 km to mile in depending on the user's location.

Is it possible in Android?

In iOS I can use something like

fileprivate let _distanceFormatter =
MKDistanceFormatter()_distanceFormatter.string(fromDistance: model.distanse)


问:
List to array Netlogo
My problem is about converting a block of list data to the array, however, I am stuck on this and have tried to code it in all possible ways that I can think of. Unfortunately, I could not figure it out.

First, I have two text files which contain these values:

0 1 2 3 438 418 424 434 439 417 421 0 ... 447 412 426 436 448 413 422
  0

Then I want to add it to Netlogo so I use this:

```<code>extensions [table matrix array csv]
globals
[
  Dummy-Retrieve-list
  patch-data
  string-array
]
to setup
file-close-all
ca
file-open "Matching.txt"
while [ not file-at-end? ]
  [
    set string-array (list n-values 4 [file-read])
    print string-array
    let i 0
    foreach string-array
    [ x -> array:set patch-data i x
      set i (i + 1)
      print patch-data
    ]
  print patch-data
  ]
file-close
</code>```

What I want here is to take a batch of 4 values (maybe n-values in the future) in the input list and then form it into an array as input for another array. However, I don't know how, so I use the foreach function to make loop through the values and then use array:set to set data onto the new array.

I don't know how the position of the values will change so I use the "set i (i + 1)" to preserve ordering. But it returns false, as it expects an anonymous command instead of list or block so I'm stuck.

Does anyone know any easier ways for transforming a list of values into a list of array values? The reason I ask this is that in the future, it may be not 4 values that will be selected but perhaps more of it, so it is impossible to use code like this:

```<code>set string-array list file-read file-read file-read file-read
</code>```

That is why I use list n-values 4 [file-read] instead. I have also searched Google and all other examples provided by NetLogo program however still not figure it out.

In summary, what I want is transforming a list like this:

```<code>[[v11 v21 v31 ... vn1] [[v12 v22 v32 ... vn2] ... [v1m v2m v3m ... vnm]]
</code>```

Into this array:

```<code>{{array: {{array: v11 v21 v31 ... vn1}} {{array: v12 v22 v32 ... vn2}} ... {{array: v1m v2m v3m ... vnm}}}}
</code>```

答:
I have found the way to answer my question and it is using the double foreach loop.

Thank you for helping me on the way answering it, @NicolasPayette.

This is the answer for my problem:

```<code>file-open "Matching.txt"
let k 0
while [ not file-at-end? ]
[
  let j 0
  set string-array (list n-values 4 [file-read])
  print string-array
  foreach string-array
  [ [i] -> foreach i
    [ [m] -> insert-retrieval j k m
      set j j + 1
    ]
  ]
  set k k + 1
  print Retrieve-list
]
file-close
</code>```

insert-retrieval j k m is a function for inputting data into the Retrieve-list with j is the column, k is the row and m is the value.

Title: List to array Netlogo

Body:
My problem is about converting a block of list data to the array, however, I am stuck on this and have tried to code it in all possible ways that I can think of. Unfortunately, I could not figure it out.

First, I have two text files which contain these values:

0 1 2 3 438 418 424 434 439 417 421 0 ... 447 412 426 436 448 413 422
  0

Then I want to add it to Netlogo so I use this:

extensions [table matrix array csv]
globals
[
  Dummy-Retrieve-list
  patch-data
  string-array
]
to setup
file-close-all
ca
file-open "Matching.txt"
while [ not file-at-end? ]
  [
    set string-array (list n-values 4 [file-read])
    print string-array
    let i 0
    foreach string-array
    [ x -> array:set patch-data i x
      set i (i + 1)
      print patch-data
    ]
  print patch-data
  ]
file-close

What I want here is to take a batch of 4 values (maybe n-values in the future) in the input list and then form it into an array as input for another array. However, I don't know how, so I use the foreach function to make loop through the values and then use array:set to set data onto the new array.

I don't know how the position of the values will change so I use the "set i (i + 1)" to preserve ordering. But it returns false, as it expects an anonymous command instead of list or block so I'm stuck.

Does anyone know any easier ways for transforming a list of values into a list of array values? The reason I ask this is that in the future, it may be not 4 values that will be selected but perhaps more of it, so it is impossible to use code like this:

set string-array list file-read file-read file-read file-read

That is why I use list n-values 4 [file-read] instead. I have also searched Google and all other examples provided by NetLogo program however still not figure it out.

In summary, what I want is transforming a list like this:

[[v11 v21 v31 ... vn1] [[v12 v22 v32 ... vn2] ... [v1m v2m v3m ... vnm]]

Into this array:

{{array: {{array: v11 v21 v31 ... vn1}} {{array: v12 v22 v32 ... vn2}} ... {{array: v1m v2m v3m ... vnm}}}}

Body:
I have found the way to answer my question and it is using the double foreach loop.

Thank you for helping me on the way answering it, @NicolasPayette.

This is the answer for my problem:

file-open "Matching.txt"
let k 0
while [ not file-at-end? ]
[
  let j 0
  set string-array (list n-values 4 [file-read])
  print string-array
  foreach string-array
  [ [i] -> foreach i
    [ [m] -> insert-retrieval j k m
      set j j + 1
    ]
  ]
  set k k + 1
  print Retrieve-list
]
file-close

insert-retrieval j k m is a function for inputting data into the Retrieve-list with j is the column, k is the row and m is the value.


问:
JSF 2 : tag wrapper to encapsulate common attribute values?
Based on this previous question How to get ID of calling component in the getter method? , here's another idea i want to ask your opinion about :

there are lots of duplicated code across jsf pages such as these examples (notice the repeating size and maxlength attribute) across components :

```<code><h:inputText label="#{msgs.userId}" id="UserId" value="#{userBean.userId}"
   required="true"
   size="#{variableConfigBean.getSize(component.id)}"
   maxlength="#{variableConfigBean.getMaxLength(component.id)}"
/>
<h:inputSecret label="#{msgs.password}" id="Password" value="#{userBean.password}"
   required="true"
   size="#{variableConfigBean.getSize(component.id)}"
   maxlength="#{variableConfigBean.getMaxLength(component.id)}"
/>
</code>```

Im thinking of :

using composite component for that
input text tag,

hardcoding the size and maxlength in the implementation section of that composite component,

so that i dont have to duplicate all
these stuffs everytime i need to use
that component.

but i'll have to open
up all attributes in the interface
section of that composite component

Is this idea ok, or perhaps there are other better ways to solve this problem ?

答:
You could do so. I've also implemented it in some projects. It only adds some (minor) overhead. You could for this particular purpose also just use a Facelets tag file instead of a JSF composite component. It's not mandatory to define the attributes then. In your particular case you can refactor pretty much duplicates if you reuse the bean property name as id and key for message bundle label.

E.g.

```<code><my:input type="text" bean="#{userBean}" property="userId" required="true" />
<my:input type="secret" bean="#{userBean}" property="password" required="true" />
</code>```

with the following in a Facelets tag file:

```<code><c:set var="id" value="#{not empty id ? id : property}" />
<c:set var="required" value="#{not empty required and required}" />

<c:choose>
    <c:when test="#{type == 'text'}">
        <h:inputText id="#{id}"
            label="#{msgs[property]}"
            value="#{bean[property]}"
            size="#{config.size(id)}"
            maxlength="#{config.maxlength(id)}"
            required="#{required}" />
    </c:when>
    <c:when test="#{type == 'secret'}">
        <h:inputSecret id="#{id}"
            label="#{msgs[property]}"
            value="#{bean[property]}"
            size="#{config.size(id)}"
            maxlength="#{config.maxlength(id)}"
            required="#{required}" />
    </c:when>
    <c:otherwise>
        <h:outputText value="Unknown input type: #{type}" />
    </c:otherwise>
</c:choose>
</code>```

I've however implemented it with an <h:outputLabel> before and a <h:message> after which makes refactoring like this more reasonable.

Body:
Based on this previous question How to get ID of calling component in the getter method? , here's another idea i want to ask your opinion about :

there are lots of duplicated code across jsf pages such as these examples (notice the repeating size and maxlength attribute) across components :

<h:inputText label="#{msgs.userId}" id="UserId" value="#{userBean.userId}"
   required="true"
   size="#{variableConfigBean.getSize(component.id)}"
   maxlength="#{variableConfigBean.getMaxLength(component.id)}"
/>
<h:inputSecret label="#{msgs.password}" id="Password" value="#{userBean.password}"
   required="true"
   size="#{variableConfigBean.getSize(component.id)}"
   maxlength="#{variableConfigBean.getMaxLength(component.id)}"
/>

Im thinking of :

using composite component for that
input text tag,

hardcoding the size and maxlength in the implementation section of that composite component,

so that i dont have to duplicate all
these stuffs everytime i need to use
that component.

but i'll have to open
up all attributes in the interface
section of that composite component

Is this idea ok, or perhaps there are other better ways to solve this problem ?

Body:
You could do so. I've also implemented it in some projects. It only adds some (minor) overhead. You could for this particular purpose also just use a Facelets tag file instead of a JSF composite component. It's not mandatory to define the attributes then. In your particular case you can refactor pretty much duplicates if you reuse the bean property name as id and key for message bundle label.

E.g.

<my:input type="text" bean="#{userBean}" property="userId" required="true" />
<my:input type="secret" bean="#{userBean}" property="password" required="true" />

with the following in a Facelets tag file:

<c:set var="id" value="#{not empty id ? id : property}" />
<c:set var="required" value="#{not empty required and required}" />

<c:choose>
    <c:when test="#{type == 'text'}">
        <h:inputText id="#{id}"
            label="#{msgs[property]}"
            value="#{bean[property]}"
            size="#{config.size(id)}"
            maxlength="#{config.maxlength(id)}"
            required="#{required}" />
    </c:when>
    <c:when test="#{type == 'secret'}">
        <h:inputSecret id="#{id}"
            label="#{msgs[property]}"
            value="#{bean[property]}"
            size="#{config.size(id)}"
            maxlength="#{config.maxlength(id)}"
            required="#{required}" />
    </c:when>
    <c:otherwise>
        <h:outputText value="Unknown input type: #{type}" />
    </c:otherwise>
</c:choose>

I've however implemented it with an <h:outputLabel> before and a <h:message> after which makes refactoring like this more reasonable.


问:
Passing Google Script Value in JavaScript and JSON
I have a code that looks like this.

code.gs

```<code>function doGet(e) {

  var t = HtmlService.createTemplateFromFile('Index');
  var matgrp = e.parameter.matgrp;
  t.dataFromServerTemplate = {first: matgrp};

  t.data = SpreadsheetApp
      .openById('1231455566776fgfgggggggg')
      .getActiveSheet()
      .getDataRange()
      .getValues();

  return t.evaluate();

}
</code>```

Please focus on this part.

var matgrp = e.parameter.matgrp;
      t.dataFromServerTemplate = {first: matgrp};

and here is index.html

```<code><!DOCTYPE html>

<script>
    var data = <?!= JSON.stringify(dataFromServerTemplate) ?>; //Stores the data directly in the javascript code

    function initialize() {
        document.getElementById("myTitle").innerText = data.first;

    }

    window.onload = initialize;
</script>

<html>
<head>
<base target="_top">

<style>
table,th,td
{
border:1px solid #ddd; font-family:tahoma;font-size: 10px
}
</style>

</head>

<body>

 <H2 id="myTitle"></H2>

<table cellspacing="0" cellpadding="3"  height ="100%" width ="60%" align = "center">
   <th>Item Code</th>
   <th>Product Name</th>
   <th>Main Description</th>
   <th>Other Description</th>

        <? for (var i = 2; i < data.length; i++) { ?>
        <tr>
        <? if(data[i][13] == "Wall Fan") {?>
        <td><?= data[i][1] ?></td>
        <td><?= data[i][2] ?></td>
     <td><?= data[i][3] ?></td>
     <td><?= data[i][4] ?></td>
     <? }else{ ?>
     <?}?>
     <? } ?>

     </tr>
</table>

</body>
</html>
</code>```

as what you see on the code above the function initialize gets the data from code.gs and display it in header. the

 my question is how can i pass the value in this line of code?

```<code><table cellspacing="0" cellpadding="3"  height ="100%" width ="60%" align = "center">
   <th>Item Code</th>
   <th>Product Name</th>
   <th>Main Description</th>
   <th>Other Description</th>

        <? for (var i = 2; i < data.length; i++) { ?>
        <tr>
        <? if(data[i][13] == "This is where I need to put the data") {?>
        <td><?= data[i][1] ?></td>
        <td><?= data[i][2] ?></td>
     <td><?= data[i][3] ?></td>
     <td><?= data[i][4] ?></td>
     <? }else{ ?>
     <?}?>
     <? } ?>

     </tr>
</table>
</code>```

this is my last problem and I dont know how to pass. the reason why im doing this is to use that value to create a table based on condition.

TYSM for help

答:
Change </p>

```<code><? if(data[i][13] == "This is where I need to put the data") {?>
</code>```

<p>to </p>

```<code><? if(data[i][13] == dataFromServerTemplate.first) {?>
</code>```

Body:
I have a code that looks like this.

code.gs

function doGet(e) {

  var t = HtmlService.createTemplateFromFile('Index');
  var matgrp = e.parameter.matgrp;
  t.dataFromServerTemplate = {first: matgrp};

  t.data = SpreadsheetApp
      .openById('1231455566776fgfgggggggg')
      .getActiveSheet()
      .getDataRange()
      .getValues();

  return t.evaluate();

}

Please focus on this part.

var matgrp = e.parameter.matgrp;
      t.dataFromServerTemplate = {first: matgrp};

and here is index.html

<!DOCTYPE html>

<base target="_top">

   Item Code
   Product Name
   Main Description
   Other Description

        <? for (var i = 2; i < data.length; i++) { ?>

        <? if(data[i][13] == "Wall Fan") {?>
        <?= data[i][1] ?>
        <?= data[i][2] ?>
     <?= data[i][3] ?>
     <?= data[i][4] ?>
     <? }else{ ?>
     <?}?>
     <? } ?>

as what you see on the code above the function initialize gets the data from code.gs and display it in header. the

 my question is how can i pass the value in this line of code?

   Item Code
   Product Name
   Main Description
   Other Description

        <? for (var i = 2; i < data.length; i++) { ?>

        <? if(data[i][13] == "This is where I need to put the data") {?>
        <?= data[i][1] ?>
        <?= data[i][2] ?>
     <?= data[i][3] ?>
     <?= data[i][4] ?>
     <? }else{ ?>
     <?}?>
     <? } ?>

this is my last problem and I dont know how to pass. the reason why im doing this is to use that value to create a table based on condition.

TYSM for help

Body:
Change

<? if(data[i][13] == "This is where I need to put the data") {?>

to

<? if(data[i][13] == dataFromServerTemplate.first) {?>