小编Ist*_*van的帖子

导入Python库并在它们不可用时进行优雅处理

我想导入一堆库并捕获异常.

如果我只有1个尝试catch块,我会得到1个异常(第一个).是否存在迭代所有库的模式,并且每个缺少的lib都有一个单独的例外?

#!/usr/bin/env python

try: import sys
except: print sys.exc_info()
try: import numpy as np
except: print sys.exc_info()
try: import scipy as sp
except: print sys.exc_info()
try: import os as os
except: print sys.exc_info()
try: from operator import itemgetter
except: print sys.exc_info()
try: import socket
except: print sys.exc_info()
try: import logging
except: print sys.exc_info()
try: from time import gmtime, strftime
except: print sys.exc_info()
Run Code Online (Sandbox Code Playgroud)

python exception-handling egg setup.py

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

等待Clojure异步通道的惯用方法是什么?

这是代码的当前版本,它可以完成非常简单的工作.它启动10个例程,每个例程向通道添加10条消息.另一端是一个真正的循环,读取通道并每500毫秒超时.

我在想有更好的东西.我认为while true循环可以替换为recur,其中它读取通道,并且在每次成功读取之后它会再次读取它.如果发生超时,它只会终止执行.

我有两个问题: - 这是正确的方法吗? - 如何使用惯用的Clojure实现它

(defn -main [& args]
  (let [c (async/chan)]
    (doseq [i (range 10)]
      (async/go
        (doseq [j (range 10)]
          (Thread/sleep (rand-int 1000))
          (async/>! c (str i " :: " j)))))
    (while  true
    (async/<!!
      (async/go
        (let [[result source] (async/alts! [c (async/timeout 500)])]
          (if (= source c)
            (println "Got a value!" result)
            (println "Timeout!"))))))))
Run Code Online (Sandbox Code Playgroud)

clojure core.async

5
推荐指数
1
解决办法
1984
查看次数

有没有办法以编程方式列出AWS服务的每个操作的所有可用操作?

我正在寻找一种方法来列出可以在AWS IAM策略中使用的所有操作.

