text:
Q: How to use a view controller as a side menu in Swift3 I am trying to implement the side menu in my application programatically. So I have designed a view controller with half of its view as table view. The design as well as coding is done, now i wish to use this view controller as a Side Menu controller. My SideMenu Storyboard is:

Now my code looks like this:
import UIKit

class SideBarViewController: UIViewController {
  @IBOutlet weak var menu: UIView!
  @IBOutlet weak var menuTableView: UITableView!
  var fieldImages = [UIImage]()
  var isFirstSectionHidden: Bool = true
  var isSecondSectionHidden: Bool = true
  var selectedIndex: Int = 0
  var menuTag: Int = 0
  var name = ""
  var email = ""
  var imageURL = ""
  var language = "English"

  var accountNames: [String] = ["My Subscriptions", "My Proposals","My Interests"]
  var languageNames: [String] = ["English", "Arabic", "Malayalam"]
    override func viewDidLoad() {
        super.viewDidLoad()
      selectedIndex = -1
      self.menu.isHidden = true
      menuTag = 0
     // self.profile()
      let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
      swipeRight.direction = UISwipeGestureRecognizerDirection.right
      self.view.addGestureRecognizer(swipeRight)

      let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(self.respondToSwipeGesture))
      swipeLeft.direction = UISwipeGestureRecognizerDirection.left
      self.view.addGestureRecognizer(swipeLeft)
      self.fieldImages.append(UIImage(named: "my_subscription_icon")!)
      self.fieldImages.append(UIImage(named: "my_proposal_icon")!)
      self.fieldImages.append(UIImage(named: "my_interest_icon")!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
  func respondToSwipeGesture(gesture: UIGestureRecognizer) {
  if let swipeGesture = gesture as? UISwipeGestureRecognizer {
  switch swipeGesture.direction {
  case UISwipeGestureRecognizerDirection.right:
    menuAction()
  print("Swiped right")
  case UISwipeGestureRecognizerDirection.left:
    menuAction()
  print("Swiped left")
  default:
  break
  }
  }
  }
  func menuAction() {
    if menuTag == 0 {
      UIView.animate(withDuration: 0.5, animations: {() -> Void in
        self.menu.frame = CGRect(x: 0, y: 0, width: self.menu.frame.size.width, height: self.menu.frame.size.height)
        self.menu.isHidden = false
        self.menuTag = 1
        self.menuTableView.reloadData()
      })
    }
    else {
      UIView.animate(withDuration: 0.5, animations: {() -> Void in
        self.menu.frame = CGRect(x: -self.menu.frame.size.width, y: 0, width: self.menu.frame.size.width, height: self.menu.frame.size.height)
          self.menu.isHidden = true
        self.menuTag = 0
        self.menuTableView.reloadData()
      })
      selectedIndex = -1

    }
  }
  func profile() {
    if Utility.isConnectedToInternet {
      Utility.startActivityIdicator()
      VanpoolAPI.profile { (response) in
        Utility.stopActivityIndicator()
        if response == nil {
          Utility.showAlert(title: Constants.error, message: Constants.someThingWrong, delegate: self)
        } else {
          if response?.status == ResponseCode.success.code {
            self.name = (response?.name)!
            self.email = (response?.email)!
            self.imageURL = (response?.displayPictureUrl)!
          } else {
            Utility.showAlert(title:Constants.appName, message:response?.message?.key ?? "", delegate: self)
          }
        }
      }
    } else {
      Utility.showAlert(title: Constants.appName, message: Constants.noNetwork, delegate: self)
    }
  }
  func logout() {
    if Utility.isConnectedToInternet {
      Utility.startActivityIdicator()
      VanpoolAPI.logout { (response) in
        Utility.stopActivityIndicator()
        if response == nil {
          Utility.showAlert(title: Constants.error, message: Constants.someThingWrong, delegate: self)
        } else {
          if response?.status == ResponseCode.success.code {
          } else {
            Utility.showAlert(title:Constants.appName, message:response?.message?.key ?? "", delegate: self)
          }
        }
      }
    } else {
      Utility.showAlert(title: Constants.appName, message: Constants.noNetwork, delegate: self)
    }
  }

    /*
    // MARK: - Navigation

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

}
extension SideBarViewController: UITableViewDelegate, UITableViewDataSource {

  func numberOfSections(in tableView: UITableView) -> Int {
  return 11
  }
  // number of rows in table view
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
      return 1
    } else if selectedIndex == section {
      return 3
    } else {
      return 0
    }
}
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell = UITableViewCell()
    switch indexPath.section {
    case 0:

  let cellProfile = (menuTableView.dequeueReusableCell(withIdentifier:"profileCell", for: indexPath)as? MenuTableViewCell)!
   cellProfile.profile.layer.masksToBounds = false
   cellProfile.profile.layer.cornerRadius = cellProfile.profile.frame.height/2
   cellProfile.profile.clipsToBounds = true
   cellProfile.name.text = self.name
   cellProfile.email.text = self.email
   cell = cellProfile
    case 3:
  let cellAccount = (menuTableView.dequeueReusableCell(withIdentifier:"accountCell", for: indexPath)as? MenuAccountTableViewCell)!
   cellAccount.title.text = accountNames[indexPath.row]
  cellAccount.icon.image = fieldImages[indexPath.row]
      cell = cellAccount
    case 5:
  let cellLanguage = (menuTableView.dequeueReusableCell(withIdentifier:"languageCell", for: indexPath)as? MenuLanguageTableViewCell)!
  cellLanguage.languageLabel.text = languageNames[indexPath.row]
    cell = cellLanguage
    default:
      print("Something else")

    }
    return cell
  }
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.section {
    case 5:
     let currentCell = tableView.cellForRow(at: indexPath) as? MenuLanguageTableViewCell
     language = (currentCell?.languageLabel.text)!
     selectedIndex = -1
     isSecondSectionHidden = true
     menuTableView.reloadData()
    default:
      print("Something else")
    }
  }
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.section == 0 {
      return 180
    } else if indexPath.section == 3||indexPath.section == 5 {
      return 40
    }
    return 0
  }

  func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if section == 0 {
      return 0
    }
   return 50
  }

  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
      let headerView = UIView(frame: CGRect(x: 0, y: 0, width: menuTableView.frame.size.width, height: 40))
    let headerImage = UIImageView()
    headerImage.frame = CGRect(x: 15, y: 15, width: 12, height: 12)
    let headerLbl = UILabel()
    headerLbl.frame = CGRect(x: headerImage.frame.origin.x + headerImage.frame.size.width + 20, y: 10, width:menuTableView.frame.size.width - 40, height: 20)
    headerLbl.font = UIFont().robotoLight(withFontSize: 9)
    headerLbl.textColor = CustomColor.menuGrey.color
    let arrowImage = UIImageView()
    arrowImage.isHidden = true
    switch section {
    case 1:
    headerImage.image = UIImage(named: "home_icon")
    headerLbl.text = "Home"
    case 2:
    headerImage.image = UIImage(named: "my_Id_icon")
    headerLbl.text = "My ID"
    case 3:
    headerImage.image = UIImage(named: "my_interest_icon")
    headerLbl.text = "My Account"
    arrowImage.isHidden = false
    if isFirstSectionHidden {
      arrowImage.frame = CGRect(x: menuTableView.frame.size.width - 30, y: 15, width: 3, height: 5)
      arrowImage.image = UIImage(named: "side_arrow")
    } else {
       arrowImage.frame = CGRect(x: menuTableView.frame.size.width - 30, y: 15, width: 5, height: 3)
    arrowImage.image = UIImage(named: "down_arrow")
      }
    case 4:
    headerImage.image = UIImage(named: "my_profile_icon")
    headerLbl.text = "My Profile"
    case 5:
    headerImage.image = UIImage(named: "language_icon")
    headerLbl.text = language
    arrowImage.isHidden = false
    if isSecondSectionHidden {
      arrowImage.frame = CGRect(x: menuTableView.frame.size.width - 30, y: 15, width: 3, height: 5)
      arrowImage.image = UIImage(named: "side_arrow")
    } else {
      arrowImage.frame = CGRect(x: menuTableView.frame.size.width - 30, y: 15, width: 5, height: 3)
      arrowImage.image = UIImage(named: "down_arrow")
      }

    case 6:
    headerImage.image = UIImage(named: "notification_icon")
    headerLbl.text = "Notifications"
    case 7:
    headerImage.image = UIImage(named: "about_us_icon")
    headerLbl.text = "About Us"
    case 8:
    headerImage.image = UIImage(named: "faq_icon")
    headerLbl.text = "FAQ"
    case 9:
    headerImage.image = UIImage(named: "contact_us_icon")
    headerLbl.text = "Contact Us"
    case 10:
    headerImage.image = UIImage(named: "logout_icon")
    headerLbl.text = "Logout"
    default:
      print("Something else")

    }
      let headerClick = UIButton(type: .custom)
      headerClick.addTarget(self, action: #selector(self.headerAction), for: .touchUpInside)
      headerClick.frame = CGRect(x: 0, y: 0, width: menuTableView.frame.size.width, height: 40)
      headerClick.tag = section
      headerClick.backgroundColor = UIColor.clear
    headerView.addSubview(arrowImage)
    headerView.addSubview(headerLbl)
    headerView.addSubview(headerImage)
    headerView.addSubview(headerClick)
    return headerView
  }
  func headerAction(_ sender: UIButton) {
    if sender.tag == 3 {
      if isFirstSectionHidden  {
        selectedIndex = Int(sender.tag)
        isFirstSectionHidden = false
        isSecondSectionHidden  = true
      } else {
        selectedIndex = -1
        isFirstSectionHidden  = true

      }
    }else if sender.tag == 5 {
        if isSecondSectionHidden  {
          selectedIndex = Int(sender.tag)
          isSecondSectionHidden = false
          isFirstSectionHidden = true
        } else {
          selectedIndex = -1
          isSecondSectionHidden = true
        }
    } else {
    selectedIndex = -1
      isSecondSectionHidden = true
      isFirstSectionHidden = true
    }
     menuTableView.reloadData()
  }
}

Any idea how to do this view controller as my side view controller programatically. Note, i am trying to avoid the third party classes at the best.

A: Simple you can do is
Now
1. In Base View Controller add a container view. Add Side View Controller to container view via segue
2. Make Container view width 275 or as per requirement.
3. Add constraints to container view trailing (assuming side menu right side of view), top , bottom and constant width.
4. Now create outlet of trailing constraint in view and toggle its constant value -275 to hide and 0 to show.
P.S. I have sample project also https://drive.google.com/open?id=0ByCC2aGldkpUVU0xUkd5bTRCNzQ


text:
Q: Передача аргументов методу При передаче объекта в качестве параметра методу ссылка должна копироваться. Тогда почему вывод 0 9 9, а не 9 9 9? Получается, s1 и s2 ссылаются на разные объекты?
public class Main {

    public static void main(String[] args) {
        Integer s = 0;
        foo(s, s = 9);
        System.out.println(s);
    }

    static void foo(Integer s1, Integer s2) {
        System.out.println(s1);
        System.out.println(s2);
    }
}

A: Параметры вычисляются слева направо, и поэтому s1 и s2 ссылаются на разные объекты. Если вы напишите
foo(s = 9, s);

То получите 9 9 9. Так как в этом случае операция = выполнится перед вычислением второго параметра. Ваш код равнозначен (за исключением того, что никаких новых переменных нет):
Integer s = 0;
// "раскрыл скобки" для foo(s, s = 9);
Integer old_s = s;
s = 9;
foo(old_s, s);
// "раскрыл скобки"
System.out.println(s);

A: Это происходит потому, что вы - сначала отправляете в первый аргумент, а во втором вы переопределяете переменную на 9.
Одну и туже переменную вы, можете переопределять неограниченное кол.-во раз, только в том случае, если она не final.
Integer i = 1;
i = i * 2;
i = i + i;
i-=1;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Проблема с SDL в C++ Изучаю SDL, и сейчас встретился с проблемой.
Использую пример кода с сайта:
#include <iostream>
#include <SDL.h>

int main(int argc, char* argv[])
{

    if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
    {
        std::cout << "SDL initialization failed. SDL Error: " << SDL_GetError();
    }
    else
    {
        std::cout << "SDL initialization succeeded!";
    }

    std::cin.get();
    return 0;
}

В свойствах проекта всё установлено правильно, все нужные библиотеки установлены. SDL2.dll находится в одной папке с exe-шником, но при запуске появляется данная ошибка:

"Project3.exe" (Win32). Загружено "D:\C++
  Projects\Project3\Debug\Project3.exe". Символы загружены.
"Project3.exe" (Win32). Загружено "C:\Windows\SysWOW64\ntdll.dll".
"Project3.exe" (Win32). Загружено "C:\Windows\SysWOW64\kernel32.dll".
"Project3.exe" (Win32). Загружено
  "C:\Windows\SysWOW64\KernelBase.dll".
"Project3.exe" (Win32). Загружено "C:\Program Files\AVAST
  Software\Avast\x86\aswhook.dll".
Поток 0x3a0 завершился с кодом -1073741701 (0xc000007b).
Программа "[8024] Project3.exe" завершилась с кодом -1073741701
  (0xc000007b).

В чем проблема?
Скрины настроек проекта:

A: В итоге я просто посмотрел первое попавшееся видио на Ютубе. Всё дело действительно оказалось в файле SDL2.dll. Вероятнее всего я скопировал файл для 64 битной разрядности, и по этому программа не работала. Если что то вот то видео: https://www.youtube.com/watch?v=Sfn7yOiwJLw


text:
Q: Cannot use imported classes methods with cocos2d There is a problem, I just installed cocos2d for iPhone.
The first problem was that it wasn't recognizing any header like CCDirectory.h for example.
So I turned on user search paths in the project, but this way I could just import the header and have an object pointer without getting any warning, but methods aren't recognized.
It's hard to explain, so see this code:
Header:
#import <UIKit/UIKit.h>
#import <CCMenuItem.h>
#import <cocos2d.h>

Inside applicationDidFinishLaunching:
CCMenuItem* item; // This does not give a warning, except for the "unused variable"
                  // But the class is recognized

[CCMenuItem setFontName: @""]; // Warning

The warning is:
Class method '+setFontName:' not found (return type default to 'id')

And it doesn't recognize any other method, just NSObject's methods.

A: Are you sure the methods you are calling exists in that class? CCMenuItem doesn't contain a static method named setFontName. Try changing CCMenuItem to CCMenuItemFont.
[CCMenuItemFont setFontName: @""];


text:
Q: Reference current value of property before ON MATCH SET within neo4j query For the app I am building, users can rate each other after each phone call (similar to Whatsapp). For the algorithm I am implementing, User A's average rating should be updated such that it equals the average of all the other users' average ratings of User A. For example, if there are 3 users and both User B and User C have rated User A, then I want to calculate User A's average rating as follows:
((User B's average rating of User A) + (User C's average rating of User A)) / 2

This is my query:
MATCH (u1:User { userId: $userId })-[r1:PARTICIPANT]-(c:Chat { roomId: $roomId })-[r2:PARTICIPANT]-(u2:User)
WHERE (r1.participantDuration > 0) AND (r2.participantDuration > 0)
SET r1.rating = $rating
MERGE (u1)-[r3:REVIEW]->(u2)
ON CREATE SET
    r3.ratingCount = 1,
    r3.averageRating = $rating,
    u2.averageRating = ((u2.averageRating * u2.uniqueRatingCount) + $rating) / (u2.uniqueRatingCount + 1),
    u2.uniqueRatingCount = u2.uniqueRatingCount + 1
ON MATCH WITH r3.averageRating AS oldAverage, r3.ratingCount AS oldCount SET
    r3.averageRating = ((oldAverage * oldCount) + $rating) / (oldCount + 1),
    r3.ratingCount = oldCount + 1,
    u2.averageRating = u2.averageRating + ((r3.averageRating - oldAverage) / u2.uniqueRatingCount)
RETURN u2 { .averageRating }

I am having an issue with capturing the previous state of averageRating and ratingCount before ON MATCH SET gets executed. I think I am getting an error because neo4j does not allow a WITH clause after ON MATCH.
Also, is there a better way to approach this query that may be more performant and hopefully more readable?

A: You can use the old values by just referencing them
MATCH (u1:User { userId: $userId })-[r1:PARTICIPANT]-(c:Chat { roomId: $roomId })-[r2:PARTICIPANT]-(u2:User)
WHERE (r1.participantDuration > 0) AND (r2.participantDuration > 0)
SET r1.rating = $rating
MERGE (u1)-[r3:REVIEW]->(u2)
ON CREATE SET
    r3.ratingCount = 1,
    r3.averageRating = $rating,
    u2.averageRating = ((u2.averageRating * u2.uniqueRatingCount) + $rating) / (u2.uniqueRatingCount + 1),
    u2.uniqueRatingCount = u2.uniqueRatingCount + 1
ON MATCH SET
    r3.averageRating = ((r3.averageRating *  r3.ratingCount) + $rating) / ( r3.ratingCount + 1),
    r3.ratingCount = oldCount + 1,
    u2.averageRating = u2.averageRating + ((r3.averageRating - r3.averageRating) / u2.uniqueRatingCount)
RETURN u2 { .averageRating }


text:
Q: Google Apps Add editors folder I have a list of email user in Listvalideur[]. I have created a folder.

*

*How can I add editor right to the new folder with this Listvalideur? These few lines don't work:
var folder = optFolder.createFolder(folderName);
for (var i=0; i<Listvalideur.length; i++) {
    folder.addEditor(Listvalideur[i][0]);
}

*Can you also give me the syntax for folder.addeditors methods? These 2 syntaxs don't work:
folder.addEditors('xxx1.yyy1@vvv.com','xxx2.yyyy2@vvv.com');
folder.addEditors('xxx1.yyy1@vvv.com,xxx2.yyyy2@vvv.com');

Thanks a lot
Thks for your answer.
In fact my array is only one dimension Listvalideur[i]. I get this variable from a spreadsheet sheet Call $ListValideur
   |       A
1  |  email1@etc
2  |  email2@example

I use this syntax to read and set a array call listvalideur[]
var Listvalideur = SpreadsheetApp.openById(sskeyTable)
     .getSheetByName('$ListValideur')
     .getDataRange()
     .getValues();

Now I want to Add all email user from my array listvalideur[] to acces to a folder.
I try this syntax without manage :
var folder = optFolder.createFolder(folderName);
folder.addEditors(ListValideur[]);

A: *

*In your question you say that you have a list of emails in Listvalideur variable. Is it really a one dimension array (e.g. a list) or a matrix? Because on your code you write Listvalideur[i][0]. Try Listvalideur[i] only. Or show us how you get/create this variable. The rest of the code looks fine.

*You need to pass an array of emails, e.g. (notice the brackets)
folder.addEditors(['email1@etc', 'email2@example']);


text:
Q: Seeking from end of file throwing unsupported exception I have this code snippet and I'm trying to seek backwards from the end of file using python:
f=open('D:\SGStat.txt','a');
    f.seek(0,2)
    f.seek(-3,2)

This throws the following exception while running:
f.seek(-3,2)
io.UnsupportedOperation: can't do nonzero end-relative seeks

Am i missing something here?

A: From the documentation for Python 3.2 and up:

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)).

This is because text files do not have a 1-to-1 correspondence between encoded bytes and the characters they represent, so seek can't tell where to jump to in the file to move by a certain number of characters.
If your program is okay with working in terms of raw bytes, you can change your program to read:
f = open('D:\SGStat.txt', 'ab')
f.seek(-3, 2)

Note the b in the mode string, for a binary file. (Also note the removal of the redundant f.seek(0, 2) call.)
However, you should be aware that adding the b flag when you are reading or writing text can have unintended consequences (with multibyte encoding for example), and in fact changes the type of data read or written.

A: The existing answers do answer the question, but provide no solution.
As pointed out in the comments, this answer is based on undefined behavior and does not handle UnicodeDecodeError, which you may encounter with UTF-8 files. It works fine with ASCII and other fixed-width encodings as long as you seek to the beginning of a character. Please see Philip's answer which includes a workaround and further comments discussing why seeking backwards in UTF-8 is a problem.
From readthedocs:

If the file is opened in text mode (without b), only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

This is supported by the documentation, which says that:

In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file [os.SEEK_SET] are allowed...

This means if you have this code from old Python:
f.seek(-1, 1)   # seek -1 from current position

it would look like this in Python 3:
f.seek(f.tell() - 1, os.SEEK_SET)   # os.SEEK_SET == 0

Solution Putting this information together we can achieve the goal of the OP:
f.seek(0, os.SEEK_END)              # seek to end of file; f.seek(0, 2) is legal
f.seek(f.tell() - 3, os.SEEK_SET)   # go backwards 3 bytes

A: Eric Lindsey's answer does not work because UTF-8 files can have more than one byte per character.  Worse, for those of us who speak English as a first language and work with English only files, it might work just long enough to get out into production code and really break things.

The following answer is based on undefined behavior
... but it does work for now for UTF-8 in Python 3.7.
To seek backwards through a file in text mode, you can do so as long as you correctly handle the UnicodeDecodeError caused by seeking to a byte which is not the start of a UTF-8 Character.  Since we are seeking backwards we can simply seek back an extra byte until we find the start of the character.
The result of f.tell() is still the byte position in the file for UTF-8 files, at-least for now. So an f.seek() to an invalid offset will raise a UnicodeDecodeError when you subsequently f.read() and this can be corrected by f.seek() again to a different offset. At least this works for now.
Eg, seeking to the beginning of a line (just after the \n):
pos = f.tell() - 1
if pos < 0:
    pos = 0
f.seek(pos, os.SEEK_SET)
while pos > 0:
    try:
        character = f.read(1)
        if character == '\n':
            break
    except UnicodeDecodeError:
        pass
    pos -= 1
    f.seek(pos, os.SEEK_SET)

A: In order to use seek from current position and end you have to open the text file in binary mode. See this example where I have created a file "nums.txt" and have put "ABCDEFGHIJKLMNOPQRSTUVWXYZ" in the file. I read the letters of the string "PYTHON" from the file and display the same. See the code I've run in python 3.6 windows in anaconda 4.2
    >>> file=open('nums.txt','rb')
    >>> file.seek(15,0)
    15
    >>> file.read(1).decode('utf-8')
    'P'
    >>> file.seek(8,1)
    24
    >>> file.read(1).decode('utf-8')
    'Y'
    >>> file.seek(-7,2)
    19
    >>> file.read(1).decode('utf-8')
    'T'
    >>> file.seek(7,0)
    7
    >>> file.read(1).decode('utf-8')
    'H'
    >>> file.seek(6,1)
    14
    >>> file.read(1).decode('utf-8')
    'O'
    >>> file.seek(-2,1)
    13
    >>> file.read(1).decode('utf-8')
    'N'


text:
Q: How to fill the black in a black-transparent png in core graphics? I've been stuggling over this for a few hours, to no avail.
I have a PNG of a black shape on a transparent background. I want to fill the black part of the image with another color, and leave the transparent background to be transparent.
How can I do this?


text:
Q: unsigned int data types in c Please help me in differentiating these codes in C:
Code 1:
#include<stdio.h>
#include <stdint.h>

uint8_t fb(int a)
{
    return -3;
}

int main()
{
    int a = fb(-3);
    printf("%d",a);
    return 0;
}

Code 2:
#include<stdio.h>

unsigned int fb(int a)
{
    return -3;
}

int main()
{
    int a = fb(-3);
    printf("%d",a);
    return 0;
}

The problem is the the first code returns 253 as expected but the second code returns -3 which is unexpected as return type is unsigned. Please help me how this is possible?
I have used mingw gcc compiler.

A: In the first program,

*

*When the function returns, int -3 (FFFFFFFD) is cast to uint8_t is 253 (FD). The higher order bytes are dropped so it fits.

*When the assignment is performed, uint8_t 253 (FD) is cast to int by sign extension to 253 (000000FD).

In the second program,

*

*When the function returns, int -3 (FFFFFFFD) cast to unsigned int 4294967293 (FFFFFFFD). No bytes needed to be dropped.

*When the assignment is performed, unsigned int 4294967293 (FFFFFFFD) cast to int is -3 (FFFFFFFD).

Notes:

*

*Assumes 32-bit ints, but it's a similar story with 64-bit ints.

*This is an explanation of what happens for you; it isn't necessarily what the C spec calls to happen.

A: The conversion from signed to unsigned will follow the rules laid out in section 6.3.1.3 Signed and unsigned integers of the draft C99 standard which says:

Otherwise, if the new type is unsigned, the value is converted by
  repeatedly adding or subtracting one more than the maximum value that
  can be represented in the new type until the value is in the range of
  the new type.49)

So this means that -3 will be converted to by adding UMAX +1 to the value. In the case of uint8_t this is a relatively small value 253 which fits into a singed int and therefore is converted to signed int without issue.
In your second case with the return value of unsigned int, we will end up with a rather large value upon conversion, actually std::numeric_limits<unsigned int>::max() + 1 - 3. Which will not fit into an signed int this is overflow and is thus undefined behavior as per section 6.5 paragraph 5 which says:

If an exceptional condition occurs during the evaluation of an
  expression (that is, if the result is not mathematically defined or
  not in the range of representable values for its type), the behavior
  is undefined.

A: The rule for conversion from integral type to an unsigned integral type is simple:
Add/Subtact (Maximum value of target type + 1) as often as needed to fit.
The rule for conversion from integral type to signd integral type is simpler still:
Preserve the value, if out-of-range the conversion is undefined.
Most modern implementations (all on windows platform) define it to add/subtract same constant as for corresponding unsigned type until it fits though.
Using those rules, the conversion on return from fb() in the first example is value-preserving and ok:
-3 -> 256-3 = 253 -> 253
The return in the second example is out-of-range and thus undefined behavior, though normally:
-3 -> 2CHAR_BIT*sizeof(int)-3 -> -3
Bonus facts:

*

*Passing a variadic function a signed/unsigned type where the corresponding other one was expected is allowed, though the raw value cannot be converted and will just be assumed to be of the indicated type.

*CHAR_BIT is a preprocessor constant giving the number of bits in a byte.

*sizeof is an operator giving the number of bytes in a type / variable.

A: unsigned int should be printed as %u instead of %d


text:
Q: Social graphs using bitsets I came across the following line in an article where this internet technology firm talks about how they baked social features into their application:

Apache Thrift, Krati Data Store, JavaEWAH Compressed Bitmaps and JRuby
  forms the part of our remote service which stores our social graph in
  high-performing persistent compressed bitmap format.

I am trying to make sense out of this. Till now I have figured out what is meant by Apache Thift (and why it is to be used), JavaEWAH, bit sets, social graph and GUI analysis. Krati Data source does not seem to have a good wiki/tutorial for itself. Furthermore I cannot understand the setup, as to how social graph is being stored and processed using bitsets and the mentioned technology.
If you could explain the same and guide me to relevant resources. Alternatively if you can suggest a better alternative to the stack so described.

A: Ok, let's put some basics upfront:
I guess, your article is that one: http://www.nextbigwhat.com/technology-implementation-for-social-features-297/
http://en.wikipedia.org/wiki/Social_graph
'The social graph in the Internet context is a graph that depicts personal relations of internet users'
http://thrift.apache.org/
combines a software stack with a code generation engine to build services that work efficiently and seamlessly between C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, OCaml and Delphi and other languages.
https://github.com/krati/krati
Krati is a simple persistent data store with very low latency and high throughput. It is designed for easy integration with read-write-intensive applications with little effort in tuning configuration, performance and JVM garbage collection.
http://code.google.com/p/javaewah/
The bit array data structure is implemented in Java as the BitSet class.... JavaEWAH is a word-aligned compressed variant of the Java bitset class.
http://jruby.org/apidocs/serialized-form.html
....
----- Here's are my interpretations:
The context of the article is technology impementation. So they listed everything. In this context I guess we can ignore apache Thrift for now, as this is just the glue, which they use to attach technologies to each other. Also jrubi forms goes somewhat out of scope for the social graph considerations. Yes a social graph needs input and output, but forms addresses the topic which level of details comes from there.
The interesting part is krati and javaewah. Well reading the article makes obvious, that they implement their social graphs via memberships. This can be about groups or roles or something similar. Memberships can be implemented as bitmap: Have a group with a bitmap with one bit per each user. Each Bit can be addressed to check if the user is member or not. As simple as that. The Bitmaps are made up by Krati and than stored in/managed by JavaEWAH.
The cons is: The more users, the bigger does the bitmap go.  The Pro: It is FAST.
In relational databases each relation would be implemented as foreign key 2 foreign key pair (which causes some index overhead >eg. 2 ints for the keys and then 2*2+x ints for the double index, whereby the x debends on the database). Especially with lots of memberships per group this can get a disk space utilization challenge. So I guess in such cases the compressed BitMap is implementation is even better in terms of storage utilization.
UPDATE---
One could write books on the whole topic. I guess I need to make a point here. However good starting points from here are:
http://www.slideshare.net/lemire/all-about-bitmap-indexes-and-sorting-them
https://github.com/jingwei/krati/commit/ab1432003e59a07269d23c1cb307625b0e8c5be2
http://en.wikipedia.org/wiki/Data_store
http://en.wikipedia.org/wiki/Key-value_store (to get an idea about different database concepts than just the relative one)
http://dev.mysql.com/doc/refman/5.0/en/innodb-physical-record.html (to get some indication what about the costs of a foreign key 2 foreign key relation)


text:
Q: Jupyter lab failing to launch I updated my conda environment today. Before, I could launch jupyter lab from the terminal. After the updates (which included installing theano, but I'm guessing that's unrelated), I get the following error that I do not understand:
marcel@flaptop:~$ jupyter lab
Traceback (most recent call last):
File "/home/marcel/anaconda3/bin/jupyter-lab", line 7, in <module> from jupyterlab.labapp import main
File "/home/marcel/anaconda3/lib/python3.6/site-packages/jupyterlab/labapp.py", line 7, in <module> from notebook.notebookapp import NotebookApp, aliases, flags
File "/home/marcel/anaconda3/lib/python3.6/site-packages/notebook/notebookapp.py", line 45, in <module> ioloop.install()
File "/home/marcel/anaconda3/lib/python3.6/site-packages/zmq/eventloop/ioloop.py", line 210, in install assert (not ioloop.IOLoop.initialized()) or  AttributeError: type object 'IOLoop' has no attribute 'initialized'

Does anyone know what is going on here?t

A: Seems to be Tornado version 5. There's discussion here:
Install Jupyter Notebook on Miniconda

pip uninstall tornado
pip install tornado==4.5.3

fixed it for me, as posted in the link above.


text:
Q: Android authorization with Google for my own server So I'll start from the beginning. I want to create an Android application and a server (written in java). The server will be written in Java. What I want to do is to be able to log in to my server from the Android application, using the Google account. After the device is logged in, there will be some information sharing with HTTP Requests. I want to use REST.
How should I proceed for achieving my goal? I guess I should use the Google API and Google App Engine. What should I do to implement the log in and the part in the server. It's first time for me writing a server and an application with log in, so any advises will be appreciated. The application is for educational purposes. Thanks in advance!

A: Use Google Play services (you don't need App Engine).
Here is the complete process with code samples:  Authorizing with Google for REST APIs
Another option you can look at: Google+ Sign-in for Android
On the server side, once you have the auth token, you access the Google REST API with the username and token, and Google will tell you if the access is authorized.
I understand what you're trying to do.  Your user already has a username and credentials on Google, why not just get the username and let Google do all the authentication?
However, you might want to re-think this approach.
The problem is that you will ask your user to sign in to Google and Google will ask the user (through logic in the Android API code) if your application can have access to their information in Google.  Your users may balk at granting that kind of access to your application, and that will hamper your efforts to get people to use your app.
Now, if your app actually uses the Google REST APIs, then this would make more sense, because the auth token your app requests will provide access to a Google API.
But if all you're doing is authenticating, your users might be hesitant to authorize your app for some Google operation they don't think you need.
To get a feel for the OAuth 2.0 message flow, you can use this: OAuth 2.0 Playground

A: I would really suggest you give Google App Engine a try, specially combining it with Cloud endpoints which are designed to connect your server to clients like an Android App. Using endpoints you'll get cloud infrastructure + REST services + native libraries ( for Android, JS and iOS) and everything related to authentication is already sorted out (via OAuth).
App Engine can also be developed using Java and it's already integrated with popular IDEs like Eclipse (through the Google Plugin) and Android Studio (as backend modules) so you prbably have everything you need to star working on your App Engine server.


text:
Q: Difference between Created and Created. in SharePoint REST API Call I call SPO Rest API and in response I found two type of dates. I am not able to find any documentation on their difference especially the one with Dot (.)
Both Dates are shown here
We want to use one with Dot as its in standard format, but not sure about its authenticity. We are using RenderListDataAsStream as end point to get data.
Any documentation of properties coming with Dot(.) will be helpful to understand it. In attached image count is also another same example having dot.
P.S: here are the differnt ways to access them

A: I think the value of the normal named key (like technical field name) represents the value shown in UI to a user. So it is affected by the regional settings of the web.
The value of the additional "."-key (technical field name plus ".") represents the UTC-0 value in ISO format (like the data is stored in DB internaly).
For example:
"Created": "0;#2022-09-07 06:17:37",  // timestamp by Regional Settings
"Created.": "2022-09-07T13:17:37Z",  // UTC-0 in ISO format


text:
Q: I have an error about vue2.js and its router I have a navbar,Home and login elements. It is simple login page. I want to add api to go home and login page. For this i have router.js file. I am sharing all of file here.
This is my Main.js

import Vue from 'vue'
import App from './App.vue'
import useRoute from './router'

Vue.config.productionTip = false

new Vue({
  useRoute,
  render: h => h(App),
}).$mount('#app')

And Router.js

import Vue from 'vue'
import { useRoute } from 'vue-router'
import Home from './components/Home.vue'
import LoginPage from './components/Login.vue'

Vue.use(useRoute)

export default new useRoute({
    routes: [
        { path: '/', component: Home },
        { path: '/login', component: LoginPage }
    ]
})

App.vue

<template>

    <NavBar />

        <router-view />

</template>

And for easy finding i am sharing console error
And also i want to share this information that if i write "/login" or "/" it just going to home page,and nothing changing
vue.runtime.esm.js?c320:4605 [Vue warn]: inject() can only be used inside setup() or functional components.
warn @ vue.runtime.esm.js?c320:4605
vue.runtime.esm.js?c320:4605 [Vue warn]: Unknown custom element: <router-view> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

found in

---> <App> at src/App.vue
       <Root>


text:
Q: JavaMail, no exception is thrown if the receivers mail are wrong This codesnippet, sends a mail:
if (m.send()) {
    Log.i("MAIL SENDER: ", "Succesfully");
    Toast.makeText(getApplicationContext(),
    "The log file has been sent",
    Toast.LENGTH_LONG).show();

} else {

    throw new MailException();
}

If the receivers mail isn't correct, e.g example@gmail.co instead of example@gmail.com the code runs into the first if-block. Why does this happend when the receivers isn't correct. Could anyone help me out here?
The mail settings is retrieved from SharedPreferences, and checked in this method:
public static boolean isValidEmailAddress(String email) {
    boolean result = true;
    try {
        InternetAddress emailAddr = new InternetAddress(email);
        emailAddr.validate();
    } catch (AddressException ex) {
        result = false;
    }
    return result;
}

When the user types in a email address in the textfield and hit Ok this is whats happening:
if (isValidEmailAddress(mail))
            editor.putString("Tomail", mail);
else
    Toast.makeText(getApplicationContext(), "Invalid", Toast.LENGHT_LONG).show();

This will only check if the mail contains a @ and therefor its valid.
In my send method:
public SendMail(Context c) {
    this();

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(c);
    _host = sharedPrefs.getString("host", null);
    _port = sharedPrefs.getString("port", null);
    _sport = sharedPrefs.getString("port", null);
    _user = sharedPrefs.getString("mail", null);
    _pass = sharedPrefs.getString("pw", null);

}

public boolean send() throws Exception {
    Properties props = _setProperties();

    if (!_user.equals("") && !_pass.equals("") && _to.length > 0
            && !_from.equals("") && !_subject.equals("")
            && !_body.equals("")) {

        Session session = Session.getInstance(props,
                new GMailAuthenticator(_user, _pass));

        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(_from));

        InternetAddress[] addressTo = new InternetAddress[_to.length];
        for (int i = 0; i < _to.length; i++) {
            addressTo[i] = new InternetAddress(_to[i]);
        }
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

        msg.setSubject(_subject);
        msg.setSentDate(new Date());

        // setup message body
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(_body);
        _multipart.addBodyPart(messageBodyPart);

        // Put parts in message
        msg.setContent(_multipart);

        // send email
        Transport.send(msg);

        return true;
    } else {
        return false;
    }
}

A: This happens because mail is an asynchronous protocol. Basically, mail isn't delivered to the destination, it's just delivered to your local mail server which does something smart with it. Eventually. In a few hours.
If something is wrong, the sender of the mail will get a mail with the error message, so you better make sure that address is correct.
This means receiver addresses are only checked at a later time. There is no way to validate them. You could do some simple pattern matching validation to check for broken domain names but that will stop working in a few months when the new top level domains become available and I get my digulla@home email address.

A: validate() used in isValidEmailAddress() method follows the syntax rules of RFC822. Unfortunately, "example@gmail.co" is considered a valid mail, thus it returned true. You can check the validity of mail using RFC822 over here.
Documentation: validate() of InternetAddress class

Update: You will have to do additional validation, have a look at http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/


text:
Q: Differentiation of a function defined over $\mathbb{R}^{m^{2}}$ (matrix spaces).
For $1\leq i,j\leq m$, let $f_{ij}:\mathbb{R}^{m^{2}} \to \mathbb{R}$ defined by $f_{ij}(X)V = (X^{2})_{ij}$. For any $X,V \in \mathbb{R}^{m^{2}}$, show that $df_{ij}(X)V$ is the $ij$-th element of the matrix $XV + VX$. Get a similar result with $X^{3}$. Generalize.

I don't want an answer. Actually, I didn't understand how this function works. I would like an explanation to understand this function and a small hint to start solving.

A: Recall the definition of the differential. $df_{ij}(X) : \mathbb{R}^{m^2} \to \mathbb{R}$ is the unique linear map such that
$$\lim_{H \to 0} \frac{\left|f_{ij}(X + H) - f_{ij}(X) - df_{ij}(X)H\right|}{\|H\|} = 0$$
where $\|\cdot\|$ is the euclidean norm on matrices.
It suffices to verify that $V \mapsto (XV + VX)_{ij}$ satisfies the above limit.
\begin{align}
\lim_{H \to 0} \frac{\left|f_{ij}(X + H) - f_{ij}(X) - (XH + HX)_{ij}\right|}{\|H\|} &= \lim_{H \to 0} \frac{\left|((X + H)^2)_{ij} - (X^2)_{ij} - (XH + HX)_{ij}\right|}{\|H\|}\\
 &= \lim_{H \to 0}\frac{\left|(X^2 + XH + HX + H^2)_{ij} - (X^2)_{ij} - (XH + HX)_{ij}\right|}{\|H\|}\\
&= \lim_{H\to 0} \frac{\left|(H^2)_{ij}\right|}{\|H\|}\\
&\le \lim_{H\to 0} \frac{\|H^2\|}{\|H\|}\\
&\le \lim_{H\to 0} \frac{\|H\|^2}{\|H\|}\\
&= \lim_{H\to 0} \|H\|\\
&= 0
\end{align}
Therefore $df_{ij}(X)V = (XV + VX)_{ij}$.

A: We can actually calculate $df_{ij}(X)\cdot V$. Remember that $df_{ij}(X)\cdot V=\langle\text{grad } f_{ij}(X),V\rangle=\dfrac{\partial f_{ij}}{\partial V}(X)$, then
\begin{align*}
df_{ij}(X)\cdot V&=\dfrac{\partial f_{ij}}{\partial V}(X)=\lim_{t\to0}\dfrac{f_{ij}(X+tV)-f_{ij}(X)}{t}\\&=\lim_{t\to0}\dfrac{(X^2+tXV+tVX+t^2V^2)_{ij}-(X^2)_{ij}}{t}\\
&=\lim_{t\to0}\dfrac{t(XV+VX)_{ij}+t^2(V^2)_{ij}}{t}=(XV+VX)_{ij}
\end{align*}
It's analogous for $f_{ij}(X)=(X^3)_{ij}$, you just need to observe that
$$([X+V]^3)_{ij}-(X^3)_{ij}=t(X^2V+XVX+VX^2)_{ij}+t^2(XV^2+VXV+tV^2)_{ij}$$
The geral answer can be found after suspecting for $g_k(X)=X^k$ we have $$dg_k(X)\cdot V=\displaystyle\sum_{i=1}^kX^{i-1}VX^{k-i}$$
Using induction :
\begin{align*}
dg_{k+1}(X)\cdot V=\dfrac{\partial g_{k+1}(X)}{\partial V}&=\dfrac{\partial(XX^k)}{\partial V}=\dfrac{\partial (Xg_k(X))}{\partial V}\\&=\dfrac{\partial X}{\partial V}\cdot g_k(X)+X\dfrac{\partial g_k(X)}{\partial V}\\&=VX^k+Xdg_k(X)\cdot V\\&=VX^k+X\displaystyle\sum_{i=1}^kX^{i-1}VX^{k-i}=\sum_{i=1}^{k+1}X^{i-1}VX^{k+1-i}\end{align*}


text:
Q: Trouble using xmldb:store with collection name with space I cannot seem to get this right. I have a system where the web user is running a jQuery request to add a new document. The code works perfect if the collection they are storing to have no spaces in the name. This code is:
xquery version "3.0";
declare option exist:serialize "method=xhtml media-type=text/html indent=yes";
let $specialty := request:get-parameter("specialty", "")
let $collection := xmldb:encode-uri($specialty)
let $docnum := request:get-parameter("docnum", "")
let $title := request:get-parameter("title", "")
let $file := concat($docnum, '.xml')
let $path := concat($collection, '/', $file)
let $content :=

First Panel

Content goes here

 return
   let $new_article := xmldb:store($collection, $file, $content, 'application/xml')
      return
        let $changepermiss := sm:chmod($new_article, 'rw-rw----')
           return

               {$docnum, ': ', xmldb:decode($title)}

Now, if the collection name that comes from the request contains a space ... like this (after encoding) ... it fails.
"/db/Test/data/Core/Test%20Collection"
The error is:
exerr:ERROR Could not locate collection: /db/Test/data/Core/Test%20Collection
This occurs at this line: xmldb:store($collection, $file, $content, 'application/xml') with $collection not be recognized because of the space.
Now, to test things out, I run this and it is fine.
    xquery version "3.0";
    declare option exist:serialize "method=xhtml media-type=text/html indent=yes";
    let $test := "/db/EIDO/data/Core/Disease%20Prevention"
    let $content :=

First Panel

Content goes here

    return
    let $newdoc := xmldb:store($test, "test.xml", $content, 'application/xml')
    return
        $newdoc

I cannot understand where I am going wrong in trying to reference the collection with a space in xmldb:store.
NOTE: As I said, the code works if there is no space in the name of the collection.
I have tried many combinations of encoding the URL and making a string from it but nothing seems to work.

A: If your collection or resource names are possibly going to contain characters that need to be encoded, you need to use xmldb:encode-uri() on the names. In your first sample, you encode the collection name ($collection) but not the resource name ($file). In your second sample, you pre-encode the collection name, but the resource name contains no characters that need to be encoded; so you've fully accounted for the encoding.
Take care to ensure that the collection name, as encoded, does exist. If not, you should pre-create the collection. This could actually be the cause of the error you cite.
When you create links to these resources in HTML output, take care not to double-encode them.
You might find it useful to reference an app that handles encoding well. See the source to eXide https://github.com/wolfgangmm/eXide.

A: The answer was permission issue (although I am a bit lost at that).
The collection had rw-rw-r-- and the user is in the group and is in fact the owner of the collection.
When I change to include execute (rwxrwxr--) it works as expected. Confusing, but apparently execute permission in required on the collection that is going to be stored into.


text:
Q: How to using Array Loop on validation Form using Vue? I would like to create a simple web app that can validation form using Vue?
I have two input fields, firstname[1] and firstname[2]
 data: {
    firstname: ['',''],
 }

I want to use the following code to validate the form, but finally not suessful.
computed: {
    missfirstname(){
        for(var i=1;i<this.firstname.length;i++){
         if(this.firstname[i] =='' && this.attemptSubmit) {
           this.firstname_ErrMsg[i] = 'Not be empty';
           return true;
          }
           return false;
        }
    }
 },
  methods: {
    validateForm: function (e) {
        this.attemptSubmit = true;
         if(this.missfirstname){
            e.preventDefault();
           }else{
            return true;
           }
    }
  },

Is it possible to use array Loop on the validation form??
here it my code I am using Vue 2
my full code
script.js
var app = new Vue({
  el: '#app',
  data: {
    firstname: ['',''],
    firstname_ErrMsg: ['',''],
    attemptSubmit: false
  },
  mounted () {
    var self = this;
   },
computed: {
    missfirstname(){
        for(var i=1;i<this.firstname.length;i++){
         if(this.firstname[i] =='' && this.attemptSubmit) {
           this.firstname_ErrMsg[i] = 'Not be empty';
           return true;
          }
           return false;
        }
    }
 },
  methods: {
    validateForm: function (e) {
        this.attemptSubmit = true;
         if(this.missfirstname){
            e.preventDefault();
           }else{
            return true;
           }
    }
  },
})

index.html

<form action='process.php' method="post" autocomplete="off" name="submit_form" v-on:submit="validateForm">
  firstname1 : <input type='text' id='firstname1' name='firstname1' alt='1' v-model='firstname[1]'>

{{firstname_ErrMsg[1]}}

  firstname2 :
  <input type='text' id='firstname2' name='firstname2' alt='2' v-model='firstname[2]'>

{{firstname_ErrMsg[2]}}

  <input id="submit" class="preview_button" name="submit_form" type="submit">
</form>

A: The array of javascript start from index 0.
Which means in your missfirstname(), i should be defined with 0
missfirstname(){
    for(var i=0;i<this.firstname.length;i++){
     if(this.firstname[i] =='' && this.attemptSubmit) {
       this.firstname_ErrMsg[i] = 'Not be empty';
       return true;
      }
       return false;
    }
}

A: Observations :

*

*missfirstname property should be separate for each field else it will be difficult to assign the error for a specific field.

*Instead of iterating over a this.firstname everytime in computed property, you can use @blur and check the value for that particular field which user touched.

*v-model properties should be unique else it will update other one on changing current one.

Your user object should be like this and you can use v-for to iterate it in HTML for dynamic fields creation instead of hardcoding.
data: {
  user: [{
    name: 'firstName1',
    missfirstname: false
  }, {
    name: 'firstName2',
    missfirstname: false
  }]
}

Now, In validateForm() you can just pass the index of the iteration and check the model value. If value is empty, you can assign missfirstname as true for that particular index object in user array.
Update : As per author comment, assigning object in users array via for loop.
data: {
  users: []
},
mounted() {
  for(let i = 1; i <= 2; i++) {
    this.users.push({
      name: 'firstName' + i,
      missfirstnam: false
    })
  }
}


text:
Q: How to use an AFP network share with fast user switching? I'm trying to mount an AFP network share from my NAS so that multiple users can have access when using Fast User Switching (FUS).
Once I mount the share as User1 and log into User2's account the mounted share will show up but is not accessible. Same the other way around.
Both users are in the group wheel. Is there any way to specify permissions of the newly mounted share? I looked into the man pages of mount, fstab, mount_afp but couldn't seem to find any way how to specify the permissions of the mounted share.
The problem is e.g. if you have a shared iTunes library with music files on say an AFP network volume called music that the first user will mount that under /Volumes/music. If the second user decides to mount it as well (while the first user has still mounted it) a new mount point will be created and the volume is mounted to /Volumes/music-1.
Since iTunes stores the file path as something like /Volumes/music/album/artist/title.ext in an XML file, iTunes will say it  can't find the file even though the network share is mounted (but the path is wrong now and the user doesn't have access to the other mount).
Any thoughts on this issue? Any help greatly appreciated!

A: I'm not sure if your situation is similar but I use netatalk on my NAS; I had to make sure permissions were set allowing both users access in the AppleVolumes.default config file in order for the share to mount properly on my mac so that both users have access to it.
Also I think by default User2's desktop won't show the share, you have to manually go to it.

A: I think what you're going to need to do is have the mount done automatically before logging in, or handled by Mac OS X's automounter called autofs.  Here's some general info on setting up automatic mounts.
This thread over on the ReadyNAS forum may describe something closer to exactly what you're looking for.
Also note, as in one of the other replies here, make sure permissions are done appropriately on the NAS such that all your users can read/write to the afp mount.


text:
Q: how to php query and encode to json level 2 This is my database table

Questions Table
id | qname                           | ansid
1  | 1.what's your favorite color ?  |  a-01
2  | 2.what's your hair color ?      |  a-01

Answer Table
id | ansid | aname
1  | a-01  | red
2  | a-01  | blue
3  | a-01  | green

when i use php query and encode to json
 select * from questions inner join answers on question.ansid = answer.ansid
 [
     {
       "question": "1. What's your favorite color ?",
       "choices": [{"a": "red"}]
     },
     {
       "question": "1. What's your favorite color ?",
       "choices": [{"a": "blue"}]
     },
     {
       "question": "1. What's your favorite color ?",
       "choices": [{"a": "green"}]
     },
     {
       "question": "2. what's your hair color ?",
       "choices": [{"a": "red"}]
     },
     {
       "question": "2. what's your hair color ?",
       "choices": [{"a": "blue"}]
     },
     {
       "question": "2. what's your hair color ?",
       "choices": [{"a": "green"}]
     }
    ]

Is it possible to encode json data like
[
 {
  "question": "1. What's your favorite color ?",
  "choices": [{"a": "red"},{"a": "blue"},{"a": "green"}]
 },
 {
  "question": "2. What's your hair color ?",
  "choices": [{"a": "red"},{"a": "blue"},{"a": "green"}]
 }
]

A: You can get this in two queries like below-
// first select questions with your criteria for me limiting to 20
 $stmt = $pdo->prepare("SELECT * FROM questions limit ?");
 $stmt = $stmt->execute([20]);
 $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
 //collect ansid
 $ansIds = [];
 foreach($questions as $qst)
 {
     $ansIds[] = $qst['ansid'];
 }

 $ansIds = array_unique($ansIds);

// now collect answers belongs above questions

$stmt = $pdo->prepare("SELECT * FROM answers WHERE ansis in (?)");
$stmt = $stmt->execute([implode(",", $ansIds)]);
$answers = $stmt->fetchAll(PDO::FETCH_ASSOC);
// now combine them having loop like below
// pass by reference in foreach
 foreach($questions as &$question)
 {
     $question['choices'] = [];
     foreach($answers as $ans)
     {
        if($question['ansid'] == $ans["ansid"])
        {
          array_push($question['choices'], ['a' => $ans['aname']]);
        }
     }
 }
// now your $questions variable is ready

 echo json_encode($questions);

A: I think you're asking for a different query to get the desired result and it's somewhat unrelated to the JSON part.
Given your schema here I've prepared a couple of queries over there.
The short answer is: No you can't do that. There are Database-specific ways to do some collection aggregation over the n-side of a query, however I do not recommend it at all, since the way this is done highly depends on the database you're using and hence you're loosing the portability of your query if you choose to do so.
The cleanest approach would be the fetch the questions first:
SELECT ansid, qname FROM questions;

and then once you've got all the ansid's you can iterate over your results and for each result fetch the answer options:
SELECT id, aname FROM answers WHERE ansid = 'a-01';

Lastly you just need to merge the two together to get your desired output.


text:
Q: Use values outside excel cell in apache poi Bar chart I am trying to create a bar chart in excel file using Apache poi and following the code mentioned here:
Create Bar Chart in Excel with Apache POI.
In my case, I need to use data values coming from a different source instead of the excel cells. How can I use those values in the BarChart?
Assume that the values will come as an array of float/double values. Also, I need to be able to set Bar colors independently. For example, some bars will be green while some others will be red.
I modified the data portion of Create Bar Chart in Excel with Apache POI code in the following manner:
 CTBarSer ctBarSer = ctBarChart.addNewSer();
 CTSerTx ctSerTx = ctBarSer.addNewTx();
 CTStrRef ctStrRef = ctSerTx.addNewStrRef();
ctStrRef.setF("hardcoded" + r);
ctBarSer.addNewIdx().setVal(r-2);
CTAxDataSource cttAxDataSource = ctBarSer.addNewCat();
CTStrData ctStrData = cttAxDataSource.addNewStrLit();
ctStrData.addNewPt().setV("Val1");
ctStrData.addNewPt().setV("Val2");
ctStrData.addNewPt().setV("Val3");

CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();

CTNumData ctNumData = ctNumDataSource.addNewNumLit();
CTNumVal ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.92));

ctNumData = ctNumDataSource.addNewNumLit();
ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.95));

ctNumData = ctNumDataSource.addNewNumLit();
ctNumVal = ctNumData.addNewPt();
ctNumVal.setV(String.valueOf(0.98));

Any help is greatly appreciated. Thanks!
When I output the excel file using print, it gives the following result:
<xml-fragment xmlns:char="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:main="http://schemas.openxmlformats.org/drawingml/2006/main">
  <char:plotArea>
    <char:layout/>
    <char:barChart>
      <char:barDir val="col"/>
      <char:varyColors val="false"/>
      <char:ser>
        <char:idx val="0"/>
        <char:tx>
          <char:strRef>
            <char:f>hardcoded2</char:f>
          </char:strRef>
        </char:tx>
        <char:spPr>
          <main:ln>
            <main:solidFill>
              <main:srgbClr val="000000"/>
            </main:solidFill>
          </main:ln>
        </char:spPr>
        <char:cat>
          <char:strLit>
            <char:pt>
              <char:v>Val1</char:v>
            </char:pt>
            <char:pt>
              <char:v>Val2</char:v>
            </char:pt>
            <char:pt>
              <char:v>Val3</char:v>
            </char:pt>
          </char:strLit>
        </char:cat>
        <char:val>
          <char:numLit>
            <char:pt>
              <char:v>0.92</char:v>
            </char:pt>
          </char:numLit>
          <char:numLit>
            <char:pt>
              <char:v>0.95</char:v>
            </char:pt>
          </char:numLit>
          <char:numLit>
            <char:pt>
              <char:v>0.98</char:v>
            </char:pt>
          </char:numLit>
        </char:val>
      </char:ser>
      <char:axId val="123456"/>
      <char:axId val="123457"/>
    </char:barChart>
    <char:catAx>
      <char:axId val="123456"/>
      <char:scaling>
        <char:orientation val="minMax"/>
      </char:scaling>
      <char:delete val="false"/>
      <char:axPos val="b"/>
      <char:tickLblPos val="nextTo"/>
      <char:crossAx val="123457"/>
    </char:catAx>
    <char:valAx>
      <char:axId val="123457"/>
      <char:scaling>
        <char:orientation val="minMax"/>
      </char:scaling>
      <char:delete val="false"/>
      <char:axPos val="l"/>
      <char:tickLblPos val="nextTo"/>
      <char:crossAx val="123456"/>
    </char:valAx>
  </char:plotArea>
  <char:plotVisOnly val="true"/>
</xml-fragment>

A: Main problems with your changings are:

*

*You forgot setting the Idx of the CTStrVal and the CTNumVal, you have added using addNewPt.

*CTNumData added to CTNumDataSource with addNewNumLit should contain as much CTNumVals like there are data points in the series. There should not be multiple CTNumDatain one series. With CTStrData in CTAxDataSource you have done it right - except the missing Idx, see 1.
Following  code is creating the same chart as the one in the linked answer but without cell references:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.usermodel.charts.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFChart;

import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarChart;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarSer;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTAxDataSource;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumDataSource;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerTx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTScaling;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTLegend;
import org.openxmlformats.schemas.drawingml.x2006.chart.STAxPos;
import org.openxmlformats.schemas.drawingml.x2006.chart.STBarDir;
import org.openxmlformats.schemas.drawingml.x2006.chart.STOrientation;
import org.openxmlformats.schemas.drawingml.x2006.chart.STLegendPos;
import org.openxmlformats.schemas.drawingml.x2006.chart.STTickLblPos;

/*
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumRef;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef;
*/

import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal;

public class BarChartPlainValues {

    public static void main(String[] args) throws Exception {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("Sheet1");

/*
cell filing code deleted
*/

        Drawing drawing = sheet.createDrawingPatriarch();
        ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 0, 5, 8, 20);

        Chart chart = drawing.createChart(anchor);

        CTChart ctChart = ((XSSFChart)chart).getCTChart();
        CTPlotArea ctPlotArea = ctChart.getPlotArea();
        CTBarChart ctBarChart = ctPlotArea.addNewBarChart();
        CTBoolean ctBoolean = ctBarChart.addNewVaryColors();
        ctBoolean.setVal(true);
        ctBarChart.addNewBarDir().setVal(STBarDir.COL);

//new code start

        for (int s = 1; s < 5; s++) {
           CTBarSer ctBarSer = ctBarChart.addNewSer();
           CTSerTx ctSerTx = ctBarSer.addNewTx();
           ctSerTx.setV("Serie " + s);
           ctBarSer.addNewIdx().setVal(s-1);

           CTAxDataSource ctAxDataSource = ctBarSer.addNewCat();
           CTStrData ctStrData = ctAxDataSource.addNewStrLit();
           ctStrData.addNewPtCount().setVal(3);
           CTStrVal ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(0);
           ctStrVal.setV("HEADER 1");
           ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(1);
           ctStrVal.setV("HEADER 2");
           ctStrVal = ctStrData.addNewPt();
           ctStrVal.setIdx(2);
           ctStrVal.setV("HEADER 3");

           CTNumDataSource ctNumDataSource = ctBarSer.addNewVal();
           CTNumData ctNumData = ctNumDataSource.addNewNumLit();
           ctNumData.addNewPtCount().setVal(3);
           CTNumVal ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(0);
           ctNumVal.setV("" + new java.util.Random().nextDouble());
           ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(1);
           ctNumVal.setV("" + new java.util.Random().nextDouble());
           ctNumVal = ctNumData.addNewPt();
           ctNumVal.setIdx(2);
           ctNumVal.setV("" + new java.util.Random().nextDouble());

           //at least the border lines in Libreoffice Calc ;-)
           ctBarSer.addNewSpPr().addNewLn().addNewSolidFill().addNewSrgbClr().setVal(new byte[] {0,0,0});

        }

//new code end

/*
chart reference code deleted
*/

        //telling the BarChart that it has axes and giving them Ids
        ctBarChart.addNewAxId().setVal(123456);
        ctBarChart.addNewAxId().setVal(123457);

        //cat axis
        CTCatAx ctCatAx = ctPlotArea.addNewCatAx();
        ctCatAx.addNewAxId().setVal(123456); //id of the cat axis
        CTScaling ctScaling = ctCatAx.addNewScaling();
        ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
        ctCatAx.addNewDelete().setVal(false);
        ctCatAx.addNewAxPos().setVal(STAxPos.B);
        ctCatAx.addNewCrossAx().setVal(123457); //id of the val axis
        ctCatAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

        //val axis
        CTValAx ctValAx = ctPlotArea.addNewValAx();
        ctValAx.addNewAxId().setVal(123457); //id of the val axis
        ctScaling = ctValAx.addNewScaling();
        ctScaling.addNewOrientation().setVal(STOrientation.MIN_MAX);
        ctValAx.addNewDelete().setVal(false);
        ctValAx.addNewAxPos().setVal(STAxPos.L);
        ctValAx.addNewCrossAx().setVal(123456); //id of the cat axis
        ctValAx.addNewTickLblPos().setVal(STTickLblPos.NEXT_TO);

        //legend
        CTLegend ctLegend = ctChart.addNewLegend();
        ctLegend.addNewLegendPos().setVal(STLegendPos.B);
        ctLegend.addNewOverlay().setVal(false);

System.out.println(ctChart);

        FileOutputStream fileOut = new FileOutputStream("BarChartPlainValues.xlsx");
        wb.write(fileOut);
        fileOut.close();
    }
}

Problem: Normally arrays of string literals like ={"HEADER 1","HEADER 2","HEADER 3"} are not allowed as axis labels. Only references are allowed here. Excel accepts this while rendering the chart but you cannot edit those axis labels in Excel GUI.


text:
Q: Why the function is not returning the desired list? My code:
directions = ["north", "south", "east", "west"]
def scan(sentence):
    global sentence_list
    sentence_list = []
    sentence.split()
    for i in sentence:
        if i in directions:
            a = ('direction', i)
            sentence_list.append(a)
            del a
    return sentence_list

I am trying to split a string and return the words in a tuple within a list, but whenever i test it using returns empty list.
Here's my output:
PS C:\Users\dell 3521\lpythw\ex48> nosetests
F
======================================================================
FAIL: tests.lexicon_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\dell 3521\AppData\Local\Programs\Python\Python36-
 32\lib\site-packages\nose-1.3.7-py3.6.egg\nose\case.py
    ", line 198, in runTest
    self.test(*self.arg)
  File "C:\Users\dell 3521\lpythw\ex48\tests\lexicon_tests.py", line 5, in
test_directions
    assert_equal(lexicon.scan("north"), [('direction', 'north')])
AssertionError: Lists differ: [] != [('direction', 'north')]

Second list contains 1 additional elements.
First extra element 0:
('direction', 'north')

- []
+ [('direction', 'north')]

----------------------------------------------------------------------
Ran 1 test in 0.021s

FAILED (failures=1)

Thanks in advance.

A: You have to reassign sentence to the return value of sentence.split() or iterate directly over sentence.split(), because the str.split() method does not modify sentence in place, but returns a list instead.
Also you do not need the del a statement.
Change your code to
directions = ["north", "south", "east", "west"]

def scan(sentence):
    global sentence_list
    sentence_list = []
    for i in sentence.split():
        if i in directions:
            a = ('direction', i)
            sentence_list.append(a)

