小编OG *_*ude的帖子

Jersey,如何POST一个JSON对象列表?

我正在使用Jersey 1.11在Java中构建RESTful Web服务,并且在实现消耗JSON-ised实体列表的方法时遇到问题.单实例方法工作正常.

我得到的错误是:

Status 400 - Bad Request. The request sent by the client was syntactically incorrect.
Run Code Online (Sandbox Code Playgroud)

我的方法签名如下所示:

@POST
@Path("/some-path/{someParam}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public String createBatch(List<MyEntity> myEnts, @PathParam("someParam") String someParam)
{
   ... 
}
Run Code Online (Sandbox Code Playgroud)

我在请求中发送的MyEntityJSON 是一个JSON对象数组:

[{"field1" : value1, "field2" : value2}, {"field1" : value3, "field2" : value4}, ...]
Run Code Online (Sandbox Code Playgroud)

之前已经提出了类似的问题,一个直接的建议是将消费的媒体类型更改为文本并手动反序列化JSON,但我更喜欢更清洁的解决方案.

我发送的JSON在这种情况下是否有效,或者我是否需要顶级{}即包装器实体?这似乎有点不自然.

谢谢,

/大卫

java rest json jersey

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

使用服务器发送的事件和cubism.js图

可以使用从服务器发送的事件接收的数据填充cubism.js图吗?如果是这样,这很容易实现吗?

谢谢,

/大卫

d3.js cubism.js

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

正则表达式:如何匹配字符串末尾的键值对序列

我试图匹配出现在(长)字符串末尾的键值对.字符串看起来像(我替换了"\n")

my_str = "lots of blah
          key1: val1-words
          key2: val2-words
          key3: val3-words"
Run Code Online (Sandbox Code Playgroud)

所以我希望匹配"key1:val1-words","key2:val2-words"和"key3:val3-words".

  • 可能的密钥名称集是已知的.
  • 并非所有可能的键都出现在每个字符串中
  • 每个字符串中至少会出现两个键(如果这样可以更容易匹配).
  • val-words可以是几个单词.
  • 键值对只应在字符串末尾匹配.
  • 我正在使用Python re模块.

我刚在想

re.compile('(?:tag1|tag2|tag3):')

加上一些前瞻性断言的东西将是一个解决方案.我不能说得对.我该怎么办?

谢谢.

/大卫

真实示例字符串:

my_str = u'ucourt métrage pour kino session volume 18\nThème: O sombres héros\nContraintes: sous titrés\nAuthor: nicoalabdou\nTags: wakatanka productions court métrage kino session humour cantat bertrand noir désir sombres héros mer medine marie trintignant femme droit des femmes nicoalabdou pute soumise\nPosted: 06 June 2009\nRating: 1.3\nVotes: 3'
Run Code Online (Sandbox Code Playgroud)

编辑:

根据Mikel的解决方案,我现在使用以下内容:


my_tags = ['\S+'] # gets all tags
my_tags …
Run Code Online (Sandbox Code Playgroud)

python regex key-value

6
推荐指数
1
解决办法
8897
查看次数

.NET System :: String到UTF8字节存储在char*中

我在.NET项目中包含一些非托管C++代码.为此我需要转换System::String为存储的UTF8字节char*.

我不确定这是否是最佳或甚至是正确的方法,如果有人可以看一看并提供反馈,我将不胜感激.

谢谢,

/大卫

// Copy into blank VisualStudio C++/CLR command line solution.
#include "stdafx.h"
#include <stdio.h>

using namespace System;
using namespace System::Text;
using namespace System::Runtime::InteropServices;

// Test for calling with char* argument.
void MyTest(const char* buffer)
{
    printf_s("%s\n", buffer);
    return;
}

int main()
{

   // Create a UTF-8 encoding.
   UTF8Encoding^ utf8 = gcnew UTF8Encoding;

   // A Unicode string with two characters outside an 8-bit code range.
   String^ unicodeString = L"This unicode string contains two characters …
Run Code Online (Sandbox Code Playgroud)

.net c++ string unmanaged char

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

限制 Python 线程的并发数和速率

给定一定数量的线程,我想将对工作函数的调用速率限制为每秒一次。

我的想法是跟踪所有线程上次调用的时间,并将其与每个线程中的当前时间进行比较。那么如果current_time - last_time < rate. 我让线程休眠一会儿。我的实现有问题 - 我想我可能对锁的工作原理有错误的想法。

我的代码:

from Queue import Queue
from threading import Thread, Lock, RLock
import time

num_worker_threads = 2
rate = 1
q = Queue()
lock = Lock()
last_time = [time.time()]

def do_work(i, idx):
    # Do work here, print is just a dummy.
    print('Thread: {0}, Item: {1}, Time: {2}'.format(i, idx, time.time()))

def worker(i):
    while True:
        lock.acquire()
        current_time = time.time()
        interval = current_time - last_time[0]
        last_time[0] = current_time
        if interval < rate:
            time.sleep(rate …
Run Code Online (Sandbox Code Playgroud)

python concurrency multithreading rate-limiting

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

如何使用pytest-django在测试之间将数据保存到DB?

在Django应用程序的测试运行中使用pytest/pytest-django时,如何将数据保存到DB?

我运行pytest 并按预期创建py.test --nomigrations --reuse-db -sPostgres DB test_<configued_db_name>,但是在测试之间似乎没有任何东西持久存在,并且在测试运行结束时DB没有.

import pytest
from django.contrib.auth.models import User


@pytest.mark.django_db(transaction=False)
def test_insert_user():
    user = User.objects.create_user(username="test_user", email="test_user@test.com", password="test")
    users = User.objects.all()
    assert len(users) > 0

@pytest.mark.django_db(transaction=False)
def test_check_user():
    users = User.objects.all()
    assert len(users) > 0
Run Code Online (Sandbox Code Playgroud)

第一次测试通过,第二次测试没有让我怀疑是否有任何东西持续存在于DB中.根据pystest-django文档,@pytest.mark.django_db(transaction=False)不会回滚受装饰测试影响的任何内容.

谢谢,

/大卫

django pytest pytest-django

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

在LINQ查询中突破Parallel.ForEach

我正在循环使用LINQ to SQL映射Parallel.ForEach.一旦处理了一定数量的元素,我就会脱离循环.处理停止,但循环然后在我收到错误之前挂起几秒钟:

System.Data.SqlClient.SqlErrorCollection: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

如何让循环正常退出?通过ToList()在查询中添加say a 来强制本地集合是没有选择的.我也尝试将所有内容包装在一个using块中但无济于事.注意,那个

这是代码:

var query = SomeDataContext.SomeTableMapping; // All ok, if I append Take(maxRecords)
int maxRecords = 1000;
Parallel.ForEach(query, (queryResult, pLoopState, idx) =>
{
    // Do whatever here on queryResult.
    if (idx > maxRecords)
    {
         Console.WriteLine("Reached maximum number of records: {0}", maxRecords);
         pLoopState.Break();
    }
});
Run Code Online (Sandbox Code Playgroud)

谢谢,

/大卫

.net linq-to-sql task-parallel-library

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

设置DAY_OF_WEEK会返回意外结果

我想将给定的日历实例的时间戳设置为一周的开头(星期一),而是返回一个看似完全不相关的时间戳 - 除非我在这之前访问任何日历的字段.我在下面提供了一个示例,请在Ideone中看到这个可运行的示例.

这是预期的行为吗?这背后的逻辑是什么?是的,我听说过Joda Time.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;


class MyTest {

private static Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"), Locale.FRANCE);
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

public static void main(String[] args) {

    // Set to any date.
    calendar.set(2013, 10, 3);
    System.out.println(dateFormat.format(calendar.getTime()));

    // Set to another day.
    calendar.set(2014, 0, 15);
    // --- THE WTF STARTS HERE ---
    // Uncommenting the line below returns the correct date in the end.
    // calendar.getTime();

    // Set to monday …
Run Code Online (Sandbox Code Playgroud)

java calendar

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

如何在MongoDB shell中将变量用作字段名称的一部分?

如何在mongodb shell中使用变量作为字段名称的一部分?我正在尝试执行以下操作:

> var site = "google.com";
> var y = 10;
> var m = 5;

// This fails (field names as concatenation):
> db.test.update({ "domain" : site},
      { $inc : {"counts.year."+y : 1, "counts.month."+m : 1}}, upsert=true);

> Thu Apr 19 19:12:56 SyntaxError: missing : after property id (shell):1

// This works:
> db.test.update({ "domain" : site}, { $inc : {"counts.year.10" : 1,
      "counts.month.5" : 1}}, upsert=true);
Run Code Online (Sandbox Code Playgroud)

我想问题就在于JS对象的创建方式:例如var t = 10; doc = {t : 0};有效 …

javascript mongodb mongo-shell

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