问:
Bootstrap dropdown menu doesn't open
Navber code:

                Home (current)

                  Behandelingen

                  Sportmassage
                  Massagetherapie
                  Ontspanningsmassage

                Afspraak maken

                Tarieven

                Contact

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

<p>Bootstrap code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"></code>```

Dropdown menu inside the navbar doesn't open, anyone an idea on how to fix this?
Not very experienced with bootstrap and don't now what the problem is.

答:
Try this for Bootstrap 4 dropdown navbar</p>

```<code><nav class="navbar navbar-expand-lg navbar-light" style="background-color: #fdfeff;">
  <a class="navbar-brand" href="#">
    <img src="images\logo1.png" width="200" height="80" class="d-inline-block align-top" alt="">
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navCollapse"
    aria-controls="navCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse justify-content-center" id="navCollapse">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="navbar-nav dropdown">
        <a class="nav-link dropdown-toggle" type="button" id="dropdown01"
          data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Behandelingen
        </a>
        <div class="dropdown-menu" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="sportmassage.html">Sportmassage</a>
          <a class="dropdown-item" href="#">Massagetherapie</a>
          <a class="dropdown-item" href="#">Ontspanningsmassage</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Afspraak maken</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Tarieven</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact</a>
      </li>
    </ul>
  </div>
</nav>
</code>```

Title: Bootstrap dropdown menu doesn't open

Body:
Navber code:

                Home (current)

                  Behandelingen

                  Sportmassage
                  Massagetherapie
                  Ontspanningsmassage

                Afspraak maken

                Tarieven

                Contact

Bootstrap code:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Dropdown menu inside the navbar doesn't open, anyone an idea on how to fix this?
Not very experienced with bootstrap and don't now what the problem is.

Body:
Try this for Bootstrap 4 dropdown navbar

<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #fdfeff;">
  <a class="navbar-brand" href="#">
    <img src="images\logo1.png" width="200" height="80" class="d-inline-block align-top" alt="">
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navCollapse"
    aria-controls="navCollapse" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse justify-content-center" id="navCollapse">
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="index.html">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="navbar-nav dropdown">
        <a class="nav-link dropdown-toggle" type="button" id="dropdown01"
          data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Behandelingen
        </a>
        <div class="dropdown-menu" aria-labelledby="dropdown01">
          <a class="dropdown-item" href="sportmassage.html">Sportmassage</a>
          <a class="dropdown-item" href="#">Massagetherapie</a>
          <a class="dropdown-item" href="#">Ontspanningsmassage</a>
        </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Afspraak maken</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Tarieven</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Contact</a>
      </li>
    </ul>
  </div>
</nav>


来源: stackexchange

问:
ASP.NET MVC: Reuse of View by two controller actions
'Add' and 'Edit' views are typically more or less identical. How can I reuse a View so that Foos/Add and Foos/Edit/[Id] both use it? What would the actions look like?

Thanks

答:
Simply specify the view name when calling the View() method like

```<code>public ViewResult Add() {
  //...
  return View("Foo");
}

public ViewResult Edit(int id) {
  //...
  var model = repository.get(id);
  return View("Foo", model);
}
</code>```

Your view will have to handle null/empty model values for the Add action or you could populate your model with default values.

ContentLicense: CC BY-SA 3.0

Body:
Simply specify the view name when calling the View() method like

public ViewResult Add() {
  //...
  return View("Foo");
}

public ViewResult Edit(int id) {
  //...
  var model = repository.get(id);
  return View("Foo", model);
}

Your view will have to handle null/empty model values for the Add action or you could populate your model with default values.


问:
Issues with displaying and/or storing content of a Text File in C#
For my Intermediate C# Class I'm tasked with pulling and maintaining data in a .txt file connected to the program via a filestream. Everything I understand about my coding is correct but when the form loads it's not pulling the data. I've troubleshot it from every angle I can think of but I'm at a loss for where I am. I'll include the relevant bits of code below, but I have a class with methods specifically to handle the filestream and data fill, as well as a class for "Student Objects".

Here is the data in the .txt file that I'm trying to read

Jeff Dickson|100|97|68

Sharon Beaudry|95|76|87

Hallie Neupert|95|89|94

Here is the method I have in the StudentsDB class to pull from the source file

```<code>public static List<Student> GetStudents()
        {
            //Creates a new list to be returned
            List<Student> students = new List<Student>();
            //Creates a new file stream to read the data
            StreamReader filler = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
            //Starts the fill loop
            while(filler.Peek() != -1)
            {
                string row = filler.ReadLine();
                //Creates an array to fill with the line, deliniated by the pipe
                string[] columns = row.Split('|');
                //Creates an instantiation of the Student Class to use for filling purposes
                Student student = new Student();
                //Adds the student name from the array to the Student Object
                student.Name = columns[0];
                //Creates a loop that will go through the string array and pull the scores to add to the list
                //Converting them to integer in the process
                for (int i = 1; i < columns.Length; i++)
                {
                    student.Scores.Add(Convert.ToInt32(columns[i]));
                }
                //Adds the instance of the student object to the list
                students.Add(student);
            }
            //Closes the stream and returns the list
            filler.Close();
            return students;
</code>```

Here is the Student Class with the properties and methods:

```<code>public class Student
    {
        //General Constructor
        public Student()
        { }

        //Public Properties
        public string Name
        {
            get;
            set;
        }
        public List<int> Scores
        {
            get;
            set;
        }

        public string GetDisplayText()
        {
            string total = "";
            foreach (int score in Scores)
            {
                total += "|" + score;
            }
            return Name + total;
        }

    }
</code>```

And here is my method to fill the list box with each of the student items:

```<code>//Program wide variable for a list of students
        public List<Student> students = null;

        //Method to fill the list box
        private void FillBox()
        {
            //Clears the list box in order to allow for the data to be entered
            lstStudents.Items.Clear();
            //Fills the students list variable using the method from studentDB class
            students = studentDB.GetStudents();
            //Cycles throught the list and fills the list box
            foreach(Student s in students)
            {
                lstStudents.Items.Add(s.GetDisplayText());
            }
        }
</code>```

答:
You aren't initializing Student.Scores in the constructor, so it will be null. You can't add items to null.

It'd be easier to check whether .ReadLine() returns null and break if it does instead of Peeking the reader.

You should be using an using() block for the StreamReader instead of manually managing .Close().

Beyond that, things seem to work.

ContentLicense: CC BY-SA 4.0

Body:
For my Intermediate C# Class I'm tasked with pulling and maintaining data in a .txt file connected to the program via a filestream. Everything I understand about my coding is correct but when the form loads it's not pulling the data. I've troubleshot it from every angle I can think of but I'm at a loss for where I am. I'll include the relevant bits of code below, but I have a class with methods specifically to handle the filestream and data fill, as well as a class for "Student Objects".

Here is the data in the .txt file that I'm trying to read

Jeff Dickson|100|97|68

Sharon Beaudry|95|76|87

Hallie Neupert|95|89|94

Here is the method I have in the StudentsDB class to pull from the source file

public static List<Student> GetStudents()
        {
            //Creates a new list to be returned
            List<Student> students = new List<Student>();
            //Creates a new file stream to read the data
            StreamReader filler = new StreamReader(new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));
            //Starts the fill loop
            while(filler.Peek() != -1)
            {
                string row = filler.ReadLine();
                //Creates an array to fill with the line, deliniated by the pipe
                string[] columns = row.Split('|');
                //Creates an instantiation of the Student Class to use for filling purposes
                Student student = new Student();
                //Adds the student name from the array to the Student Object
                student.Name = columns[0];
                //Creates a loop that will go through the string array and pull the scores to add to the list
                //Converting them to integer in the process
                for (int i = 1; i < columns.Length; i++)
                {
                    student.Scores.Add(Convert.ToInt32(columns[i]));
                }
                //Adds the instance of the student object to the list
                students.Add(student);
            }
            //Closes the stream and returns the list
            filler.Close();
            return students;

Here is the Student Class with the properties and methods:

public class Student
    {
        //General Constructor
        public Student()
        { }

        //Public Properties
        public string Name
        {
            get;
            set;
        }
        public List<int> Scores
        {
            get;
            set;
        }

        public string GetDisplayText()
        {
            string total = "";
            foreach (int score in Scores)
            {
                total += "|" + score;
            }
            return Name + total;
        }

    }

And here is my method to fill the list box with each of the student items:

//Program wide variable for a list of students
        public List<Student> students = null;

        //Method to fill the list box
        private void FillBox()
        {
            //Clears the list box in order to allow for the data to be entered
            lstStudents.Items.Clear();
            //Fills the students list variable using the method from studentDB class
            students = studentDB.GetStudents();
            //Cycles throught the list and fills the list box
            foreach(Student s in students)
            {
                lstStudents.Items.Add(s.GetDisplayText());
            }
        }


答:
i've not tested this but i've had trouble before with accessing data in string arrays. in your GetStudents() function you have:

```<code> for (int i = 1; i < columns.Length; i++)

 {

     student.Scores.Add(Convert.ToInt32(columns[i]));
 }
</code>```

