2024-08-17

Akshare 是一个提供快速、便捷、统一的接口来获取全球金融数据的 Python 库。以下是使用 Akshare 获取股票数据的示例代码:




import akshare as ak
import pandas as pd
 
# 获取股票数据
df_stock_day = ak.stock_zh_a_hist(symbol="sh600000", period="daily", start_date="20200101", end_date="20201231", adjust="hfq")
 
# 查看数据
print(df_stock_day)

在这个例子中,我们使用 ak.stock_zh_a_hist 函数获取上证指数(sh600000 代表上证指数)在2020年全年的日线数据(按日获取开盘价、收盘价、最高价、最低价、成交量和总金额)。period="daily" 表示获取日k线数据,start_dateend_date 设置数据获取的时间范围,adjust="hfq" 表示使用后复权的价格。

Akshare 提供的接口简洁易懂,返回的数据格式为 Pandas DataFrame,方便进一步的数据处理和分析。

2024-08-17



import numpy as np
 
# 创建一个形状为(3, 4)的零数组
zeros_array = np.zeros((3, 4))
print("形状为(3, 4)的零数组:")
print(zeros_array)
 
# 创建一个形状为(3, 4)的浮点型零数组
zeros_float_array = np.zeros((3, 4), dtype=np.float64)
print("\n形状为(3, 4)的浮点型零数组:")
print(zeros_float_array)
 
# 创建一个形状为(6,)的零向量
zeros_vector = np.zeros(6)
print("\n形状为(6,)的零向量:")
print(zeros_vector)
 
# 创建一个形状为(3, 4, 2)的多维零数组
zeros_multi_array = np.zeros((3, 4, 2))
print("\n形状为(3, 4, 2)的多维零数组:")
print(zeros_multi_array)

这段代码演示了如何使用np.zeros函数创建形状不同的零数组,包括二维、一维和多维数组,并可以指定数据类型。这对于初始化需要填充零值的数组是非常有用的。

2024-08-17

解释:

这个问题通常意味着在Anaconda新建的环境中没有安装notebook包,或者环境没有被正确设置为Kernel。

解决方法:

  1. 确认环境已经被创建。
  2. 激活新建的环境:

    
    
    
    conda activate 你的环境名
  3. 在激活的环境中安装notebook

    
    
    
    conda install notebook
  4. 安装ipykernel包,这样可以将环境加入到Jupyter的可用kernel列表中:

    
    
    
    conda install ipykernel
  5. 将新环境添加到Jupyter的kernel中:

    
    
    
    python -m ipykernel install --user --name 你的环境名 --display-name "Python (你的环境名)"
  6. 启动Jupyter notebook:

    
    
    
    jupyter notebook
  7. 在Jupyter页面上,新建一个Notebook,检查是否可以选择刚才创建的环境。

如果按照以上步骤操作后仍然无法在Notebook中看到新环境的Python选项,可能需要重启Jupyter服务或者检查是否有其他的错误信息提示。

2024-08-17

MQTT (Message Queuing Telemetry Transport) 是一种轻量级的消息协议,常用于物联网设备之间的通信。以下是针对不同编程语言的MQTT客户端库的简单介绍和链接:

  1. C语言:
  1. C++:
  1. Java:
  1. C#:
  1. Python:

注意:以上链接为官方或主要的开源库,还有其他的实现,例如Eclipse的Paho项目就包含了多个不同语言的MQTT客户端库。在选择时,可以考虑使用更加简洁的库,或者根据项目需求和社区支持情况来选择合适的库。

2024-08-17



import os
import shutil
 
