AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

全部问题(coding)

Martin Hope
rain snow
Asked: 2025-04-28 08:17:38 +0800 CST

使用破折号绘制偏回归图

  • 6

我有数据框,其中给出了 x 和 y 列,我想在它们之间绘制回归模型,主要想法是我应该使用 dash 框架,因为根据 chow 检验,两个回归模型在不同实例值下可能会有差异,基于以下链接:dash 模型

我写了下面的代码:

import pandas as pd
from dash import Dash,html,dcc,callback,Output,Input
from sklearn.linear_model import LinearRegression
import plotly.express as px
data =pd.read_csv("regression.csv")
model =LinearRegression()
print(data)
app = Dash()

# Requires Dash 2.17.0 or later
app.layout = [
    html.H1(children='Our regression Model', style={'textAlign':'center'}),
    dcc.Dropdown(data.Year.unique(), '2004', id='dropdown-selection'),
    dcc.Graph(id='graph-content')
]

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def  scatter_graph(value):
    selected =data[data.Year==value]
    return px.scatter(selected,x='x',y='y')
@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def  Regression_graph(value):
    selected =data[data.Year==value]
    X =selected['x'].values
    X =X.reshape(-1,1)
    y =selected['y'].values
    model.fit(X,y)
    y_predicted =model.predict(X)
    return px.line(selected,x='x',y=y_predicted)

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

这部分工作正常:

@callback(
    Output('graph-content', 'figure'),
    Input('dropdown-selection', 'value')
)
def  scatter_graph(value):
    selected =data[data.Year==value]
    return px.scatter(selected,x='x',y='y')

但是回归图的第二个装饰器不起作用,下面是示例: 在此处输入图片描述

请帮我解决该如何解决?

python
  • 1 个回答
  • 33 Views
Martin Hope
egg-kun
Asked: 2025-04-28 07:55:54 +0800 CST

我为一项作业编写了一些内联代码,我想知道使用或不使用它会更有效率吗?

  • 5

作业的目标是初始化一个名为rand_array的空列表,然后用 10 个唯一的随机数填充它

我按照老师的指示正常完成了作业:

import random

rand_array = []
while len(rand_array) != 10:
    lmnt = random.randint(1, 15)
    if lmnt not in rand_array:
        rand_array.append(lmnt)

print(rand_array)

后来我将其修改为内联,以提高效率,因为我的老师不喜欢我使用内联:

import random

rand_array = []
while len(rand_array) < 10:
    lmnt = random.randint(1, 15)
    rand_array.append(lmnt) if lmnt not in rand_array else None

我开始怀疑这是否真的更高效,如果去掉初始化空列表的要求,是否还能让它变得更好。所以,主要的问题是:“第二个版本比第一个版本更高效吗?”以及“我能让第二个版本更高效吗?”

此外,在有人说“这只是一项小任务,没关系”之前,如果我将来使用大量内联代码,我需要知道我使用它的方式是否比非内联代码更有效。

如果我输入的内容不准确,我提前表示歉意。

python
  • 2 个回答
  • 96 Views
Martin Hope
iiRosie1
Asked: 2025-04-28 07:15:05 +0800 CST

Flipbook 仅在检查元素模式和移动设备上运行,但不在笔记本电脑上运行

  • 5

我想编写一个交互式翻页书来展示我的杂志设计,但这个翻页书只有在我进入“检查元素”模式或在移动设备上打开我的网站时才能正常工作。我是一名编程新手,使用了 turn.js 来实现翻页效果。

这是我的网页的 JS 代码

