问:
Cropper is not a function
On my symfony project with webpack encore, I am using PrestaImageBundle https://github.com/prestaconcept/PrestaImageBundle , I have installed cropper, as stated in the documentation https://github.com/fengyuanchen/jquery-cropper#installation but when uploading the image I ended up with this error in my console :

cropper.js:158 Uncaught TypeError: this.$container.$preview.children(...).cropper is not a function
at Cropper../vendor/presta/image-bundle/Resources/public/js/cropper.js.Cropper.prepareCropping (cropper.js:158)
at FileReader.reader.onload (cropper.js:72)

There are no 404 error, only this one when uploading an image.

It should give me the option to crop the image to the desired size.

here are links and config used :

in base template :

```<code><script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</code>```

in twig config :

```<code>twig:
default_path: '%kernel.project_dir%/templates'
form_themes: ['bootstrap_4_layout.html.twig']
</code>```

in js file :

```<code>import 'jquery/dist/jquery.min';
import 'cropperjs/dist/cropper.min';
import 'jquery-cropper/dist/jquery-cropper.min.js';
import * as Cropper from '../../vendor/presta/image-bundle/Resources/public/js/cropper.js';
import '../css/form.scss';
</code>```

in css file :

```<code>@import "/../../node_modules/cropperjs/dist/cropper.min";
@import '../../vendor/presta/image-bundle/Resources/public/css/cropper.css';
</code>```

If any of you has an idea why I end up with this error, please let me know, We have read documentation several times and still don't understand why it doesn't work.

答: I solved the problem myself, the answer was in the webpack.config file : https://symfony.com/doc/current/frontend/encore/legacy-applications.html (you have to uncommented a line and wepack Encore will can read a jQuery plugin)</p>

Title: Cropper is not a function

Body:
On my symfony project with webpack encore, I am using PrestaImageBundle https://github.com/prestaconcept/PrestaImageBundle , I have installed cropper, as stated in the documentation https://github.com/fengyuanchen/jquery-cropper#installation but when uploading the image I ended up with this error in my console :

cropper.js:158 Uncaught TypeError: this.$container.$preview.children(...).cropper is not a function
at Cropper../vendor/presta/image-bundle/Resources/public/js/cropper.js.Cropper.prepareCropping (cropper.js:158)
at FileReader.reader.onload (cropper.js:72)

There are no 404 error, only this one when uploading an image.

It should give me the option to crop the image to the desired size.

here are links and config used :

in base template :

in twig config :

twig:
default_path: '%kernel.project_dir%/templates'
form_themes: ['bootstrap_4_layout.html.twig']

in js file :

import 'jquery/dist/jquery.min';
import 'cropperjs/dist/cropper.min';
import 'jquery-cropper/dist/jquery-cropper.min.js';
import * as Cropper from '../../vendor/presta/image-bundle/Resources/public/js/cropper.js';
import '../css/form.scss';

in css file :

@import "/../../node_modules/cropperjs/dist/cropper.min";
@import '../../vendor/presta/image-bundle/Resources/public/css/cropper.css';

If any of you has an idea why I end up with this error, please let me know, We have read documentation several times and still don't understand why it doesn't work.


来源: stackexchange

问:
How do I print out "id" in this array?
This question might have been asked earlier. I will appreciate an answer as well as a guide to previously asked questions if they exist.

```<code>array:3 [▼
"027c91341fd5cf4d2579b49c4b6a90da" => array:9 [▼
"rowId" => "027c91341fd5cf4d2579b49c4b6a90da"
"id" => "1"
"name" => "ks"
"qty" => "2"
"price" => 500.0
"options" => []
"tax" => "105.00"
"isSaved" => false
"subtotal" => "1000.00"
]
"370d08585360f5c568b18d1f2e4ca1df" => array:9 [▼
"rowId" => "370d08585360f5c568b18d1f2e4ca1df"
"id" => "2"
"name" => "clear glass"
"qty" => "2"
"price" => 500.0
"options" => []
"tax" => "105.00"
"isSaved" => false
"subtotal" => "1000.00"
]

"efb26e2c6ab6bd4d1323288923522d4e" => array:9 [▼
"rowId" => "efb26e2c6ab6bd4d1323288923522d4e"
"id" => "4"
"name" => "Double wall glass"
"qty" => 1
"price" => 34.0
"options" => []
"tax" => "7.14"
"isSaved" => false
"subtotal" => "34.00"
]
]
</code>```

How do I print id , name, qty...?

答:
Read about multidimensional array in the doc.
Here is a hint : </p>