when i had a similar issue i did:

```<code> for (int i = 1; i < columns.Length -1; i++)

 {

     student.Scores.Add(Convert.ToInt32(columns[i]));
 }
</code>```

Arrays start at 0 in most programming languages. If you have an array of 3 elements, you have 3 positions available - positions 0, 1 and 2. As a result, fetching the length would return 3, so you need to subtract 1 to get the last element, the element at position 2.
https://www.neowin.net/forum/topic/639159-actionscript-arraylength-1/

Title: Issues with displaying and/or storing content of a Text File in C#

Body:
i've not tested this but i've had trouble before with accessing data in string arrays. in your GetStudents() function you have:

 for (int i = 1; i < columns.Length; i++)

 {

     student.Scores.Add(Convert.ToInt32(columns[i]));
 }

when i had a similar issue i did:

 for (int i = 1; i < columns.Length -1; i++)

 {

     student.Scores.Add(Convert.ToInt32(columns[i]));
 }

Arrays start at 0 in most programming languages. If you have an array of 3 elements, you have 3 positions available - positions 0, 1 and 2. As a result, fetching the length would return 3, so you need to subtract 1 to get the last element, the element at position 2.
https://www.neowin.net/forum/topic/639159-actionscript-arraylength-1/


问:
How do I properly install httplib2 on Google App Engine?
I copied my httplib2 directory into my GAE project, and now I'm getting the following error:

```<code>line 64, in <module> _ssl_wrap_socket = ssl.wrap_socket
</code>```

Is this an issue with Google App Engine, or did I somehow install my httplib2 incorrectly?

Full error dump, as request(it's big!):

```<code>--> --> -->
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 4053, in _HandleRequest
    self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3977, in _Dispatch
    base_env_dict=env_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 588, in Dispatch
    base_env_dict=base_env_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3050, in Dispatch
    self._module_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2954, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2834, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\main.py", line 25, in <module>
    import twitter as twitter
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2450, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2339, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2282, in LoadModuleRestricted
    description)
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\twitter.py", line 65, in <module>
    import oauth2 as oauth
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2450, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2339, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2282, in LoadModuleRestricted
    description)
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\oauth2\__init__.py", line 32, in <module>
    import httplib2
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2450, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2339, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2282, in LoadModuleRestricted
    description)
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\httplib2\__init__.py", line 64, in <module>
    _ssl_wrap_socket = ssl.wrap_socket
AttributeError: 'module' object has no attribute 'wrap_socket'
</code>```

Still having this issue. About the only thing I can think of that could possibly be causing this is my machine running Python 2.7; Is it possible that is causing the issue?

答:
As a workaround:

Can you use Google App Engine SDK 1.4.3 (this looks like a 1.5.0 regression).

Or force httplib2 fallback on httplib.FakeSocket with:

```<code>import sys
sys.modules['ssl'] = None
import httplib2
</code>```

A new issue has been filled there:
http://code.google.com/p/googleappengine/issues/detail?id=5064

It looks already fixed in httplib2 side:
http://code.google.com/p/httplib2/source/detail?r=cf721c1693a68e9438899be3d78acccae6ab0e30#

Body:
I copied my httplib2 directory into my GAE project, and now I'm getting the following error:

line 64, in <module> _ssl_wrap_socket = ssl.wrap_socket

Is this an issue with Google App Engine, or did I somehow install my httplib2 incorrectly?

Full error dump, as request(it's big!):

--> --> -->
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 4053, in _HandleRequest
    self._Dispatch(dispatcher, self.rfile, outfile, env_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3977, in _Dispatch
    base_env_dict=env_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 588, in Dispatch
    base_env_dict=base_env_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 3050, in Dispatch
    self._module_dict)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2954, in ExecuteCGI
    reset_modules = exec_script(handler_path, cgi_path, hook)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2834, in ExecuteOrImportScript
    exec module_code in script_module.__dict__
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\main.py", line 25, in <module>
    import twitter as twitter
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2450, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2339, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2282, in LoadModuleRestricted
    description)
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\twitter.py", line 65, in <module>
    import oauth2 as oauth
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2450, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2339, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2282, in LoadModuleRestricted
    description)
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\oauth2\__init__.py", line 32, in <module>
    import httplib2
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2450, in load_module
    return self.FindAndLoadModule(submodule, fullname, search_path)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2339, in FindAndLoadModule
    description)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 1505, in Decorate
    return func(self, *args, **kwargs)
  File "C:\Program Files (x86)\Google\google_appengine\google\appengine\tools\dev_appserver.py", line 2282, in LoadModuleRestricted
    description)
  File "C:\Users\quaunaut\Documents\Aptana Studio 3 Workspace\qushoutout\src\httplib2\__init__.py", line 64, in <module>
    _ssl_wrap_socket = ssl.wrap_socket
AttributeError: 'module' object has no attribute 'wrap_socket'

Still having this issue. About the only thing I can think of that could possibly be causing this is my machine running Python 2.7; Is it possible that is causing the issue?

Body:
As a workaround:

Can you use Google App Engine SDK 1.4.3 (this looks like a 1.5.0 regression).

Or force httplib2 fallback on httplib.FakeSocket with:

import sys
sys.modules['ssl'] = None
import httplib2

A new issue has been filled there:
http://code.google.com/p/googleappengine/issues/detail?id=5064

It looks already fixed in httplib2 side:
http://code.google.com/p/httplib2/source/detail?r=cf721c1693a68e9438899be3d78acccae6ab0e30#


问:
How do I make my Angular 8 application use the whole viewport?
I am developing a single-page application consisting of a navbar and a router-outlet which displays the component selected in the navbar. The primary component which loads by default is a Leaflet map which I would like to fill the entire page aside from the navbar. Currently I cannot even get the main component to fill the whole page, as it insists on including white space on the sides. I've set the container to have a high-res background image so I can see how much space it is actually filling.

The main page with all its unnecessary whitespace

The code:

app.component.html

```<code><body>
  <app-nav-menu></app-nav-menu>
  <div class="container" id="main-container">
    <router-outlet></router-outlet>
  </div>
</body>
</code>```

styles.css

```<code>body {
height: 98vh;
width: 98vw;
}

html, body, .container {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

#main-container {
  background-image: url("src/assets/chicago-wallpaper.jpg");
  width: 98vw;
  height: 94vh;
}
</code>```

答: Matthew Allen seems to have supplied the embarrassingly simple answer. Bootstrap had applied a max-width rule to .container, and setting "max-width: none" in styles.css lets the map fill the page.</p>

Body:
I am developing a single-page application consisting of a navbar and a router-outlet which displays the component selected in the navbar. The primary component which loads by default is a Leaflet map which I would like to fill the entire page aside from the navbar. Currently I cannot even get the main component to fill the whole page, as it insists on including white space on the sides. I've set the container to have a high-res background image so I can see how much space it is actually filling.

The main page with all its unnecessary whitespace

The code:

app.component.html

  <app-nav-menu></app-nav-menu>

    <router-outlet></router-outlet>

styles.css

body {
height: 98vh;
width: 98vw;
}

html, body, .container {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

#main-container {
  background-image: url("src/assets/chicago-wallpaper.jpg");
  width: 98vw;
  height: 94vh;
}


问:
Could not launch './qemu/linux-x86_64/qemu-system-i386': No such file or directory
With 25rc1 of the SDK tools I am having a problem when starting the emulators from $PATH

```<code>➜  ~  which emulator
/home/ligi/bin/android-sdk/tools/emulator
➜  ~  emulator @M
Could not launch './qemu/linux-x86_64/qemu-system-i386': No such file or directory
➜  ~  /home/ligi/bin/android-sdk/tools/emulator @M
console on port 5554, ADB on port 5555
</code>```

Anyone knows a workaround? I could write a script to start emulators and cd in tools before but perhaps there is a better solution.

答:
In Ubuntu 19.10!

With the environment variables already configured ($ANDROID_HOME), you should be able to list the AVDs, but if you are unable to start the AVD, do the following:

# Check the AVD target name

emulator -list-avds

# But to start do:

$ANDROID_HOME/emulator/emulator @avd_name

or

/home/$USER/Android/Sdk/emulator/emulator @avd_name

Body:
With 25rc1 of the SDK tools I am having a problem when starting the emulators from $PATH

➜  ~  which emulator
/home/ligi/bin/android-sdk/tools/emulator
➜  ~  emulator @M
Could not launch './qemu/linux-x86_64/qemu-system-i386': No such file or directory
➜  ~  /home/ligi/bin/android-sdk/tools/emulator @M
console on port 5554, ADB on port 5555

Anyone knows a workaround? I could write a script to start emulators and cd in tools before but perhaps there is a better solution.


问:
How to retrieve one random row for each category?
I would like to retrieve one random row for each user_group. How can I do this ?

Here find 2 tables, user and user_group.

user :

```<code>id
firstname
user_group_id
</code>```

user_group :

```<code>id
label
</code>```

Data

users

```<code>1 | Thor        | 1
2 | Iron man    | 2
3 | Hulk        | 3
4 | Groot       | 3
</code>```