    return sentence_list

Or a even shorter way is using list comprehension
directions = ["north", "south", "east", "west"]

def scan(sentence):
    global sentence_list
    sentence_list = [('direction', i) for i in sentence.split() if i in directions]

    return sentence_list

The output is
>>> scan("north")
[('direction', 'north')]

And you may want the over think the use of the global statement in your code.
As explained in various resources, you want to avoid using global variables for the readability and maintainability of your code.

A: The str.split() method does not modify the string in-place. You should assign the returning value of str.split() to a variable, or in this case, you can simply iterate over it instead:
sentence_list = []
for i in sentence.split():


text:
Q: Discrepancy of elements in minimal members of a union-closed set This question is motivated by Frankl's union-closet sets conjecture.
Let $n\in\mathbb{N}$ and set $[n] = \{0,1,\ldots,n\}$. We say that a family ${\cal A} \subseteq {\cal P}([n])$ is union-closed if $\emptyset\notin{\cal A}$ and  $A,B\in {\cal A}$ implies $A\cup B\in{\cal A}$.
For $k\in[n]$ we define the weight of $k$ to be $$w(k) = |\{A\in {\cal A}: k\in A\}|.$$ For a set $A\in{\cal A}$ we set the discrepancy to be $$\text{disc}(A) = \max\{w(j):j\in A\} - \min\{w(j):j\in A\}.$$
Let $r\in ]0,1[$ be given. Is there $n\in\mathbb{N}$ and a union closed family ${\cal A}$ on $[n]$ and $M$ minimal amongst the members of ${\cal A}$ such that $$\frac{\text{disc}(M)}{|{\cal A}|} \geq r?$$

A: Surely yes.
Firstly, we may achieve $\max\{w(j)\colon j\in M\}=|\mathcal A|$ for free. Just take any union-closed family of subsets on $[n-1]$, and add $n$ to every set.
So it suffices to make $\min\{w(j)\colon j\in M\}$ small compared with $\mathcal A$. To make this, take $2^{[n-2]}\setminus\{\varnothing\}$ and add to it $[n-1]\setminus\{1\}$ and $[n-1]$; we get a union-closed family.. Then $[n-1]\setminus \{1\}$ is minimal, and $w(n-1)=2$.


text:
Q: changed commit message ok in gitlog but not in github I followed the steps from Change old commit message on Git, and I confirmed the commit message updated in git log. But when I click the "Commit History" tab in Github, I still see the old message and old SHA-1.
So, I blindly tried git push origin master, but that failed with:
To git@github.com:foobar.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:foobar.git'
To prevent you from losing history, non-fast-forward updates were rejected
Merge the remote changes (e.g. 'git pull') before pushing again.  See the
'Note about fast-forwards' section of 'git push --help' for details.

The error tells me to "merge with remote changes before pushing again", but that seems like the wrong thing to do: merging new stuff into an amended commit (from an older base). I'm confused.
How can I commit my amended message?

A: if you are rewriting history, you need to call:
git push --force

A: As @xsace says, you are rewriting history here.
A commit in git is linked to several things:

*

*the commit metadata (author, committer, timestamps, commit message);

*the parent commit (or commit_s_ if it is a merge);

*the tree.

If you change any of these, and you did here (you changed the commit message), your history and github's (or any other remote's for that matter) diverge:
[parent]----[master@github]
    \
     \------[your local master]