def copy_and_move_files(source_folder, target_folder, copy_files, move_files):
    """
    将文件从source_folder复制到target_folder,然后移动指定文件。
    
    参数:
    source_folder -- 包含文件的源文件夹路径
    target_folder -- 文件将被复制到的目标文件夹路径
    copy_files -- 需要复制的文件名列表
    move_files -- 需要移动的文件名列表
    """
    # 创建目标文件夹,如果它不存在
    os.makedirs(target_folder, exist_ok=True)
    
    # 复制文件
    for file in copy_files:
        src = os.path.join(source_folder, file)
        dst = os.path.join(target_folder, file)
        shutil.copy2(src, dst)  # 使用shutil.copy2保留元数据
        print(f"Copied: {file}")
    
    # 移动文件
    for file in move_files:
        src = os.path.join(source_folder, file)
        dst = os.path.join(target_folder, file)
        shutil.move(src, dst)
        print(f"Moved: {file}")
 
# 使用示例
source_folder = '/path/to/source'
target_folder = '/path/to/target'
copy_files = ['file1.txt', 'file2.jpg']
move_files = ['file3.txt', 'file4.jpg']
 
copy_and_move_files(source_folder, target_folder, copy_files, move_files)

这段代码定义了一个函数copy_and_move_files,它接受源文件夹、目标文件夹以及需要复制和移动的文件名列表作为参数。函数将首先复制指定的文件,然后移动它们到新的位置。在复制和移动操作后,它打印出操作的结果。这个函数可以用于自动化文件管理任务。

2024-08-17



{
    "python.pythonPath": "D:/Python38/python.exe",
    "jupyter.jupyterServerType": "local",
    "jupyter.notebookFileRoot": "D:/JupyterProjects",
    "python.dataScience.notebookFile": "*.ipynb",
    "python.dataScience.jupyterServerURI": "http://localhost:8888/",
    "workbench.startupEditor": "newUntitledFile",
    "workbench.colorTheme": "Default Dark+",
    "[jsonc]": {
        "editor.defaultFormatter": "vscode.json-language-features"
    },
    "editor.formatOnSave": true,
    "editor.suggestSelection": "first",
    "vsintellicode.modifySettingsJson": true,
    "[python]": {
        "editor.defaultFormatter": "ms-python.python"
    },
    "python.analysis.diagnosticSeverityOverrides": {
        "reportMissingImports": "none"
    },
    "python.autoComplete.addBrackets": true,
    "python.autoComplete.extraPaths": [
        "D:/Python38/Lib",
        "D:/Python38/Lib/site-packages",
        "D:/Python38/DLLs",
        "D:/Python38/Lib/lib-tk",
        "D:/Python38/Lib/lib-dynload"
    ],
    "python.autoComplete.preloadModules": [
        "numpy",
        "pandas",
        "matplotlib",
        "scipy",
        "statsmodels",
        "sklearn"
    ],
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": false,
    "python.linting.flake8Enabled": true,
    "python.linting.flake8Args": [
        "--max-line-length=248"
    ],
    "python.linting.pycodestyleEnabled": false,
    "python.linting.pydocstyleEnabled": false,
    "python.linting.mypyEnabled": true,
    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        "--style",
        "{based_on_style: google, column_limit: 248}"
    ],
    "python.linting.pylintUseMinimalCheckers": true,
    "python.linting.enabled": true,
    "python.linting.flake8Enabled": true,
    "python.linting.pylintEnabled": false,
    "python.linting.mypyEnabled": true,
    "python.linting.pylintPath": "D:/Python38/Scripts/pylint.exe",
    "python.linting.flake8Path": "D:/Python38/Scripts/flake8.exe",
    "python.linting.mypyPath": "D:/Python38/Scripts/mypy.exe",
    "python.linting.pylintArgs": [
        "--load-plugins",
        "pylint_django",
        "--errors-only"
    ],
    "python.dataScience.jupyterServerURI": "http://localhost:8888/",
    "python.dataScience.notebookFile": "*.ipynb",
    "python.dataScience.changeDirOnEnte
2024-08-17