```<code>foreach ($array as $key => $value) {
    echo $value['id'].'<br/>';
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How do I print out "id" in this array?

Body:
This question might have been asked earlier. I will appreciate an answer as well as a guide to previously asked questions if they exist.

array:3 [▼
"027c91341fd5cf4d2579b49c4b6a90da" => array:9 [▼
"rowId" => "027c91341fd5cf4d2579b49c4b6a90da"
"id" => "1"
"name" => "ks"
"qty" => "2"
"price" => 500.0
"options" => []
"tax" => "105.00"
"isSaved" => false
"subtotal" => "1000.00"
]
"370d08585360f5c568b18d1f2e4ca1df" => array:9 [▼
"rowId" => "370d08585360f5c568b18d1f2e4ca1df"
"id" => "2"
"name" => "clear glass"
"qty" => "2"
"price" => 500.0
"options" => []
"tax" => "105.00"
"isSaved" => false
"subtotal" => "1000.00"
]

"efb26e2c6ab6bd4d1323288923522d4e" => array:9 [▼
"rowId" => "efb26e2c6ab6bd4d1323288923522d4e"
"id" => "4"
"name" => "Double wall glass"
"qty" => 1
"price" => 34.0
"options" => []
"tax" => "7.14"
"isSaved" => false
"subtotal" => "34.00"
]
]

How do I print id , name, qty...?

Body:
Read about multidimensional array in the doc.
Here is a hint :

foreach ($array as $key => $value) {
    echo $value['id'].'<br/>';
}


问:
How can I modify all nodes in a DocumentFragment?
I am getting a DocumentFragment from a Range, which is from a Selection:

var foo = window.getSelection().getRangeAt(0).cloneContents()

How can I iteratively modify all nodes in the DocumentFragment?

How can I re-insert this DocumentFragment to overwrite the original Selection?

https://codepen.io/MichaelArnoldOwens/pen/wvMwzLY

答:
```<code>// i just used Selection to get a DocumenetFragment, but this can be applied to any DocumentFragment
var contents = window.getSelection().getRangeAt(0).extractContents()
// I generate a NodeList with querySelectorAll() and pass it the wildcard selector to get all the nodes
let list = contents.querySelectorAll('*')
// I instantiate a new DocumentFragment
let newFrag = new DocumentFragment()
// I iterate through the node list and make any modifications I want to each node before appending it to the new DocumentFragment
for (let i of list) {
  i.style.color = 'red'
  newFrag.appendChild(i)
}
// you can now append your new DocumentFragment to the DOM
...
</code>```


问:
How can I adjust DIV width to contents
I have a div element with style attached:

```<code>.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;
}
</code>```

I am diplaying WordPress post contents inside the DIV block but for simplicity let assume that there is only one  inside the DIV. I want my div to be minimum 700 px wide and adjust the width if image is wider than 700 px.

What are my options to achieve that? Please advice.

UPDATE

See my Fiddle
http://jsfiddle.net/cpt_comic/4qjXv/

答:
EDIT2- Yea auto fills the DOM SOZ!

```<code>#img_box{
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}
</code>```

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

```<code> min-height: 400px;
</code>```

ContentLicense: CC BY-SA 3.0

Title: How can I adjust DIV width to contents

Body:
I have a div element with style attached:

.mypost {
    border: 1px solid Peru;
    font-family: arial;
    margin: auto;
    min-width: 700px;
    width: 700px;
}

I am diplaying WordPress post contents inside the DIV block but for simplicity let assume that there is only one  inside the DIV. I want my div to be minimum 700 px wide and adjust the width if image is wider than 700 px.

What are my options to achieve that? Please advice.

UPDATE

See my Fiddle
http://jsfiddle.net/cpt_comic/4qjXv/

Body:
EDIT2- Yea auto fills the DOM SOZ!

#img_box{
    width:90%;
    height:90%;
    min-width: 400px;
    min-height: 400px;
}

check out this fiddle

http://jsfiddle.net/ppumkin/4qjXv/2/

http://jsfiddle.net/ppumkin/4qjXv/3/

and this page

http://www.webmasterworld.com/css/3828593.htm

Removed original answer because it was wrong.

The width is ok- but the height resets to 0

so

 min-height: 400px;


问:
Mark Duplicated Rows & Add Range Numbers for Duplicate Rows, Python 3.6
Data:

```<code>Data = pd.DataFrame([['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['3', '5', '2', '6'], ['10', '9', '8', '7'], ['5', '6', '7', '3'], ['10', '9', '8', '7']], columns=['F1', 'F2', 'F3', 'F4'])
</code>```

Marking Duplicate Rows:

```<code>Data['Is_Dup'] = Data[['F1', 'F2', 'F3', 'F4']].duplicated(keep=False).astype(int)
</code>```

Data:

Expected Results: I want to generate extra field called Dup_Ser, here range values needs to add for duplicate rows.

答:
Idea is sorting bay all columns with Is_Dup descending and then add new column with GroupBy.cumcount, added 1 and multiple by Data['Is_Dup'] for 0 for not duplicated values:

```<code>cols = ['F1', 'F2', 'F3', 'F4']
Data['Is_Dup'] = Data[cols].duplicated(keep=False).astype(int)

Data = Data.sort_values(['Is_Dup'] + cols, ascending=[False] + [True] * len(cols))
Data['Dup_Ser'] = Data.groupby(cols).cumcount().add(1).mul(Data['Is_Dup'])
print (Data)
   F1 F2 F3 F4  Is_Dup  Dup_Ser
0   1  2  3  4       1        1
2   1  2  3  4       1        2
4   1  2  3  4       1        3
6  10  9  8  7       1        1
8  10  9  8  7       1        2
1   4  3  2  1       1        1
3   4  3  2  1       1        2
5   3  5  2  6       0        0
7   5  6  7  3       0        0
</code>```

Body:
Data:

Data = pd.DataFrame([['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['4', '3', '2', '1'], ['1', '2', '3', '4'], ['3', '5', '2', '6'], ['10', '9', '8', '7'], ['5', '6', '7', '3'], ['10', '9', '8', '7']], columns=['F1', 'F2', 'F3', 'F4'])

Marking Duplicate Rows:

Data['Is_Dup'] = Data[['F1', 'F2', 'F3', 'F4']].duplicated(keep=False).astype(int)

Data:

Expected Results: I want to generate extra field called Dup_Ser, here range values needs to add for duplicate rows.

Body:
Idea is sorting bay all columns with Is_Dup descending and then add new column with GroupBy.cumcount, added 1 and multiple by Data['Is_Dup'] for 0 for not duplicated values:

cols = ['F1', 'F2', 'F3', 'F4']
Data['Is_Dup'] = Data[cols].duplicated(keep=False).astype(int)

Data = Data.sort_values(['Is_Dup'] + cols, ascending=[False] + [True] * len(cols))
Data['Dup_Ser'] = Data.groupby(cols).cumcount().add(1).mul(Data['Is_Dup'])
print (Data)
   F1 F2 F3 F4  Is_Dup  Dup_Ser
0   1  2  3  4       1        1
2   1  2  3  4       1        2
4   1  2  3  4       1        3
6  10  9  8  7       1        1
8  10  9  8  7       1        2
1   4  3  2  1       1        1
3   4  3  2  1       1        2
5   3  5  2  6       0        0
7   5  6  7  3       0        0


问:
Compare two version strings in Swift
I have two different app version Strings (i.e. "3.0.1" and "3.0.2").

How can compare these using Swift?

答:
Here is my effort to cover all cases of version formats like compare "10.0" with "10.0.1", let me know if I have missed any case.

Here is the gist https://gist.github.com/shamzahasan88/bc22af2b7c96b6a06a064243a02c8bcc. Hope it helps everyone.

And here is the code if anyone don't want to rate my gist :P

```<code>extension String {

  // Version format "12.34.39" where "12" is "Major", "34" is "Minor" and "39" is "Bug fixes"
  // "maximumDigitCountInVersionComponent" is optional parameter determines the maximum length of "Maajor", "Minor" and "Bug Fixes"
  func shouldUpdateAsCompareToVersion(storeVersion: String, maximumDigitCountInVersionComponent: Int = 5) -> Bool {
        let adjustTralingZeros: (String, Int)->String = { val, count in
            return "\(val)\((0..<(count)).map{_ in "0"}.joined(separator: ""))"
        }
        let adjustLength: ([String.SubSequence], Int)->[String] = { strArray, count in
            return strArray.map {adjustTralingZeros("\($0)", count-$0.count)}
        }
        let storeVersionSubSequence = storeVersion.split(separator: ".")
        let currentVersionSubSequence = self.split(separator: ".")
        let formatter = NumberFormatter()
        formatter.minimumIntegerDigits = maximumDigitCountInVersionComponent
        formatter.maximumIntegerDigits = maximumDigitCountInVersionComponent
        let storeVersions = adjustLength(storeVersionSubSequence, maximumDigitCountInVersionComponent)
        let currentVersions = adjustLength(currentVersionSubSequence, maximumDigitCountInVersionComponent)
        var storeVersionString = storeVersions.joined(separator: "")
        var currentVersionString = currentVersions.joined(separator: "")
        let diff = storeVersionString.count - currentVersionString.count

        if diff > 0 {
            currentVersionString = adjustTralingZeros(currentVersionString, diff)
        }else if diff < 0 {
            storeVersionString = adjustTralingZeros(storeVersionString, -diff)
        }
        let literalStoreVersion = Int(storeVersionString)!
        let literalCurrentVersion = Int(currentVersionString)!
        return literalCurrentVersion < literalStoreVersion
    }
}
</code>```

Usage:

```<code>print("33.29".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // true
print("35.29".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // false
print("34.23.2".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // false
print("34.23.18".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // true
</code>```

Title: Compare two version strings in Swift

Body:
Here is my effort to cover all cases of version formats like compare "10.0" with "10.0.1", let me know if I have missed any case.

Here is the gist https://gist.github.com/shamzahasan88/bc22af2b7c96b6a06a064243a02c8bcc. Hope it helps everyone.

And here is the code if anyone don't want to rate my gist :P

extension String {

  // Version format "12.34.39" where "12" is "Major", "34" is "Minor" and "39" is "Bug fixes"
  // "maximumDigitCountInVersionComponent" is optional parameter determines the maximum length of "Maajor", "Minor" and "Bug Fixes"
  func shouldUpdateAsCompareToVersion(storeVersion: String, maximumDigitCountInVersionComponent: Int = 5) -> Bool {
        let adjustTralingZeros: (String, Int)->String = { val, count in
            return "\(val)\((0..<(count)).map{_ in "0"}.joined(separator: ""))"
        }
        let adjustLength: ([String.SubSequence], Int)->[String] = { strArray, count in
            return strArray.map {adjustTralingZeros("\($0)", count-$0.count)}
        }
        let storeVersionSubSequence = storeVersion.split(separator: ".")
        let currentVersionSubSequence = self.split(separator: ".")
        let formatter = NumberFormatter()
        formatter.minimumIntegerDigits = maximumDigitCountInVersionComponent
        formatter.maximumIntegerDigits = maximumDigitCountInVersionComponent
        let storeVersions = adjustLength(storeVersionSubSequence, maximumDigitCountInVersionComponent)
        let currentVersions = adjustLength(currentVersionSubSequence, maximumDigitCountInVersionComponent)
        var storeVersionString = storeVersions.joined(separator: "")
        var currentVersionString = currentVersions.joined(separator: "")
        let diff = storeVersionString.count - currentVersionString.count

        if diff > 0 {
            currentVersionString = adjustTralingZeros(currentVersionString, diff)
        }else if diff < 0 {
            storeVersionString = adjustTralingZeros(storeVersionString, -diff)
        }
        let literalStoreVersion = Int(storeVersionString)!
        let literalCurrentVersion = Int(currentVersionString)!
        return literalCurrentVersion < literalStoreVersion
    }
}

Usage:

print("33.29".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // true
print("35.29".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // false
print("34.23.2".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // false
print("34.23.18".shouldUpdateAsCompareToVersion(storeVersion: "34.23.19")) // true


问:
How can I update the numberOfRowsInSection and how do I show all added values in this tableView?
I am trying to send values from one view controller - NewZoomAddressViewController to another one - Add_EditAddressViewController. I am sending the values to an array in the second view controller (addressArray).

Here is the first view controller:

```<code>class NewZoomAddressViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!
var addressArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    print("in Zoom map VC")
    mapView.delegate = self
    addressLabel.text = "\(self.sublocalityName!) \(localityName!) \(self.zipName!)"

}
@IBAction func confirmBtn(_ sender: Any) {
    let viewController = storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController
    addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    viewController.addressArray = addressArray
    navigationController?.pushViewController(viewController, animated: true)
}
}
</code>```

Then here I am adding values to addressArray from NewZoomAddressViewController like below:

```<code>class Add_EditAddressViewController: UIViewController,DataEnteredDelegate {
@IBOutlet var addressEDITTableview: UITableView!

  var addressArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    addressEDITTableview.register(UINib(nibName: "EditAddressTableViewCell", bundle: nil), forCellReuseIdentifier: "EditAddressTableViewCell")
    addressEDITTableview.reloadData()

}
}
extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return addressArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = addressArray[indexPath.row]//"\(city) \(pincode) \(locality)"

    return cell
}
}
</code>```

However, in the table view I am only getting one row. The first time, the single row is okay, but if I add another address - the row is replaced with the new address, and I am no longer getting the old address. How do I show all of the added addresses in the table view?

答:
addressArray gets deallocated everytime you move back to the screen. You should declare it in Add_EditAddressViewController and append the data there only then send it to otherviewcontroller

```<code>  var addressArray : [String] = []

  @IBAction func confirmBtn(_ sender: Any) {

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController;
    self.addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    vc.addressArray = self.addressArray
    self.navigationController?.pushViewController(viewController, animated: true);

}
</code>```

And then in your otherViewController

```<code>var addressArray : [String] = [] {
      didSet {
          self.addressEDITTableview.reloadData()
      }
 }
 override func viewDidLoad() {
    super.viewDidLoad()
  }

  extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return addressArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = addressArray[indexPath.row]
  return cell
 }
 }
