问:
React Hook to find user
I am trying to use the React useState Hook for an online project. What I want to happen is, when I type the users name in the search box, It will find the users card on the browser. I am able to log the user to the console, but I am stuck on how to get it to render on screen. Tried so many ways and just not getting it.

console output

App.js

```<code>import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput] = useState('');

  function onSearchChange(e) {

    searchInput = e.target.value;

    const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  }

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      <CardList id={robots.id} name={robots.name} email={robots.email}/>
    </div>
  );
}

export default App;
</code>```

CardList.js

```<code>import React from 'react';
import Card from './Card';
import {robots} from './robots';

function CardList(props) {
  return (
    <div>
    {
      robots.map(function(user) {
        return <Card key={user.id} id={user.id} name={user.name} email={user.email} />
      })
    };
  </div> )
}

export default CardList;
</code>```

Card.js

```<code>import React from 'react';
import 'tachyons';

function Card(props) {
  return (
    <div className='bg-light-green dib br3 pa3 ma2 grow shadow-5'>
      <img src={`https://robohash.org/${props.id}`} alt="Robot" />
      <h2>{props.name}</h2>
      <p>{props.email}</p>
    </div>
  );
}

export default Card;
</code>```

答:
You should not be mutating the searchInput value like searchInput = e.target.value. It is better to call a setter function to update the value. For example,

```<code>const [searchInput, setSearchInput] = useState('');

// to update the value of searchInput call setSearchInput
function onSearchChange(e) {
    setSearchInput(e.target.value)
}

</code>```

State changes are asynchronous. When you try to filter the robots it is not guaranteed that it will be called with the latest value of searchInput that's why you should be using useEffect hook which will filter the robots when the value of searchInput changes.

Here is a solution,

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput, setSearchInput] = useState('');
  let [filterdRobots, setFilteredRobots] = useState(robots);

  function onSearchChange(e) {
    setSearchInput(e.target.value);
  }

  useEffect(() => {
     setFilteredRobots(robots.filter(r =>
       r.name.toLowerCase().includes(searchInput.toLowerCase())))
  }, [searchInput, robots])

  return (

RoboFriends

      <SearchBox searchChange={onSearchChange} />
      <CardList robots={filteredRobots}/>

  );
}

export default App;

```

check the codesanbox for demo

Title: React Hook to find user

Body:
I am trying to use the React useState Hook for an online project. What I want to happen is, when I type the users name in the search box, It will find the users card on the browser. I am able to log the user to the console, but I am stuck on how to get it to render on screen. Tried so many ways and just not getting it.

console output

App.js

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput] = useState('');

  function onSearchChange(e) {

    searchInput = e.target.value;

    const filteredRobots = robots.filter(function(robot){
      return robot.name.toLowerCase().includes(searchInput.toLowerCase());
    });

    console.log(filteredRobots);

  }

  return (

RoboFriends

      <SearchBox searchChange={onSearchChange} />
      <CardList id={robots.id} name={robots.name} email={robots.email}/>

  );
}

export default App;

CardList.js

import React from 'react';
import Card from './Card';
import {robots} from './robots';

function CardList(props) {
  return (

    {
      robots.map(function(user) {
        return <Card key={user.id} id={user.id} name={user.name} email={user.email} />
      })
    };

 )
}

export default CardList;

Card.js

import React from 'react';
import 'tachyons';

function Card(props) {
  return (

      <img src={`https://robohash.org/${props.id}`} alt="Robot" />

{props.name}

{props.email}

  );
}

export default Card;

Body:
You should not be mutating the searchInput value like searchInput = e.target.value. It is better to call a setter function to update the value. For example,

const [searchInput, setSearchInput] = useState('');

// to update the value of searchInput call setSearchInput
function onSearchChange(e) {
    setSearchInput(e.target.value)
}

State changes are asynchronous. When you try to filter the robots it is not guaranteed that it will be called with the latest value of searchInput that's why you should be using useEffect hook which will filter the robots when the value of searchInput changes.

Here is a solution,

import React, { useState } from 'react';
import CardList from './CardList';
import {robots} from './robots';
import SearchBox from './SearchBox';

function App() {

  let [searchInput, setSearchInput] = useState('');
  let [filterdRobots, setFilteredRobots] = useState(robots);

  function onSearchChange(e) {
    setSearchInput(e.target.value);
  }

  useEffect(() => {
     setFilteredRobots(robots.filter(r =>
       r.name.toLowerCase().includes(searchInput.toLowerCase())))
  }, [searchInput, robots])

  return (
    <div className='tc'>
      <h1>RoboFriends</h1>
      <SearchBox searchChange={onSearchChange} />
      <CardList robots={filteredRobots}/>
    </div>
  );
}

export default App;

check the codesanbox for demo


来源: stackexchange

问:
How to make dotnet publish command use private Nuget sources
I am using VS2019 (16.4) within a company walls. I changed the VS Nuget sources and my solution compiles and runs after several requests to our internal foundation to approve Nuget packages.

Now I am trying to use the dotnet publish command, but it fails miserably with bunch of errors such as: error NU1605: Detected package downgrade: System.Runtime.Extensions from 4.3.0 to 4.1.0. Reference the package directly from the project to select a different version..

I figured it is probably not cognizant of the private Nuget sources.....so I searched around and the solution seems to be to include a NuGet.Config file at the solution root:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="Company Artifactory" value="https://repo.comany.com/artifactory/api/nuget/comany-nuget" />
    <add key="Company Eval Artifactory" value="https://repo.comany.com/artifactory/api/nuget/comany-nuget-eval" />
  </packageSources>
</configuration>
</code>```

This did not help.   It seems that there is a new dotnet command that will allow adding sources via the CLI: https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-add-source but unfortunately our version is is 3.1.100 and the new command is applicable to 3.1.200...yes...it will take an act congress to get the new version in our company.

Any help is appreciated.

答:
Thanks @omajid for your help. Here is what works for me:

In each project root folder:

dotnet restore

dotnet build --configuration Release

dotnet publish --no-restore -r win-x64 -c Release -o c:\somwhere /p:PublishSingleFile=true /p:DebugType=None

The above requires that we add the runtime identifier to the project file:

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
    <AssemblyVersion>0.0.2.0</AssemblyVersion>
</PropertyGroup>
```

Unfortunately, restore with runtime identifier did not work (same errors as in my original problem) which would probably mean that a runtime identifier is not needed in the project file:

dotnet restore --runtime win-x64

My initial observation was incorrect! Nuget sources were NOT causing the restore problems in publish....it was the runtime identifier. I still do not know why the error was manifested the way it did ...but calling dotnet publish with --no-restore switch seems to have done it for me.

The problem remains as to why dotnet restore --runtime win-x64 fails.

ContentLicense: CC BY-SA 4.0

Body:
I am using VS2019 (16.4) within a company walls. I changed the VS Nuget sources and my solution compiles and runs after several requests to our internal foundation to approve Nuget packages.

Now I am trying to use the dotnet publish command, but it fails miserably with bunch of errors such as: error NU1605: Detected package downgrade: System.Runtime.Extensions from 4.3.0 to 4.1.0. Reference the package directly from the project to select a different version..

I figured it is probably not cognizant of the private Nuget sources.....so I searched around and the solution seems to be to include a NuGet.Config file at the solution root:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="Company Artifactory" value="https://repo.comany.com/artifactory/api/nuget/comany-nuget" />
    <add key="Company Eval Artifactory" value="https://repo.comany.com/artifactory/api/nuget/comany-nuget-eval" />
  </packageSources>
</configuration>

This did not help.   It seems that there is a new dotnet command that will allow adding sources via the CLI: https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-nuget-add-source but unfortunately our version is is 3.1.100 and the new command is applicable to 3.1.200...yes...it will take an act congress to get the new version in our company.

Any help is appreciated.

Body:
Thanks @omajid for your help. Here is what works for me:

In each project root folder:

dotnet restore

dotnet build --configuration Release

dotnet publish --no-restore -r win-x64 -c Release -o c:\somwhere /p:PublishSingleFile=true /p:DebugType=None

The above requires that we add the runtime identifier to the project file:

<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
    <AssemblyVersion>0.0.2.0</AssemblyVersion>
</PropertyGroup>

Unfortunately, restore with runtime identifier did not work (same errors as in my original problem) which would probably mean that a runtime identifier is not needed in the project file:

dotnet restore --runtime win-x64

My initial observation was incorrect! Nuget sources were NOT causing the restore problems in publish....it was the runtime identifier. I still do not know why the error was manifested the way it did ...but calling dotnet publish with --no-restore switch seems to have done it for me.

The problem remains as to why dotnet restore --runtime win-x64 fails.


问:
Accessing information from a struct
I am trying to add annotations to a map but I am having trouble accessing the different variables stored in my struct. I would like to set the name, latitude and longitude to draw off of an element in the variable restaurants. However, when trying to implement the latitude, longitude and name, I get error messages. How would I do this so that I can access any restaurant's name, latitude and longitude inside of my variable. </p>

<p>Here is my code. </p>

