prompt
large_stringlengths 72
9.34k
| completion
large_stringlengths 0
7.61k
|
---|---|
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def <|fim_middle|>():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | test_stmt_simplify |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def <|fim_middle|>():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | test_thread_extent_simplify |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def <|fim_middle|>():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | test_if_likely |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def <|fim_middle|>():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | test_basic_likely_elimination |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def <|fim_middle|>(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | f |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def <|fim_middle|>():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | test_complex_likely_elimination |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def <|fim_middle|>(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | cumsum |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def <|fim_middle|>(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | sparse_lengths_sum |
<|file_name|>test_tir_transform_simplify.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
from tvm import te
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.Store)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.Store)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def <|fim_middle|>(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
if __name__ == "__main__":
test_stmt_simplify()
test_thread_extent_simplify()
test_if_likely()
test_basic_likely_elimination()
test_complex_likely_elimination()
<|fim▁end|> | sls |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""<|fim▁hole|> self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}<|fim▁end|> | def __init__(self, name, uri): |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
<|fim_middle|>
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | def command(self, cmd):
print(cmd) |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
<|fim_middle|>
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | print(cmd) |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
<|fim_middle|>
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | """An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1 |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
<|fim_middle|>
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
<|fim_middle|>
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | "Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1 |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
<|fim_middle|>
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | "Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1 |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
<|fim_middle|>
rules = {}
<|fim▁end|> | """A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules] |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
<|fim_middle|>
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | self.name = name
self.uri = uri
self.rules = [] |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
<|fim_middle|>
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read()) |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
<|fim_middle|>
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', []))) |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
<|fim_middle|>
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | build_rules(yaml.load(payload)) |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
<|fim_middle|>
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | [r.install() for r in self.rules] |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
<|fim_middle|>
rules = {}
<|fim▁end|> | [r.uninstall() for r in self.rules] |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
<|fim_middle|>
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
<|fim_middle|>
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1 |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
<|fim_middle|>
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1 |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
<|fim_middle|>
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1 |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
<|fim_middle|>
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | d = open(self.uri, 'r')
return test_load_cb(d.read()) |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def <|fim_middle|>(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | command |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def <|fim_middle|>(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | __init__ |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def <|fim_middle|>(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | install |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def <|fim_middle|>(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | uninstall |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def <|fim_middle|>(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | __init__ |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def <|fim_middle|>(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | load |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def <|fim_middle|>(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | build_rules |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def <|fim_middle|>(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | test_load_cb |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def <|fim_middle|>(self):
[r.install() for r in self.rules]
def uninstall(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | install |
<|file_name|>ignoretogether.py<|end_file_name|><|fim▁begin|># ignore-together.py - a distributed ignore list engine for IRC.
from __future__ import print_function
import os
import sys
import yaml
weechat_is_fake = False
try:
import weechat
except:
class FakeWeechat:
def command(self, cmd):
print(cmd)
weechat = FakeWeechat()
weechat_is_fake = True
class IgnoreRule:
"""An ignore rule.
This provides instrumentation for converting ignore rules into weechat filters.
It handles both types of ignore-together ignore rules.
"""
def __init__(self, ignorelist, rulename, rationale, typename='ignore', hostmasks=[], accountnames=[], patterns=[]):
self.ignorelist = ignorelist
self.rulename = rulename.replace(' ', '_')
self.rationale = rationale
self.typename = typename
self.hostmasks = hostmasks
self.accountnames = accountnames
self.patterns = patterns
def install(self):
"Install an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
# XXX - accountnames
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter add ignore-together.{ignorelist}.{rulename}.{ctr} irc.* * {pattern}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr, pattern=pattern))
subrule_ctr += 1
def uninstall(self):
"Uninstall an ignore rule."
subrule_ctr = 0
if self.typename == 'ignore':
for pattern in self.hostmasks:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
elif self.typename == 'message':
for pattern in self.patterns:
weechat.command('/filter del ignore-together.{ignorelist}.{rulename}.{ctr}'.format(
ignorelist=self.ignorelist.name, rulename=self.rulename, ctr=subrule_ctr))
subrule_ctr += 1
class IgnoreRuleSet:
"""A downloaded collection of rules.
Handles merging updates vs current state, and so on."""
def __init__(self, name, uri):
self.name = name
self.uri = uri
self.rules = []
def load(self):
def build_rules(s):
for k, v in s.items():
self.rules.append(IgnoreRule(self, k, v.get('rationale', '???'), v.get('type', 'ignore'), v.get('hostmasks', []), v.get('accountnames', []), v.get('patterns', [])))
def test_load_cb(payload):
build_rules(yaml.load(payload))
if weechat_is_fake:
d = open(self.uri, 'r')
return test_load_cb(d.read())
def install(self):
[r.install() for r in self.rules]
def <|fim_middle|>(self):
[r.uninstall() for r in self.rules]
rules = {}
<|fim▁end|> | uninstall |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [<|fim▁hole|>])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()<|fim▁end|> | ('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None), |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
<|fim_middle|>
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close() |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
<|fim_middle|>
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close() |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
<|fim_middle|>
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close() |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
<|fim_middle|>
<|fim▁end|> | seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close() |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def <|fim_middle|>(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | test_make_gym_venv_nostack |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def <|fim_middle|>(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | test_make_gym_concat |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def <|fim_middle|>(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_downsize(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | test_make_gym_stack |
<|file_name|>test_vec_env.py<|end_file_name|><|fim▁begin|>from slm_lab.env.vec_env import make_gym_venv
import numpy as np
import pytest
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_venv_nostack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape, reward_scale', [
('PongNoFrameskip-v4', (1, 84, 84), 'sign'),
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_concat(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'concat' # used for image, or for concat vector
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len * state_shape[0],) + state_shape[1:]
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.skip(reason='Not implemented yet')
@pytest.mark.parametrize('name,state_shape,reward_scale', [
('LunarLander-v2', (8,), None),
('CartPole-v0', (4,), None),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def test_make_gym_stack(name, num_envs, state_shape, reward_scale):
seed = 0
frame_op = 'stack' # used for rnn
frame_op_len = 4
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, reward_scale=reward_scale)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
stack_shape = (num_envs, frame_op_len,) + state_shape
assert state.shape == stack_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
@pytest.mark.parametrize('name,state_shape,image_downsize', [
('PongNoFrameskip-v4', (1, 84, 84), (84, 84)),
('PongNoFrameskip-v4', (1, 64, 64), (64, 64)),
])
@pytest.mark.parametrize('num_envs', (1, 4))
def <|fim_middle|>(name, num_envs, state_shape, image_downsize):
seed = 0
frame_op = None
frame_op_len = None
venv = make_gym_venv(name, num_envs, seed, frame_op=frame_op, frame_op_len=frame_op_len, image_downsize=image_downsize)
venv.reset()
for i in range(5):
state, reward, done, info = venv.step([venv.action_space.sample()] * num_envs)
assert isinstance(state, np.ndarray)
assert state.shape == (num_envs,) + state_shape
assert isinstance(reward, np.ndarray)
assert reward.shape == (num_envs,)
assert isinstance(done, np.ndarray)
assert done.shape == (num_envs,)
assert len(info) == num_envs
venv.close()
<|fim▁end|> | test_make_gym_venv_downsize |
<|file_name|>add_dict.py<|end_file_name|><|fim▁begin|>d = {}
for i in range(100000):
d[i] = i
JS_CODE = '''
var d = {};
for (var i = 0; i < 100000; i++) {
d[i] = i;<|fim▁hole|><|fim▁end|> | }
''' |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)<|fim▁hole|> webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()<|fim▁end|> | logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run': |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
<|fim_middle|>
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | return render_template('index.html'), 200 |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
<|fim_middle|>
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200 |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
<|fim_middle|>
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500 |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
<|fim_middle|>
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT) |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
<|fim_middle|>
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5 |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
<|fim_middle|>
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT) |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
<|fim_middle|>
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404 |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
<|fim_middle|>
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200 |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
<|fim_middle|>
<|fim▁end|> | """
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action() |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
<|fim_middle|>
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | webapp.run() |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
<|fim_middle|>
<|fim▁end|> | daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action() |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def <|fim_middle|>():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | index |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def <|fim_middle|>():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | app_settings |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def <|fim_middle|>():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | data |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def <|fim_middle|>(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def run(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | __init__ |
<|file_name|>webapp.py<|end_file_name|><|fim▁begin|>import redis
import logging
import simplejson as json
import sys
from msgpack import Unpacker
from flask import Flask, request, render_template
from daemon import runner
from os.path import dirname, abspath
# add the shared settings file to namespace
sys.path.insert(0, dirname(dirname(abspath(__file__))))
import settings
REDIS_CONN = redis.StrictRedis(unix_socket_path=settings.REDIS_SOCKET_PATH)
app = Flask(__name__)
app.config['PROPAGATE_EXCEPTIONS'] = True
@app.route("/")
def index():
return render_template('index.html'), 200
@app.route("/app_settings")
def app_settings():
app_settings = {'GRAPHITE_HOST': settings.GRAPHITE_HOST,
'OCULUS_HOST': settings.OCULUS_HOST,
'FULL_NAMESPACE': settings.FULL_NAMESPACE,
}
resp = json.dumps(app_settings)
return resp, 200
@app.route("/api", methods=['GET'])
def data():
metric = request.args.get('metric', None)
try:
raw_series = REDIS_CONN.get(metric)
if not raw_series:
resp = json.dumps({'results': 'Error: No metric by that name'})
return resp, 404
else:
unpacker = Unpacker(use_list = False)
unpacker.feed(raw_series)
timeseries = [item[:2] for item in unpacker]
resp = json.dumps({'results': timeseries})
return resp, 200
except Exception as e:
error = "Error: " + e
resp = json.dumps({'results': error})
return resp, 500
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = settings.LOG_PATH + '/webapp.log'
self.stderr_path = settings.LOG_PATH + '/webapp.log'
self.pidfile_path = settings.PID_PATH + '/webapp.pid'
self.pidfile_timeout = 5
def <|fim_middle|>(self):
logger.info('starting webapp')
logger.info('hosted at %s' % settings.WEBAPP_IP)
logger.info('running on port %d' % settings.WEBAPP_PORT)
app.run(settings.WEBAPP_IP, settings.WEBAPP_PORT)
if __name__ == "__main__":
"""
Start the server
"""
webapp = App()
logger = logging.getLogger("AppLog")
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/webapp.log')
handler.setFormatter(formatter)
logger.addHandler(handler)
if len(sys.argv) > 1 and sys.argv[1] == 'run':
webapp.run()
else:
daemon_runner = runner.DaemonRunner(webapp)
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action()
<|fim▁end|> | run |
<|file_name|>basesingleton.py<|end_file_name|><|fim▁begin|>'''
Created on Nov 19, 2011
@author: scottporter
'''
class BaseSingleton(object):
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:<|fim▁hole|> return cls._instance<|fim▁end|> | cls._instance = cls()
|
<|file_name|>basesingleton.py<|end_file_name|><|fim▁begin|>'''
Created on Nov 19, 2011
@author: scottporter
'''
class BaseSingleton(object):
<|fim_middle|>
<|fim▁end|> | _instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance |
<|file_name|>basesingleton.py<|end_file_name|><|fim▁begin|>'''
Created on Nov 19, 2011
@author: scottporter
'''
class BaseSingleton(object):
_instance = None
@classmethod
def get_instance(cls):
<|fim_middle|>
<|fim▁end|> | if cls._instance is None:
cls._instance = cls()
return cls._instance |
<|file_name|>basesingleton.py<|end_file_name|><|fim▁begin|>'''
Created on Nov 19, 2011
@author: scottporter
'''
class BaseSingleton(object):
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
<|fim_middle|>
return cls._instance<|fim▁end|> | cls._instance = cls() |
<|file_name|>basesingleton.py<|end_file_name|><|fim▁begin|>'''
Created on Nov 19, 2011
@author: scottporter
'''
class BaseSingleton(object):
_instance = None
@classmethod
def <|fim_middle|>(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance<|fim▁end|> | get_instance |
<|file_name|>home.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Will
"""
from django import forms
from app01 import models
class ImportFrom(forms.Form):
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
host_type = forms.IntegerField(<|fim▁hole|> )
hostname = forms.CharField()
def __init__(self,*args,**kwargs):
super(ImportFrom,self).__init__(*args,**kwargs)
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name")
models.userInfo.objects.get()
models.userInfo.objects.filter()<|fim▁end|> | widget=forms.Select(choices=HOST_TYPE) |
<|file_name|>home.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Will
"""
from django import forms
from app01 import models
class ImportFrom(forms.Form):
<|fim_middle|>
<|fim▁end|> | HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
host_type = forms.IntegerField(
widget=forms.Select(choices=HOST_TYPE)
)
hostname = forms.CharField()
def __init__(self,*args,**kwargs):
super(ImportFrom,self).__init__(*args,**kwargs)
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name")
models.userInfo.objects.get()
models.userInfo.objects.filter()
|
<|file_name|>home.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Will
"""
from django import forms
from app01 import models
class ImportFrom(forms.Form):
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
host_type = forms.IntegerField(
widget=forms.Select(choices=HOST_TYPE)
)
hostname = forms.CharField()
def __init__(self,*args,**kwargs):
super(Impo<|fim_middle|>
<|fim▁end|> | rtFrom,self).__init__(*args,**kwargs)
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name")
models.userInfo.objects.get()
models.userInfo.objects.filter()
|
<|file_name|>home.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Will
"""
from django import forms
from app01 import models
class ImportFrom(forms.Form):
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
host_type = forms.IntegerField(
widget=forms.Select(choices=HOST_TYPE)
)
hostname = forms.CharField()
def __init__(s<|fim_middle|>s,**kwargs):
super(ImportFrom,self).__init__(*args,**kwargs)
HOST_TYPE=((1,"001"),(2,"002")) #替換爲文件
self.fields['host_type'].widget.choices = models.userInfo.objects.all().values_list("id","name")
models.userInfo.objects.get()
models.userInfo.objects.filter()
<|fim▁end|> | elf,*arg |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#<|fim▁hole|># "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()<|fim▁end|> | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
<|fim_middle|>
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | l = get_type (type_id)
if not l:
return None
return l['name'] |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
<|fim_middle|>
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
<|fim_middle|>
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
<|fim_middle|>
if __name__ == '__main__':
test()
<|fim▁end|> | import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id), |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
<|fim_middle|>
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | return None |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
<|fim_middle|>
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | return None |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
<|fim_middle|>
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | return None |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
<|fim_middle|>
<|fim▁end|> | test() |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def <|fim_middle|> (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | get_type_name |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def <|fim_middle|> (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | get_type |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def <|fim_middle|> ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def test ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | get_types |
<|file_name|>Type.py<|end_file_name|><|fim▁begin|># Copyright (C) 2010 CENATIC: Centro Nacional de Referencia de
# Aplicacion de las TIC basadas en Fuentes Abiertas, Spain.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# Neither the name of the CENATIC nor the names of its contributors
# may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You may contact the copyright holder at: Fundacion CENATIC, Edificio
# de Servicios Sociales: C/ Vistahermosa, 1, 3ra planta, 06200
# Almendralejo (Badajoz), Spain
from DBSlayer import Query
def get_type_name (type_id):
l = get_type (type_id)
if not l:
return None
return l['name']
def get_type (type_id):
q = "SELECT id, type "\
"FROM asset_types WHERE id=%(type_id)s;" % locals()
query = Query(q)
if len(query) != 1:
return None
ret = {'id': type_id,
'name': query['type'][0]}
return ret
def get_types ():
q = "SELECT id, type "\
"FROM asset_types;" % locals()
query = Query(q)
if not len(query):
return None
ret = []
for x in query:
d={'id': query[x]['id'],
'name': query[x]['type']}
ret.append(d)
return ret
def <|fim_middle|> ():
import sys
try:
type_id = sys.argv[1]
except IndexError:
print 'Required test parameters: type_id'
sys.exit(1)
print 'Types:', get_types()
print 'type_id %s, type_name %s' % (type_id, get_type_name(type_id))
print get_type(type_id),
if __name__ == '__main__':
test()
<|fim▁end|> | test |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from solum import objects
from solum.objects import extension as abstract_extension
from solum.objects import operation as abstract_operation
from solum.objects import plan as abstract_plan
from solum.objects import sensor as abstract_sensor
from solum.objects import service as abstract_srvc
from solum.objects.sqlalchemy import extension
from solum.objects.sqlalchemy import operation
from solum.objects.sqlalchemy import plan
from solum.objects.sqlalchemy import sensor
from solum.objects.sqlalchemy import service
def load():<|fim▁hole|> objects.registry.add(abstract_srvc.ServiceList, service.ServiceList)
objects.registry.add(abstract_operation.Operation, operation.Operation)
objects.registry.add(abstract_operation.OperationList,
operation.OperationList)
objects.registry.add(abstract_sensor.Sensor, sensor.Sensor)
objects.registry.add(abstract_sensor.SensorList, sensor.SensorList)
objects.registry.add(abstract_extension.Extension, extension.Extension)
objects.registry.add(abstract_extension.ExtensionList,
extension.ExtensionList)<|fim▁end|> | """Activate the sqlalchemy backend."""
objects.registry.add(abstract_plan.Plan, plan.Plan)
objects.registry.add(abstract_plan.PlanList, plan.PlanList)
objects.registry.add(abstract_srvc.Service, service.Service) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from solum import objects
from solum.objects import extension as abstract_extension
from solum.objects import operation as abstract_operation
from solum.objects import plan as abstract_plan
from solum.objects import sensor as abstract_sensor
from solum.objects import service as abstract_srvc
from solum.objects.sqlalchemy import extension
from solum.objects.sqlalchemy import operation
from solum.objects.sqlalchemy import plan
from solum.objects.sqlalchemy import sensor
from solum.objects.sqlalchemy import service
def load():
<|fim_middle|>
<|fim▁end|> | """Activate the sqlalchemy backend."""
objects.registry.add(abstract_plan.Plan, plan.Plan)
objects.registry.add(abstract_plan.PlanList, plan.PlanList)
objects.registry.add(abstract_srvc.Service, service.Service)
objects.registry.add(abstract_srvc.ServiceList, service.ServiceList)
objects.registry.add(abstract_operation.Operation, operation.Operation)
objects.registry.add(abstract_operation.OperationList,
operation.OperationList)
objects.registry.add(abstract_sensor.Sensor, sensor.Sensor)
objects.registry.add(abstract_sensor.SensorList, sensor.SensorList)
objects.registry.add(abstract_extension.Extension, extension.Extension)
objects.registry.add(abstract_extension.ExtensionList,
extension.ExtensionList) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2013 - Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from solum import objects
from solum.objects import extension as abstract_extension
from solum.objects import operation as abstract_operation
from solum.objects import plan as abstract_plan
from solum.objects import sensor as abstract_sensor
from solum.objects import service as abstract_srvc
from solum.objects.sqlalchemy import extension
from solum.objects.sqlalchemy import operation
from solum.objects.sqlalchemy import plan
from solum.objects.sqlalchemy import sensor
from solum.objects.sqlalchemy import service
def <|fim_middle|>():
"""Activate the sqlalchemy backend."""
objects.registry.add(abstract_plan.Plan, plan.Plan)
objects.registry.add(abstract_plan.PlanList, plan.PlanList)
objects.registry.add(abstract_srvc.Service, service.Service)
objects.registry.add(abstract_srvc.ServiceList, service.ServiceList)
objects.registry.add(abstract_operation.Operation, operation.Operation)
objects.registry.add(abstract_operation.OperationList,
operation.OperationList)
objects.registry.add(abstract_sensor.Sensor, sensor.Sensor)
objects.registry.add(abstract_sensor.SensorList, sensor.SensorList)
objects.registry.add(abstract_extension.Extension, extension.Extension)
objects.registry.add(abstract_extension.ExtensionList,
extension.ExtensionList)
<|fim▁end|> | load |
<|file_name|>__manifest__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2016 Acsone SA/NV
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Account Invoice Check Total',
'summary': """
Check if the verification total is equal to the bill's total""",
'version': '10.0.1.0.0',
'license': 'AGPL-3',
'author': 'Acsone SA/NV,Odoo Community Association (OCA)',
'website': 'https://acsone.eu/',
'depends': [
'account',
],
'data': [
'views/account_config_settings.xml',
'security/account_invoice_security.xml',<|fim▁hole|><|fim▁end|> | 'views/account_invoice.xml',
],
} |
<|file_name|>devfilters.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from mezzanine.conf import settings
from mezzanine_developer_extension.utils import refactor_html
register = template.Library()
# Checking settings.TEMPLATE_STYLE.
# Possible values are:
# - mezzanine_developer_extension.styles.macos
# - mezzanine_developer_extension.styles.ubuntu
# - mezzanine_developer_extension.styles.windows
_prefix = "mezzanine_developer_extension.styles"
try:
if settings.TERMINAL_STYLE not in \
["%s.macos" % _prefix, "%s.ubuntu" % _prefix, "%s.windows" % _prefix]:
# If the user has specified a wrong terminal styling format, we
# raise an exception warning about this.
msg = "Wrong terminal style format. Check the value of TERMINAL_STYLE"\
" in your settings.py file."
raise Exception(msg)
except AttributeError:
msg = "You have not specified a terminal output format. You have to"\
" define the attribute TERMINAL_STYLE in your settings.py"
raise Exception(msg)
@register.filter(name='safe_developer')
def safe_developer(content, style="macos"):
"""
Renders content without cleaning the original.<|fim▁hole|> Replaces the terminal divs for a more complext html layout.
"""
new_content = refactor_html(content, style)
return mark_safe(new_content)<|fim▁end|> | |
<|file_name|>devfilters.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from mezzanine.conf import settings
from mezzanine_developer_extension.utils import refactor_html
register = template.Library()
# Checking settings.TEMPLATE_STYLE.
# Possible values are:
# - mezzanine_developer_extension.styles.macos
# - mezzanine_developer_extension.styles.ubuntu
# - mezzanine_developer_extension.styles.windows
_prefix = "mezzanine_developer_extension.styles"
try:
if settings.TERMINAL_STYLE not in \
["%s.macos" % _prefix, "%s.ubuntu" % _prefix, "%s.windows" % _prefix]:
# If the user has specified a wrong terminal styling format, we
# raise an exception warning about this.
msg = "Wrong terminal style format. Check the value of TERMINAL_STYLE"\
" in your settings.py file."
raise Exception(msg)
except AttributeError:
msg = "You have not specified a terminal output format. You have to"\
" define the attribute TERMINAL_STYLE in your settings.py"
raise Exception(msg)
@register.filter(name='safe_developer')
def safe_developer(content, style="macos"):
<|fim_middle|>
<|fim▁end|> | """
Renders content without cleaning the original.
Replaces the terminal divs for a more complext html layout.
"""
new_content = refactor_html(content, style)
return mark_safe(new_content) |
<|file_name|>devfilters.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from mezzanine.conf import settings
from mezzanine_developer_extension.utils import refactor_html
register = template.Library()
# Checking settings.TEMPLATE_STYLE.
# Possible values are:
# - mezzanine_developer_extension.styles.macos
# - mezzanine_developer_extension.styles.ubuntu
# - mezzanine_developer_extension.styles.windows
_prefix = "mezzanine_developer_extension.styles"
try:
if settings.TERMINAL_STYLE not in \
["%s.macos" % _prefix, "%s.ubuntu" % _prefix, "%s.windows" % _prefix]:
# If the user has specified a wrong terminal styling format, we
# raise an exception warning about this.
<|fim_middle|>
except AttributeError:
msg = "You have not specified a terminal output format. You have to"\
" define the attribute TERMINAL_STYLE in your settings.py"
raise Exception(msg)
@register.filter(name='safe_developer')
def safe_developer(content, style="macos"):
"""
Renders content without cleaning the original.
Replaces the terminal divs for a more complext html layout.
"""
new_content = refactor_html(content, style)
return mark_safe(new_content)<|fim▁end|> | msg = "Wrong terminal style format. Check the value of TERMINAL_STYLE"\
" in your settings.py file."
raise Exception(msg) |
<|file_name|>devfilters.py<|end_file_name|><|fim▁begin|>from django import template
from django.utils.safestring import mark_safe
from mezzanine.conf import settings
from mezzanine_developer_extension.utils import refactor_html
register = template.Library()
# Checking settings.TEMPLATE_STYLE.
# Possible values are:
# - mezzanine_developer_extension.styles.macos
# - mezzanine_developer_extension.styles.ubuntu
# - mezzanine_developer_extension.styles.windows
_prefix = "mezzanine_developer_extension.styles"
try:
if settings.TERMINAL_STYLE not in \
["%s.macos" % _prefix, "%s.ubuntu" % _prefix, "%s.windows" % _prefix]:
# If the user has specified a wrong terminal styling format, we
# raise an exception warning about this.
msg = "Wrong terminal style format. Check the value of TERMINAL_STYLE"\
" in your settings.py file."
raise Exception(msg)
except AttributeError:
msg = "You have not specified a terminal output format. You have to"\
" define the attribute TERMINAL_STYLE in your settings.py"
raise Exception(msg)
@register.filter(name='safe_developer')
def <|fim_middle|>(content, style="macos"):
"""
Renders content without cleaning the original.
Replaces the terminal divs for a more complext html layout.
"""
new_content = refactor_html(content, style)
return mark_safe(new_content)<|fim▁end|> | safe_developer |
<|file_name|>hello.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def helloworld():
"""
Hello world routine !<|fim▁hole|><|fim▁end|> | """
print("Hello world!") |
<|file_name|>hello.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def helloworld():
<|fim_middle|>
<|fim▁end|> | """
Hello world routine !
"""
print("Hello world!") |
<|file_name|>hello.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def <|fim_middle|>():
"""
Hello world routine !
"""
print("Hello world!")
<|fim▁end|> | helloworld |
<|file_name|>b_lanterns.py<|end_file_name|><|fim▁begin|>import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
(n, l) = str_to_int(args[0])
a = tuple(str_to_int(args[1]))<|fim▁hole|> list_a = list(a)
list_a.sort()
max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2)
for x in xrange(len(a) - 1):
max_dist = max(max_dist, list_a[x + 1] - list_a[x])
if verbose:
print max_dist / float(2)
return max_dist / float(2)
def test():
assert(str_to_int('1 2 3') == [ 1, 2, 3 ])
assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5)))
assert(solve([ '2 5', '2 5' ]) == 2.0)
assert(solve([ '4 5', '0 1 2 3' ]) == 2.0)
assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5)
if __name__ == '__main__':
from sys import argv
if argv.pop() == 'test':
test()
else:
solve(list(fileinput.input()), verbose=True)<|fim▁end|> | return(l, a)
def solve(args, verbose=False):
(l, a) = proc_input(args) |
<|file_name|>b_lanterns.py<|end_file_name|><|fim▁begin|>import fileinput
def str_to_int(s):
<|fim_middle|>
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
(n, l) = str_to_int(args[0])
a = tuple(str_to_int(args[1]))
return(l, a)
def solve(args, verbose=False):
(l, a) = proc_input(args)
list_a = list(a)
list_a.sort()
max_dist = max(list_a[0] * 2, (l - list_a[-1]) * 2)
for x in xrange(len(a) - 1):
max_dist = max(max_dist, list_a[x + 1] - list_a[x])
if verbose:
print max_dist / float(2)
return max_dist / float(2)
def test():
assert(str_to_int('1 2 3') == [ 1, 2, 3 ])
assert(proc_input([ '2 5', '2 5' ]) == (5, (2, 5)))
assert(solve([ '2 5', '2 5' ]) == 2.0)
assert(solve([ '4 5', '0 1 2 3' ]) == 2.0)
assert(solve([ '7 15', '15 5 3 7 9 14 0' ]) == 2.5)
if __name__ == '__main__':
from sys import argv
if argv.pop() == 'test':
test()
else:
solve(list(fileinput.input()), verbose=True)
<|fim▁end|> | return([ int(x) for x in s.split() ]) |
Subsets and Splits