小编Mel*_*art的帖子

useState 更新 React 中的多个值

我使用钩子在 React 组件中收集了一系列用户数据元素。

const [mobile, setMobile] = useState('');
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
Run Code Online (Sandbox Code Playgroud)

其中每一个更新如下。

<input type="text"
       className="form-control"
       id="mobile"
       placeholder="Enter a valid mobile number"
       onChange={event => {setMobile(event.target.value)}}/>
Run Code Online (Sandbox Code Playgroud)

使用对象作为变量有没有更简洁的方法来做到这一点?

javascript reactjs react-hooks

16
推荐指数
3
解决办法
2万
查看次数

在恒定时间内查找平均值和中位数

这是一个常见的面试问题.你有一串数字进来(让我们说超过一百万).数字介于[0-999]之间.

Implement a class which supports three methods in O(1) 

* insert(int i); 
* getMean(); 
* getMedian(); 
Run Code Online (Sandbox Code Playgroud)

这是我的代码.

public class FindAverage {

  private int[] store;
  private long size;
  private long total;
  private int highestIndex;
  private int lowestIndex;

  public FindAverage() {
    store  = new int[1000];
    size = 0;
    total = 0;
    highestIndex = Integer.MIN_VALUE;
    lowestIndex = Integer.MAX_VALUE;

  }

  public void insert(int item) throws OutOfRangeException {
    if(item < 0 || item > 999){
      throw new OutOfRangeException();
    }
    store[item] ++;
    size ++;
    total …
Run Code Online (Sandbox Code Playgroud)

java algorithm data-structures

9
推荐指数
2
解决办法
1368
查看次数

沿numpy数组应用函数

我有以下numpy ndarray.

[ -0.54761371  17.04850603   4.86054302]
Run Code Online (Sandbox Code Playgroud)

我想将此函数应用于数组的所有元素

def sigmoid(x):
  return 1 / (1 + math.exp(-x))

probabilities = np.apply_along_axis(sigmoid, -1, scores)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误.

TypeError: only length-1 arrays can be converted to Python scalars
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么.

python numpy

8
推荐指数
2
解决办法
1万
查看次数

实现Trie以支持Python中的自动完成

我正在尝试实现一个支持网站上自动完成功能的数据结构。我设法实现了Trie的迭代版本。它支持在Trie中添加和搜索的两种主要方法。但是,现在我需要添加一个方法,该方法返回以以下前缀开头的所有单词。有人可以帮我弄这个吗。

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word):
        curr = self.root
        for letter in word:
            node = curr.children.get(letter)
            if not node:
                node = TrieNode()
                curr.children[letter] = node
            curr = node
        curr.end = True

    def search(self, word):
        curr = self.root
        for letter in word:
            node = curr.children.get(letter)
            if not node:
                return False
            curr = node
        return curr.end

    def all_words_beginning_with_prefix(self, prefix):
        #I'm not sure how to go about this one.
Run Code Online (Sandbox Code Playgroud)

python prefix-tree

7
推荐指数
1
解决办法
2303
查看次数

无法登录在django admin后端创建的超级用户

我正在尝试在django管理员后端创建超级用户,但不知怎的,我无法让他们登录.这是我的用户类,

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, max_length=255)
    mobile = PhoneNumberField(null=True)
    username = models.CharField(null=False, unique=True, max_length=255)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)


    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']
    objects = UserManager()
Run Code Online (Sandbox Code Playgroud)

这是用于创建超级用户的UserManager功能,

class UserManager(BaseUserManager):

    def create_user(self, email, mobile=None, username=None, full_name=None, gender=None, birthday=None, password=None,
                    is_staff=False,
                    is_superuser=False, is_active=False, is_mobile_verified=False, is_bot=False, is_online=False,
                    is_logged_in=True):
        if not email:
            raise ValueError("Can't create User without a mobile number!")
        if not password:
            raise ValueError("Can't create User without a password!")
        user …
Run Code Online (Sandbox Code Playgroud)

python django django-admin

7
推荐指数
1
解决办法
570
查看次数

在Django中更改项目名称

从我改变了我的Django项目的名称oldnamenewname使用Pycharm的重构>重命名。我遍历该项目,似乎到处都更改了名称。但是当我尝试运行服务器时,这就是我得到的,

Traceback (most recent call last):
  File "/Users/melissa/Dropbox/newname/manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/core/management/__init__.py", line 317, in execute
    settings.INSTALLED_APPS
  File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/conf/__init__.py", line 56, in __getattr__
    self._setup(name)
  File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/conf/__init__.py", line 43, in _setup
    self._wrapped = Settings(settings_module)
  File "/Users/melissa/Dropbox/newname/env/lib/python3.7/site-packages/django/conf/__init__.py", line 106, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load …