```<code>import UIKit
import MapKit

struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double

init(name: String, latitude: Double, longitude: Double) {
    self.name = name
    self.latitude = latitude
    self.longitude = longitude
}
}

class MapViewController: UIViewController {

var restaurants = [PlacesOnMap(name: "Pete's", latitude: -73.2455, longitude: 65.4443),
    PlacesOnMap(name: "Bake shop on 5th", latitude: 34.55555, longitude: 34.3333),
    PlacesOnMap(name: "Italian", latitude: -33.4444, longitude: 43.567)
]

@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

}

func setRestaurantsAnnotations() {
    let places = MKPointAnnotation()
    places.coordinate = CLLocationCoordinate2D(latitude: restaurants.latitude, longitude: restaurants.longitude) //I get the error: Value of type '[PlacesOnMap]' has no member 'latitude' or 'longitude'
    places.title = restaurants.name //I get the error: Value of type '[PlacesOnMap]' has no member 'name'
    mapView.addAnnotation(places)
}
}
</code>```

答:
Actually this is what you want to do:

```<code>restaurants.forEach { placeOnMap in
    let place = MKPointAnnotation()
    place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
    place.title = placeOnMap.name
    mapView.addAnnotation(place)
}
</code>```

As mentioned by @matt in the comments section, restaurant is an array of PlacesOnMap. Your goal is to add these places to the map, so you need to convert each of these places to a CLLocationCoordinate2D instance and then add it to your map.

Alternatively, you can do it this way:

```<code>let places = restaurants.map { placeOnMap -> MKPointAnnotation in
    let place = MKPointAnnotation()
    place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
    place.title = placeOnMap.name
    return place
}
mapView.addAnnotations(places)
</code>```

In this one, you're mapping the array of restaurants that you have into an array of MKPointAnnotation instances and then you just pass this array to the mapView.

Title: Accessing information from a struct

Body:
I am trying to add annotations to a map but I am having trouble accessing the different variables stored in my struct. I would like to set the name, latitude and longitude to draw off of an element in the variable restaurants. However, when trying to implement the latitude, longitude and name, I get error messages. How would I do this so that I can access any restaurant's name, latitude and longitude inside of my variable.

Here is my code.

import UIKit
import MapKit

struct PlacesOnMap {
var name: String
var latitude: Double
var longitude: Double

init(name: String, latitude: Double, longitude: Double) {
    self.name = name
    self.latitude = latitude
    self.longitude = longitude
}
}

class MapViewController: UIViewController {

var restaurants = [PlacesOnMap(name: "Pete's", latitude: -73.2455, longitude: 65.4443),
    PlacesOnMap(name: "Bake shop on 5th", latitude: 34.55555, longitude: 34.3333),
    PlacesOnMap(name: "Italian", latitude: -33.4444, longitude: 43.567)
]

@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

}

func setRestaurantsAnnotations() {
    let places = MKPointAnnotation()
    places.coordinate = CLLocationCoordinate2D(latitude: restaurants.latitude, longitude: restaurants.longitude) //I get the error: Value of type '[PlacesOnMap]' has no member 'latitude' or 'longitude'
    places.title = restaurants.name //I get the error: Value of type '[PlacesOnMap]' has no member 'name'
    mapView.addAnnotation(places)
}
}

Body:
Actually this is what you want to do:

restaurants.forEach { placeOnMap in
    let place = MKPointAnnotation()
    place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
    place.title = placeOnMap.name
    mapView.addAnnotation(place)
}

As mentioned by @matt in the comments section, restaurant is an array of PlacesOnMap. Your goal is to add these places to the map, so you need to convert each of these places to a CLLocationCoordinate2D instance and then add it to your map.

Alternatively, you can do it this way:

let places = restaurants.map { placeOnMap -> MKPointAnnotation in
    let place = MKPointAnnotation()
    place.coordinate =  CLLocationCoordinate2D(latitude: placeOnMap.latitude, longitude: placeOnMap.longitude)
    place.title = placeOnMap.name
    return place
}
mapView.addAnnotations(places)

In this one, you're mapping the array of restaurants that you have into an array of MKPointAnnotation instances and then you just pass this array to the mapView.


问:
Same partial view on one page, how to handle binding?
I am still new to MVC. I am currently having a add person page, the page includes person first name, last name and home address which is complex object (include addressline1,addressline2, state etc), delivery address (same to home address).

So I'd like to create a partial view which use to display address, but when I submit the form, I can't distinguish which value is for home address, coz home address and delivery address render the same name on the form.

MyClass

```<code> Public class Person
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int DateOfBirthMonth { get; set; }
    public Gender Sex { get; set; }

    public AddressModel HomeAddress { get; set; }
    public AddressModel DeliveryAddress { get; set; }

    public Person()
    {
        HomeAddress = new AddressModel();
        DeliveryAddress = new AddressModel();
    }
}

    public class AddressModel
    {
      public string Addr1 { get; set; }
      public string Addr2 { get; set; }
      public string Suburb { get; set; }
   }

public enum Gender
{
    Male = 1,
    Female = 2
}
</code>```

My Address Partial View

```<code>@model MvcApplication1.Models.AddressModel

<fieldset>
<legend>Address</legend>

<div class="editor-label">
    @Html.LabelFor(model => model.Addr1)
</div>
<div class="editor-field">

    @Html.TextBoxFor(model => model.Addr1)
    @Html.ValidationMessageFor(model => model.Addr1)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Addr2)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Addr2)
    @Html.ValidationMessageFor(model => model.Addr2)
</div>

<div class="editor-label">
    @Html.LabelFor(model => model.Suburb)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Suburb)
    @Html.ValidationMessageFor(model => model.Suburb)
</div>
</code>```

Add Person page

```<code>  @using MvcApplication1.Models
  @model MvcApplication1.Models.Person

 @{
    ViewBag.Title = "AddPerson";
  }
</code>```

AddPerson

```<code>@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Person</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Gender)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(m => m.Gender, Model.Sex.ToSelectList())
        @Html.ValidationMessageFor(model => model.Sex)
    </div>

    <div class="editor-field">
        @{Html.RenderPartial("_Address", Model.HomeAddress);}
    </div>
    <div class="editor-field">
        @{Html.RenderPartial("_Address", Model.DeliveryAddress);}
    </div>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
</code>```

}

    @Html.ActionLink("Back to List", "Index")

答:
I found a likely problem here: two nested model properties of same complex type

In your AddPerson View, you can use:

```<code>   @{Html.EditorFor(model => model.HomeAddress, "_Address");}
   @{Html.EditorFor(model => model.DeliveryAddress, "_Address");}
</code>```

instead of:

```<code><div class="editor-field">
    @{Html.RenderPartial("_Address", Model.HomeAddress);}
</div>
<div class="editor-field">
    @{Html.RenderPartial("_Address", Model.DeliveryAddress);}
</div>
<p>
    <input type="submit" value="Create" />
</p>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am still new to MVC. I am currently having a add person page, the page includes person first name, last name and home address which is complex object (include addressline1,addressline2, state etc), delivery address (same to home address).

So I'd like to create a partial view which use to display address, but when I submit the form, I can't distinguish which value is for home address, coz home address and delivery address render the same name on the form.

MyClass

 Public class Person
    {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Gender { get; set; }
    public int DateOfBirthMonth { get; set; }
    public Gender Sex { get; set; }

    public AddressModel HomeAddress { get; set; }
    public AddressModel DeliveryAddress { get; set; }

    public Person()
    {
        HomeAddress = new AddressModel();
        DeliveryAddress = new AddressModel();
    }
}

    public class AddressModel
    {
      public string Addr1 { get; set; }
      public string Addr2 { get; set; }
      public string Suburb { get; set; }
   }

public enum Gender
{
    Male = 1,
    Female = 2
}

My Address Partial View

@model MvcApplication1.Models.AddressModel

<fieldset>
<legend>Address</legend>

    @Html.LabelFor(model => model.Addr1)

    @Html.TextBoxFor(model => model.Addr1)
    @Html.ValidationMessageFor(model => model.Addr1)

    @Html.LabelFor(model => model.Addr2)

    @Html.EditorFor(model => model.Addr2)
    @Html.ValidationMessageFor(model => model.Addr2)

    @Html.LabelFor(model => model.Suburb)

    @Html.EditorFor(model => model.Suburb)
    @Html.ValidationMessageFor(model => model.Suburb)

Add Person page

  @using MvcApplication1.Models
  @model MvcApplication1.Models.Person

 @{
    ViewBag.Title = "AddPerson";
  }

AddPerson

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Person</legend>

        @Html.LabelFor(model => model.FirstName)

        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)

        @Html.LabelFor(model => model.LastName)

        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)

        @Html.LabelFor(model => model.Gender)

        @Html.DropDownListFor(m => m.Gender, Model.Sex.ToSelectList())
        @Html.ValidationMessageFor(model => model.Sex)

        @{Html.RenderPartial("_Address", Model.HomeAddress);}

        @{Html.RenderPartial("_Address", Model.DeliveryAddress);}

        <input type="submit" value="Create" />

</fieldset>

}

    @Html.ActionLink("Back to List", "Index")

Body:
I found a likely problem here: two nested model properties of same complex type

In your AddPerson View, you can use:

   @{Html.EditorFor(model => model.HomeAddress, "_Address");}
   @{Html.EditorFor(model => model.DeliveryAddress, "_Address");}

instead of:

<div class="editor-field">
    @{Html.RenderPartial("_Address", Model.HomeAddress);}
</div>
<div class="editor-field">
    @{Html.RenderPartial("_Address", Model.DeliveryAddress);}
</div>
<p>
    <input type="submit" value="Create" />
</p>


问:
Closing concurrent server socket (TCP)
I'm making a concurrent server/client program in C using threads. Whenever a client connects, I create a new thread to handle it.

My problem is: I want to be able to close the server, from the client. With the command '..' for example. When I type '..' in the client, I want the server to close immediately.

I thought about having a global variable, that indicates wether the server should close or not. The problem is: When the thread is created to handle the client, the main thread goes back to accept(), and it cannot check that variable. So, it will only close when a new client connects.

Any ideas on how to solve this?

Thanks!

答: Use select() or (e)poll() or equivalent to wait for a client to connect BEFORE you then call accept() to accept the connection.  Those kind of functions allow you to specify a timeout, that will allow you to stop waiting periodically to check for other conditions, like a shutdown request.  On some platforms, you can even have these functions wait on not only the listening socket but also a separate pipe that you create privately for yourself, and when you want to "wake up" your waiting loop to do something, simply write a byte into that pipe, and when the loop detects that byte arriving then it can act accordingly.

Title: Closing concurrent server socket (TCP)


问:
django rest frame work API Test case (Authentication needed)
I am using (simple JWT rest framework) as a default AUTHENTICATION CLASSES
Now I want to write an API test case for one of my view which needed authentication
I don't know how to add "access" token and how to use this in rest framework test cases

I will be thankful if you answer to my question

答:
You can do this using a rest_framework.APITestCase.

```<code>self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
</code>```

Before that you need an access token which you can get from the API you are using to obtain a JWT access token. This is what I did in making test cases:

```<code>class BaseAPITestCase(APITestCase):
    def get_token(self, email=None, password=None, access=True):
        email = self.email if (email is None) else email
        password = self.password if (password is None) else password

        url = reverse("token_create")  # path/url where of API where you get the access token
        resp = self.client.post(
            url, {"email": email, "password": password}, format="json"
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)
        token = resp.data["access"] if access else resp.data["refresh"]
        return token

    def api_authentication(self, token=None):
        token = self.token if (token is None) else token
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)
</code>```

Body:
You can do this using a rest_framework.APITestCase.

self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)

Before that you need an access token which you can get from the API you are using to obtain a JWT access token. This is what I did in making test cases:

class BaseAPITestCase(APITestCase):
    def get_token(self, email=None, password=None, access=True):
        email = self.email if (email is None) else email
        password = self.password if (password is None) else password

        url = reverse("token_create")  # path/url where of API where you get the access token
        resp = self.client.post(
            url, {"email": email, "password": password}, format="json"
        )
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertTrue("access" in resp.data)
        self.assertTrue("refresh" in resp.data)
        token = resp.data["access"] if access else resp.data["refresh"]
        return token

    def api_authentication(self, token=None):
        token = self.token if (token is None) else token
        self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + token)


问:
Flask/Python - How can I run this python script in Flask and render output in html page
Im writting this code to get some values of stock prices, and how can I render output results in results.html page?
I'm using Heroku to make this app.

Please help me with this app.
This is the main file to call others files.

Please tell me if need more details to run this app.

Here are the codes I've made, to display the output in view.html page.
x.py

print('----EURO DO REMESSA ONLINE-----')
import melhor
print('-----COTAÇÃO DOLARHOJE.COM-----')
import cota
print('-----INDICADOR EURO COMERCIAL H1----')
import indicator
print('-----INVESTING VALOR EURO COM-----')
import invest
print( '-------------\n', 'Conhece a ti mesmo. (Tales de Mileto)', '\n-------------')
```

<hr>

