RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-296927

Anton Buketov's questions

Martin Hope
Anton Buketov
Asked: 2023-02-16 23:58:27 +0000 UTC

REACT 组件不是在循环中创建的

  • 5

上一部分返回 REACT 问题中的循环。

现在我可以像这样访问workers对象的每个属性:

workers[item][item2].firstName

根据这些数据,我想制作与TableRow条目一样多的组件。

    {isReady && Object.keys(workers).map(item =>{
      // console.log(workers[item])
      Object.keys(workers[item]).map(item2 =>{
        console.log(workers[item][item2].job_name)
        {
        <TableRow
          firstName={workers[item][item2].firstName}
          lastName={workers[item][item2].lastName}
          job_name={workers[item][item2].job_name}
          hourly_rates = {workers[item][item2].hourly_rates}
          fixed_fee={workers[item][item2].fixed_fee}
        />
      }
      })
    })
  }

工人自己存储什么: 在此处输入图像描述

或文本:

{
    "data": [
        {
            "workerid": 2,
            "firstName": "Vladimir",
            "lastName": "Moskalev",
            "ratesid": "mnt",
            "idrates": 1,
            "job_name": "mentor",
            "hourly_rates": "7",
            "fixed_fee": "0",
            "jobcode": "mnt"
        },
        {
            "workerid": 1,
            "firstName": "Anton",
            "lastName": "Buketov",
            "ratesid": "mnt",
            "idrates": 1,
            "job_name": "mentor",
            "hourly_rates": "7",
            "fixed_fee": "0",
            "jobcode": "mnt"
        }
    ]
}

但什么也没发生

成分TableRow

import React from 'react'

const TableRow = ({firstName,lastName,job_name,hourly_rates,fixed_fee}) => {
  return (
    <tr>
      <td>{ firstName } { lastName }</td>
      <td>{ job_name }</td>
      <td>{ hourly_rates }</td>
      <td>{ fixed_fee }</td>
    </tr>
    
  )
}

export default TableRow
javascript
  • 2 个回答
  • 20 Views
Martin Hope
Anton Buketov
Asked: 2022-07-31 03:58:30 +0000 UTC

我不明白为什么请求不起作用?节点js快递

  • 0

我想把data ban收到的regions添加到下拉菜单中,但是我不太明白为什么他们不能正常处理请求,理论上showRegionsmain里面的函数应该有regions列表.js。

这是在我的 main.js 文件中

function showRegions(data) {
    if (document.querySelector(".dropdown-menu")) {
        console.log(data)
    }
}

window.addEventListener('DOMContentLoaded', (event) => {
    main()
});

getText = async function (url, callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState == 4 && request.status == 200) {
            console.log(request.responseText)
            callback(request.responseText);
        }
    };
    console.log("передал гет")
    request.open("GET", url);
    request.send();
}
function main(){
    getText('/getAllRegions', showRegions);

}

然后逻辑上我必须处理这个请求

我在 app.js 中处理

var createError = require('http-errors');
var express = require('express');
const bodyParser = require('body-parser');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const db_funcs = require("./db/db_func.js")

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');


var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', (req, res, next)=>{
  console.log("рендерим индекс")
  res.render("index")
})

app.get('/getAllRegions', (req, res, next)=>{
  console.log("гет запрос пришел")
  let result = db_funcs.getRegions()
  console.log(result)
  // res.send(data)

})

以及数据库查询所在的 db_funcs.js 文件本身:

async function getRegions() {
    const response = new Promise((resolve, reject) => {
    const query = "SELECT stops.zone_name FROM stops GROUP BY zone_name;"
    connection.query(query, (err, results) => {
        if(err) reject(new Error(err.message));
            // console.log(results)
            resolve(results);
            // return results;
        });
        return response
    })
};

更新 1.0

javascript node.js
  • 1 个回答
  • 42 Views
Martin Hope
Anton Buketov
Asked: 2022-06-26 16:06:39 +0000 UTC

Firebase + react - db._checkNotDeleted 不是函数如何修复

  • 0

我不明白问题出在哪里,我什至无法上传测试数据。

firebase.js

import { initializeApp } from 'firebase/app'
import {getAuth} from 'firebase/auth'

const firebaseConfig = {
  apiKey: "---",
  authDomain: "---",
  databaseURL: "---",
  projectId: "---",
  storageBucket: "---",
  messagingSenderId: "---",
  appId: "---"
}


// Initialize Firebase and Firebase Authentication
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
export {auth}

ProfileEdit.js

import { useAuthValue } from './AuthContext'
import { signOut } from 'firebase/auth'
import { getDatabase, ref, child, push, update,set } from "firebase/database";
import React, { useState, useEffect } from 'react';
import xtype from 'xtypejs'

import { auth } from './firebase'




function ProfileEdit() {
  const { currentUser } = useAuthValue();

  const db = ref(getDatabase());


  const [name, setName] = useState()
  const [phone, setPhone] = useState()
  const [payment, setPayment] = useState()
  const [address, setAddress] = useState()

  const Submit = () => {
      
     const postData = {
      address: "test",
      firstName: "test",
      paymentByCard: "test",
      phone: "test",
  
    };

    const data = {}
    data["users/" + currentUser?.uid] = postData
    console.log(data)
    return update(ref(db,data))
  }
  console.log(currentUser?.uid)



  return (


    <form action="" className="profile-filling" >
      <input type="text" name={"name"} id="" placeholder="Enter your  firstname" />
      <input type="text" name={"address"} id="" placeholder="Enter your  Address" />
      <input type="text" name={"phone"} id="" placeholder="Enter your  phoneNumber" />

      <div>
        <span>  Credit cart? </span>
        <input type="checkBox" name={"payment"} id="" placeholder="Enter your  firstname" />
        <span>Cahs?</span>
        <input type="checkBox" name={"payment"} id="" placeholder="Enter your  firstname" />
      </div>
      <span onClick={Submit}>Submit</span>
    </form>
  )
}

export default ProfileEdit
reactjs firebase
  • 1 个回答
  • 32 Views
Martin Hope
Anton Buketov
Asked: 2022-06-21 00:22:06 +0000 UTC

我通常如何从 Firebas 获取数据并在 html 标签中显示数据

  • 0

如何从 firebase 获得正常响应。我尝试过这样的事情:

      const db  =  ref(getDatabase(),'Restaurants/');
      let data = []
      onValue(db, (snapshot) => {
        data = snapshot.val();
        return data
      });
      console.log(data)

然后我将它放入一个新数组中:

  let list = []
  for( let i =0;i<=data.length;i++){
    if (data[i] === undefined){
      continue
    }
    else{
      console.log(data[i])
      list.push(data[i])
    }

  }

结果我得到: 在此处输入图像描述

我正在尝试像这样显示 html 标记:

  return(
    <div className="restaraunts">
      {list.map((restaraunt) => (
      <div className="restaraunt-info">
        <span className="restaraunt-name"> {restaraunt.name}</span>
        <span className="restaraunt-desc"> {restaraunt.name}</span>
        <span className="restaraunt-price">{restaraunt.name}</span>
        <span className="restaraunt-time">{restaraunt.name}</span>
        <span className="restaraunt-logo"> {restaraunt.name}</span>
      </div>
      ))}
    </div>
  )

完整代码:

import React from 'react';
import {useState} from 'react'
import { getDatabase, ref, child, get,onValue } from "firebase/database";




function Restaraunts(){

  const db  =  ref(getDatabase(),'Restaurants/');
  let data = []
  onValue(db, (snapshot) => {
    data = snapshot.val();
    return data
  });
  console.log(data)


  let list = []
  for( let i =0;i<=data.length;i++){
    if (data[i] === undefined){
      continue
    }
    else{
      console.log(data[i])
      list.push(data[i])
    }

  }
  console.log(list)
  return(

    <div className="restaraunts">
      {list.map((restaraunt) => (
      <div className="restaraunt-info">
        <span className="restaraunt-name"> {restaraunt.name}</span>
        <span className="restaraunt-desc"> {restaraunt.name}</span>
        <span className="restaraunt-price">{restaraunt.name}</span>
        <span className="restaraunt-time">{restaraunt.name}</span>
        <span className="restaraunt-logo"> {restaraunt.name}</span>
      </div>
      ))}
    </div>
  )
}

export default Restaraunts

我刚开始使用 react 和 firebase。主要问题是为什么我得到一个空数组?以及如何以 HTML 格式输出所有接收到的数据。

reactjs firebase
  • 1 个回答
  • 48 Views
Martin Hope
Anton Buketov
Asked: 2022-07-21 03:42:29 +0000 UTC

是否可以从位于 tilda 的表单中以某种方式向 heroku 发送请求

  • 0

是否有可能以某种方式将数据从表单发送到 tilda,立即发送到 heroku 上的应用程序?

post
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-06-20 16:19:19 +0000 UTC

帮助拆卸 Gson 并创建对象

  • 0

我有来自服务器的 json 响应。还有加工。

问题是我无法data使用来自使用gson.

    public class Main{

    public static void main(String[] args) {

        try {
            String url = "https://ghibliapi.herokuapp.com/films";
            URL obj = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;

            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
//                response.append("\n");
            }

            in.close();

//            System.out.println(response.toString().replaceAll("^.|.$", ""));
            String resString = response.toString().replaceAll("^.|.$", "");
            Gson gson = new Gson();
            String gsonString = gson.toJson(resString);
            System.out.println(gsonString);
            Data data = gson.fromJson(resString, Data.class);
            
            System.out.println(data);
//
//            String name = (String) jsonObject.get("title");
//            System.out.println(name);
//            Ghibli ghibli = new Ghibli();
//            ghibli.startApp();
        } catch (IOException ex) {
            Logger.getLogger(Ghibli.class.getName()).log(Level.SEVERE, null, ex);
        }

//     ghibli.getData("https://ghibliapi.herokuapp.com/films");
    }

}

我的数据类看起来很简单,字段和构造函数:

class Data {

private String id;
private String title;
@SerializedName("original_title")
private String mOriginal_title;
@SerializedName("original_title_romanised")
private String mOriginal_title_romanised;
private String description;
private String director;
private String producer;
@SerializedName("release_date")
private int mRelease_date;
@SerializedName("running_time")
private int mRunning_time;
@SerializedName("rt_score")
private int mRt_score;
private String[] people;
private String[] species;
private String[] locations;
private String[] vehicles;
private String[] url;

public Data(String id, String title, String mOriginal_title, String mOriginal_title_romanised, String description, String director, String producer, int mRelease_date, int mRunning_time, int mRt_score, String[] people, String[] species, String[] locations, String[] vehicles, String[] url) {
    this.id = id;
    this.title = title;
    this.mOriginal_title = mOriginal_title;
    this.mOriginal_title_romanised = mOriginal_title_romanised;
    this.description = description;
    this.director = director;
    this.producer = producer;
    this.mRelease_date = mRelease_date;
    this.mRunning_time = mRunning_time;
    this.mRt_score = mRt_score;
    this.people = people;
    this.species = species;
    this.locations = locations;
    this.vehicles = vehicles;
    this.url = url;
}
}

请求的去向(就在链接“https://ghibliapi.herokuapp.com/films”):

在此处输入图像描述

答案是什么: 在此处输入图像描述

java
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-06-19 17:35:36 +0000 UTC

如何在Java中将接收到的字符串转换为hasmap或arrayList?

  • -1

有GET一个请求,在所有的阴谋之后,我得到了所有信息的一条大线。我怎样才能将它转换成更结构化的东西,比如hasmapor arrayList?

package ghibli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Main {

    public static void main(String[] args) {

        try {
            String url = "https://ghibliapi.herokuapp.com/films";
            URL obj = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;

            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
//                response.append("\n");
            }

            in.close();

//            System.out.println(response.toString().replaceAll("^.|.$", ""));
            
            
            String stringValuses = response.toString().replaceAll("^.|.$", "");
            System.out.println(stringValuses);


            Object objJson = JSONValue.parse(stringValuses);
//            System.out.println(stringValuses);

            JSONObject jsonObject = (JSONObject) objJson;
            System.out.println(jsonObject);

            String name = (String) jsonObject.get("title");
//            System.out.println(name);

//            Ghibli ghibli = new Ghibli();
//            ghibli.startApp();

        } catch (IOException ex) {
            Logger.getLogger(Ghibli.class.getName()).log(Level.SEVERE, null, ex);
        }

//     ghibli.getData("https://ghibliapi.herokuapp.com/films");
    }

}
java
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-06-05 22:33:22 +0000 UTC

我不明白对象在 python 中是如何工作的。游戏。新的 smallFish 对象从何而来

  • 1

有以下代码。而且我的方法eating和think类有问题smallFish。在执行我的代码时,鱼不仅吃藻类,它们还设法繁殖,我不明白这有什么关系。吃海藻的逻辑:如果周围有海藻,鱼就会吃掉它(我们替换了海藻,我们用一个物体填充了旧的地方,place而在新的地方,这条鱼已经 - smallFish)

import pygame
from pygame import *
import random

width,height = 100, 50;
directions = [
    [-1,0],
    [1,0],
    [0,1],
    [0,-1],
    [-1,1],
    [-1,-1],
    [1,-1],
    [1,1],
    [0,0],
    ]

def derictionRandomazer(arr):
    random.shuffle(arr);
    return arr;

def addObjects(obj,objCount,count):
    while count <= objCount:
        x = random.randint(1,width-2);
        y = random.randint(1,height-2);
        if type(pond[x][y]) == Place:
            pond[x][y] = obj(x,y);
            pond[x][y].spawn();
            count += 1
    pygame.display.flip();

pygame.init();

screen = pygame.display.set_mode( (width * 10, height * 10) )
pygame.display.set_caption("Life in Pond"); 

class Place:
    color = (52,152,219)
    def __init__(self, x,y):
        self.x = x;
        self.y = y ;

    def spawn(self):
        square = pygame.Rect(self.x*10, self.y*10, 10, 10);
        pygame.draw.rect(screen, self.color, square);

class Stone(Place):
    color = (0,0,0);

class Seaweed(Place):
    lifePeriod = 40;
    color = (2,124,2);
    reproductivePeriod = 10;
    def __init__(self,x,y):
        super().__init__(x,y);
        self.age = 0;

    def aging(self):
        self.age += 1;
        if self.age == self.lifePeriod:
            self.dying();


    def dying(self):
        pond[self.x][self.y] = Place(self.x, self.y);
        pond[self.x][self.y].spawn();
 

pond = [[ 0 for x in range(height)] for y in range(width)]

for y in range(height):
    for x in range(width):
        pond[x][y] = Place(x,y);
        pond[x][y].spawn();

pygame.display.flip();
num = 0;