</code>```

Body:
I am trying to send values from one view controller - NewZoomAddressViewController to another one - Add_EditAddressViewController. I am sending the values to an array in the second view controller (addressArray).

Here is the first view controller:

class NewZoomAddressViewController: UIViewController {

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!
var addressArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    print("in Zoom map VC")
    mapView.delegate = self
    addressLabel.text = "\(self.sublocalityName!) \(localityName!) \(self.zipName!)"

}
@IBAction func confirmBtn(_ sender: Any) {
    let viewController = storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController
    addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    viewController.addressArray = addressArray
    navigationController?.pushViewController(viewController, animated: true)
}
}

Then here I am adding values to addressArray from NewZoomAddressViewController like below:

class Add_EditAddressViewController: UIViewController,DataEnteredDelegate {
@IBOutlet var addressEDITTableview: UITableView!

  var addressArray = [String]()
override func viewDidLoad() {
    super.viewDidLoad()
    addressEDITTableview.register(UINib(nibName: "EditAddressTableViewCell", bundle: nil), forCellReuseIdentifier: "EditAddressTableViewCell")
    addressEDITTableview.reloadData()

}
}
extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return addressArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = addressArray[indexPath.row]//"\(city) \(pincode) \(locality)"

    return cell
}
}

However, in the table view I am only getting one row. The first time, the single row is okay, but if I add another address - the row is replaced with the new address, and I am no longer getting the old address. How do I show all of the added addresses in the table view?

Body:
addressArray gets deallocated everytime you move back to the screen. You should declare it in Add_EditAddressViewController and append the data there only then send it to otherviewcontroller

  var addressArray : [String] = []

  @IBAction func confirmBtn(_ sender: Any) {

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "Add_EditAddressViewController") as! Add_EditAddressViewController;
    self.addressArray.append("\(sublocalityName ?? "") \(zipName ?? "") \(localityName ?? "")")
    vc.addressArray = self.addressArray
    self.navigationController?.pushViewController(viewController, animated: true);

}

And then in your otherViewController

var addressArray : [String] = [] {
      didSet {
          self.addressEDITTableview.reloadData()
      }
 }
 override func viewDidLoad() {
    super.viewDidLoad()
  }

  extension Add_EditAddressViewController : UITableViewDelegate,UITableViewDataSource {

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return addressArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = addressArray[indexPath.row]
  return cell
 }
 }


问:
Count size-k connected components in an undirected graph
Given an undirected graph of size n. How to count how many size k connected components are there in the graph? Assume k<=n, and that the input graph is connected.

For example, given a graph of [(0,1), (1,2)]. It has 3 size 1 connected components, 2 size 2 connected components, and 1 size 3 connected components.

答: i think your problem is the exact same thing in here (this is about finding all connected subgraphs size k and the time complexity is n ^ k)</p>


问:
How to plot a single value with line in line chart graph using charts.js?
I need to plot a single value in line chart. Currently i am using charts.JS library for line graph purpose.

The data will be varied some times i'll get the single data inside the data set at that time i need to plot the single value with line in the line chart.

I tried with the charts.js annotation plugin but it wasn't met my requirements. which is like it wis overlapping the plotted point in the graph area.

CODE WHICH I HAD TRIED

```<code>createLineChart() {
   this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: "line",

      data: {
        labels:[],

        datasets: [
          {
            fill: false,

            backgroundColor: "#0168FF",
            borderColor: "#0168FF",
            pointBackgroundColor: "white", // wite point fill
            pointBorderWidth: 1, // point border width
            lineTension: 0,
            pointBorderColor: "blue",
            pointRadius: 4,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                padding: 20,
                beginAtZero: true,
                min: 0,

                stepSize: 100,
              },
              gridLines: {
                drawBorder: false,
              },
            },
          ],
          xAxes: [
            {
             // offset: true,
              ticks: {
                display: false,
               //beginAtZero: true,
               min: 0,

              },
              gridLines: {
                zeroLineColor: "transparent",
                drawBorder: false,
                display: false,
              },
              //offset:true,
            },
          ],
          legend: {
            display: false,
          },
          tooltips: {
            enabled: false,
          },
        },
          drawTime: "afterDraw", // (default)
        } as ChartOptions,
       // plugins: [ChartAnnotation]
      },
    });
  }
</code>```

To generate dynamic data and plot in the graph area.

```<code>generateRandomDataSet(size) {
    let yaxisArr = [];
    let xaxisArr = [];
    let random_data:any = this.getRandomData(size)
    let maxYTickVal = Math.max.apply(Math, random_data.map((val) => {return val.yaxis}));
    let maxVal = Math.ceil((maxYTickVal+1) / 10) * 10

    for(let data of random_data) {
      yaxisArr.push(data.yaxis)
      xaxisArr.push(data.xaxis)
    }

    console.log("X-Axis array values : "+xaxisArr)
    console.log("Y-Axis array values : "+yaxisArr)
    this.lineChart.data.datasets[0].data = yaxisArr
    this.lineChart.config.data.labels = []
    this.lineChart.config.data.labels = xaxisArr
    this.lineChart.config.options.scales.yAxes[0].ticks.max =maxVal
    this.lineChart.config.options.scales.yAxes[0].ticks.stepSize = maxVal/2

    this.lineChart.update()
  }

getRandomData(arraySize) {
  let data = []
  for(var i=1; i<=arraySize; i++) {
    let number = Math.floor(Math.random() * 200) + 1
    data.push({'xaxis':i,'yaxis':number})
  }
  return data
  }
</code>```

with the above code i am getting like

what i need to have

答:
You can define an animation.onComplete function as follows to draw the line in case a single data value is present.

```<code>animation: {
  onComplete: e => {
    var ctx = chart.chart.ctx;
    var data =  chart.config.data.datasets[0].data;
    if (data[0] == null) {
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      var y = yAxis.getPixelForValue(data[1]);
      ctx.save();
      ctx.globalCompositeOperation='destination-over';
      ctx.strokeStyle = 'blue'
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(xAxis.left, y);
      ctx.lineTo(xAxis.right, y);
      ctx.stroke();
      ctx.restore();
    }
  }
},
</code>```

This function expects the data array to be of format [null, <value>, null] in case a single value is present, otherwise it will be hard to horizontally center the data point (see this answer). It's up to you to change the generateRandomDataSet() function in a way that it provides such data.

Please have a look at your changed code below.

const chart = new Chart('line-chart', {
  type: "line",
  data: {
    labels: ['', 'A', ''],
    datasets: [{
      data: [null, 120, null],
      fill: false,
      backgroundColor: "#0168FF",
      borderColor: "#0168FF",
      pointBackgroundColor: "white",
      pointBorderWidth: 1,
      lineTension: 0,
      pointBorderColor: "blue",
      pointRadius: 4,
    }],
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    animation: {
      onComplete: e => {
        var ctx = chart.chart.ctx;
        var data =  chart.config.data.datasets[0].data;
        if (data[0] == null) {
          var xAxis = chart.scales['x-axis-0'];
          var yAxis = chart.scales['y-axis-0'];
          var y = yAxis.getPixelForValue(data[1]);
          ctx.save();
          ctx.globalCompositeOperation='destination-over';
          ctx.strokeStyle = 'blue'
          ctx.lineWidth = 2;
          ctx.beginPath();
          ctx.moveTo(xAxis.left, y);
          ctx.lineTo(xAxis.right, y);
          ctx.stroke();
          ctx.restore();
        }
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          padding: 20,
          min: 0,
          stepSize: 100
        },
        gridLines: {
          drawBorder: false
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          zeroLineColor: "transparent",
          drawBorder: false,
          display: false
        }
      }]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas></code>```

Body:
I need to plot a single value in line chart. Currently i am using charts.JS library for line graph purpose.

The data will be varied some times i'll get the single data inside the data set at that time i need to plot the single value with line in the line chart.

I tried with the charts.js annotation plugin but it wasn't met my requirements. which is like it wis overlapping the plotted point in the graph area.

CODE WHICH I HAD TRIED

createLineChart() {
   this.lineChart = new Chart(this.lineCanvas.nativeElement, {
      type: "line",

      data: {
        labels:[],

        datasets: [
          {
            fill: false,

            backgroundColor: "#0168FF",
            borderColor: "#0168FF",
            pointBackgroundColor: "white", // wite point fill
            pointBorderWidth: 1, // point border width
            lineTension: 0,
            pointBorderColor: "blue",
            pointRadius: 4,
          },
        ],
      },
      options: {
        scales: {
          yAxes: [
            {
              ticks: {
                padding: 20,
                beginAtZero: true,
                min: 0,

                stepSize: 100,
              },
              gridLines: {
                drawBorder: false,
              },
            },
          ],
          xAxes: [
            {
             // offset: true,
              ticks: {
                display: false,
               //beginAtZero: true,
               min: 0,

              },
              gridLines: {
                zeroLineColor: "transparent",
                drawBorder: false,
                display: false,
              },
              //offset:true,
            },
          ],
          legend: {
            display: false,
          },
          tooltips: {
            enabled: false,
          },
        },
          drawTime: "afterDraw", // (default)
        } as ChartOptions,
       // plugins: [ChartAnnotation]
      },
    });
  }

To generate dynamic data and plot in the graph area.

generateRandomDataSet(size) {
    let yaxisArr = [];
    let xaxisArr = [];
    let random_data:any = this.getRandomData(size)
    let maxYTickVal = Math.max.apply(Math, random_data.map((val) => {return val.yaxis}));
    let maxVal = Math.ceil((maxYTickVal+1) / 10) * 10

    for(let data of random_data) {
      yaxisArr.push(data.yaxis)
      xaxisArr.push(data.xaxis)
    }

    console.log("X-Axis array values : "+xaxisArr)
    console.log("Y-Axis array values : "+yaxisArr)
    this.lineChart.data.datasets[0].data = yaxisArr
    this.lineChart.config.data.labels = []
    this.lineChart.config.data.labels = xaxisArr
    this.lineChart.config.options.scales.yAxes[0].ticks.max =maxVal
    this.lineChart.config.options.scales.yAxes[0].ticks.stepSize = maxVal/2

    this.lineChart.update()
  }

getRandomData(arraySize) {
  let data = []
  for(var i=1; i<=arraySize; i++) {
    let number = Math.floor(Math.random() * 200) + 1
    data.push({'xaxis':i,'yaxis':number})
  }
  return data
  }

with the above code i am getting like

what i need to have

Body:
You can define an animation.onComplete function as follows to draw the line in case a single data value is present.

animation: {
  onComplete: e => {
    var ctx = chart.chart.ctx;
    var data =  chart.config.data.datasets[0].data;
    if (data[0] == null) {
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      var y = yAxis.getPixelForValue(data[1]);
      ctx.save();
      ctx.globalCompositeOperation='destination-over';
      ctx.strokeStyle = 'blue'
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(xAxis.left, y);
      ctx.lineTo(xAxis.right, y);
      ctx.stroke();
      ctx.restore();
    }
  }
},