这是使用IAM操作的示例策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1457442845000",
            "Effect": "Allow",
            "Action": [
                "iam:CreatePolicy",
                "iam:CreatePolicyVersion",
                "iam:GetGroupPolicy",
                "iam:CreateGroup",
                "iam:GetPolicy",
                "iam:GetPolicyVersion",
                "iam:GetRolePolicy",
                "iam:ListAttachedGroupPolicies"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我想搜索文件中的操作,为此我想拥有所有可用的操作.我找不到一种方法来获得该列表.任何方向表示赞赏.

amazon-web-services amazon-iam

5
推荐指数
3
解决办法
430
查看次数

如何在Python中从S3读取Avro文件?

我有一堆 Avro 文件,我想从 S3 中逐个读取它们。我以字节形式读取文件没有问题,但我想知道之后如何迭代整个文件。当前代码:

conn = boto.s3.connect_to_region("us-east-1")
my_bucket=boto.s3.bucket.Bucket(conn, "my_bucket")
my_key = my_bucket.get_key("folder/file.avro")
raw_bytes = my_key.read()

test_schema = '''
{
  "namespace": "com.company",
  "type": "record",
  "name": "MimeMessage_v2",
  "fields": [
    {
      "name": "record_timestamp",
      "type": "long"
    },
    {
      "name": "contents",
      "type": "bytes"
    }
  ],
  "message_id": 2
}
'''
schema = avro.schema.Parse(test_schema)
#this is the problematic section
dreader = DatumReader(schema, schema)
v = dreader.read(raw_bytes)
Run Code Online (Sandbox Code Playgroud)

我想知道如何正确读取包含 Avro 文件字节的变量。

python amazon-s3 avro

5
推荐指数
1
解决办法
6418
查看次数

有没有办法在Bokeh中使用基于文本的X值?

我试图用Bokeh绘制一个简单的图表但是当x值是基于文本时它无法显示任何内容:

x=['-', 'AF', 'AS', 'EU', 'NA', 'OC', 'SA']
y=[8, 7621750, 33785311, 31486697, 38006434, 7312002, 7284879]
p = figure(plot_width=480, plot_height=300,title='test')
p.vbar(x=x, width=0.5, bottom=0, top=y, color="navy", alpha=0.5)
p.toolbar.logo = None
p.toolbar_location = None
v = gridplot([[p]])
show(v)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我想知道这是不是一个bug.版本:0.13.0

应用建议的修复后,它可以工作:

for i in range(4):
    ind=i+offset
    rez[ind].sort(key=lambda tup: tup[0])
    x = [x[0] for x in rez[ind]]
    y = [x[1] for x in rez[ind]]
    if type(x[0]) == str:
        charts[i] = figure(
            plot_width=480, 
            plot_height=300,
            title=columns_being_investigated[ind],
            x_range=x)
    else:
        charts[i] = figure(
            plot_width=480, 
            plot_height=300,
            title=columns_being_investigated[ind])
    charts[i].vbar(x=x, width=0.5, bottom=0, …
Run Code Online (Sandbox Code Playgroud)

python bokeh

5
推荐指数
1
解决办法
125
查看次数

Dotnet list-sdks 未列出已安装的 SDK

我使用的是 Mac,新的 .NET 5.0 刚刚发布。我已经用 dotnet-install.sh 安装了它

dotnet-install.sh --version 5.0.100

dotnet-install: Note that the intended use of this script is for Continuous Integration (CI) scenarios, where:
dotnet-install: - The SDK needs to be installed without user interaction and without admin rights.
dotnet-install: - The SDK installation doesn't need to persist across multiple CI runs.
dotnet-install: To set up a development environment or to run apps, use installers rather than this script. Visit https://dotnet.microsoft.com/download to get the installer.

dotnet-install: .NET Core …
Run Code Online (Sandbox Code Playgroud)

macos .net-5

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

如何配置 FastAPI 日志记录,使其在本地和生产中都能与 Uvicorn 一起使用?

我有一个 api.py 文件,其中包含以下内容:

from fastapi import FastAPI
import logging
import uvicorn

app = FastAPI(title="api")

LOG = logging.getLogger(__name__)
LOG.info("API is starting up")
LOG.info(uvicorn.Config.asgi_version)

@app.get("/")
async def get_index():
    LOG.info("GET /"
    return {"Hello": "Api"}

Run Code Online (Sandbox Code Playgroud)

该应用程序在本地运行:

uvicorn api:app --reload
Run Code Online (Sandbox Code Playgroud)
INFO:     Will watch for changes in these directories: ['/Users/user/code/backend/api']
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [44258] using StatReload
INFO:     Started server process [44260]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
Run Code Online (Sandbox Code Playgroud)

它不记录任何启动消息。

稍后向 api 发送 http 请求时: …

python logging fastapi

5
推荐指数
1
解决办法
9345
查看次数

在Elixir中生成数字流的惯用方法是什么?

目前我有以下使用生成器:

(for i <- 999..100, j <- i..100, into: [], do:  i * j)
|> Stream.filter(&(palindromic?(&1)))
|> Enum.sort
|> List.last
Run Code Online (Sandbox Code Playgroud)

有没有办法生成产品流?

streaming generator elixir

4
推荐指数
1
解决办法
95
查看次数

在OCaml中定义多个arity函数的正确方法是什么?

我试图在OCaml中实现一个简单的范围函数,我想知道如何为不同的arity调用做到这一点.

let range_aux ~start  ~stop  ~step  =
  let rec aux start stop step acc =
    match (start, stop, step, acc) with
    | (start,stop,step,acc) when start = stop -> List.rev acc
    | (start,stop,step,acc) -> aux (start + step) stop step (start :: acc) in
  aux start stop step []

let range ~start ~stop  ~step  = range_aux ~start ~stop ~step
let range ~stop  ~step  = range_aux ~start:0 ~stop ~step
let range ~stop  = range_aux ~start:0 ~stop ~step:1
Run Code Online (Sandbox Code Playgroud)

这显然不适用于最后一个定义胜利.有没有办法定义多个arity函数?

ocaml

4
推荐指数
1
解决办法
139
查看次数

如何将 http::HeaderMap 序列化为 JSON?

http::HeaderMap在 Rust 中将HTTP 请求标头 ( )序列化为 JSON的正确方法是什么?

我正在实现一个 AWS Lambda 函数,我想要一个简单的回声函数来进行调试。

use lambda_http::{lambda, IntoResponse, Request};
use lambda_runtime::{error::HandlerError, Context};
use log::{self, info};
use simple_logger;
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    simple_logger::init_with_level(log::Level::Debug)?;
    info!("Starting up...");
    lambda!(handler);

    return Ok(());
}

fn handler(req: Request, ctx: Context) -> Result<impl IntoResponse, HandlerError> {
    Ok(format!("{}", req.headers()).into_response())
}
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法可以转换req.headers()为 JSON 并返回?

http rust

4
推荐指数
1
解决办法
435
查看次数