云裳

文章 评论 浏览 30

云裳 2025-02-20 15:30:26

您的json

const json = {
  "Albums": {
    "Krezip": [
      {
        "artist":"Krezip",
        "title":"Days like this",
      }
     ]
  }
}

内部循环

const albums = json.Albums // this is an array of albums

for(let key of Object.keys(albums)){
    const album = albums[key]
    // If this is an array then you might need to loop through them
    console.log(album[0])
}

your json

const json = {
  "Albums": {
    "Krezip": [
      {
        "artist":"Krezip",
        "title":"Days like this",
      }
     ]
  }
}

inside for loop

const albums = json.Albums // this is an array of albums

for(let key of Object.keys(albums)){
    const album = albums[key]
    // If this is an array then you might need to loop through them
    console.log(album[0])
}

如何在JavaScript中访问JSON对象?

云裳 2025-02-20 11:20:08

问题是在问题标题中,您正在尝试在render_products方法中显示{product.trating}。它不是一个数字,而是{速率,计数}作为密钥的对象。请参考以下代码。

import React, { useState, useEffect } from "react";
import axios from "axios";

const idealoBackendUrl = "https://fakestoreapi.com/products"


function App() {


const render_products = (Products) => {
   
    return <div className='category-section fixed'>
        <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2>

        <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}>
            {/* Loop Products */}
            {Products.map(product => (
                <div className="group relative shadow-lg" >
                    <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none">
                        <img
                            alt="Product Image"
                            src=""
                            className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                        />
                    </div>
                    <div className="flex justify-between p-3">
                        <div>
                            <h3 className="text-sm text-gray-700">
                                <a href={product.href}>
                                    <span aria-hidden="true" className="absolute inset-0" />
                                    <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.item_name}</span>
                                </a>
                                <p>Tag -</p>
                            </h3>
                            {/* Here was the issue */}
                            <p className="mt-1 text-sm text-gray-500">Rating: {product.rating.rate}</p>
                        </div>
                        <p className="text-sm font-medium text-green-600">${product.current_price}</p>
                    </div>
                </div>
            ))}
        </div>
    </div>
}

const [itemData, setItemData] = useState(null);
const [error, setError] = React.useState(null);

useEffect(() => {
    getItemDataWithAxios().then(r => console.log(r));
}, []);

const getItemDataWithAxios = async () => {
    const response = await axios.get(idealoBackendUrl);
    console.log('print response data')
    console.log(response.data);
    setItemData(response.data);
};

if (error) return `Error: ${error.message}`;
if (!itemData) return <center style={{ marginTop: '200px' }}> <img src="https://icons8.com/preloaders/preloaders/1474/Walk.gif" style={{ width: '70px' }} /> </center>;


return (
      
          <div className="flex fixed flex-row">
              <div className="h-screen  bg-slate-800 p-3 xl:basis-1/5" style={{ minWidth: '65%' }}>
                  <img className="w-full" src="" alt="Sunset in the mountains" />
                  <div className="px-6 py-4">
                      <h1 className="text-3xl mb-2 font-bold text-white"> Idealo product catalog </h1>
                      <p className="text-gray-700 text-white">
                          by - <b style={{ color: 'orange' }}>Sithija</b>
                      </p>
                  </div>
              </div>
              <div className="ml-5  p-10 xl:basis-4/5">
                  {render_products(itemData)}
              </div>
          </div>
      // </>
   
  );
}

export default App;

随意编辑代码以包含您的徽标组件和其他图标,我将其删除,因为我没有这些项目的副本。

Issue is in the question title, you are trying to display {product.rating} in the render_products method. It is not a number but an object of {rate, count} as keys. Please refer the below code.

import React, { useState, useEffect } from "react";
import axios from "axios";

const idealoBackendUrl = "https://fakestoreapi.com/products"


function App() {


const render_products = (Products) => {
   
    return <div className='category-section fixed'>
        <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2>

        <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}>
            {/* Loop Products */}
            {Products.map(product => (
                <div className="group relative shadow-lg" >
                    <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none">
                        <img
                            alt="Product Image"
                            src=""
                            className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                        />
                    </div>
                    <div className="flex justify-between p-3">
                        <div>
                            <h3 className="text-sm text-gray-700">
                                <a href={product.href}>
                                    <span aria-hidden="true" className="absolute inset-0" />
                                    <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.item_name}</span>
                                </a>
                                <p>Tag -</p>
                            </h3>
                            {/* Here was the issue */}
                            <p className="mt-1 text-sm text-gray-500">Rating: {product.rating.rate}</p>
                        </div>
                        <p className="text-sm font-medium text-green-600">${product.current_price}</p>
                    </div>
                </div>
            ))}
        </div>
    </div>
}