This function expects the data array to be of format [null, <value>, null] in case a single value is present, otherwise it will be hard to horizontally center the data point (see this answer). It's up to you to change the generateRandomDataSet() function in a way that it provides such data.

Please have a look at your changed code below.

const chart = new Chart('line-chart', {
  type: "line",
  data: {
    labels: ['', 'A', ''],
    datasets: [{
      data: [null, 120, null],
      fill: false,
      backgroundColor: "#0168FF",
      borderColor: "#0168FF",
      pointBackgroundColor: "white",
      pointBorderWidth: 1,
      lineTension: 0,
      pointBorderColor: "blue",
      pointRadius: 4,
    }],
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      enabled: false
    },
    animation: {
      onComplete: e => {
        var ctx = chart.chart.ctx;
        var data =  chart.config.data.datasets[0].data;
        if (data[0] == null) {
          var xAxis = chart.scales['x-axis-0'];
          var yAxis = chart.scales['y-axis-0'];
          var y = yAxis.getPixelForValue(data[1]);
          ctx.save();
          ctx.globalCompositeOperation='destination-over';
          ctx.strokeStyle = 'blue'
          ctx.lineWidth = 2;
          ctx.beginPath();
          ctx.moveTo(xAxis.left, y);
          ctx.lineTo(xAxis.right, y);
          ctx.stroke();
          ctx.restore();
        }
      }
    },
    scales: {
      yAxes: [{
        ticks: {
          padding: 20,
          min: 0,
          stepSize: 100
        },
        gridLines: {
          drawBorder: false
        }
      }],
      xAxes: [{
        ticks: {
          display: false
        },
        gridLines: {
          zeroLineColor: "transparent",
          drawBorder: false,
          display: false
        }
      }]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="line-chart" height="80"></canvas>


问:
site not enabling ssl after auto configuration by Certbot
We have a static site code and want to have ssl enabled on it. This server has other few static sites running as well. Here is what I have in configurations

```<code>server {
  root /home/ubuntu/projects/example-beta/dist;
  index index.html index.htm index.nginx-debian.html;

  server_name  beta.example.com;

  location / {
    try_files $uri $uri/ =404;
  }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/beta.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/beta.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = beta.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

  server_name  beta.example.com;

    listen 80;
    return 404; # managed by Certbot

}
</code>```

But it doesnt pick ssl. I have replaced actual domain name with example. its been few days I have been trying different solutions. Sorry I am newbie in devOps. Any workaround or help is really appreciated

Edit

current configs

```<code>server {
  root /home/ubuntu/projects/savepakistan-beta/dist;
  index index.html index.htm index.nginx-debian.html;

  server_name  beta.wesavepakistan.com;

  location / {
    try_files $uri $uri/ =404;
  }

  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/beta.wesavepakistan.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/beta.wesavepakistan.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name beta.wesavepakistan.com;
  return 301 https://$host$request_uri;
}
</code>```

答:
To everyone visiting this question

Fix was: In UFW(if enabled), you have to enable FULL nginx and Ports(for HTTPs) in AWS EC2(in my case, yours can be different)

Body:
We have a static site code and want to have ssl enabled on it. This server has other few static sites running as well. Here is what I have in configurations

server {
  root /home/ubuntu/projects/example-beta/dist;
  index index.html index.htm index.nginx-debian.html;

  server_name  beta.example.com;

  location / {
    try_files $uri $uri/ =404;
  }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/beta.example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/beta.example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
    if ($host = beta.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

  server_name  beta.example.com;

    listen 80;
    return 404; # managed by Certbot

}

But it doesnt pick ssl. I have replaced actual domain name with example. its been few days I have been trying different solutions. Sorry I am newbie in devOps. Any workaround or help is really appreciated

Edit

current configs

server {
  root /home/ubuntu/projects/savepakistan-beta/dist;
  index index.html index.htm index.nginx-debian.html;

  server_name  beta.wesavepakistan.com;

  location / {
    try_files $uri $uri/ =404;
  }

  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/beta.wesavepakistan.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/beta.wesavepakistan.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name beta.wesavepakistan.com;
  return 301 https://$host$request_uri;
}


问:
how to upload file to S3 bucket using pre-signed url in angular or javascript
Can any one please provide example of how to upload to s3 bucket using presigned url.
I am able to generate pre singed url  but using PUT verb I am not able to upload to S3, giving below error:

Access to XMLHttpRequest at 'https://s3-bulk-files-upload.s3.ap-south-1.amazonaws.com/File1.txt?X-Amz-Expires=599&x-amz-security-token=IQoJb3JpZ2luX2VjEDAaCXVzLWVh....' from origin 'http://localhost:2020' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Thanks,
Raj4ms

答:
Solved this issue by generating presinged url from aws-sdk javascript and upload the file using PUT operation, signed URL and added headers as below                           headers: new HttpHeaders({
             'x-amz-server-side-encryption': 'aws:kms',
             'x-amz-server-side-encryption-aws-kms-key-id': 'arn:aws:kms:us-east-1:...'
        })

as S3 bucket is configured with KMS-encryption.


问:
Execute a BigQuery query in Cloud Build step
I'm using Cloud Build with the gcloud builder. I override the entrypoint to be bq so I can run some BigQuery SQL in my build step. Previously, I had the SQL embedded directly in the YAML config for Cloud Build. This works fine:

```<code>steps:
- name: gcr.io/cloud-builders/gcloud
  entrypoint: 'bq'
  args: ['query', '--use_legacy_sql=false', 'SELECT 1']
</code>```

Now I'd like to refactor the SQL out of the YAML and into a file instead. According to here, you can cat the file or pipe it to bq. This works on the command line without any problems.

But, I can't get it to work with Cloud Build. I've tried lots of different combinations, and escaping chars etc. but no matter what I try the shell doesn't evaluate/execute the cat my_query.sl backticks, and instead thinks that it's the query itself:

Works fine:

Build in Cloud Build it won't work:

```<code>steps:
- name: gcr.io/cloud-builders/gcloud
  entrypoint: 'bq'
  args: ['query', '--use_legacy_sql=false', '`cat my_query.sql`']
</code>```

I also tried piping it instead of using cat, but I get the same error.

I must be missing something obvious here, but I can't see it. I could build a custom docker image, and wrap everything in a shell script, but I'd rather not have to do that if possible.

How do you use Cloud Build with shell evaluation inside a build step?

答:
I have done this:

```<code>- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  dir: 'my/directory'
  args: ['-c', 'bq --project_id=my-project-name query --use_legacy_sql=false < ./my_query.sql']
</code>```

Which works with gcloud builds submit ... and eliminates one file if you prefer.

Body:
I'm using Cloud Build with the gcloud builder. I override the entrypoint to be bq so I can run some BigQuery SQL in my build step. Previously, I had the SQL embedded directly in the YAML config for Cloud Build. This works fine:

steps:
- name: gcr.io/cloud-builders/gcloud
  entrypoint: 'bq'
  args: ['query', '--use_legacy_sql=false', 'SELECT 1']

Now I'd like to refactor the SQL out of the YAML and into a file instead. According to here, you can cat the file or pipe it to bq. This works on the command line without any problems.

But, I can't get it to work with Cloud Build. I've tried lots of different combinations, and escaping chars etc. but no matter what I try the shell doesn't evaluate/execute the cat my_query.sl backticks, and instead thinks that it's the query itself:

Works fine:

Build in Cloud Build it won't work:

steps:
- name: gcr.io/cloud-builders/gcloud
  entrypoint: 'bq'
  args: ['query', '--use_legacy_sql=false', '`cat my_query.sql`']

I also tried piping it instead of using cat, but I get the same error.

I must be missing something obvious here, but I can't see it. I could build a custom docker image, and wrap everything in a shell script, but I'd rather not have to do that if possible.

How do you use Cloud Build with shell evaluation inside a build step?

Body:
I have done this:

- name: 'gcr.io/cloud-builders/gcloud'
  entrypoint: 'bash'
  dir: 'my/directory'
  args: ['-c', 'bq --project_id=my-project-name query --use_legacy_sql=false < ./my_query.sql']

Which works with gcloud builds submit ... and eliminates one file if you prefer.


问:
Redirecting to preferred language at site root
I'm working on a multilingual website in hugo using a multilingual-supported theme. I added the content in two languages and set the following two settings in the config file:

```<code>defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true
</code>```

I also specified the two languages as follows:

```<code>[languages]
  [languages.en]
    baseURL = "https://example.com/en"
    weight = 100
  [languages.nl]
    baseURL = "https://example.com/nl"
</code>```

When hugo generates the website, two directories are created as expected, one for each language. When I deploy the website, navigating to either of those urls send me to the website in the respective language. However, navigating to the base url example.com leads me nowhere because there is no html generated at that location.

I can implement this by bypassing hugo and manually adding an index.html at the site root:

```<code><!DOCTYPE html>
<html lang="en-us">
  <head>
   <script type="text/javascript">

      var languageCookie = getCookie("preferredLanguage")

      if (languageCookie) {
         var language = languageCookie
      } else {
         var language = navigator.language || navigator.userLanguage;
      }

      if (language == "nl") {
         window.location.href = "https://example.app/nl"
         document.cookie = "preferredLanguage=nl"
      }
      else {
         window.location.href = "https://example.app/en"
      }

      function getCookie(name) {
         const value = `; ${document.cookie}`;
         const parts = value.split(`; ${name}=`);
         if (parts.length === 2) return parts.pop().split(';').shift();
      }

   </script>
  </head>
</html>
</code>```

But I rather have hugo generate this html. How can I specify a seperate page/javascript, that is language independent? Or is there another place where I can call this javascript? Any help is appreciated

答:
Generating index.html

However, navigating to the base url example.com leads me nowhere because there is no html generated at that location.

It might have to do with the fact that you have the same baseURL for both languages; the config docs mention it's for the hostname. Indeed, I can't find anything obvious about it on the docs, but it seems like it's intended to be used for different domains altogether, rather than different paths on the same domain. If this is your use-case, then sorry, I don't know!

It might very well be a bug, but I didn't search for that either.

Out of the box

What should work, however, if you have just one domain, is

```<code>DefaultContentLanguage = "en"
defaultContentLanguageInSubdir = true

output= ["html"]

[languages]
  [languages.en]
    languageName = "English"
    contentDir = "content/en"
    weight = 10
  [languages.nl]
    languageName = "Nederlands"
    contentDir = "content/nl"
    weight = 20
</code>```

to result in a structure like this:

```<code>public
├── index.html
├── en
│   ├── index.html
│   ├── posts
│   │   └── index.html
│   ├── sitemap.xml
│   └── tags
│       └── index.html
├── nl
│   ├── index.html
│   ├── posts
│   │   └── index.html
│   ├── sitemap.xml
│   └── tags
│       └── index.html
└── sitemap.xml
</code>```

With the mention that the generated index.html already has the redirect made for you, and that's using a <meta> refresh tag redirecting to your default language.

This should solve your index.html issue, without having to create extra stuff.

Host-dependent

Depending on how you are hosting the site, you can check whether you can supply them your custom redirect rules, e.g. Netlify's _redirects file.

Language independent output

How can I specify a seperate page/javascript, that is language independent?

If you want custom code on that root index.html, then I don't know if you can have that, unfortunately. But, if you really want to, you can

Try the first suggestion, so you still have an index.html;

Just drop that js into your layout

Body:
I'm working on a multilingual website in hugo using a multilingual-supported theme. I added the content in two languages and set the following two settings in the config file:

defaultContentLanguage = "en"
defaultContentLanguageInSubdir = true

I also specified the two languages as follows:

[languages]
  [languages.en]
    baseURL = "https://example.com/en"
    weight = 100
  [languages.nl]
    baseURL = "https://example.com/nl"

When hugo generates the website, two directories are created as expected, one for each language. When I deploy the website, navigating to either of those urls send me to the website in the respective language. However, navigating to the base url example.com leads me nowhere because there is no html generated at that location.

I can implement this by bypassing hugo and manually adding an index.html at the site root:

<!DOCTYPE html>

But I rather have hugo generate this html. How can I specify a seperate page/javascript, that is language independent? Or is there another place where I can call this javascript? Any help is appreciated

Body:
Generating index.html

However, navigating to the base url example.com leads me nowhere because there is no html generated at that location.

It might have to do with the fact that you have the same baseURL for both languages; the config docs mention it's for the hostname. Indeed, I can't find anything obvious about it on the docs, but it seems like it's intended to be used for different domains altogether, rather than different paths on the same domain. If this is your use-case, then sorry, I don't know!

It might very well be a bug, but I didn't search for that either.

Out of the box

What should work, however, if you have just one domain, is

DefaultContentLanguage = "en"
defaultContentLanguageInSubdir = true

output= ["html"]

[languages]
  [languages.en]
    languageName = "English"
    contentDir = "content/en"
    weight = 10
  [languages.nl]
    languageName = "Nederlands"
    contentDir = "content/nl"
    weight = 20

to result in a structure like this:

public
├── index.html
├── en
│   ├── index.html
│   ├── posts
│   │   └── index.html
│   ├── sitemap.xml
│   └── tags
│       └── index.html
├── nl
│   ├── index.html
│   ├── posts
│   │   └── index.html
│   ├── sitemap.xml
│   └── tags
│       └── index.html
└── sitemap.xml

With the mention that the generated index.html already has the redirect made for you, and that's using a <meta> refresh tag redirecting to your default language.

This should solve your index.html issue, without having to create extra stuff.

Host-dependent

Depending on how you are hosting the site, you can check whether you can supply them your custom redirect rules, e.g. Netlify's _redirects file.

Language independent output

How can I specify a seperate page/javascript, that is language independent?

If you want custom code on that root index.html, then I don't know if you can have that, unfortunately. But, if you really want to, you can

Try the first suggestion, so you still have an index.html;

Just drop that js into your layout


问:
how to stop consuming messages from kafka when error occurred and restart consuming again after some time in spring boot
This is the first time i am using Kafka. i have a spring boot application and i am consuming messages from kafka topics and storing messages in DB. I have a requirement to handle DB fail over, if DB is down that message should not be committed and suspend consuming messages for some time and after some time listener can start consuming messages again. what is the better approach to do this.</p>

```<code> i am using spring-kafka:2.2.8.RELEASE which is internally using kafka 2.0.1
</code>```

答:
Configure a ContainerStoppingErrorHandler and throw an exception from your listener.

https://docs.spring.io/spring-kafka/docs/2.2.13.RELEASE/reference/html/#container-stopping-error-handlers

You can restart the container later when you have detected that your DB is back online.

https://docs.spring.io/spring-kafka/docs/2.2.13.RELEASE/reference/html/#kafkalistener-lifecycle

EDIT

@SpringBootApplication
public class So62125817Application {

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

    @Bean
    TaskScheduler scheduler() {
        return new ThreadPoolTaskScheduler();
    }

    @Bean
    public NewTopic topic() {
        return TopicBuilder.name("so62125817").partitions(1).replicas(1).build();
    }

}

@Component
class Listener {

    private final TaskScheduler scheduler;

    private final KafkaListenerEndpointRegistry registry;

    public Listener(TaskScheduler scheduler, KafkaListenerEndpointRegistry registry,
            AbstractKafkaListenerContainerFactory<?, ?, ?> factory) {

        this.scheduler = scheduler;
        this.registry = registry;
        factory.setErrorHandler(new ContainerStoppingErrorHandler());
    }

    @KafkaListener(id = "so62125817.id", topics = "so62125817")
    public void listen(String in) {
        System.out.println(in);
        // run this code if you want to stop the container and restart it in 60 seconds
        this.scheduler.schedule(() -> {
            this.registry.getListenerContainer("so62125817.id").start();
        }, new Date(System.currentTimeMillis() + 60_000));
        throw new RuntimeException("test restart");
    }

}
```

Body:
This is the first time i am using Kafka. i have a spring boot application and i am consuming messages from kafka topics and storing messages in DB. I have a requirement to handle DB fail over, if DB is down that message should not be committed and suspend consuming messages for some time and after some time listener can start consuming messages again. what is the better approach to do this.

 i am using spring-kafka:2.2.8.RELEASE which is internally using kafka 2.0.1


问:
,what is the use and benefit of Serialize() function in php
I know its Generates a storable representation of a value and  used to access the objects across the php files but what if i dont use this function while storing the objects.</p>

答:
To serialize means converting runtime variables into consistent form.
Often this is a simple string or XML representation of the code segment.

Usage:

```<code><?php

    $user = new UserObjectFromDatabase();
    $data = serialize($user);

    http_reqeust_send($to = "some remote server", $data);
    // the remote server can now use unserialize($data) to re-construct the user object

?>
</code>```

Body:
To serialize means converting runtime variables into consistent form.
Often this is a simple string or XML representation of the code segment.

Usage:

<?php

    $user = new UserObjectFromDatabase();
    $data = serialize($user);

    http_reqeust_send($to = "some remote server", $data);
    // the remote server can now use unserialize($data) to re-construct the user object

?>


问:
Define a value in JSR223 Assertion and Access it from User Defined Variables in a Different Thread
Simply this is what I want help with,

Using Jmeter -

Set a variable in the JSR223 Assertion in the 1st thread

Access that value in a different threads User Defined Variables

Thanks in advance

答:
You can use below method:

props.put("var","value");            // set property in 1st thread group

props.get("var");               // get property in 2nd thread group

Alternatively you can user "Inter-Thread Communication" plugins in JMeter.


问:
What is the difference between these two C++ statements to concatenate a string?
I'm new to C++ and I was wondering what the difference is between these two lines:

```<code>cout << "John " << "Doe" << endl;
cout << "John " + "Doe" << endl;
</code>```

The first one works but the second one doesn't. Any ideas?

答:
To concatenate two literal strings, just write one after the other with no intervening characters other than whitespace:

```<code>const char *lit = "John " "Doe";
std::cout << lit << '\n';
</code>```

or

```<code>std::cout << "John "

    "Doe";
</code>```

etc.

Body:
I'm new to C++ and I was wondering what the difference is between these two lines:

cout << "John " << "Doe" << endl;
cout << "John " + "Doe" << endl;

The first one works but the second one doesn't. Any ideas?

Body:
To concatenate two literal strings, just write one after the other with no intervening characters other than whitespace:

const char *lit = "John " "Doe";
std::cout << lit << '\n';

or

std::cout << "John "

    "Doe";

etc.


问:
"Syntax error on token "module", interface expected"
this bit of code gives me the error message: "Syntax error on token "module", interface expected. Does anyone know why?</p>

```<code>module TeaThiever{
}
</code>```

答:
The module statement is only valid in a module-info.java file and it must be used with Java 9 or above.

In Eclipse set the 'Compiler compliance level' on the project 'Java Compiler' properties page to be Java 9 or above (you also need to have a suitable Java installed).

Body:
this bit of code gives me the error message: "Syntax error on token "module", interface expected. Does anyone know why?

module TeaThiever{
}


问:
Export button is not visible with django-import-export package
I am trying to use django-import-export module in my admin and here are my settings

admin.py

```<code>from import_export.admin import ImportExportMixin, ImportMixin, ExportActionModelAdmin, ImportExportActionModelAdmin

class RegistrationAdmin(ImportExportActionModelAdmin):
    list_display = ('user', 'activation_key_expired')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name', 'user__last_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)
</code>```

With the above code, i can able to see an Import button in admin as below

But i can't able to see Export option, so what's the problem what am i missing here ?

I have seen some ticket about export button permission here
https://github.com/django-import-export/django-import-export/issues/38 ? can anyone please let me know what need to be done in order for Export to appear ?

By the way i am using django suit as my admin theme

答:
You need to use ImportExportModelAdmin

Eg:

```<code>from django.contrib import admin
from .models import Question, Choice
from import_export.admin import ImportExportModelAdmin

# Register your models here.

@admin.register(Question)
class ViewAdmin(ImportExportModelAdmin):
    pass

@admin.register(Choice)
class ViewAdmin(ImportExportModelAdmin):
    pass
</code>```

Body:
I am trying to use django-import-export module in my admin and here are my settings

admin.py

from import_export.admin import ImportExportMixin, ImportMixin, ExportActionModelAdmin, ImportExportActionModelAdmin

class RegistrationAdmin(ImportExportActionModelAdmin):
    list_display = ('user', 'activation_key_expired')
    raw_id_fields = ['user']
    search_fields = ('user__username', 'user__first_name', 'user__last_name')

admin.site.register(RegistrationProfile, RegistrationAdmin)

With the above code, i can able to see an Import button in admin as below

But i can't able to see Export option, so what's the problem what am i missing here ?

I have seen some ticket about export button permission here
https://github.com/django-import-export/django-import-export/issues/38 ? can anyone please let me know what need to be done in order for Export to appear ?

By the way i am using django suit as my admin theme

Body:
You need to use ImportExportModelAdmin

Eg:

from django.contrib import admin
from .models import Question, Choice
from import_export.admin import ImportExportModelAdmin

# Register your models here.

@admin.register(Question)
class ViewAdmin(ImportExportModelAdmin):
    pass

@admin.register(Choice)
class ViewAdmin(ImportExportModelAdmin):
    pass


问:
Firefox not recognizing a link registered by the vue eventhandler in older Firefox
I do have a following HTML code:

```<code><button id="btncontinue" ref="btncontinue" v-on:click="oncontinueclick" v-show="continuevisible">
<i class="fa fa-arrow-alt-circle-right fa-2x continue-icon"  v-show="continuevisible"></i>
</button>
</code>```

oncontinueclick fires registered method in the vue app. It works fine in the last browsers.
However, there is an odd problem with older browsers. I have to make it work for FF 45.9 and newer.
On FF 52 i experienced following problem - there are no script errors, but the button itself is not clickable (It's not even showing a hand cursor like on FF 7x, icon and the button are just the part of the background). It's like the eventhandler is not recognized, but in the inspector i see events attached, they even redirect to vue invoker, so it seems that FF has no problems with the scripts.

 element wasn't originally clickable, i just made it so for tests purposes. Is there any workaround? Or is this simply my error?

Vue version: 2.6.11 (but also 2.5.13)
There a bootstrap linked (without js)
and Axios (0.19.2)

答: Nevermind, the problem was with the z-order, nothing to do with scripts, just the older browser differently interpreted some css settings and the button was covered by the input.</p>

Body:
I do have a following HTML code:

<button id="btncontinue" ref="btncontinue" v-on:click="oncontinueclick" v-show="continuevisible">

</button>

oncontinueclick fires registered method in the vue app. It works fine in the last browsers.
However, there is an odd problem with older browsers. I have to make it work for FF 45.9 and newer.
On FF 52 i experienced following problem - there are no script errors, but the button itself is not clickable (It's not even showing a hand cursor like on FF 7x, icon and the button are just the part of the background). It's like the eventhandler is not recognized, but in the inspector i see events attached, they even redirect to vue invoker, so it seems that FF has no problems with the scripts.

 element wasn't originally clickable, i just made it so for tests purposes. Is there any workaround? Or is this simply my error?

Vue version: 2.6.11 (but also 2.5.13)
There a bootstrap linked (without js)
and Axios (0.19.2)


问:
invalid literal for int() with base 10: 'Last'
I am getting this error while executing Python code. The code runs perfectly until this print statement. What am I doing wrong?</p>

```<code>print("Category Loaded")

            # Find pagination if any
            lis=soup.select(".pagination li")
            if len(lis)>0:
                #get last page num
                last_page=int(lis[-1].get_text().strip())
                page_num=1
                # Loop to get all pages
                while True:
                    print("Loading Page : "+str(page_num))

</code>```

答:
You're attempting to convert a value into an integer using this line:

last_page=int(lis[-1].get_text().strip())
```

That isn't going to work if the value you're converting - the text of the last element in a list - doesn't consist solely of digits.

Your value is "Last", rather than anything that int() can work with, so you get the error. I would imagine that soup.select(".pagination li") returns, in addition to the numbers you want, "First", "Previous", "Next", and "Last". You need to do more cleaning on your list to just show the numbers.

Body:
I am getting this error while executing Python code. The code runs perfectly until this print statement. What am I doing wrong?

print("Category Loaded")

            # Find pagination if any
            lis=soup.select(".pagination li")
            if len(lis)>0:
                #get last page num
                last_page=int(lis[-1].get_text().strip())
                page_num=1
                # Loop to get all pages
                while True:
                    print("Loading Page : "+str(page_num))

Body:
You're attempting to convert a value into an integer using this line:

last_page=int(lis[-1].get_text().strip())

That isn't going to work if the value you're converting - the text of the last element in a list - doesn't consist solely of digits.

Your value is "Last", rather than anything that int() can work with, so you get the error. I would imagine that soup.select(".pagination li") returns, in addition to the numbers you want, "First", "Previous", "Next", and "Last". You need to do more cleaning on your list to just show the numbers.


问:
Issues with flask in Windows PowerShell
I use Windows PowerShell to install flask but when I execute python app.py I get this error

```<code>C:\Users\User\Desktop\flask\Deployed Model> python app.py
</code>```

Using TensorFlow backend.

  2020-06-01 12:36:45.548048: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2

  Model loaded. Start serving...

Can anyone help me with this error? I installed all the libraries in Windows PowerShell and I also installed tensorflow==2.0

答:
Since I cannot comment I'm writing this answer instead.
It seems like you don't have a GPU installed on your PC and if its true then you need to compile tensorflow binary for use.

This warning is specific to your CPU and it tells that your CPU dosen't support AVX2.

But if you have a GPU then simply disable the warning using

```<code>import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
</code>```

Title: Issues with flask in Windows PowerShell

Body:
I use Windows PowerShell to install flask but when I execute python app.py I get this error

C:\Users\User\Desktop\flask\Deployed Model> python app.py

Using TensorFlow backend.

  2020-06-01 12:36:45.548048: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2

  Model loaded. Start serving...

Can anyone help me with this error? I installed all the libraries in Windows PowerShell and I also installed tensorflow==2.0

Body:
Since I cannot comment I'm writing this answer instead.
It seems like you don't have a GPU installed on your PC and if its true then you need to compile tensorflow binary for use.

This warning is specific to your CPU and it tells that your CPU dosen't support AVX2.

But if you have a GPU then simply disable the warning using

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'


问:
Add values from a list to each unique ID code [SQL]
I have a list of product names (Book, Car, Table). My table currently looks like this:

What i would like my table to show is all 3 products for each JobID e.g.:

So essentially for each distinct JobID, there should be 3 products.

How can I do this in SQL? This is a sample dataset, i'm actually working with a much larger and complex dataset but I would like to understand how to do this with a simple dataset and adapt it to my larger dataset.

答:
*Edited the order by from ordinal positions to actual column names after @Eric's comment.    </p>

```<code>WITH products(  jobId ,productname )
 AS
 (
  SELECT 1200, 'Book' UNION
  SELECT 1400, 'Car' UNION
  SELECT 1600, 'Table'
 )

Select j.jobid, p.productname
from products j
cross join products p
order by j.jobid, p.productname

jobid   productname
1200    Book
1200    Car
1200    Table
1400    Book
1400    Car
1400    Table
1600    Book
1600    Car
1600    Table
</code>```

Body:
*Edited the order by from ordinal positions to actual column names after @Eric's comment.

WITH products(  jobId ,productname )
 AS
 (
  SELECT 1200, 'Book' UNION
  SELECT 1400, 'Car' UNION
  SELECT 1600, 'Table'
 )

Select j.jobid, p.productname
from products j
cross join products p
order by j.jobid, p.productname

jobid   productname
1200    Book
1200    Car
1200    Table
1400    Book
1400    Car
1400    Table
1600    Book
1600    Car
1600    Table


问:
Android Recycler Adapter position not working properly: onClick handling doesn't work properly
I have a recycler view where I fetch details from my database. An ArrayList of FriendEntity is given by the room database which works fine. I want to first have an unchecked box image for the whole list, and if I tap the image, it should change into a checked box image. But when I am achieving this, when I click on 1st item of recyclerView, my 16th item of recyclerView gets changed from unchecked to checked itself and the same goes with the 2nd and 17th, 3rd, and 18th and so on. I don't know if this is a problem with a recycler view adapter or something else.

Data Class FriendEntity :

     @Entity(tableName = "Friends")
     data class FriendEntity (
     @PrimaryKey val friend_name: String ,
     @ColumnInfo(name = "debt") val debt: Float )
```

<p>ExpenseActivity.xml for RecyclerView:</p>

<pre class="lang-xml prettyprint-override"><code>       <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
</code>```

ExpenseActivity.kt:

    class ExpenseActivity : AppCompatActivity() {
    private lateinit var binding: ActivityExpenseBinding
    private lateinit var layoutManager: LinearLayoutManager
    private lateinit var recyclerAdapter: FriendListAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this@ExpenseActivity,R.layout.activity_expense)
        layoutManager = LinearLayoutManager(this@ExpenseActivity)
        val friendsList = GetFriends(applicationContext).execute().get()
        binding.txtDef.visibility = if(friendsList.size==0) View.VISIBLE else View.GONE
        binding.recyclerList.visibility = if(friendsList.size!=0) View.VISIBLE else View.GONE
        recyclerAdapter = FriendListAdapter(this@ExpenseActivity,friendsList)
        binding.recyclerList.layoutManager = layoutManager
        binding.recyclerList.adapter = recyclerAdapter
     } }
```

<p>I have tested my GetFriends it works fine.</p>

<p>FriendListAdapter.kt:</p>

<pre class="lang-kotlin prettyprint-override"><code>    class FriendListAdapter(val context: Context, private val itemList: ArrayList<FriendEntity>):
    RecyclerView.Adapter<FriendListAdapter.FriendViewHolder>() {
    private var checkList: ArrayList<FriendEntity> = arrayListOf()

    class FriendViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val txtFriendName: TextView = view.findViewById(R.id.txtFriendName)
        val imgCheck: ImageView = view.findViewById(R.id.imgCheck)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendViewHolder {
        val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recycler_single_friend,parent,false)
        return FriendViewHolder(view)
    }
    override fun getItemCount() = itemList.size
    override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
        val itemObject = itemList[position]
        holder.txtFriendName.text = itemObject.friend_name
        holder.imgCheck.setOnClickListener {
            if(checkList.contains(itemObject)) {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
                checkList.remove(itemObject)
            } else {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
                checkList.add(itemObject)
            }
        }
     } }
</code>```

The problem I get is :

I tap on 1st element

The 16th automatically changes

I tap 2nd image

The 17th gets automatically clicked

Also, the behavior is so much problematic that when I tap on the 16th image, it doesn't respond.2nd time clicking makes it unchecked. Same with the 17th image. I guess there is some problem with the adapter.

Then I tried having a small view for individual items so that my screen gets a total of 20 items altogether. Now when I tap on the 1st image, the 24th gets selected, 2nd click changes the 25th. It means it clicks items who are not in the view right now but how?

I paste a GDriveLink for the video here if anyone doesn't understand it till now: Link to video of the problem

I want to know how to remove this error?

答:
the problem you are facing is due to the reuse of view holders. The simplest solution would be to create a boolean field in you POJO class FriendEntity .

```<code>data class FriendEntity (
@PrimaryKey val friend_name: String ,
@ColumnInfo(name = "debt") val debt: Float
val isSelected  //To store current status)
</code>```

Now check this status while binding your data and set the checkbox according to it.

```<code>override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
val itemObject = itemList[position]
//Image selection will be done at binding.
if(itemObject.isSelected){
  holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
}else{
  holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
}
holder.txtFriendName.text = itemObject.friend_name
holder.imgCheck.setOnClickListener {
   //Just change the status and notify the change.
    itemObject.isSelected = !itemObject.isSelected
    notifyItemChanged(position)
}
</code>```

Body:
I have a recycler view where I fetch details from my database. An ArrayList of FriendEntity is given by the room database which works fine. I want to first have an unchecked box image for the whole list, and if I tap the image, it should change into a checked box image. But when I am achieving this, when I click on 1st item of recyclerView, my 16th item of recyclerView gets changed from unchecked to checked itself and the same goes with the 2nd and 17th, 3rd, and 18th and so on. I don't know if this is a problem with a recycler view adapter or something else.

Data Class FriendEntity :

     @Entity(tableName = "Friends")
     data class FriendEntity (
     @PrimaryKey val friend_name: String ,
     @ColumnInfo(name = "debt") val debt: Float )

ExpenseActivity.xml for RecyclerView:

       <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerList"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>

ExpenseActivity.kt:

    class ExpenseActivity : AppCompatActivity() {
    private lateinit var binding: ActivityExpenseBinding
    private lateinit var layoutManager: LinearLayoutManager
    private lateinit var recyclerAdapter: FriendListAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this@ExpenseActivity,R.layout.activity_expense)
        layoutManager = LinearLayoutManager(this@ExpenseActivity)
        val friendsList = GetFriends(applicationContext).execute().get()
        binding.txtDef.visibility = if(friendsList.size==0) View.VISIBLE else View.GONE
        binding.recyclerList.visibility = if(friendsList.size!=0) View.VISIBLE else View.GONE
        recyclerAdapter = FriendListAdapter(this@ExpenseActivity,friendsList)
        binding.recyclerList.layoutManager = layoutManager
        binding.recyclerList.adapter = recyclerAdapter
     } }