<p>melhor.py</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bs
import time
import re
from Color import *
url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
print('Euro COMERCIAL: R$', Base.BOLD, ANSI_Compatible.Color(120), mult, ANSI_Compatible.END, Base.END)
eur_rate = 1.035145
eur_ra = str(mult * eur_rate)[:6]
print('Euro TURISMO: R$', Base.BOLD, eur_ra, Base.END)
current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
print(current)
with open('remessa.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + eur_ra + ' ' + 'Data:' + current + '\n')
</code>```

cota.py

import requests
import time

response = requests.get('http://dolarhoje.com/cotacao.txt')
data = response.text
print('1 USD comercial =',"R$",data )

response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
data = response.text
print('1 USD turismo =',"R$",data )

response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
data2 = response.text
print('1 EUR comercial =',"R$",data2 )

response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
data2 = response.text
print('1 EUR turismo =',"R$",data2 )

response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
data3 = response.text
print('1 BTC =',"R$",data3 )

current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")
with open('cota.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + data2 + ' ' + 'Data:' + current + '\n')
```

<hr>

<p>indicator.py</p>

<pre class="lang-py prettyprint-override"><code>import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
print(resumo)
</code>```

invest.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
print(resumo)
```

Thanks for your attention.

答:
I solved the problem! Here is the solution I've found:

First, you can visit the app here: finance-python.herokuapp.com

app.py

from flask import Flask
from functools import wraps
import sqlite3
import requests
import bs4
import requests_html
from flask import render_template
import subprocess
import re
import flask
from bs4 import BeautifulSoup as bs
import time

app = flask.Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    page = requests.get(url, headers=headers)
    page
    page.status_code
    page.text
    soup = bs(page.text, 'html.parser')
    resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
    mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
    euro_comercial_rem = print('Euro COMERCIAL: R$', mult)
    eur_rate = 1.035145
    eur_ra = str(mult * eur_rate)[:6]
    euro_turismo_rem = print('Euro TURISMO: R$', eur_ra)
    current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
    print(current)

    response = requests.get('http://dolarhoje.com/cotacao.txt')
    data = response.text
    dolar_com_dolar_hoje = print('1 USD comercial =',"R$",data )
    response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
    dataa = response.text
    dolar_tur_dolar_hoje = print('1 USD turismo =',"R$",dataa )

    response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
    data2 = response.text
    euro_com_dolar_hoje = print('1 EUR comercial =',"R$",data2 )
    response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
    dataa2 = response.text
    euro_tur_dolar_hoje = print('1 EUR turismo =',"R$",dataa2 )

    response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
    data3 = response.text
    btc_dolar_hoje = print('1 BTC =',"R$",data3 )

    current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")

    url = 'https://br.investing.com/currencies/eur-brl-technical'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    page = requests.get(url, headers=headers)
    page
    page.status_code
    page.text
    soup = bs(page.text, 'html.parser')
    resumoo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
    resumo_inves = print(resumoo)

    url = 'https://br.investing.com/currencies/eur-brl-technical'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    page = requests.get(url, headers=headers)
    page
    page.status_code
    page.text
    soup = bs(page.text, 'html.parser')
    resumooo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
    resumo_invest_eur_brl = print(resumooo)
    #resumos = 'eur_ra' + 'euro_turismo_rem' + 'dolar_com_dolar_hoje' + 'dolar_tur_dolar_hoje' + 'btc_dolar_hoje' + 'resumo_inves' + 'euro_com_dolar_hoje' + 'euro_tur_dolar_hoje'

    return flask.render_template('index.html', mult=mult, eur_ra=eur_ra, current=current, data=data, dataa=dataa, data2=data2, dataa2=dataa2, data3=data3, resumoo=resumoo, resumooo=resumooo)

if __name__ == '__main__':
    app.run()
```

<p>index.html into <em>template</em> folder</p>

<pre class="lang-html prettyprint-override"><code>-----EURO DO REMESSA ONLINE----- <br>
EURO COMERCIAL : R$ {{ mult }} <br>
EURO TURISMO: R$ {{ eur_ra }} <br>
{{ current }} <br> <br>
----COTAÇÃO DOLARHOJE.COM----- <br>
1 USD comercial = R$ {{ data }} <br>
1 USD turismo = R$ {{ dataa }} <br>
1 EUR comercial = R$ {{ data2 }} <br>
1 EUR turismo = R$ {{ dataa2 }} <br>
1 BTC = R$ {{ data3 }} <br> <br>
-----INDICADOR EURO COMERCIAL H1----- <br>
{{ resumoo }} <br> <br>
-----VARIAÇÃO DO EURO-----<br>
{{ resumooo }} <br> <br>

Conhece a ti mesmo - Tales de Mileto
</code>```

Body:
Im writting this code to get some values of stock prices, and how can I render output results in results.html page?
I'm using Heroku to make this app.

Please help me with this app.
This is the main file to call others files.

Please tell me if need more details to run this app.

Here are the codes I've made, to display the output in view.html page.
x.py

print('----EURO DO REMESSA ONLINE-----')
import melhor
print('-----COTAÇÃO DOLARHOJE.COM-----')
import cota
print('-----INDICADOR EURO COMERCIAL H1----')
import indicator
print('-----INVESTING VALOR EURO COM-----')
import invest
print( '-------------\n', 'Conhece a ti mesmo. (Tales de Mileto)', '\n-------------')

melhor.py

import requests
from bs4 import BeautifulSoup as bs
import time
import re
from Color import *
url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
print('Euro COMERCIAL: R$', Base.BOLD, ANSI_Compatible.Color(120), mult, ANSI_Compatible.END, Base.END)
eur_rate = 1.035145
eur_ra = str(mult * eur_rate)[:6]
print('Euro TURISMO: R$', Base.BOLD, eur_ra, Base.END)
current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
print(current)
with open('remessa.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + eur_ra + ' ' + 'Data:' + current + '\n')

cota.py

import requests
import time

response = requests.get('http://dolarhoje.com/cotacao.txt')
data = response.text
print('1 USD comercial =',"R$",data )

response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
data = response.text
print('1 USD turismo =',"R$",data )

response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
data2 = response.text
print('1 EUR comercial =',"R$",data2 )

response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
data2 = response.text
print('1 EUR turismo =',"R$",data2 )

response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
data3 = response.text
print('1 BTC =',"R$",data3 )

current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")
with open('cota.txt', 'a') as f:
    f.writelines('Valor euro turismo:' + 'R$' + data2 + ' ' + 'Data:' + current + '\n')

indicator.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
print(resumo)

invest.py

import requests
from bs4 import BeautifulSoup as bs

url = 'https://br.investing.com/currencies/eur-brl-technical'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
page = requests.get(url, headers=headers)
page
page.status_code
page.text
soup = bs(page.text, 'html.parser')
resumo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
print(resumo)

Thanks for your attention.

Body:
I solved the problem! Here is the solution I've found:

First, you can visit the app here: finance-python.herokuapp.com

app.py

from flask import Flask
from functools import wraps
import sqlite3
import requests
import bs4
import requests_html
from flask import render_template
import subprocess
import re
import flask
from bs4 import BeautifulSoup as bs
import time

app = flask.Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def index():
    url = 'https://www.remessaonline.com.br/cotacao/cotacao-euro'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    page = requests.get(url, headers=headers)
    page
    page.status_code
    page.text
    soup = bs(page.text, 'html.parser')
    resumo = soup.find_all('div', class_="style__Text-sc-27fg4f-2 ddwOcG")[0].get_text('')
    mult = float(re.sub('[^0-9.]', "", resumo.replace(",",".")))
    euro_comercial_rem = print('Euro COMERCIAL: R$', mult)
    eur_rate = 1.035145
    eur_ra = str(mult * eur_rate)[:6]
    euro_turismo_rem = print('Euro TURISMO: R$', eur_ra)
    current = time.strftime("%Y / dia:%d mês:%m horário:%H:%M:%S")
    print(current)

    response = requests.get('http://dolarhoje.com/cotacao.txt')
    data = response.text
    dolar_com_dolar_hoje = print('1 USD comercial =',"R$",data )
    response = requests.get('http://dolarhoje.com/dolar-turismo/cotacao.txt')
    dataa = response.text
    dolar_tur_dolar_hoje = print('1 USD turismo =',"R$",dataa )

    response = requests.get('http://dolarhoje.com/euro/cotacao.txt')
    data2 = response.text
    euro_com_dolar_hoje = print('1 EUR comercial =',"R$",data2 )
    response = requests.get('http://dolarhoje.com/euro-turismo/cotacao.txt')
    dataa2 = response.text
    euro_tur_dolar_hoje = print('1 EUR turismo =',"R$",dataa2 )

    response = requests.get('http://dolarhoje.com/bitcoin-hoje/cotacao.txt')
    data3 = response.text
    btc_dolar_hoje = print('1 BTC =',"R$",data3 )

    current = time.strftime("ano:%Y dia:%d mês:%m horário:%H:%M:%S")

    url = 'https://br.investing.com/currencies/eur-brl-technical'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    page = requests.get(url, headers=headers)
    page
    page.status_code
    page.text
    soup = bs(page.text, 'html.parser')
    resumoo = soup.find_all(id='techStudiesInnerWrap')[0].get_text(' ')
    resumo_inves = print(resumoo)

    url = 'https://br.investing.com/currencies/eur-brl-technical'
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}
    page = requests.get(url, headers=headers)
    page
    page.status_code
    page.text
    soup = bs(page.text, 'html.parser')
    resumooo = soup.find_all('div', class_="top bold inlineblock")[0].get_text(' ')
    resumo_invest_eur_brl = print(resumooo)
    #resumos = 'eur_ra' + 'euro_turismo_rem' + 'dolar_com_dolar_hoje' + 'dolar_tur_dolar_hoje' + 'btc_dolar_hoje' + 'resumo_inves' + 'euro_com_dolar_hoje' + 'euro_tur_dolar_hoje'

    return flask.render_template('index.html', mult=mult, eur_ra=eur_ra, current=current, data=data, dataa=dataa, data2=data2, dataa2=dataa2, data3=data3, resumoo=resumoo, resumooo=resumooo)

if __name__ == '__main__':
    app.run()

index.html into template folder

-----EURO DO REMESSA ONLINE----- <br>
EURO COMERCIAL : R$ {{ mult }} <br>
EURO TURISMO: R$ {{ eur_ra }} <br>
{{ current }} <br> <br>
----COTAÇÃO DOLARHOJE.COM----- <br>
1 USD comercial = R$ {{ data }} <br>
1 USD turismo = R$ {{ dataa }} <br>
1 EUR comercial = R$ {{ data2 }} <br>
1 EUR turismo = R$ {{ dataa2 }} <br>
1 BTC = R$ {{ data3 }} <br> <br>
-----INDICADOR EURO COMERCIAL H1----- <br>
{{ resumoo }} <br> <br>
-----VARIAÇÃO DO EURO-----<br>
{{ resumooo }} <br> <br>

Conhece a ti mesmo - Tales de Mileto


问:
Unity NavMesh on a Sphere Unity 5.6 Navigation
with Unity 5.6 the NavMesh / Navigation has changed in some parts. My Question is:

Is it now possible to create a NavMesh, that covers a whole sphere ?

Thank you for your Answers!

答:
Here is my spherical navmesh on complex topology: youtube
In short - I baked my planet 6 times, rotating different sides up. Then I manually added baked navmesh pieces, setting it`s rotation. And then connected it with off mesh links (sure, it must be more accurate for production).</p>


问:
How a passed variable to pug are accessible in pug script?
I am now to web development, in fact, this is the first one I am working on. I am trying to pass a variable from my main app like

```<code>app.get('/',(req,res)=>{
    getdata().then(record=>{
        res.render("index",{title:'Login',users:record})
    })
})
</code>```

Then in my index.pug file the variable is accessible everywhere except my script there like

```<code>form()
          input(type="text", class='normal',id='uname', placeholder = 'Username')
          input(type="password", class='normal',id='password', placeholder='Password')
          input(type="submit", class='submit',value="Login",onclick="checkaccount(users)")
script.
    function checkaccount(users){
      let user=document.getElementById('uname').value
      let password = document.getElementById('password').value
      console.log(users)
    }
</code>```

the code won't execute because users variable is not defined I guess.
**users variable is an array of array with format array(a,b)
this works when i use

```<code>each val in users
    p.
        val
</code>```

elsewhere from my scripts.

答:
the script. means that everything that follows is interpreted as literal. you can still use the code, but the syntax is different:

```<code>script.
    var users = JSON.parse('#{JSON.stringify(users)'});
    function checkaccount(/*set users elsewhere*/){
      let user=document.getElementById('uname').value
      let password = document.getElementById('password').value
      console.log(users)
    }
</code>```

actually, this is not a good idea, better to use a serialization library, but the idea is that you have to serialize it, then tell put to get make a string literal '#{}' out of an expression #{} and then parse it on frontend (JSON.parse('#{}')). You would have to JSON.stringify().replace(/'/g, "'") to prevent the single quote in one of your data to break this solution.

on the frontend, with object {'hello': "world's"}:

```<code>- var myvalue = JSON.stringify(obj).replace(/'/g, "\\'");
JSON.parse('#{myvalue}')
</code>```

becomes

JSON.parse('{"hello":"world\'s"}');
```

Body:
I am now to web development, in fact, this is the first one I am working on. I am trying to pass a variable from my main app like

app.get('/',(req,res)=>{
    getdata().then(record=>{
        res.render("index",{title:'Login',users:record})
    })
})

Then in my index.pug file the variable is accessible everywhere except my script there like

form()
          input(type="text", class='normal',id='uname', placeholder = 'Username')
          input(type="password", class='normal',id='password', placeholder='Password')
          input(type="submit", class='submit',value="Login",onclick="checkaccount(users)")
script.
    function checkaccount(users){
      let user=document.getElementById('uname').value
      let password = document.getElementById('password').value
      console.log(users)
    }

the code won't execute because users variable is not defined I guess.
**users variable is an array of array with format array(a,b)
this works when i use

each val in users
    p.
        val

elsewhere from my scripts.

Body:
the script. means that everything that follows is interpreted as literal. you can still use the code, but the syntax is different:

script.
    var users = JSON.parse('#{JSON.stringify(users)'});
    function checkaccount(/*set users elsewhere*/){
      let user=document.getElementById('uname').value
      let password = document.getElementById('password').value
      console.log(users)
    }

actually, this is not a good idea, better to use a serialization library, but the idea is that you have to serialize it, then tell put to get make a string literal '#{}' out of an expression #{} and then parse it on frontend (JSON.parse('#{}')). You would have to JSON.stringify().replace(/'/g, "'") to prevent the single quote in one of your data to break this solution.

on the frontend, with object {'hello': "world's"}:

- var myvalue = JSON.stringify(obj).replace(/'/g, "\\'");
JSON.parse('#{myvalue}')

becomes

JSON.parse('{"hello":"world\'s"}');


问:
Setting up half-icons with a rating system
I built a component that is basically a rating system that allows you to add more icons depending on the dropdown.

I was wondering if there was a way to make half stars, I've looked through older code on the internet, but there isn't anything that has been updated. Any help with be appreciated

```<code>import React, { useState } from 'react'
import {FaStar} from "react-icons/all";
import './Rater.css'

const Rater = () => {
    const [rating, setRating] = useState(null)
    const [hover, setHover] = useState(null)
    const [value] = useState(100)
    const [iconValue, setIconValue] = useState(5)

    return (
        <div>
            <select onChange={(e) =>
            {setIconValue(Number(e.target.value))}}>
                { Array.from(new Array(value),(value, index) =>
                    index + 1).map(value => <option
                    key={value} value={value}>{value}</option>) }
            </select>
            <h1> Select Amount of Icons </h1>

            {[... Array(iconValue)].map((icon, i) => {
                const value = i + 1

                return (
                    <label>
                        <input type='radio'
                               name='rating'
                               value={value}
                               onClick={() => setRating(value)}
                        />
                        <FaStar classname='star'
                                color={value <= (hover || rating) ? '#ffc107' : '#e4e5e9'}
                                size={100}
                                onMouseEnter={() => setHover(value)}
                                onMouseLeave={() => setHover(null)}
                        />
                    </label>
                )
            })}
        </div>
    )
}

export default Rater
</code>```

答:
There are several ways of accomplish that, a simple one may (I don't know if it is the best for you application) can be use tree layers: A background, a transparent icon and another one that will be the "fill" of the star.

You may then position the star inside the background, and put the "fill" layer behind the star. You then set the fill layer width according to the rating.

Another option can use two icons, one for the filled star and another for the half star. You could also use polygons to represent the stars and manipulate the points via CSS. I think the layered solution is better because you will not need to export a new icon asset or manipulate polygons directly, all you would need is to position some divs, one over another and manipulate their width based on the rate amount

Body:
I built a component that is basically a rating system that allows you to add more icons depending on the dropdown.

I was wondering if there was a way to make half stars, I've looked through older code on the internet, but there isn't anything that has been updated. Any help with be appreciated

import React, { useState } from 'react'
import {FaStar} from "react-icons/all";
import './Rater.css'

const Rater = () => {
    const [rating, setRating] = useState(null)
    const [hover, setHover] = useState(null)
    const [value] = useState(100)
    const [iconValue, setIconValue] = useState(5)

    return (

            <select onChange={(e) =>
            {setIconValue(Number(e.target.value))}}>
                { Array.from(new Array(value),(value, index) =>
                    index + 1).map(value => <option
                    key={value} value={value}>{value}</option>) }
            </select>

 Select Amount of Icons

            {[... Array(iconValue)].map((icon, i) => {
                const value = i + 1

                return (

                        <input type='radio'
                               name='rating'
                               value={value}
                               onClick={() => setRating(value)}
                        />
                        <FaStar classname='star'
                                color={value <= (hover || rating) ? '#ffc107' : '#e4e5e9'}
                                size={100}
                                onMouseEnter={() => setHover(value)}
                                onMouseLeave={() => setHover(null)}
                        />

                )
            })}

    )
}

export default Rater


问:
git clone vim and make occurs error message
First, I'm following instructions here: https://www.vim.org/git.php

I got git clone of vim and go to directory vim/src and typed make, I got this error message:

```<code>no terminal library found
checking for tgetent()... configure: error: NOT FOUND!
      You need to install a terminal library; for example ncurses.
      Or specify the name of the library with --with-tlib.
Makefile:2046: recipe for target 'auto/config.mk' failed
make: *** [auto/config.mk] Error 1

</code>```

I didn't make changes so I didn't take  step like "git pull" "git stash" ....

答:
You just need to install a missing dependencie : ncurses :

For debian/ubuntu based distros: # apt install ncurses-base

For redhat/centos: # yum install ncurses

Body:
First, I'm following instructions here: https://www.vim.org/git.php

I got git clone of vim and go to directory vim/src and typed make, I got this error message:

no terminal library found
checking for tgetent()... configure: error: NOT FOUND!
      You need to install a terminal library; for example ncurses.
      Or specify the name of the library with --with-tlib.
Makefile:2046: recipe for target 'auto/config.mk' failed
make: *** [auto/config.mk] Error 1

I didn't make changes so I didn't take  step like "git pull" "git stash" ....


问:
Why not always use psyco for Python code?
psyco seems to be quite helpful in optimizing Python code, and it does it in a very non-intrusive way.

Therefore, one has to wonder. Assuming you're always on a x86 architecture (which is where most apps run these days), why not just always use psyco for all Python code? Does it make mistakes sometimes and ruins the correctness of the program? Increases the runtime for some weird cases?

Have you had any negative experiences with it? My most negative experience so far was that it made my code faster by only 15%. Usually it's better.

Naturally, using psyco is not a replacement for efficient algorithms and coding. But if you can improve the performance of your code for the cost of two lines (importing and calling psyco), I see no good reason not to.

答:
A couple of other things:

It doesn't seem to be very actively maintained.

It can be a memory hog.

OwnerDisplayName: eliben

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: eliben

OwnerDisplayName: Jason Baker


问:
C++ Placing Random Values In A Multiplication Chart (Nested Loop)
I created a multiplication table for the integers 1...10. Here is the code:

```<code>for (int i = 1; i <= 10; i++) {
    for (int j = 1; j <= 10; j++) {
      std::cout << "\t" << i * j;
    }
    std::cout << std::endl;
}
</code>```

And my output is this:

```<code>1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   12  15  18  21  24  27  30
4   8   12  16  20  24  28  32  36  40
5   10  15  20  25  30  35  40  45  50
6   12  18  24  30  36  42  48  54  60
7   14  21  28  35  42  49  56  63  70
8   16  24  32  40  48  56  64  72  80
9   18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90  100
</code>```

The problem I am struggling with is that I need to insert a random number that represents an error value inside the multiplication table. For example:

```<code>1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   13  15  18  21  24  27  30
</code>```

As you can see in this example, the error value is 13 where 3 x 4 = 12, but instead there is the number 13.

Should I use another loop to insert the random number? If so, how to go about it?

答:
So thank's to everyone's input - especially @Wolfgang.
I did read up on C++11's random header file and it's functions.
I did create a source code with random functions and one without.
Any feed would be appreciated on how to make my source code more efficient.
Other than that, it achieves what I needed it to do.</p>

```<code>#include <iostream>
#include <ctime>
#include <iomanip>

const unsigned int ROWS = 10;
const unsigned int COLUMNS = 10;

void randomValue(unsigned int &, unsigned int &, unsigned int &);

int main()
{
  unsigned int rValue;
  unsigned int cValue;
  unsigned int pValue;

  unsigned int rowError;
  unsigned int columnError;
  unsigned int productError;

  unsigned int userRowGuess;
  unsigned int userColumnGuess;

  char choice;

  do
  {
    randomValue(rValue, cValue, pValue);

    std::cout << "\033[2J\033[0;0H"; // This code clears the screen
    std::cout << std::endl << std::endl;
    std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
    std::cout << std::setw(35) << "+ Multiplication Table +" << std::endl;
    std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
    std::cout << std::endl << std::endl;

    while (true)
    {
      rowError = rValue;
      columnError = cValue;
      productError = pValue;

      if (productError == rowError * columnError)
      {
        productError--;
      }

      for (unsigned int row = 1; row <= ROWS; row++)
      {
        for (unsigned int column = 1; column <= COLUMNS; column++)
        {
          if (row == rowError && column == columnError)
          {
            std::cout << "\t" << "" << productError;
          }
          else
          {
            std::cout << "\t" <<  row * column;
          }
        }
      std::cout << std::endl;
      }
      break;
    }

    std::cout << std::endl << std::endl;
    std::cout << "\t\t" << "Type in the column number " << std::endl;
    std::cout << "\t\t" << "of the location of the    " << std::endl;
    std::cout << "\t\t" << "error & then press        " << std::endl;
    std::cout << "\t\t" << "[Enter]: ";
    std::cin >> userColumnGuess;
    std::cout << std::endl;

    std::cout << "\t\t" << "Type in the row number " << std::endl;
    std::cout << "\t\t" << "of the location of the    " << std::endl;
    std::cout << "\t\t" << "error & then press        " << std::endl;
    std::cout << "\t\t" << "[Enter]: ";
    std::cin >> userRowGuess;
    std::cout << std::endl;

    if (userRowGuess != rowError && userColumnGuess != columnError)
    {
      std::cout << "\t\t" << "Your answer was incorrect!" << std::endl << std::endl;
      std::cout << "\t\t" << "Error value '" << productError << "' is located" << std::endl;
      std::cout << "\t\t" << "on row " << rowError << ", column " << columnError << "." << std::endl;
    }
    else
    {
      std::cout << "\t\t" << "You are correct! You win!" << std::endl;
    }

    std::cout << std::endl;
    std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
    std::cout << "\t\t" << "Type in 'Y' for yes or 'N'" << std::endl;
    std::cout << "\t\t" << "for no & then press [Enter]: ";
    std::cin >> choice;

    while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N')
    {
      std::cout << std::endl;
      std::cout << "\t\t" << "Invalid entry. Only 'Y' or 'N'" << std::endl;
      std::cout << "\t\t" << "are accepted answers." << std::endl << std::endl;
      std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
      std::cout << "\t\t" << "Type in 'Y' for yes or 'N' for" << std::endl;
      std::cout << "\t\t" << "no & then press [Enter]: ";
      std::cin >> choice;
    }
    std::cout << std::endl;

  } while (choice == 'y' || choice == 'Y');

  std::cout << "\t\t" << "Press [Enter] to continue....." << std::endl;
  std::cin.get();
  std::cin.get();

  return 0;
}

void randomValue(unsigned int &rValue, unsigned int &cValue, unsigned int &pValue)
{
  srand((unsigned)time(NULL));

  unsigned int r = rValue = (rand() % ROWS) + 1;
  unsigned int c = cValue = (rand() % COLUMNS) + 1;
  unsigned int p = pValue = (rand() % (ROWS * COLUMNS)) + 1;
}
</code>```

Body:
I created a multiplication table for the integers 1...10. Here is the code:

for (int i = 1; i <= 10; i++) {
    for (int j = 1; j <= 10; j++) {
      std::cout << "\t" << i * j;
    }
    std::cout << std::endl;
}

And my output is this:

1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   12  15  18  21  24  27  30
4   8   12  16  20  24  28  32  36  40
5   10  15  20  25  30  35  40  45  50
6   12  18  24  30  36  42  48  54  60
7   14  21  28  35  42  49  56  63  70
8   16  24  32  40  48  56  64  72  80
9   18  27  36  45  54  63  72  81  90
10  20  30  40  50  60  70  80  90  100

The problem I am struggling with is that I need to insert a random number that represents an error value inside the multiplication table. For example:

1   2   3   4   5   6   7   8   9   10
2   4   6   8   10  12  14  16  18  20
3   6   9   13  15  18  21  24  27  30

As you can see in this example, the error value is 13 where 3 x 4 = 12, but instead there is the number 13.

Should I use another loop to insert the random number? If so, how to go about it?

Body:
So thank's to everyone's input - especially @Wolfgang.
I did read up on C++11's random header file and it's functions.
I did create a source code with random functions and one without.
Any feed would be appreciated on how to make my source code more efficient.
Other than that, it achieves what I needed it to do.

#include <iostream>
#include <ctime>
#include <iomanip>

const unsigned int ROWS = 10;
const unsigned int COLUMNS = 10;

void randomValue(unsigned int &, unsigned int &, unsigned int &);

int main()
{
  unsigned int rValue;
  unsigned int cValue;
  unsigned int pValue;

  unsigned int rowError;
  unsigned int columnError;
  unsigned int productError;

  unsigned int userRowGuess;
  unsigned int userColumnGuess;

  char choice;

  do
  {
    randomValue(rValue, cValue, pValue);

    std::cout << "\033[2J\033[0;0H"; // This code clears the screen
    std::cout << std::endl << std::endl;
    std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
    std::cout << std::setw(35) << "+ Multiplication Table +" << std::endl;
    std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
    std::cout << std::endl << std::endl;

    while (true)
    {
      rowError = rValue;
      columnError = cValue;
      productError = pValue;

      if (productError == rowError * columnError)
      {
        productError--;
      }

      for (unsigned int row = 1; row <= ROWS; row++)
      {
        for (unsigned int column = 1; column <= COLUMNS; column++)
        {
          if (row == rowError && column == columnError)
          {
            std::cout << "\t" << "" << productError;
          }
          else
          {
            std::cout << "\t" <<  row * column;
          }
        }
      std::cout << std::endl;
      }
      break;
    }

    std::cout << std::endl << std::endl;
    std::cout << "\t\t" << "Type in the column number " << std::endl;
    std::cout << "\t\t" << "of the location of the    " << std::endl;
    std::cout << "\t\t" << "error & then press        " << std::endl;
    std::cout << "\t\t" << "[Enter]: ";
    std::cin >> userColumnGuess;
    std::cout << std::endl;

    std::cout << "\t\t" << "Type in the row number " << std::endl;
    std::cout << "\t\t" << "of the location of the    " << std::endl;
    std::cout << "\t\t" << "error & then press        " << std::endl;
    std::cout << "\t\t" << "[Enter]: ";
    std::cin >> userRowGuess;
    std::cout << std::endl;

    if (userRowGuess != rowError && userColumnGuess != columnError)
    {
      std::cout << "\t\t" << "Your answer was incorrect!" << std::endl << std::endl;
      std::cout << "\t\t" << "Error value '" << productError << "' is located" << std::endl;
      std::cout << "\t\t" << "on row " << rowError << ", column " << columnError << "." << std::endl;
    }
    else
    {
      std::cout << "\t\t" << "You are correct! You win!" << std::endl;
    }

    std::cout << std::endl;
    std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
    std::cout << "\t\t" << "Type in 'Y' for yes or 'N'" << std::endl;
    std::cout << "\t\t" << "for no & then press [Enter]: ";
    std::cin >> choice;

    while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N')
    {
      std::cout << std::endl;
      std::cout << "\t\t" << "Invalid entry. Only 'Y' or 'N'" << std::endl;
      std::cout << "\t\t" << "are accepted answers." << std::endl << std::endl;
      std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
      std::cout << "\t\t" << "Type in 'Y' for yes or 'N' for" << std::endl;
      std::cout << "\t\t" << "no & then press [Enter]: ";
      std::cin >> choice;
    }
    std::cout << std::endl;

  } while (choice == 'y' || choice == 'Y');

  std::cout << "\t\t" << "Press [Enter] to continue....." << std::endl;
  std::cin.get();
  std::cin.get();

  return 0;
}

void randomValue(unsigned int &rValue, unsigned int &cValue, unsigned int &pValue)
{
  srand((unsigned)time(NULL));

  unsigned int r = rValue = (rand() % ROWS) + 1;
  unsigned int c = cValue = (rand() % COLUMNS) + 1;
  unsigned int p = pValue = (rand() % (ROWS * COLUMNS)) + 1;
}


问:
Django-tables2 does not sort
I display a database table using django-tables2. All appears OK, but clicking on the column headers does not sort by that column. The headers are clickable, but  in their html has no url text in it, e.g.:

```<code><div class="table-container">
<table class="paleblue"><thead><tr><th class="id orderable sortable"><a href="">ID</a>
</th><th class="orderable sortable system"><a href="">System</a></th> ...
</code>```

I checked the django-tables2 template source and it sais this:

```<code>... <a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}"> ...
</code>```

Which I do not understand.

I can only make sorting work by setting order_by in view.py:

```<code>class ResultsTable(tables.Table):
    class Meta:
        model = Performance
        attrs = {'class': 'paleblue'}
        order_by_field = True

def result(request, system):
    results = Performance.objects.filter(system__name=system)
    table = ResultsTable(results, order_by=('<any column name from Performance>',))
    RequestConfig(request).configure(table)
    return render_to_response('result.html', {'table': table})
</code>```

but that obviously only works for one column and I want to click on columns to choose which one to sort by.

It is my understanding from the docs that sorting by column should work 'out of the box', is this correct, or am I doing something else wrong?

答:
Other responses on this page point in the right direction, but just wanted to include everything required to get this working in one place. In the view:

Define your queryset without ordering

Pass the queryset into the table instance

Set any customizations on the table obj, like default ordering

Wrap it all in RequestConfig (essential - ordering won't work without this!)

Pass the fully-configured table into template context

```<code># views.py
from django_tables2 import RequestConfig
...
data = MyModel.objects.all()
my_table = MySummariesTable(data)
my_table.order_by = "-name"
RequestConfig(request).configure(my_table)
ctx = {"my_table": my_table}

return render(request, "path/mytemplate.html", ctx)
</code>```

If any of your columns need to be orderable by foreign-key relations, define those in your table column definitions with e.g.

```<code>col1 = tables.Column(verbose_name="Some Col", order_by="mycol.foobar.name")

</code>```

Title: Django-tables2 does not sort

Body:
I display a database table using django-tables2. All appears OK, but clicking on the column headers does not sort by that column. The headers are clickable, but  in their html has no url text in it, e.g.:

ID
	System	 ...

I checked the django-tables2 template source and it sais this:

...  ...

Which I do not understand.

I can only make sorting work by setting order_by in view.py:

class ResultsTable(tables.Table):
    class Meta:
        model = Performance
        attrs = {'class': 'paleblue'}
        order_by_field = True

def result(request, system):
    results = Performance.objects.filter(system__name=system)
    table = ResultsTable(results, order_by=('<any column name from Performance>',))
    RequestConfig(request).configure(table)
    return render_to_response('result.html', {'table': table})

but that obviously only works for one column and I want to click on columns to choose which one to sort by.

It is my understanding from the docs that sorting by column should work 'out of the box', is this correct, or am I doing something else wrong?

Body:
Other responses on this page point in the right direction, but just wanted to include everything required to get this working in one place. In the view:

Define your queryset without ordering

Pass the queryset into the table instance

Set any customizations on the table obj, like default ordering

Wrap it all in RequestConfig (essential - ordering won't work without this!)

Pass the fully-configured table into template context

# views.py
from django_tables2 import RequestConfig
...
data = MyModel.objects.all()
my_table = MySummariesTable(data)
my_table.order_by = "-name"
RequestConfig(request).configure(my_table)
ctx = {"my_table": my_table}

return render(request, "path/mytemplate.html", ctx)

If any of your columns need to be orderable by foreign-key relations, define those in your table column definitions with e.g.

col1 = tables.Column(verbose_name="Some Col", order_by="mycol.foobar.name")


问:
Execute javascript when another function exists
I'm writing two scripts in an web environment where I don't have control over the order in which they are loaded.  Let's say the two scripts are called MyUtil and DoSomething.

MyUtil contains utilities that I will bind to the window object using window.myUtil = myUtil.  I'm then going to call methods of myUtil from within DoSomething.

If MyUtil is loaded first, everything will work. If it's loaded second, window.myUtil will be undefined.

How can I modify the code in DoSomething (and/or MyUtil) to wait until window.myUtil exists before DoSomething executes its code?

NB: I'm using jQuery 1.2.3.

答:
I ended up using a trigger in MyUtil that I check for in DoSomething. This worked perfectly.

At the end of MyUtil, I added:

```<code>$(document).trigger('myUtilLoaded');
</code>```

At the end of DoSomething, I added:

```<code>if (!(window.myUtil))
{
  $(document).bind('myUtilLoaded', function(e) {
    doSomething();
  });
}
else
{
  doSomething();
}
</code>```

Body:
I ended up using a trigger in MyUtil that I check for in DoSomething. This worked perfectly.

At the end of MyUtil, I added:

$(document).trigger('myUtilLoaded');

At the end of DoSomething, I added:

if (!(window.myUtil))
{
  $(document).bind('myUtilLoaded', function(e) {
    doSomething();
  });
}
else
{
  doSomething();
}


问:
Using pandas, what is the best way to go through a column in a dataframe while comparing each successive value to the previous value
For example lets say I have the following data set which goes on for 20,000 rows (large data set).

```<code>time      velocity
0.000000  2.36949
0.005217  2.36169
0.010434  2.35677
0.015651  2.35299
0.020869  2.35015
</code>```

I would want to take the second value in 'velocity' and subtract it from the first value. If the difference is less than say, 0.005, then continue to the third value.

And continue to take the difference between third and second value, but if difference is greater than 0.005, divide the difference of these two values by another value and store the result.

I would like to continue this process throughout the entire dataframe.

Ultimately I want to plot the 'delta values' which meet my condition versus the time at which they occur.

Any help is appreciated.

答:
Do the diff then with np.where

```<code>s=df.velocity.diff()
df['new']=np.where(s.abs()>0.005,s/value,s)
</code>```

Body:
For example lets say I have the following data set which goes on for 20,000 rows (large data set).

time      velocity
0.000000  2.36949
0.005217  2.36169
0.010434  2.35677
0.015651  2.35299
0.020869  2.35015

I would want to take the second value in 'velocity' and subtract it from the first value. If the difference is less than say, 0.005, then continue to the third value.

And continue to take the difference between third and second value, but if difference is greater than 0.005, divide the difference of these two values by another value and store the result.

I would like to continue this process throughout the entire dataframe.

Ultimately I want to plot the 'delta values' which meet my condition versus the time at which they occur.

Any help is appreciated.

Body:
Do the diff then with np.where

s=df.velocity.diff()
df['new']=np.where(s.abs()>0.005,s/value,s)


问:
How to use FuncAnimation to animate a sequence of points/tuples in a grid
I am doing a path-finding algorithm implementation in python, I have a grid and the obtained path. So I wanna use FuncAnimation to animate the sequence of points from the start to the goal in the grid. I try to code this but it doesn't give me the line. This is what I did, In this example code I give the grid and the path(positions x,y in the grid), but the output is just the grid without the path, I don't know what to do to fix the problem, please help!</p>

```<code>import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

def mazeanimation(grid, route):

        fig, ax = plt.subplots(figsize=(10,10))

        ax.imshow(grid, cmap=plt.cm.terrain)

        line, = ax.plot([],[], color="black")

        def init():
            line.set_data([],[])
            return line,

        def animate(i):
            x = route[i][0]

            y = route[i][1]

            line.set_data(x, y)
            return line,

        FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

grid = np.array([

        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

route = [(13, 1), (12, 2), (11, 3), (10, 4), (9, 5), (8, 5),
         (7, 5), (6, 5), (5, 5), (4, 5), (3, 5), (2, 6), (2, 7),
         (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13),
         (2, 14), (3, 15)]

mazeanimation(grid, route)
</code>```

Body:
I am doing a path-finding algorithm implementation in python, I have a grid and the obtained path. So I wanna use FuncAnimation to animate the sequence of points from the start to the goal in the grid. I try to code this but it doesn't give me the line. This is what I did, In this example code I give the grid and the path(positions x,y in the grid), but the output is just the grid without the path, I don't know what to do to fix the problem, please help!

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

def mazeanimation(grid, route):

        fig, ax = plt.subplots(figsize=(10,10))

        ax.imshow(grid, cmap=plt.cm.terrain)

        line, = ax.plot([],[], color="black")

        def init():
            line.set_data([],[])
            return line,

        def animate(i):
            x = route[i][0]

            y = route[i][1]

            line.set_data(x, y)
            return line,

        FuncAnimation(fig, animate, init_func=init,
                               frames=100, interval=20, blit=True)

grid = np.array([

        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

route = [(13, 1), (12, 2), (11, 3), (10, 4), (9, 5), (8, 5),
         (7, 5), (6, 5), (5, 5), (4, 5), (3, 5), (2, 6), (2, 7),
         (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13),
         (2, 14), (3, 15)]

mazeanimation(grid, route)

Body:
You can achieve this by making use of matplotlib's interactive mode:

import numpy as np
import matplotlib.pyplot as plt

#inputs###
grid = np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1],
        [1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
        [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])

route = [(13, 1), (12, 2), (11, 3), (10, 4), (9, 5), (8, 5),
         (7, 5), (6, 5), (5, 5), (4, 5), (3, 5), (2, 6), (2, 7),
         (2, 8), (2, 9), (2, 10), (2, 11), (2, 12), (2, 13),
         (2, 14), (3, 15)]
#setup the plot
fig, ax = plt.subplots(figsize=(10,10))
ax.imshow(grid, cmap=plt.cm.terrain)
line, = ax.plot([],[], color="black")

##### set interactive mode####
plt.ion()
plt.show()

for i,j in route:
#set up the canvas
    plt.gcf().canvas.draw()
    line, = ax.plot(i,j,'.',c='black')
    plt.pause(0.1)

Here's how the route looks:

Alternately, with FuncAnimation:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], '.',c='black')

def init():
    ax.imshow(grid, cmap=plt.cm.terrain)
    return ln,

def update(frame):
    xdata.append(frame[0])
    ydata.append(frame[1])
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=route,init_func=init, blit=True)
plt.show()


问:
Calculuate the differences between averages in a paired data in R
I have a data frame as below:</p>
```<code>df <- data.frame(Staff = c("Jack", "Ruth", "Michael", "Ruth", "Jack", "Jack", "Ruth", "Michael"),
                 Client = c("Julie", "Julie", "Julie", "Julie", "Julie", "Candice", "Candice", "Candice"),
                 Assessment = c(1, 2, 2, 1, 7, 4, 1, 1),
                 Staff_avg_by_client = c(4, 1.5, 2, 1.5, 4, 4, 1, 1))
</code>```

答:
For every Client we can subtract Staff_avg_by_client by mean of Assessment for all other Staff.  Using dplyr this can be done as :

```<code>library(dplyr)
library(purrr)

df %>%
  group_by(Client) %>%
  mutate(diff = map_dbl(row_number(),
              ~Staff_avg_by_client[.x] - mean(Assessment[Staff != Staff[.x]])))

# Month Staff   Client  Assessment Staff_avg_by_client  diff
#  <dbl> <chr>   <chr>        <dbl>               <dbl> <dbl>
#1     1 Jack    Julie            1                 4    2.33
#2     1 Ruth    Julie            2                 1.5 -1.83
#3     1 Michael Julie            2                 2   -0.75
#4     1 Ruth    Julie            1                 1.5 -1.83
#5     1 Jack    Julie            7                 4    2.33
#6     1 Jack    Candice          4                 4    3
#7     1 Ruth    Candice          1                 1   -1.5
#8     1 Michael Candice          1                 1   -1.5
</code>```

Body:
I have a data frame as below:

df <- data.frame(Staff = c("Jack", "Ruth", "Michael", "Ruth", "Jack", "Jack", "Ruth", "Michael"),
                 Client = c("Julie", "Julie", "Julie", "Julie", "Julie", "Candice", "Candice", "Candice"),
                 Assessment = c(1, 2, 2, 1, 7, 4, 1, 1),
                 Staff_avg_by_client = c(4, 1.5, 2, 1.5, 4, 4, 1, 1))

Body:
For every Client we can subtract Staff_avg_by_client by mean of Assessment for all other Staff.  Using dplyr this can be done as :

library(dplyr)
library(purrr)

df %>%
  group_by(Client) %>%
  mutate(diff = map_dbl(row_number(),
              ~Staff_avg_by_client[.x] - mean(Assessment[Staff != Staff[.x]])))

# Month Staff   Client  Assessment Staff_avg_by_client  diff
#  <dbl> <chr>   <chr>        <dbl>               <dbl> <dbl>
#1     1 Jack    Julie            1                 4    2.33
#2     1 Ruth    Julie            2                 1.5 -1.83
#3     1 Michael Julie            2                 2   -0.75
#4     1 Ruth    Julie            1                 1.5 -1.83
#5     1 Jack    Julie            7                 4    2.33
#6     1 Jack    Candice          4                 4    3
#7     1 Ruth    Candice          1                 1   -1.5
#8     1 Michael Candice          1                 1   -1.5


问:
Set button in position "fixed" in React Native
I would like set button on the bottom right corner width fixed position in React Native.

position: fixed don't work in React Native and stickyHeaderIndices method in ScrollView does not allow to position an element above the others component.

Anyone have already test this feature ?

答: Just put the component outside of the scrollview and set it with position absolute</p>


问:
Extract table structure from image containing Tables with borders
I am trying to extract the cell locations in the table below.

I was able to get the contours around the cell positions after applying adaptive thresholding and HoughLines get vertical and horizontal structuring elements.
Here's my code :

```<code>img = cv2.imread(os.path.join(img_path, file))
img1 = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 17, 1)
bw = cv2.bitwise_not(bw)

#detect horizontal lines
horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))

horizontal = cv2.erode(bw, horizontalStructure)
horizontal = cv2.dilate(horizontal, horizontalStructure)

horizontal = cv2.dilate(horizontal, (1,1), iterations=5)
horizontal = cv2.erode(horizontal, (1,1), iterations=5)

hlines = cv2.HoughLinesP(horizontal, 1, np.pi/180, 20, np.array([]), 20, 2)

for line in hlines :
    for x1,y1,x2,y2 in line:
        if abs(x1 - x2) > img.shape[1]/4:
            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

#detect vertical lines
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 15))

vertical = cv2.erode(bw, verticalStructure)
vertical = cv2.dilate(vertical, verticalStructure)

vertical = cv2.dilate(vertical, (1,1), iterations=5)
#vertical = cv2.erode(vertical, (1,1), iterations=5)

vlines = cv2.HoughLinesP(vertical, 1, np.pi/180, 20, np.array([]), 20, 2)

for line in vlines :
    for x1,y1,x2,y2 in line:
        #if abs(y1 - y2) > img.shape[0]/2:
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

# red color boundaries [B, G, R]
lower = [0, 240, 0]
upper = [20, 255, 20]

# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")

# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(img, lower, upper)
output = cv2.bitwise_and(img1, img, mask=mask)

ret,thresh = cv2.threshold(mask, 40, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img_area  = img.shape[0] * img.shape[1]

for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    if w * h > 0.005 * img_area:
        cv2.rectangle(img1, (x, y), (x+w, y+h), (0, 0, 255), 2)
</code>```

How can I improve this solution? What other approaches can I implement in order to extract the table cells information better and in a more robust manner ?

答: for each box detected , take a wider area to get along with an arbitrary error treshold (in n pixel width, like 5 pixel), you should be able to detect every text content</p>

Body:
I am trying to extract the cell locations in the table below.

I was able to get the contours around the cell positions after applying adaptive thresholding and HoughLines get vertical and horizontal structuring elements.
Here's my code :

img = cv2.imread(os.path.join(img_path, file))
img1 = img.copy()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 17, 1)
bw = cv2.bitwise_not(bw)

#detect horizontal lines
horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 1))