const [itemData, setItemData] = useState(null);
const [error, setError] = React.useState(null);

useEffect(() => {
    getItemDataWithAxios().then(r => console.log(r));
}, []);

const getItemDataWithAxios = async () => {
    const response = await axios.get(idealoBackendUrl);
    console.log('print response data')
    console.log(response.data);
    setItemData(response.data);
};

if (error) return `Error: ${error.message}`;
if (!itemData) return <center style={{ marginTop: '200px' }}> <img src="https://icons8.com/preloaders/preloaders/1474/Walk.gif" style={{ width: '70px' }} /> </center>;


return (
      
          <div className="flex fixed flex-row">
              <div className="h-screen  bg-slate-800 p-3 xl:basis-1/5" style={{ minWidth: '65%' }}>
                  <img className="w-full" src="" alt="Sunset in the mountains" />
                  <div className="px-6 py-4">
                      <h1 className="text-3xl mb-2 font-bold text-white"> Idealo product catalog </h1>
                      <p className="text-gray-700 text-white">
                          by - <b style={{ color: 'orange' }}>Sithija</b>
                      </p>
                  </div>
              </div>
              <div className="ml-5  p-10 xl:basis-4/5">
                  {render_products(itemData)}
              </div>
          </div>
      // </>
   
  );
}

export default App;

Feel free to edit the code to include your logo component and other icons, I removed them since I don't have the copy of those items.

映射产品和获取“对象”无效,因为React child'错误

云裳 2025-02-20 04:33:17

一个选项是首先汇总数据以计算 Yellowcards GAMES by leagueCountry 的数量。之后,您可以将长时间转换为长时间,从而可以轻松地通过 ggplot2 绘制。

使用一些虚假的随机示例数据模仿您的真实数据:

set.seed(123)

new_soccer_referee <- data.frame(
  player = sample(letters, 20),
  leagueCountry = sample(c("Spain", "France", "England", "Italy"), 20, replace = TRUE),
  yellowCards = sample(1:5, 20, replace = TRUE),
  games = sample(1:20, 20, replace = TRUE)
)

library(dplyr)
library(tidyr)
library(ggplot2)

new_soccer_referee_long <- new_soccer_referee %>% 
  group_by(leagueCountry) %>%
  summarise(across(c(yellowCards, games), sum)) %>%
  pivot_longer(-leagueCountry, names_to = "variable", values_to = "number")

ggplot(new_soccer_referee_long, aes(leagueCountry, number, fill = variable)) +
  geom_col(position = "dodge")

“”

One option would be to first aggregate your data to compute the number of yellowCards and games by leagueCountry. Afterwards you could convert to long which makes it easy to plot via ggplot2.

Using some fake random example data to mimic your real data:

set.seed(123)

new_soccer_referee <- data.frame(
  player = sample(letters, 20),
  leagueCountry = sample(c("Spain", "France", "England", "Italy"), 20, replace = TRUE),
  yellowCards = sample(1:5, 20, replace = TRUE),
  games = sample(1:20, 20, replace = TRUE)
)

library(dplyr)
library(tidyr)
library(ggplot2)

new_soccer_referee_long <- new_soccer_referee %>% 
  group_by(leagueCountry) %>%
  summarise(across(c(yellowCards, games), sum)) %>%
  pivot_longer(-leagueCountry, names_to = "variable", values_to = "number")

ggplot(new_soccer_referee_long, aes(leagueCountry, number, fill = variable)) +
  geom_col(position = "dodge")

位置= barplot中的geom_col中的道奇

云裳 2025-02-19 21:02:05

将此依赖性添加到pom.xml

org.hibernate Hibernate-entityManager 5.2.3.final

Add this dependency to pom.xml

org.hibernate hibernate-entitymanager 5.2.3.Final

SomeService需要一个名为&#x27; EntityManagerFactory&#x27;的豆子。找不到

云裳 2025-02-19 18:02:33

这在很大程度上取决于 speed data 类中的类是具有某些代码执行或仅是正常字段的属性。

没有太大的区别:

public float speed = 2f;

对绩效有影响:

public float speed {
    get {
         return ExpensiveFunction();
    }
}

It depends largely if speed in the Data class is a property with some code execution or just a normal field.

not much of a difference:

public float speed = 2f;

has an impact on performance:

public float speed {
    get {
         return ExpensiveFunction();
    }
}

Unity从另一个脚本表演中访问变量

云裳 2025-02-19 09:07:13

这是一个仅在原始lapply中进行的示例,正​​如我在评论中提到的那样

library(dplyr)
library(readr)