I have tested my GetFriends it works fine.

FriendListAdapter.kt:

    class FriendListAdapter(val context: Context, private val itemList: ArrayList<FriendEntity>):
    RecyclerView.Adapter<FriendListAdapter.FriendViewHolder>() {
    private var checkList: ArrayList<FriendEntity> = arrayListOf()

    class FriendViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val txtFriendName: TextView = view.findViewById(R.id.txtFriendName)
        val imgCheck: ImageView = view.findViewById(R.id.imgCheck)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FriendViewHolder {
        val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.recycler_single_friend,parent,false)
        return FriendViewHolder(view)
    }
    override fun getItemCount() = itemList.size
    override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
        val itemObject = itemList[position]
        holder.txtFriendName.text = itemObject.friend_name
        holder.imgCheck.setOnClickListener {
            if(checkList.contains(itemObject)) {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
                checkList.remove(itemObject)
            } else {
                holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
                checkList.add(itemObject)
            }
        }
     } }

The problem I get is :

I tap on 1st element

The 16th automatically changes

I tap 2nd image

The 17th gets automatically clicked

Also, the behavior is so much problematic that when I tap on the 16th image, it doesn't respond.2nd time clicking makes it unchecked. Same with the 17th image. I guess there is some problem with the adapter.

Then I tried having a small view for individual items so that my screen gets a total of 20 items altogether. Now when I tap on the 1st image, the 24th gets selected, 2nd click changes the 25th. It means it clicks items who are not in the view right now but how?