horizontal = cv2.erode(bw, horizontalStructure)
horizontal = cv2.dilate(horizontal, horizontalStructure)

horizontal = cv2.dilate(horizontal, (1,1), iterations=5)
horizontal = cv2.erode(horizontal, (1,1), iterations=5)

hlines = cv2.HoughLinesP(horizontal, 1, np.pi/180, 20, np.array([]), 20, 2)

for line in hlines :
    for x1,y1,x2,y2 in line:
        if abs(x1 - x2) > img.shape[1]/4:
            cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

#detect vertical lines
verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 15))

vertical = cv2.erode(bw, verticalStructure)
vertical = cv2.dilate(vertical, verticalStructure)

vertical = cv2.dilate(vertical, (1,1), iterations=5)
#vertical = cv2.erode(vertical, (1,1), iterations=5)

vlines = cv2.HoughLinesP(vertical, 1, np.pi/180, 20, np.array([]), 20, 2)

for line in vlines :
    for x1,y1,x2,y2 in line:
        #if abs(y1 - y2) > img.shape[0]/2:
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

# red color boundaries [B, G, R]
lower = [0, 240, 0]
upper = [20, 255, 20]

# create NumPy arrays from the boundaries
lower = np.array(lower, dtype="uint8")
upper = np.array(upper, dtype="uint8")

# find the colors within the specified boundaries and apply
# the mask
mask = cv2.inRange(img, lower, upper)
output = cv2.bitwise_and(img1, img, mask=mask)

ret,thresh = cv2.threshold(mask, 40, 255, 0)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

img_area  = img.shape[0] * img.shape[1]

for c in contours:
    x, y, w, h = cv2.boundingRect(c)
    if w * h > 0.005 * img_area:
        cv2.rectangle(img1, (x, y), (x+w, y+h), (0, 0, 255), 2)

How can I improve this solution? What other approaches can I implement in order to extract the table cells information better and in a more robust manner ?


问:
Use switch operator with Firebase in react Drawer Navigatoin
I have a drawer navigation in which I would only like to show certain screens based on a condition from firebase realtime database, but the function below is returning undefined. This is in expo React Native.

```<code>function getType(){

  Firebase.database().ref('allTeachers/' + Firebase.auth().currentUser.uid + '/name')
  .once('value').then(function(snapshot){

    return snapshot.exists()
  })
}
</code>```

and this is the navigator where I want to use the result of this function. The navigator is inside a functional component

```<code>!user ? (
            <Drawer.Screen name = "Log In" component={SignUp}/>
            ):getType() ?(

              <>
              <Drawer.Screen name = "Session Creation" component={TeacherSession} />
              <Drawer.Screen name = "Activate Session" component={StartSession} />
              <Drawer.Screen name = "Teacher Details" component={TeacherDetails} />
              <Drawer.Screen name = "Sign Out" component={SignOut} />

              </>
            ):(

                <>
                <Drawer.Screen name = "Student Details" component={StudentDetails} />

                <Drawer.Screen name = "Sign Out" component={SignOut} />
                </>
            )}
</code>```