// Load navbar and footer into every page
document.addEventListener("DOMContentLoaded", () => {
    // Load the navbar
    fetch("navbar.html")
        .then((res) => res.text())
        .then((data) => {
            document.getElementById("navbar").innerHTML = data;
        });

    // Load the footer
    fetch("footer.html")
        .then((res) => res.text())
        .then((data) => {
            document.getElementById("footer").innerHTML = data;
        });

    // Wait for the DOM to fully load before initializing Turn.js
    const flipbook = document.querySelector(".flipbook");

    // Ensure the flipbook exists before initializing Turn.js
    if (flipbook) {
        const initializeFlipbook = () => {
            const screenWidth = window.innerWidth;

            // Adjust flipbook size based on screen width
            let flipbookWidth = 800;
            let flipbookHeight = 500; // Default aspect ratio: 16:10

            if (screenWidth <= 768) {
                flipbookWidth = 600;
                flipbookHeight = flipbookWidth * 0.625; // Maintain aspect ratio
            }

            if (screenWidth <= 480) {
                flipbookWidth = 320;
                flipbookHeight = flipbookWidth * 0.625; // Maintain aspect ratio
            }

            // Set the container's dimensions
            const flipbookContainer = document.querySelector(".flipbook-container");
            flipbookContainer.style.width = `${flipbookWidth}px`;
            flipbookContainer.style.height = `${flipbookHeight}px`;

            // Force reflow
            flipbook.offsetHeight;

            // Initialize Turn.js
            $(flipbook).turn({
                width: flipbookWidth,
                height: flipbookHeight,
                autoCenter: true,
                elevation: 50,
                gradients: true,
                when: {
                    turning: function (event, page, view) {
                        console.log("Turning to page:", page);
                    },
                },
            });
        };

        // Initialize the flipbook
        initializeFlipbook();

        // Reinitialize the flipbook on window resize
        window.addEventListener("resize", () => {
            if ($(flipbook).data("turn")) {
                $(flipbook).turn("destroy"); // Destroy the existing flipbook
            }
            initializeFlipbook(); // Reinitialize with new dimensions
        });
    }
    $(flipbook).turn({
        width: flipbookWidth,
        height: flipbookHeight,
        autoCenter: true,
        elevation: 50,
        gradients: true,
        when: {
            turning: function (event, page, view) {
                console.log("Turning to page:", page);
            },
        },
    });
    console.log("Turn.js initialized!");
    
});

如果有帮助的话,这是我的 github 存储库:https://github.com/iiRosie1/portfolio

您可以查看网页,了解它目前是如何损坏的:https://iirosie1.github.io/portfolio/brandmagazine.html

任何帮助都值得感激!

javascript
  • 1 个回答
  • 72 Views
Martin Hope
SneakyTactician2
Asked: 2025-04-28 06:09:56 +0800 CST

Rust 如何重新导出第三方包

  • 6

我正在尝试重新导出第三方板条箱,以便我的库的消费者不必手动添加通过 proc 宏生成的某些代码所需的所有依赖项。

但是,我似乎无法获得编译器要解析的路径,即使我获得了导航到该路径的代码完成。

如何从我自己的包中正确地重新导出第三方包,以便使用我的 proc 宏的包的消费者不必手动添加第三方包来支持生成的代码?

下面是一个简化的示例,它应该与我的问题等同,即使我的真实项目在由我自己的 proc 宏生成的代码中解析此路径时存在问题。

文件结构:

│   Cargo.lock
│   Cargo.toml
│   rust-toolchain.toml
│
├───consumer
│   │   .gitignore
│   │   Cargo.toml
│   │
│   └───src
│           main.rs
│
└───exporter
    │   .gitignore
    │   Cargo.toml
    │
    └───src
            lib.rs

在我的“消费者”板条箱中,我尝试使用板条箱Debug提供的派生宏derive_more。

消费者中的 Main.rs:

#[derive(exporter::reexports::derive_more::Debug)]
pub struct Foo {
    x: u64
}


fn main() {
    println!("Hello, world!");
}

消费者中的 Cargo.toml:

[package]
name = "consumer"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
exporter = { path = "../exporter" }

导出器中的 lib.rs:

pub mod reexports {
    pub use derive_more;
}

出口商中的 Cargo.toml:

[package]
name = "exporter"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
derive_more = { version = "2", features = ["full"] }
rust
  • 1 个回答
  • 52 Views
Martin Hope
JL Peyret
Asked: 2025-04-28 05:26:15 +0800 CST