user_groups

```<code>1 | admin
2 | support
3 | user
</code>```

Results expected

```<code>1 | Thor        | admin
2 | Iron man    | support
4 | Groot       | user (or 3 | Hulk | user)
</code>```

答:
A solution that can work with MySQL 5.7 and later

You can create a temporary table from users using ORDER BY rand() to order your users randomly.

Then you can user GROUP BY with ANY_VALUE() in that temporary table to get the id of a random user from that group and just JOIN with your tables to get the other data you want.

You can see a working example here:

https://www.db-fiddle.com/f/jtjPDxFVyzh4zGjXNbLAiL/5

```<code>CREATE TEMPORARY TABLE temp_tbl
SELECT * FROM `users` ORDER BY rand() ;

SELECT u.id,u.firstname,g.label FROM
(
SELECT ANY_VALUE(id) AS id FROM temp_tbl GROUP BY user_group_id
) t
INNER JOIN `users` u ON t.id=u.id
INNER JOIN `user_groups` g ON g.id=u.user_group_id
</code>```

Body:
I would like to retrieve one random row for each user_group. How can I do this ?

Here find 2 tables, user and user_group.

user :

id
firstname
user_group_id

user_group :

id
label

Data

users

1 | Thor        | 1
2 | Iron man    | 2
3 | Hulk        | 3
4 | Groot       | 3

user_groups

1 | admin
2 | support
3 | user

Results expected

1 | Thor        | admin
2 | Iron man    | support
4 | Groot       | user (or 3 | Hulk | user)

Body:
A solution that can work with MySQL 5.7 and later

You can create a temporary table from users using ORDER BY rand() to order your users randomly.

Then you can user GROUP BY with ANY_VALUE() in that temporary table to get the id of a random user from that group and just JOIN with your tables to get the other data you want.

You can see a working example here:

https://www.db-fiddle.com/f/jtjPDxFVyzh4zGjXNbLAiL/5

CREATE TEMPORARY TABLE temp_tbl
SELECT * FROM `users` ORDER BY rand() ;

SELECT u.id,u.firstname,g.label FROM
(
SELECT ANY_VALUE(id) AS id FROM temp_tbl GROUP BY user_group_id
) t
INNER JOIN `users` u ON t.id=u.id
INNER JOIN `user_groups` g ON g.id=u.user_group_id


问:
How do I define an array of objects in TypeScript?
I'm new to typescript plz help

I'm struggling to understand the error message for the below code. I'm just trying to define an array of objects and can't seem to figure out why it's not working?

```<code>interface FieldClass {
  id: string,
    name: string,
    type: string,
    label: string
}

const fields: FieldClass[] = [{
  id: 'name',
  name: 'input',
  type: 'name',
  label: 'Name',
}, {
  id: 'email',
  name: 'email',
  type: 'email',
  label: 'Email',
}, {
  id: 'password',
  name: 'password',
  type: 'password',
  label: 'Password',
}, , {
  id: 'confirm-password',
  name: 'confirm-password',
  type: 'confirm-password',
  label: 'Confirm password',
}];
</code>```

Error message:

```<code>Type '({ id: string; name: string; type: string; label: string; } | undefined)[]' is not assignable to type 'FieldClass[]'.
  Type '{ id: string; name: string; type: string; label: string; } | undefined' is not assignable to type 'FieldClass'.
    Type 'undefined' is not assignable to type 'FieldClass'.  TS2322
</code>```

答:
You have a type error here:

```<code>  label: 'Password',
}, , {
  id: 'confirm-password',
</code>```

Should be with one comma

```<code>  label: 'Password',
}, {
  id: 'confirm-password',
</code>```

Body:
I'm new to typescript plz help

I'm struggling to understand the error message for the below code. I'm just trying to define an array of objects and can't seem to figure out why it's not working?

interface FieldClass {
  id: string,
    name: string,
    type: string,
    label: string
}

const fields: FieldClass[] = [{
  id: 'name',
  name: 'input',
  type: 'name',
  label: 'Name',
}, {
  id: 'email',
  name: 'email',
  type: 'email',
  label: 'Email',
}, {
  id: 'password',
  name: 'password',
  type: 'password',
  label: 'Password',
}, , {
  id: 'confirm-password',
  name: 'confirm-password',
  type: 'confirm-password',
  label: 'Confirm password',
}];

Error message:

Type '({ id: string; name: string; type: string; label: string; } | undefined)[]' is not assignable to type 'FieldClass[]'.
  Type '{ id: string; name: string; type: string; label: string; } | undefined' is not assignable to type 'FieldClass'.
    Type 'undefined' is not assignable to type 'FieldClass'.  TS2322

Body:
You have a type error here:

  label: 'Password',
}, , {
  id: 'confirm-password',

Should be with one comma

  label: 'Password',
}, {
  id: 'confirm-password',


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答:
this answer is more or less correct. When you want something parametrized at compile time - you should prefer templates. When you want something parametrized at runtime, you should prefer virtual functions being overridden.

However, using templates does not preclude you from doing both (making the template version more flexible):

```<code>struct Brake {
    virtual void stopCar() = 0;
};

struct BrakeChooser {
    BrakeChooser(Brake *brake) : brake(brake) {}
    void stopCar() { brake->stopCar(); }

    Brake *brake;
};

template<class Brake>
struct Car
{
    Car(Brake brake = Brake()) : brake(brake) {}
    void slamTheBrakePedal() { brake.stopCar(); }

    Brake brake;
};

// instantiation
Car<BrakeChooser> car(BrakeChooser(new AntiLockBrakes()));
</code>```

That being said, I would probably NOT use templates for this... But its really just personal taste.

ContentLicense: CC BY-SA 2.5

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

Body:
this answer is more or less correct. When you want something parametrized at compile time - you should prefer templates. When you want something parametrized at runtime, you should prefer virtual functions being overridden.

However, using templates does not preclude you from doing both (making the template version more flexible):

struct Brake {
    virtual void stopCar() = 0;
};

struct BrakeChooser {
    BrakeChooser(Brake *brake) : brake(brake) {}
    void stopCar() { brake->stopCar(); }

    Brake *brake;
};

template<class Brake>
struct Car
{
    Car(Brake brake = Brake()) : brake(brake) {}
    void slamTheBrakePedal() { brake.stopCar(); }

    Brake brake;
};

// instantiation
Car<BrakeChooser> car(BrakeChooser(new AntiLockBrakes()));

That being said, I would probably NOT use templates for this... But its really just personal taste.

OwnerDisplayName: Greg Rogers


问:
Android retain callback state after configuration change
I understand pretty well about Android lifecycle. I post here because I've observed one weird behavior, anyway this is my own thought.

My case is like this: One activity will use a simple layout with just a single EditText. In the activity onCreate method, i set some default text to the EditText and in later part of the method, assign a TextWatcher to the EditText so whenever user types in anything, i can response in my own way.

Everything is alright until I rotate the screen. The TextWatcher callback starts to react against the code that initialize the EditText.

According to the normal code flow, the TextWatcher is assigned later after initializing text value of the EditText. so it's not supposed to fire because of the text assignment in the onCreate method.

Could anyone here explain this?

答:
When ever you rotate the device the onCreate method of activity called again.if you want to prevent to call onCreate when rotating the device do the following code in the Manifest

```<code>android:configChanges="orientation|keyboardHidden"
</code>```

and in your activity

```<code>public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);

    if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
    {

    }
    else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
    {

    }
}
</code>```

Body:
When ever you rotate the device the onCreate method of activity called again.if you want to prevent to call onCreate when rotating the device do the following code in the Manifest

android:configChanges="orientation|keyboardHidden"

and in your activity

public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);

    if(newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE)
    {

    }
    else if(newConfig.orientation==Configuration.ORIENTATION_PORTRAIT)
    {

    }
}


问:
R - convert DFM to LSA then compute cosine similarity: Error inherits(x, "Matrix") is not TRUE
I have a Document-Features-Matrix (DFM):
I want to convert it into a LSA object and finally to compute cosine similarity between each documents.

this are the passages I followed

```<code>lsa_t2 <- convert(DFM_tfidf, to = "lsa" , omit_empty = TRUE)
t2_lsa_tfidf_cos_sim = sim2(x = lsa_t2, method = "cosine", norm = "l2")
</code>```

but I get this error:

Error in sim2(x = lsa_t2, method = "cosine", norm = "l2") :

  inherits(x, "matrix") || inherits(x, "Matrix") is not TRUE

to give more context this is what las_t2 looks like

any of the documents contain text (I check it already) and I filtered outdocuments without text before I cleated the dfm.

Any idea of what happened?

答:
The error you receive basically means that the function sim2 does not work with the lsa object. However, I'm not really sure if I understand the question. Why do you want to convert the dfm to lsa textmatrix format in the first place?

If you want to calculate cosine similarity between texts, you can do this directly in quenteda

