这是我实施的模型:
public class LoginSession {
private static final Gson gson = new Gson();
private String id;
private String name;
private long timestamp;
public LoginSession(String id, String name) {
this.id = id;
this.name = name;
this.timestamp = System.currentTimeMillis();
}
public String toJson() {
return gson.toJson(this);
}
public static LoginSession fromJson(String json) {
checkArgument(!isNullOrEmpty(json));
return gson.fromJson(json, LoginSession.class);
}
}
Run Code Online (Sandbox Code Playgroud)
我认为为每个LoginSession实例创建新的Gson实例是没用的.
但我担心的是线程安全问题.将创建大约1000多个实例/秒.
将Gson实例用作静态字段是否可以?
感谢您的任何建议/更正.
我ToStringBuilder.reflectionToString(class)在commons-lang中用来实现toString()简单的DTO.现在我正在尝试使用Google Guava而不是Apache commons库.我Objects.ToStringHelper在瓜瓦找到了.但如果班上有很多成员,那就太啰嗦了.例如:
@Override
public String toString() {
return MoreObjects.toStringHelper(this.getClass()).add("name", name)
.add("emailAddress", emailAddress)
.add("department", department).add("yearJoined", yearJoined)
.toString();
}
Run Code Online (Sandbox Code Playgroud)
如果我使用commons-lang则更简单:
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法来实施toString()番石榴,而不是公共场所?
找到一个使用cx_Oracle的例子,这个例子显示了所有的信息Cursor.description.
import cx_Oracle
from pprint import pprint
connection = cx_Oracle.Connection("%s/%s@%s" % (dbuser, dbpasswd, oracle_sid))
cursor = cx_Oracle.Cursor(connection)
sql = "SELECT * FROM your_table"
cursor.execute(sql)
data = cursor.fetchall()
print "(name, type_code, display_size, internal_size, precision, scale, null_ok)"
pprint(cursor.description)
pprint(data)
cursor.close()
connection.close()
Run Code Online (Sandbox Code Playgroud)
我想看到的是Cursor.description[0](名称)列表,所以我更改了代码:
import cx_Oracle
import pprint
connection = cx_Oracle.Connection("%s/%s@%s" % (dbuser, dbpasswd, oracle_sid))
cursor = cx_Oracle.Cursor(connection)
sql = "SELECT * FROM your_table"
cursor.execute(sql)
data = cursor.fetchall()
col_names = []
for i in range(0, len(cursor.description)):
col_names.append(cursor.description[i][0])
pp = pprint.PrettyPrinter(width=1024) …Run Code Online (Sandbox Code Playgroud) 我正在测试Flume NG(1.2.0)来收集日志.这是一个简单的测试,Flume收集日志文件flume_test.log并将收集的日志作为sysout输出到控制台.conf/flume.conf是:
agent.sources = tail
agent.channels = memoryChannel
agent.sinks = loggerSink
agent.sources.tail.type = exec
agent.sources.tail.command = tail -f /Users/pj/work/flume_test.log
agent.sources.tail.channels = memoryChannel
agent.sinks.loggerSink.channel = memoryChannel
agent.sinks.loggerSink.type = logger
agent.channels.memoryChannel.type = memory
agent.channels.memoryChannel.capacity = 100
Run Code Online (Sandbox Code Playgroud)
我按照以下方式运行Flume:
$ $FLUME_HOME/bin/flume-ng agent --conf $FLUME_HOME/conf --conf-file $FLUME_HOME/conf/flume.conf --name agent1 -Dflume.root.logger=DEBUG,console
Run Code Online (Sandbox Code Playgroud)
在控制台上运行Flume日志后:
Info: Sourcing environment configuration script /usr/local/lib/flume-ng/conf/flume-env.sh
+ exec /Library/Java/JavaVirtualMachines/jdk1.7.0_07.jdk/Contents/Home/bin/java -Xmx20m -Dflume.root.logger=DEBUG,console -cp '/usr/local/lib/flume-ng/conf:/usr/local/lib/flume-ng/lib/*' -Djava.library.path= org.apache.flume.node.Application --conf-file /usr/local/lib/flume-ng/conf/flume.conf --name agent1
2012-09-12 18:23:52,049 (main) [INFO - org.apache.flume.lifecycle.LifecycleSupervisor.start(LifecycleSupervisor.java:67)] Starting lifecycle supervisor 1
2012-09-12 …Run Code Online (Sandbox Code Playgroud) 我想查询的数据user_id是'1'和name是'John'.编写常用的SQL很容易:
select * from t where user_id = '1' and name = 'John';
Run Code Online (Sandbox Code Playgroud)
但是我对弹性搜索进行查询并不容易.
首先,我查询了user_id:
{
"query" : {
"match" : {
"user_id" : "1"
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果是我的预期.
然后,我查询name:
{
"query" : {
"match" : {
"name" : "John"
}
}
}
Run Code Online (Sandbox Code Playgroud)
它运作良好.
但我无法通过和操作加入2个条件的查询.如何将这两个匹配查询合并为一个使用和操作?
我正在使用应用程序模板中的Polymer构建一个Web应用程序polymer init starter-kit.
我有一些特定于阶段的环境变量,例如后端API入口点.这些环境变量有一个行为:
<script>
EnvBehavior = {
properties: {
apiBaseUrl: {
type: String,
// value: '//some-url.com' // production
value: 'http://localhost:8000' // development
}
}
};
</script>
Run Code Online (Sandbox Code Playgroud)
并apiBaseUrl用于其他元素:
<dom-module id="my-element">
<template>
<iron-ajax url="{{apiBaseUrl}}/foo" method="POST"
content-type="application/x-www-form-urlencoded"
body="{{requestBody}}" handle-as="json"
on-response="onResponse" on-error="onError"></iron-ajax>
</template>
<script>
Polymer({
is: 'my-element',
properties: {
requestBody: {foo: 'bar'}
},
behaviors: [EnvBehavior],
onResponse: function(e) {
console.log(e.detail.response);
},
onError: function(e) {
console.log(e.detail.request.xhr.response);
}
});
</script>
</dom-module>
Run Code Online (Sandbox Code Playgroud)
这有效.但我想构建一个带有apiBaseUrl默认值的生产应用程序,该应用程序//some-url.com在代码中被注释掉了.如何在构建时有效地设置特定于阶段的变量?我使用聚合物-cli进行构建; 跑polymer build.
在官方API文档中,它说:
以Int为单位返回此数字的值,可能涉及舍入或截断.
我想截断,但不确定.任何人都可以解释其确切含义may involve rounding or truncation吗?
ps:在我的单元测试中,(1.7).toInt()为1,这可能涉及截断.
我想要的是使用time.sleep()打印出每秒打印一个点的5个点,但结果是在延迟5秒后立刻打印了5个点.
尝试了print和sys.stdout.write,结果相同.
感谢您的任何建议.
import time
import sys
def wait_for(n):
"""Wait for {n} seconds. {n} should be an integer greater than 0."""
if not isinstance(n, int):
print 'n in wait_for(n) should be an integer.'
return
elif n < 1:
print 'n in wait_for(n) should be greater than 0.'
return
for i in range(0, n):
sys.stdout.write('.')
time.sleep(1)
sys.stdout.write('\n')
def main():
wait_for(5) # FIXME: doesn't work as expected
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print '\nAborted.'
Run Code Online (Sandbox Code Playgroud) 我是函数式编程的新手,有人建议lodash理解主要的高阶函数.
浏览lodash API文档,我把握不住示例代码为_.after():
var saves = ['profile', 'settings'];
var done = _.after(saves.length, function() {
console.log('Done saving!');
});
_.forEach(saves, function(type) {
asyncSave({ 'type': type, 'complete': done });
});
// ? logs 'Done saving!', after all saves have completed
Run Code Online (Sandbox Code Playgroud)
上面的示例代码没有实现asyncSave(),所以我应该为自己实现这个功能.但我不知道如何实现它.这是因为我不了解_.after()自己的规范.
如果有人解释函数比API文档说的更容易,那就太棒了.或者,一个易于理解和实用的功能示例将是一个很大的帮助.谢谢!
我需要一个函数,它接受两个参数input字符串和default字符串,然后返回,input如果不是空白,或default.
(defn default-if-blank [input default]
(if (clojure.string/blank? input)
default
input))
Run Code Online (Sandbox Code Playgroud)
我可以实现这个功能,但我认为在Clojure世界中会有很多优秀的实用程序库,比如Apache公共或Java世界中的Guava.
我自己实现这些功能,而不是使用某些库是常见的吗?我是Clojure的新手,所以这可能是个愚蠢的问题,但任何建议都会对我有所帮助.谢谢.