urlparse/urlsplit 和 urlunparse,Pythonic 方法是什么?

  • 6

背景(但不是仅限 Django 的问题)是 Django 测试服务器不会在其响应和请求 URL 中返回方案或 netloc。

例如,我得到了/foo/bar,并且我希望以 结束http://localhost:8000/foo/bar。

urllib.parse.urlparse (但并没有那么复杂urllib.parse.urlsplit)使得从测试 URL 和我已知的服务器地址收集相关信息变得容易。看起来比必要更复杂的是,通过urllib.parse.urlcompose添加 scheme 和 netloc 来重新组合一个新的 URL ,这个 URL 需要位置参数,但没有文档说明它们是什么,也不支持命名参数。同时,解析函数返回的是不可变的元组……

def urlunparse(components):
    """Put a parsed URL back together again.  This may result in a ..."""

我确实让它工作了,请参阅下面的代码,但它看起来真的很笨拙,围绕我需要首先将解析元组转换为列表,然后在所需的索引位置修改列表的部分。

有没有更 Pythonic 的方式?

示例代码:


from urllib.parse import urlsplit, parse_qs, urlunparse, urlparse, urlencode, ParseResult, SplitResult

server_at_ = "http://localhost:8000"
url_in = "/foo/bar"  # this comes from Django test framework I want to change this to "http://localhost:8000/foo/bar"

from_server = urlparse(server_at_)
print("  scheme and netloc from server:",from_server)


print(f"{url_in=}")
from_urlparse = urlparse(url_in)

print("  missing scheme and netloc:",from_urlparse)

#this works
print("I can rebuild it unchanged :",urlunparse(from_urlparse))

#however, using the modern urlsplit doesnt work (I didn't know about urlunsplit when asking)
try:
    print("using urlsplit", urlunparse(urlsplit(url_in)))
#pragma: no cover pylint: disable=unused-variable
except (Exception,) as e: 
    print("no luck with urlsplit though:", e)


#let's modify the urlparse results to add the scheme and netloc
try:
    from_urlparse.scheme = from_server.scheme
    from_urlparse.netloc = from_server.netloc
    new_url = urlunparse(from_urlparse)
except (Exception,) as e: 
    print("can't modify tuples:", e)


# UGGGH, this works, but is there a better way?
parts = [v for v in from_urlparse]
parts[0] = from_server.scheme
parts[1] = from_server.netloc

print("finally:",urlunparse(parts))

示例输出:

  scheme and netloc from server: ParseResult(scheme='http', netloc='localhost:8000', path='', params='', query='', fragment='')
url_in='/foo/bar'
  missing scheme and netloc: ParseResult(scheme='', netloc='', path='/foo/bar', params='', query='', fragment='')
I can rebuild it unchanged : /foo/bar
no luck with urlsplit though: not enough values to unpack (expected 7, got 6)
can't modify tuples: can't set attribute
finally: http://localhost:8000/foo/bar
python
  • 1 个回答
  • 46 Views
Martin Hope
Volodymyr Yeromin
Asked: 2025-04-28 04:10:08 +0800 CST

PayPal JavaScript SDK:无法在结帐按钮上显示“PP”徽标

  • 5

我正在使用 @paypal/react-paypal-js 包将 PayPal JavaScript SDK 集成到我的 React + TypeScript 应用程序中。我的目标是显示带有“PP”徽标的 PayPal 按钮,如 PayPal 文档中所示:https://developer.paypal.com/sdk/js/reference/#label 预期结果

然而,无论怎样配置,按钮都只显示“PayPal”文字,没有“PP”标志: 实际结果

我试过:

  • 以按钮样式设置标签。
  • 调整按钮样式:布局、颜色、形状和高度。
  • 确保容器具有足够的宽度。
<PayPalButtons
    style={{
        color: 'gold',
        layout: 'horizontal',
        shape: 'pill',
        label: 'paypal',
        tagline: false,
        height: 40,
    }}
    onApprove={onApprove}
    onError={onErrorFunc}
    onCancel={onCancelFunc}