$(document).ready(function() {
    // 表单提交事件
    $('form').on('submit', function(e) {
        e.preventDefault(); // 阻止表单默认提交行为
 
        // 清除之前的错误提示
        $('.form-group').removeClass('has-error');
        $('.help-block').empty();
 
        // 检查用户名和密码
        var username = $('#username').val();
        var password = $('#password').val();
 
        if (username.trim() === '') {
            $('#username-group').addClass('has-error');
            $('#username-help').text('用户名不能为空');
        }
        if (password.trim() === '') {
            $('#password-group').addClass('has-error');
            $('#password-help').text('密码不能为空');
        }
 
        // 如果没有错误,则允许提交
        if ($('.form-group.has-error').length === 0) {
            $(this).off('submit').submit(); // 移除事件监听并允许提交
        }
    });
});

这段代码在表单提交时阻止默认行为,并检查用户名和密码是否为空。如果为空,则向对应的表单组添加错误类并显示错误信息;只有当没有错误时,才允许表单提交。

2024-08-17



import cv2
import numpy as np
 
# 读取相机参数和ArUco标志参数
camera_matrix = np.load('camera_matrix.npy')  # 相机内参矩阵
dist_coeffs = np.load('dist_coeffs.npy')      # 相机畸变系数
markerLength = 100                             # ArUco标志的边长(单位:mm)
 
# 初始化视频捕捉
cap = cv2.VideoCapture(0)
 
while(True):
    # 读取一帧图像
    ret, frame = cap.read()
    if not ret:
        print("Failed to grab frame")
        break
 
    # 检测ArUco标志并返回其角点
    corners, ids, _ = cv2.detectMarkers(frame, cv2.aruco.Dictionary_get(cv2.aruco.DICT_6X6_250), 
                                         parameters=cv2.aruco.DetectorParameters_create())
    if np.all(corners != None):
        rvec, tvec = cv2.estimatePoseSingleMarkers(corners, markerLength, camera_matrix, dist_coeffs)
 
        # 绘制标志和相机姿态
        frame = cv2.aruco.drawDetectedMarkers(frame, corners)
        frame = cv2.aruco.drawAxis(frame, camera_matrix, dist_coeffs, rvec, tvec, 10)
 
    # 显示图像
    cv2.imshow('ARuco Marker Detection', frame)
 
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
 
# 释放视频捕捉和关闭所有窗口
cap.release()
cv2.destroyAllWindows()

这段代码使用OpenCV库读取视频流,检测图像中的ArUco标志,估计每个标志的相对姿态,并绘制坐标轴以展示标志的方向和位置。代码中需要提供相机内参矩阵和相机畸变系数文件,这些可以通过标定过程获得。

2024-08-17

首先,确保你已经安装了Node.js环境。

  1. 通过npm安装gRPC库和protocol buffer编译器:



npm install @grpc/grpc-js google-protobuf
  1. 创建.proto文件定义gRPC服务:



// helloworld.proto
syntax = "proto3";
 
package helloworld;
 
// 定义服务
service Greeter {
  // 定义rpc方法
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
 
// 请求消息
message HelloRequest {
  string name = 1;
}
 
// 响应消息
message HelloReply {
  string message = 1;
}
  1. 使用protocol buffer编译器生成gRPC客户端和服务端存根代码:



npm install -g protoc
protoc --js_out=import_style=commonjs,binary:. --grpc-web_out=import_style=commonjs,mode=grpcwebtext:. helloworld.proto

上述命令会生成helloworld_pb.jshelloworld_grpc_web_pb.js两个文件。

  1. 创建gRPC客户端调用服务端:



const grpc = require('@grpc/grpc-js');
 
// 导入生成的protobuf定义
const proto = require('./helloworld_pb');
const service = require('./helloworld_grpc_web_pb');
 
// 定义gRPC服务器地址和端口
const host = 'localhost:50051';
 
// 创建gRPC通道
const channel = grpc.credentials.createInsecure();
const client = new service.GreeterClient(host, channel);
 
// 创建请求消息
const request = new proto.HelloRequest();
request.setName('World');
 
// 调用rpc方法
client.sayHello(request, {}, (err, response) => {
  if (err) {
    console.error(err);
  } else {
    console.log(response.getMessage());
  }
});

确保你的gRPC服务器在本地运行并监听50051端口。这个例子展示了如何在node.js中创建一个gRPC客户端,并向服务器发送请求。