小编Jey*_*eyJ的帖子

找到最长的序列长度,其总和可以被3整除

我有一个需要用O(n)时间复杂度完成的练习,但是,我只能用O(n ^ 2)解决方案解决它.

你有一个数组,你需要计算最长的连续序列,使得它的总和可以被分成3而没有任何余数.例如array {1,2,3,-4,-1),函数将返回4,因为它sum(0)可以被分成的最长序列3是{2,3,-4,-1}.

我的解决方案O(n ^ 2)基于arithmetic progression.有没有办法用O(n)复杂度做到这一点?

拜托,我只想要一个线索或理论解释.请不要写完整的解决方案:)

algorithm math recursion time-complexity

17
推荐指数
1
解决办法
2231
查看次数

aws s3 sdk 返回“您尝试创建的存储桶数量超出了允许的数量”

我在代码中使用 aws s3 SDK。在我的测试中,我尝试为测试创建/删除存储桶。

我的sdk版本是1.11.800:

<aws-s3-sdk.version>1.11.800</aws-s3-sdk.version>
<aws-java-sdk-core.version>1.11.800</aws-java-sdk-core.version>
Run Code Online (Sandbox Code Playgroud)

创建的代码与 aws 示例中的代码完全相同:

 public void createBucket(String bucketName){
        try {
            if (!s3Client.doesBucketExistV2(bucketName)) {
                // Because the CreateBucketRequest object doesn't specify a region, the
                // bucket is created in the region specified in the client.
                s3Client.createBucket(new CreateBucketRequest(bucketName));

                // Verify that the bucket was created by retrieving it and checking its location.
                String bucketLocation = s3Client.getBucketLocation(new GetBucketLocationRequest(bucketName));
                System.out.println("Bucket location: " + bucketLocation);
            }
        } catch (AmazonServiceException e) {
            // The call was transmitted successfully, but Amazon …
Run Code Online (Sandbox Code Playgroud)

java amazon-s3 amazon-web-services

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

如何从AWS lambda授权者返回401而不引发异常

我有一个用 Python 编写的 lambda 授权方。

我知道通过以下访问策略我可以返回 200/403 :

{
        "principalId": "yyyyyyyy",
        "policyDocument": {
            "Version": "2012-10-17",
            "Statement": [
                {
                    "Action": "execute-api:Invoke",
                    "Effect": "Deny",
                    "Resource": "*"
                }
            ]
        },
        "context": {
            "stringKey": "value",
            "numberKey": "1",
            "booleanKey": "true"
        },
        "usageIdentifierKey": "{api-key}"
    }
Run Code Online (Sandbox Code Playgroud)

如果客户没有发送任何令牌,我会尝试返回 401 错误,因此我提出了一个异常:

raise Exception("Unauthorized")
Run Code Online (Sandbox Code Playgroud)

此解决方案的问题在于,AWS lambda 失败,然后执行被标记为执行失败,而不是 lambda 的成功执行。有没有办法在 lambda 失败的情况下返回 401 ?

还尝试了以下类似 lambda 集成的方法,但没有成功:

return  {"statusCode": 401, "body" : "Unauthorized"}
Run Code Online (Sandbox Code Playgroud)

python amazon-web-services aws-lambda

12
推荐指数
1
解决办法
8710
查看次数

FastAPI 通过 TestClient 在 get 请求中传递 json

我正在尝试测试我用 Fastapi 编写的 api。我的路由器中有以下方法:

@app.get('/webrecord/check_if_object_exist')
async def check_if_object_exist(payload: WebRecord) -> bool:
    key = get_key_of_obj(payload.data) if payload.key is None else payload.key
    return await check_if_key_exist(key)
Run Code Online (Sandbox Code Playgroud)

以及我的测试文件中的以下测试:

client = TestClient(app)
class ServiceTest(unittest.TestCase):
.....
    def test_check_if_object_is_exist(self):
        webrecord_json = {'a':1}
        response = client.get("/webrecord/check_if_object_exist", json=webrecord_json)
        assert response.status_code == 200
        assert response.json(), "webrecord should already be in db, expected : True, got : {}".format(response.json())
Run Code Online (Sandbox Code Playgroud)

当我在调试中运行代码时,我意识到未到达 get 方法内的断点。当我更改发布请求的类型时,一切正常。

我究竟做错了什么?

python fastapi

8
推荐指数
1
解决办法
8161
查看次数

构建没有主文件的 Go 模块

我有一个小模块,其中包含一些共享代码。该模块如下所示:

\n
Shared\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.mod\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.sum\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 logging\n\xe2\x94\x82   \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 logger.go\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 db-utils\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 db.go\n
Run Code Online (Sandbox Code Playgroud)\n

如果我尝试从目录内部构建共享模块,我会收到一条错误消息,指出该模块下没有可用的 go 文件。

\n
bash-3.2$ go build .\nno Go files in /Users/xxxx/go/src/Shared\n
Run Code Online (Sandbox Code Playgroud)\n

有没有办法构建一个内部只有包而没有 main.go 文件的 Go 模块?这里的动机是在无法访问互联网或私人存储库的其他 go 模块中使用这些包来检索包。

\n

go go-modules

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

SpringBoot没有主清单属性(Maven)

运行我的jar文件时:java -jar target / places-1.0-SNAPSHOT.jar我遇到下一个错误:

no main manifest attribute, in target/places-1.0-SNAPSHOT.jar
Run Code Online (Sandbox Code Playgroud)

我的pom.xml包含spring-boot-maven-plugin:

 <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <mainClass>com.places.Main</mainClass>
            </configuration>
 </plugin>
Run Code Online (Sandbox Code Playgroud)

我也试图创建一个MANIFEST.MF文件并指定该类,但是它没有帮助。

另外,我还尝试了:

<properties>
      <!-- The main class to start by executing "java -jar" -->
      <start-class>com.places.Main</start-class>
</properties>
Run Code Online (Sandbox Code Playgroud)

我的主要:

@SpringBootApplication
 public class Main {
public static void main(String[] args) throws InterruptedException {
    SpringApplication.run(Main.class,args);
  }
  }
Run Code Online (Sandbox Code Playgroud)

你知道我还能尝试什么吗?

java manifest maven spring-boot spring-boot-maven-plugin

7
推荐指数
4
解决办法
5680
查看次数

在不加载 Spring 上下文的情况下测试 @ConfigurationProperties 注解

我正在尝试测试一个具有注释@ConfigurationProperties但不加载整个 Spring 上下文的类。我尝试仅使用 JUnit5 的功能来做到这一点,但到目前为止还没有成功。

我正在使用spring-boot-starter-parentv2.6.2 。

我正在测试的课程:

@ConfigurationProperties("db.mongo")
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class MongoProperties {
    private String host;
    private String db;
    private String user;
    private String password;
}
Run Code Online (Sandbox Code Playgroud)

application.yaml:

db:
  mongo:
    host: localhost
    db: test
    user: test-user
    password: secret
Run Code Online (Sandbox Code Playgroud)

我的测试课:

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties({MongoProperties.class})
public class MongoPropertiesTest {

    @Autowired
    private  MongoProperties properties;

    @Test
    public void mongoPropertiesLoadedTest(){
        assertNotNull(properties.getDb());
        assertNotNull(properties.getHost());
        assertNotNull(properties.getPassword());
        assertNotNull(properties.getUser());
    }
}
Run Code Online (Sandbox Code Playgroud)

beanMongoProperties注入成功,但是里面的所有值都是 null 并且断言失败。

添加@SpringBootTest解决了 bean 实例中空值的问题,但它也启动了整个 spring 上下文,这是我不想要的。

java spring spring-test spring-boot junit5

7
推荐指数
1
解决办法
5488
查看次数

输入字符串的格式不正确 - 使用了错误的上下文

将 ASP.NET Core Identity 更改为使用int而不是 GUID(根据此博客文章)后,我收到以下错误:

ArgumentException: 395438ed-1cd9-4420-8a58-3f3b1f550bfc 不是 Int32 的有效值。参数名称:值 System.ComponentModel.BaseNumberConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) Microsoft.AspNetCore.Identity.UserStoreBase.ConvertIdFromString(string id) Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore.FindByIdAsync(string userId, CancellationToken) cancelToken) Microsoft.AspNetCore.Identity.UserManager.FindByIdAsync(string userId) Microsoft.AspNetCore.Identity.UserManager.GetUserAsync(ClaimsPrincipal principal) Microsoft.AspNetCore.Identity.SignInManager.ValidateSecurityStampAsync(ClaimsPrincipalPrincipal) Microsoft.AspNetCore.Identity.SecurityStampValidAsyncator (CookieValidatePrincipalContext 上下文)Microsoft.AspNetCore.Authentication。