class smallFish(Seaweed):
    lifePeriod = 30;
    color = (0, 77, 255);
    reproductivePeriod =  5;

    def __init__(self,x,y):
        super().__init__(x,y)
        self.age = 0;
        self.hunger =  8;


    def reproduction(self,obj):
        if self.age % self.reproductivePeriod == 0:
            for direction in derictionRandomazer(directions):
                new_x = self.x + direction[0];
                new_y = self.y + direction[1];
            if 0 <= new_x < width and 0 <= new_y < height:
                if type(pond[new_x][new_y]) == Place:
                    pond[new_x][new_y] = obj(new_x,new_y);
                    pond[new_x][new_y].spawn();

    def aging(self):
        self.age += 1;
        if self.age == self.lifePeriod:
            self.dying();

    def hungering(self):
        self.hunger -= 1;
        if self.hunger == 0:
            self.dying();

    def think(self,obj):
        for direction in directions:
            new_x = self.x + direction[0];
            new_y = self.y + direction[1];
            if 0 <= new_x < width and 0 <= new_y < height:
                if type(pond[new_x][new_y]) == Seaweed:
                    self.eating(self.x,self.y,new_x,new_y,obj);


        for direction in derictionRandomazer(directions):   
                new_x = self.x + direction[0];
                new_y = self.y + direction[1];
        if 0 <= new_x < width and 0 <= new_y < height:
            if type(pond[new_x][new_y]) == Place:
                self.swim(self.x,self.y,new_x,new_y,obj);

    def reproduction(self,obj):
        if self.age % self.reproductivePeriod == 0:
            for direction in derictionRandomazer(directions):
                new_x = self.x + direction[0];
                new_y = self.y + direction[1];
            if 0 <= new_x < width and 0 <= new_y < height:
                if type(pond[new_x][new_y]) == Place:
                    pond[new_x][new_y] = obj(new_x,new_y);
                    pond[new_x][new_y].spawn();

    def eating(self,x,y,new_x,new_y,obj):
            pond[x][y] = Place(x,y);
            pond[x][y].spawn();
            
            pond[new_x][new_y] = smallFish(new_x,new_y);
            pond[new_x][new_y].spawn();
            self.hunger =+ 1;
        
    def swim(self,x,y,new_x,new_y,obj):
        pond[x][y] = Place(x,y);
        pond[x][y].spawn();
        pond[new_x][new_y] = obj(new_x,new_y);
        pond[new_x][new_y].spawn(); 



addObjects(smallFish,1,0);
addObjects(Stone,50,0);
addObjects(Seaweed,1,0);


while True:
    for y in range(height):
        for x in range(width):
            #  or type(pond[x][y]) == predatoryFish

            if type(pond[x][y]) == Seaweed:
                pond[x][y].aging();
                if type(pond[x][y]) == Seaweed :
                    pond[x][y].reproduction(Seaweed);
    


            if type(pond[x][y]) == smallFish:
                    pond[x][y].aging();
                    # pond[x][y].reproduction(smallFish);
                    pond[x][y].hungering();
                    if type(pond[x][y]) == smallFish:
                        pond[x][y].think(smallFish);


    pygame.display.flip();
python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-05-19 20:49:33 +0000 UTC

我不明白变量的行为

  • 1

我想知道 del 运算符用什么更快,结果我写了这样的代码,但是循环和变量的行为让我有点惊讶,为什么 while 循环中的计数从 50 开始?

import random
import string
import time

listTest = [];
dictinaryTest = {};
for i in range(100):
    n = round(random.random()*10);
    listTest.append(n);
    dictinaryTest.update({i:n})

print("listTest =",len(listTest))
print("dictinaryTest =",len(dictinaryTest))
print("dictinaryTest =",dictinaryTest)
start_timeList = time.time()
j= 0
while j < len(listTest):
 
    del listTest[j]
    j+=1
end_timeList = time.time() -  start_timeList;
print(end_timeList)



start_timeDict = time.time()
k=0
while k < len(dictinaryTest):
    del dictinaryTest[k]
    k += 1;
end_timeDict = time.time() - start_timeDict;    

print(end_timeDict)

print(dictinaryTest)
print(listTest);

初始列表的样子:

在此处输入图像描述

循环后列表的样子:

在此处输入图像描述

python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-04-08 22:51:32 +0000 UTC

我无法弄清楚我的代码有什么问题

  • 0

这个想法是模拟池塘中的生活。问题出在类方法reproduction(self)中。给出“列表索引超出范围”,我该如何正常修复它?

import pygame
from pygame import *
import random

stone_count = 50;
seawed_count = 50;
width,height = 100, 50;
directions = [
    [-1,0],
    [1,0],
    [0,1],
    [0,-1],
    [-1,1],
    [-1,-1],
    [1,-1],
    [1,1],
    [0,0],
    ]

def derictionRandomazer(arr):
    random.shuffle(arr)
    # print(arr);
    return arr

# def is_suitable(arr):
#     print(arr);


pygame.init()

screen = pygame.display.set_mode( (width * 10, height * 10) )
pygame.display.set_caption("Life in Pond"); 
class Place:
    color = (52,152,219)
    def __init__(self, x,y):
        self.x = x
        self.y = y 

    def aseta(self):
        square = pygame.Rect(self.x*10, self.y*10, 10, 10)
        pygame.draw.rect(screen, self.color, square)

class Stone(Place):
    color = (0,0,0)