Here, you want to push yourlocalmaster to github, but this is not a fast forward, ie the current master head at github is not an immediate parent to your commit. Therefore you need to force the push.
This can also be done with git push github +master.


text:
Q: Segue with TableView I have some cell's (image bellow) created by tab[] I need to segue correct value to another view (moreViewController) on this view I have 'nazwa' 'szerokosc' 'dlugosc' and I need to save to nazwa correct "place" from cell etc
have somebody any solution? I search it but I don't find :/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    self.performSegue(withIdentifier: "more", sender: tableView)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let destViewController:moreViewController = segue.destination as! moreViewController

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nazwaTab.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! cellTableViewCell
    let nazwa = nazwaTab[indexPath.row]
    let szerokosc = szerokoscTab[indexPath.row]
    let dlugosc = dlugoscTab[indexPath.row]
    cell.nazwaLabel.text = nazwa
    cell.szerokoscLabel.text = szerokosc
    cell.dlugoscLabel.text = dlugosc
    return (cell)
}

A: Declare a variable nazwa in MoreViewController and assign a value to it before segueing to it.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            let identifier = segue.identifier ?? ""
            switch identifier {
              case "more":
                guard let vc = segue.destination as? MoreViewController else {
                  return
                }
                vc.nazwa = self.clickedNazwa
              default:
                break
            }
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
    self.clickedNazwa = nazwaTab[indexPath.row]
    self.performSegue(withIdentifier: "more", sender: tableView)

}