lapply(list_of_files, \(f) {
  read_csv(f, col_names=TRUE) %>% 
    rename_with(~c("A", "B", "C", "D")) %>%  
    mutate(newcol1 = paste0(A,B),newcol2 = paste0(C,D))
})

Here is an example of just doing all in the original lapply, as I mentioned in the comments

library(dplyr)
library(readr)

lapply(list_of_files, \(f) {
  read_csv(f, col_names=TRUE) %>% 
    rename_with(~c("A", "B", "C", "D")) %>%  
    mutate(newcol1 = paste0(A,B),newcol2 = paste0(C,D))
})

在R中的数据帧列表中操作

云裳 2025-02-19 04:46:01

您应该看一下sectionList的外推道。当数据更新时,Extradata更新列表

You should have a look SectionList's extraData prop. extraData update the list when data is updated

我使用suctionList,并且在数据阵列内有一个团队阵列,当我注册一个播放器时,sectionList在API上未更新,直到我重新加载应用程序

云裳 2025-02-19 01:30:14

只需将您的帖子ID纳入路径:

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Entity\Post;

class ArticleAdminController extends BaseController
{
    public function temporaryUploadAction(Request $request, Post $post, string $projectDir)
    {
        /** @var UploadedFile $uploadedFile */
        $uploadedFile = $request->files->get('image');
        $uploadedFile->move("{$projectDir}/private/{$post->getId()}");
    }
}

Simply incorporate your Post ID into path:

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Entity\Post;

class ArticleAdminController extends BaseController
{
    public function temporaryUploadAction(Request $request, Post $post, string $projectDir)
    {
        /** @var UploadedFile $uploadedFile */
        $uploadedFile = $request->files->get('image');
        $uploadedFile->move("{$projectDir}/private/{$post->getId()}");
    }
}

Symfony-从请求中存储图像

云裳 2025-02-18 18:51:06

要仅在特定分支上提出拉请请求时运行阶段,您可以在舞台上设置条件。

condition: and(eq(variables['System.PullRequest.TargetBranch'], 'refs/heads/branchname'), eq(variables['Build.Reason'], 'PullRequest'))

以下是一个示例:

stages:
- stage: A
  condition: and(eq(variables['System.PullRequest.TargetBranch'], 'refs/heads/branchname'), eq(variables['Build.Reason'], 'PullRequest'))
  jobs:
  - job: A1
    steps:
      - script: xx

您可以使用预定义的变量: system.pullrequest.targetBranch build.Reason 来过滤触发方法并拉请求目标分支。

有关更多详细信息,您可以参考文档:条件预定义变量

To run a stage only when a pull request has been made on a particular branch, you can set the condition in the stage.

condition: and(eq(variables['System.PullRequest.TargetBranch'], 'refs/heads/branchname'), eq(variables['Build.Reason'], 'PullRequest'))

Here is an example:

stages:
- stage: A
  condition: and(eq(variables['System.PullRequest.TargetBranch'], 'refs/heads/branchname'), eq(variables['Build.Reason'], 'PullRequest'))
  jobs:
  - job: A1
    steps:
      - script: xx

You can use predefined variables: System.PullRequest.TargetBranch and Build.Reason to filter the trigger method and pull request target branch.

For more detailed info, you can refer to the docs: Condition and Predefined variables.

只有在YAML提出拉动请求时,我才能运行一个舞台

云裳 2025-02-17 20:58:52

我设法找到了解决方案。这是浏览器,我猜是对https:// 2f81239fe704/(是docker容器hostname)和我的任何nginx.conf更改的第一个不正确的重定向响应。清洁cookie和网站数据后,更改为nginx.conf实际上会产生效果。最后,我最终得到了:

server_name localhost;
        
if ($scheme = http) {
    return 301 https://localhost:8021$request_uri;
}

I managed to find the solution. It was the browser, which I guess, cached my first, incorrect redirection response to https://2f81239fe704/ (which was docker container hostname) and any of my nginx.conf change didn't really had any effect. After cleaning cookies and site data, changes to nginx.conf actually make effects. Finally, I ended up with:

server_name localhost;
        
if ($scheme = http) {
    return 301 https://localhost:8021$request_uri;
}

重定向到docker容器内Nginx上的HTTPS

云裳 2025-02-17 16:45:21

要在Keras中创建自定义内核初始化,请尝试以下类似:

import numpy as np
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import load_breast_cancer

X,y = load_breast_cancer(return_X_y =True)

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1)


def my_custom_initialization(shape, dtype=None):
    return tf.random.normal(shape, dtype=dtype)

model = Sequential()
model.add(Dense(units=30,input_dim=X_train.shape[1],activation='relu',
                kernel_initializer=my_custom_initialization))
model.add(Dense(units=20,activation='relu',
                kernel_initializer=my_custom_initialization))
model.add(Dense(units=1,activation='sigmoid',
                kernel_initializer=my_custom_initialization))

model.compile(optimizer='sgd',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=3,batch_size=40,verbose=1)

输出:

Epoch 1/3
10/10 [==============================] - 2s 65ms/step - loss: 598388.8750 - accuracy: 0.5553 - val_loss: 0.6913 - val_accuracy: 0.6316
Epoch 2/3
10/10 [==============================] - 0s 9ms/step - loss: 0.6907 - accuracy: 0.6256 - val_loss: 0.6898 - val_accuracy: 0.6316
Epoch 3/3
10/10 [==============================] - 0s 8ms/step - loss: 0.6893 - accuracy: 0.6256 - val_loss: 0.6883 - val_accuracy: 0.6316

For creating custom kernel initialization in Keras, try like below:

import numpy as np
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense
from sklearn.datasets import load_breast_cancer

X,y = load_breast_cancer(return_X_y =True)

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,random_state=1)


def my_custom_initialization(shape, dtype=None):
    return tf.random.normal(shape, dtype=dtype)

model = Sequential()
model.add(Dense(units=30,input_dim=X_train.shape[1],activation='relu',
                kernel_initializer=my_custom_initialization))
model.add(Dense(units=20,activation='relu',
                kernel_initializer=my_custom_initialization))
model.add(Dense(units=1,activation='sigmoid',
                kernel_initializer=my_custom_initialization))

model.compile(optimizer='sgd',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(X_train,y_train,validation_data=(X_test,y_test),epochs=3,batch_size=40,verbose=1)

Output:

Epoch 1/3
10/10 [==============================] - 2s 65ms/step - loss: 598388.8750 - accuracy: 0.5553 - val_loss: 0.6913 - val_accuracy: 0.6316
Epoch 2/3
10/10 [==============================] - 0s 9ms/step - loss: 0.6907 - accuracy: 0.6256 - val_loss: 0.6898 - val_accuracy: 0.6316
Epoch 3/3
10/10 [==============================] - 0s 8ms/step - loss: 0.6893 - accuracy: 0.6256 - val_loss: 0.6883 - val_accuracy: 0.6316

Keras中的自定义内核初始化

云裳 2025-02-16 23:47:08

以下可以完成这项工作

arr.reshape((-1, n))[:, :m] = 100

The following could do the job

arr.reshape((-1, n))[:, :m] = 100

元素循环范围的数值变化值

云裳 2025-02-16 20:43:04

假设您的项目被构建为-A.Jar
而且该a.jar取决于另一个库-B.Jar

两个罐子都取决于log4j.jar的记录目的。

在这种情况下,您将将log4j作为运行时依赖关系添加到B.Jar的POM中,以便无需任何问题就可以编译。
当通过其POM建立a.jar时,将包括log4j和b.jar。

这也将有助于避免运行时方法冲突。

Assume that you project is builded as - A.jar
and this A.jar is dependent on another library - B.jar

Both the jars are dependent on log4j.jar for logging purpose.

In this case you will be adding log4j as runtime dependency to B.jar's pom so that it will compile without any issues.
And when A.jar is builded from its pom the log4j and B.jar will be included.

This will also help to avoid runtime method conflict.

如何使用Runtime&#x27;范围可以有用(使用)?

云裳 2025-02-16 19:20:33

经过一番研究,我在必须具有EIP55校验和。但是,由于API提供了检查和创建这些功能的功能,因此我认为我尝试了一下,并且可以使用!

因此,在功能开始时添加了一条线之后:

to_public=web3.toChecksumAddress(to_public)

它可以使用。

After some more research I found the solution in the Web3.py Documentation. To me, it's not clearly stated there, that addresses must have an EIP55 checksum. But as the API provides functions to check and create these, I thought I give it a try, and it worked!

So after adding an additional line at the beginning of the function:

to_public=web3.toChecksumAddress(to_public)

it worked.

错误将资产发送到使用Python/web3的二元地址3

云裳 2025-02-16 10:29:59

您可以将字符串连接起来:

let str = 'prefix';
str = str + ' ';
// str === 'prefix '

或者,如果要将任何大小的字符串粘贴到指定的长度:

let str = 'prefix';
str = str.padEnd(7, " ");
// str === 'prefix '

You can concatenate the strings:

let str = 'prefix';
str = str + ' ';
// str === 'prefix '

or, if you want to pad any sized string to a specified length:

let str = 'prefix';
str = str.padEnd(7, " ");
// str === 'prefix '

如何在字符串末端添加空空间?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文