Run Code Online (Sandbox Code Playgroud)

python django

7
推荐指数
3
解决办法
4471
查看次数

在 Django 基于类的视图中传递查询参数

我正在尝试形成这样的网址, http://localhost:8000/mealplan/meals/search/2?from_date=2019-12-29&to_date=2019-12-30&from_time=06:00&to_time=22:00

这是我在 urls.py 中尝试过的

    url(r'^meals/search/(?P<user_id>[\w.-]+)/(?P<from_time>[\w.-]+)/(?P<to_time>[\w.-]+)/(?P<from_date>[\w.-]+)/(?P<to_date>[\w.-]+)$', FilterMealList.as_view(), name='filter_meals'),
Run Code Online (Sandbox Code Playgroud)

显然这不起作用。我收到 404,邮递员上不存在 url。这也是我基于班级的观点。

class FilterMealList(views.APIView):
    def get(self, request, **kwargs):
        try:
            from_time, to_time, from_date, to_date = kwargs.get('from_time'), kwargs.get('to_time'), kwargs.get(
                'from_date'), kwargs.get('to_date')
            return Response({"Suceess": "{}, {}, {}, {}".format(from_time, to_time, from_date, to_date)},
                            status=status.HTTP_200_OK)
        except KeyError as e:
            return Response({"Failure": "Incomplete query params"}, status=status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,1.如何定义一个 url 来在 django 中获取查询参数?2. 如何在基于类的视图中捕获参数?

如何创建一个 url 来获取 django 中的查询参数

python django

7
推荐指数
2
解决办法
1万
查看次数

将数组设置为 null 然后在 useEffect React 中更新它

我是 React 的新手。我有一个 MealList 组件,我正在向它传递一组道具,基于它进行数据调用并更新我在表格中显示的膳食数组。

const MealList = (props) => {
    const [meals, setMeals] = useState([]);

    useEffect(() => {

        const fetchMeals = async (userId, fromDate, toDate, fromTime, toTime) => {
            ...
            return resp;
        };
        fetchMeals(localStorage.getItem('user_id'), props.fromDate, props.toDate, props.fromTime, props.toTime).then(r => {
            setMeals([...meals, ...r.data])//The fetched data is stored in an array here.
        });
    }, [props]);
    console.log(props.fromDate);
    return (
        <div style={{width: '70%'}}>
            ...
            <Table striped bordered hover>
                <thead>
                <tr>
                    ...
                </tr>
                </thead>
                <tbody>
                {meals.map((meal, index) => (<Meal key={meal.id} count={index +1} meal={meal}/>))}//And displayed …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs react-hooks

7
推荐指数
1
解决办法
2553
查看次数

环境设置用于运行猎鹰应用程序

我有一个简单的猎鹰应用程序,我使用以下命令在终端上运行,

gunicorn -b 0.0.0.0:5000 main:app --reload
Run Code Online (Sandbox Code Playgroud)

main.py是实例化app = falcon.API()的python文件.这有效.

所以我试着在PyCharm中设置这个配置.但是这个我无法运行.这是PyCharm配置窗口

在此输入图像描述

有人可以帮助我配置此窗口以使应用程序运行.

pycharm gunicorn falconframework

6
推荐指数
1
解决办法
1739
查看次数

React boostrap 轮播不工作

我正在尝试使用react-bootstrap 创建一个简单的轮播。这是我试图创建的简单的不受控制的轮播。 https://react-bootstrap.github.io/components/carousel/

这是我的代码,

import React from 'react';
import Carousel1 from '../../../assets/FootTheBall_SignUpScreen_CarouselImage-01.png';
import Carousel2 from '../../../assets/FootTheBall_SignUpScreen_CarouselImage-02.png';
import Carousel3 from '../../../assets/FootTheBall_SignUpScreen_CarouselImage-03.png';
import Carousel4 from 
import Carousel from 'react-bootstrap/lib/Carousel';


    const Core = () => (
        <main className="core">
            <article className="left">
                <Carousel>
                    <Carousel.Item>
                        <img src={Carousel1} alt=""/>
                    </Carousel.Item>
                    <Carousel.Item>
                        <img src={Carousel2} alt=""/>
                    </Carousel.Item>
                    <Carousel.Item>
                        <img src={Carousel3} alt=""/>
                    </Carousel.Item>
                </Carousel>

            </article>
            <article className="right"></article>
        </main>

    );
    export default Core
Run Code Online (Sandbox Code Playgroud)

图像垂直堆叠并且不会发生任何过渡。我在这里做错了什么。

javascript reactjs react-bootstrap

6
推荐指数
2
解决办法
2万
查看次数