I want to be able to switch between the two cases based on whether the path exists or not, can anyone help me with this?

Thanks

答:
The function getType() doesn't have a return statement, so it will never return a value. To achieve what you want you will have to manage that asyncronously. A simple way of accomplish that is using a state.

Assuming that the component that holds your navigator is a functional one, the following should work

```<code>const [exists, setExists] = useState(false);

function getType(){

  Firebase.database().ref('allTeachers/' + Firebase.auth().currentUser.uid + '/name')
  .once('value').then(function(snapshot){

    setExists(snapshot.exists());
  })
}

React.useEffect(() => {
    getType();
}, []);
</code>```

...

```<code>!user ? (
            <Drawer.Screen name = "Log In" component={SignUp}/>
            ):exists ?(

              <>
              <Drawer.Screen name = "Session Creation" component={TeacherSession} />
              <Drawer.Screen name = "Activate Session" component={StartSession} />
              <Drawer.Screen name = "Teacher Details" component={TeacherDetails} />
              <Drawer.Screen name = "Sign Out" component={SignOut} />

              </>
            ):(

                <>
                <Drawer.Screen name = "Student Details" component={StudentDetails} />

                <Drawer.Screen name = "Sign Out" component={SignOut} />
                </>
            )}
</code>```

Body:
I have a drawer navigation in which I would only like to show certain screens based on a condition from firebase realtime database, but the function below is returning undefined. This is in expo React Native.

function getType(){

  Firebase.database().ref('allTeachers/' + Firebase.auth().currentUser.uid + '/name')
  .once('value').then(function(snapshot){

    return snapshot.exists()
  })
}

and this is the navigator where I want to use the result of this function. The navigator is inside a functional component

!user ? (
            <Drawer.Screen name = "Log In" component={SignUp}/>
            ):getType() ?(

              <>
              <Drawer.Screen name = "Session Creation" component={TeacherSession} />
              <Drawer.Screen name = "Activate Session" component={StartSession} />
              <Drawer.Screen name = "Teacher Details" component={TeacherDetails} />
              <Drawer.Screen name = "Sign Out" component={SignOut} />

              </>
            ):(

                <>
                <Drawer.Screen name = "Student Details" component={StudentDetails} />

                <Drawer.Screen name = "Sign Out" component={SignOut} />
                </>
            )}

I want to be able to switch between the two cases based on whether the path exists or not, can anyone help me with this?

Thanks

Body:
The function getType() doesn't have a return statement, so it will never return a value. To achieve what you want you will have to manage that asyncronously. A simple way of accomplish that is using a state.

Assuming that the component that holds your navigator is a functional one, the following should work

const [exists, setExists] = useState(false);

function getType(){

  Firebase.database().ref('allTeachers/' + Firebase.auth().currentUser.uid + '/name')
  .once('value').then(function(snapshot){

    setExists(snapshot.exists());
  })
}

React.useEffect(() => {
    getType();
}, []);

...

!user ? (
            <Drawer.Screen name = "Log In" component={SignUp}/>
            ):exists ?(

              <>
              <Drawer.Screen name = "Session Creation" component={TeacherSession} />
              <Drawer.Screen name = "Activate Session" component={StartSession} />
              <Drawer.Screen name = "Teacher Details" component={TeacherDetails} />
              <Drawer.Screen name = "Sign Out" component={SignOut} />

              </>
            ):(

                <>
                <Drawer.Screen name = "Student Details" component={StudentDetails} />

                <Drawer.Screen name = "Sign Out" component={SignOut} />
                </>
            )}