class Seaweed(Place):
    lifePeriod = 20;
    color = (2,124,2)
    reproductivePeriod = 5;
    def __init__(self,x,y):
        super().__init__(x,y)
        self.age = 0;

    def aging(self):
        self.age += 1;
        if self.age == self.lifePeriod:
            self.dying();
        elif self.age % self.reproductivePeriod == 0:
            self.reproduction();
    
    def reproduction(self):
        for direction in derictionRandomazer(directions):
            new_x = self.x + direction[0];
            new_y = self.y + direction[1];
            if type(pond[new_x][new_y]) == Place:
                pond[new_x][new_y] = Seaweed(new_x,new_y)
                pond[new_x][new_y].aseta();

    def dying(self):
        pond[self.x][self.y] = Place(self.x, self.y)
        pond[self.x][self.y].aseta();

pond = [[ 0 for x in range(width)] for y in range(width)]

# заполнили массив обьектами Place
for y in range(height):
    for x in range(width):
        pond[x][y] = Place(x,y);
        pond[x][y].aseta();

pygame.display.flip();

num = 0

# Добавляем Stone
while num <= stone_count:
    x = random.randint(1,width-2)
    y = random.randint(1,height-2)
    if type(pond[x][y]) == Place:
        pond[x][y] = Stone(x,y)
        pond[x][y].aseta();
        num += 1


pygame.display.flip();

seawedNum = 0

# Добавляем Seaweeds
while seawedNum <= seawed_count:
    x = random.randint(1,width-2)
    y = random.randint(1,height-2)
    if type(pond[x][y]) == Place:
        pond[x][y] = Seaweed(x,y)
        pond[x][y].aseta();
        seawedNum += 1

pygame.display.flip();
s = 0
while True:

    for y in range(height):
        for x in range(width):
            if type(pond[x][y]) == Seaweed:
                s+=1
                # print(s)
                pond[x][y].aging();
    pygame.display.flip();
python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-03-28 00:05:03 +0000 UTC

接口的问题

  • 0

我不知道问题是什么,它给出了:“返回类型 void 与字符串接口 java 不兼容”,我读了一些关于相同方法签名的东西,但不明白。我该如何解决这个问题或向哪个方向挖掘。

public class Student implements Printable { 


    Student() {
         ...
    }


    public void doing() {
        System.out.printf(" что то делает ");
    }
}

class StudentDetails extends Student implements Printable {

    StudentDetails() {
        super()
         ...
    }

    public void doing(){
        System.out.println("делает что то вдобавок");
    }
}

interface Printable {

    void doing();

}

class Main {

public static void main(String[] arg) {
    Student st1 = new Student();
    Student st2 = new Student();
    Student st3 = new Student();
    Student st4 = new Student();
    Student st5 = new Student();

    Student[] students = new Student[5];
    students[0] = st1;
    students[1] = st2;
    students[2] = st3;
    students[3] = st4;
    students[4] = st5;

    for (int i = 0; i < students.length; i++) {
        System.out.println(students[i].doing());
    }

}

}
java
  • 2 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-03-13 00:53:48 +0000 UTC

面向对象,继承

  • -1

有石头,海藻和地方3类。但是在创建类的对象时,Seaweed 写道,没有 X、Y 属性。海藻新的init属性如何使用 ,所以继承的地方属性

class Place:
    color = (52,152,219)
    def __init__(self, x,y):
        self.x = x
        self.y = y 

    def aseta(self):
        square = pygame.Rect(self.x*10, self.y*10, 10, 10)
        pygame.draw.rect(screen, self.color, square)

class Stone(Place):
    color = (0,0,0)

class Seaweed(Place):
    color = (2,124,2)
    def __init__(self, lifePeriod , age, reproductivePeriod ):
        self.lifePeriod = lifePeriod;
        self.age = age;
        self.reproductivePeriod = reproductivePeriod;

    def aging(self):
        self.age += 1 ;

    # def reproduction():

    # def dying():



pond = [[ 0 for x in range(width)] for y in range(width)]


for y in range(height):
    for x in range(width):
        pond[x][y] = Place(x,y);
        pond[x][y].aseta()

pygame.display.flip();

num = 0

while num <= stone_count:
    x = random.randint(1,width-2)
    y = random.randint(1,height-2)
    if isinstance(pond[x][y], Place):
        pond[x][y] = Stone(x,y)
        pond[x][y].aseta();
        num += 1


pygame.display.flip();

seawedNum = 0
while seawedNum <= seawed_count:
    x = random.randint(1,width-2)
    y = random.randint(1,height-2)
    if isinstance(pond[x][y], Place):
        pond[x][y] = Seaweed(1,1,1)
        pond[x][y].aseta();
        seawedNum += 1

pygame.display.flip();
python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-03-08 01:25:32 +0000 UTC

继承与封装

  • 0

我写了一个训练的例子,但是我不明白为什么不能调用 netflix.displayInfo(); 它,我也对public void displayInfo()亚马逊类的问题感兴趣,我如何访问从公司类继承的字段。

package CompanyProgram;