```<code>library(quanteda)

texts <- c(d1 = "Shipment of gold damaged in a fire",
           d2 = "Delivery of silver arrived in a silver truck",
           d3 = "Shipment of gold arrived in a truck" )

texts_dfm <- dfm(texts)

textstat_simil(texts_dfm,
               margin = "documents",
               method = "cosine")
#> textstat_simil object; method = "cosine"
#>       d1    d2    d3
#> d1 1.000 0.359 0.714
#> d2 0.359 1.000 0.598
#> d3 0.714 0.598 1.000
</code>```

If you want to use sim2 from text2vec, you can do so using the same object without converting it first:

```<code>library(text2vec)
sim2(x = texts_dfm, method = "cosine", norm = "l2")
#> 3 x 3 sparse Matrix of class "dsCMatrix"
#>           d1        d2        d3
#> d1 1.0000000 0.3585686 0.7142857
#> d2 0.3585686 1.0000000 0.5976143
#> d3 0.7142857 0.5976143 1.0000000
</code>```

As you can see, the results are the same.

Update

As by the comments, I now understand that you want to apply a transformation of your data via Latent semantic analysis. You can follow the tutorial linked below and plug in the dfm instead of the dtm that is used in the tutorial:

```<code>texts_dfm_tfidf <- dfm_tfidf(texts_dfm)

library(text2vec)
lsa = LSA$new(n_topics = 2)
dtm_tfidf_lsa = fit_transform(texts_dfm_tfidf, lsa) # I get a warning here, probably due to the size of the toy dfm
d1_d2_tfidf_cos_sim = sim2(x = dtm_tfidf_lsa, method = "cosine", norm = "l2")
d1_d2_tfidf_cos_sim
#>              d1           d2        d3           d4
#> d1  1.000000000 -0.002533794 0.5452992  0.999996189
#> d2 -0.002533794  1.000000000 0.8368571 -0.005294431
#> d3  0.545299245  0.836857086 1.0000000  0.542983071
#> d4  0.999996189 -0.005294431 0.5429831  1.000000000
</code>```

Note that these results differ from run to run unless you use set.seed().

Or if you want to do everything in quanteda:

```<code>texts_lsa <- textmodel_lsa(texts_dfm_tfidf, 2)

textstat_simil(as.dfm(texts_lsa$docs),
               margin = "documents",
               method = "cosine")
#> textstat_simil object; method = "cosine"
#>          d1       d2    d3       d4
#> d1  1.00000 -0.00684 0.648  1.00000
#> d2 -0.00684  1.00000 0.757 -0.00894
#> d3  0.64799  0.75720 1.000  0.64638
#> d4  1.00000 -0.00894 0.646  1.00000
</code>```

Body:
I have a Document-Features-Matrix (DFM):
I want to convert it into a LSA object and finally to compute cosine similarity between each documents.

this are the passages I followed

lsa_t2 <- convert(DFM_tfidf, to = "lsa" , omit_empty = TRUE)
t2_lsa_tfidf_cos_sim = sim2(x = lsa_t2, method = "cosine", norm = "l2")

but I get this error:

Error in sim2(x = lsa_t2, method = "cosine", norm = "l2") :

  inherits(x, "matrix") || inherits(x, "Matrix") is not TRUE

to give more context this is what las_t2 looks like

any of the documents contain text (I check it already) and I filtered outdocuments without text before I cleated the dfm.

Any idea of what happened?

Body:
The error you receive basically means that the function sim2 does not work with the lsa object. However, I'm not really sure if I understand the question. Why do you want to convert the dfm to lsa textmatrix format in the first place?

If you want to calculate cosine similarity between texts, you can do this directly in quenteda

library(quanteda)

texts <- c(d1 = "Shipment of gold damaged in a fire",
           d2 = "Delivery of silver arrived in a silver truck",
           d3 = "Shipment of gold arrived in a truck" )

texts_dfm <- dfm(texts)

textstat_simil(texts_dfm,
               margin = "documents",
               method = "cosine")
#> textstat_simil object; method = "cosine"
#>       d1    d2    d3
#> d1 1.000 0.359 0.714
#> d2 0.359 1.000 0.598
#> d3 0.714 0.598 1.000

If you want to use sim2 from text2vec, you can do so using the same object without converting it first:

library(text2vec)
sim2(x = texts_dfm, method = "cosine", norm = "l2")
#> 3 x 3 sparse Matrix of class "dsCMatrix"
#>           d1        d2        d3
#> d1 1.0000000 0.3585686 0.7142857
#> d2 0.3585686 1.0000000 0.5976143
#> d3 0.7142857 0.5976143 1.0000000

As you can see, the results are the same.

Update

As by the comments, I now understand that you want to apply a transformation of your data via Latent semantic analysis. You can follow the tutorial linked below and plug in the dfm instead of the dtm that is used in the tutorial:

texts_dfm_tfidf <- dfm_tfidf(texts_dfm)

library(text2vec)
lsa = LSA$new(n_topics = 2)
dtm_tfidf_lsa = fit_transform(texts_dfm_tfidf, lsa) # I get a warning here, probably due to the size of the toy dfm
d1_d2_tfidf_cos_sim = sim2(x = dtm_tfidf_lsa, method = "cosine", norm = "l2")
d1_d2_tfidf_cos_sim
#>              d1           d2        d3           d4
#> d1  1.000000000 -0.002533794 0.5452992  0.999996189
#> d2 -0.002533794  1.000000000 0.8368571 -0.005294431
#> d3  0.545299245  0.836857086 1.0000000  0.542983071
#> d4  0.999996189 -0.005294431 0.5429831  1.000000000

Note that these results differ from run to run unless you use set.seed().

Or if you want to do everything in quanteda:

texts_lsa <- textmodel_lsa(texts_dfm_tfidf, 2)

textstat_simil(as.dfm(texts_lsa$docs),
               margin = "documents",
               method = "cosine")
#> textstat_simil object; method = "cosine"
#>          d1       d2    d3       d4
#> d1  1.00000 -0.00684 0.648  1.00000
#> d2 -0.00684  1.00000 0.757 -0.00894
#> d3  0.64799  0.75720 1.000  0.64638
#> d4  1.00000 -0.00894 0.646  1.00000


问:
NameError: name 'dot' is not defined
I am using Tensorflow and Keras.I wrote codes,

```<code>from keras.layers import *

match = dot([input_encoded_m, question_encoded], axes=(2, 2))
</code>```

When I run it,

```<code>match = dot([input_encoded_m, question_encoded], axes=(2, 2))
NameError: name 'dot' is not defined
</code>```

error happens. I think by using import * , dot method can be called, but is it wrong? How should I fix this?

答: dot is a function of NumPy, you just call it by numpy.dot(x,y), it will work fine...</p>

Title: NameError: name 'dot' is not defined

Body:
I am using Tensorflow and Keras.I wrote codes,

from keras.layers import *

match = dot([input_encoded_m, question_encoded], axes=(2, 2))

When I run it,

match = dot([input_encoded_m, question_encoded], axes=(2, 2))
NameError: name 'dot' is not defined

error happens. I think by using import * , dot method can be called, but is it wrong? How should I fix this?


问:
Dismissing a modal view controller using a different animation than it was presented with
I have an application that presents a view controller (for registering / logging in) with a container view, and two views as switched between eachother using horizontal flipping. The app itself can be used before registration. I'm looking to change the way this is handled with storyboarding.

So upon opening the app there's a login button. If the user taps login a view controller is presented using Cover Vertical animation. On the top left of this view controller is a button to Register. Tapping on that does modal segue with a Horizontal Flip animation. On the Register view controller there's Login and Cancel buttons. I want Login to return to the login screen, and Cancel to go back to the view controller that was displayed using the Cover Vertical animation. Getting it there is fine, but the animation used is the Horizontal Flip animation, and not a (un)Cover Vertical animation.

I'ved tried the following code:

```<code>self.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
</code>```

before dismissing the view controller, but it's still flipping instead of uncovering.

Thanks for the help!

~James

答:
for Swift you can call this:</p>

```<code>viewController.modalTransitionStyle = .coverVertical
viewController.dismiss(animated: true, completion: nil)
</code>```

Body:
I have an application that presents a view controller (for registering / logging in) with a container view, and two views as switched between eachother using horizontal flipping. The app itself can be used before registration. I'm looking to change the way this is handled with storyboarding.

So upon opening the app there's a login button. If the user taps login a view controller is presented using Cover Vertical animation. On the top left of this view controller is a button to Register. Tapping on that does modal segue with a Horizontal Flip animation. On the Register view controller there's Login and Cancel buttons. I want Login to return to the login screen, and Cancel to go back to the view controller that was displayed using the Cover Vertical animation. Getting it there is fine, but the animation used is the Horizontal Flip animation, and not a (un)Cover Vertical animation.

I'ved tried the following code:

self.modalTransitionStyle = UIModalTransitionStyleCoverVertical;

before dismissing the view controller, but it's still flipping instead of uncovering.

Thanks for the help!

~James

Body:
for Swift you can call this:

viewController.modalTransitionStyle = .coverVertical
viewController.dismiss(animated: true, completion: nil)


问:
I am trying to get some data from user input into a JSON file.I get this message
I get this JSON error that tells me that I have a syntax error an I can't figure out where I made the mistake. I have provided the code in case if helps.