I paste a GDriveLink for the video here if anyone doesn't understand it till now: Link to video of the problem

I want to know how to remove this error?

Body:
the problem you are facing is due to the reuse of view holders. The simplest solution would be to create a boolean field in you POJO class FriendEntity .

data class FriendEntity (
@PrimaryKey val friend_name: String ,
@ColumnInfo(name = "debt") val debt: Float
val isSelected  //To store current status)

Now check this status while binding your data and set the checkbox according to it.

override fun onBindViewHolder(holder: FriendViewHolder, position: Int) {
val itemObject = itemList[position]
//Image selection will be done at binding.
if(itemObject.isSelected){
  holder.imgCheck.setImageResource(R.drawable.ic_cb_full)
}else{
  holder.imgCheck.setImageResource(R.drawable.ic_cb_empty)
}
holder.txtFriendName.text = itemObject.friend_name
holder.imgCheck.setOnClickListener {
   //Just change the status and notify the change.
    itemObject.isSelected = !itemObject.isSelected
    notifyItemChanged(position)
}


问:
Changing the group of a model in Django Admin
For whatever reason I have three models related to authentication, but in Django Admin they show up in two different groups. For example:

```<code>AUTHORIZATION
-------------
Security Questions
Users

AUTHORIZATION AND AUTHENTICATION
--------------------------------
Groups
</code>```

Seems like they should be under one group and I would like to move them to be under one group.

I came across this Q/A from a few years ago:

Adding a model in Django Admin to the User/Group models?

Wonder if there is an easier way now in Django 1.11 like using a class Meta: in the model or in admin.py. Looking through the documentation and haven't come across anything yet.

答:
The simplest solution is to use the django-modeladmin-reorder: it allows you to reorder and merge apps in the admin site.

Here is the configuration that you'd need for this particular example:

ADMIN_REORDER = [
    {
        'app': 'auth',
        'models': [
            'my_custom_auth_app.User',
            'my_custom_auth_app.SecurityQuestions',
            'auth.Group',
        ]
    }
]
```

Behind the scenes, this app uses a middleware that changes the app_list context when rendering the admin templates.

Body:
For whatever reason I have three models related to authentication, but in Django Admin they show up in two different groups. For example:

AUTHORIZATION
-------------
Security Questions
Users

AUTHORIZATION AND AUTHENTICATION
--------------------------------
Groups

Seems like they should be under one group and I would like to move them to be under one group.

I came across this Q/A from a few years ago:

Adding a model in Django Admin to the User/Group models?

Wonder if there is an easier way now in Django 1.11 like using a class Meta: in the model or in admin.py. Looking through the documentation and haven't come across anything yet.

Body:
The simplest solution is to use the django-modeladmin-reorder: it allows you to reorder and merge apps in the admin site.

Here is the configuration that you'd need for this particular example:

ADMIN_REORDER = [
    {
        'app': 'auth',
        'models': [
            'my_custom_auth_app.User',
            'my_custom_auth_app.SecurityQuestions',
            'auth.Group',
        ]
    }
]

Behind the scenes, this app uses a middleware that changes the app_list context when rendering the admin templates.


问:
Whats the point of DOCTYPE?
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks </p>

<p>UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01? </p>

答:
The  declaration is not an XHTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.

The  declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers render the content correctly.

Title: Whats the point of DOCTYPE?

Body:
I know that different doctypes are essentially about how compliant the html is, but what difference does it make what doctype you specify? Do browsers handle the same code differently depending on the doctype?
Thanks

UPDATE - most answers mention quirks mode can be set off if no doctype is specified. But what would be the different between xhtml and html 4.01?


问:
Android Doze mode for motion sensors
I have question(s) related to Android Doze Mode (Android N [deep doze] and M). As per Android official documentation once device enters doze mode, it stops receiving location updates either via GPS or Network.

And to exit doze mode, either screen turns on or power plugged in. But how about

1) In doze mode if device is moved but screen remains off. Will device exit the doze mode for movement?

2) In Doze mode are sensors such as Gyro or accelerometer are they working or also stopped?

答:
Sure, device will leave the Doze mode. Because as written in Android Doze docs, device will be in Doze mode, only if it's stationary.

There are two type of sensors.

Wake-up sensor: ensure that their data is delivered independently of the state of the SoC.

Non-wake-up sensor: do not prevent the SoC from going into suspend mode and do not wake the SoC up to report data.

Accelerometer and Gyroscope are non-wake-up sensors, so they will be stopped. From Android Sensor Type page.

Title: Android Doze mode for motion sensors


问:
How can I solve the output error in flipping a coin?
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.

```<code>import random

tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
    for a in range(1, 101):
        heads = 0; tails = 0
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, coin_probability(n))) `
</code>```

I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:

```<code>1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...
</code>```

it should be printed like this.
(※I set heads to 0 and tails to 1.)

答:
I believe this is what you're looking for.</p>

```<code>import random

def coin_probability(n):
    tries = 0
    heads = 0
    for a in range(n):
        number = random.randint(0, 1)
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = 100*heads/tries
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5f%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = 100*heads/tries
            if tries%10 == 0:
               print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5f%%" %(tries, cp))
    return cp
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
p = coin_probability(n)
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, p))
</code>```

Body:
I am writing code about the probability of flipping a coin as follows, but I keep getting errors.

import random

tries = 0
number = random.randint(0, 1)
def coin_probability(hehe):
    for a in range(1, 101):
        heads = 0; tails = 0
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = heads/n
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5d%%" %(tries, cp))
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, coin_probability(n))) `

I want the probability to come out one by one from 1 to 10, and display 10 units from 11 to 100. For example:

1 번째까지~: (probability)%
2 번째까지~: (probability)%
3 번째까지~: (probability)%
...
10 번째까지~: (probability)%
20 번째까지~: (probability)%
...

it should be printed like this.
(※I set heads to 0 and tails to 1.)

Body:
I believe this is what you're looking for.

import random

def coin_probability(n):
    tries = 0
    heads = 0
    for a in range(n):
        number = random.randint(0, 1)
        tries += 1
        if tries <= 10:
            if number == 0:
                heads += 1
            cp = 100*heads/tries
            print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5f%%" %(tries, cp))
        else:
            if number == 0:
                heads += 1
            cp = 100*heads/tries
            if tries%10 == 0:
               print("%4d 번째까지 던지기에서 앞면이 나온 확률 :%5f%%" %(tries, cp))
    return cp
n = int(input("동전 던지기 시도 횟수를 입력(1 - 100) : "))
print('*' * 47)
p = coin_probability(n)
print('*' * 47)
print('총 %d번 동전 던지기에서 앞면이 나올 확률 :  %s' %(n, p))


问:
Show form validation errors using laravel and ajax
I need to output the validation errors in case if the validation fails.
But the errors are not being displayed.
I have used Laravel for the server side and ajax for sending the HTTP request.

FORM

```<code><form action="#" method="POST" id="frmcontactuspage" class="contact-form">
            {{ csrf_field() }}
            <div class="form-row">
                <label for="">@lang('language.name') *</label>
                <input id="name" type="text" name="name">
                  <span class="text-danger" id="name-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.address') *</label>
                <input id="address" type="text" name="address">
                <span class="text-danger" id="address-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.phone') *</label>
                <input id="phoneno" type="text" name="phoneno">
                   <span class="text-danger" id="phone-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.email') *</label>
                <input id="email" type="email" name="email">
                <span class="text-danger" id="email-error"></span>
            </div>

            <div class="form-row">
                <label for="">@lang('language.subject') *</label>
                <input id="metitle" type="text" name="subject">
                    <span class="text-danger" id="subject-error"></span>
            </div>
            <div class="form-row">
                <label for="">@lang('language.message') *</label>
                <textarea name="message" id="message" rows="3"></textarea>

            </div>
            <div class="form-row-s">
                 <button type="button" class="submit s-btn-a" id="btncontactuspage">@lang('language.submit')</button>
                </button>
            </div>

        </form>