public class Company {
    private int avgSalary;
    private String address;
    public int worksNum;
    public String companyName;
    
    
    public static void main(String[] args) {
        Company company = new Company("Company", 3, "West Hollywood", 40000);
        Amazon amazon = new Amazon("Amazon", 1200, "Nord Hollywood",70000,7);
        HBO hbo = new HBO("Amazon", 1200, "Nord Hollywood",70000,2);
        Netflix  netflix = new Netflix("Netflix", 3, "South Hollywood", 80000);
        
        Netflix.displayInfo();
    }
    
    
    public Company(String companyName, int worksNum, String address, int avgSalary){
        this.companyName = companyName;
        this.worksNum = worksNum;
        this.address = address;
        this.avgSalary = avgSalary;
    }
    
    public String getAddress(){
        return this.address;
    }

    public void displayInfo(){
        System.out.printf("Company name: %d \n", companyName);
        System.out.printf("Workers count: %d \n",worksNum);
        System.out.printf("adress: %d \n", address);
        System.out.printf("average salary: %d \n", avgSalary);
    }
    
    public void setAddress(String address){
        this.address = address;
    }    
    
    public String getAvgSalary(){
        return this.companyName;
    }
    public void setAvgSalary(int avgSalary){
        this.avgSalary = avgSalary;
    }  
}


class Amazon extends Company{
    private int filmCount;
    
    public Amazon(String companyName, int worksNum, String address, int avgSalary, int filmCount) {
        super(companyName, worksNum, address, avgSalary);
        this.filmCount = filmCount;
    }
    
    public int getFilmCount(){
        return this.filmCount;
    }
    public void setFilmCount(int filmCount){
        this.filmCount = filmCount;
    }
    
    public void displayInfo(){
//        System.out.printf("Company name: %d \n", companyName);
//        System.out.printf("Workers count: %d \n",worksNum);
//        System.out.printf("address: %d \n", address);
//        System.out.printf("average salary: %d \n", avgSalary());
        System.out.printf("Film Count: %d \n", filmCount);
    }
    
}

class Netflix extends Company{
    public Netflix(String companyName, int worksNum, String address, int avgSalary) {
        super(companyName, worksNum, address, avgSalary);
    }
}

class HBO extends Amazon{
    public HBO(String companyName, int worksNum, String address, int avgSalary, int filmCount) {
        super(companyName, worksNum, address, avgSalary, filmCount);
    }

}
java
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-01-16 17:59:33 +0000 UTC

我不明白为什么字典最后是空的

  • 0

在于datesAndPrices以下几点:

{'2019-01-01': 3869.47, '2019-01-02': 3941.2167, '2019-01-03': 3832.155, '2019-01-04': 3863.6267, '2019-01-05': 3835.5983}

我不明白为什么up_periods它们down_periods是空的。

inup_periods应该是这样的:

up_periods = {
'1': [2019-01-01, 2019-01-02],
'2': [2019-01-03, 2019-01-04],
}

down_periods相反,应该有价格下跌的日子。

仅up_periods在价格值高于前一天的那些日子,down_periods降低。

我的代码:

value = 0
up_periods = {}
# down_periods = {}
values = []
keyValues = list(datesAndPrices.keys());
pos = -1;
for j in sorted(datesAndPrices):
    pos += 1;
    if pos >= len(keyValues):
        pos  = len(keyValues)-1
    if datesAndPrices[j] > value:
        value = datesAndPrices[j];
        values.append(j)
    if datesAndPrices[keyValues[pos]] < value:
        up_periods.update({"key": j, "prices": values.copy()})
        values.clear()

print (up_periods)
python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-01-16 02:20:08 +0000 UTC

如何将新列表添加到带有列表的字典中

  • 0

有字典up_periods,down_periods我想在哪里存储带有值的列表。如果比特币每天都在增长,那么我应该用这些天的价值来补充列表。如果第二天比特币汇率下跌,我必须将这个现成的列表添加到字典中,并将已经下降的比特币汇率添加到down_periods.

数据:

{'2019-01-01': 3869.47, '2019-01-02': 3941.2167, '2019-01-03': 3832.155, '2019-01-04': 3863.6267, '2019-01-05': 3835.5983}

我想做的事:

up_periods = {
'1': [2019-01-01, 2019-01-02 , 2019-01-05, 2019-01-04],
'2': [2019-01-10, 2019-01-11],
'3': [2019-01-25, 2019-01-26 , 2019-01-27, 2019-01-28, 2019-01-29],
}

与 down_periods 字典类似。这个字典和列表可以是任意长度。

问题:我不太明白如何在一个周期中创建新列表,并且在价格开始下跌时从同一个地方继续。

我的代码:

value = 0
up_periods = {}
down_periods = {}
values = []

for i in sorted(datesAndPrices):
    values = []
    for j in sorted(datesAndPrices):
    #    if datesAndPrices[i] <= value тут падение
        if datesAndPrices[j] > value:
            value = datesAndPrices[j];
            values.append(j)
        else:
            up_periods.update({"key": values[0], "prices": values})
python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2022-01-04 17:42:55 +0000 UTC

变量计数错误

  • 2
print("start")
start = {"x":20, "y":20};
print(start)
print("startingPos")
startingPos = start;
print(startingPos)