```<code> var isNode= typeof module !=="undefined"
var clientData;
var auxClientData;
var aux=[];
var k=0;
if (!isNode)
{
var storedObjects=JSON.parse(localStorage.getItem("objects"));
console.log(storedObjects);

var ok=false;
buttonConfirm.addEventListener("click",function(){
    for(var i=0;i<inputs.length;i++)
    {
        var inputShow=inputs[i].value;
        if (inputShow!=null && inputShow!="")
                {
                    aux[k++]=inputShow;
               }
               else
               {
                   alert("ALL THE FIELDS MUST BE COMPLETED! ");
                   ok=true;
                   break;
               }
    }
     clientData={fullName:aux[0],emailAddress:aux[1],phoneNumber:aux[2]};
    //localStorage.setItem("clientData",JSON.stringify(clientData));
   // console.log(clientData);
    if (ok==true){
        alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
    }
    console.log(JSON.parse(JSON.stringify(clientData)));
})

}
else
{
    var clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
    var fs=require("fs");
     auxClientData=JSON.stringify(clientData);

    fs.writeFile("clients.json",auxClientData,finished)
    function finished()
    {
        console.log("ok");
        var ok=fs.readFileSync("clients.json");
        var test=JSON.parse(ok);
        console.log(test);

    }

}
</code>```

Here is the error:

SyntaxError: Unexpected end of JSON input
      at JSON.parse ()

答:
I've just realised what the problem is :

```<code> var clientData;
 auxClientData=JSON.stringify(clientData);
</code>```

clientData inside your else statement is never set and it will be undefined. so you will need to redefine it inside the else. aux will need to be available and in scope further up your program for this to work. You can confirm my assumption by manually setting clientData to something else inside the else statement.

```<code>else
{
    var fs=require("fs");
    clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
     auxClientData=JSON.stringify(clientData);
    fs.writeFile("clients.json",auxClientData,finished)
    function finished()
    {
        console.log("ok");
    }
    var ok=fs.readFileSync("clients.json");
    var test=JSON.parse(ok);
    console.log(test);

}
</code>```

------------------------------YOUR CODE.

```<code>var isNode = typeof module !== "undefined"
var clientData;
var auxClientData;
var aux = [];
var k = 0;

if (!isNode) {

    // INSIDE THE IF
    var storedObjects = JSON.parse(localStorage.getItem("objects"));
    console.log(storedObjects);
    var ok = false;
    //add a listener inside the if statement for the click.
    buttonConfirm.addEventListener("click", function () {
         // when it is clicked.
        for (var i = 0; i < inputs.length; i++) {

            var inputShow = inputs[i].value;
            if (inputShow != null && inputShow != "") {
                //POPULATE THE AUX ARRAY adding one to k each time?
                // seems weird, why is this not aux[i] = inputShow;
                aux[k++] = inputShow;
            }
            else {
                alert("ALL THE FIELDS MUST BE COMPLETED! ");
                ok = true;
                break;
            }
        }
        clientData = { fullName: aux[0], emailAddress: aux[1], phoneNumber: aux[2] };
        //localStorage.setItem("clientData",JSON.stringify(clientData));
        // console.log(clientData);
        if (ok == true) {
            alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
        }
        console.log(JSON.parse(JSON.stringify(clientData)));
    })

}
else {

    //inside the else.
    //aux is an empty array here. so aux[0] = undefined, aux[1] = undefined etc.
    //i.e. the button hasn't been pressed to populate it at this point.
    var clientData = { "fullName": aux[0], "emailAddress": aux[1], "phoneNumber": aux[2] };
    var fs = require("fs");
    auxClientData = JSON.stringify(clientData);

    fs.writeFile("clients.json", auxClientData, finished)
    function finished() {
        console.log("ok");
        var ok = fs.readFileSync("clients.json");
        var test = JSON.parse(ok);
        console.log(test);

    }

}
</code>```

Body:
I get this JSON error that tells me that I have a syntax error an I can't figure out where I made the mistake. I have provided the code in case if helps.

 var isNode= typeof module !=="undefined"
var clientData;
var auxClientData;
var aux=[];
var k=0;
if (!isNode)
{
var storedObjects=JSON.parse(localStorage.getItem("objects"));
console.log(storedObjects);

var ok=false;
buttonConfirm.addEventListener("click",function(){
    for(var i=0;i<inputs.length;i++)
    {
        var inputShow=inputs[i].value;
        if (inputShow!=null && inputShow!="")
                {
                    aux[k++]=inputShow;
               }
               else
               {
                   alert("ALL THE FIELDS MUST BE COMPLETED! ");
                   ok=true;
                   break;
               }
    }
     clientData={fullName:aux[0],emailAddress:aux[1],phoneNumber:aux[2]};
    //localStorage.setItem("clientData",JSON.stringify(clientData));
   // console.log(clientData);
    if (ok==true){
        alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
    }
    console.log(JSON.parse(JSON.stringify(clientData)));
})

}
else
{
    var clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
    var fs=require("fs");
     auxClientData=JSON.stringify(clientData);

    fs.writeFile("clients.json",auxClientData,finished)
    function finished()
    {
        console.log("ok");
        var ok=fs.readFileSync("clients.json");
        var test=JSON.parse(ok);
        console.log(test);

    }

}

Here is the error:

SyntaxError: Unexpected end of JSON input
      at JSON.parse ()

Body:
I've just realised what the problem is :

 var clientData;
 auxClientData=JSON.stringify(clientData);

clientData inside your else statement is never set and it will be undefined. so you will need to redefine it inside the else. aux will need to be available and in scope further up your program for this to work. You can confirm my assumption by manually setting clientData to something else inside the else statement.

else
{
    var fs=require("fs");
    clientData={"fullName":aux[0],"emailAddress":aux[1],"phoneNumber":aux[2]};
     auxClientData=JSON.stringify(clientData);
    fs.writeFile("clients.json",auxClientData,finished)
    function finished()
    {
        console.log("ok");
    }
    var ok=fs.readFileSync("clients.json");
    var test=JSON.parse(ok);
    console.log(test);

}

------------------------------YOUR CODE.

var isNode = typeof module !== "undefined"
var clientData;
var auxClientData;
var aux = [];
var k = 0;

if (!isNode) {

    // INSIDE THE IF
    var storedObjects = JSON.parse(localStorage.getItem("objects"));
    console.log(storedObjects);
    var ok = false;
    //add a listener inside the if statement for the click.
    buttonConfirm.addEventListener("click", function () {
         // when it is clicked.
        for (var i = 0; i < inputs.length; i++) {

            var inputShow = inputs[i].value;
            if (inputShow != null && inputShow != "") {
                //POPULATE THE AUX ARRAY adding one to k each time?
                // seems weird, why is this not aux[i] = inputShow;
                aux[k++] = inputShow;
            }
            else {
                alert("ALL THE FIELDS MUST BE COMPLETED! ");
                ok = true;
                break;
            }
        }
        clientData = { fullName: aux[0], emailAddress: aux[1], phoneNumber: aux[2] };
        //localStorage.setItem("clientData",JSON.stringify(clientData));
        // console.log(clientData);
        if (ok == true) {
            alert("THANK YOU FOR YOUR PURCHASE! CHECK YOUR E-MAIL")
        }
        console.log(JSON.parse(JSON.stringify(clientData)));
    })

}
else {

    //inside the else.
    //aux is an empty array here. so aux[0] = undefined, aux[1] = undefined etc.
    //i.e. the button hasn't been pressed to populate it at this point.
    var clientData = { "fullName": aux[0], "emailAddress": aux[1], "phoneNumber": aux[2] };
    var fs = require("fs");
    auxClientData = JSON.stringify(clientData);

    fs.writeFile("clients.json", auxClientData, finished)
    function finished() {
        console.log("ok");
        var ok = fs.readFileSync("clients.json");
        var test = JSON.parse(ok);
        console.log(test);

    }

}


问:
Migrate From An IntegerField With Choices To A CharField
In Django I have a model with the following IntegerField.

```<code>GENDER_CHOICES = (
    (0, 'Male'),
    (1, 'Female'),
)
gender = models.IntegerField(choices=GENDER_CHOICES)
</code>```

I would like to altar this model to become a CharField using the choices.

```<code>GENDER_CHOICES = (
    ("MALE", 'Male'),
    ("FEMALE", 'Female'),
    ("NA", 'Id Rather Not Say'),
)
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)
</code>```

If I were to do this by running makemigrations and migrate I would lose the existing data in the database.

How would I make this (and similar) migrations without losing the existing data in the database?

Ideally I would do this in the migration itself that way it will run on the production server the second we use the migrate command.

答: Firstly, you can store your old field and add new field your model with new choices. After that you can run standalone code and map your old data to new field.</p>

Body:
In Django I have a model with the following IntegerField.

GENDER_CHOICES = (
    (0, 'Male'),
    (1, 'Female'),
)
gender = models.IntegerField(choices=GENDER_CHOICES)

I would like to altar this model to become a CharField using the choices.

