我刚刚得到了道格拉斯·克罗克福德的Javascript:The Good Parts,我很难理解他关于原型的一个例子.书中的代码如下:
if (typeof Object.create !== "function") {
Object.create = function(o) {
var F = function () {}
F.prototype = o;
return new F;
};
}
Run Code Online (Sandbox Code Playgroud)
我假设这段代码用于定位函数的原型.但为什么要使用这种复杂的方法呢?为什么不直接使用variable.prototype?Crockford是Javascript领域的领先专家,所以我确信有充分的理由使用这个模型.谁能帮助我更好地理解它?任何帮助,将不胜感激.
我正在尝试编写一个返回两个字符串中较长字符的函数.到目前为止,这就是我所拥有的:
maxString :: String -> String -> String
maxString a b
| (length a) > (length b) = a
| otherwise = b
Run Code Online (Sandbox Code Playgroud)
这有效,但我想知道是否有更优雅的方式来写这个.注意:这两个参数不能在列表中.它们必须是单独的参数以允许currying.
思考?
我正在尝试为两个整数之间的“接近”行为提出一种算法。基本上,给定两个整数a和b,我想a“接近” b,即使b小于a. 我认为这应该看起来是循环增量函数的交换:
for (var i = a; approachCond(i, a, b); approachDir(i,a, b)) {
// some fn(a, b);
}
Run Code Online (Sandbox Code Playgroud)
在哪里
approachCond(i, a, b) {
return a < b ? i < b : i > b;
}
Run Code Online (Sandbox Code Playgroud)
和
approachDir(i, a, b) {
return a < b ? i++ : i--
}
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试这样做时,浏览器会冻结(Chrome)。有谁知道如何动态改变循环的方向?
我正在尝试创建一个数据库并在我的容器网络中连接到它。我不想通过 ssh 进入一个盒子来创建用户/数据库等,因为这不是一个可扩展或易于分发的过程。
这是我到目前为止:
# docker-compose.yml
db:
image: postgres:9.4
volumes:
- ./db/init.sql:/docker-entrypoint-initdb/10-init.sql
environment:
- PGDATA=/tmp
- PGDATABASE=web
- PGUSER=docker
- PGPASSWORD=password
Run Code Online (Sandbox Code Playgroud)
这是我的init.sql文件:
CREATE DATABASE web;
CREATE USER docker WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE web TO docker;
Run Code Online (Sandbox Code Playgroud)
当我启动容器并尝试连接到它时,出现此错误:
db_1 | FATAL: role "docker" does not exist
db_1 | done
db_1 | server started
db_1 | FATAL: database "web" does not exist
db_1 | psql: FATAL: database "web" does not exist
Run Code Online (Sandbox Code Playgroud)
第一次发生这种情况时,我尝试创建一个这样的角色:
CREATE ROLE docker with SUPERUSER …Run Code Online (Sandbox Code Playgroud) 我试过在IDLE中运行以下代码:
import sys
dir(sys)
Run Code Online (Sandbox Code Playgroud)
没有结果:
>>>
Run Code Online (Sandbox Code Playgroud)
但是当我在命令行中运行它时,我得到了这个:
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions', 'winver']
Run Code Online (Sandbox Code Playgroud)
有人能解释我所做的不同吗?
我正在尝试将字符串流式传输到另一个流:
streamer = new stream.Transform objectMode: true
stringer = (string) ->
streamer._transform = (chunk, encoding, done) ->
@push string.split('').shift()
done()
return streamer
streamer.on 'readable', ->
console.log 'readable'
stringer('hello').pipe process.stdout
Run Code Online (Sandbox Code Playgroud)
但是控制台中没有任何日志。我究竟做错了什么?
我正在尝试声明一个类型列表的数据Either类型.
data EitherInts = [Either Int Int]
Run Code Online (Sandbox Code Playgroud)
但是当我尝试编译这种类型时,我收到一个错误:
Cannot parse data constructor in a data/newtype declaration: [Either Int Int]
Run Code Online (Sandbox Code Playgroud)
我不知道为什么.我究竟做错了什么?
这是我的代码:
# Process connections
print('Listening on port', port)
while True:
c, addr = s.accept()
print("Got connection from", addr)
msg = "<html></html>"
response_headers = {
'Content-Type': 'text/html; encoding=utf8',
'Content-Length': len(msg.encode(encoding="utf-8")),
'Connection': 'close',
}
response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in response_headers.items())
response_proto = 'HTTP/1.1'
response_status = '200'
response_status_text = 'OK' # this can be random
# sending all this stuff
r = '%s %s %s' % (response_proto, response_status, response_status_text)
c.send(r.encode(encoding="utf-8"))
c.send(response_headers_raw.encode(encoding="utf-8"))
c.send('\n'.encode(encoding="utf-8")) # to separate headers from …Run Code Online (Sandbox Code Playgroud) 我一直试图解决一个奇怪的问题很长一段时间了.在单步执行大量角度代码后,我注意到在通过Charles将请求记录到我的服务器时有些奇怪.
当我发布到网址时/myurl,请求永远不会真正命中我的服务器.相反,它得到301响应,然后GET请求hite我的服务器.
这令人难以置信的令人费解.有没有其他人遇到这个问题?我已经上传了我感兴趣的查尔斯日志的截图.
作为参考,这是我的服务器的样子:
type FormStruct struct {
Test string
}
func PHandler(w http.ResponseWriter, r *http.Request) {
var t FormStruct
req, _ := httputil.DumpRequest(r, true)
log.Println(string(req))
log.Println(r.Method) // GET
log.Println(r.Body)
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&t)
log.Println("Decoding complete")
if err != nil {
log.Println("Error")
panic(err.Error()+"\n\n")
}
log.Println(t.Test)
w.Write([]byte("Upload complete, no errors"))
}
func main() {
http.HandleFunc("/myurl/", PHandler)
fmt.Println("Go Server listening on port 8001")
http.ListenAndServe(":8001", nil)
}
Run Code Online (Sandbox Code Playgroud) 我不确定该主题是否更适合此处或数学上的溢出。由于我使用的是numpy,因此我想将其发布在这里。
我正在尝试在3维空间中旋转多维数据集,然后将其投影到2维平面上。
我从Identiy矩阵开始:
import numpy as np
I = [[1,0,0],
[0,1,0],
[0,0,1]]
Run Code Online (Sandbox Code Playgroud)
然后,我将旋转变换应用于Y轴:
from math import sin, cos
theta = radians(30)
c, s = cos(theta), sin(theta)
RY = np.array([[c, 0, s],[0, 1, 0], [-s, 0, c]])
# at this point I'd be dotting the Identiy matrix, but I'll include for completeness
I_RY = np.dot(I, RY)
Run Code Online (Sandbox Code Playgroud)
在这一点上,我有一个新的基础空间,它已绕Y轴旋转了30度。
现在,我想将此投影到二维空间上。我认为,这个新空间基本上是Z轴设置为零的标识基础:
FLAT = [[1,0,0],
[0,1,0],
[0,0,0]]
Run Code Online (Sandbox Code Playgroud)
所以现在,我认为我可以对此进行组合以完成从立方体到正方形的完整转换:
NEW_SPACE = np.dot(I_RY, FLAT)
Run Code Online (Sandbox Code Playgroud)
剩下的就是变换原始立方体的点。假设原始多维数据集的东北点设置为[1,1,1]和[1,1,-1],我可以这样获得新点:
NE_1 = np.array([1,1,1])
NE_2 = np.array([1,1,-1])
np.dot(NEW_SPACE, NE_1)
np.dot(NEW_SPACE, NE_2)
Run Code Online (Sandbox Code Playgroud)
但是,这给了我以下几点:
array([ …Run Code Online (Sandbox Code Playgroud) python ×3
haskell ×2
http ×2
javascript ×2
coffeescript ×1
docker ×1
go ×1
loops ×1
node.js ×1
numpy ×1
oop ×1
postgresql ×1
sockets ×1