def refreshCoords(directions,startingPos):
    if directions == "^":
        startingPos = {"x":startingPos["x"], "y":startingPos["y"]+1};
    if directions == "v":
        startingPos = {"x":startingPos["x"], "y":startingPos["y"]-1};
        return startingPos  
    if directions == ">":
        startingPos = {"x":startingPos["x"]+1, "y":startingPos["y"]};
    if directions == "<":
        startingPos = {"x":startingPos["x"]-1, "y":startingPos["y"]}; 

def walker(direction,startingPos):
    print(refreshCoords(direction,startingPos))

for i in range(1,10,1):
    walker("v",startingPos)

我需要帮助解释,我不明白为什么在调用 walker("v",startingPos) 时,"Y" 只更改一次,然后值重复。它必须根据需要更改多次(在此示例中,调用函数时它从 20 更改为 10)。这段代码有什么错误?

python
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2020-10-06 22:27:58 +0000 UTC

x 轴显示未定义,尽管有值。图表js

  • 0

我不知道为什么我没有定义 x 轴上的正常分区名称 (100,200,300)。我已经在这个问题上苦苦挣扎了两天了。

链接:https ://codepen.io/kotbegemotest/pen/oNvGJXp

faValues = [];
raValues = [];

for(let i = 100; i<=20000; i+=100) {
    faValues[i] = i;
}

for(let i = 100; i<=20000; i+=100) {
    raValues[i] =  Math.round(Math.pow(i, 2)/(Math.exp(i/500)-1))
}

let plotLineChart = document.getElementById('plotLineChart');
Chart.defaults.scale.ticks.beginAtZero = true
const data = {
    labels: faValues,
    datasets: [
        {
            label: 'T=500',
            borderWidth: 2,
            boderColor: 'blue',
            pointBackgroundColor : 'blue',
            backgroundColor: 'rgba(65,52,71,0.0)',
            data: raValues

        }                  

    ]
}

const lineChart = new Chart(plotLineChart,{
    type: 'line',
    data: data,
    options : {
      scales: {
        yAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'r',
            fontSize: 32
          }
        }],
        xAxes: [{
          scaleLabel: {
            display: true,
            labelString: 'f',
            fontSize: 32
          }
        }],
      }
    }
});
    <canvas id="plotLineChart">

    </canvas>

在此处输入图像描述

javascript
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2020-07-24 19:36:36 +0000 UTC

如何更改 WordPress 中排序选项的显示顺序?

  • 0

如何交换排序点?它在哪里完成?我添加了这些排序选项,如下所示:

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );
    if ( 'diametr_asc' == $orderby_value ) {
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'ASC';
        $args['meta_key'] = 'diametr';
    }
    elseif ( 'diametr_desc' == $orderby_value ) {
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'DESC';
        $args['meta_key'] = 'diametr';
    }

    return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby',5 );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby',5 );

function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['diametr-desc'] = __('Размер: по убыванию','woocomerce');
    $sortby['diametr-asc'] = __('Размер: по возрастанию','woocomerce');
    return $sortby;
}

在此处输入图像描述

wordpress
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2020-07-20 17:55:57 +0000 UTC

如何按您的领域对货物进行分类?

  • 0

我看到很多添加排序的示例。但我需要添加我的。但我无法理解一些事情。例如 $sortby['stock_list_asc'] stock_list_asc- 它来自哪里或者它的名字?

    $args['orderby'] = 'meta_value_num wp_posts.ID';
    $args['order'] = 'ASC';
    $args['meta_key'] = '_stock';

以及这些字段,最好告诉他们,$args['orderby'] 和 $args['meta_key'] 的位置。或将我引导至文档链接。我需要按照示例进行操作,但仅针对大小。

add_filter( 'woocommerce_get_catalog_ordering_args', 'custom_woocommerce_get_catalog_ordering_args' );

function custom_woocommerce_get_catalog_ordering_args( $args ) {
    $orderby_value = isset( $_GET['orderby'] ) ? wc_clean( $_GET['orderby'] ) : apply_filters( 'woocommerce_default_catalog_orderby', get_option( 'woocommerce_default_catalog_orderby' ) );

    if ( 'stock_list_asc' == $orderby_value ) {
        $args['orderby'] = 'meta_value_num wp_posts.ID';
        $args['order'] = 'ASC';
        $args['meta_key'] = '_stock';
    }
    elseif ( 'stock_list_desc' == $orderby_value ) {
        $args['orderby'] = 'meta_value_num wp_posts.ID';
        $args['order'] = 'DESC';
        $args['meta_key'] = '_stock';
    }

    return $args;
}

add_filter( 'woocommerce_default_catalog_orderby_options', 'custom_woocommerce_catalog_orderby' );
add_filter( 'woocommerce_catalog_orderby', 'custom_woocommerce_catalog_orderby' );

function custom_woocommerce_catalog_orderby( $sortby ) {
    $sortby['stock_list_desc'] = 'Остаток: по убыванию';
    $sortby['stock_list_asc'] = 'Остаток: по возрастанию';
    return $sortby;
}
wordpress
  • 1 个回答
  • 10 Views
Martin Hope
Anton Buketov
Asked: 2020-07-17 20:11:26 +0000 UTC

打印页面的显示差异,在不同的页面上,虽然样式是一样的

  • -1