GENDER_CHOICES = (
    ("MALE", 'Male'),
    ("FEMALE", 'Female'),
    ("NA", 'Id Rather Not Say'),
)
gender = models.CharField(choices=GENDER_CHOICES, max_length=10)

If I were to do this by running makemigrations and migrate I would lose the existing data in the database.

How would I make this (and similar) migrations without losing the existing data in the database?

Ideally I would do this in the migration itself that way it will run on the production server the second we use the migrate command.


问:
Monkey patch post install test
I have a problem with the post-install test and I want to Monkey Patch it like this.

import addons.product.tests.test_product_attribute_value_config
from addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueSetup
from odoo.tests import tagged

print(TestProductAttributeValueSetup)
print(addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches)
print("START")
@tagged('post_install', '-at_install')
class TestProductAttributeValueConfig(TestProductAttributeValueSetup):
    print("IN Class")
    def test_clear_caches(self):
        print("IN method")
        return

print("OUT")
addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches\
    = TestProductAttributeValueConfig.test_clear_caches
print("STOP")
```

<p>Here is the OUTPUT of my prints.</p>

```<class 'addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueSetup'>
<function TestProductAttributeValueConfig.test_clear_caches at 0x7f680f0c6d90>
START
IN Class
OUT
STOP
```

<p>The method in my monkey patch is never called and the test fails.</p>

```2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: ERROR: test_clear_caches (odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig)
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: ` The goal of this test is to make sure the cache is invalidated when it should be.
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: Traceback (most recent call last):
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `   File "/home/antonp/workspace/Odoo12/addons/product/tests/test_product_attribute_value_config.py", line 494, in test_clear_caches
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `     self.env['product.product'].browse(variant_id).unlink()
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `   File "/home/antonp/workspace/Odoo12/addons/product/tests/test_variants.py", line 781, in unlink
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `     raise Exception('just')
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: ` Exception: just
```

答:
You need to patch the absolute reference to  test_clear_caches:

```<code>odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches
</code>```

Try with the following code:

```<code>import odoo

@odoo.tests.tagged('post_install', '-at_install')
class TestProductAttributeValueConfig(
    odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig):

    def test_clear_caches(self):
        print("IN method")

odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches = \
    TestProductAttributeValueConfig.test_clear_caches
</code>```

Title: Monkey patch post install test

Body:
I have a problem with the post-install test and I want to Monkey Patch it like this.

import addons.product.tests.test_product_attribute_value_config
from addons.product.tests.test_product_attribute_value_config import TestProductAttributeValueSetup
from odoo.tests import tagged

print(TestProductAttributeValueSetup)
print(addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches)
print("START")
@tagged('post_install', '-at_install')
class TestProductAttributeValueConfig(TestProductAttributeValueSetup):
    print("IN Class")
    def test_clear_caches(self):
        print("IN method")
        return

print("OUT")
addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches\
    = TestProductAttributeValueConfig.test_clear_caches
print("STOP")

Here is the OUTPUT of my prints.

<class 'addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueSetup'>
<function TestProductAttributeValueConfig.test_clear_caches at 0x7f680f0c6d90>
START
IN Class
OUT
STOP

The method in my monkey patch is never called and the test fails.

2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: ERROR: test_clear_caches (odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig)
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: ` The goal of this test is to make sure the cache is invalidated when it should be.
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: Traceback (most recent call last):
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `   File "/home/antonp/workspace/Odoo12/addons/product/tests/test_product_attribute_value_config.py", line 494, in test_clear_caches
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `     self.env['product.product'].browse(variant_id).unlink()
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `   File "/home/antonp/workspace/Odoo12/addons/product/tests/test_variants.py", line 781, in unlink
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: `     raise Exception('just')
2020-02-14 09:20:23,851 840 ERROR test_60 odoo.addons.product.tests.test_product_attribute_value_config: ` Exception: just

Body:
You need to patch the absolute reference to  test_clear_caches:

odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches

Try with the following code:

import odoo

@odoo.tests.tagged('post_install', '-at_install')
class TestProductAttributeValueConfig(
    odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig):

    def test_clear_caches(self):
        print("IN method")

odoo.addons.product.tests.test_product_attribute_value_config.TestProductAttributeValueConfig.test_clear_caches = \
    TestProductAttributeValueConfig.test_clear_caches


问:
Gojs : How do I save data that belongs to the UI and not to the diagram?
I have a data array updated by the user but it is not part of the diagram.
How do I save it along with the diagram?</p>

答: You could have that Array be a property on the Model.modelData object.  That object is automatically written out by Model.toJson and read in again by Model.fromJson.  No nodes or links need exist for that information to be saved in the model.  However, the contents of the Array had better be serializable by that method and that static function if you are going to call them.


问:
Setting up Copper CoAP Plugin for Firefox
I'm trying to set up Copper on Firefox version 53.0.3 and I am aware that the extension/plugin is not available anymore for Firefox 56+. I followed the instructions on how to set it up (https://github.com/mkovatsc/Copper) and I'm stuck at creating the text file copper@vs.inf.ethz.ch in the extensions directory of my Firefox profile. I noticed that the extensions file should be an .xpi file. Do I need to write anything in the file like any other Firefox extension to make it work?. I'm pretty new at this and I could use some help from more experienced people. Thank you and have a nice day.</p>

答: Try in chrome browser!It perfectly works for me.Firefox in Cu4r is a little complex.</p>


问:
REST API design with admin views
I have API application with endpoints:

```<code>/api/v1/accounts
/api/v1/accounts/id
</code>```

API have authorization with roles (user, admin). Users can mark accounts as visible or hidden. If account is hidden then it's not visible in search (/api/v1/accounts) but want to allow search for admin in "user mode" (where hidden are hidden) and "admin mode" (where hidden are visible too). User can see their account even if its marked as hidden

What is the best way to achieve it? Add a parameter to detect if it's admin to every endpoint or create separated endpoints? (eg. /api/v1/accounts and /admin/api/v1/accounts). If I'm using mediator pattern shoud make separate queries/commands for admin (single principle responsibility) or keep in one? I'm searching best solution form my problem

答:
This is very opinionated question so no answer will be complete or single point of truth. I'm writing this, because the information is too much to fit into the comment section and I think I could provide you with some good guidelines in order to make the best decision for you.

I will also express my own opinion so you should have this in mind as well.

That being said, first of all I see that you are using .NET-Core and C# which kind of outlines one of the options that you have. Since at least ASP.NET MVC 3 we have the option to use areas which I feel will give you the behavior you want using the .NET way sort of speak. You can read about areas in .NET Core here and here is a short quote:

Consider using Areas in a project when:

The app is made of multiple high-level functional components that can be logically separated.

You want to partition the app so that each functional area can be worked on independently.

So the pros are that:

You get out of the box routing in the form of /admin/accounts/...

In the future if you need to add additional admin functionalities you can easily keep them separated which will make your code cleaner and easier to maintain

However I personally am not big fan of this approach. First it seems a little bit artificial to me. Usually you end up with 95% duplicated code and some small adjustments and at the end it's very questionable if the extra code that you need to maintain is worth the benefits that you get from this extra separation.

Maybe areas are viable options after all, but only if you have quite a lot of functionality that you can encapsulate inside it so that you get some real benefit.

Conclusion : You are able, and if you decide to resort to /admin/accounts/... solution I advice you to consider the area usage but I personally would not go there.

Second option
You may not complicate the project that much and just provide some extra routes to handle your specific needs. The problems with that are several I will outline those:

Very often the exception became the norm. Now you need some extra functionality for the admins, after some time you will need something for the managers..

Your resource identifiers will become very inconsistent, and even though it's not very professional I think it would be somewhat ugly to have such routes in your app.

Event though you are not obliged to make your services RESTful it would help if you follow some of the constraint that REST apply.

First, request should be stateless:

Each request from client to server must contain all of the information
  necessary to understand the request

In other words all that logic, that you are describing in your question, the request should contain the data that the server will need to return the correct response. In more practical terms I'm speaking about something like JWT where you can the Claims to pass that additional information about the user so the server can fetch you the correct data.

Second, Uniform interface :

REST is defined by four interface constraints: identification of
  resources; manipulation of resources through representations;
  self-descriptive messages; and, hypermedia as the engine of
  application state.

In your case, I think this is the most important constraint identification of resources To get the desired resource you don't actually need the admin part, it's part of the business logic of your application who can see what and all the information that the server need to fetch the correct data should be inside the request and not the URI.

Conclusion : I think that you should extend your request with some additional data in order to let the server perform the business logic and keep the routes as they are now.

HOWEVER
As you can see, things like areas exist and the people in Microsoft are much better API designers than me and you so there is no black/white answer here.

Hope at least I managed to give you some food for thought.

Title: REST API design with admin views

Body:
I have API application with endpoints:

/api/v1/accounts
/api/v1/accounts/id

API have authorization with roles (user, admin). Users can mark accounts as visible or hidden. If account is hidden then it's not visible in search (/api/v1/accounts) but want to allow search for admin in "user mode" (where hidden are hidden) and "admin mode" (where hidden are visible too). User can see their account even if its marked as hidden

What is the best way to achieve it? Add a parameter to detect if it's admin to every endpoint or create separated endpoints? (eg. /api/v1/accounts and /admin/api/v1/accounts). If I'm using mediator pattern shoud make separate queries/commands for admin (single principle responsibility) or keep in one? I'm searching best solution form my problem


问:
Link to an item on a paginated page in php
I'm quite a novice coder in PHP / MySQL. I am developing a site at the moment and have found many answers to some of the questions I have had on this site - Great Resource! - but now I need to ask one of my own which I'm struggling with. Do bear with me...

So on my site I have a side panel which shows testimonials from a database and randomly pulls in 1 result so that the testimonial showing changes every time the user navigates around the site. The side panel is an php include and is shown across the site. I am only showing a few lines of the testimonial and then including a read more link.

On the testimonials page, I have 13 testimonials paginated on 1 per page (13 pages) as each testimonial is quite long - that's how the client wants it.

What I am looking to do is to link from the 'Read More' link to the relevant testimonial - I assume using an html anchor is best? The issue I'm finding is that I can't seem to link to the relevant item on it's paginated page. If I use the testimonial ID I can link through to only page 1 of the testimonials.php and not to the specific page that the testimonial appears on. I hope this makes sense?

I have included a copy of my code from the Side Panel and also on the Testimonial page.

Any insight or help would be greatly appreciated.

Thanks.

Sidebar.php

```<code>$gettest = mysql_query ("SELECT * FROM testimonial ORDER BY RAND() LIMIT 1");