尝试查询数据库时。关于为什么会这样的任何线索?

.net c# asp.net-core

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

如果 HTTP 响应为 401,则 Angular 重定向页面

我在 Angular (10) 应用程序中发送多个 API 请求。如果其中一个请求返回状态为 401 的响应,我想将页面重定向到我的登录页面(从组件页面)。

我有一个负责 API 调用的服务,它有以下 2 种方法:

    export class ApiService {
    constructor(private http: HttpClient){
}
      public get<T>(path: string, params: HttpParams = new HttpParams(), headers: HttpHeaders = new HttpHeaders()): Observable<T> {
        return this.getBodyOfResponseOrRedirect(
          this.http.get<T>(path, {headers, params, observe: 'response'}));
      }
    
      private getBodyOfResponseOrRedirect<T>(responseObservable: Observable<HttpResponse<T>>): Observable<T> {
        return responseObservable.pipe(map(response => {
          if (response.status === 401) {
            window.location.href = 'https://custom-url';
          } else {
            return response.body;
          }
        }));
      }
Run Code Online (Sandbox Code Playgroud)

现在我尝试在另一个服务中使用API​​服务方法:

 export class ShopDataService{
  ...
  getShopsData(): Observable<Shop[]> {
    return this.apiService.get<Shop[]>("https://shops.com/v1/endpoint)
      .pipe( …
Run Code Online (Sandbox Code Playgroud)

angular

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

使用 Redis 作为键值存储

我正在测试 Redis 是否可以成为键值存储的良好解决方案。就我而言,租户的用户可以在我们的系统中保存键值对。数据如下所示:

{
"user" : "x1",
"tenant" : "y1",
"key": "key1",
"value": "value1",
"last_updated": "xxx-xx-xxx"
"another-metadata-field": "ddd"
}
Run Code Online (Sandbox Code Playgroud)

我的主要目标是:

  1. 根据用户和租户快速查询key1的值(select value from table where user=x and tenant=y and key=z)。
  2. 快速存储用户和租户的键值对。
  3. 检索特定用户/租户的所有键值对和元数据(last_updated..)(可能慢约 2 秒)(select * from table where user=x and tenant=y或select * from table where tenant=z)

我可以使用 RDBMS 来做到这一点,但我想它会比使用内存数据库(持久性)慢。

对于 Redis,我考虑通过以下方式保存数据(使用本机 Redis 类型):

127.0.0.1:6379> sadd tenant1 user1
(integer) 1
127.0.0.1:6379> sadd tenant1 user2
(integer) 1
127.0.0.1:6379> sadd tenant1_user1 key1
(integer) 1
127.0.0.1:6379> sadd tenant1_user1 …
Run Code Online (Sandbox Code Playgroud)

json redis

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