折腾了一天,不明白是什么问题。在“主”和“价格”页面,当你点击打印按钮时,会出现不同的结果。 在此处输入图像描述

主页摘要: 在此处输入图像描述

价格页面:

在此处输入图像描述

@media print

{

@page {
    margin: 1cm 1cm 1cm 1cm !important;
}

span.print-heading
{
    position: relative !important;
    display: block !important;
    margin-bottom: 25px !important;
    min-width: 100% !important;
    font-size: 28px !important;
    color: #82b440 !important;
    text-align: center !important;
    page-break-before: always !important;
    z-index: 999 !important;

}

.materials_wrapper .m_tbl
    {
    position: relative !important;
    page-break-inside: avoid !important;
    }

.materials_wrapper .m_tbl .material_wrapper .m_legend h3
    {
    font-weight: normal !important;
    font-size: 24px !important;
    }


.materials_wrapper .m_tbl .m_wrapper
{
position: relative !important;
page-break-inside: avoid !important;
}

.material_wrapper{
    top: 5px !important;
    position: relative !important;
    /*page-break-inside: avoid;*/
    page-break-before: always !important;
    page-break-after: always !important;
    /*min-height: 700px;*/
    z-index: 999 !important;
}

.material_wrapper:first-child{
    position: relative !important;
    margin-top: 0px !important;
    padding-bottom: 0px !important;
    top: -70px !important;
    /*page-break-inside: auto;*/
    page-break-before: auto !important;
    page-break-after: auto !important;
}

.tg-main-section.pricing,
.materials_wrapper .m_tbl>div
    {
    position: relative !important;
    display: block !important;
    }

.materials_wrapper .m_tbl>div,
.tg-main-section.pricing
{
position: relative !important;
padding-bottom: 0px !important;
}

.tg-main-section.services,
.tg-main-section-2,
.tg-main-section-3,
.lifestyle-area,
.tg-main-section-products,
.tg-main-section.materials,
#footer,
.tg-home-slider,
#header,
.tg-banner,
tg-breadcrumb,
.materials_wrapper .m_navi a.print_btn,
#languages,
.preloader-bg,
top-alert,
modal-alert-bg,
.materials_wrapper .m_navi .m_btns button,
.materials_wrapper .m_navi .m_btns,
.tg-section-head,
.materials_wrapper .m_tbl .m_image,
parallax-mirror,
img
{
    display: none !important;
}

.materials_wrapper .m_tbl .m_wrapper .m_price_info
{
position: relative !important;
min-width: 150px !important;
text-align: right !important;
}

.materials_wrapper .m_legend
{
position: relative !important;
margin-top: 10px !important;
padding-bottom: 20px !important;
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
align-items: center !important;
width: 100% !important;
left: 0 !important;
right: 0 !important;
}

.materials_wrapper .m_legend .row div[data-mcol="1"]
{
width: auto !important;
height: 100% !important;
min-width: 150px !important;
z-index: 999 !important;
position: relative !important;
display: flex !important;
justify-content: flex-end !important;
}

.materials_wrapper .m_legend h3
    {
    position: relative !important;
    color: #82b440 !important;
    width: 100% !important;
    background-color: #fff !important;
    margin-top: 10px !important;
    bottom: 0px !important;
    /*page-break-before: always !important;*/
    /*page-break-after: auto !important;*/
    }

.materials_wrapper .m_tbl .material_wrapper .m_legend h3 + .row
{
    display: inline-block !important;
    position: relative !important;
    width: auto !important;
}

.materials_wrapper .m_navi .m_btns button,
.materials_wrapper .m_navi .m_btns
{
display: block !important;
position: absolute !important;
}

.materials_wrapper .m_navi
{
position: relative !important;
border-bottom: none !important;
}

*
{
background-color: #fff !important;
position: relative !important;
}

body
{
position: relative !important;
bottom: 0 !important;
top: 0 !important;
left: -5px !important;
overflow: hidden !important;
max-height: 100% !important;
background-color: #fff !important;
height: auto!important;
float: none!important;
}

.materials_wrapper .m_tbl .material_wrapper:nth-child(1)>.m_legend
{
    border-bottom:4px solid #fff !important;
    position: relative !important;
}

.materials_wrapper .m_tbl .material_wrapper>.m_legend
{
    position: relative !important;
    border-bottom:4px solid #82b440 !important;
    bottom: -17px !important;
}

.materials_wrapper .m_tbl>div
{
    position: relative !important;
    background-color: #fff !important;
    left: -2px !important;
    page-break-before: auto !important;
    page-break-after: auto !important;
    page-break-inside: avoid !important;
}


.materials_wrapper .material_wrapper .row
{
    page-break-inside: avoid !important;
}

.materials_wrapper .m_tbl .m_wrapper .m_main_info h4
{
    position: relative !important;
    font-size: 16px !important;
    color: #82b440 !important;
}

.materials_wrapper .m_tbl .m_wrapper
{
    position: relative !important;
    padding-bottom: 0px !important;
    page-break-inside: avoid !important;
}

}

网站本身https://basemetal.multiweb.ee/price

javascript
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5