while ($row=mysql_fetch_array($gettest))
{
$testimonial = $row['testimonial'];
$shorttest = myTruncate($testimonial, 200, " ");
?>

<blockquote><span class="bqstart">“</span><p><?PHP echo $shorttest;?></p><span class="bqend">”</span></blockquote>
<p><a href="testimonials.php#<?PHP echo '' . $row["id"] . '';?>"><?PHP echo '' . $row["name"] . '';?></a></p>
<br clear='all' />

<?PHP
}
mysql_close($DB);
?>
</code>```

Testimonials.php

```<code><?php

include('connectDB.php');

$tableName="testimonial";
$targetpage = "testimonials.php";
$limit = 1;

$query = "SELECT COUNT(*) as num FROM testimonial";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

$stages = 3;
$page = mysql_escape_string($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}

// Get page data
$query1 = "SELECT * FROM testimonial LIMIT $start, $limit";
$result = mysql_query($query1);

// Initial page num setup
if ($page == 0){$page = 1;}
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages/$limit);
$LastPagem1 = $lastpage - 1;

$paginate = '';
if($lastpage > 1)
{

$paginate .= "<div class='paginate'>";
// Previous
if ($page > 1){
$paginate.= "<a href='$targetpage?page=$prev'>previous</a>";
}else{
$paginate.= "<span class='disabled'>previous</span>";   }

// Pages
if ($lastpage < 7 + ($stages * 2))  // Not enough pages to breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page){
 $paginate.= "<span class='current'>$counter</span>";
}else{
 $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
}
elseif($lastpage > 5 + ($stages * 2))   // Enough pages to hide a few?
{

// Beginning only hide later pages
if($page < 1 + ($stages * 2))
{
for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
{
 if ($counter == $page){
     $paginate.= "<span class='current'>$counter</span>";
 }else{
     $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
$paginate.= "...";
$paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>";
$paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
}

// Middle hide some front and some back
elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
{
$paginate.= "<a href='$targetpage?page=1'>1</a>";
$paginate.= "<a href='$targetpage?page=2'>2</a>";
$paginate.= "...";
for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
{
 if ($counter == $page){
     $paginate.= "<span class='current'>$counter</span>";
 }else{
     $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
$paginate.= "...";
$paginate.= "<a href='$targetpage?page=$LastPagem1'>$LastPagem1</a>";
$paginate.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";
}

// End only hide early pages
else
{
$paginate.= "<a href='$targetpage?page=1'>1</a>";
$paginate.= "<a href='$targetpage?page=2'>2</a>";
$paginate.= "...";
for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
{
 if ($counter == $page){
     $paginate.= "<span class='current'>$counter</span>";
 }else{
     $paginate.= "<a href='$targetpage?page=$counter'>$counter</a>";}
}
}

}

// Next
if ($page < $counter - 1){
$paginate.= "<a href='$targetpage?page=$next'>next</a>";
}else{
$paginate.= "<span class='disabled'>next</span>";
}

$paginate.= "</div>";

}
// pagination
echo $paginate;

?>

<?php

while($row = mysql_fetch_array($result))
{

?>
<a name="<?PHP echo '' . $row["ID"] . '';?>"></a>

<blockquote><span class="bqstart">“</span><p><?PHP echo '' .nl2br($row["testimonial"]) . '';?></p><span class="bqend">”</span></blockquote>
<p class="highlight"><?PHP echo '' . $row["name"] . '';?></p>
<br clear='all' />

<?PHP
}

echo $paginate;

mysql_close($DB);

?>
</code>```

答:
I'm not going to to go into all the changes you can do to your code, because right now it's messy.

You probably went lost in your own code.

Just change this line (on the sidebar.php), to:

```<code><p><a href="testimonials.php?page=<?PHP echo '' . $row["id"] . '';?>"><?PHP echo '' . $row["name"] . '';?></a></p>
</code>```

(similar to what you've already done on your "Testimonials.php" page.)

Body:
I'm quite a novice coder in PHP / MySQL. I am developing a site at the moment and have found many answers to some of the questions I have had on this site - Great Resource! - but now I need to ask one of my own which I'm struggling with. Do bear with me...

So on my site I have a side panel which shows testimonials from a database and randomly pulls in 1 result so that the testimonial showing changes every time the user navigates around the site. The side panel is an php include and is shown across the site. I am only showing a few lines of the testimonial and then including a read more link.

On the testimonials page, I have 13 testimonials paginated on 1 per page (13 pages) as each testimonial is quite long - that's how the client wants it.

What I am looking to do is to link from the 'Read More' link to the relevant testimonial - I assume using an html anchor is best? The issue I'm finding is that I can't seem to link to the relevant item on it's paginated page. If I use the testimonial ID I can link through to only page 1 of the testimonials.php and not to the specific page that the testimonial appears on. I hope this makes sense?

I have included a copy of my code from the Side Panel and also on the Testimonial page.

Any insight or help would be greatly appreciated.

Thanks.

Sidebar.php

$gettest = mysql_query ("SELECT * FROM testimonial ORDER BY RAND() LIMIT 1");

while ($row=mysql_fetch_array($gettest))
{
$testimonial = $row['testimonial'];
$shorttest = myTruncate($testimonial, 200, " ");
?>

“
<?PHP echo $shorttest;?>
”

<a href="testimonials.php#<?PHP echo '' . $row["id"] . '';?>"><?PHP echo '' . $row["name"] . '';?>

<?PHP
}
mysql_close($DB);
?>

Testimonials.php

<?php

include('connectDB.php');

$tableName="testimonial";
$targetpage = "testimonials.php";
$limit = 1;

$query = "SELECT COUNT(*) as num FROM testimonial";
$total_pages = mysql_fetch_array(mysql_query($query));
$total_pages = $total_pages[num];

$stages = 3;
$page = mysql_escape_string($_GET['page']);
if($page){
$start = ($page - 1) * $limit;
}else{
$start = 0;
}

// Get page data
$query1 = "SELECT * FROM testimonial LIMIT $start, $limit";
$result = mysql_query($query1);

// Initial page num setup
if ($page == 0){$page = 1;}
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages/$limit);
$LastPagem1 = $lastpage - 1;

$paginate = '';
if($lastpage > 1)
{

$paginate .= "
";
// Previous
if ($page > 1){
$paginate.= "previous";
}else{
$paginate.= "previous";   }

// Pages
if ($lastpage < 7 + ($stages * 2))  // Not enough pages to breaking it up
{
for ($counter = 1; $counter <= $lastpage; $counter++)
{
if ($counter == $page){
 $paginate.= "$counter";
}else{
 $paginate.= "$counter";}
}
}
elseif($lastpage > 5 + ($stages * 2))   // Enough pages to hide a few?
{

// Beginning only hide later pages
if($page < 1 + ($stages * 2))
{
for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
{
 if ($counter == $page){
     $paginate.= "$counter";
 }else{
     $paginate.= "$counter";}
}
$paginate.= "...";
$paginate.= "$LastPagem1";
$paginate.= "$lastpage";
}

// Middle hide some front and some back
elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
{
$paginate.= "1";
$paginate.= "2";
$paginate.= "...";
for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
{
 if ($counter == $page){
     $paginate.= "$counter";
 }else{
     $paginate.= "$counter";}
}
$paginate.= "...";
$paginate.= "$LastPagem1";
$paginate.= "$lastpage";
}

// End only hide early pages
else
{
$paginate.= "1";
$paginate.= "2";
$paginate.= "...";
for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
{
 if ($counter == $page){
     $paginate.= "$counter";
 }else{
     $paginate.= "$counter";}
}
}

}

// Next
if ($page < $counter - 1){
$paginate.= "next";
}else{
$paginate.= "next";
}

$paginate.= "
";

}
// pagination
echo $paginate;

?>

<?php

while($row = mysql_fetch_array($result))
{

?>
<a name="<?PHP echo '' . $row["ID"] . '';?>">

“
<?PHP echo '' .nl2br($row["testimonial"]) . '';?>
”

<?PHP echo '' . $row["name"] . '';?>

<?PHP
}

echo $paginate;

mysql_close($DB);

?>

Body:
I'm not going to to go into all the changes you can do to your code, because right now it's messy.

You probably went lost in your own code.

Just change this line (on the sidebar.php), to:

<p><a href="testimonials.php?page=<?PHP echo '' . $row["id"] . '';?>"><?PHP echo '' . $row["name"] . '';?></a></p>

(similar to what you've already done on your "Testimonials.php" page.)


问:
Why is my class styling not being recognized?? React
I'm mapping an object in the state called items2

```<code>items2: [
  {
    id: 1,
    title: 'TRENDING ON THE COURT',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/8ef2ada7-0cf4-43d4-a0a1-4a60e3071b06/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/1b387797-073a-4f60-8b67-9485c23ca556/jordan.jpg',
    image1title: 'AIR JORDAN XXXIV SE',
    image2header: 'L.A BORN',
    image2title: 'JORDAN "WHY NOT?" ZERO.3',
    a1text: 'Shop',
    a2text: 'Shop'

  },
  {
    id: 2,
    title: 'TRENDING ON THE STREETS',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/ac454c04-2d8b-4cf5-b73a-7245545b6f7c/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/de7332be-8c0d-405f-af9e-201ba9f61ab3/jordan.jpg',
    image1title: 'JORDAN AIR MAX 200',
    image2title: "JORDAN WOMEN'S FLIGHT CAPSULE",
    a1text: 'Shop',
    a2text: 'Shop'
  },
  {
    id: 3,
    title: 'MEMBER ACCESS',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/2225370e-a461-4ea3-ac94-3ece70dc3575/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/037f5213-a631-4e91-9c70-9187aefda947/jordan.jpg',
    image1header: "'JORDAN UNITE COLLECTION'",
    image1title: 'AIR JORDAN III',
    image2title: "GET JORDAN'S LATEST",
    a1text: 'Shop Now',
    a2text: 'Download SNKRS'
  },
  {
    id: 4,
    title: 'EXPLORE MORE FROM JORDAN',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/063f62a9-28b5-4f40-9e06-a894f5c469dd/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/6d0400bf-5378-4ec5-85f1-40145fce3d30/jordan.jpg',
    image1title: 'STORIES UNITING THE COMMUNITY',
    image2title: 'THE ULTIMATE HISTORY OF AIR JORDAN',
    a1text: 'Explore',
    a2text: 'Explore'

  }
]
</code>```

And rendering those items:

```<code>renderItems2 = () => {
  return (
    <div className='items2-container'>
      {this.state.items2.map(item => {
        return (
          <div className='item2-card' key={item.id}>
            <h2>{item.title}</h2>
            <img src={item.image1} />
            <div>
              <h6>{item.image1header}</h6>
              <h2>{item.image1title}</h2>
              <a className={item.a1text !== 'Shop' ? '.shop-now' : '.shop'}>{item.a1text}</a>

            </div>
            <img src={item.image2} />
            <div>
              <h6>{item.image2header}</h6>
              <h2>{item.image2title}</h2>
              <a className={item.a2text !== 'Shop' ? '.shop-now' : '.shop'}>{item.a2text}</a>
            </div>

          </div>
        )
      })}
    </div>
  )
}
</code>```

The good thing is everything renders properly and I get no errors in my console. I was trying to use ternary's to change class name for my  elements based on what is in state and the logic works because the class does change in chrome dev tools! However when I inspect it the styling that I imported from my css file specifically is not applied/does not work and only shows element.style {} for that specific element. I checked to see if my import for my stylesheet was the issue but other elements are styled correctly. I have also tried using !important for the css and checked if there were any other css files that style .shop and .shop-now accidentally in which there weren't.

```<code>.shop {
    padding-top: 11px;
    padding-bottom: 9px;
    padding-left: 24px;
    width: 40%;
    padding-right: 24px;
    border-radius: 20px;
    background-color: #fff;
    color: #111;
}

.shop-now {
    padding: 20px;
    border-radius: 20px;
    background: #fff;
    color: #111;
}
</code>```

答:
You should remove the . in your className reference e.g. 'shop-now' instead of '.shop-now':

```<code><a className={item.a2text !== 'Shop' ? 'shop-now' : 'shop'}>{item.a2text}</a>
</code>```

CSS class names should be defined with a . in your stylesheets, but referenced on HTML elements without the .

Body:
I'm mapping an object in the state called items2

items2: [
  {
    id: 1,
    title: 'TRENDING ON THE COURT',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/8ef2ada7-0cf4-43d4-a0a1-4a60e3071b06/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/1b387797-073a-4f60-8b67-9485c23ca556/jordan.jpg',
    image1title: 'AIR JORDAN XXXIV SE',
    image2header: 'L.A BORN',
    image2title: 'JORDAN "WHY NOT?" ZERO.3',
    a1text: 'Shop',
    a2text: 'Shop'

  },
  {
    id: 2,
    title: 'TRENDING ON THE STREETS',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/ac454c04-2d8b-4cf5-b73a-7245545b6f7c/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/de7332be-8c0d-405f-af9e-201ba9f61ab3/jordan.jpg',
    image1title: 'JORDAN AIR MAX 200',
    image2title: "JORDAN WOMEN'S FLIGHT CAPSULE",
    a1text: 'Shop',
    a2text: 'Shop'
  },
  {
    id: 3,
    title: 'MEMBER ACCESS',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/2225370e-a461-4ea3-ac94-3ece70dc3575/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/037f5213-a631-4e91-9c70-9187aefda947/jordan.jpg',
    image1header: "'JORDAN UNITE COLLECTION'",
    image1title: 'AIR JORDAN III',
    image2title: "GET JORDAN'S LATEST",
    a1text: 'Shop Now',
    a2text: 'Download SNKRS'
  },
  {
    id: 4,
    title: 'EXPLORE MORE FROM JORDAN',
    image1: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/063f62a9-28b5-4f40-9e06-a894f5c469dd/jordan.jpg',
    image2: 'https://c.static-nike.com/a/images/f_auto/dpr_2.0/h_500,c_limit/6d0400bf-5378-4ec5-85f1-40145fce3d30/jordan.jpg',
    image1title: 'STORIES UNITING THE COMMUNITY',
    image2title: 'THE ULTIMATE HISTORY OF AIR JORDAN',
    a1text: 'Explore',
    a2text: 'Explore'

  }
]

And rendering those items:

renderItems2 = () => {
  return (

      {this.state.items2.map(item => {
        return (

{item.title}

{item.image1header}

{item.image1title}

              {item.a1text}

{item.image2header}

{item.image2title}

              {item.a2text}

        )
      })}

  )
}

The good thing is everything renders properly and I get no errors in my console. I was trying to use ternary's to change class name for my  elements based on what is in state and the logic works because the class does change in chrome dev tools! However when I inspect it the styling that I imported from my css file specifically is not applied/does not work and only shows element.style {} for that specific element. I checked to see if my import for my stylesheet was the issue but other elements are styled correctly. I have also tried using !important for the css and checked if there were any other css files that style .shop and .shop-now accidentally in which there weren't.

.shop {
    padding-top: 11px;
    padding-bottom: 9px;
    padding-left: 24px;
    width: 40%;
    padding-right: 24px;
    border-radius: 20px;
    background-color: #fff;
    color: #111;
}

.shop-now {
    padding: 20px;
    border-radius: 20px;
    background: #fff;
    color: #111;
}

Body:
You should remove the . in your className reference e.g. 'shop-now' instead of '.shop-now':

<a className={item.a2text !== 'Shop' ? 'shop-now' : 'shop'}>{item.a2text}</a>

CSS class names should be defined with a . in your stylesheets, but referenced on HTML elements without the .


问:
Which IDE (Android Studio and Visual Code) is better in terms of less memory consumption for Android application development?
I have 4GB RAM and Intel HD graphics so suggest to me in that way which one to choose between Android Studio and Visual Code for android app dev.?</p>

答:
Just check minimum system requirements:

Android Studio: https://developer.android.com/studio

Visual Studio Code: https://code.visualstudio.com/docs/supporting/requirements

It looks like Android Studio recommends 8gb of RAM and Visual Studio 1gb

But the best idea is to check both and check which one works better for you and which one suits you better


答:
You'll need a data migration (as I recently outlined in this answer: How to modify a models who's already migrated in Database?), but the steps are:

rename gender to gender_integer (or similar); make a migration out of that

add the new gender field; make a migration out of that

create a data migration to map gender_integer's content to gender (see the link above)

remove gender_integer; make a migration out of that.

Title: Migrate From An IntegerField With Choices To A CharField