问:
How to fix 'tableview cellforrowat not called?'
I'm setting up a tableview with customtableview cell, but when i run the app, the data is not shown.

I already check all the connection, identifier, class name, etc

import UIKit

class ViewController: UITableViewController {
    @IBOutlet var testingTableView: UITableView!
    var data = ["Indomie","Kacang Tanah","Soya"]
    override func viewDidLoad() {
        super.viewDidLoad()

        testingTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = testingTableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customTableViewCell
        cell.customLabel.text = data[indexPath.row]
        return cell
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
}
```

This is my code for the table view, it's should call the cellforrowat but it's not

答:
You are missing tableView(_:numberOfRowsInSection:) implementation.

You have number of data.count section, but each section has 0 row.

Try replacing numberOfSections(in:) to tableView(_:numberOfRowsInSection:)

Body:
I'm setting up a tableview with customtableview cell, but when i run the app, the data is not shown.

I already check all the connection, identifier, class name, etc

import UIKit

class ViewController: UITableViewController {
    @IBOutlet var testingTableView: UITableView!
    var data = ["Indomie","Kacang Tanah","Soya"]
    override func viewDidLoad() {
        super.viewDidLoad()

        testingTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = testingTableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customTableViewCell
        cell.customLabel.text = data[indexPath.row]
        return cell
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
}

This is my code for the table view, it's should call the cellforrowat but it's not


来源: stackexchange

问:
how to access all images from facebook in swift 5?
I am trying to access all the images form facebook that user uploaded
I try it with user_photos

https://developers.facebook.com/docs/facebook-login/permissions/#reference-user_photos

I also try graph API explore from this
iOS :How to get Facebook Album Photo's Picker

my code

for Login

```<code>  func btnFbClicked()
        {
        fbLoginManager.logOut()
        fbLoginManager.loginBehavior = .web
        fbLoginManager.logIn(withReadPermissions: ["public_profile", "email", "user_friends","user_photos"], from: self) { (result, error) in

        if error != nil
        {
        print("error occured with login \(String(describing: error?.localizedDescription))")
        }

        else if (result?.isCancelled)!
        {
        print("login canceled")
        }

        else
        {
        if FBSDKAccessToken.current() != nil
        {

        FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"id, name, first_name, last_name, picture.type(normal), email,gender"]).start(completionHandler: { (connection, userResult, error) in

        if error != nil {

        print("error occured \(String(describing: error?.localizedDescription))")
        }
        else if userResult != nil {
        print("Login with FB is success")
        print(userResult as! [String:Any])

        self.fbData = (userResult as? NSDictionary)!

        let mutableFBDict = NSMutableDictionary(dictionary: self.fbData)
        print(mutableFBDict)

        if((mutableFBDict["email"] as? String) ?? "") == ""{

    //    self.showAlertNoHide(title: "", message: "If permission is granted then please set any email as a primary email in facebook general settings, then only facebook will return email to third party application. Sorry for the inconvenience.")

        return
        }

        var gender = Int64()
        if(mutableFBDict["gender"] as? String == "male")
        {
        gender = Int64(1)
        }
        else  if(mutableFBDict["gender"] as? String == "female")
        {
        gender = Int64(2)
        }
        else
        {
        gender = Int64(0)
        }

        self.fetchListOfUserPhotos()
}
</code>```

for fetching Photos

```<code>func fetchListOfUserPhotos()
    {
        guard let id  = self.fbData["id"] as? String else
        {
            return
        }
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: id + "/photos" , parameters: ["fields":"user_photos"], httpMethod: "GET")

        //FBSDKGraphRequest(graphPath: id + "/photos" , parameters: nil, httpMethod: "GET")

        graphRequest.start(completionHandler: { (connection, result, error) -> Void in

            if ((error) != nil)
            {
                // Process error
                print("Error: \(error)")
            }
            else
            {
                print("fetched user: \(result)")

                let fbResult:[String:AnyObject] = result as! [String : AnyObject]

                self.userPhotos = fbResult["data"] as! NSArray?

                self.myCollectionView.reloadData()

            }
        })
    }
</code>```

Respons I get

```<code>Optional({
    data =     (
    );
})
</code>```

so my question is can access images that user uploaded on facebook or facebook change policies?

答:
```<code>"fields":"user_photos"
</code>```

user_photos is a permission, not a field for API requests. About the existing fields for photos, check out the API reference: https://developers.facebook.com/docs/graph-api/reference/photo/

If you don´t get any photos, debug your Access Token and make sure it really is a User Token that includes the user_photos permission: https://developers.facebook.com/tools/debug/accesstoken/

ContentLicense: CC BY-SA 4.0

Body:
I am trying to access all the images form facebook that user uploaded
I try it with user_photos

https://developers.facebook.com/docs/facebook-login/permissions/#reference-user_photos

I also try graph API explore from this
iOS :How to get Facebook Album Photo's Picker

my code

for Login

  func btnFbClicked()
        {
        fbLoginManager.logOut()
        fbLoginManager.loginBehavior = .web
        fbLoginManager.logIn(withReadPermissions: ["public_profile", "email", "user_friends","user_photos"], from: self) { (result, error) in

        if error != nil
        {
        print("error occured with login \(String(describing: error?.localizedDescription))")
        }

        else if (result?.isCancelled)!
        {
        print("login canceled")
        }

        else
        {
        if FBSDKAccessToken.current() != nil
        {

        FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"id, name, first_name, last_name, picture.type(normal), email,gender"]).start(completionHandler: { (connection, userResult, error) in

        if error != nil {

        print("error occured \(String(describing: error?.localizedDescription))")
        }
        else if userResult != nil {
        print("Login with FB is success")
        print(userResult as! [String:Any])

        self.fbData = (userResult as? NSDictionary)!

        let mutableFBDict = NSMutableDictionary(dictionary: self.fbData)
        print(mutableFBDict)

        if((mutableFBDict["email"] as? String) ?? "") == ""{

    //    self.showAlertNoHide(title: "", message: "If permission is granted then please set any email as a primary email in facebook general settings, then only facebook will return email to third party application. Sorry for the inconvenience.")

        return
        }

        var gender = Int64()
        if(mutableFBDict["gender"] as? String == "male")
        {
        gender = Int64(1)
        }
        else  if(mutableFBDict["gender"] as? String == "female")
        {
        gender = Int64(2)
        }
        else
        {
        gender = Int64(0)
        }

        self.fetchListOfUserPhotos()
}

for fetching Photos

func fetchListOfUserPhotos()
    {
        guard let id  = self.fbData["id"] as? String else
        {
            return
        }
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: id + "/photos" , parameters: ["fields":"user_photos"], httpMethod: "GET")

        //FBSDKGraphRequest(graphPath: id + "/photos" , parameters: nil, httpMethod: "GET")

        graphRequest.start(completionHandler: { (connection, result, error) -> Void in

            if ((error) != nil)
            {
                // Process error
                print("Error: \(error)")
            }
            else
            {
                print("fetched user: \(result)")

                let fbResult:[String:AnyObject] = result as! [String : AnyObject]

                self.userPhotos = fbResult["data"] as! NSArray?

                self.myCollectionView.reloadData()

            }
        })
    }

Respons I get

Optional({
    data =     (
    );
})

so my question is can access images that user uploaded on facebook or facebook change policies?

Body:
"fields":"user_photos"

user_photos is a permission, not a field for API requests. About the existing fields for photos, check out the API reference: https://developers.facebook.com/docs/graph-api/reference/photo/

If you don´t get any photos, debug your Access Token and make sure it really is a User Token that includes the user_photos permission: https://developers.facebook.com/tools/debug/accesstoken/


问:
JS Promise doesn't chain while working chrome.storage.sync
I'm trying to make a promise chaining, but somehow the asynchronous calling using chrome.storage.sync.get always return later. Here's a correct order I thought it should be:

Create an element and append to body

Call chrome.storage.sync

Based on 2) result, trigger some event on element created in 1)

I've already tried to put new Promise in 2) step, but no successful.
The console.log always return in a wrong order. Something like:

// insertChecbox done

// start promise chrome.storage.sync

// undefined

// result asnyc: ...

Here's my attempt:

```<code>const pr = new Promise(resolve => {
  this.createCheckbox();
  console.log('insertChecbox done')
  resolve();
});

pr
  .then( resolve => {
    console.log("start promise chrome.storage.sync");

    return new Promise( resolve => {
      return resolve(chrome.storage.sync.get(["code", "isAutocheck"], result => {
        console.log('result async: ', result );
        return result
      }));
    });
  })
  .then( result => {
    console.log(result);
    console.log('This always run before the `chrome.storage.sync` finishes loading`)
    if (result.isAutocheck) {
      const domCheckbox = this.getCheckboxElement();
      domCheckbox && domCheckbox.click();
    }
  });
</code>```

I wanted to separate the result of chrome.storage.sync because I need to  work on other stuff, not making this callback too complex

答:
Thanks for noticing this question, I've found an solution by changing a bit in my first .then, by explicitly resolving the result of chrome.storage.sync.get, not the whole thing.

```<code>pr
  .then( () => {
    return new Promise( resolve => {
      return chrome.storage.sync.get(["code", "isAutocheck"], result => {
        console.log('result async: ', result );
        return resolve(result)
      });
    });
  })
  .then(...);
</code>```

Body:
I'm trying to make a promise chaining, but somehow the asynchronous calling using chrome.storage.sync.get always return later. Here's a correct order I thought it should be:

Create an element and append to body

Call chrome.storage.sync

Based on 2) result, trigger some event on element created in 1)

I've already tried to put new Promise in 2) step, but no successful.
The console.log always return in a wrong order. Something like:

// insertChecbox done

// start promise chrome.storage.sync

// undefined

// result asnyc: ...

Here's my attempt:

const pr = new Promise(resolve => {
  this.createCheckbox();
  console.log('insertChecbox done')
  resolve();
});

pr
  .then( resolve => {
    console.log("start promise chrome.storage.sync");

    return new Promise( resolve => {
      return resolve(chrome.storage.sync.get(["code", "isAutocheck"], result => {
        console.log('result async: ', result );
        return result
      }));
    });
  })
  .then( result => {
    console.log(result);
    console.log('This always run before the `chrome.storage.sync` finishes loading`)
    if (result.isAutocheck) {
      const domCheckbox = this.getCheckboxElement();
      domCheckbox && domCheckbox.click();
    }
  });

I wanted to separate the result of chrome.storage.sync because I need to  work on other stuff, not making this callback too complex

Body:
Thanks for noticing this question, I've found an solution by changing a bit in my first .then, by explicitly resolving the result of chrome.storage.sync.get, not the whole thing.

pr
  .then( () => {
    return new Promise( resolve => {
      return chrome.storage.sync.get(["code", "isAutocheck"], result => {
        console.log('result async: ', result );
        return resolve(result)
      });
    });
  })
  .then(...);


答:
1). Add this line

```<code> @IBOutlet var testingTableView: UITableView! {
        didSet {
                  testingTableView.delegate = self
                  testingTableView.dataSource = self
              }
  }
</code>```

2). You also can add this feature via Stroyboard. Click on your table and using right click drag the pointer on ViewController and add delegate and dataSource.

And i think you missed

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 0 //As per your need.
}
</code>```

Title: How to fix 'tableview cellforrowat not called?'

Body:
1). Add this line

 @IBOutlet var testingTableView: UITableView! {
        didSet {
                  testingTableView.delegate = self
                  testingTableView.dataSource = self
              }
  }

2). You also can add this feature via Stroyboard. Click on your table and using right click drag the pointer on ViewController and add delegate and dataSource.

And i think you missed

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 0 //As per your need.
}


问:
Problem displaying components of JList
I am trying to dsiplay the twitter timeline in a Jlist component. I have already fixed the size of my frame and the cell height and cell width of the JList too with the following code.

```<code>jlist.setFixedCellHeight(50);
jlist.setFixedCellWidth(70);
</code>```

I find that the height and width of each cell are fine but if the content of the tweet inside the cell exceeds the width it is not displaying the further part of the tweet.

For example: Assume that 70 width exactly fits the tweet "I am good"

Suppose if the tweet is "I am good and great" The tweet is getting displayed as "I am good....." The exceeded part of the tweet is not getting displayed.

What I want to do here is, I want the rest out part of the tweet to be displayed below the line as I do have sufficient height to display the tweet in a second line. In the same example, within the cell, I want the content to be displayed as

"I am good

and great"

How can I achieve this?

答:
quoting from the JList java doc

JList doesn't implement scrolling
directly. To create a list that
scrolls, make it the viewport view of
a JScrollPane. For example:

JScrollPane scrollPane = new
JScrollPane(myList);

// Or in two steps:  JScrollPane
scrollPane = new JScrollPane();
scrollPane.getViewport().setView(myList);

ContentLicense: CC BY-SA 3.0

Title: Problem displaying components of JList

Body:
I am trying to dsiplay the twitter timeline in a Jlist component. I have already fixed the size of my frame and the cell height and cell width of the JList too with the following code.

jlist.setFixedCellHeight(50);
jlist.setFixedCellWidth(70);

I find that the height and width of each cell are fine but if the content of the tweet inside the cell exceeds the width it is not displaying the further part of the tweet.

For example: Assume that 70 width exactly fits the tweet "I am good"

Suppose if the tweet is "I am good and great" The tweet is getting displayed as "I am good....." The exceeded part of the tweet is not getting displayed.

What I want to do here is, I want the rest out part of the tweet to be displayed below the line as I do have sufficient height to display the tweet in a second line. In the same example, within the cell, I want the content to be displayed as

"I am good

and great"

How can I achieve this?


问:
How to perform more than one operation in django function view
I'm trying to perform 2 operation with in a single function view. But it perform only first operation. Which operation i mentioned first only that operation is executed second operation is not executed. Any other way to solve this problem.    </p>

```<code>def home_view(request):
    if 'username' in request.session:
        if 'username' in request.session:
            username = request.session['username']
            business_objs = AddBusiness.objects.all().values()
            return render(request, 'home/index.html', {'business_objs': business_objs})
        elif request.method == 'GET':
            username = request.session['username']
            form = ProfileForm(request.POST)
            if form.is_valid():
                profile_info = Profile.objects.filter(username=username).values()
                for i in profile_info:
                    profiledict = i
                    return render(request, 'home/index.html',
                                  {'profile_first_name': profiledict['first_name'],
                                   'profile_last_name': profiledict["last_name"],
                                   'profile_phone_number': profiledict['phone_number'],
                                   'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
                                   'profile_image': profiledict['image']})
                return redirect('/home/')
            return redirect('/home/')

    else:
        return redirect('/login/')
</code>```

答:
I think you can try like this:

```<code>def home_view(request):
    if 'username' in request.session:
        if <b>'request.method == 'GET'</b>:
            username = request.session['username']
            business_objs = AddBusiness.objects.all().values()
            return render(request, 'home/index.html', {'business_objs': business_objs})
        elif <b>request.method == 'POST'</b>:
            username = request.session['username']
            form = ProfileForm(request.POST)
            if form.is_valid():
                profile_info = Profile.objects.filter(username=username).values()
                for i in profile_info:
                    profiledict = i
                    return render(request, 'home/index.html',
                                  {'profile_first_name': profiledict['first_name'],
                                   'profile_last_name': profiledict["last_name"],
                                   'profile_phone_number': profiledict['phone_number'],
                                   'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
                                   'profile_image': profiledict['image']})
                return redirect('/home/')
            return redirect('/home/')

    else:
        return redirect('/login/')</code>```

In that way, you will be able to handle both GET and POST request using this function based view. More information can be found in documentation.

Body:
I'm trying to perform 2 operation with in a single function view. But it perform only first operation. Which operation i mentioned first only that operation is executed second operation is not executed. Any other way to solve this problem.

def home_view(request):
    if 'username' in request.session:
        if 'username' in request.session:
            username = request.session['username']
            business_objs = AddBusiness.objects.all().values()
            return render(request, 'home/index.html', {'business_objs': business_objs})
        elif request.method == 'GET':
            username = request.session['username']
            form = ProfileForm(request.POST)
            if form.is_valid():
                profile_info = Profile.objects.filter(username=username).values()
                for i in profile_info:
                    profiledict = i
                    return render(request, 'home/index.html',
                                  {'profile_first_name': profiledict['first_name'],
                                   'profile_last_name': profiledict["last_name"],
                                   'profile_phone_number': profiledict['phone_number'],
                                   'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
                                   'profile_image': profiledict['image']})
                return redirect('/home/')
            return redirect('/home/')

    else:
        return redirect('/login/')

Body:
I think you can try like this:

def home_view(request):
    if 'username' in request.session:
        if 'request.method == 'GET':
            username = request.session['username']
            business_objs = AddBusiness.objects.all().values()
            return render(request, 'home/index.html', {'business_objs': business_objs})
        elif request.method == 'POST':
            username = request.session['username']
            form = ProfileForm(request.POST)
            if form.is_valid():
                profile_info = Profile.objects.filter(username=username).values()
                for i in profile_info:
                    profiledict = i
                    return render(request, 'home/index.html',
                                  {'profile_first_name': profiledict['first_name'],
                                   'profile_last_name': profiledict["last_name"],
                                   'profile_phone_number': profiledict['phone_number'],
                                   'profile_email': profiledict['email'], 'profile_address': profiledict['address'],
                                   'profile_image': profiledict['image']})
                return redirect('/home/')
            return redirect('/home/')

    else:
        return redirect('/login/')

In that way, you will be able to handle both GET and POST request using this function based view. More information can be found in documentation.


问:
How to prevent dublicated items in mongoDB when an item is updated
I am creating a multi-user dictionary, where several users can add words. I don't want that the same word could have dublicates. I was able to prevent dublicates when a word is added, but struggle with a functionality to prevent dublicates when a word is updated. For example, there is a word "apple" in a database, let's imagine someone wanted to update a word "apply" and accidentally wrote "apple", in such a case, updated word "apple" should not go to database, since there is already such word there. Please help me.

Words API

```<code>const express = require('express');
const router = express.Router();
const Word = require('../../models/Word');
const validateWordInput = require('../../validation/word');
const passport = require('passport');

// @route  GET api/words/test
// @desc   tests words route
// @access Public
router.get('/test', (req, res) => res.json({ msg: 'Words works' }));

// @route  POST api/words
// @desc   Add words to profile
// @access Private
router.post(
  '/',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Word.find({}).then(word => {
      if (
        word.filter(
          wrd =>
            wrd.ugrWordCyr.toString().toLowerCase() ===
            req.body.ugrWordCyr.toLowerCase()
        ).length !== 0
      ) {
        return res
          .status(404)
          .json({ wordalreadyexists: 'Word already exists' });
      } else {
        const newWord = new Word({
          user: req.user.id,
          ugrWordCyr: req.body.ugrWordCyr,
          rusTranslation: req.body.rusTranslation,
          example: req.body.example,
          exampleTranslation: req.body.exampleTranslation,
          origin: req.body.origin,
          sphere: req.body.sphere,
          lexis: req.body.lexis,
          grammar: req.body.grammar,
          partOfSpeech: req.body.partOfSpeech,
          style: req.body.style
        });

        newWord.save().then(word => res.json(word));
      }
    });
  }
);

// @route  Put api/words/:id
// @desc   Update a word by id
// @access Private

router.put(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id)
        .then(word => {
          // Check for word owner
          if (word.user.toString() !== req.user.id) {
            return res
              .status(401)
              .json({ notauthorized: 'User not authorized' });
          }

          const wordID = req.params.id;
          const wordInput = req.body;

          // Update
          Word.findByIdAndUpdate(
            { _id: wordID },
            { $set: wordInput },
            { returnOriginal: false },
            (err, word) => {
              if (err) {
                console.log(err);
              }
            }
          ).then(word => {
            res.json(word);
          });
        })
        .catch(err => res.status(404).json({ nowordfound: 'No word found' }));
    });
  }
);

// @route  GET api/words
// @desc   Dislay all words
// @access Public
router.get('/', (req, res) => {
  Word.find()
    .sort({ date: -1 })
    .then(words => res.json(words))
    .catch(err => res.status(404).json({ nonwordsfound: 'No words found' }));
});

//@route  Get api/words/:id
//@desc   Get word by id
//@access Public
router.get('/:id', (req, res) => {
  Word.findById(req.params.id)
    .then(word => res.json(word))
    .catch(err =>
      res.status(404).json({ nonwordfound: 'No word found with that ID' })
    );
});

//@route  DELETE api/words/:id
//@desc   DELETE word
//@access Private

router.delete(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id)
        .then(word => {
          // Check for post owner
          if (word.user.toString() !== req.user.id) {
            return res
              .status(401)
              .json({ notauthorized: 'User not authorized' });
          }

          // Delete
          word.remove().then(() => res.json({ success: true }));
        })
        .catch(err => res.status(404).json({ postnotfound: 'No post found' }));
    });
  }
);

module.exports = router;
</code>```

I used the following code to prevent dublicated on addition.

```<code>   if (
                word.filter(
                  wrd =>
                    wrd.ugrWordCyr.toString().toLowerCase() ===
                    req.body.ugrWordCyr.toLowerCase()
                ).length !== 0
              ) {
                return res
                  .status(404)
                  .json({ wordalreadyexists: 'Word already exists' });
              } else {
                const newWord = new Word({
                  user: req.user.id,
                  ugrWordCyr: req.body.ugrWordCyr,
                  rusTranslation: req.body.rusTranslation,
                  example: req.body.example,
                  exampleTranslation: req.body.exampleTranslation,
                  origin: req.body.origin,
                  sphere: req.body.sphere,
                  lexis: req.body.lexis,
                  grammar: req.body.grammar,
                  partOfSpeech: req.body.partOfSpeech,
                  style: req.body.style
                });
</code>```

What code should I write to do the same on update?

答:
Before executing Word.findByIdAndUpdate(), you can do a check to see if the text in req.body matches any existing words in your database.

```<code>// @route  Put api/words/:id
// @desc   Update a word by id
// @access Private

router.put(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id)
        .then(word => {
          // Check for word owner
          if (word.user.toString() !== req.user.id) {
            return res
              .status(401)
              .json({ notauthorized: 'User not authorized' });
          }

          const wordID = req.params.id;
          const wordInput = req.body;

         //find all words
          Word.find()
              .then((allWords) => {
                  //create an array of strings using each word ("apple", "apricot", ...etc)
                  const wordStrings = allWords.map((word) => word.ugrWordCyr) //not sure if thats the property that has the word-spelling

                  //check if user input already exists in all words
                  if(wordStrings.includes(req.body.ugrWordCyr)){
                       return res.status(400).json({ error : "word already exists" })
                  }

                  // Update
                  Word.findByIdAndUpdate(
                      { _id: wordID },
                      { $set: wordInput },
                      { returnOriginal: false },
                      (err, word) => {
                          if (err) {
                             console.log(err);
                          }
                      }).then(word => {
                           res.json(word);
                      });

               })
               .catch((errors) => {
                   return res.status(400).json({ errors: "could not find any words" })
               })

        })
        .catch(err => res.status(404).json({ nowordfound: 'No word found' }));
    });
  }
);
</code>```

Alternatively, you could also update your Word model and use the unique property when setting up your mongoose schema. I imagine your schema looks something like this:

```<code>const mongoose = require("mongoose")

    const wordSchema = new mongoose.Schema({
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
      },
      ugrWordCyr: { type: String, unique: true}, <-- set unique to true
      rusTranslation: { type: String },
      example: { type: String },
      exampleTranslation: { type: String },
      origin: { type: String },
      sphere: { type: String },
      lexis: { type: String },
      grammar: { type: String },
      partOfSpeech: { type: String },
      style: { type: String }
    })

const Word = mongoose.model("Word", userSchema)

module.exports = Word
</code>```

Now when you use findByIdAndUpdate(), it will not complete unless you pass in a new/unique string to ugrWordCyr or whatever you use as the explicit word.

```<code>      Word.findByIdAndUpdate(
        { _id: wordID },
        { $set: wordInput },
        { returnOriginal: false },
        (err, word) => {
          if (err) {
            console.log(err);
          }
        }
        ).then(word => {
             res.json(word);
          });
         .catch(err => {
             return res.status(400).json({ error: "could not update word" })
          })
       })
</code>```

Body:
I am creating a multi-user dictionary, where several users can add words. I don't want that the same word could have dublicates. I was able to prevent dublicates when a word is added, but struggle with a functionality to prevent dublicates when a word is updated. For example, there is a word "apple" in a database, let's imagine someone wanted to update a word "apply" and accidentally wrote "apple", in such a case, updated word "apple" should not go to database, since there is already such word there. Please help me.

Words API

const express = require('express');
const router = express.Router();
const Word = require('../../models/Word');
const validateWordInput = require('../../validation/word');
const passport = require('passport');

// @route  GET api/words/test
// @desc   tests words route
// @access Public
router.get('/test', (req, res) => res.json({ msg: 'Words works' }));

// @route  POST api/words
// @desc   Add words to profile
// @access Private
router.post(
  '/',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Word.find({}).then(word => {
      if (
        word.filter(
          wrd =>
            wrd.ugrWordCyr.toString().toLowerCase() ===
            req.body.ugrWordCyr.toLowerCase()
        ).length !== 0
      ) {
        return res
          .status(404)
          .json({ wordalreadyexists: 'Word already exists' });
      } else {
        const newWord = new Word({
          user: req.user.id,
          ugrWordCyr: req.body.ugrWordCyr,
          rusTranslation: req.body.rusTranslation,
          example: req.body.example,
          exampleTranslation: req.body.exampleTranslation,
          origin: req.body.origin,
          sphere: req.body.sphere,
          lexis: req.body.lexis,
          grammar: req.body.grammar,
          partOfSpeech: req.body.partOfSpeech,
          style: req.body.style
        });

        newWord.save().then(word => res.json(word));
      }
    });
  }
);

// @route  Put api/words/:id
// @desc   Update a word by id
// @access Private

router.put(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id)
        .then(word => {
          // Check for word owner
          if (word.user.toString() !== req.user.id) {
            return res
              .status(401)
              .json({ notauthorized: 'User not authorized' });
          }

          const wordID = req.params.id;
          const wordInput = req.body;

          // Update
          Word.findByIdAndUpdate(
            { _id: wordID },
            { $set: wordInput },
            { returnOriginal: false },
            (err, word) => {
              if (err) {
                console.log(err);
              }
            }
          ).then(word => {
            res.json(word);
          });
        })
        .catch(err => res.status(404).json({ nowordfound: 'No word found' }));
    });
  }
);

// @route  GET api/words
// @desc   Dislay all words
// @access Public
router.get('/', (req, res) => {
  Word.find()
    .sort({ date: -1 })
    .then(words => res.json(words))
    .catch(err => res.status(404).json({ nonwordsfound: 'No words found' }));
});

//@route  Get api/words/:id
//@desc   Get word by id
//@access Public
router.get('/:id', (req, res) => {
  Word.findById(req.params.id)
    .then(word => res.json(word))
    .catch(err =>
      res.status(404).json({ nonwordfound: 'No word found with that ID' })
    );
});

//@route  DELETE api/words/:id
//@desc   DELETE word
//@access Private

router.delete(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id)
        .then(word => {
          // Check for post owner
          if (word.user.toString() !== req.user.id) {
            return res
              .status(401)
              .json({ notauthorized: 'User not authorized' });
          }

          // Delete
          word.remove().then(() => res.json({ success: true }));
        })
        .catch(err => res.status(404).json({ postnotfound: 'No post found' }));
    });
  }
);

module.exports = router;

I used the following code to prevent dublicated on addition.

   if (
                word.filter(
                  wrd =>
                    wrd.ugrWordCyr.toString().toLowerCase() ===
                    req.body.ugrWordCyr.toLowerCase()
                ).length !== 0
              ) {
                return res
                  .status(404)
                  .json({ wordalreadyexists: 'Word already exists' });
              } else {
                const newWord = new Word({
                  user: req.user.id,
                  ugrWordCyr: req.body.ugrWordCyr,
                  rusTranslation: req.body.rusTranslation,
                  example: req.body.example,
                  exampleTranslation: req.body.exampleTranslation,
                  origin: req.body.origin,
                  sphere: req.body.sphere,
                  lexis: req.body.lexis,
                  grammar: req.body.grammar,
                  partOfSpeech: req.body.partOfSpeech,
                  style: req.body.style
                });

What code should I write to do the same on update?

Body:
Before executing Word.findByIdAndUpdate(), you can do a check to see if the text in req.body matches any existing words in your database.

// @route  Put api/words/:id
// @desc   Update a word by id
// @access Private

router.put(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id)
        .then(word => {
          // Check for word owner
          if (word.user.toString() !== req.user.id) {
            return res
              .status(401)
              .json({ notauthorized: 'User not authorized' });
          }

          const wordID = req.params.id;
          const wordInput = req.body;

         //find all words
          Word.find()
              .then((allWords) => {
                  //create an array of strings using each word ("apple", "apricot", ...etc)
                  const wordStrings = allWords.map((word) => word.ugrWordCyr) //not sure if thats the property that has the word-spelling

                  //check if user input already exists in all words
                  if(wordStrings.includes(req.body.ugrWordCyr)){
                       return res.status(400).json({ error : "word already exists" })
                  }

                  // Update
                  Word.findByIdAndUpdate(
                      { _id: wordID },
                      { $set: wordInput },
                      { returnOriginal: false },
                      (err, word) => {
                          if (err) {
                             console.log(err);
                          }
                      }).then(word => {
                           res.json(word);
                      });

               })
               .catch((errors) => {
                   return res.status(400).json({ errors: "could not find any words" })
               })

        })
        .catch(err => res.status(404).json({ nowordfound: 'No word found' }));
    });
  }
);

Alternatively, you could also update your Word model and use the unique property when setting up your mongoose schema. I imagine your schema looks something like this:

const mongoose = require("mongoose")

    const wordSchema = new mongoose.Schema({
      user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
      },
      ugrWordCyr: { type: String, unique: true}, <-- set unique to true
      rusTranslation: { type: String },
      example: { type: String },
      exampleTranslation: { type: String },
      origin: { type: String },
      sphere: { type: String },
      lexis: { type: String },
      grammar: { type: String },
      partOfSpeech: { type: String },
      style: { type: String }
    })

const Word = mongoose.model("Word", userSchema)

module.exports = Word

Now when you use findByIdAndUpdate(), it will not complete unless you pass in a new/unique string to ugrWordCyr or whatever you use as the explicit word.

      Word.findByIdAndUpdate(
        { _id: wordID },
        { $set: wordInput },
        { returnOriginal: false },
        (err, word) => {
          if (err) {
            console.log(err);
          }
        }
        ).then(word => {
             res.json(word);
          });
         .catch(err => {
             return res.status(400).json({ error: "could not update word" })
          })
       })


问:
How to encode a string to UTF8 and then display it correctly in html?
I have a program, in which a table is shown on the screen. The content is displayed correctly as long as there are no accents.

This is my code

StringBuffer sBuff = new StringBuffer();
if(!("CSV".equalsIgnoreCase(exportFormat) || "HTML".equalsIgnoreCase(exportFormat))){
        sBuff.append("
");
        sBuff.append(displayparseado);
        sBuff.append("
");
}
else{
        sBuff.append(display);
}
```

<p>I have also tried parsing the string.</p>

<pre class="lang-java prettyprint-override"><code>byte arr[] = display.getBytes("UTF-8");
String displayparseado = new String(arr);
</code>```

Expected output: Descripción de prueba.

Actual output:

A note; I can not use external libraries.

答: Try StringEscapeUtils to escape your String for html. This did a good job for me till now.</p>

Body:
I have a program, in which a table is shown on the screen. The content is displayed correctly as long as there are no accents.

This is my code

StringBuffer sBuff = new StringBuffer();
if(!("CSV".equalsIgnoreCase(exportFormat) || "HTML".equalsIgnoreCase(exportFormat))){
        sBuff.append("
");
        sBuff.append(displayparseado);
        sBuff.append("
");
}
else{
        sBuff.append(display);
}

I have also tried parsing the string.

byte arr[] = display.getBytes("UTF-8");
String displayparseado = new String(arr);

Expected output: Descripción de prueba.

Actual output:

A note; I can not use external libraries.


问:
Is it possible to start counting from a specific div in Python using XPATH and Selenium?
I have 80 divs, each div (in our case, class 24, 27, 30) contains 2 children.

Is it possible to start counting from let's say, the 24rd row (EXCLUDING CHILDREN), then keep counting the rows under it? (using XPATH only, not CSS selectors ;) )

```<code><div class="container">
    ... # dots signify the divs before it
    <div class="24">
        <div class="25"></div>
        <div class="26"></div>
    </div>
    <div class="27">
        <div class="28"></div>
        <div class="29"></div>
    </div>
    <div class="30">
        <div class="31"></div>
        <div class="32"></div>
    </div>
    ... # divs after it
</div>
</code>```

Is there something like:

Let's say:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        # something like:
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
       # or
       divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
        break
    x += 1
```

OUTPUT: The length should be 2 (class 27 and 30 without their children)
Many thanks.

答:
You could use XPath Filter predicates in order to return only children of the
 which are greater than the given number.

The relevant expression would be:

```<code>//div[@class='container']/child::*[number(@class)>24]
</code>```

translated into Python and Selenium bindings

```<code>divNumber = 24

interestingDivs = driver.find_elements_by_xpath(
    "//div[@class='container']/child::*[number(@class)>" + str(divNumber) + "]")

for interestingDiv in interestingDivs:
    print(interestingDiv.get_attribute("class"))
</code>```

See XPath Syntax article for more information

Body:
I have 80 divs, each div (in our case, class 24, 27, 30) contains 2 children.

Is it possible to start counting from let's say, the 24rd row (EXCLUDING CHILDREN), then keep counting the rows under it? (using XPATH only, not CSS selectors ;) )

    ... # dots signify the divs before it

    ... # divs after it

Is there something like:

Let's say:

x = 0
all_the_divs = driver.find_elements_by_xpath("//div/*")
while x < len(all_the_divs):
    # do something
    pass
    if x == 24:
        # catch all the divs under 24 (excluding 24)
        # something like:
        divs_under_x = len(driver.find_elements_by_xpath("//div/div[" + str(x) + "]::"))
       # or
       divs_under_x = len(driver.find_elements_by_xpath("//div/following-sibling::div[" + str(x) + "]*"))
        break
    x += 1

OUTPUT: The length should be 2 (class 27 and 30 without their children)
Many thanks.

Body:
You could use XPath Filter predicates in order to return only children of the <div class="container"> which are greater than the given number.

The relevant expression would be:

//div[@class='container']/child::*[number(@class)>24]

translated into Python and Selenium bindings

divNumber = 24

interestingDivs = driver.find_elements_by_xpath(
    "//div[@class='container']/child::*[number(@class)>" + str(divNumber) + "]")

for interestingDiv in interestingDivs:
    print(interestingDiv.get_attribute("class"))

See XPath Syntax article for more information


问:
How can I print underlined text in C/C++?
I'm coding an application, and want to print underlined text. What I'm doing wrong?

I'm using a "translated" code from C#, normally it works great in C# but does not in C++. After I fixed the errors, the code simply does not work. It shows some characters that normaly won't. This is what it prints instead (https://i.imgur.com/V1X2uWk.png)

Here's the code I used

```<code>auto DllHandler = GetStdHandle(-11);
unsigned int Mode;
GetConsoleMode(DllHandler,PDWORD(Mode));
Mode |= 4;
SetConsoleMode(DllHandler,DWORD(Mode));
cout << "\x1b[5mUnderlined \x1b[0mtext" << endl;
</code>```

And here's the original (C#) code:

```<code>    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr GetStdHandle(int nStdHandle);
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
    [DllImport("kernel32.dll")]
    public static extern IntPtr SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
        var DllHandler = Kernel32.GetStdHandle(-11);
        uint Mode;
        GetConsoleMode(DllHandler,out Mode);
        Mode |= 4;
        SetConsoleMode(DllHandler, Mode);
        Console.Write("\x1b[5mUnderlined \x1b[0mText");
</code>```

Thanks in advance.

答:
Just like @RbMm said, use ULONG type can compile successfully and achieve the desired results.

But the real cause of the error is the error of pointer transmission.
If you want to use unsigned int, the first step is to apply for pointers and allocate memory for pointers, and then force type conversion in GetConsoleMode.

```<code>    auto DllHandler = GetStdHandle(-11);
    unsigned int *Mode = new unsigned int;
    GetConsoleMode(DllHandler, PDWORD(Mode));
    *Mode = *Mode | 4;
    SetConsoleMode(DllHandler, DWORD(*Mode));
    cout << "\x1b[4mUnderlined \x1b[4mtext" << endl;

    delete Mode;
</code>```

Body:
I'm coding an application, and want to print underlined text. What I'm doing wrong?

I'm using a "translated" code from C#, normally it works great in C# but does not in C++. After I fixed the errors, the code simply does not work. It shows some characters that normaly won't. This is what it prints instead (https://i.imgur.com/V1X2uWk.png)

Here's the code I used

auto DllHandler = GetStdHandle(-11);
unsigned int Mode;
GetConsoleMode(DllHandler,PDWORD(Mode));
Mode |= 4;
SetConsoleMode(DllHandler,DWORD(Mode));
cout << "\x1b[5mUnderlined \x1b[0mtext" << endl;

And here's the original (C#) code:

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern IntPtr GetStdHandle(int nStdHandle);
    [DllImport("kernel32.dll")]
    public static extern IntPtr GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
    [DllImport("kernel32.dll")]
    public static extern IntPtr SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
        var DllHandler = Kernel32.GetStdHandle(-11);
        uint Mode;
        GetConsoleMode(DllHandler,out Mode);
        Mode |= 4;
        SetConsoleMode(DllHandler, Mode);
        Console.Write("\x1b[5mUnderlined \x1b[0mText");

Thanks in advance.

Body:
Just like @RbMm said, use ULONG type can compile successfully and achieve the desired results.

But the real cause of the error is the error of pointer transmission.
If you want to use unsigned int, the first step is to apply for pointers and allocate memory for pointers, and then force type conversion in GetConsoleMode.

    auto DllHandler = GetStdHandle(-11);
    unsigned int *Mode = new unsigned int;
    GetConsoleMode(DllHandler, PDWORD(Mode));
    *Mode = *Mode | 4;
    SetConsoleMode(DllHandler, DWORD(*Mode));
    cout << "\x1b[4mUnderlined \x1b[4mtext" << endl;

    delete Mode;


问:
Plugin cakephp 3.7
How can I map a plugin  into the cakephp 3.7, through a remote folder?

after version 3.4 I am no longer able to load a plugin, I looked at the documentation and checked that it had changes already tried using Application :: addplugin (); and Application :: bootstrap (); that were the solutions I found searching, I do not know if I have to do any more procedure or if some other syntax has changed.

答:
From CakePHP documentation:

The plugin shell allows you to load and unload plugins via the command
  prompt. If you need help, run:

```<code>bin/cake plugin --help
</code>```

Loading Plugins

Via the Load task you are able to load plugins in your
  config/bootstrap.php. You can do this by running:

```<code>bin/cake plugin load MyPlugin
</code>```

This will add the following to your src/Application.php:

```<code>// In the bootstrap method add:
$this->addPlugin('MyPlugin');

// Prior to 3.6, add the following to config/bootstrap.php
Plugin::load('MyPlugin');
</code>```

If you need plugin before any method / event in your bootstrap, then use like:

```<code>class Application extends BaseApplication
    {
        /**
         * {@inheritDoc}
         */
        public function bootstrap()
        {
            $this->addPlugin('OAuthServer', ['routes' => true]);

            // Call parent to load bootstrap from files.
            parent::bootstrap();

            if (PHP_SAPI === 'cli') {
                try {
                    $this->addPlugin('Bake');
                } catch (MissingPluginException $e) {
                    // Do not halt if the plugin is missing
                }

                $this->addPlugin('Migrations');
            }

            /*
             * Only try to load DebugKit in development mode
             * Debug Kit should not be installed on a production system
             */
            if (Configure::read('debug')) {
                $this->addPlugin(\DebugKit\Plugin::class);
            }

            // Other plugins
            $this->addPlugin('BootstrapUI');
            $this->addPlugin('Search');
</code>```

Read more:

https://book.cakephp.org/3.0/en/console-and-shells/plugin-shell.html

Title: Plugin cakephp 3.7

Body:
From CakePHP documentation:

The plugin shell allows you to load and unload plugins via the command
  prompt. If you need help, run:

bin/cake plugin --help

Loading Plugins

Via the Load task you are able to load plugins in your
  config/bootstrap.php. You can do this by running:

bin/cake plugin load MyPlugin

This will add the following to your src/Application.php:

// In the bootstrap method add:
$this->addPlugin('MyPlugin');

// Prior to 3.6, add the following to config/bootstrap.php
Plugin::load('MyPlugin');

If you need plugin before any method / event in your bootstrap, then use like:

class Application extends BaseApplication
    {
        /**
         * {@inheritDoc}
         */
        public function bootstrap()
        {
            $this->addPlugin('OAuthServer', ['routes' => true]);

            // Call parent to load bootstrap from files.
            parent::bootstrap();

            if (PHP_SAPI === 'cli') {
                try {
                    $this->addPlugin('Bake');
                } catch (MissingPluginException $e) {
                    // Do not halt if the plugin is missing
                }

                $this->addPlugin('Migrations');
            }

            /*
             * Only try to load DebugKit in development mode
             * Debug Kit should not be installed on a production system
             */
            if (Configure::read('debug')) {
                $this->addPlugin(\DebugKit\Plugin::class);
            }

            // Other plugins
            $this->addPlugin('BootstrapUI');
            $this->addPlugin('Search');

Read more:

https://book.cakephp.org/3.0/en/console-and-shells/plugin-shell.html


问:
How to cache common (for all pixels) variables in ShaderLab?
Suppose I have the following shader:

```<code>Shader "Sprites/X"
{
    Properties
    {
        [HideInInspector] _MainTex("Sprite Texture", 2D) = "black" {}
    }

    SubShader
    {
        Pass
        {
            CGPROGRAM

            // bla bla

            fixed4 frag(v2f i) : SV_Target
            {
                float a = calculateA();
                float b = calculateB();
                .
                .
                .
                float z = calculateZ();

                // Here the values above mix with x-y position of the pixel
                // and then return a color
            }
            ENDCG
        }
    }
}
</code>```

In the above code I need to calculate the values of the variables a - z from the related functions calculateA() -  calculateZ() (it's just a generalization example). Suppose these functions are complex and that they depend from other properties of the shader that change in each frame, instead of the pixel itself. We know that the complex functions are computed every time for each pixel.

There is a way to "cache" these values to avoid the calculation each time for each pixel? In every frame their values is the same for all the pixels.

Currently I'm solving the problem by setting the values in the C# script with:

```<code>gameObject.GetComponent<Renderer>().material.SetFloat("a", calculateA());
.
.
.
gameObject.GetComponent<Renderer>().material.SetFloat("z", calculateZ());
</code>```

but i prefer to mantain the shader and the C# script code separated.

答:
Well, that's exactly how you'd do it :)

It depends on why exactly you'd want to avoid using C#

If said method is computed solely out of constants then the compiler
would optimize it away.

If the method has few predictable outcomes
you could pre-compute them into an array declared in the shader itself, or set once from code instead of every frame.

If there are a lot of those predictable outcomes you could look into baking them
into a texture, or if you can use a modern GPU, into structured
buffers.

Body:
Suppose I have the following shader:

Shader "Sprites/X"
{
    Properties
    {
        [HideInInspector] _MainTex("Sprite Texture", 2D) = "black" {}
    }

    SubShader
    {
        Pass
        {
            CGPROGRAM

            // bla bla

            fixed4 frag(v2f i) : SV_Target
            {
                float a = calculateA();
                float b = calculateB();
                .
                .
                .
                float z = calculateZ();

                // Here the values above mix with x-y position of the pixel
                // and then return a color
            }
            ENDCG
        }
    }
}

In the above code I need to calculate the values of the variables a - z from the related functions calculateA() -  calculateZ() (it's just a generalization example). Suppose these functions are complex and that they depend from other properties of the shader that change in each frame, instead of the pixel itself. We know that the complex functions are computed every time for each pixel.

There is a way to "cache" these values to avoid the calculation each time for each pixel? In every frame their values is the same for all the pixels.

Currently I'm solving the problem by setting the values in the C# script with:

gameObject.GetComponent<Renderer>().material.SetFloat("a", calculateA());
.
.
.
gameObject.GetComponent<Renderer>().material.SetFloat("z", calculateZ());

but i prefer to mantain the shader and the C# script code separated.


问:
How to unmarshal an xml enum attribute in go?
I want to parse an xml attribute as an iota enum type (int) in go.

Below you can see what I tried but this does not work because the address of enum variables can't be taken.

```<code>type EnumType int
const (
    EnumUnknown EnumType = iota
    EnumFoo
    EnumBar
)

func (E *EnumType) UnmarshalXMLAttr(attr xml.Attr) error {
    switch attr.Value {
    case "foo":
        E = &EnumFoo
    case "bar":
        E = &EnumBar
    default:
        E = &EnumUnknown
    }
    return nil
}

// Example of how the unmarshal could be called:
type Tag struct {
    Attribute EnumType `xml:"attribute,attr"`
}

func main() {
    tag := &Tag{}
    xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
}
</code>```

Any other way to make UnmarshalXMLAttr work with int types?

Update: I know I can solve this by adding the UnmarshalXML method to Tag but I want to avoid this if possible because I have a lot of different tags with a lot of different attributes but only a few custom typed attributes. So implementing UnmarshalXML methods for each tag would not be preferred.

答:
I solved the problem by wrapping the int in a struct.

```<code>type EnumType int
const (
    EnumUnknown EnumType = iota
    EnumFoo
    EnumBar
)
type EnumContainer struct {
    Value EnumType
}

func (E *EnumContainer) UnmarshalXMLAttr(attr xml.Attr) error {
    switch attr.Value {
    case "foo":
        E.Value = EnumFoo
    case "bar":
        E.Value = EnumBar
    default:
        E.Value = EnumUnknown
    }
    return nil
}

// Example of how the unmarshal could be called:
type Tag struct {
    Attribute EnumContainer `xml:"attribute,attr"`
}

func main() {
    tag := &Tag{}
    xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
</code>```

Is there a "more elegant" way or should I be happy with what I now have?

Body:
I want to parse an xml attribute as an iota enum type (int) in go.

Below you can see what I tried but this does not work because the address of enum variables can't be taken.

type EnumType int
const (
    EnumUnknown EnumType = iota
    EnumFoo
    EnumBar
)

func (E *EnumType) UnmarshalXMLAttr(attr xml.Attr) error {
    switch attr.Value {
    case "foo":
        E = &EnumFoo
    case "bar":
        E = &EnumBar
    default:
        E = &EnumUnknown
    }
    return nil
}

// Example of how the unmarshal could be called:
type Tag struct {
    Attribute EnumType `xml:"attribute,attr"`
}

func main() {
    tag := &Tag{}
    xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)
}

Any other way to make UnmarshalXMLAttr work with int types?

Update: I know I can solve this by adding the UnmarshalXML method to Tag but I want to avoid this if possible because I have a lot of different tags with a lot of different attributes but only a few custom typed attributes. So implementing UnmarshalXML methods for each tag would not be preferred.

Body:
I solved the problem by wrapping the int in a struct.

type EnumType int
const (
    EnumUnknown EnumType = iota
    EnumFoo
    EnumBar
)
type EnumContainer struct {
    Value EnumType
}

func (E *EnumContainer) UnmarshalXMLAttr(attr xml.Attr) error {
    switch attr.Value {
    case "foo":
        E.Value = EnumFoo
    case "bar":
        E.Value = EnumBar
    default:
        E.Value = EnumUnknown
    }
    return nil
}

// Example of how the unmarshal could be called:
type Tag struct {
    Attribute EnumContainer `xml:"attribute,attr"`
}

func main() {
    tag := &Tag{}
    xml.Unmarshal([]byte("<tag attribute=\"foo\"/>"), tag)

Is there a "more elegant" way or should I be happy with what I now have?


问:
How to fix problem with Roboto font load in Google Chrome?
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

```<code>GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND
</code>```

I tried to import directy in the CSS and in the HTML this:

```<code>@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}
</code>```

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>
        <style>
            @import url('https://fonts.googleapis.com/css?family=Roboto&display=swap');
        </style>
        <!-- JQuery Mobile -->
        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>
        <!-- Project CSS -->
        <link rel="stylesheet" href="./css/style.css"></link>
        <!-- NativeDroid2 CSS -->
        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>
    </head>
    <body>
        <div data-role="main" class="ui-content">
            <form method="post">
                <div class="img-container">
                    <img src="img/logo_gemott.png" alt="No es pot carregar la imatge" height="110" width="350">
                </div>

                <div>
                    <h2>Registre</h2>
                    <hr>
                    <label for="mail"><b>Correu electrònic</b></label>
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    <label for="psw"><b>Contrasenya</b></label>
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>
                    <div class="center-text">
                        <p>Al registrar-te, acceptes els <a href=#>termes de privacitat</a></p>
                        <p>Ja estàs <a href="login.html">registrat?</a></p>
                    </div>
                </div>

                <a href="javascript:registry()" class="ui-btn ui-btn-raised clr-primary">Registrar-me</a>

                <div class="img-container" id="uab-logo">
                    <img src="img/UAB.jpg" alt="No es pot carrerar la imatge" height="150" witdh="150">
                </div>
            </form>
        </div>
        <!-- JQuery -->
        <script type="text/javascript" src="jquery/jquery-2.2.4.js"></script>
        <!-- Project Js -->
        <script type="text/javascript" src="js/app.js"></script>
        <!-- JQuery Mobile -->
        <script type="text/javascript" src="jquery/jquery.mobile-1.4.5.min.js"></script>
        <!-- NativeDroid2 Js -->
        <script type="text/javascript" src="bower_components/Waves/dist/waves.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/nd2settings.js"></script>
        <script type="text/javascript" src="bower_components/nativeDroid2/js/nativedroid2.js"></script>
    </body>
</html>
</code>```

答: Finally I've found the problem. I'm using a Jquery Mobile theme called NativeDroid2 and it was loading the Roboto font-family incorrectly in the CSS file. I simply commented the url and now works perfectly.</p>

Body:
I'm trying to render my website and I takes a lot of time in Google Chrome, but in Mozilla works perfectly. The console shows the error

GET file://fonts.googleapis.com/css?family=RobotoDraft:300,400,500,700,400italic net::ERR_FILE_NOT_FOUND

I tried to import directy in the CSS and in the HTML this:

@import url(http://fonts.googleapis.com/css?family=Roboto:400,400italic,500,500italic,700,700italic,900,900italic,300italic,300,100italic,100);

body {
   font-family: 'Roboto', sans-serif;
}

But it still doesn't work, it throws the same error.

Here is the full HTML code of my website:

<!DOCTYPE html>

        <meta charset="utf-8"> </meta>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"></meta>
        <title>Sign in</title>

        <link rel="stylesheet" href="./jquery/jquery.mobile-1.4.5.css"></link>

        <link rel="stylesheet" href="./css/style.css"></link>

        <link rel="stylesheet" href="./bower_components/nativeDroid2/css/nativedroid2.css"></link>

            <form method="post">

Registre

                    Correu electrònic
                    <input type="text" placeholder="Introduir correu electrònic..." name="mail" required>
                    Contrasenya
                    <input type="password" placeholder="Introduir contrasenya..." name="psw" required>

Al registrar-te, acceptes els termes de privacitat

Ja estàs registrat?

                Registrar-me

            </form>


问:
HttpSession, session.getAttribute(), problem
I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:

```<code>Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);
</code>```

Thanks.

答:
The code is either broken or the setAttribute() is futile.

If you get a mutable container (like a list or a vector) from the session, then it's not necessary to put it again into the session. It's the equivalent of this code:

```<code> session.setAttribute("Register", buylist);
 session.setAttribute("Register", buylist);
 session.setAttribute("Register", buylist);
</code>```

None but the first line have an effect.

The other possibility is that the code has a bug and what really was meant was this:

```<code>Vector buylist = session.getAttribute("Register");
if( buylist == null ) {
    buylist = new Vector();
    session.setAttribute("Register", buylist);
}
</code>```

i.e. create a new vector if it doesn't exist already.

Body:
I have a problem related to Java servlet sessions. I don't understand why the getAttribute() function of the session object is used before setAttribute(); Here is the code:

Vector buylist=(Vector)session.getAttribute("Register");
if (action.equals("del")) {
String del = request.getParameter("deli");
int d = (new Integer(del)).intValue();
buylist.removeElementAt(d);
}
session.setAttribute("Register", buylist);

Thanks.

Body:
The code is either broken or the setAttribute() is futile.

If you get a mutable container (like a list or a vector) from the session, then it's not necessary to put it again into the session. It's the equivalent of this code:

 session.setAttribute("Register", buylist);
 session.setAttribute("Register", buylist);
 session.setAttribute("Register", buylist);

None but the first line have an effect.

The other possibility is that the code has a bug and what really was meant was this:

Vector buylist = session.getAttribute("Register");
if( buylist == null ) {
    buylist = new Vector();
    session.setAttribute("Register", buylist);
}

i.e. create a new vector if it doesn't exist already.


问:
How can i reduce the space between list builder items?
I have created a ListView of RadioListTile and there is some intrinsic padding between the tiles which I am not able to remove. How can i fix this? Thanks in advance

My code:

```<code> @override Widget build(BuildContext context) {

    Column screen = Column(
        ....
        ,
        Expanded(
          child:
          ListView.builder(
            padding: EdgeInsets.all(0.0),
            itemCount: tasks.length
            itemBuilder: (context, index) {
                return RadioListTile<String>(
                    title:  Text(tasks[index], style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w400)),
                    value: tasks[index],
                    groupValue: selectedRadio,
                    onChanged: (val){
                      setSelectedRadio(val);
                    }
                );
            },
          ),
        ),
      ],
    );

    return Scaffold(
      body: screen,
    );
  }
</code>```

答:
You can use the ListTileTheme widget to remove the padding and set a vertically dense layout.

```<code>    ListTileTheme.merge(
              contentPadding: EdgeInsets.all(0.0),
              dense: true,
              child: ListView.builder(
                padding: EdgeInsets.all(0.0),
                itemCount: 7,
                itemBuilder: (context, index) {
                  return RadioListTile<String>(
                       ...
                      });
                },
              ),
            ),
</code>```

Body:
I have created a ListView of RadioListTile and there is some intrinsic padding between the tiles which I am not able to remove. How can i fix this? Thanks in advance

My code:

 @override Widget build(BuildContext context) {

    Column screen = Column(
        ....
        ,
        Expanded(
          child:
          ListView.builder(
            padding: EdgeInsets.all(0.0),
            itemCount: tasks.length
            itemBuilder: (context, index) {
                return RadioListTile<String>(
                    title:  Text(tasks[index], style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.w400)),
                    value: tasks[index],
                    groupValue: selectedRadio,
                    onChanged: (val){
                      setSelectedRadio(val);
                    }
                );
            },
          ),
        ),
      ],
    );

    return Scaffold(
      body: screen,
    );
  }

Body:
You can use the ListTileTheme widget to remove the padding and set a vertically dense layout.

    ListTileTheme.merge(
              contentPadding: EdgeInsets.all(0.0),
              dense: true,
              child: ListView.builder(
                padding: EdgeInsets.all(0.0),
                itemCount: 7,
                itemBuilder: (context, index) {
                  return RadioListTile<String>(
                       ...
                      });
                },
              ),
            ),


问:
How can i create Google Maps link in Javascript
Hi Guys i want make a link and this link include latitude and longitude in javascript function can you help me about this.

My javascipt code:

```<code>function jsFilter(item) {
                   document.getElementById("myDiv").innerHTML = "";
                    item.Agency.forEach(agency=> {
                        $("#myDiv").append(
                            "<div style='border-style:ridge;'>Agency Name : <strong>" + agency.name+ "</strong><br>" +
                            "Agency Adress : <strong>" + agency.ADRESS_TEXT + "</strong><br>" +
                            "Agency EMail: <strong>" + agency.EMAIL+ "</strong></div>",
                            "https://maps.google.com/maps?q=" + agency.lat+ ',' + agency.lon   // i wanna add here.
                        );
                    });
                }
</code>```

答:
Because the most of your code looks good, i guees you only needed the correct maps link and how the values are applyed to it?

Then thats what you need:

```<code>function jsFilter(item) {
                   document.getElementById("myDiv").innerHTML = "";
                    item.Agency.forEach(agency=> {
                        $("#myDiv").append(
                            "<div style='border-style:ridge;'>Agency Name : <strong>" + agency.name+ "</strong><br>" +
                            "Agency Adress : <strong>" + agency.ADRESS_TEXT + "</strong><br>" +
                            "Agency EMail: <strong>" + agency.EMAIL+ "</strong></div>" +
                            "<a href=\"https://maps.google.com/maps/@" + agency.lat + "," + agency.lon + "\">Google Maps Link</a>"
                        );
                    });
                }
</code>```

// EDIT
Added the Link as HTML link.

Edit 2

As of the discussion in the comments, you needed a syntax for a HTML Link.
Solution:

```<code>// replace this line:
"https://maps.google.com/maps?q=" + agency.lat+ ',' + agency.lon"
// with:
"<a href=\"https://maps.google.com/maps?q=" + agency.lat+ "," + agency.lon+ "\">google link</div>"
</code>```

This will give you an working Google Maps link.

Body:
Hi Guys i want make a link and this link include latitude and longitude in javascript function can you help me about this.

My javascipt code:

function jsFilter(item) {
                   document.getElementById("myDiv").innerHTML = "";
                    item.Agency.forEach(agency=> {
                        $("#myDiv").append(
                            "
Agency Name : " + agency.name+ "
" +
                            "Agency Adress : " + agency.ADRESS_TEXT + "
" +
                            "Agency EMail: " + agency.EMAIL+ "
",
                            "https://maps.google.com/maps?q=" + agency.lat+ ',' + agency.lon   // i wanna add here.
                        );
                    });
                }

Body:
Because the most of your code looks good, i guees you only needed the correct maps link and how the values are applyed to it?

Then thats what you need:

function jsFilter(item) {
                   document.getElementById("myDiv").innerHTML = "";
                    item.Agency.forEach(agency=> {
                        $("#myDiv").append(
                            "<div style='border-style:ridge;'>Agency Name : <strong>" + agency.name+ "</strong><br>" +
                            "Agency Adress : <strong>" + agency.ADRESS_TEXT + "</strong><br>" +
                            "Agency EMail: <strong>" + agency.EMAIL+ "</strong></div>" +
                            "<a href=\"https://maps.google.com/maps/@" + agency.lat + "," + agency.lon + "\">Google Maps Link</a>"
                        );
                    });
                }

// EDIT
Added the Link as HTML link.

Edit 2

As of the discussion in the comments, you needed a syntax for a HTML Link.
Solution:

// replace this line:
"https://maps.google.com/maps?q=" + agency.lat+ ',' + agency.lon"
// with:
"<a href=\"https://maps.google.com/maps?q=" + agency.lat+ "," + agency.lon+ "\">google link</div>"

This will give you an working Google Maps link.


问:
How to extract latest/recent partition from the list of year month day partition columns
I have used show partitions in spark sql which gives me the following:

```<code>year=2019/month=1/day=21
year=2019/month=1/day=22
year=2019/month=1/day=23
year=2019/month=1/day=24
year=2019/month=1/day=25
year=2019/month=1/day=26
year=2019/month=2/day=27
</code>```

I need to extract latest partition

I need to the year, month and day separately so I can use it in another dataframe as variables. I.e:

```<code>part_year=2019
part_month=1
part_day=29
</code>```

I have used:

```<code>val overwrite2 = overwrite.select(col("partition",8,8) as year
</code>```

from which I get

```<code>2019/month
</code>```

For removing this I use another dataframe where I use regex_replace to replace month with blank so another dataframe is created.

This is in turn creating a lot of overhead. What I want is for all these steps to be done in one dataframe so I can get the resultant dataframe as:

```<code>part_year=2019
part_month=2
part_day=27
</code>```

with latest partition being picked up.

答:
Question : How to extract latest/recent partition from the list of year month day
  partition columns

1) I need to extract latest partition.

2) I need to the year, month and day separately so I can use it in
  another dataframe as  variables.

Since final goal is to get latest/recent partition... You can use joda api DateTime  by sorting with isAfter to get latest partition like given as below example.

After spark.sql(s"show Partitions $yourtablename") you will get a dataframe collect that since its small data no issue.

once you collect the dataframe partitions you will get an array like this

```<code>       val x = Array(
    "year=2019/month=1/day=21",
    "year=2019/month=1/day=22",
    "year=2019/month=1/day=23",
    "year=2019/month=1/day=24",
    "year=2019/month=1/day=25",
    "year=2019/month=1/day=26",
    "year=2019/month=2/day=27"
  )
  val finalPartitions = listKeys()

  import org.joda.time.DateTime

  def listKeys(): Seq[Map[String, DateTime]] = {
    val keys: Seq[DateTime] = x.map(row => {
      println(s" Identified Key: ${row.toString()}")
      DateTime.parse(row.replaceAll("/", "")
        .replaceAll("year=", "")
        .replaceAll("month=", "-")
        .replaceAll("day=", "-")
      )
    })
      .toSeq
    println(keys)
    println(s"Fetched ${keys.size} ")
    val myPartitions: Seq[Map[String, DateTime]] = keys.map(key => Map("businessdate" -> key))

    myPartitions
  }
  val mapWithMostRecentBusinessDate = finalPartitions.sortWith(
    (a, b) => a("businessdate").isAfter(b("businessdate"))
  ).head

  println(mapWithMostRecentBusinessDate)
  val latest: Option[DateTime] = mapWithMostRecentBusinessDate.get("businessdate")
  val year = latest.get.getYear();
  val month = latest.get.getMonthOfYear();
  val day = latest.get.getDayOfMonth();
  println("latest year "+ year + "  latest month " + month + "  latest day  " + day)
</code>```

Final result : i.e. your most recent date is 2019-02-27 now based on this you can query hive data in an optimized way.

```<code> Identified Key: year=2019/month=1/day=22
 Identified Key: year=2019/month=1/day=23
 Identified Key: year=2019/month=1/day=24
 Identified Key: year=2019/month=1/day=25
 Identified Key: year=2019/month=1/day=26
 Identified Key: year=2019/month=2/day=27
WrappedArray(2019-01-21T00:00:00.000-06:00, 2019-01-22T00:00:00.000-06:00, 2019-01-23T00:00:00.000-06:00, 2019-01-24T00:00:00.000-06:00, 2019-01-25T00:00:00.000-06:00, 2019-01-26T00:00:00.000-06:00, 2019-02-27T00:00:00.000-06:00)
Fetched 7
Map(businessdate -> 2019-02-27T00:00:00.000-06:00)
latest year 2019  latest month 2  latest day  27
</code>```

Body:
I have used show partitions in spark sql which gives me the following:

year=2019/month=1/day=21
year=2019/month=1/day=22
year=2019/month=1/day=23
year=2019/month=1/day=24
year=2019/month=1/day=25
year=2019/month=1/day=26
year=2019/month=2/day=27

I need to extract latest partition

I need to the year, month and day separately so I can use it in another dataframe as variables. I.e:

part_year=2019
part_month=1
part_day=29

I have used:

val overwrite2 = overwrite.select(col("partition",8,8) as year

from which I get

2019/month

For removing this I use another dataframe where I use regex_replace to replace month with blank so another dataframe is created.

This is in turn creating a lot of overhead. What I want is for all these steps to be done in one dataframe so I can get the resultant dataframe as:

part_year=2019
part_month=2
part_day=27

with latest partition being picked up.

Body:
Question : How to extract latest/recent partition from the list of year month day
  partition columns

1) I need to extract latest partition.

2) I need to the year, month and day separately so I can use it in
  another dataframe as  variables.

Since final goal is to get latest/recent partition... You can use joda api DateTime  by sorting with isAfter to get latest partition like given as below example.

After spark.sql(s"show Partitions $yourtablename") you will get a dataframe collect that since its small data no issue.

once you collect the dataframe partitions you will get an array like this

       val x = Array(
    "year=2019/month=1/day=21",
    "year=2019/month=1/day=22",
    "year=2019/month=1/day=23",
    "year=2019/month=1/day=24",
    "year=2019/month=1/day=25",
    "year=2019/month=1/day=26",
    "year=2019/month=2/day=27"
  )
  val finalPartitions = listKeys()

  import org.joda.time.DateTime

  def listKeys(): Seq[Map[String, DateTime]] = {
    val keys: Seq[DateTime] = x.map(row => {
      println(s" Identified Key: ${row.toString()}")
      DateTime.parse(row.replaceAll("/", "")
        .replaceAll("year=", "")
        .replaceAll("month=", "-")
        .replaceAll("day=", "-")
      )
    })
      .toSeq
    println(keys)
    println(s"Fetched ${keys.size} ")
    val myPartitions: Seq[Map[String, DateTime]] = keys.map(key => Map("businessdate" -> key))

    myPartitions
  }
  val mapWithMostRecentBusinessDate = finalPartitions.sortWith(
    (a, b) => a("businessdate").isAfter(b("businessdate"))
  ).head

  println(mapWithMostRecentBusinessDate)
  val latest: Option[DateTime] = mapWithMostRecentBusinessDate.get("businessdate")
  val year = latest.get.getYear();
  val month = latest.get.getMonthOfYear();
  val day = latest.get.getDayOfMonth();
  println("latest year "+ year + "  latest month " + month + "  latest day  " + day)

Final result : i.e. your most recent date is 2019-02-27 now based on this you can query hive data in an optimized way.

 Identified Key: year=2019/month=1/day=22
 Identified Key: year=2019/month=1/day=23
 Identified Key: year=2019/month=1/day=24
 Identified Key: year=2019/month=1/day=25
 Identified Key: year=2019/month=1/day=26
 Identified Key: year=2019/month=2/day=27
WrappedArray(2019-01-21T00:00:00.000-06:00, 2019-01-22T00:00:00.000-06:00, 2019-01-23T00:00:00.000-06:00, 2019-01-24T00:00:00.000-06:00, 2019-01-25T00:00:00.000-06:00, 2019-01-26T00:00:00.000-06:00, 2019-02-27T00:00:00.000-06:00)
Fetched 7
Map(businessdate -> 2019-02-27T00:00:00.000-06:00)
latest year 2019  latest month 2  latest day  27


问:
Merging a tensor of 3x10 to 1x10, what methods to use?
I have made some model that in the end will output a tensor of 3 x 10. The reason why it's 3 x 10 is because the vocabulary size is 10, and there are 3 elements in a sequence (this is a sequence multilabel classification problem). This tensor will need to somehow be softmaxed to a 1x10 tensor. Can someone give me explanations about the methods that are available and maybe some example in Keras?

I saw some merging methods in Keras like average or add. Those can be useful in this case but those seems to need two or more tensors as the input. Therefore I probably need to split the 3 x 10 tensor to 3 tensors 1 x 10 each and average them. Maybe there are better ways to achieve this?

答:
A simple way to achieve what you want is to use a final 1x1 Convolution layer.

A layer with 1×1 convolution kernel allow to merge your 3x10 tensor into a 1x10, and
simultaneously learns the fusion weight during training.

Add this layer :

```<code>   output = Conv2D(1, (1, 1), activation='your_activation')(your_3x10_tensor)
</code>```

Hope this is the solution you were looking for !

Body:
A simple way to achieve what you want is to use a final 1x1 Convolution layer.

A layer with 1×1 convolution kernel allow to merge your 3x10 tensor into a 1x10, and
simultaneously learns the fusion weight during training.

Add this layer :

   output = Conv2D(1, (1, 1), activation='your_activation')(your_3x10_tensor)

Hope this is the solution you were looking for !


问:
How can I set vendor email notification recipients in WooCommerce to the vendor email and not the administrator email?
The email settings in WooCommerce list the WordPress administrator email address and I need the email to go from the customer to the vendor, not to the administrator. Can anyone please assist? Thank you.</p>

答: You may need to modify the WooCommerce email function to send that e-mail to the vendor e-mail. If you check dokan_wc_email_recipient_add_seller in dokan-lite/include/functions.php then you will see that Dokan is adding vendor e-mail with the admin e-mail to send new-order email to the vendor. Similarly, you have to do this for other email notification.


问:
Eclipse can't find Maven dependency package
In Eclipse, I created a project using Maven and added pdfbox as a dependency. Eclipse automatically rebuilt the project, and I see pdfbox-2.0.11.jar in Maven Dependencies in the package explorer.

However, in my main Java file where I intend to use this:

```<code>package my.group.project;
import org.apache.pdfbox.pdmodel.PDDocument;
</code>```

Eclipse tells me "The import org cannot be resolved."

What do I do?

My pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>my.group</groupId>
  <artifactId>project</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>invoices</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>10</maven.compiler.source>
    <maven.compiler.target>10</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.11</version>
    </dependency>
  </dependencies>
</project>
</code>```

答: Maybe I have luck, but for me it worked just close and open the project (right click menu on project)</p>

Body:
In Eclipse, I created a project using Maven and added pdfbox as a dependency. Eclipse automatically rebuilt the project, and I see pdfbox-2.0.11.jar in Maven Dependencies in the package explorer.

However, in my main Java file where I intend to use this:

package my.group.project;
import org.apache.pdfbox.pdmodel.PDDocument;

Eclipse tells me "The import org cannot be resolved."

What do I do?

My pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>my.group</groupId>
  <artifactId>project</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>invoices</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>10</maven.compiler.source>
    <maven.compiler.target>10</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.pdfbox</groupId>
        <artifactId>pdfbox</artifactId>
        <version>2.0.11</version>
    </dependency>
  </dependencies>
</project>


问:
Getting temporary AWS credentials using Java SDK2
The AWS documentation seems still to refer to AWS Java SDK1 with regard to STS / assume role authentication.

If I have:

AWS Java SDK2 (v.2.5.49)

role-arn

external-id

..is there a way to create with those:

accessKey

secretKey

sessionToken

答:
One should use StsAssumeRoleCredentialsProvider that does the refreshing of temporary tokens for you.

```<code>def apply(roleArn: String, externalId: String, expires: FiniteDuration, sessionName: String): StsAssumeRoleCredentialsProvider = {
    val durationSecs: Int = expires.toSeconds.toInt

    val stsClient: StsClient = StsClient.builder.build()

    val req: AssumeRoleRequest = AssumeRoleRequest.builder
      .roleArn(roleArn)
      .externalId(externalId)
      .durationSeconds(durationSecs)
      .roleSessionName(sessionName)
      .build()

    StsAssumeRoleCredentialsProvider.builder
      .stsClient(stsClient)
      .refreshRequest(req)
      .build()
  }
</code>```

Note that when calling .resolveCredentials() the AWS SDK 2 returns an AwsCredentials that does not provide the session token. The returned value can just be casted to AwsSessionCredentials which provides all the three.

```<code>val prov: AwsCredentialsProvider = ???
val creds: AwsSessionCredentials = prov.resolveCredentials().asInstanceOf[AwsSessionCredentials]
</code>```

Body:
One should use StsAssumeRoleCredentialsProvider that does the refreshing of temporary tokens for you.

def apply(roleArn: String, externalId: String, expires: FiniteDuration, sessionName: String): StsAssumeRoleCredentialsProvider = {
    val durationSecs: Int = expires.toSeconds.toInt

    val stsClient: StsClient = StsClient.builder.build()

    val req: AssumeRoleRequest = AssumeRoleRequest.builder
      .roleArn(roleArn)
      .externalId(externalId)
      .durationSeconds(durationSecs)
      .roleSessionName(sessionName)
      .build()

    StsAssumeRoleCredentialsProvider.builder
      .stsClient(stsClient)
      .refreshRequest(req)
      .build()
  }

Note that when calling .resolveCredentials() the AWS SDK 2 returns an AwsCredentials that does not provide the session token. The returned value can just be casted to AwsSessionCredentials which provides all the three.

val prov: AwsCredentialsProvider = ???
val creds: AwsSessionCredentials = prov.resolveCredentials().asInstanceOf[AwsSessionCredentials]


问:
How to fix 'tableview cellforrowat not called?'
I'm setting up a tableview with customtableview cell, but when i run the app, the data is not shown.

I already check all the connection, identifier, class name, etc

import UIKit

class ViewController: UITableViewController {
    @IBOutlet var testingTableView: UITableView!
    var data = ["Indomie","Kacang Tanah","Soya"]
    override func viewDidLoad() {
        super.viewDidLoad()

        testingTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = testingTableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customTableViewCell
        cell.customLabel.text = data[indexPath.row]
        return cell
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
}
```

This is my code for the table view, it's should call the cellforrowat but it's not

答:
You are using the wrong API, numberOfSections returns the number of sections but you have to return the number of rows

```<code>override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { {
    return data.count
}
</code>```

There is no need to override numberOfRowsInSection, the default value is 1.

And delete

```<code>@IBOutlet var testingTableView: UITableView!
</code>```

There is an implicit tableView property of UITableViewController

Body:
I'm setting up a tableview with customtableview cell, but when i run the app, the data is not shown.

I already check all the connection, identifier, class name, etc

import UIKit

class ViewController: UITableViewController {
    @IBOutlet var testingTableView: UITableView!
    var data = ["Indomie","Kacang Tanah","Soya"]
    override func viewDidLoad() {
        super.viewDidLoad()

        testingTableView.register(UINib(nibName: "TableViewCell", bundle: nil), forCellReuseIdentifier: "customCell")
        // Do any additional setup after loading the view.
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = testingTableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! customTableViewCell
        cell.customLabel.text = data[indexPath.row]
        return cell
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return data.count
    }
}

This is my code for the table view, it's should call the cellforrowat but it's not

Body:
You are using the wrong API, numberOfSections returns the number of sections but you have to return the number of rows

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { {
    return data.count
}

There is no need to override numberOfRowsInSection, the default value is 1.

And delete

@IBOutlet var testingTableView: UITableView!

There is an implicit tableView property of UITableViewController