I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this?
我有一个包含值的数组,我想创建它的直方图.我主要对低端号码感兴趣,并希望在一个箱子中收集300以上的每个号码.此箱应具有与所有其他(同样宽)箱相同的宽度.我怎样才能做到这一点?
注意:此问题与此问题有关:在Matplotlib直方图中定义bin宽度/ x轴刻度
这是我到目前为止所尝试的:
import matplotlib.pyplot as plt
import numpy as np
def plot_histogram_01():
np.random.seed(1)
values_A = np.random.choice(np.arange(600), size=200, replace=True).tolist()
values_B = np.random.choice(np.arange(600), size=200, replace=True).tolist()
bins = [0, 25, 50, 75, 100, 125, 150, 175, 200, 225, 250, 275, 300, 600]
fig, ax = plt.subplots(figsize=(9, 5))
_, bins, patches = plt.hist([values_A, values_B], normed=1, # normed is deprecated and will be replaced by density
bins=bins,
color=['#3782CC', '#AFD5FA'],
label=['A', 'B'])
xlabels = np.array(bins[1:], dtype='|S4')
xlabels[-1] = '300+'
N_labels = len(xlabels)
plt.xlim([0, …Run Code Online (Sandbox Code Playgroud) 我有以下(简化)React组件.
class SalesView extends Component<{}, State> {
state: State = {
salesData: null
};
componentDidMount() {
this.fetchSalesData();
}
render() {
if (this.state.salesData) {
return <SalesChart salesData={this.state.salesData} />;
} else {
return <p>Loading</p>;
}
}
async fetchSalesData() {
let data = await new SalesService().fetchSalesData();
this.setState({ salesData: data });
}
}
Run Code Online (Sandbox Code Playgroud)
安装时,我从API中获取数据,我在一个名为的类中抽象出来SalesService.这个类我想模拟,对于fetchSalesData我想要指定返回数据的方法(在一个promise中).
这或多或少是我希望我的测试用例看起来像:
设置mockSalesService以返回在解析时返回预定义测试数据的promise
创建组件
测试SalesChart的外观不是这个问题的一部分,我希望使用Enzyme来解决这个问题.我一直在尝试几十种来模拟这个异步调用,但我似乎无法正确地嘲笑它.我在网上找到了以下Jest模拟的例子,但它们似乎没有涵盖这个基本用法.
我希望能够在我的一个核心数据模型上的字符串属性上覆盖getter,在getter中我需要找出该属性的值.
@interface LabTest : NSManagedObject {
}
@property (nonatomic, retain) NSString *status;
@end
@implementation LabTest
@dynamic status;
- (NSString *)status {
NSString *tempStatus = [super valueForKey:@"status"];
//do some checking here
return tempStatus;
}
@end
Run Code Online (Sandbox Code Playgroud)
上面的代码崩溃了这个过程.我尝试了一些不同的东西,但我认为它们最终都是无限循环,程序崩溃时代码为139.
在getter中访问核心数据成员的正确方法是什么?
我已经制作了两个相同的类X和Y,并且指向了彼此.请参阅下面的代码Xh,Yh与所有X和Y的互换相同.但是,此代码在我的方法Connect中出错(错误C2027:使用未定义类型'Y').在Xh中,我已经向前声明了类Y,但它不知道Y有一个名为SetXPointer的方法.因此我还需要转发声明这个方法,对吗?
如果我尝试这样做(添加行Y :: SetXPointer(X*pX_in);在行类Y;)下,我得到编译器错误C2761:'void Y :: SetXPointer(X*)':成员函数重新声明不允许.有没有办法在类X中使用类Y的公共方法?
// X.h
#pragma once
#include "Y.h"
// Forward declaration
class Y;
class X
{
public:
X(void) : data(24) {};
~X(void) {};
int GetData() { return data; }
void SetYPointer(Y* pY_in) { pY = pY_in; }
Y* GetYPointer() { return pY; }
void Connect(Y* Y_in) { pY = Y_in; Y_in->SetXPointer(this); }
private:
int data;
Y *pY;
};
Run Code Online (Sandbox Code Playgroud) 我在本主题中看到,如果要使用参数,可以在shell登录脚本中添加函数而不是别名.但是,我将以下代码放在带有别名的部分的.cshrc文件中:
function gf()
{
grep -n $1 `find .` | grep -v "can't open"
}
Run Code Online (Sandbox Code Playgroud)
但是当我输入source .cshrc时,我收到错误消息:Badly placed()的.C shell的语法与Bash shell的语法不同吗?如果是这样,那么正确的语法是什么?
假设我有一个简单的Django REST Framework视图,它扩展了多个模型类,并为一个URL端点中的所有方法提供服务:
class UserAPIView(RetrieveAPIView, DestroyAPIView, BaseObjectAPIView):
permission_classes = (IsAuthenticated, )
serializer_class = UserSerializer
def get_serializer_class(self, *args, **kwargs):
# return different serializer depending on method??
# return UserUpdateSerializer
return UserViewSerializer
def get(self, request, *args, **kwargs):
"""
Retrieve user details
"""
# ...
return Response(data={'result': "OK"}, status=200)
def delete(self, request, pk):
"""
Delete user
"""
# ...
return Response(data={'result': "OK"}, status=200)
def put(self, request, pk):
"""
Change user
"""
# ...
return Response(data={'result': "OK"}, status=200)
Run Code Online (Sandbox Code Playgroud)
现在我需要为每个方法使用不同的序列化器,因为我的get-method将使用与put-method不同的字段,例如序列化器:
class UserViewSerializer(serializers.ModelSerializer):
firstname = serializers.Field(source='firstname') …Run Code Online (Sandbox Code Playgroud) 我有一个表和一个如下所示的查询.有关工作示例,请参阅此SQL小提琴.
SELECT o.property_B, SUM(o.score1), w.score
FROM o
INNER JOIN
(
SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B
) w ON w.property_B = o.property_B
WHERE o.property_A = 'specific_A'
GROUP BY property_B;
Run Code Online (Sandbox Code Playgroud)
使用我的真实数据,此查询需要27秒.但是,如果我首先创建w作为临时表和索引property_B,它们总共需要约1秒.
CREATE TEMPORARY TABLE w AS
SELECT o.property_B, SUM(o.score2) AS score FROM o GROUP BY property_B;
ALTER TABLE w ADD INDEX `property_B_idx` (property_B);
SELECT o.property_B, SUM(o.score1), w.score
FROM o
INNER JOIN w ON w.property_B = o.property_B
WHERE o.property_A = 'specific_A'
GROUP BY property_B;
DROP TABLE …Run Code Online (Sandbox Code Playgroud) 我需要在java中构造的一种结构,并将其作为响应发送:
var abc = {"action":"Remove",
"datatable":[
{"userid":"userid0","username":"name0"},
{"userid":"userid1","username":"name1"},
{"userid":"userid2","username":"name2"},
{"userid":"userid3","username":"name3"}
]
,
"msgType":"success"};
Run Code Online (Sandbox Code Playgroud)
我在做:
JSONArray jsonArray = new JSONArray();
for (loop) {
JSONObject jsonObj= new JSONObject();
jsonObj.put("srcOfPhoto", srcOfPhoto);
jsonObj.put("username", "name"+count);
jsonObj.put("userid", "userid"+count);
jsonArray .add(jsonObj.toJSONString());
}
Map paramMap = new HashMap();
paramMap.put("action", "remove");
paramMap.put("datatable", jsonArray );
paramMap.put(Constant.MSG_TYPE , Constant.SUCCESS);
getJSONMessage(paramMap);
Run Code Online (Sandbox Code Playgroud)
以上函数将paramMap转换为json字符串,如:
public static String getJSONMessage(Map<String, String> paramMap){
if(paramMap != null && paramMap.size() > 0)
return JSONObject.toJSONString(paramMap);
else
return "";
}
Run Code Online (Sandbox Code Playgroud)
但它没有创造出正确的结构,任何人都可以帮助我吗?
这是我得到的输出:
{ "动作": "删除", "数据表":[ "{\" 用户ID\":\" userid0 \",\ "srcOfPhoto …
我使用Anaconda发行版的Python 3.4.在这个发行版中,我发现该pymysql库连接到现有的MySQL数据库,该数据库位于另一台计算机上.
import pymysql
config = {
'user': 'my_user',
'passwd': 'my_passwd',
'host': 'my_host',
'port': my_port
}
try:
cnx = pymysql.connect(**config)
except pymysql.err.OperationalError :
sys.exit("Invalid Input: Wrong username/database or password")
Run Code Online (Sandbox Code Playgroud)
我现在想为我的应用程序编写测试代码,我希望在setUp每个测试用例中创建一个非常小的数据库,最好是在内存中.但是,当我尝试使用pymysql它时,它无法建立连接.
def setUp(self):
config = {
'user': 'test_user',
'passwd': 'test_passwd',
'host': 'localhost'
}
cnx = pymysql.connect(**config)
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 61] Connection refused)")
Run Code Online (Sandbox Code Playgroud)
我一直在谷歌搜索,并发现了一些关于SQLite和MySQLdb.我有以下问题:
sqlite3或MySQLdb适合在内存中快速创建数据库?MySQLdb在Anaconda包中安装?setUp?这甚至是个好主意吗? …python ×3
mysql ×2
alias ×1
arrays ×1
asynchronous ×1
bins ×1
c++ ×1
core-data ×1
dictionary ×1
histogram ×1
indexing ×1
iphone ×1
javascript ×1
jestjs ×1
json ×1
login ×1
matplotlib ×1
mysql-python ×1
objective-c ×1
pymysql ×1
reactjs ×1
sequence ×1
shell ×1
sqlite ×1
subquery ×1
unit-testing ×1