A: You can save a selected row to global variable and use it after call: prepare(for segue: UIStoryboardSegue, sender: Any?)


text:
Q: Проблема с аутентификацией в EXIM4 MD5 Есть exim4  пользователи хранятся в mysql пароли в MD5
CREATE TABLE mailboxes (
  id INT(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  domain_id INT(10) NOT NULL,
  local_part VARCHAR(250) NOT NULL,
  password VARCHAR(100) NULL,
  description VARCHAR(250) NULL,
  active TINYINT(1) NOT NULL DEFAULT 0,
  created TIMESTAMP NOT NULL DEFAULT NOW(),
  modified TIMESTAMP NULL
);

Пароль задаю так
INSERT INTO mailboxes VALUES(NULL,1,'joe',MD5('password'),'My account for joe@mydomain.com',1,NOW(),NOW());

Соответственно что нужно прописать в 20_exim4-config_mysql-authenticator чтобы аунтефикация работала?

A:
Соответственно что нужно прописать в 20_exim4-config_mysql-authenticator

вероятно, речь о файле в каталоге /etc/exim4/conf.d/auth?
примерно так (скопировано с рабочей системы с адаптацией под ваши имена полей):
mysql_plain:
  driver = plaintext
  public_name = PLAIN
  server_condition = ${lookup mysql{select id from mailboxes where local_part = '${quote_mysql:$auth2}' and password = md5('${quote_mysql:$auth3}')}{yes}{no}}
  server_prompts = :
  server_set_id = $auth2

mysql_login:
  driver = plaintext
  public_name = LOGIN
  server_condition = ${lookup mysql{select id from mailboxes where local_part = '${quote_mysql:$auth1}' and password = md5('${quote_mysql:$auth2}')}{yes}{no}}
  server_prompts = Username:: : Password::
  server_set_id = $auth1

mysql_cram_md5:
  driver = cram_md5
  public_name = CRAM-MD5
  server_secret = ${lookup mysql{select password from mailboxes where local_part =  '${quote_mysql:$auth1}'}{$value}fail}
  server_set_id = $auth2

правда, не уверен за ту часть, которая про cram_md5: там, откуда я копировал, пароль в базе записан открытым текстом. воспользуйтесь примерами из /etc/exim4/conf.d/auth/30_exim4-config_examples для адаптации.
впрочем, если судить по этой, например, инструкции, то и без данной части (про cram_md5) должно работать.


text: Q: What are the minimum hardware requirement to run Xcode 6 on mac mini? Can anybody please tell me the minimum hardware requirements to run "Xcode 6".I have installed the "Xcode 6" already but it is running too slow.I have a mac mini with 4 giga bytes Ram and  core 2 duo processor.Please suggest me any needful way.


text:
Q: Can't set TextureWic C++DirectX I am trying to use a texture embedded in a file, it's not a tga.
Here is my code, I don't know where the logical error is.
ID3D11ShaderResourceView* texturePtr = nullptr;
ID3D11Texture2D* texture2D = nullptr;
ID3D11SamplerState* sampleStatePtr = nullptr;

hr = CoInitialize(NULL);

assert(SUCCEEDED(hr));

devConPtr->PSSetSamplers(0, 1, &sampleStatePtr);
devConPtr->PSSetShaderResources(0, 1, &texturePtr);

Texture2D tex : TEXTURE;
SamplerState mySampler : SAMPLER;

D3D11_SAMPLER_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sd.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sd.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sd.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sd.MipLODBias = 0.0f;
sd.MaxLOD = D3D11_FLOAT32_MAX;
sd.ComparisonFunc = D3D11_COMPARISON_NEVER;

hr = devPtr->CreateSamplerState(&sd, &sampleStatePtr);

DXGI_SAMPLE_DESC sample;

sample.Count = 1;
sample.Quality = 0;

D3D11_TEXTURE2D_DESC textureDesc;

textureDesc.Width = w;
textureDesc.Height = h;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
textureDesc.SampleDesc = sample;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
textureDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
textureDesc.MiscFlags = 0;

D3D11_SUBRESOURCE_DATA subData;

subData.pSysMem = data;
subData.SysMemPitch = sizeof(*data)*w;

HRESULT hr = devPtr->CreateTexture2D(
    &textureDesc,
    &subData,
    &texture2D
);
assert(SUCCEEDED(hr));

//(ID3D11Texture2D*)texture2D;

texturePtr->QueryInterface(IID_ID3D11Texture2D, (void**)&texture2D);

D3D11_SHADER_RESOURCE_VIEW_DESC shvD;

shvD.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
shvD.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;

hr= devPtr->CreateShaderResourceView(texture2D, &shvD, &texturePtr);

assert(SUCCEEDED(hr));

hr = DirectX::CreateWICTextureFromMemory(devPtr, devConPtr, (const
uint8_t*)&data, sizeof(*data),
nullptr, &texturePtr, NULL);

assert(SUCCEEDED(hr));

unsigned int textureCount = mat->GetTextureCount(aiTextureType_UNKNOWN);

    for (UINT j = 0; j < textureCount; j++)
    {

        aiString* path = nullptr;
        mat->GetTexture(aiTextureType_UNKNOWN, j, path);

        assert(path->length >= 2);
        int index = atoi(&path->C_Str()[1]);
        createTexture(scenePtr->mTextures[index]->mWidth, scenePtr-
>mTextures[index]->mHeight, (uint8_t*)scenePtr->mTextures[index]->pcData);
    }

If you could find some kind of logical error or help with the debugging that would be super helpful, I try to put a breakpoint at my HRESULTS but I can't find the variables however it does say that my resourceviewptr is always nullptr despite me trying to use it.
I am using c++ and directx and directx toolkit etc.

A: You are not initializing shvD completely. To fix it, initialize it like this:
D3D11_SHADER_RESOURCE_VIEW_DESC shvD;

shvD.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
shvD.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
shvD.Texture2D.MostDetailedMip = 0;
shvD.Texture2D.MipLevels = 1;


text:
Q: database connection error while connecting database in live server error 1045 my .env file setup like this on the live server. but while I am
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=onlyaruv_notepad-apps
DB_USERNAME=onlyaruv_notepad
DB_PASSWORD=mypassword

the error was
SQLSTATE[28000] [1045] Access denied for user 'onlyaruv_notepad'@'127.0.0.1' (using password: YES) (SQL: select * from `users` where `email` = ih76632@gmail.com limit 1)

I access my ssh via putty using this host and password
http://5.100.156.10:2082 I am confused .

A: Have you given All privileges to onlyaruv_notepad this user?
if you not please give all privileges to the user.
still, The problem not solved check host is correct or not.
(change DB_HOST=127.0.0.1  to DB_HOST=localhost

A: Check your database connection carefully. If it does not work then
Run the following artisan command and try again
php artisan config:clear
php artisan cache:clear
php artisan view:clear


text:
Q: How to create a user in django with custom attributes using create_user? I'm trying to run a test of the middleware of a django app. Looks like this:
    class TestAuthenticationMiddleware(TestCase):
        @classmethod
        def setUpTestData(cls):
            cls.user = User.objects.create_user('test_user', 'test@example.com', 'test_password')

        def setUp(self):
            self.middleware = AuthenticationMiddleware(lambda req: HttpResponse())
            self.client.force_login(self.user)
            self.request = HttpRequest()
            self.request.session = self.client.session

But I'm getting this attribute error:
    queryset = user.get_subscriptions_all()
AttributeError: 'User' object has no attribute 'get_subscriptions_all'

because the User class is defined like this:
User(AbstractBaseUser, LimitHelpers):
    [...]
    def get_subscriptions_all(self):
        return self.subscriptions.all().union(self.account.subscriptions.all())

and on my utils.py:
        @receiver(user_logged_in)
    def callback_user_loggedin(sender, request, user, **kwargs):
        if not user.is_staff and not user.is_superuser:
            # Activating user's language
            saveCodeCountryFromUser(request, user)
            # Updating subscriptions
            queryset = user.get_subscriptions_all()
            for sub in queryset:
                cls = get_subscription_class(sub)
                if cls is not None:
                    cls.callback_user_loggedin()

Any idea about how to use the create_user to include the get_subscriptions_all attr?

A: You must set the setting AUTH_USER_MODEL = 'myapp.models.User'
See: substituting a custom user model.
Without this setting, Django will continue to use the default builtin User. You should also ensure your tests also have this configuration (if you use a separate config for tests)


text:
Q: My sbt plugin doesn't pack its dependency library I'm creating a sbt plugin that requires another scalaj library. I publish the library locally and try to run/test it with another project.
However, when I test the plugin with another project, it shows java.lang.NoClassDefFoundError: scalaj/http/Http$
Here's my code..
plugin build.sbt
name := "hello-sbt-plugin"
version := "1.0"
scalaVersion := "2.10.4"
scalacOptions ++= Seq("-deprecation", "-feature")
organization := "com.abc.dev"
sbtPlugin := true
publishMavenStyle := false
libraryDependencies += "org.scalaj" %% "scalaj-http" % "0.3.16"
initialCommands in console := "import com.typesafe.sbt.rss._"

plugin project/plugins.sbt
addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.3")
addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.6.4")
addSbtPlugin("com.typesafe.sbt" % "sbt-site" % "0.8.1")

libraryDependencies <+= (sbtVersion) { sv =>
  "org.scala-sbt" % "scripted-plugin" % sv
}

// Scripted plugin needs to declare this as a dependency
libraryDependencies += "jline" % "jline" % "2.11"
libraryDependencies += "org.scalaj" %% "scalaj-http" % "0.3.16"

plugin plugin.scala
package com.abc.dev

import sbt._
import Keys._
import plugins._
import sbt.plugins.JvmPlugin
import scalaj.http.Http
import scalaj.http.HttpOptions

object HelloPlugin extends AutoPlugin {

  object autoImport {
    val rssList = settingKey[Map[String, String]]("The list of RSS urls to update.")
    val gatlingses = inputKey[Unit]("Prints RSS")
  }

  import autoImport._
  override def trigger: PluginTrigger = allRequirements
  override def requires = JvmPlugin

  override def projectSettings: Seq[Setting[_]] = Seq(
    gatlingsesSetting
  )

  def gatlingsesSetting: Setting[_] = gatlingses := {
  /*Things*/
  }

}

Below is the code of testing project.
build.sbt
name := "sbt-tester"

version := "1.0"
scalaVersion := "2.12.1"

lazy val myProject = (project in file(".")).enablePlugins(HelloPlugin)

libraryDependencies += "org.apache.httpcomponents" % "httpclient" % "4.5.3"
libraryDependencies +=  "org.scalaj" %% "scalaj-http" % "2.3.0"

rssList := Map(
  "key" -> "value",
)

project/plugin.sbt
addSbtPlugin("com.abc.dev" % "hello-sbt-plugin" % "1.0")


text:
Q: How to translate admin panel? I need to translate magento 2 admin panel to Persian language.
Can anyone suggest to me the best ways to achieve this?
I suppose I need to download some language pack and then install it.
Or I just could export all the admin phrases and translate them manually and then install translated phrases.
If somebody could explain to me both ways I would be very thankful.

A: Please try with this:

Settings:
  https://zemez.io/magento/support/how-to/magento-2-1-x-how-to-change-the-admin-panel-language/
files needed:
  https://www.mageplaza.com/magento-2-persian-language-pack.html

A: You can actually change it directly from your Admin Account Settings
In the Interface Locale, choose Persian then Save.
After that, run static content deploy command:
php bin/magento setup:static-content:deploy -f fa_IR --area adminhtml

Then flush cache.
After that, you can collect translatable phrases for fa_IR which is the Persian locale.
php bin/magento i18n:collect-phrases --output "app/i18n/Magento/fa_IR.csv" --magento

Note: check the link in collect translatable phrases and do the same for manually translating words and deploy it afterwards

A: There is a Persian-Languagepack provided.
https://github.com/mageplaza/magento-2-persian-language-pack
Feel free to contribute if something is missing


text:
Q: In source code, is it more secure to use several MySQL users that have limited access as opposed to using one user that can access everything? I have a Perl website back-end that connects to MySQL databases. We have dozens of customers and each customer has their own database. So depending on which customer webpage we're on, the Perl will connect to a specific database using a MySQL user that only has access to that database. For example, MySQL user customer1 only has access to database customer1 and MySQL user customer2 only has access to database customer2, etc.
Is that a common practice to make things more secure, or would it be just as secure to always use the same MySQL user that has access to all databases?


text:
Q: Issue with Bash script, i am new to bash, unable to understand the syntax error I am new to bash scripting, I am writing a script that will deploy a new artifact to AWS Elasticbeanstalk, rather than going to AWS UI, and developers taking a long time. please see below and let me know if I am doing anything wrong. I am worried about this part:
if [ "$1" = "help" ] HELP <<EOF
then
read -r -d ''
Usage:
\t$(basename $0) list - list all applications
\t$(basename $0) deploy    - deploy artifact to an environment
EOF
die "$HELP"
exit 0
fi
Running this command to run the script:
AWS_PROFILE=default ARTIFACT_BUCKET=myawsstudybucket ARTIFACT_NAME=artifact1.zip ./deploy.sh deploy demo-app Demoapp-env artifact.zip
#!/bin/bash

PROFILE=$(aws sts get-caller-identity --query Account)
RED='\033[0;31m'
COLOR_OFF='\033[0m'

if [ -z "$PROFILE" ]
then
    echo "Credentials missing"
else
    region=$(aws configure get region)
fi

if [ "$1" = "list" ]
then
    echo $(aws elasticbeanstalk describe-applications --query "Applications[].ApplicationName")
    exit 0
fi

if [ "$1" = "help" ] HELP <<EOF
then
    read -r -d ''
    Usage:
    \t$(basename $0) list - list all applications
    \t$(basename $0) deploy <app-name> <environment-name> <local-artifact-path> - deploy artifact to an environment
    EOF
    die "$HELP"
    exit 0
fi

die() { echo -e "$*" >&2; exit 1; }

[[ -z $EB_APP ]] && die "ERROR: Missing application name"
[[ -z $EB_ENV ]] && die "ERROR: Missing application environment"
[[ -z $EB_ARTIFACT ]] && die "ERROR: Missing application artifact location"

s3path="s3://$ARTIFACT_LOCATION/$ARTIFACT_NAME"
aws s3 cp $artifactpath $s3path

versionlabel=$(date +%s%N)
aws elasticbeanstalk create-application-version --application-name "$ebapp" --version-label $versionlabel --source-bundle S3Bucket=$ARTIFACT_LOCATION,S3Key=$ARTIFACT_NAME
aws elasticbeanstalk update-environment --environment-name $ebenv --version-label $versionlabel

echo "Deployment in progress"
while [[ "$STATUS" != OK ]] && [[ "$STATUS" != Severe ]];
do
    echo "Checking environment status"
    status=$(aws elasticbeanstalk describe-environment-health --environment-name $ebenv --attribute-names HealthStatus --query "HealthStatus"| tr -d '"')
    echo "Current status: $status."
    sleep 5
done

echo "Deployed successfully"

A: That part is definitely strange. What should the word HELP do after the ]?
You probably wanted something like
if [ "$1" = "help" ]
then
    echo Press Enter to display the help...
    read
    cat <<-EOF
    Usage:
        $(basename $0) list - list all applications
        $(basename $0) deploy <app-name> <environment-name> <local-artifact-path> - deploy artifact to an environment
    EOF
fi

Note that you need the real Tab before the closing EOF.
Or maybe you wanted this?
die() { echo -e "$*" >&2; exit 1; }

if [ "$1" = "help" ]
then
   HELP="
    Usage:
        $(basename $0) list - list all applications
        $(basename $0) deploy <app-name> <environment-name> <local-artifact-path> - deploy artifact to an environment
"
   die "$HELP"
fi

Strings in quotes can be multiline.
Note that die must be declared before you can call it.


text:
Q: pygooglevoice parse_sms beautifulsoup error I am trying to run the pygooglevoice example script parse_sms.py to try and download the content of an sms with Python and am receiving the following error:
Traceback (most recent call last):
  File "C:\Python27\pygooglevoice-0.5-extras\examples\parse_sms.py", line 39, in <module>
    for msg in extractsms(voice.sms.html):
  File "C:\Python27\pygooglevoice-0.5-extras\examples\parse_sms.py", line 20, in extractsms
    tree = BeautifulSoup.BeautifulSoup(htmlsms)         # parse HTML into tree
AttributeError: type object 'BeautifulSoup' has no attribute 'BeautifulSoup'

I am running Windows 7 x64, Python 2.7
I have modified the parse_sms.py file only by changing the import of BeautifulSoup to 'from bs4 import BeautifulSoup'
I am new to Python and brand new to BeautifulSoup and I don't know what to do next to try and resolve this issue.  Your help is appreciated.

A: I had the same AttributeError when I was trying to use another tool (Wapiti). What helped me was to specifically use an older version of BeautifulSoup. By default, pip installs the latest version (currently 4.3.2). As soon as I installed the latest version 3 (3.2.1, dated February 16, 2012) it run without errors.
Here's what I did to install another version, using pip (on Mac OS X):
pip install beautifulsoup==3.2.1

Not sure though if that will help you, being on Windows.


text:
Q: Notify the REST when user close the browser from local machine I am making a REST call through PHP curl and in the response  i am getting an url that url
opening in new tab . Now Here's my problem  starts .
1) The url that i am getting from REST is basically a profile url so on that page a logout
option is present and while clicking on logout button i can notify to my REST client .
But suppose if user close the browser in that case how can i notify to my REST client .
Is there any way to do this .?
Any help would be appreciated.
Example :   I make  a REST call to http://somweb.com/hi?id=12
In the response i got a URL i.e http://someurl.net/user?id=19
Now i open the REST url(http://someurl.net/user?id=19) in a new tab to my local machine
Now Question is if user close the tab (REST returned tab  )How can i notify to my REST client

A: May not be the sleekest solution, and it may not work for you but it can be done with a cronjob script and delayed events (not to be confused with browser events!!!).
When you open the url, write in you storage (db, file) that event should be triggered at certain time.
If all goes well, delete the entry form storage and notify REST client.
If user closes tab before it all completes, then event entry will not be deleted and cronjob script may be used to check for these entries and executes those that are overdue and deletes entries.
A cronjob can be setup to execute a script every minute or every few minutes.
This may not be good solution since cronjob script should be executed very often and this may reduce your server performance, but if you think it is worth it - then go for it.
Hope this helps


text:
Q: Displaying two parts of a similar equation successively [Beamer] I want to configure an itemize option on a beamer template in order to display successively two parts of a similar equation. Unfortunately, it doesn't work because it seems like I am not implementing it correctly...
Basically, I want to display the equation until the first 2 colored boxes (and the linked boxes) and then displaying the 3rd green box.

\documentclass[french]{beamer}

\usepackage{pgf, tikz, adjustbox}
\usepackage[beamer,customcolors,norndcorners]{hf-tikz}

%%%%%%%CADRES DES EQUATIONS%%%%%
\usepackage[most]{tcolorbox}
\tcbset{highlight math style={enhanced,colframe=red,colback=red!10!white,boxsep=0pt,sharp corners,
equal height group=C,
minimum for equal height group=C:1.5cm,
valign=center,
}}

%%%%%%% MARGES CUSTOM%%%%%%%%
\newcommand\Wider[2][4em]{%
\makebox[\linewidth][c]{%
  \begin{minipage}{\dimexpr\textwidth+#1\relax}
  \raggedright#2
  \end{minipage}%
  }%

\begin{document}

    \begin{frame}{Equation des films minces}
        \begin{exampleblock}{Cas cylindrique : ajoutons un peu de tension !}
            \begin{itemize}[<+-| alert@+>]
        \Wider[4em]{
        \item \begin{equation*}
          \frac{\partial h}{\partial t} = \frac{1}{12 \mu r}  \frac{\partial}{\partial r}  \left(r h^{3} \left(
          %
          \tcbhighmath[remember as=a,tcbox raise=-9mm]{
            \rho g \frac{\partial h}{\partial r}
          }
          +
          \tcbhighmath[remember as=b,colback=blue!10,colframe=blue,tcbox raise=-9mm]{
           D \frac{\partial}{\partial r}(\Delta^2_r h)
          }
          \right) \right)
        \end{equation*}

        \vskip0.5cm

\begin{equation*}
    \tcbhighmath[
     tcbox raise=0mm,
      remember as=c,
      overlay={
        \node[anchor=north] at (frame.south) {Pesanteur};
        \draw[red,-latex,thick] (a.south) -- (frame.north);
      }
    ]{
      \displaystyle R \propto t^{\frac{1}{2}}
    } \qquad
  \tcbhighmath[
         tcbox raise=0mm,
         remember as=e,
         colback=blue!10,
         colframe=blue,
         overlay={
          \draw[blue,-latex,thick] (b.south) -- (frame.north);
          \node[anchor=north] at (frame.south) {Elastique};
        }
       ]{
    R \propto t^{\frac{1}{3}}
    }
    \end{equation*}
    %%%%PART 2%%%%%%%
    \item \begin{equation*}
          \frac{\partial h}{\partial t} = \frac{1}{12 \mu r}  \frac{\partial}{\partial r}  \left(r h^{3} \left(
          %
          \tcbhighmath[remember as=a,tcbox raise=-9mm]{
            \rho g \frac{\partial h}{\partial r}
          }
          +
          \tcbhighmath[remember as=b,colback=blue!10,colframe=blue,tcbox raise=-9mm]{
           D \frac{\partial}{\partial r}(\Delta^2_r h)
          }
          -
          \tcbhighmath[remember as=bb,colback=green!10,colframe=green,tcbox raise=-9mm]{
          T \frac{\partial}{\partial r}(\Delta_r h)
          }
          \right) \right)
        \end{equation*}

        \vskip0.5cm

\begin{equation*}
    \tcbhighmath[
     tcbox raise=0mm,
      remember as=c,
      overlay={
        \node[anchor=north] at (frame.south) {Pesanteur};
        \draw[red,-latex,thick] (a.south) -- (frame.north);
      }
    ]{
      \displaystyle R \propto t^{\frac{1}{2}}
    } \qquad
  \tcbhighmath[
         tcbox raise=0mm,
         remember as=e,
         colback=blue!10,
         colframe=blue,
         overlay={
          \draw[blue,-latex,thick] (b.south) -- (frame.north);
          \node[anchor=north] at (frame.south) {Elastique};
        }
       ]{
    R \propto t^{\frac{1}{3}}
    } \qquad
      \tcbhighmath[
         tcbox raise=0mm,
         remember as=f,
         colback=green!10,
         colframe=green,
         overlay={
          \draw[green,-latex,thick] (bb.south) -- (frame.north);
          \node[anchor=north] at (frame.south) {Tension};
        }
       ]{
    R \propto t^{\frac{1}{5}}
    }
    \end{equation*}
    }
    \end{itemize}
    \end{exampleblock}
    \end{frame}

/end{document}

Is there a simple way to do so ? I don't know why \item doesn't work in this case ?

A: You can use beamer overlays like \visible<>{...} to uncover the content step by step:
\documentclass[french]{beamer}

\usepackage{pgf, tikz, adjustbox}
\usepackage[beamer,customcolors,norndcorners]{hf-tikz}

%%%%%%%CADRES DES EQUATIONS%%%%%
\usepackage[most]{tcolorbox}
\tcbset{highlight math style={enhanced,colframe=red,colback=red!10!white,boxsep=0pt,sharp corners,
equal height group=C,
minimum for equal height group=C:1.5cm,
valign=center,
}}

%%%%%%% MARGES CUSTOM%%%%%%%%

\begin{document}

    \begin{frame}{Equation des films minces}
    \begin{columns}
    \begin{column}{.95\paperwidth}
        \begin{exampleblock}{Cas cylindrique : ajoutons un peu de tension !}

     \begin{equation*}
          \frac{\partial h}{\partial t} = \frac{1}{12 \mu r}  \frac{\partial}{\partial r}  \left(r h^{3} \left(
          %
          \tcbhighmath[remember as=a,tcbox raise=-9mm]{
            \rho g \frac{\partial h}{\partial r}
          }
          +
          \tcbhighmath[remember as=b,colback=blue!10,colframe=blue,tcbox raise=-9mm]{
           D \frac{\partial}{\partial r}(\Delta^2_r h)
          }
          \visible<2->{-
          \tcbhighmath[remember as=bb,colback=green!10,colframe=green,tcbox raise=-9mm]{
          T \frac{\partial}{\partial r}(\Delta_r h)
          }}
          \right) \right)
        \end{equation*}

        \vskip0.5cm

\begin{equation*}
    \tcbhighmath[
     tcbox raise=0mm,
      remember as=c,
      overlay={
        \node[anchor=north] at (frame.south) {Pesanteur};
        \draw[red,-latex,thick] (a.south) -- (frame.north);
      }
    ]{
      \displaystyle R \propto t^{\frac{1}{2}}
    } \qquad
  \tcbhighmath[
         tcbox raise=0mm,
         remember as=e,
         colback=blue!10,
         colframe=blue,
         overlay={
          \draw[blue,-latex,thick] (b.south) -- (frame.north);
          \node[anchor=north] at (frame.south) {Elastique};
        }
       ]{
    R \propto t^{\frac{1}{3}}
    } \qquad
      \visible<2->{\tcbhighmath[
         tcbox raise=0mm,
         remember as=f,
         colback=green!10,
         colframe=green,
         overlay={
          \draw[green,-latex,thick] (bb.south) -- (frame.north);
          \node[anchor=north] at (frame.south) {Tension};
        }
       ]{
    R \propto t^{\frac{1}{5}}
    }}
    \end{equation*}

    \end{exampleblock}
        \end{column}
        \end{columns}
    \end{frame}

\end{document}