</code>```

CONTROLLER

```<code>public function insertfeedback(Request $request){
        $validator = Validator::make($request->all(), [
            'name'              => 'required|min:2',
            'email'             => 'required|email',
            'phoneno'           => 'required',
            'address'           => 'required|min:5',
            'message'           => 'required|min:10',
        ]);

    if ($validator->passes()) {
        $contact = new AdminContact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->address = $request->address;
        $contact->phoneno = $request->phoneno;
        $contact->message = $request->message;
        $contact->inserted_date = date('Y-m-d H:i:s');

        $contact->save();

         $message = "We've received your feedback. Thank You !!!";

        return response()->json(['error' => false, 'message' => $message]);
    }
else{
    return response()->json(['error' => true,'errors' => $validator->errors()]);
}
}
</code>```

AJAX

```<code>$('#btncontactuspage').click(function(event) {
    var formdata = $("#frmcontactuspage").serialize();
    $("#name-error").html("");
    $("#email-error").html("");
    $("#phoneno-error").html("");
    $("#address-error").html("");
    $("#message-error").html("");
    $("#statuspage-msg").html("");
    $.ajax({
        url: baseurl+'/'+locale+'/insertfeedback',
        type: "POST",
        data: formdata
    }).always(function(resp) {
        console.log(resp)
        if(resp.error=='true'){
            if(resp.errors.branch_id){
              $('#branch_id-error').html(resp.errors.branch_id[0]);
            }
            if(resp.errors.name){
              $('#name-error').html(resp.errors.name[0]);
            }
            if(resp.errors.email){
              $('#email-error').html(resp.errors.email[0]);
            }
            if(resp.errors.phoneno){
              $('#phoneno-error').html(resp.errors.phoneno[0]);
            }
            if(resp.errors.address){
              $('#address-error').html(resp.errors.address[0]);
            }
            if(resp.errors.message){
              $('#message-error').html(resp.errors.message[0]);
            }
        }
        if(resp.error=='false'){
            $("#frmcontactuspage")[0].reset();
            $("#statuspage-msg").removeClass('d-none');
            $("#statuspage-msg").html(resp.message);
        }
    });
</code>```

});

Whats the issue here?
Why is the validation not being displayed? Is there any problem in the ajax code?
I am not being able to sort it out.
help

答:
Try your code as below. use ->fails() method to check validation failed.

```<code>if ($validator->fails()) {
    $arr = response()->json(['error' => true,'errors' => $validator->errors()->first()]);
} else {
    $contact = new AdminContact;
    ...
    ...
}
</code>```

Body:
I need to output the validation errors in case if the validation fails.
But the errors are not being displayed.
I have used Laravel for the server side and ajax for sending the HTTP request.

FORM

<form action="#" method="POST" id="frmcontactuspage" class="contact-form">
            {{ csrf_field() }}

                @lang('language.name') *
                <input id="name" type="text" name="name">

                @lang('language.address') *
                <input id="address" type="text" name="address">

                @lang('language.phone') *
                <input id="phoneno" type="text" name="phoneno">

                @lang('language.email') *
                <input id="email" type="email" name="email">

                @lang('language.subject') *
                <input id="metitle" type="text" name="subject">

                @lang('language.message') *
                <textarea name="message" id="message" rows="3"></textarea>

                 <button type="button" class="submit s-btn-a" id="btncontactuspage">@lang('language.submit')</button>
                </button>

        </form>

CONTROLLER

public function insertfeedback(Request $request){
        $validator = Validator::make($request->all(), [
            'name'              => 'required|min:2',
            'email'             => 'required|email',
            'phoneno'           => 'required',
            'address'           => 'required|min:5',
            'message'           => 'required|min:10',
        ]);

    if ($validator->passes()) {
        $contact = new AdminContact;
        $contact->name = $request->name;
        $contact->email = $request->email;
        $contact->address = $request->address;
        $contact->phoneno = $request->phoneno;
        $contact->message = $request->message;
        $contact->inserted_date = date('Y-m-d H:i:s');

        $contact->save();

         $message = "We've received your feedback. Thank You !!!";

        return response()->json(['error' => false, 'message' => $message]);
    }
else{
    return response()->json(['error' => true,'errors' => $validator->errors()]);
}
}

AJAX

$('#btncontactuspage').click(function(event) {
    var formdata = $("#frmcontactuspage").serialize();
    $("#name-error").html("");
    $("#email-error").html("");
    $("#phoneno-error").html("");
    $("#address-error").html("");
    $("#message-error").html("");
    $("#statuspage-msg").html("");
    $.ajax({
        url: baseurl+'/'+locale+'/insertfeedback',
        type: "POST",
        data: formdata
    }).always(function(resp) {
        console.log(resp)
        if(resp.error=='true'){
            if(resp.errors.branch_id){
              $('#branch_id-error').html(resp.errors.branch_id[0]);
            }
            if(resp.errors.name){
              $('#name-error').html(resp.errors.name[0]);
            }
            if(resp.errors.email){
              $('#email-error').html(resp.errors.email[0]);
            }
            if(resp.errors.phoneno){
              $('#phoneno-error').html(resp.errors.phoneno[0]);
            }
            if(resp.errors.address){
              $('#address-error').html(resp.errors.address[0]);
            }
            if(resp.errors.message){
              $('#message-error').html(resp.errors.message[0]);
            }
        }
        if(resp.error=='false'){
            $("#frmcontactuspage")[0].reset();
            $("#statuspage-msg").removeClass('d-none');
            $("#statuspage-msg").html(resp.message);
        }
    });

});

Whats the issue here?
Why is the validation not being displayed? Is there any problem in the ajax code?
I am not being able to sort it out.
help

Body:
Try your code as below. use ->fails() method to check validation failed.

if ($validator->fails()) {
    $arr = response()->json(['error' => true,'errors' => $validator->errors()->first()]);
} else {
    $contact = new AdminContact;
    ...
    ...
}