/>
reactjs
  • 1 个回答
  • 56 Views
Martin Hope
Luis Morales Knight
Asked: 2025-04-28 03:53:09 +0800 CST

将单元格连接成文本列表以在 R 中输出

  • 6

我有一张学术课程和专业能力的表格,每门课程都标记为满足特定能力要求。例如:

课程编号 课程名称 能力 1 能力 2
101 简介 十
201 中间的 十
301 先进的 十 十

使用 R Markdown 时,我希望能够提取符合特定能力要求的所有课程列表。首先,我希望看到的输出是:

[拉出能力 1 的列表]
101 入门
301 高级

到目前为止,这是我弄清楚的代码:

compcourses <- function (competency){
                  courselist <- sprintf("%s %s",Table$CourseNumber[which(!is.na(Table[[competency]]))],Table$CourseName[which(!is.na(Table[[competency]]))])
                  return(courselist)
                }

然而,在 R Markdown 文档中:

`r compcourses("Competency 1")'

输出结果如下:

101 入门,301 高级

我不知道这个该死的逗号是从哪里来的,如何抑制它,或者如何获得输出以使每个课程都在自己的单独一行上。

非常感谢任何帮助。

  • 1 个回答
  • 65 Views
Martin Hope
Ajay Satpati
Asked: 2025-04-28 03:31:32 +0800 CST

NoCredentialException:没有可用的凭证

  • 5

我正在尝试在我的 Kotlin Jetpack Compose 中使用 Firebase 添加 Google 登录。但出现了“没有可用凭据”的问题。我想显示 Google 帐户列表,然后选中该帐户,系统会显示登录成功的提示。我尝试了不同的方法,但问题依旧。

            Row(
                horizontalArrangement = Arrangement.Center
            ) {
                val context = LocalContext.current

                // Initialize Credential Manager
                val credentialManager = CredentialManager.create(context)

                // Configure Credential Request
                val request = GetCredentialRequest.Builder()
                    .addCredentialOption(
                        GetGoogleIdOption.Builder()
                            .setServerClientId(context.getString(R.string.default_web_client_id))
                            .setFilterByAuthorizedAccounts(true)
                            .setAutoSelectEnabled(true)
                            .build()
                    )
                    .build()

                var showToast by remember { mutableStateOf(false) }
                var showFailureToast by remember { mutableStateOf(false) }
                // Google Sign-In Icon
                Icon(
                    painter = painterResource(id = R.drawable.google_search_logo),
                    contentDescription = "Google Icon",
                    modifier = Modifier
                        .size(windowWidthFraction(0.075f))
                        .clickable {
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    val response = credentialManager.getCredential(context, request)
                                    val credential = response.credential
                                    if (credential is CustomCredential && credential.type == GoogleIdTokenCredential.TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) {
                                        val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data)
                                        val idToken = googleIdTokenCredential.idToken
                                        val authCredential = GoogleAuthProvider.getCredential(idToken, null)
                                        FirebaseAuth.getInstance().signInWithCredential(authCredential).addOnCompleteListener{ task ->
                                                if (task.isSuccessful) {
                                                    Log.d("SignIn", "Sign-in successful!")
                                                    showToast = true
                                                }
                                            }
                                    }
                                } catch (e: NoCredentialException) {
                                    // Silent sign-in failed, try with user interaction
                                    try {
                                        val interactiveRequest = GetCredentialRequest.Builder()
                                            .addCredentialOption(
                                                GetGoogleIdOption.Builder()
                                                    .setServerClientId(context.getString(R.string.default_web_client_id))
                                                    .setFilterByAuthorizedAccounts(false) // Allow account picker
                                                    .setAutoSelectEnabled(true)
                                                    .build()
                                            )
                                            .build()

                                        val response = credentialManager.getCredential(context, interactiveRequest)
                                        handleGoogleCredential(response.credential) {
                                            showToast = true
                                        }

                                    } catch (ex: Exception) {
                                        Log.e("SignIn", "Interactive sign-in failed", ex)
                                        showFailureToast = true
                                    }
                                } catch (e: Exception) {
                                    Log.e("SignIn", "Unexpected error during sign-in", e)
                                    showFailureToast = true
                                }
                            }
                        },
                    tint = Color.Unspecified
                )
             }
  • 1 个回答
  • 52 Views
Martin Hope
user7289922
Asked: 2025-04-28 03:22:25 +0800 CST

无法在 Google Cloud Run 中查看 Firebase 数据库的日志来发送推送通知

  • 5

我正在尝试使用 Firebase 日志。我能够将新记录添加到我的 Firebase 实时数据库Chat实体中。
问题是,我在 Google Cloud Log Explorer 中浏览它们时看不到任何日志或错误。

我使用以下命令从我的文件夹成功提交:

 gcloud builds submit --tag gcr.io/relay-world/realtime-database-handler .

我按照建议迁移到工件注册表,并创建了以下文件夹:

  • asia.gcr.io

  • cloud-run-source-deploy

  • eu.gcr.io

  • gcf-artifacts

  • gcr.io

  • us.gcr.io

如果我打开gcr.io文件夹,就会看到 realtime-database-handler里面的内容。我的目标是向用户的设备发送推送通知,但目前我只想记录数据。代码如下:

const admin = require("firebase-admin");
const { PubSub } = require("@google-cloud/pubsub");

console.log("BEFORE APP INIT");

// Initialize Firebase Admin SDK
admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: "https://relay-world.firebaseio.com", // Replace with your database URL
});

// Initialize Pub/Sub
const pubsub = new PubSub();
const topicName = "realtime-database-chat-topic";

// Reference the Realtime Database path
const db = admin.database();
const ref = db.ref("Chat");

console.log("Listening for Realtime Database changes...");

// Listen for new children added to the collection
ref.on("child_added", async (snapshot) => {
  const newValue = snapshot.val();
  const childId = snapshot.key;

  console.log(`New child added: ${childId}`, newValue);

  // Publish a message to the Pub/Sub topic
  const message = {
    data: {
      id: childId,
      ...newValue,
    },
  };

  try {
    const messageId = await pubsub.topic(topicName).publishMessage({
      json: message,
    });
    console.log(`Message published with ID: ${messageId}`);
  } catch (error) {
    console.error("Error publishing message:", error);
  }
});

你知道问题可能出在哪里吗?非常感谢!

  • 1 个回答
  • 24 Views
Martin Hope
learnerbmb
Asked: 2025-04-28 03:21:05 +0800 CST

Postgres sql外部约束删除限制更新级联

  • 5

有 2 个表“用户”和“地址”。

create table address (
        username varchar(255) not null,
        address1 varchar(255),
        primary key (username)
    )

和

    create table users (
        user_id varchar(255) not null,
        username varchar(255) not null,
        address varchar(255) not null,
        primary key (user_id)
    )

“用户”表有几列,包括一个名为“地址”的列,这个“用户”表被修改为

1. alter table if exists users add constraint uk_users_username unique (username)
2. alter TABLE users ADD CONSTRAINT fk_user_address FOREIGN KEY(address) REFERENCES address(username) ON DELETE RESTRICT ON UPDATE CASCADE

(只是试图建立“用户”到“地址”的一对一单向关系)

现在,正如预期的那样,当我在“users”表中添加一条有效记录时,它会自动在“address”表中添加一条记录。此外,当我使用以下 DELETE sql 之一时

1. delete from users where user_id = 'some_user_id';
2. delete from users where username = 'some_user_name';

它会按照预期从“用户”表中删除记录;但不会删除“地址”中的相关记录。

问题:它不应该抱怨“用户”表对“地址”有约束,并且直到“地址”中的相关记录也被删除之前,这个“用户”不能被删除(因为我们有...ON DELETE RESTRICT ON UPDATE CASCADE)?

提前致谢!!

hibernate
  • 1 个回答
  • 39 Views
上一页
下一页

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

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

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve