hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 2 1.02M | avg_line_length float64 1 958k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 2
classes | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f727c080bee1883b62b81efe7828d2d40ce4de8a | 375 | py | Python | CodeSignal/Arcade/The_Core/Level_10_Lab_Of_Transformation/085_Higher_Version.py | Zubieta/CPP | fb4a3cbf2e4edcc590df15663cd28fb9ecab679c | [
"MIT"
] | 8 | 2017-03-02T07:56:45.000Z | 2021-08-07T20:20:19.000Z | CodeSignal/Arcade/The_Core/Level_10_Lab_Of_Transformation/085_Higher_Version.py | zubie7a/Algorithms | fb4a3cbf2e4edcc590df15663cd28fb9ecab679c | [
"MIT"
] | null | null | null | CodeSignal/Arcade/The_Core/Level_10_Lab_Of_Transformation/085_Higher_Version.py | zubie7a/Algorithms | fb4a3cbf2e4edcc590df15663cd28fb9ecab679c | [
"MIT"
] | 1 | 2021-08-07T20:20:20.000Z | 2021-08-07T20:20:20.000Z | # https://app.codesignal.com/arcade/code-arcade/lab-of-transformations/vsKRjYKv4SCjzJc8r/
def higherVersion(ver1, ver2):
# Split by dots, convert individual elements to ints.
ver1 = [int(x) for x in ver1.split(".")]
ver2 = [int(x) for x in ver2.split(".")]
# This will do a comparison item-wise of all elements in the iterable arrays.
return ver1 > ver2
| 41.666667 | 89 | 0.696 |
def higherVersion(ver1, ver2):
ver1 = [int(x) for x in ver1.split(".")]
ver2 = [int(x) for x in ver2.split(".")]
return ver1 > ver2
| true | true |
f727c1a63c15749305645ffe5f2bcd064e0496d2 | 23,239 | py | Python | code_generate.py | Taekyoon/Python-Mini-C-Compiler | deabdba9f92f772e7b5276288d05b94cb96e4d72 | [
"MIT"
] | 4 | 2018-10-11T12:30:46.000Z | 2019-11-12T12:17:17.000Z | code_generate.py | Taekyoon/Python-Mini-C-Compiler | deabdba9f92f772e7b5276288d05b94cb96e4d72 | [
"MIT"
] | null | null | null | code_generate.py | Taekyoon/Python-Mini-C-Compiler | deabdba9f92f772e7b5276288d05b94cb96e4d72 | [
"MIT"
] | null | null | null | from lex import tsymbol_dict
from expression import *
from code_generate_table import *
from code_generate_utils import *
class CodeGenerator(object):
def __init__(self, tree):
self.tree = tree
self.base, self.offset, self.width = 1, 1, 1
self.TERMINAL, self.NONTERMINAL = 0, 1
self.lvalue, self.rvalue = None, None
self.labelNum = 0
self.opcodeName = opcodeName
self.symbolTable = list()
self.symLevel = 0
self.ucode_str = ""
def generate(self):
ptr = self.tree
self.initSymbolTable()
p = ptr.son
while p:
if p.token["type"] == nodeNumber.DCL:
self.processDeclaration(p.son)
elif p.token["type"] == nodeNumber.FUNC_DEF:
self.processFuncHeader(p.son)
else:
icg_error(3)
p = p.brother
globalSize = self.offset - 1
p = ptr.son
while p:
if p.token["type"] == nodeNumber.FUNC_DEF:
self.processFunction(p)
p = p.brother
self.emit1(opcode.bgn, globalSize)
self.emit0(opcode.ldp)
self.emitJump(opcode.call, "main")
self.emit0(opcode.endop)
def initSymbolTable(self):
self.symbolTable.clear()
### DECLARATION
def insert(self, name, typeSpecifier, typeQualifier, base, offset, width, initialValue):
item = {"name": name,
"typeSpecifier": typeSpecifier,
"typeQualifier": typeQualifier,
"base": base,
"offset": offset,
"width": width,
"initialValue": initialValue,
"level": self.symLevel}
self.symbolTable.append(item)
def processDeclaration(self, ptr):
if not ptr.token["type"] == nodeNumber.DCL_SPEC:
raise AttributeError("icg_error(4)")
typeSpecifier = typeEnum.INT_TYPE
typeQualifier = typeEnum.VAR_TYPE
p = ptr.son
while p:
if p.token["type"] == nodeNumber.INT_NODE:
typeSpecifier = typeEnum.INT_TYPE
elif p.token["type"] == nodeNumber.CONST_NODE:
typeQualifier = typeEnum.CONST_TYPE
else:
print("processDeclaration: not yet implemented")
p = p.brother
p = ptr.brother
if not p.token["type"] == nodeNumber.DCL_ITEM:
raise AttributeError("icg_error")
switch_case = {nodeNumber.SIMPLE_VAR: self.processSimpleVariable,
nodeNumber.ARRAY_VAR: self.processArrayVariable}
while p:
q = p.son
token_number = q.token["type"]
if token_number in switch_case:
switch_case[token_number](q, typeSpecifier, typeQualifier)
else:
print("error in SIMPLE_VAR or ARRAY_VAR")
p = p.brother
def processSimpleVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
q = ptr.brother
sign = 1
if not ptr.token["type"] == nodeNumber.SIMPLE_VAR:
print("error in SIMPLE_VAR")
if typeQualifier == typeEnum.CONST_TYPE:
if q is None:
print(ptr.son.token["value"], " must have a constant value")
return
if q.token["type"] == nodeNumber.UNARY_MINUS:
sign = -1
q = q.son
initialValue = sign * q.token["value"]
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
0, 0, 0, initialValue)
else:
size = typeSize(typeSpecifier)
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
self.base, self.offset, self.width, 0)
self.offset += size
def processArrayVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
if not ptr.token["type"] == nodeNumber.ARRAY_VAR:
print("error in ARRAY_VAR")
return
if p.brother is None:
print("array size must be specified")
else:
size = int(p.brother.token["value"])
size *= typeSize(typeSpecifier)
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
self.base, self.offset, size, 0)
self.offset += size
### EXPRESSION
def lookup(self, name):
for i, item in enumerate(self.symbolTable):
print(item["name"], self.symLevel, item["level"])
if item["name"] == name and item["level"] == self.symLevel:
return i
return -1
def emit0(self, opcode):
self.ucode_str += " {}\n".format(self.opcodeName[opcode])
def emit1(self, opcode, operand):
self.ucode_str += " {} {}\n".format(self.opcodeName[opcode], operand)
def emit2(self, opcode, operand1, operand2):
self.ucode_str += " {} {} {}\n".format(self.opcodeName[opcode], operand1, operand2)
def emit3(self, opcode, operand1, operand2, operand3):
self.ucode_str += " {} {} {} {}\n".format(self.opcodeName[opcode], operand1, operand2, operand3)
def emitJump(self, opcode, label):
self.ucode_str += " {} {}\n".format(self.opcodeName[opcode], label)
def rv_emit(self, ptr):
if ptr.token["type"] == tsymbol_dict["tnumber"]:
self.emit1(opcode.ldc, ptr.token["value"])
else:
stIndex = self.lookup(ptr.token["value"])
if stIndex == -1:
return
if self.symbolTable[stIndex]["typeQualifier"] == typeEnum.CONST_TYPE:
self.emit1(opcode.ldc, self.symbolTable[stIndex]["initialValue"])
elif self.symbolTable[stIndex]["width"] > 1:
self.emit2(opcode.lda, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
else:
self.emit2(opcode.lod, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
def read_emit(self, ptr):
if ptr.token["type"] == tsymbol_dict["tnumber"]:
self.emit1(opcode.ldc, ptr.token["value"])
else:
stIndex = self.lookup(ptr.token["value"])
if stIndex == -1:
return
if self.symbolTable[stIndex]["typeQualifier"] == typeEnum.CONST_TYPE:
self.emit1(opcode.ldc, self.symbolTable[stIndex]["initialValue"])
else:
self.emit2(opcode.lda, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
def processOperator(self, ptr):
token_number = ptr.token["type"]
if token_number == nodeNumber.ASSIGN_OP:
lhs, rhs = ptr.son, ptr.son.brother
if lhs.noderep == self.NONTERMINAL:
self.lvalue = 1
self.processOperator(lhs)
self.lvalue = 0
if rhs.noderep == self.NONTERMINAL:
self.processOperator(rhs)
else:
self.rv_emit(rhs)
if lhs.noderep == self.TERMINAL:
stIndex = self.lookup(lhs.token["value"])
if stIndex == -1:
print("undefined variable : ", lhs.token["value"])
return
self.emit2(opcode._str, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"]) ### Need to fill out
else:
self.emit0(opcode.sti) ### Need to fill out
elif token_number == nodeNumber.ADD_ASSIGN or\
token_number == nodeNumber.SUB_ASSIGN or\
token_number == nodeNumber.MUL_ASSIGN or\
token_number == nodeNumber.DIV_ASSIGN or\
token_number == nodeNumber.MOD_ASSIGN:
lhs, rhs = ptr.son, ptr.son.brother
current_nodeNumber = ptr.token["type"]
ptr.token["type"] = nodeNumber.ASSIGN_OP
if lhs.noderep == self.NONTERMINAL:
self.lvalue = 1
self.processOperator(lhs)
self.lvalue = 0
ptr.token["type"] = current_nodeNumber
if lhs.noderep == self.NONTERMINAL:
self.processOperator(lhs)
else:
self.rv_emit(lhs)
if rhs.noderep == self.NONTERMINAL:
self.processOperator(rhs)
else:
self.rv_emit(rhs)
# step 4
if token_number == nodeNumber.ADD_ASSIGN: self.emit0(opcode.add)
elif token_number == nodeNumber.SUB_ASSIGN: self.emit0(opcode.sub)
elif token_number == nodeNumber.MUL_ASSIGN: self.emit0(opcode.mult)
elif token_number == nodeNumber.DIV_ASSIGN: self.emit0(opcode.divop)
elif token_number == nodeNumber.MOD_ASSIGN: self.emit0(opcode.modop)
# step 5
if lhs.noderep == self.TERMINAL:
stIndex = self.lookup(lhs.token["value"])
if stIndex == -1:
print("undefined variable : ", lhs.son.token["value"])
return
self.emit2(opcode._str, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
else:
self.emit0(opcode.sti)
elif token_number == nodeNumber.ADD or token_number == nodeNumber.SUB or\
token_number == nodeNumber.MUL or token_number == nodeNumber.DIV or\
token_number == nodeNumber.MOD or token_number == nodeNumber.EQ or\
token_number == nodeNumber.NE or token_number == nodeNumber.GT or\
token_number == nodeNumber.GE or token_number == nodeNumber.LT or\
token_number == nodeNumber.LE or\
token_number == nodeNumber.LOGICAL_AND or\
token_number == nodeNumber.LOGICAL_OR:
lhs, rhs = ptr.son, ptr.son.brother
if lhs.noderep == self.NONTERMINAL:
self.processOperator(lhs)
else:
self.rv_emit(lhs)
if rhs.noderep == self.NONTERMINAL:
self.processOperator(rhs)
else:
self.rv_emit(rhs)
# step 3
if token_number == nodeNumber.ADD: self.emit0(opcode.add)
elif token_number == nodeNumber.SUB: self.emit0(opcode.sub)
elif token_number == nodeNumber.MUL: self.emit0(opcode.mult)
elif token_number == nodeNumber.DIV: self.emit0(opcode.divop)
elif token_number == nodeNumber.MOD: self.emit0(opcode.modop)
elif token_number == nodeNumber.EQ: self.emit0(opcode.eq)
elif token_number == nodeNumber.NE: self.emit0(opcode.ne)
elif token_number == nodeNumber.GT: self.emit0(opcode.gt)
elif token_number == nodeNumber.LT: self.emit0(opcode.lt)
elif token_number == nodeNumber.GE: self.emit0(opcode.ge)
elif token_number == nodeNumber.LE: self.emit0(opcode.le)
elif token_number == nodeNumber.LOGICAL_AND: self.emit0(opcode.andop)
elif token_number == nodeNumber.LOGICAL_OR: self.emit0(opcode.orop)
elif token_number == nodeNumber.UNARY_MINUS or\
token_number == nodeNumber.LOGICAL_NOT:
p = ptr.son
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
if token_number == nodeNumber.UNARY_MINUS: self.emit0(opcode.neg)
elif token_number == nodeNumber.LOGICAL_NOT: self.emit0(opcode.notop)
## switch something
elif token_number == nodeNumber.PRE_INC or token_number == nodeNumber.PRE_DEC or\
token_number == nodeNumber.POST_INC or token_number == nodeNumber.POST_DEC:
p = ptr.son
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
q = p
while not q.noderep == self.TERMINAL:
q = q.son
if q is None or not q.token["type"] == tsymbol_dict["tident"]:
print("increment/decrement operators can not be applied in expression")
return
stIndex = self.lookup(q.token["value"])
if stIndex == -1:
return
if token_number == nodeNumber.PRE_INC or token_number == nodeNumber.POST_INC:
self.emit0(opcode.incop)
elif token_number == nodeNumber.PRE_DEC or token_number == nodeNumber.POST_DEC:
self.emit0(opcode.decop)
if p.noderep == self.TERMINAL:
stIndex = self.lookup(p.token["value"])
if stIndex == -1:
return
self.emit2(opcode._str, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"]) # Need to do
elif p.token["type"] == nodeNumber.INDEX:
self.lvalue = 1
self.processOperator(p)
self.lvalue = 0
self.emit0(opcode.swp)
self.emit0(opcode.sti)
else:
print("error in increment/decrement operators")
elif token_number == nodeNumber.INDEX:
indexExp = ptr.son.brother
if indexExp.noderep == self.NONTERMINAL:
self.processOperator(indexExp)
else:
self.rv_emit(indexExp)
stIndex = self.lookup(ptr.son.token["value"])
if stIndex == -1:
print("undefined variable: ", ptr.son.token["value"])
return
self.emit2(opcode.lda, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
self.emit0(opcode.add)
if self.lvalue == 0:
self.emit0(opcode.ldi)
elif token_number == nodeNumber.CALL:
p = ptr.son
if self.checkPredefined(p):
return
functionName = p.token["value"]
print(functionName)
stIndex = self.lookup(functionName)
print(stIndex)
if stIndex == -1:
return
noArguments = self.symbolTable[stIndex]["width"]
self.emit0(opcode.ldp)
p = p.brother
while p:
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
noArguments -= 1
p = p.brother
if noArguments > 0:
print(functionName, " : too few actual arguments")
if noArguments < 0:
print(functionName, " : too many actual arguments")
self.emitJump(opcode.call, ptr.son.token["value"])
else:
print("processOperator: not yet implemented")
def checkPredefined(self, ptr):
p = None
if ptr.token["value"] == "read":
self.emit0(opcode.ldp)
p = ptr.brother
while p:
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.read_emit(p)
p = p.brother
self.emitJump(opcode.call, "read")
return True
elif ptr.token["value"] == "write":
self.emit0(opcode.ldp)
p = ptr.brother
while p:
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
p = p.brother
self.emitJump(opcode.call, "write")
return True
elif ptr.token["value"] == "lf":
self.emitJump(opcode.call, "lf")
return True
return False
### STATEMENT
def genLabel(self):
ret_str = "$${}".format(self.labelNum)
self.labelNum += 1
return ret_str
def emitLabel(self, label):
self.ucode_str += "{:11}{}\n".format(label, "nop")
def processCondition(self, ptr):
if ptr.noderep == self.NONTERMINAL:
self.processOperator(ptr)
else:
self.rv_emit(ptr)
def processStatement(self, ptr):
token_number = ptr.token["type"]
if token_number == nodeNumber.COMPOUND_ST:
p = ptr.son.brother
p = p.son
while p:
self.processStatement(p)
p = p.brother
elif token_number == nodeNumber.EXP_ST:
if ptr.son is not None:
self.processOperator(ptr.son)
elif token_number == nodeNumber.RETURN_ST:
if ptr.son is not None:
returnWithValue = 1
p = ptr.son
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
self.emit0(opcode.retv)
else:
self.emit0(opcode.ret)
elif token_number == nodeNumber.IF_ST:
label = self.genLabel()
self.processCondition(ptr.son)
self.emitJump(opcode.fjp, label)
self.processStatement(ptr.son.brother)
self.emitLabel(label)
elif token_number == nodeNumber.IF_ELSE_ST:
label1, label2 = self.genLabel(), self.genLabel()
self.processCondition(ptr.son)
self.emitJump(opcode.fjp, label1)
self.processStatement(ptr.son.brother)
self.emitJump(opcode.ujp, label2)
self.emitLabel(label1)
self.processStatement(ptr.son.brother.brother)
self.emitLabel(label2)
elif token_number == nodeNumber.WHILE_ST:
label1, label2 = self.genLabel(), self.genLabel()
self.emitLabel(label1)
self.processCondition(ptr.son)
self.emitJump(opcode.fjp, label2)
self.processStatement(ptr.son.brother)
self.emitJump(opcode.ujp, label1)
self.emitLabel(label2)
else:
print("processStatement: not yet implemented.")
print_part_tree(ptr)
raise AttributeError("Bang!")
### FUNCTION
def processSimpleParamVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
if not ptr.token["type"] == nodeNumber.SIMPLE_VAR:
print("error in SIMPLE_VAR")
size = typeSize(typeSpecifier)
stindex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
self.base, self.offset, 0, 0)
self.offset += size
def processArrayParamVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
if not ptr.token["type"] == nodeNumber.ARRAY_VAR:
print("error in ARRAY_VAR")
return
size = typeSize(typeSpecifier)
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
base, offset, width, 0)
offset += size
def processParamDeclaration(self, ptr):
if not ptr.token["type"] == nodeNumber.DCL_SPEC:
icg_error(4)
typeSpecifier = typeEnum.INT_TYPE
typeQualifier = typeEnum.VAR_TYPE
p = ptr.son
while p:
if p.token["type"] == nodeNumber.INT_NODE:
typeSpecifier = typeEnum.INT_TYPE
elif p.token["type"] == nodeNumber.CONST_NODE:
typeQualifier = typeEnum.CONST_TYPE
else:
print("processParamDeclaration: not yet implemented")
p = p.brother
p = ptr.brother
token_number = p.token["type"]
if token_number == nodeNumber.SIMPLE_VAR:
self.processSimpleParamVariable(p, typeSpecifier, typeQualifier)
elif token_number == nodeNumber.ARRAY_VAR:
self.processArrayParamVariable(p, typeSpecifier, typeQualifier)
else:
print(token_number, nodeNumber.SIMPLE_VAR, nodeNumber.ARRAY_VAR)
print("error in SIMPLE_VAR or ARRAY_VAR")
def emitFunc(self, FuncName, operand1, operand2, operand3):
self.ucode_str += "{:11}{} {} {} {}\n".format(FuncName, "fun", operand1, operand2, operand3)
def processFuncHeader(self, ptr):
if not ptr.token["type"] == nodeNumber.FUNC_HEAD:
print("error in processFuncHeader")
p = ptr.son.son
while p:
if p.token["type"] == nodeNumber.INT_NODE:
returnType = typeEnum.INT_TYPE
elif p.token["type"] == nodeNumber.VOID_NODE:
returnType = typeEnum.VOID_TYPE
else:
print("invalid function return type")
p = p.brother
p = ptr.son.brother.brother
p = p.son
noArguments = 0
while p:
noArguments += 1
p = p.brother
stIndex = self.insert(ptr.son.brother.token["value"], returnType,
typeEnum.FUNC_TYPE, 1, 0, noArguments, 0)
def processFunction(self, ptr):
sizeOfVar, numOfVar = 0, 0
self.base += 1
self.offset = 1
if not ptr.token["type"] == nodeNumber.FUNC_DEF:
icg_error(4)
p = ptr.son.son.brother.brother
p = p.son
while p:
if p.token["type"] == nodeNumber.PARAM_DCL:
self.processParamDeclaration(p.son)
sizeOfVar += 1
numOfVar += 1
p = p.brother
p = ptr.son.brother.son.son
while p:
if p.token["type"] == nodeNumber.DCL:
self.processDeclaration(p.son)
q = p.son.brother
while q:
if q.token["type"] == nodeNumber.DCL_ITEM:
if q.son.token["type"] == nodeNumber.ARRAY_VAR:
sizeOfVar += int(q.son.son.brother.token["value"])
else:
sizeOfVar += 1
numOfVar += 1
q = q.brother
p = p.brother
p = ptr.son.son.brother
self.emitFunc(p.token["value"], sizeOfVar, self.base, 2)
for stIndex in range(len(self.symbolTable)-numOfVar, len(self.symbolTable)):
self.emit3(opcode.sym, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"],
self.symbolTable[stIndex]["width"])
p = ptr.son.brother
self.processStatement(p)
p = ptr.son.son
if p.token["type"] == nodeNumber.DCL_SPEC:
p = p.son
if p.token["type"] == nodeNumber.VOID_NODE:
self.emit0(opcode.ret)
elif p.token["type"] == nodeNumber.CONST_NODE:
if p.brother.token["type"] == nodeNumber.VOID_NODE:
self.emit0(opcode.ret)
self.emit0(opcode.endop)
self.base -= 1
#self.symLevel += 1
def write_code_to_file(self, file_name):
file_name = file_name + ".uco"
with open(file_name, 'w') as f:
f.write(self.ucode_str)
| 36.887302 | 132 | 0.547399 | from lex import tsymbol_dict
from expression import *
from code_generate_table import *
from code_generate_utils import *
class CodeGenerator(object):
def __init__(self, tree):
self.tree = tree
self.base, self.offset, self.width = 1, 1, 1
self.TERMINAL, self.NONTERMINAL = 0, 1
self.lvalue, self.rvalue = None, None
self.labelNum = 0
self.opcodeName = opcodeName
self.symbolTable = list()
self.symLevel = 0
self.ucode_str = ""
def generate(self):
ptr = self.tree
self.initSymbolTable()
p = ptr.son
while p:
if p.token["type"] == nodeNumber.DCL:
self.processDeclaration(p.son)
elif p.token["type"] == nodeNumber.FUNC_DEF:
self.processFuncHeader(p.son)
else:
icg_error(3)
p = p.brother
globalSize = self.offset - 1
p = ptr.son
while p:
if p.token["type"] == nodeNumber.FUNC_DEF:
self.processFunction(p)
p = p.brother
self.emit1(opcode.bgn, globalSize)
self.emit0(opcode.ldp)
self.emitJump(opcode.call, "main")
self.emit0(opcode.endop)
def initSymbolTable(self):
self.symbolTable.clear()
typeSpecifier, typeQualifier, base, offset, width, initialValue):
item = {"name": name,
"typeSpecifier": typeSpecifier,
"typeQualifier": typeQualifier,
"base": base,
"offset": offset,
"width": width,
"initialValue": initialValue,
"level": self.symLevel}
self.symbolTable.append(item)
def processDeclaration(self, ptr):
if not ptr.token["type"] == nodeNumber.DCL_SPEC:
raise AttributeError("icg_error(4)")
typeSpecifier = typeEnum.INT_TYPE
typeQualifier = typeEnum.VAR_TYPE
p = ptr.son
while p:
if p.token["type"] == nodeNumber.INT_NODE:
typeSpecifier = typeEnum.INT_TYPE
elif p.token["type"] == nodeNumber.CONST_NODE:
typeQualifier = typeEnum.CONST_TYPE
else:
print("processDeclaration: not yet implemented")
p = p.brother
p = ptr.brother
if not p.token["type"] == nodeNumber.DCL_ITEM:
raise AttributeError("icg_error")
switch_case = {nodeNumber.SIMPLE_VAR: self.processSimpleVariable,
nodeNumber.ARRAY_VAR: self.processArrayVariable}
while p:
q = p.son
token_number = q.token["type"]
if token_number in switch_case:
switch_case[token_number](q, typeSpecifier, typeQualifier)
else:
print("error in SIMPLE_VAR or ARRAY_VAR")
p = p.brother
def processSimpleVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
q = ptr.brother
sign = 1
if not ptr.token["type"] == nodeNumber.SIMPLE_VAR:
print("error in SIMPLE_VAR")
if typeQualifier == typeEnum.CONST_TYPE:
if q is None:
print(ptr.son.token["value"], " must have a constant value")
return
if q.token["type"] == nodeNumber.UNARY_MINUS:
sign = -1
q = q.son
initialValue = sign * q.token["value"]
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
0, 0, 0, initialValue)
else:
size = typeSize(typeSpecifier)
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
self.base, self.offset, self.width, 0)
self.offset += size
def processArrayVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
if not ptr.token["type"] == nodeNumber.ARRAY_VAR:
print("error in ARRAY_VAR")
return
if p.brother is None:
print("array size must be specified")
else:
size = int(p.brother.token["value"])
size *= typeSize(typeSpecifier)
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
self.base, self.offset, size, 0)
self.offset += size
me):
for i, item in enumerate(self.symbolTable):
print(item["name"], self.symLevel, item["level"])
if item["name"] == name and item["level"] == self.symLevel:
return i
return -1
def emit0(self, opcode):
self.ucode_str += " {}\n".format(self.opcodeName[opcode])
def emit1(self, opcode, operand):
self.ucode_str += " {} {}\n".format(self.opcodeName[opcode], operand)
def emit2(self, opcode, operand1, operand2):
self.ucode_str += " {} {} {}\n".format(self.opcodeName[opcode], operand1, operand2)
def emit3(self, opcode, operand1, operand2, operand3):
self.ucode_str += " {} {} {} {}\n".format(self.opcodeName[opcode], operand1, operand2, operand3)
def emitJump(self, opcode, label):
self.ucode_str += " {} {}\n".format(self.opcodeName[opcode], label)
def rv_emit(self, ptr):
if ptr.token["type"] == tsymbol_dict["tnumber"]:
self.emit1(opcode.ldc, ptr.token["value"])
else:
stIndex = self.lookup(ptr.token["value"])
if stIndex == -1:
return
if self.symbolTable[stIndex]["typeQualifier"] == typeEnum.CONST_TYPE:
self.emit1(opcode.ldc, self.symbolTable[stIndex]["initialValue"])
elif self.symbolTable[stIndex]["width"] > 1:
self.emit2(opcode.lda, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
else:
self.emit2(opcode.lod, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
def read_emit(self, ptr):
if ptr.token["type"] == tsymbol_dict["tnumber"]:
self.emit1(opcode.ldc, ptr.token["value"])
else:
stIndex = self.lookup(ptr.token["value"])
if stIndex == -1:
return
if self.symbolTable[stIndex]["typeQualifier"] == typeEnum.CONST_TYPE:
self.emit1(opcode.ldc, self.symbolTable[stIndex]["initialValue"])
else:
self.emit2(opcode.lda, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
def processOperator(self, ptr):
token_number = ptr.token["type"]
if token_number == nodeNumber.ASSIGN_OP:
lhs, rhs = ptr.son, ptr.son.brother
if lhs.noderep == self.NONTERMINAL:
self.lvalue = 1
self.processOperator(lhs)
self.lvalue = 0
if rhs.noderep == self.NONTERMINAL:
self.processOperator(rhs)
else:
self.rv_emit(rhs)
if lhs.noderep == self.TERMINAL:
stIndex = self.lookup(lhs.token["value"])
if stIndex == -1:
print("undefined variable : ", lhs.token["value"])
return
self.emit2(opcode._str, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"]) lf.emit0(opcode.sti) mber.ADD_ASSIGN or\
token_number == nodeNumber.SUB_ASSIGN or\
token_number == nodeNumber.MUL_ASSIGN or\
token_number == nodeNumber.DIV_ASSIGN or\
token_number == nodeNumber.MOD_ASSIGN:
lhs, rhs = ptr.son, ptr.son.brother
current_nodeNumber = ptr.token["type"]
ptr.token["type"] = nodeNumber.ASSIGN_OP
if lhs.noderep == self.NONTERMINAL:
self.lvalue = 1
self.processOperator(lhs)
self.lvalue = 0
ptr.token["type"] = current_nodeNumber
if lhs.noderep == self.NONTERMINAL:
self.processOperator(lhs)
else:
self.rv_emit(lhs)
if rhs.noderep == self.NONTERMINAL:
self.processOperator(rhs)
else:
self.rv_emit(rhs)
if token_number == nodeNumber.ADD_ASSIGN: self.emit0(opcode.add)
elif token_number == nodeNumber.SUB_ASSIGN: self.emit0(opcode.sub)
elif token_number == nodeNumber.MUL_ASSIGN: self.emit0(opcode.mult)
elif token_number == nodeNumber.DIV_ASSIGN: self.emit0(opcode.divop)
elif token_number == nodeNumber.MOD_ASSIGN: self.emit0(opcode.modop)
if lhs.noderep == self.TERMINAL:
stIndex = self.lookup(lhs.token["value"])
if stIndex == -1:
print("undefined variable : ", lhs.son.token["value"])
return
self.emit2(opcode._str, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
else:
self.emit0(opcode.sti)
elif token_number == nodeNumber.ADD or token_number == nodeNumber.SUB or\
token_number == nodeNumber.MUL or token_number == nodeNumber.DIV or\
token_number == nodeNumber.MOD or token_number == nodeNumber.EQ or\
token_number == nodeNumber.NE or token_number == nodeNumber.GT or\
token_number == nodeNumber.GE or token_number == nodeNumber.LT or\
token_number == nodeNumber.LE or\
token_number == nodeNumber.LOGICAL_AND or\
token_number == nodeNumber.LOGICAL_OR:
lhs, rhs = ptr.son, ptr.son.brother
if lhs.noderep == self.NONTERMINAL:
self.processOperator(lhs)
else:
self.rv_emit(lhs)
if rhs.noderep == self.NONTERMINAL:
self.processOperator(rhs)
else:
self.rv_emit(rhs)
if token_number == nodeNumber.ADD: self.emit0(opcode.add)
elif token_number == nodeNumber.SUB: self.emit0(opcode.sub)
elif token_number == nodeNumber.MUL: self.emit0(opcode.mult)
elif token_number == nodeNumber.DIV: self.emit0(opcode.divop)
elif token_number == nodeNumber.MOD: self.emit0(opcode.modop)
elif token_number == nodeNumber.EQ: self.emit0(opcode.eq)
elif token_number == nodeNumber.NE: self.emit0(opcode.ne)
elif token_number == nodeNumber.GT: self.emit0(opcode.gt)
elif token_number == nodeNumber.LT: self.emit0(opcode.lt)
elif token_number == nodeNumber.GE: self.emit0(opcode.ge)
elif token_number == nodeNumber.LE: self.emit0(opcode.le)
elif token_number == nodeNumber.LOGICAL_AND: self.emit0(opcode.andop)
elif token_number == nodeNumber.LOGICAL_OR: self.emit0(opcode.orop)
elif token_number == nodeNumber.UNARY_MINUS or\
token_number == nodeNumber.LOGICAL_NOT:
p = ptr.son
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
if token_number == nodeNumber.UNARY_MINUS: self.emit0(opcode.neg)
elif token_number == nodeNumber.LOGICAL_NOT: self.emit0(opcode.notop)
n_number == nodeNumber.PRE_INC or token_number == nodeNumber.PRE_DEC or\
token_number == nodeNumber.POST_INC or token_number == nodeNumber.POST_DEC:
p = ptr.son
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
q = p
while not q.noderep == self.TERMINAL:
q = q.son
if q is None or not q.token["type"] == tsymbol_dict["tident"]:
print("increment/decrement operators can not be applied in expression")
return
stIndex = self.lookup(q.token["value"])
if stIndex == -1:
return
if token_number == nodeNumber.PRE_INC or token_number == nodeNumber.POST_INC:
self.emit0(opcode.incop)
elif token_number == nodeNumber.PRE_DEC or token_number == nodeNumber.POST_DEC:
self.emit0(opcode.decop)
if p.noderep == self.TERMINAL:
stIndex = self.lookup(p.token["value"])
if stIndex == -1:
return
self.emit2(opcode._str, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
elif p.token["type"] == nodeNumber.INDEX:
self.lvalue = 1
self.processOperator(p)
self.lvalue = 0
self.emit0(opcode.swp)
self.emit0(opcode.sti)
else:
print("error in increment/decrement operators")
elif token_number == nodeNumber.INDEX:
indexExp = ptr.son.brother
if indexExp.noderep == self.NONTERMINAL:
self.processOperator(indexExp)
else:
self.rv_emit(indexExp)
stIndex = self.lookup(ptr.son.token["value"])
if stIndex == -1:
print("undefined variable: ", ptr.son.token["value"])
return
self.emit2(opcode.lda, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"])
self.emit0(opcode.add)
if self.lvalue == 0:
self.emit0(opcode.ldi)
elif token_number == nodeNumber.CALL:
p = ptr.son
if self.checkPredefined(p):
return
functionName = p.token["value"]
print(functionName)
stIndex = self.lookup(functionName)
print(stIndex)
if stIndex == -1:
return
noArguments = self.symbolTable[stIndex]["width"]
self.emit0(opcode.ldp)
p = p.brother
while p:
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
noArguments -= 1
p = p.brother
if noArguments > 0:
print(functionName, " : too few actual arguments")
if noArguments < 0:
print(functionName, " : too many actual arguments")
self.emitJump(opcode.call, ptr.son.token["value"])
else:
print("processOperator: not yet implemented")
def checkPredefined(self, ptr):
p = None
if ptr.token["value"] == "read":
self.emit0(opcode.ldp)
p = ptr.brother
while p:
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.read_emit(p)
p = p.brother
self.emitJump(opcode.call, "read")
return True
elif ptr.token["value"] == "write":
self.emit0(opcode.ldp)
p = ptr.brother
while p:
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
p = p.brother
self.emitJump(opcode.call, "write")
return True
elif ptr.token["value"] == "lf":
self.emitJump(opcode.call, "lf")
return True
return False
:
ret_str = "$${}".format(self.labelNum)
self.labelNum += 1
return ret_str
def emitLabel(self, label):
self.ucode_str += "{:11}{}\n".format(label, "nop")
def processCondition(self, ptr):
if ptr.noderep == self.NONTERMINAL:
self.processOperator(ptr)
else:
self.rv_emit(ptr)
def processStatement(self, ptr):
token_number = ptr.token["type"]
if token_number == nodeNumber.COMPOUND_ST:
p = ptr.son.brother
p = p.son
while p:
self.processStatement(p)
p = p.brother
elif token_number == nodeNumber.EXP_ST:
if ptr.son is not None:
self.processOperator(ptr.son)
elif token_number == nodeNumber.RETURN_ST:
if ptr.son is not None:
returnWithValue = 1
p = ptr.son
if p.noderep == self.NONTERMINAL:
self.processOperator(p)
else:
self.rv_emit(p)
self.emit0(opcode.retv)
else:
self.emit0(opcode.ret)
elif token_number == nodeNumber.IF_ST:
label = self.genLabel()
self.processCondition(ptr.son)
self.emitJump(opcode.fjp, label)
self.processStatement(ptr.son.brother)
self.emitLabel(label)
elif token_number == nodeNumber.IF_ELSE_ST:
label1, label2 = self.genLabel(), self.genLabel()
self.processCondition(ptr.son)
self.emitJump(opcode.fjp, label1)
self.processStatement(ptr.son.brother)
self.emitJump(opcode.ujp, label2)
self.emitLabel(label1)
self.processStatement(ptr.son.brother.brother)
self.emitLabel(label2)
elif token_number == nodeNumber.WHILE_ST:
label1, label2 = self.genLabel(), self.genLabel()
self.emitLabel(label1)
self.processCondition(ptr.son)
self.emitJump(opcode.fjp, label2)
self.processStatement(ptr.son.brother)
self.emitJump(opcode.ujp, label1)
self.emitLabel(label2)
else:
print("processStatement: not yet implemented.")
print_part_tree(ptr)
raise AttributeError("Bang!")
eParamVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
if not ptr.token["type"] == nodeNumber.SIMPLE_VAR:
print("error in SIMPLE_VAR")
size = typeSize(typeSpecifier)
stindex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
self.base, self.offset, 0, 0)
self.offset += size
def processArrayParamVariable(self, ptr, typeSpecifier, typeQualifier):
p = ptr.son
if not ptr.token["type"] == nodeNumber.ARRAY_VAR:
print("error in ARRAY_VAR")
return
size = typeSize(typeSpecifier)
stIndex = self.insert(p.token["value"], typeSpecifier, typeQualifier,
base, offset, width, 0)
offset += size
def processParamDeclaration(self, ptr):
if not ptr.token["type"] == nodeNumber.DCL_SPEC:
icg_error(4)
typeSpecifier = typeEnum.INT_TYPE
typeQualifier = typeEnum.VAR_TYPE
p = ptr.son
while p:
if p.token["type"] == nodeNumber.INT_NODE:
typeSpecifier = typeEnum.INT_TYPE
elif p.token["type"] == nodeNumber.CONST_NODE:
typeQualifier = typeEnum.CONST_TYPE
else:
print("processParamDeclaration: not yet implemented")
p = p.brother
p = ptr.brother
token_number = p.token["type"]
if token_number == nodeNumber.SIMPLE_VAR:
self.processSimpleParamVariable(p, typeSpecifier, typeQualifier)
elif token_number == nodeNumber.ARRAY_VAR:
self.processArrayParamVariable(p, typeSpecifier, typeQualifier)
else:
print(token_number, nodeNumber.SIMPLE_VAR, nodeNumber.ARRAY_VAR)
print("error in SIMPLE_VAR or ARRAY_VAR")
def emitFunc(self, FuncName, operand1, operand2, operand3):
self.ucode_str += "{:11}{} {} {} {}\n".format(FuncName, "fun", operand1, operand2, operand3)
def processFuncHeader(self, ptr):
if not ptr.token["type"] == nodeNumber.FUNC_HEAD:
print("error in processFuncHeader")
p = ptr.son.son
while p:
if p.token["type"] == nodeNumber.INT_NODE:
returnType = typeEnum.INT_TYPE
elif p.token["type"] == nodeNumber.VOID_NODE:
returnType = typeEnum.VOID_TYPE
else:
print("invalid function return type")
p = p.brother
p = ptr.son.brother.brother
p = p.son
noArguments = 0
while p:
noArguments += 1
p = p.brother
stIndex = self.insert(ptr.son.brother.token["value"], returnType,
typeEnum.FUNC_TYPE, 1, 0, noArguments, 0)
def processFunction(self, ptr):
sizeOfVar, numOfVar = 0, 0
self.base += 1
self.offset = 1
if not ptr.token["type"] == nodeNumber.FUNC_DEF:
icg_error(4)
p = ptr.son.son.brother.brother
p = p.son
while p:
if p.token["type"] == nodeNumber.PARAM_DCL:
self.processParamDeclaration(p.son)
sizeOfVar += 1
numOfVar += 1
p = p.brother
p = ptr.son.brother.son.son
while p:
if p.token["type"] == nodeNumber.DCL:
self.processDeclaration(p.son)
q = p.son.brother
while q:
if q.token["type"] == nodeNumber.DCL_ITEM:
if q.son.token["type"] == nodeNumber.ARRAY_VAR:
sizeOfVar += int(q.son.son.brother.token["value"])
else:
sizeOfVar += 1
numOfVar += 1
q = q.brother
p = p.brother
p = ptr.son.son.brother
self.emitFunc(p.token["value"], sizeOfVar, self.base, 2)
for stIndex in range(len(self.symbolTable)-numOfVar, len(self.symbolTable)):
self.emit3(opcode.sym, self.symbolTable[stIndex]["base"], self.symbolTable[stIndex]["offset"],
self.symbolTable[stIndex]["width"])
p = ptr.son.brother
self.processStatement(p)
p = ptr.son.son
if p.token["type"] == nodeNumber.DCL_SPEC:
p = p.son
if p.token["type"] == nodeNumber.VOID_NODE:
self.emit0(opcode.ret)
elif p.token["type"] == nodeNumber.CONST_NODE:
if p.brother.token["type"] == nodeNumber.VOID_NODE:
self.emit0(opcode.ret)
self.emit0(opcode.endop)
self.base -= 1
def write_code_to_file(self, file_name):
file_name = file_name + ".uco"
with open(file_name, 'w') as f:
f.write(self.ucode_str)
| true | true |
f727c25e97bf1486886310c30e2304cba568c8b8 | 3,816 | py | Python | core/metrics/recall_k.py | overlordmax/PaddleRec | ddf6ec25b228ffde83e6592163d88c3ace9069f0 | [
"Apache-2.0"
] | 1 | 2020-09-29T01:14:22.000Z | 2020-09-29T01:14:22.000Z | core/metrics/recall_k.py | Qdriving/PaddleRec | b4d6ac77450d98a935c6a5d0eba6abbb21b9d06a | [
"Apache-2.0"
] | null | null | null | core/metrics/recall_k.py | Qdriving/PaddleRec | b4d6ac77450d98a935c6a5d0eba6abbb21b9d06a | [
"Apache-2.0"
] | null | null | null | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
import math
import numpy as np
import paddle.fluid as fluid
from paddlerec.core.metric import Metric
from paddle.fluid.layers import accuracy
from paddle.fluid.initializer import Constant
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.layers.tensor import Variable
class RecallK(Metric):
"""
Metric For Fluid Model
"""
def __init__(self, input, label, k=20):
""" """
kwargs = locals()
del kwargs['self']
self.k = k
if not isinstance(input, Variable):
raise ValueError("input must be Variable, but received %s" %
type(input))
if not isinstance(label, Variable):
raise ValueError("label must be Variable, but received %s" %
type(label))
helper = LayerHelper("PaddleRec_RecallK", **kwargs)
batch_accuracy = accuracy(input, label, self.k)
global_ins_cnt, _ = helper.create_or_get_global_variable(
name="ins_cnt", persistable=True, dtype='float32', shape=[1])
global_pos_cnt, _ = helper.create_or_get_global_variable(
name="pos_cnt", persistable=True, dtype='float32', shape=[1])
for var in [global_ins_cnt, global_pos_cnt]:
helper.set_variable_initializer(
var, Constant(
value=0.0, force_cpu=True))
tmp_ones = fluid.layers.fill_constant(
shape=fluid.layers.shape(label), dtype="float32", value=1.0)
batch_ins = fluid.layers.reduce_sum(tmp_ones)
batch_pos = batch_ins * batch_accuracy
helper.append_op(
type="elementwise_add",
inputs={"X": [global_ins_cnt],
"Y": [batch_ins]},
outputs={"Out": [global_ins_cnt]})
helper.append_op(
type="elementwise_add",
inputs={"X": [global_pos_cnt],
"Y": [batch_pos]},
outputs={"Out": [global_pos_cnt]})
self.acc = global_pos_cnt / global_ins_cnt
self._global_metric_state_vars = dict()
self._global_metric_state_vars['ins_cnt'] = (global_ins_cnt.name,
"float32")
self._global_metric_state_vars['pos_cnt'] = (global_pos_cnt.name,
"float32")
metric_name = "Acc(Recall@%d)" % self.k
self.metrics = dict()
self.metrics["InsCnt"] = global_ins_cnt
self.metrics["RecallCnt"] = global_pos_cnt
self.metrics[metric_name] = self.acc
# self.metrics["batch_metrics"] = batch_metrics
def _calculate(self, global_metrics):
for key in self._global_metric_state_vars:
if key not in global_metrics:
raise ValueError("%s not existed" % key)
ins_cnt = global_metrics['ins_cnt'][0]
pos_cnt = global_metrics['pos_cnt'][0]
if ins_cnt == 0:
acc = 0
else:
acc = float(pos_cnt) / ins_cnt
return "InsCnt=%s RecallCnt=%s Acc(Recall@%d)=%s" % (
str(ins_cnt), str(pos_cnt), self.k, str(acc))
def get_result(self):
return self.metrics
| 36.692308 | 74 | 0.612945 |
import math
import numpy as np
import paddle.fluid as fluid
from paddlerec.core.metric import Metric
from paddle.fluid.layers import accuracy
from paddle.fluid.initializer import Constant
from paddle.fluid.layer_helper import LayerHelper
from paddle.fluid.layers.tensor import Variable
class RecallK(Metric):
def __init__(self, input, label, k=20):
kwargs = locals()
del kwargs['self']
self.k = k
if not isinstance(input, Variable):
raise ValueError("input must be Variable, but received %s" %
type(input))
if not isinstance(label, Variable):
raise ValueError("label must be Variable, but received %s" %
type(label))
helper = LayerHelper("PaddleRec_RecallK", **kwargs)
batch_accuracy = accuracy(input, label, self.k)
global_ins_cnt, _ = helper.create_or_get_global_variable(
name="ins_cnt", persistable=True, dtype='float32', shape=[1])
global_pos_cnt, _ = helper.create_or_get_global_variable(
name="pos_cnt", persistable=True, dtype='float32', shape=[1])
for var in [global_ins_cnt, global_pos_cnt]:
helper.set_variable_initializer(
var, Constant(
value=0.0, force_cpu=True))
tmp_ones = fluid.layers.fill_constant(
shape=fluid.layers.shape(label), dtype="float32", value=1.0)
batch_ins = fluid.layers.reduce_sum(tmp_ones)
batch_pos = batch_ins * batch_accuracy
helper.append_op(
type="elementwise_add",
inputs={"X": [global_ins_cnt],
"Y": [batch_ins]},
outputs={"Out": [global_ins_cnt]})
helper.append_op(
type="elementwise_add",
inputs={"X": [global_pos_cnt],
"Y": [batch_pos]},
outputs={"Out": [global_pos_cnt]})
self.acc = global_pos_cnt / global_ins_cnt
self._global_metric_state_vars = dict()
self._global_metric_state_vars['ins_cnt'] = (global_ins_cnt.name,
"float32")
self._global_metric_state_vars['pos_cnt'] = (global_pos_cnt.name,
"float32")
metric_name = "Acc(Recall@%d)" % self.k
self.metrics = dict()
self.metrics["InsCnt"] = global_ins_cnt
self.metrics["RecallCnt"] = global_pos_cnt
self.metrics[metric_name] = self.acc
def _calculate(self, global_metrics):
for key in self._global_metric_state_vars:
if key not in global_metrics:
raise ValueError("%s not existed" % key)
ins_cnt = global_metrics['ins_cnt'][0]
pos_cnt = global_metrics['pos_cnt'][0]
if ins_cnt == 0:
acc = 0
else:
acc = float(pos_cnt) / ins_cnt
return "InsCnt=%s RecallCnt=%s Acc(Recall@%d)=%s" % (
str(ins_cnt), str(pos_cnt), self.k, str(acc))
def get_result(self):
return self.metrics
| true | true |
f727c2bb12990251b7186d56d9373b097441a307 | 4,591 | py | Python | examples/pagination.py | LaudateCorpus1/oci-python-sdk | b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | examples/pagination.py | LaudateCorpus1/oci-python-sdk | b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | examples/pagination.py | LaudateCorpus1/oci-python-sdk | b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | # coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
# This script demonstrates different methods of pagination in the SDK via the oci.pagination module. This module supports:
#
# - Eagerly loading all possible results from a list call
# - Eagerly loading all results from a list call up to a given limit
# - Generators that can be used to lazily iterate over results from a list call. These generators can yield either values/models
# or the raw responses of the call
# - Pagination using raw responses instead of the oci.pagination module
import oci
config = oci.config.from_file()
compartment_id = config["tenancy"]
identity = oci.identity.IdentityClient(config)
# This demonstrates the eager loading of all possible results. This will return an oci.response.Response whose data attribute contains
# a list of all results. The other attributes of the Response object come from the last response received from the service.
print('--------------------------------------------')
print('Eager load all results')
print('--------------------------------------------')
response = oci.pagination.list_call_get_all_results(identity.list_users, compartment_id)
for user in response.data:
print('User: {}'.format(user.name))
# This demonstrates the eager loading of all results up to a given limit. Note that we have to specify a record limit (20) and
# a page size (5)
#
# This will return an oci.response.Response whose data attribute contains a list of all results. The other attributes of the
# Response object come from the last response received from the service.
print('--------------------------------------------')
print('Eager load up to limit')
print('--------------------------------------------')
response = oci.pagination.list_call_get_up_to_limit(identity.list_users, 20, 5, compartment_id)
total_results = 0
for user in response.data:
total_results += 1
print('User: {}'.format(user.name))
print('Total results: {}'.format(total_results))
# This demonstrates lazily loading, via a generator, all results. Here we use a generator which yields values/models via specifying
# the yield_mode as 'record'
print('--------------------------------------------')
print('Lazy load all results - yield values')
print('--------------------------------------------')
for user in oci.pagination.list_call_get_all_results_generator(identity.list_users, 'record', config["tenancy"]):
print('User: {}'.format(user.name))
# The below demonstrates lazily loading, via a generator, results up to a certain limit
print('--------------------------------------------')
print('Lazy load all results - yield raw responses')
print('--------------------------------------------')
response_num = 0
for response in oci.pagination.list_call_get_all_results_generator(identity.list_users, 'response', config["tenancy"]):
response_num += 1
for user in response.data:
print('Response: {}, User: {}'.format(response_num, user.name))
print('--------------------------------------------')
print('Lazy load up to limit - yield values')
print('--------------------------------------------')
total_results = 0
for user in oci.pagination.list_call_get_up_to_limit_generator(identity.list_users, 20, 10, 'record', config["tenancy"]):
total_results += 1
print('User: {}'.format(user.name))
print('Total results: {}'.format(total_results))
print('--------------------------------------------')
print('Lazy load up to limit - yield raw responses')
print('--------------------------------------------')
response_num = 0
total_results = 0
for response in oci.pagination.list_call_get_up_to_limit_generator(identity.list_users, 20, 10, 'response', config["tenancy"]):
response_num += 1
for user in response.data:
total_results += 1
print('Response: {}, User: {}'.format(response_num, user.name))
print('Total results: {}'.format(total_results))
print('--------------------------------------------')
print('Pagination using raw responses')
print('--------------------------------------------')
response = identity.list_users(compartment_id)
users = response.data
while response.has_next_page:
response = identity.list_users(compartment_id, page=response.next_page)
users.extend(response.data)
for u in users:
print('User: {}'.format(u.name))
| 48.840426 | 245 | 0.648007 |
import oci
config = oci.config.from_file()
compartment_id = config["tenancy"]
identity = oci.identity.IdentityClient(config)
print('--------------------------------------------')
print('Eager load all results')
print('--------------------------------------------')
response = oci.pagination.list_call_get_all_results(identity.list_users, compartment_id)
for user in response.data:
print('User: {}'.format(user.name))
print('--------------------------------------------')
print('Eager load up to limit')
print('--------------------------------------------')
response = oci.pagination.list_call_get_up_to_limit(identity.list_users, 20, 5, compartment_id)
total_results = 0
for user in response.data:
total_results += 1
print('User: {}'.format(user.name))
print('Total results: {}'.format(total_results))
print('--------------------------------------------')
print('Lazy load all results - yield values')
print('--------------------------------------------')
for user in oci.pagination.list_call_get_all_results_generator(identity.list_users, 'record', config["tenancy"]):
print('User: {}'.format(user.name))
print('--------------------------------------------')
print('Lazy load all results - yield raw responses')
print('--------------------------------------------')
response_num = 0
for response in oci.pagination.list_call_get_all_results_generator(identity.list_users, 'response', config["tenancy"]):
response_num += 1
for user in response.data:
print('Response: {}, User: {}'.format(response_num, user.name))
print('--------------------------------------------')
print('Lazy load up to limit - yield values')
print('--------------------------------------------')
total_results = 0
for user in oci.pagination.list_call_get_up_to_limit_generator(identity.list_users, 20, 10, 'record', config["tenancy"]):
total_results += 1
print('User: {}'.format(user.name))
print('Total results: {}'.format(total_results))
print('--------------------------------------------')
print('Lazy load up to limit - yield raw responses')
print('--------------------------------------------')
response_num = 0
total_results = 0
for response in oci.pagination.list_call_get_up_to_limit_generator(identity.list_users, 20, 10, 'response', config["tenancy"]):
response_num += 1
for user in response.data:
total_results += 1
print('Response: {}, User: {}'.format(response_num, user.name))
print('Total results: {}'.format(total_results))
print('--------------------------------------------')
print('Pagination using raw responses')
print('--------------------------------------------')
response = identity.list_users(compartment_id)
users = response.data
while response.has_next_page:
response = identity.list_users(compartment_id, page=response.next_page)
users.extend(response.data)
for u in users:
print('User: {}'.format(u.name))
| true | true |
f727c3080a1e1cf10bc6a51628ccb3002fa6f009 | 6,213 | py | Python | slack/webhook/client.py | timgates42/python-slack-sdk | 6339fbe81031c9aec3f95927ac03706fd31f3544 | [
"MIT"
] | null | null | null | slack/webhook/client.py | timgates42/python-slack-sdk | 6339fbe81031c9aec3f95927ac03706fd31f3544 | [
"MIT"
] | null | null | null | slack/webhook/client.py | timgates42/python-slack-sdk | 6339fbe81031c9aec3f95927ac03706fd31f3544 | [
"MIT"
] | null | null | null | import json
import logging
import urllib
from http.client import HTTPResponse
from ssl import SSLContext
from typing import Dict, Union, List, Optional
from urllib.error import HTTPError
from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler
from slack.errors import SlackRequestError
from .internal_utils import _build_body, _build_request_headers, _debug_log_response
from .webhook_response import WebhookResponse
from ..web.classes.attachments import Attachment
from ..web.classes.blocks import Block
class WebhookClient:
logger = logging.getLogger(__name__)
def __init__(
self,
url: str,
timeout: int = 30,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
default_headers: Optional[Dict[str, str]] = None,
):
"""API client for Incoming Webhooks and response_url
:param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX)
:param timeout: request timeout (in seconds)
:param ssl: ssl.SSLContext to use for requests
:param proxy: proxy URL (e.g., localhost:9000, http://localhost:9000)
:param default_headers: request headers to add to all requests
"""
self.url = url
self.timeout = timeout
self.ssl = ssl
self.proxy = proxy
self.default_headers = default_headers if default_headers else {}
def send(
self,
*,
text: Optional[str] = None,
attachments: Optional[List[Union[Dict[str, any], Attachment]]] = None,
blocks: Optional[List[Union[Dict[str, any], Block]]] = None,
response_type: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
) -> WebhookResponse:
"""Performs a Slack API request and returns the result.
:param text: the text message (even when having blocks, setting this as well is recommended as it works as fallback)
:param attachments: a collection of attachments
:param blocks: a collection of Block Kit UI components
:param response_type: the type of message (either 'in_channel' or 'ephemeral')
:param headers: request headers to append only for this request
:return: API response
"""
return self.send_dict(
body={
"text": text,
"attachments": attachments,
"blocks": blocks,
"response_type": response_type,
},
headers=headers,
)
def send_dict(
self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None
) -> WebhookResponse:
"""Performs a Slack API request and returns the result.
:param body: json data structure (it's still a dict at this point),
if you give this argument, body_params and files will be skipped
:param headers: request headers to append only for this request
:return: API response
"""
return self._perform_http_request(
body=_build_body(body),
headers=_build_request_headers(self.default_headers, headers),
)
def _perform_http_request(
self, *, body: Dict[str, any], headers: Dict[str, str]
) -> WebhookResponse:
"""Performs an HTTP request and parses the response.
:param url: a complete URL to send data (e.g., https://hooks.slack.com/XXX)
:param body: request body data
:param headers: complete set of request headers
:return: API response
"""
body = json.dumps(body)
headers["Content-Type"] = "application/json;charset=utf-8"
if self.logger.level <= logging.DEBUG:
self.logger.debug(
f"Sending a request - url: {self.url}, body: {body}, headers: {headers}"
)
try:
url = self.url
opener: Optional[OpenerDirector] = None
# for security (BAN-B310)
if url.lower().startswith("http"):
req = Request(
method="POST", url=url, data=body.encode("utf-8"), headers=headers
)
if self.proxy is not None:
if isinstance(self.proxy, str):
opener = urllib.request.build_opener(
ProxyHandler({"http": self.proxy, "https": self.proxy}),
HTTPSHandler(context=self.ssl),
)
else:
raise SlackRequestError(
f"Invalid proxy detected: {self.proxy} must be a str value"
)
else:
raise SlackRequestError(f"Invalid URL detected: {url}")
# NOTE: BAN-B310 is already checked above
resp: Optional[HTTPResponse] = None
if opener:
resp = opener.open(req, timeout=self.timeout) # skipcq: BAN-B310
else:
resp = urlopen( # skipcq: BAN-B310
req, context=self.ssl, timeout=self.timeout
)
charset: str = resp.headers.get_content_charset() or "utf-8"
response_body: str = resp.read().decode(charset)
resp = WebhookResponse(
url=url,
status_code=resp.status,
body=response_body,
headers=resp.headers,
)
_debug_log_response(self.logger, resp)
return resp
except HTTPError as e:
charset = e.headers.get_content_charset() or "utf-8"
body: str = e.read().decode(charset) # read the response body here
resp = WebhookResponse(
url=url, status_code=e.code, body=body, headers=e.headers,
)
if e.code == 429:
# for backward-compatibility with WebClient (v.2.5.0 or older)
resp.headers["Retry-After"] = resp.headers["retry-after"]
_debug_log_response(self.logger, resp)
return resp
except Exception as err:
self.logger.error(f"Failed to send a request to Slack API server: {err}")
raise err
| 40.607843 | 124 | 0.584259 | import json
import logging
import urllib
from http.client import HTTPResponse
from ssl import SSLContext
from typing import Dict, Union, List, Optional
from urllib.error import HTTPError
from urllib.request import Request, urlopen, OpenerDirector, ProxyHandler, HTTPSHandler
from slack.errors import SlackRequestError
from .internal_utils import _build_body, _build_request_headers, _debug_log_response
from .webhook_response import WebhookResponse
from ..web.classes.attachments import Attachment
from ..web.classes.blocks import Block
class WebhookClient:
logger = logging.getLogger(__name__)
def __init__(
self,
url: str,
timeout: int = 30,
ssl: Optional[SSLContext] = None,
proxy: Optional[str] = None,
default_headers: Optional[Dict[str, str]] = None,
):
self.url = url
self.timeout = timeout
self.ssl = ssl
self.proxy = proxy
self.default_headers = default_headers if default_headers else {}
def send(
self,
*,
text: Optional[str] = None,
attachments: Optional[List[Union[Dict[str, any], Attachment]]] = None,
blocks: Optional[List[Union[Dict[str, any], Block]]] = None,
response_type: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
) -> WebhookResponse:
return self.send_dict(
body={
"text": text,
"attachments": attachments,
"blocks": blocks,
"response_type": response_type,
},
headers=headers,
)
def send_dict(
self, body: Dict[str, any], headers: Optional[Dict[str, str]] = None
) -> WebhookResponse:
return self._perform_http_request(
body=_build_body(body),
headers=_build_request_headers(self.default_headers, headers),
)
def _perform_http_request(
self, *, body: Dict[str, any], headers: Dict[str, str]
) -> WebhookResponse:
body = json.dumps(body)
headers["Content-Type"] = "application/json;charset=utf-8"
if self.logger.level <= logging.DEBUG:
self.logger.debug(
f"Sending a request - url: {self.url}, body: {body}, headers: {headers}"
)
try:
url = self.url
opener: Optional[OpenerDirector] = None
if url.lower().startswith("http"):
req = Request(
method="POST", url=url, data=body.encode("utf-8"), headers=headers
)
if self.proxy is not None:
if isinstance(self.proxy, str):
opener = urllib.request.build_opener(
ProxyHandler({"http": self.proxy, "https": self.proxy}),
HTTPSHandler(context=self.ssl),
)
else:
raise SlackRequestError(
f"Invalid proxy detected: {self.proxy} must be a str value"
)
else:
raise SlackRequestError(f"Invalid URL detected: {url}")
resp: Optional[HTTPResponse] = None
if opener:
resp = opener.open(req, timeout=self.timeout)
else:
resp = urlopen(
req, context=self.ssl, timeout=self.timeout
)
charset: str = resp.headers.get_content_charset() or "utf-8"
response_body: str = resp.read().decode(charset)
resp = WebhookResponse(
url=url,
status_code=resp.status,
body=response_body,
headers=resp.headers,
)
_debug_log_response(self.logger, resp)
return resp
except HTTPError as e:
charset = e.headers.get_content_charset() or "utf-8"
body: str = e.read().decode(charset)
resp = WebhookResponse(
url=url, status_code=e.code, body=body, headers=e.headers,
)
if e.code == 429:
resp.headers["Retry-After"] = resp.headers["retry-after"]
_debug_log_response(self.logger, resp)
return resp
except Exception as err:
self.logger.error(f"Failed to send a request to Slack API server: {err}")
raise err
| true | true |
f727c35e7fd050c837120bd4cb292fd43c9f546f | 73 | py | Python | Codewars/8kyu/reversed-words/Python/solution1.py | RevansChen/online-judge | ad1b07fee7bd3c49418becccda904e17505f3018 | [
"MIT"
] | 7 | 2017-09-20T16:40:39.000Z | 2021-08-31T18:15:08.000Z | Codewars/8kyu/reversed-words/Python/solution1.py | RevansChen/online-judge | ad1b07fee7bd3c49418becccda904e17505f3018 | [
"MIT"
] | null | null | null | Codewars/8kyu/reversed-words/Python/solution1.py | RevansChen/online-judge | ad1b07fee7bd3c49418becccda904e17505f3018 | [
"MIT"
] | null | null | null | # Python - 3.6.0
reverseWords = lambda str: ' '.join(str.split()[::-1])
| 18.25 | 54 | 0.589041 |
reverseWords = lambda str: ' '.join(str.split()[::-1])
| true | true |
f727c565e144343ffc38a97bdeaadb5f3c26c99d | 3,587 | py | Python | restui/lib/alignments.py | brjones/gifts_rest | 8217e45fd1a692b00c9e9ae9f022ac2d2fab211e | [
"Apache-2.0"
] | null | null | null | restui/lib/alignments.py | brjones/gifts_rest | 8217e45fd1a692b00c9e9ae9f022ac2d2fab211e | [
"Apache-2.0"
] | 7 | 2018-09-05T10:53:44.000Z | 2022-03-08T09:36:14.000Z | restui/lib/alignments.py | brjones/gifts_rest | 8217e45fd1a692b00c9e9ae9f022ac2d2fab211e | [
"Apache-2.0"
] | 8 | 2018-09-03T14:29:28.000Z | 2020-07-30T12:54:04.000Z | """
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
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 sam_alignment_reconstructor.pairwise import pairwise_alignment
from sam_alignment_reconstructor.pairwise import cigar_split
from restui.lib.external import ensembl_sequence
from restui.lib.external import ensembl_protein
def fetch_pairwise(mapping):
"""
Function to fetch the pairwise sequence alignment for a given mapping
between a mapped sequence in ensembl and UniProt.
Parameters
----------
mappings
Returns
-------
dict
mapping_id : int
alignments : list
List of the alignments and the matching strings
"""
pairwise_alignments = []
enst = mapping.transcript.enst_id
uniprot_id = mapping.uniprot.uniprot_acc
for alignment in mapping.alignments.all():
if alignment.alignment_run.score1_type == 'identity':
pairwise_alignments.append(
_fetch_alignment(alignment, enst, uniprot_id)
)
# Break out of the loop, we're done
break
elif (
alignment.alignment_run.score1_type == 'perfect_match' and
alignment.score1 == 1
):
pairwise_alignments.append(
_fetch_alignment(alignment, enst, uniprot_id)
)
return {
'mapping_id': mapping.mapping_id,
'alignments': pairwise_alignments
}
def _fetch_alignment(alignment, enst, uniprot_id):
"""
Parameters
----------
alignment
enst : str
uniprot_id : str
Returns
-------
pw_alignment : dict
Alignment object
"""
ens_release = alignment.alignment_run.ensembl_release
ensp = ensembl_protein(enst, ens_release)
seq = ensembl_sequence(ensp, ens_release)
ensembl_seq = seq
uniprot_seq = seq
match_str = '|' * len(seq)
alignment_type = 'perfect_match'
if alignment.alignment_run.score1_type == 'identity':
cigarplus = alignment.pairwise.cigarplus
mdz = alignment.pairwise.mdz
if mdz.startswith('MD:Z:'):
mdz = mdz[len('MD:Z:'):]
uniprot_seq, match_str, ensembl_seq = pairwise_alignment(seq, cigarplus, mdz)
alignment_type = 'identity'
pw_alignment = {
'uniprot_alignment': ensembl_seq,
'ensembl_alignment': uniprot_seq,
'match_str': match_str,
'alignment_id': alignment.alignment_id,
'ensembl_release': ens_release,
'ensembl_id': ensp,
'uniprot_id': uniprot_id,
'alignment_type': alignment_type
}
return pw_alignment
def calculate_difference(cigar):
"""
Calculate the difference between 2 sequences based on the cigar string
Parameters
----------
cigar : str
Returns
-------
diff_count : int
"""
diff_count = 0
for c, op in cigar_split(cigar):
if op in ('I', 'D', 'X'):
diff_count += c
return diff_count
| 26.182482 | 85 | 0.647338 |
from sam_alignment_reconstructor.pairwise import pairwise_alignment
from sam_alignment_reconstructor.pairwise import cigar_split
from restui.lib.external import ensembl_sequence
from restui.lib.external import ensembl_protein
def fetch_pairwise(mapping):
pairwise_alignments = []
enst = mapping.transcript.enst_id
uniprot_id = mapping.uniprot.uniprot_acc
for alignment in mapping.alignments.all():
if alignment.alignment_run.score1_type == 'identity':
pairwise_alignments.append(
_fetch_alignment(alignment, enst, uniprot_id)
)
break
elif (
alignment.alignment_run.score1_type == 'perfect_match' and
alignment.score1 == 1
):
pairwise_alignments.append(
_fetch_alignment(alignment, enst, uniprot_id)
)
return {
'mapping_id': mapping.mapping_id,
'alignments': pairwise_alignments
}
def _fetch_alignment(alignment, enst, uniprot_id):
ens_release = alignment.alignment_run.ensembl_release
ensp = ensembl_protein(enst, ens_release)
seq = ensembl_sequence(ensp, ens_release)
ensembl_seq = seq
uniprot_seq = seq
match_str = '|' * len(seq)
alignment_type = 'perfect_match'
if alignment.alignment_run.score1_type == 'identity':
cigarplus = alignment.pairwise.cigarplus
mdz = alignment.pairwise.mdz
if mdz.startswith('MD:Z:'):
mdz = mdz[len('MD:Z:'):]
uniprot_seq, match_str, ensembl_seq = pairwise_alignment(seq, cigarplus, mdz)
alignment_type = 'identity'
pw_alignment = {
'uniprot_alignment': ensembl_seq,
'ensembl_alignment': uniprot_seq,
'match_str': match_str,
'alignment_id': alignment.alignment_id,
'ensembl_release': ens_release,
'ensembl_id': ensp,
'uniprot_id': uniprot_id,
'alignment_type': alignment_type
}
return pw_alignment
def calculate_difference(cigar):
diff_count = 0
for c, op in cigar_split(cigar):
if op in ('I', 'D', 'X'):
diff_count += c
return diff_count
| true | true |
f727c5f55aa71d5cb21714681206c4fac4c7f6bc | 762 | py | Python | state_management/python/sdk/order-processor/app.py | amulyavarote/quickstarts | c21a8f58d515b28eaa8a3680388fa06995c2331b | [
"Apache-2.0"
] | null | null | null | state_management/python/sdk/order-processor/app.py | amulyavarote/quickstarts | c21a8f58d515b28eaa8a3680388fa06995c2331b | [
"Apache-2.0"
] | null | null | null | state_management/python/sdk/order-processor/app.py | amulyavarote/quickstarts | c21a8f58d515b28eaa8a3680388fa06995c2331b | [
"Apache-2.0"
] | null | null | null | from time import sleep
import logging
from dapr.clients import DaprClient
logging.basicConfig(level=logging.INFO)
DAPR_STORE_NAME = "statestore"
for i in range(1, 10):
orderId = str(i)
order = {'orderId': orderId}
with DaprClient() as client:
# Save state into the state store
client.save_state(DAPR_STORE_NAME, orderId, str(order))
logging.info('Saving Order: %s', order)
# Get state from the state store
result = client.get_state(DAPR_STORE_NAME, orderId)
logging.info('Result after get: ' + str(result.data))
# Delete state from the state store
client.delete_state(store_name=DAPR_STORE_NAME, key=orderId)
logging.info('Deleting Order: %s', order)
sleep(1)
| 29.307692 | 68 | 0.670604 | from time import sleep
import logging
from dapr.clients import DaprClient
logging.basicConfig(level=logging.INFO)
DAPR_STORE_NAME = "statestore"
for i in range(1, 10):
orderId = str(i)
order = {'orderId': orderId}
with DaprClient() as client:
client.save_state(DAPR_STORE_NAME, orderId, str(order))
logging.info('Saving Order: %s', order)
result = client.get_state(DAPR_STORE_NAME, orderId)
logging.info('Result after get: ' + str(result.data))
client.delete_state(store_name=DAPR_STORE_NAME, key=orderId)
logging.info('Deleting Order: %s', order)
sleep(1)
| true | true |
f727c7c44cfc150a303ad06b4cd37d80fe4a6d31 | 3,598 | py | Python | thomasdevri_es/thomasdevri_es/settings.py | jdevries3133/chaotic_christmas_present | c7ef3f9a8fdef43211c59398b6bb9b45383cdc0d | [
"Apache-2.0"
] | null | null | null | thomasdevri_es/thomasdevri_es/settings.py | jdevries3133/chaotic_christmas_present | c7ef3f9a8fdef43211c59398b6bb9b45383cdc0d | [
"Apache-2.0"
] | null | null | null | thomasdevri_es/thomasdevri_es/settings.py | jdevries3133/chaotic_christmas_present | c7ef3f9a8fdef43211c59398b6bb9b45383cdc0d | [
"Apache-2.0"
] | null | null | null | """
Django settings for thomasdevri_es project.
Generated by 'django-admin startproject' using Django 3.0.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('DJANGO_SECRET')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'*'
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'staff',
'sql_vulnerable',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'thomasdevri_es.urls'
LOGIN_URL = '/staff/login/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'thomasdevri_es.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': 'django.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
}
| 24.47619 | 91 | 0.663424 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = os.getenv('DJANGO_SECRET')
DEBUG = False
ALLOWED_HOSTS = [
'*'
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'staff',
'sql_vulnerable',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'thomasdevri_es.urls'
LOGIN_URL = '/staff/login/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'thomasdevri_es.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'INFO',
'class': 'logging.FileHandler',
'filename': 'django.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'INFO',
'propagate': True,
},
},
}
| true | true |
f727c8673af3cda14875414f836d4092d8d30ac1 | 6,282 | py | Python | compose/container.py | alunduil/fig | fc63454c99674b3758721bcc5df0cea841ed6ba5 | [
"Apache-2.0"
] | null | null | null | compose/container.py | alunduil/fig | fc63454c99674b3758721bcc5df0cea841ed6ba5 | [
"Apache-2.0"
] | null | null | null | compose/container.py | alunduil/fig | fc63454c99674b3758721bcc5df0cea841ed6ba5 | [
"Apache-2.0"
] | null | null | null | from __future__ import absolute_import
from __future__ import unicode_literals
from functools import reduce
import six
from .const import LABEL_CONTAINER_NUMBER
from .const import LABEL_SERVICE
class Container(object):
"""
Represents a Docker container, constructed from the output of
GET /containers/:id:/json.
"""
def __init__(self, client, dictionary, has_been_inspected=False):
self.client = client
self.dictionary = dictionary
self.has_been_inspected = has_been_inspected
@classmethod
def from_ps(cls, client, dictionary, **kwargs):
"""
Construct a container object from the output of GET /containers/json.
"""
name = get_container_name(dictionary)
if name is None:
return None
new_dictionary = {
'Id': dictionary['Id'],
'Image': dictionary['Image'],
'Name': '/' + name,
}
return cls(client, new_dictionary, **kwargs)
@classmethod
def from_id(cls, client, id):
return cls(client, client.inspect_container(id))
@classmethod
def create(cls, client, **options):
response = client.create_container(**options)
return cls.from_id(client, response['Id'])
@property
def id(self):
return self.dictionary['Id']
@property
def image(self):
return self.dictionary['Image']
@property
def image_config(self):
return self.client.inspect_image(self.image)
@property
def short_id(self):
return self.id[:10]
@property
def name(self):
return self.dictionary['Name'][1:]
@property
def name_without_project(self):
return '{0}_{1}'.format(self.labels.get(LABEL_SERVICE), self.number)
@property
def number(self):
number = self.labels.get(LABEL_CONTAINER_NUMBER)
if not number:
raise ValueError("Container {0} does not have a {1} label".format(
self.short_id, LABEL_CONTAINER_NUMBER))
return int(number)
@property
def ports(self):
self.inspect_if_not_inspected()
return self.get('NetworkSettings.Ports') or {}
@property
def human_readable_ports(self):
def format_port(private, public):
if not public:
return private
return '{HostIp}:{HostPort}->{private}'.format(
private=private, **public[0])
return ', '.join(format_port(*item)
for item in sorted(six.iteritems(self.ports)))
@property
def labels(self):
return self.get('Config.Labels') or {}
@property
def log_config(self):
return self.get('HostConfig.LogConfig') or None
@property
def human_readable_state(self):
if self.is_paused:
return 'Paused'
if self.is_running:
return 'Ghost' if self.get('State.Ghost') else 'Up'
else:
return 'Exit %s' % self.get('State.ExitCode')
@property
def human_readable_command(self):
entrypoint = self.get('Config.Entrypoint') or []
cmd = self.get('Config.Cmd') or []
return ' '.join(entrypoint + cmd)
@property
def environment(self):
return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
@property
def is_running(self):
return self.get('State.Running')
@property
def is_paused(self):
return self.get('State.Paused')
def get(self, key):
"""Return a value from the container or None if the value is not set.
:param key: a string using dotted notation for nested dictionary
lookups
"""
self.inspect_if_not_inspected()
def get_value(dictionary, key):
return (dictionary or {}).get(key)
return reduce(get_value, key.split('.'), self.dictionary)
def get_local_port(self, port, protocol='tcp'):
port = self.ports.get("%s/%s" % (port, protocol))
return "{HostIp}:{HostPort}".format(**port[0]) if port else None
def start(self, **options):
return self.client.start(self.id, **options)
def stop(self, **options):
return self.client.stop(self.id, **options)
def pause(self, **options):
return self.client.pause(self.id, **options)
def unpause(self, **options):
return self.client.unpause(self.id, **options)
def kill(self, **options):
return self.client.kill(self.id, **options)
def restart(self, **options):
return self.client.restart(self.id, **options)
def remove(self, **options):
return self.client.remove_container(self.id, **options)
def inspect_if_not_inspected(self):
if not self.has_been_inspected:
self.inspect()
def wait(self):
return self.client.wait(self.id)
def logs(self, *args, **kwargs):
return self.client.logs(self.id, *args, **kwargs)
def inspect(self):
self.dictionary = self.client.inspect_container(self.id)
self.has_been_inspected = True
return self.dictionary
# TODO: only used by tests, move to test module
def links(self):
links = []
for container in self.client.containers():
for name in container['Names']:
bits = name.split('/')
if len(bits) > 2 and bits[1] == self.name:
links.append(bits[2])
return links
def attach(self, *args, **kwargs):
return self.client.attach(self.id, *args, **kwargs)
def attach_socket(self, **kwargs):
return self.client.attach_socket(self.id, **kwargs)
def __repr__(self):
return '<Container: %s (%s)>' % (self.name, self.id[:6])
def __eq__(self, other):
if type(self) != type(other):
return False
return self.id == other.id
def __hash__(self):
return self.id.__hash__()
def get_container_name(container):
if not container.get('Name') and not container.get('Names'):
return None
# inspect
if 'Name' in container:
return container['Name']
# ps
shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
return shortest_name.split('/')[-1]
| 28.554545 | 78 | 0.60554 | from __future__ import absolute_import
from __future__ import unicode_literals
from functools import reduce
import six
from .const import LABEL_CONTAINER_NUMBER
from .const import LABEL_SERVICE
class Container(object):
def __init__(self, client, dictionary, has_been_inspected=False):
self.client = client
self.dictionary = dictionary
self.has_been_inspected = has_been_inspected
@classmethod
def from_ps(cls, client, dictionary, **kwargs):
name = get_container_name(dictionary)
if name is None:
return None
new_dictionary = {
'Id': dictionary['Id'],
'Image': dictionary['Image'],
'Name': '/' + name,
}
return cls(client, new_dictionary, **kwargs)
@classmethod
def from_id(cls, client, id):
return cls(client, client.inspect_container(id))
@classmethod
def create(cls, client, **options):
response = client.create_container(**options)
return cls.from_id(client, response['Id'])
@property
def id(self):
return self.dictionary['Id']
@property
def image(self):
return self.dictionary['Image']
@property
def image_config(self):
return self.client.inspect_image(self.image)
@property
def short_id(self):
return self.id[:10]
@property
def name(self):
return self.dictionary['Name'][1:]
@property
def name_without_project(self):
return '{0}_{1}'.format(self.labels.get(LABEL_SERVICE), self.number)
@property
def number(self):
number = self.labels.get(LABEL_CONTAINER_NUMBER)
if not number:
raise ValueError("Container {0} does not have a {1} label".format(
self.short_id, LABEL_CONTAINER_NUMBER))
return int(number)
@property
def ports(self):
self.inspect_if_not_inspected()
return self.get('NetworkSettings.Ports') or {}
@property
def human_readable_ports(self):
def format_port(private, public):
if not public:
return private
return '{HostIp}:{HostPort}->{private}'.format(
private=private, **public[0])
return ', '.join(format_port(*item)
for item in sorted(six.iteritems(self.ports)))
@property
def labels(self):
return self.get('Config.Labels') or {}
@property
def log_config(self):
return self.get('HostConfig.LogConfig') or None
@property
def human_readable_state(self):
if self.is_paused:
return 'Paused'
if self.is_running:
return 'Ghost' if self.get('State.Ghost') else 'Up'
else:
return 'Exit %s' % self.get('State.ExitCode')
@property
def human_readable_command(self):
entrypoint = self.get('Config.Entrypoint') or []
cmd = self.get('Config.Cmd') or []
return ' '.join(entrypoint + cmd)
@property
def environment(self):
return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
@property
def is_running(self):
return self.get('State.Running')
@property
def is_paused(self):
return self.get('State.Paused')
def get(self, key):
self.inspect_if_not_inspected()
def get_value(dictionary, key):
return (dictionary or {}).get(key)
return reduce(get_value, key.split('.'), self.dictionary)
def get_local_port(self, port, protocol='tcp'):
port = self.ports.get("%s/%s" % (port, protocol))
return "{HostIp}:{HostPort}".format(**port[0]) if port else None
def start(self, **options):
return self.client.start(self.id, **options)
def stop(self, **options):
return self.client.stop(self.id, **options)
def pause(self, **options):
return self.client.pause(self.id, **options)
def unpause(self, **options):
return self.client.unpause(self.id, **options)
def kill(self, **options):
return self.client.kill(self.id, **options)
def restart(self, **options):
return self.client.restart(self.id, **options)
def remove(self, **options):
return self.client.remove_container(self.id, **options)
def inspect_if_not_inspected(self):
if not self.has_been_inspected:
self.inspect()
def wait(self):
return self.client.wait(self.id)
def logs(self, *args, **kwargs):
return self.client.logs(self.id, *args, **kwargs)
def inspect(self):
self.dictionary = self.client.inspect_container(self.id)
self.has_been_inspected = True
return self.dictionary
def links(self):
links = []
for container in self.client.containers():
for name in container['Names']:
bits = name.split('/')
if len(bits) > 2 and bits[1] == self.name:
links.append(bits[2])
return links
def attach(self, *args, **kwargs):
return self.client.attach(self.id, *args, **kwargs)
def attach_socket(self, **kwargs):
return self.client.attach_socket(self.id, **kwargs)
def __repr__(self):
return '<Container: %s (%s)>' % (self.name, self.id[:6])
def __eq__(self, other):
if type(self) != type(other):
return False
return self.id == other.id
def __hash__(self):
return self.id.__hash__()
def get_container_name(container):
if not container.get('Name') and not container.get('Names'):
return None
if 'Name' in container:
return container['Name']
shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
return shortest_name.split('/')[-1]
| true | true |
f727c89ca6002e8cedcf4b9d1b2de5100c7c9fad | 1,149 | py | Python | lib/systems/beta-l-lyxopyranose.py | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | lib/systems/beta-l-lyxopyranose.py | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | lib/systems/beta-l-lyxopyranose.py | pulsar-chem/BPModule | f8e64e04fdb01947708f098e833600c459c2ff0e | [
"BSD-3-Clause"
] | null | null | null | import pulsar as psr
def load_ref_system():
""" Returns beta-l-lyxopyranose as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C 1.4299 0.2461 0.7896
O 0.4230 1.0739 1.3901
C -0.9416 0.6206 1.4010
C -1.3780 0.0314 0.0512
C -0.4016 -1.0958 -0.3576
O -0.7829 -1.6098 -1.6359
C 1.0038 -0.4852 -0.5172
O 0.9231 0.4645 -1.5809
O -2.6663 -0.5389 0.3219
O 2.4097 1.2044 0.4043
H -1.0615 -0.1113 2.2208
H -1.4941 1.5476 1.6502
H 1.8808 -0.4028 1.5639
H 1.7537 -1.2585 -0.8006
H -0.3995 -1.9182 0.3913
H -1.4467 0.7936 -0.7574
H 2.0470 2.1205 0.5463
H 1.7591 1.0051 -1.5910
H -1.3277 -2.4163 -1.5204
H -3.1571 -0.6576 -0.5199
""")
| 41.035714 | 75 | 0.409051 | import pulsar as psr
def load_ref_system():
return psr.make_system("""
C 1.4299 0.2461 0.7896
O 0.4230 1.0739 1.3901
C -0.9416 0.6206 1.4010
C -1.3780 0.0314 0.0512
C -0.4016 -1.0958 -0.3576
O -0.7829 -1.6098 -1.6359
C 1.0038 -0.4852 -0.5172
O 0.9231 0.4645 -1.5809
O -2.6663 -0.5389 0.3219
O 2.4097 1.2044 0.4043
H -1.0615 -0.1113 2.2208
H -1.4941 1.5476 1.6502
H 1.8808 -0.4028 1.5639
H 1.7537 -1.2585 -0.8006
H -0.3995 -1.9182 0.3913
H -1.4467 0.7936 -0.7574
H 2.0470 2.1205 0.5463
H 1.7591 1.0051 -1.5910
H -1.3277 -2.4163 -1.5204
H -3.1571 -0.6576 -0.5199
""")
| true | true |
f727cb3319b78a06a0480e8cba138dfc007d6cb9 | 515 | py | Python | FreeTAKServer/controllers/services/federation/ConnectHandler.py | logikal/FreeTakServer | c0916ce65781b5c60079d6440e52db8fc6ee0467 | [
"MIT"
] | null | null | null | FreeTAKServer/controllers/services/federation/ConnectHandler.py | logikal/FreeTakServer | c0916ce65781b5c60079d6440e52db8fc6ee0467 | [
"MIT"
] | null | null | null | FreeTAKServer/controllers/services/federation/ConnectHandler.py | logikal/FreeTakServer | c0916ce65781b5c60079d6440e52db8fc6ee0467 | [
"MIT"
] | null | null | null | #######################################################
#
# ConnectHandler.py
# Python implementation of the Class ConnectHandler
# Generated by Enterprise Architect
# Created on: 29-Dec-2020 8:10:45 AM
# Original author: natha
#
#######################################################
from Catalog.Data.Federation.Handler import Handler
class ConnectHandler(Handler):
# default constructor def __init__(self):
def Handle(object, command):
pass
def setNextHandler(handler):
pass | 27.105263 | 55 | 0.56699 | true | true | |
f727cb4f493f60788d46a5d0eb9211f2230cd556 | 3,947 | py | Python | detr_tf/data/tfcsv.py | falcon2212/detr-tensorflow | 119da1390a02b6013e7147d822e72c38fc3a2dd9 | [
"MIT"
] | null | null | null | detr_tf/data/tfcsv.py | falcon2212/detr-tensorflow | 119da1390a02b6013e7147d822e72c38fc3a2dd9 | [
"MIT"
] | null | null | null | detr_tf/data/tfcsv.py | falcon2212/detr-tensorflow | 119da1390a02b6013e7147d822e72c38fc3a2dd9 | [
"MIT"
] | null | null | null | import tensorflow as tf
from random import shuffle
import pandas as pd
import numpy as np
import imageio
import os
from detr_tf.data import processing
from detr_tf.data.transformation import detr_transform
from detr_tf import bbox
def morethan1(img, tbbox, tclass):
ret = False
print("morethan1 ", tbbox.shape)
try:
ret = tbbox.shape[0] > 0
except:
ret = False
return ret
def load_data_from_index(index, class_names, filenames, anns, config, augmentation, img_dir):
# Open the image
image = imageio.imread(config.datadir+img_dir+"/"+filenames[index])
# Select all the annotatiom (bbox and class) on this image
image_anns = anns[anns["filename"] == filenames[index]]
# Convert all string class to number (the target class)
t_class = image_anns["class"].map(
lambda x: class_names.index(x)).to_numpy()
# Select the width&height of each image (should be the same since all the ann belongs to the same image)
width = image_anns["width"].to_numpy()
height = image_anns["height"].to_numpy()
# Select the xmin, ymin, xmax and ymax of each bbox, Then, normalized the bbox to be between and 0 and 1
# Finally, convert the bbox from xmin,ymin,xmax,ymax to x_center,y_center,width,height
bbox_list = image_anns[["xmin", "ymin", "xmax", "ymax"]].to_numpy()
bbox_list = bbox_list / [width[0], height[0], width[0], height[0]]
t_bbox = bbox.xy_min_xy_max_to_xcycwh(bbox_list)
# Transform and augment image with bbox and class if needed
image, t_bbox, t_class = detr_transform(
image, t_bbox, t_class, config, augmentation=augmentation)
# Normalized image
image = processing.normalized_images(image, config)
return image.astype(np.float32), t_bbox.astype(np.float32), np.expand_dims(t_class, axis=-1).astype(np.int64)
def load_tfcsv_dataset(config, batch_size, augmentation=False, exclude=[], ann_dir=None, ann_file=None, img_dir=None):
""" Load the hardhat dataset
"""
ann_dir = config.data.ann_dir if ann_dir is None else ann_dir
ann_file = config.data.ann_file if ann_file is None else ann_file
img_dir = config.data.img_dir if img_dir is None else img_dir
anns = pd.read_csv(config.datadir+ann_file)
for name in exclude:
anns = anns[anns["class"] != name]
unique_class = anns["class"].unique()
unique_class.sort()
# Set the background class to 0
config.background_class = 0
class_names = ["background"] + unique_class.tolist()
filenames = anns["filename"].unique().tolist()
indexes = list(range(0, len(filenames)))
shuffle(indexes)
dataset = tf.data.Dataset.from_tensor_slices(indexes)
dataset = dataset.map(lambda idx: processing.numpy_fc(
idx, load_data_from_index,
class_names=class_names, filenames=filenames, anns=anns, config=config, augmentation=augmentation, img_dir=img_dir), num_parallel_calls=tf.data.experimental.AUTOTUNE)
# Filter labels to be sure to keep only sample with at least one bbox
dataset = dataset.filter(
lambda imgs, tbbox, tclass: tf.shape(tbbox)[0] > 0)
# Pad bbox and labels
dataset = dataset.map(processing.pad_labels,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
# Batch images
dataset = dataset.batch(batch_size, drop_remainder=True)
return dataset, class_names
# print(config.data_dir)
# train_iterator, class_names = load_tfcsv_dataset(
# config=config, batch_size=config.batch_size, augmentation=True, img_dir="train", ann_file="train/_annotations.csv")
# test_iterator, class_names = load_tfcsv_dataset(
# config=config, batch_size=config.batch_size, augmentation=True, img_dir="test", ann_file="test/_annotations.csv")
# print(test_iterator.cardinality())
# print(train_iterator.cardinality())
# # tmp = list(train_iterator)
# # for i, _ in enumerate(train_iterator):
# # print(i)
# # print(int(None))
| 39.079208 | 174 | 0.7132 | import tensorflow as tf
from random import shuffle
import pandas as pd
import numpy as np
import imageio
import os
from detr_tf.data import processing
from detr_tf.data.transformation import detr_transform
from detr_tf import bbox
def morethan1(img, tbbox, tclass):
ret = False
print("morethan1 ", tbbox.shape)
try:
ret = tbbox.shape[0] > 0
except:
ret = False
return ret
def load_data_from_index(index, class_names, filenames, anns, config, augmentation, img_dir):
image = imageio.imread(config.datadir+img_dir+"/"+filenames[index])
image_anns = anns[anns["filename"] == filenames[index]]
t_class = image_anns["class"].map(
lambda x: class_names.index(x)).to_numpy()
width = image_anns["width"].to_numpy()
height = image_anns["height"].to_numpy()
bbox_list = image_anns[["xmin", "ymin", "xmax", "ymax"]].to_numpy()
bbox_list = bbox_list / [width[0], height[0], width[0], height[0]]
t_bbox = bbox.xy_min_xy_max_to_xcycwh(bbox_list)
image, t_bbox, t_class = detr_transform(
image, t_bbox, t_class, config, augmentation=augmentation)
image = processing.normalized_images(image, config)
return image.astype(np.float32), t_bbox.astype(np.float32), np.expand_dims(t_class, axis=-1).astype(np.int64)
def load_tfcsv_dataset(config, batch_size, augmentation=False, exclude=[], ann_dir=None, ann_file=None, img_dir=None):
ann_dir = config.data.ann_dir if ann_dir is None else ann_dir
ann_file = config.data.ann_file if ann_file is None else ann_file
img_dir = config.data.img_dir if img_dir is None else img_dir
anns = pd.read_csv(config.datadir+ann_file)
for name in exclude:
anns = anns[anns["class"] != name]
unique_class = anns["class"].unique()
unique_class.sort()
config.background_class = 0
class_names = ["background"] + unique_class.tolist()
filenames = anns["filename"].unique().tolist()
indexes = list(range(0, len(filenames)))
shuffle(indexes)
dataset = tf.data.Dataset.from_tensor_slices(indexes)
dataset = dataset.map(lambda idx: processing.numpy_fc(
idx, load_data_from_index,
class_names=class_names, filenames=filenames, anns=anns, config=config, augmentation=augmentation, img_dir=img_dir), num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.filter(
lambda imgs, tbbox, tclass: tf.shape(tbbox)[0] > 0)
dataset = dataset.map(processing.pad_labels,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
dataset = dataset.batch(batch_size, drop_remainder=True)
return dataset, class_names
| true | true |
f727cbb2b75d40d5dda12a85631fd79800ebe553 | 3,639 | py | Python | docs/site/node_modules/js-datatable-1.1.0/minification.py | hargitomi97/sigstat | e4928fdbd8effa3b9bdf29929f1e7035ff9ccb1f | [
"MIT"
] | 1 | 2020-09-04T12:49:43.000Z | 2020-09-04T12:49:43.000Z | docs/site/node_modules/js-datatable-1.1.0/minification.py | hargitomi97/sigstat | e4928fdbd8effa3b9bdf29929f1e7035ff9ccb1f | [
"MIT"
] | null | null | null | docs/site/node_modules/js-datatable-1.1.0/minification.py | hargitomi97/sigstat | e4928fdbd8effa3b9bdf29929f1e7035ff9ccb1f | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JS and CSS minification
============================
Author: Toni Heittola (toni.heittola@gmail.com)
This plugin will create dynamic datatable with charting features from given yaml-datafile.
"""
import os
import sys
import io
import argparse
import textwrap
from IPython import embed
__version_info__ = ('0', '1', '0')
__version__ = '.'.join(__version_info__)
def main(argv):
parser = argparse.ArgumentParser(
prefix_chars='-+',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
JS and CSS minification
---------------------------------------------
Author: Toni Heittola ( toni.heittola@gmail.com )
'''))
parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
args = parser.parse_args()
print "JS and CSS minification"
print "-----------------------"
minify_css_directory2(source='css', target='css.min')
minify_js_directory(source='js', target='js.min')
def minify_css_directory(source, target):
"""
Move CSS resources from source directory to target directory and minify. Using csscompressor.
"""
from csscompressor import compress
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(source):
for current_file in files:
if current_file.endswith(".css"):
current_file_path = os.path.join(root, current_file)
print " ", current_file_path
with open(current_file_path) as css_file:
with open(os.path.join(target, current_file.replace('.css', '.min.css')), "w") as minified_file:
minified_file.write(compress(css_file.read()))
def minify_css_directory2(source, target):
"""
Move CSS resources from source directory to target directory and minify. Using rcssmin.
"""
import rcssmin
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(source):
for current_file in files:
if current_file.endswith(".css"):
current_file_path = os.path.join(root, current_file)
print " ", current_file_path
with open(current_file_path) as css_file:
with open(os.path.join(target, current_file.replace('.css', '.min.css')), "w") as minified_file:
minified_file.write(rcssmin.cssmin(css_file.read(), keep_bang_comments=True))
def minify_js_directory(source, target):
"""
Move JS resources from source directory to target directory and minify.
"""
from jsmin import jsmin
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(source):
for current_file in files:
if current_file.endswith(".js"):
current_file_path = os.path.join(root, current_file)
print " ", current_file_path
with open(current_file_path) as js_file:
with open(os.path.join(target, current_file.replace('.js', '.min.js')), "w") as minified_file:
minified_file.write(jsmin(js_file.read()))
if __name__ == "__main__":
try:
sys.exit(main(sys.argv))
except (ValueError, IOError) as e:
sys.exit(e) | 34.330189 | 120 | 0.592745 |
"""
JS and CSS minification
============================
Author: Toni Heittola (toni.heittola@gmail.com)
This plugin will create dynamic datatable with charting features from given yaml-datafile.
"""
import os
import sys
import io
import argparse
import textwrap
from IPython import embed
__version_info__ = ('0', '1', '0')
__version__ = '.'.join(__version_info__)
def main(argv):
parser = argparse.ArgumentParser(
prefix_chars='-+',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
JS and CSS minification
---------------------------------------------
Author: Toni Heittola ( toni.heittola@gmail.com )
'''))
parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)
args = parser.parse_args()
print "JS and CSS minification"
print "-----------------------"
minify_css_directory2(source='css', target='css.min')
minify_js_directory(source='js', target='js.min')
def minify_css_directory(source, target):
"""
Move CSS resources from source directory to target directory and minify. Using csscompressor.
"""
from csscompressor import compress
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(source):
for current_file in files:
if current_file.endswith(".css"):
current_file_path = os.path.join(root, current_file)
print " ", current_file_path
with open(current_file_path) as css_file:
with open(os.path.join(target, current_file.replace('.css', '.min.css')), "w") as minified_file:
minified_file.write(compress(css_file.read()))
def minify_css_directory2(source, target):
"""
Move CSS resources from source directory to target directory and minify. Using rcssmin.
"""
import rcssmin
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(source):
for current_file in files:
if current_file.endswith(".css"):
current_file_path = os.path.join(root, current_file)
print " ", current_file_path
with open(current_file_path) as css_file:
with open(os.path.join(target, current_file.replace('.css', '.min.css')), "w") as minified_file:
minified_file.write(rcssmin.cssmin(css_file.read(), keep_bang_comments=True))
def minify_js_directory(source, target):
"""
Move JS resources from source directory to target directory and minify.
"""
from jsmin import jsmin
if os.path.isdir(source):
if not os.path.exists(target):
os.makedirs(target)
for root, dirs, files in os.walk(source):
for current_file in files:
if current_file.endswith(".js"):
current_file_path = os.path.join(root, current_file)
print " ", current_file_path
with open(current_file_path) as js_file:
with open(os.path.join(target, current_file.replace('.js', '.min.js')), "w") as minified_file:
minified_file.write(jsmin(js_file.read()))
if __name__ == "__main__":
try:
sys.exit(main(sys.argv))
except (ValueError, IOError) as e:
sys.exit(e) | false | true |
f727cbca391bd911c82cd15a769a1235f13eebfd | 13,500 | py | Python | Simulation_Python/scenarios.py | tomAntoine/multi-UAV-simulator | 2fbd8b802ea1a5f388722714bac5563d0718b28f | [
"MIT"
] | 22 | 2021-04-07T21:10:53.000Z | 2022-03-26T08:21:06.000Z | Simulation_Python/scenarios.py | alexMarFar/multi-UAV-simulator-1 | 2fbd8b802ea1a5f388722714bac5563d0718b28f | [
"MIT"
] | 2 | 2021-04-12T06:23:50.000Z | 2021-05-20T04:33:35.000Z | Simulation_Python/scenarios.py | alexMarFar/multi-UAV-simulator-1 | 2fbd8b802ea1a5f388722714bac5563d0718b28f | [
"MIT"
] | 4 | 2021-05-21T06:11:34.000Z | 2022-03-09T18:41:10.000Z | # -*- coding: utf-8 -*-
"""
author: John Bass
email: john.bobzwik@gmail.com
license: MIT
Please feel free to use and modify this, but keep the above information. Thanks!
adaptation
author: Tom Antoine and Alex Martinez
"""
import numpy as np
import matplotlib.pyplot as plt
import time
import cProfile
from trajectory import Trajectory
from ctrl import Control
from quadFiles.quad import Quadcopter
from utils.windModel import Wind
import utils
import config
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.legend import Legend
import random
"""
The variable “quad_id” is provided as an integer from 0 to the number of drones
in the simulation.
The “mode” is provided as a string and it can be split into three categories,
depending whether or not they are associated with the agent, the target or both.
The latter are simple actions such as “takeoff”, “home”, “land”, “fall” or
“charging”. Then, there are specific modes for agents like “guided” or “track”;
and targets like “enemy”. The change of mode can be pre-defined or provided
by the Mission planning and Task control subsystem. In the case of targets, the
transition is automated internally. They will be initialized in “enemy” mode and
changed into “neutralized” if the conditions are met to finally change into “fall”.
In the case of agents, the change of modes is performed externally after system
integration. However, due to the very intuitive transitions, some of them were
predefined in sequences for the subsystem validation and verification. For this
reason, “takeoff” and “land” mode were integrated at the beginning and end of
each mission. Similarly, after an agent in “track” mode neutralized its target, or
a “guided” one has reached its goal position, the mode was switched to “home”.
The “id_targ” is a specific integer input associated to the mode “track”. It
corresponds to the target identification number and is assigned as -1 by default
if any other mode is employed.
The “pos_goal” is a set of coordinates x, y and z in the global reference frame
that represent the goal position. It should be noted that although x and y are
not bounded, the z coordinate is restricted so that the drones cannot go through
the ground and by consistency with the guidance algorithms, it is defined as
negative. It should be noted that although this is an input from Mission planning
and Task control subsystem it will be updated for specific modes such as
“track”.
The “pos_obs” is a list of sets of coordinates x, y and z in the global reference
frame corresponding to the static obstacles and therefore should be kept
constant for all the drones in the simulation environment. This information is
predefined but will need to be provided by the Situation Awareness subsystem.
The “pos_ini” is a set of coordinates x, y and z in the global reference frame
that represent the initial position. It should be noted that as for the rest of
coordinates, the z coordinate is defined as negative.
The “color” is employed for the easy identification of the drones. It allows to
easily verify the correct functioning of the algorithms.
The “ctrlType” xyz_pos by default.
The “trajSelect” minimum velocity, no yaw control, average speedby default.
The “Ti” input is given as a number and indicates the initial time for the
simulation. It is common for all drones and by default set at 0s.
For most modes, the “Tf” input is given as a number and corresponds to the
final time of the simulation “Tf”. It is therefore employed for creating the
trajectories to reach goal position. However, in modes that require regular
updates as “track” or “guided”, it is substituted by the update time. In these
cases, it should be slightly modified within drones. It is usually around 0.5s.
The numerical time step “numTimeStep” is employed for the trajectories.
"""
def full_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[1, 5, -2], [8, 2, -8], [5, 8, -9], [0, 0, -2], [3, 3, -1],[3, 9, -17],[5, 7, -18],[0, 0, -10],[5, 10, -16],[10,10,-12],[13,13,-13]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal= [15,15,-15], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*90, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='guided', id_targ = -1, color = 'green', pos_ini = [0,3,0], pos_goal = [15,10,-15], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='track', id_targ = 0, color = 'pink', pos_ini = [3,0,0], pos_goal = [15,20,-15], pos_obs = pos_obs)
quads = [quad0, quad1, quad2]
return pos_obs,quads
def multi_waypoint_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[50,0,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal= [0,-17,-10], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [20,0,0], pos_goal = [-20,-15,-10], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='ennemy', id_targ = -1, color = 'red', pos_ini = [-20,-10,0], pos_goal = [-10,0,-20], pos_obs = pos_obs)
quads = [quad0, quad1, quad2]
return pos_obs,quads
def static_OA_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = []
for i in range(30):
pos_obs.append(random.sample(range(-10, 0), 3))
pos_obs = np.array(pos_obs)
print(pos_obs)
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal= [-10,-10,-10], pos_obs = pos_obs)
quads = [quad0]
return pos_obs,quads
def dynamic_CA_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
#Tf =8s
pos_obs = np.array([[50,0,0]])
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,10,-5],pos_goal = [30,10,-5], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [3,0,-5], pos_goal = [3,20,-5], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [8,0,-5], pos_goal = [8,20,-5], pos_obs = pos_obs)
quad3 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [15,0,-5], pos_goal = [15,20,-5], pos_obs = pos_obs)
quads = [quad0, quad1,quad2,quad3]
return pos_obs,quads
def dynamic_CA_scenario_random_pos(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
#Tf =8s
pos_obs = np.array([[50,0,0]])
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,10,-5],pos_goal = [30,10,-5], pos_obs = pos_obs)
x, z = random.randint(3,17),-1*random.randint(1,8)
quad1 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [x,0,z], pos_goal = [x,20,z], pos_obs = pos_obs)
x, z = random.randint(3,17),-1*random.randint(1,8)
quad2 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [x,0,z], pos_goal = [x,20,z], pos_obs = pos_obs)
x, z = random.randint(3,17),-1*random.randint(1,8)
quad3 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [x,0,z], pos_goal = [x,20,z], pos_obs = pos_obs)
quads = [quad0, quad1,quad2,quad3]
return pos_obs,quads
def simple_tracking_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[-10,-10,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal = [15,15,-15], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*90, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 0, color = 'green', pos_ini = [5,5,0], pos_goal = [2,2,-10], pos_obs = pos_obs)
quads = [quad0, quad1]
return pos_obs,quads
def multi_tracking_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[-10,-10,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal = [15,15,-15], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 0, color = 'green', pos_ini = [4,0,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='track', id_targ = 0, color = 'green', pos_ini = [4,4,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quad3 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='track', id_targ = 0, color = 'green', pos_ini = [4,-4,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quads = [quad0, quad1, quad2, quad3]
return pos_obs,quads
def tracking_loop_scenario(x,Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[x/2,x/2,-10]])
quad0 = Quadcopter(Ti, Ts*99, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='track', id_targ = 1, color = 'blue', pos_ini = [0,0,-10], pos_goal = [0,x,-10], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 2, color = 'green', pos_ini = [x,0,-10], pos_goal = [0,0,-10], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Ts*101, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='track', id_targ = 3, color = 'orange', pos_ini = [x,x,-10],pos_goal = [x,0,-10], pos_obs = pos_obs)
quad3 = Quadcopter(Ti, Ts*102, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='track', id_targ = 0, color = 'pink', pos_ini = [0,x,-10], pos_goal = [x,x,-10],pos_obs = pos_obs)
quads = [quad0, quad1,quad2,quad3]
return pos_obs,quads
def tracking_and_kill_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[-10,-10,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,-5], pos_goal = [20,15,-20], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 0, color = 'green', pos_ini = [5,0,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quads = [quad0, quad1]
return pos_obs,quads
def simple_guided_for_PF(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = []
for i in range(20):
pos_obs.append(random.sample(range(-10, 0), 3))
pos_obs = np.array(pos_obs)
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,0,-5], pos_goal = [-10,-10,-10], pos_obs = pos_obs)
quads = [quad0]
return pos_obs,quads
def ROS_simu(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
fire_station=[]
fire_truck=[]
tree_1=[]
tree_2=[]
pos_obs=[]
for i in range(20):
x = random.sample(range(-10, 10), 1)[0]
y = random.sample(range(-55, -45), 1)[0]
z = random.sample(range(-12, 0), 1)[0]
fire_station.append([x,y,z])
for i in range(5):
x = random.sample(range(-19, 21), 1)[0]
y = random.sample(range(-55, -45), 1)[0]
z = random.sample(range(-3, 0), 1)[0]
fire_truck.append([x,y,z])
for i in range(5):
x = random.sample(range(-12, -8), 1)[0]
y = random.sample(range(-42,-38), 1)[0]
z = random.sample(range(-5, 0), 1)[0]
tree_1.append([x,y,z])
for i in range(5):
x = random.sample(range(8, 12), 1)[0]
y = random.sample(range(-42,-38), 1)[0]
z = random.sample(range(-5, 0), 1)[0]
tree_2.append([x,y,z])
pos_obs = fire_station + fire_truck + tree_1 + tree_2
pos_obs = np.array(pos_obs)
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal = [0,-100,-10], pos_obs = pos_obs)
quads = [quad0]
return(pos_obs,quads)
def real_map(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
xs = [-1,0,1]
ys = [-1,0,1]
zs = [0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
tower = [[x,y,z] for x in xs for y in ys for z in zs]
xs = [-20,5,10]
ys = [5,-10,10]
zs = [0,-1,-2,-3]
trees = [[x,y,z] for x in xs for y in ys for z in zs]
xs = [-20,5,10]
ys = [5,-10,10]
zs = [-4,-5]
tops = []
for i in range(3):
x, y = xs[i], ys[i]
for z in zs:
tops = tops + [[x-1,y,z],[x+1,y,z],[x,y,z],[x,y-1,z],[x,y+1,z]]
print(tops)
pos_obs = np.array(tower + trees + tops)
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,-5], pos_goal = [-10,-10,-10], pos_obs = pos_obs)
quads = [quad0]
return pos_obs,quads
| 56.25 | 199 | 0.669333 |
import numpy as np
import matplotlib.pyplot as plt
import time
import cProfile
from trajectory import Trajectory
from ctrl import Control
from quadFiles.quad import Quadcopter
from utils.windModel import Wind
import utils
import config
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.legend import Legend
import random
def full_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[1, 5, -2], [8, 2, -8], [5, 8, -9], [0, 0, -2], [3, 3, -1],[3, 9, -17],[5, 7, -18],[0, 0, -10],[5, 10, -16],[10,10,-12],[13,13,-13]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal= [15,15,-15], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*90, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='guided', id_targ = -1, color = 'green', pos_ini = [0,3,0], pos_goal = [15,10,-15], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='track', id_targ = 0, color = 'pink', pos_ini = [3,0,0], pos_goal = [15,20,-15], pos_obs = pos_obs)
quads = [quad0, quad1, quad2]
return pos_obs,quads
def multi_waypoint_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[50,0,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal= [0,-17,-10], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [20,0,0], pos_goal = [-20,-15,-10], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='ennemy', id_targ = -1, color = 'red', pos_ini = [-20,-10,0], pos_goal = [-10,0,-20], pos_obs = pos_obs)
quads = [quad0, quad1, quad2]
return pos_obs,quads
def static_OA_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = []
for i in range(30):
pos_obs.append(random.sample(range(-10, 0), 3))
pos_obs = np.array(pos_obs)
print(pos_obs)
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal= [-10,-10,-10], pos_obs = pos_obs)
quads = [quad0]
return pos_obs,quads
def dynamic_CA_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[50,0,0]])
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,10,-5],pos_goal = [30,10,-5], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [3,0,-5], pos_goal = [3,20,-5], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [8,0,-5], pos_goal = [8,20,-5], pos_obs = pos_obs)
quad3 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [15,0,-5], pos_goal = [15,20,-5], pos_obs = pos_obs)
quads = [quad0, quad1,quad2,quad3]
return pos_obs,quads
def dynamic_CA_scenario_random_pos(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[50,0,0]])
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,10,-5],pos_goal = [30,10,-5], pos_obs = pos_obs)
x, z = random.randint(3,17),-1*random.randint(1,8)
quad1 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [x,0,z], pos_goal = [x,20,z], pos_obs = pos_obs)
x, z = random.randint(3,17),-1*random.randint(1,8)
quad2 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [x,0,z], pos_goal = [x,20,z], pos_obs = pos_obs)
x, z = random.randint(3,17),-1*random.randint(1,8)
quad3 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='ennemy', id_targ = -1, color = 'green', pos_ini = [x,0,z], pos_goal = [x,20,z], pos_obs = pos_obs)
quads = [quad0, quad1,quad2,quad3]
return pos_obs,quads
def simple_tracking_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[-10,-10,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal = [15,15,-15], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*90, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 0, color = 'green', pos_ini = [5,5,0], pos_goal = [2,2,-10], pos_obs = pos_obs)
quads = [quad0, quad1]
return pos_obs,quads
def multi_tracking_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[-10,-10,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal = [15,15,-15], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 0, color = 'green', pos_ini = [4,0,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='track', id_targ = 0, color = 'green', pos_ini = [4,4,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quad3 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='track', id_targ = 0, color = 'green', pos_ini = [4,-4,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quads = [quad0, quad1, quad2, quad3]
return pos_obs,quads
def tracking_loop_scenario(x,Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[x/2,x/2,-10]])
quad0 = Quadcopter(Ti, Ts*99, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='track', id_targ = 1, color = 'blue', pos_ini = [0,0,-10], pos_goal = [0,x,-10], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 2, color = 'green', pos_ini = [x,0,-10], pos_goal = [0,0,-10], pos_obs = pos_obs)
quad2 = Quadcopter(Ti, Ts*101, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 2, mode='track', id_targ = 3, color = 'orange', pos_ini = [x,x,-10],pos_goal = [x,0,-10], pos_obs = pos_obs)
quad3 = Quadcopter(Ti, Ts*102, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 3, mode='track', id_targ = 0, color = 'pink', pos_ini = [0,x,-10], pos_goal = [x,x,-10],pos_obs = pos_obs)
quads = [quad0, quad1,quad2,quad3]
return pos_obs,quads
def tracking_and_kill_scenario(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = np.array([[-10,-10,0]])
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,-5], pos_goal = [20,15,-20], pos_obs = pos_obs)
quad1 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 1, mode='track', id_targ = 0, color = 'green', pos_ini = [5,0,0], pos_goal = [4,4,-10], pos_obs = pos_obs)
quads = [quad0, quad1]
return pos_obs,quads
def simple_guided_for_PF(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
pos_obs = []
for i in range(20):
pos_obs.append(random.sample(range(-10, 0), 3))
pos_obs = np.array(pos_obs)
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,0,-5], pos_goal = [-10,-10,-10], pos_obs = pos_obs)
quads = [quad0]
return pos_obs,quads
def ROS_simu(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
fire_station=[]
fire_truck=[]
tree_1=[]
tree_2=[]
pos_obs=[]
for i in range(20):
x = random.sample(range(-10, 10), 1)[0]
y = random.sample(range(-55, -45), 1)[0]
z = random.sample(range(-12, 0), 1)[0]
fire_station.append([x,y,z])
for i in range(5):
x = random.sample(range(-19, 21), 1)[0]
y = random.sample(range(-55, -45), 1)[0]
z = random.sample(range(-3, 0), 1)[0]
fire_truck.append([x,y,z])
for i in range(5):
x = random.sample(range(-12, -8), 1)[0]
y = random.sample(range(-42,-38), 1)[0]
z = random.sample(range(-5, 0), 1)[0]
tree_1.append([x,y,z])
for i in range(5):
x = random.sample(range(8, 12), 1)[0]
y = random.sample(range(-42,-38), 1)[0]
z = random.sample(range(-5, 0), 1)[0]
tree_2.append([x,y,z])
pos_obs = fire_station + fire_truck + tree_1 + tree_2
pos_obs = np.array(pos_obs)
quad0 = Quadcopter(Ti, Ts*100, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='guided', id_targ = -1, color = 'blue', pos_ini = [0,0,0], pos_goal = [0,-100,-10], pos_obs = pos_obs)
quads = [quad0]
return(pos_obs,quads)
def real_map(Ti,Ts,Tf,ctrlType,trajSelect,numTimeStep):
xs = [-1,0,1]
ys = [-1,0,1]
zs = [0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
tower = [[x,y,z] for x in xs for y in ys for z in zs]
xs = [-20,5,10]
ys = [5,-10,10]
zs = [0,-1,-2,-3]
trees = [[x,y,z] for x in xs for y in ys for z in zs]
xs = [-20,5,10]
ys = [5,-10,10]
zs = [-4,-5]
tops = []
for i in range(3):
x, y = xs[i], ys[i]
for z in zs:
tops = tops + [[x-1,y,z],[x+1,y,z],[x,y,z],[x,y-1,z],[x,y+1,z]]
print(tops)
pos_obs = np.array(tower + trees + tops)
quad0 = Quadcopter(Ti, Tf, ctrlType, trajSelect, numTimeStep, Ts, quad_id = 0, mode='ennemy', id_targ = -1, color = 'blue', pos_ini = [0,0,-5], pos_goal = [-10,-10,-10], pos_obs = pos_obs)
quads = [quad0]
return pos_obs,quads
| true | true |
f727cc1948a85ac6d72771c8c995e728612019c7 | 4,358 | py | Python | src/tequila/quantumchemistry/__init__.py | naomicurnow/tequila | 739a76222005558d348a428cf2ce7cb5dfe290de | [
"MIT"
] | 1 | 2021-01-11T18:40:47.000Z | 2021-01-11T18:40:47.000Z | src/tequila/quantumchemistry/__init__.py | kiminh/tequila | 464085265e125222c63e65446861e9c0a2428bab | [
"MIT"
] | null | null | null | src/tequila/quantumchemistry/__init__.py | kiminh/tequila | 464085265e125222c63e65446861e9c0a2428bab | [
"MIT"
] | null | null | null | import typing
from .qc_base import ParametersQC, QuantumChemistryBase
SUPPORTED_QCHEMISTRY_BACKENDS = ["base", "psi4"]
INSTALLED_QCHEMISTRY_BACKENDS = {"base": QuantumChemistryBase}
try:
from .psi4_interface import QuantumChemistryPsi4
INSTALLED_QCHEMISTRY_BACKENDS["psi4"] = QuantumChemistryPsi4
except ImportError:
pass
def show_available_modules():
print("Available QuantumChemistry Modules:")
for k in INSTALLED_QCHEMISTRY_BACKENDS.keys():
print(k)
def show_supported_modules():
print(SUPPORTED_QCHEMISTRY_BACKENDS)
def Molecule(geometry: str,
basis_set: str = None,
transformation: typing.Union[str, typing.Callable] = None,
backend: str = None,
guess_wfn=None,
*args,
**kwargs) -> QuantumChemistryBase:
"""
Parameters
----------
geometry
molecular geometry as string or as filename (needs to be in xyz format with .xyz ending)
basis_set
quantum chemistry basis set (sto-3g, cc-pvdz, etc)
transformation
The Fermion to Qubit Transformation (jordan-wigner, bravyi-kitaev, bravyi-kitaev-tree and whatever OpenFermion supports)
backend
quantum chemistry backend (psi4, pyscf)
guess_wfn
pass down a psi4 guess wavefunction to start the scf cycle from
can also be a filename leading to a stored wavefunction
args
kwargs
Returns
-------
The Fermion to Qubit Transformation (jordan-wigner, bravyi-kitaev, bravyi-kitaev-tree and whatever OpenFermion supports)
"""
keyvals = {}
for k, v in kwargs.items():
if k in ParametersQC.__dict__.keys():
keyvals[k] = v
parameters = ParametersQC(geometry=geometry, basis_set=basis_set, multiplicity=1, **keyvals)
if backend is None:
if "psi4" in INSTALLED_QCHEMISTRY_BACKENDS:
backend = "psi4"
elif "pyscf" in INSTALLED_QCHEMISTRY_BACKENDS:
backend = "pyscf"
else:
requirements = [key in kwargs for key in ["one_body_integrals", "two_body_integrals", "nuclear_repulsion", "n_orbitals"]]
if not all(requirements):
raise Exception("No quantum chemistry backends installed on your system\n"
"To use the base functionality you need to pass the following tensors via keyword\n"
"one_body_integrals, two_body_integrals, nuclear_repulsion, n_orbitals\n")
else:
backend = "base"
if backend not in SUPPORTED_QCHEMISTRY_BACKENDS:
raise Exception(str(backend) + " is not (yet) supported by tequila")
if backend not in INSTALLED_QCHEMISTRY_BACKENDS:
raise Exception(str(backend) + " was not found on your system")
if guess_wfn is not None and backend != 'psi4':
raise Exception("guess_wfn only works for psi4")
if basis_set is None and backend != "base":
raise Exception("no basis_set provided for backend={}".format(backend))
elif basis_set is None:
basis_set = "custom"
parameters.basis_set=basis_set
return INSTALLED_QCHEMISTRY_BACKENDS[backend.lower()](parameters=parameters, transformation=transformation, guess_wfn=guess_wfn, *args, **kwargs)
def MoleculeFromOpenFermion(molecule,
transformation: typing.Union[str, typing.Callable] = None,
backend: str = None,
*args,
**kwargs) -> QuantumChemistryBase:
"""
Initialize a tequila Molecule directly from an openfermion molecule object
Parameters
----------
molecule
The openfermion molecule
transformation
The Fermion to Qubit Transformation (jordan-wigner, bravyi-kitaev, bravyi-kitaev-tree and whatever OpenFermion supports)
backend
The quantum chemistry backend, can be None in this case
Returns
-------
The tequila molecule
"""
if backend is None:
return QuantumChemistryBase.from_openfermion(molecule=molecule, transformation=transformation, *args, **kwargs)
else:
INSTALLED_QCHEMISTRY_BACKENDS[backend].from_openfermion(molecule=molecule, transformation=transformation, *args,
**kwargs)
| 37.568966 | 149 | 0.652593 | import typing
from .qc_base import ParametersQC, QuantumChemistryBase
SUPPORTED_QCHEMISTRY_BACKENDS = ["base", "psi4"]
INSTALLED_QCHEMISTRY_BACKENDS = {"base": QuantumChemistryBase}
try:
from .psi4_interface import QuantumChemistryPsi4
INSTALLED_QCHEMISTRY_BACKENDS["psi4"] = QuantumChemistryPsi4
except ImportError:
pass
def show_available_modules():
print("Available QuantumChemistry Modules:")
for k in INSTALLED_QCHEMISTRY_BACKENDS.keys():
print(k)
def show_supported_modules():
print(SUPPORTED_QCHEMISTRY_BACKENDS)
def Molecule(geometry: str,
basis_set: str = None,
transformation: typing.Union[str, typing.Callable] = None,
backend: str = None,
guess_wfn=None,
*args,
**kwargs) -> QuantumChemistryBase:
keyvals = {}
for k, v in kwargs.items():
if k in ParametersQC.__dict__.keys():
keyvals[k] = v
parameters = ParametersQC(geometry=geometry, basis_set=basis_set, multiplicity=1, **keyvals)
if backend is None:
if "psi4" in INSTALLED_QCHEMISTRY_BACKENDS:
backend = "psi4"
elif "pyscf" in INSTALLED_QCHEMISTRY_BACKENDS:
backend = "pyscf"
else:
requirements = [key in kwargs for key in ["one_body_integrals", "two_body_integrals", "nuclear_repulsion", "n_orbitals"]]
if not all(requirements):
raise Exception("No quantum chemistry backends installed on your system\n"
"To use the base functionality you need to pass the following tensors via keyword\n"
"one_body_integrals, two_body_integrals, nuclear_repulsion, n_orbitals\n")
else:
backend = "base"
if backend not in SUPPORTED_QCHEMISTRY_BACKENDS:
raise Exception(str(backend) + " is not (yet) supported by tequila")
if backend not in INSTALLED_QCHEMISTRY_BACKENDS:
raise Exception(str(backend) + " was not found on your system")
if guess_wfn is not None and backend != 'psi4':
raise Exception("guess_wfn only works for psi4")
if basis_set is None and backend != "base":
raise Exception("no basis_set provided for backend={}".format(backend))
elif basis_set is None:
basis_set = "custom"
parameters.basis_set=basis_set
return INSTALLED_QCHEMISTRY_BACKENDS[backend.lower()](parameters=parameters, transformation=transformation, guess_wfn=guess_wfn, *args, **kwargs)
def MoleculeFromOpenFermion(molecule,
transformation: typing.Union[str, typing.Callable] = None,
backend: str = None,
*args,
**kwargs) -> QuantumChemistryBase:
if backend is None:
return QuantumChemistryBase.from_openfermion(molecule=molecule, transformation=transformation, *args, **kwargs)
else:
INSTALLED_QCHEMISTRY_BACKENDS[backend].from_openfermion(molecule=molecule, transformation=transformation, *args,
**kwargs)
| true | true |
f727cd0adc9bd8230963be0b0db67ba35b37d18b | 2,254 | py | Python | tests/apitests/python/test_user_group.py | shaobo322/harbor | eca3de3489a009dfced253779e6aabdaa14dad70 | [
"Apache-2.0"
] | 5 | 2021-06-08T07:10:55.000Z | 2021-09-29T03:17:09.000Z | tests/apitests/python/test_user_group.py | shaobo322/harbor | eca3de3489a009dfced253779e6aabdaa14dad70 | [
"Apache-2.0"
] | 10 | 2020-04-02T01:58:11.000Z | 2021-04-19T02:13:29.000Z | tests/apitests/python/test_user_group.py | shaobo322/harbor | eca3de3489a009dfced253779e6aabdaa14dad70 | [
"Apache-2.0"
] | 4 | 2021-02-19T08:41:13.000Z | 2021-09-29T03:17:12.000Z | # coding: utf-8
"""
Harbor API
These APIs provide services for manipulating Harbor project.
OpenAPI spec version: 1.4.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
sys.path.append(os.environ["SWAGGER_CLIENT_PATH"])
import unittest
import testutils
import swagger_client
from swagger_client.rest import ApiException
from swagger_client.models.user_group import UserGroup
from swagger_client.models.configurations import Configurations
from pprint import pprint
#Testcase
#12-01-LDAP-usergroup-add
#12-02-LDAP-usergroup-update
#12-03-LDAP-usergroup-delete
class TestUserGroup(unittest.TestCase):
"""UserGroup unit test stubs"""
product_api = testutils.GetProductApi("admin", "Harbor12345")
groupId = 0
def setUp(self):
result = self.product_api.configurations_put(configurations=Configurations(ldap_group_attribute_name="cn", ldap_group_base_dn="ou=groups,dc=example,dc=com", ldap_group_search_filter="objectclass=groupOfNames", ldap_group_search_scope=2))
pprint(result)
pass
def tearDown(self):
if self.groupId > 0 :
self.product_api.usergroups_group_id_delete(group_id=self.groupId)
pass
def testAddUpdateUserGroup(self):
"""Test UserGroup"""
user_group = UserGroup(group_name="harbor_group123", group_type=1, ldap_group_dn="cn=harbor_group,ou=groups,dc=example,dc=com")
result = self.product_api.usergroups_post(usergroup=user_group)
pprint(result)
user_groups = self.product_api.usergroups_get()
found = False
for ug in user_groups :
if ug.group_name == "harbor_group123" :
found = True
print("Found usergroup")
pprint(ug)
self.groupId = ug.id
self.assertTrue(found)
result = self.product_api.usergroups_group_id_put(self.groupId, usergroup = UserGroup(group_name = "newharbor_group"))
new_user_group = self.product_api.usergroups_group_id_get(group_id=self.groupId)
self.assertEqual("newharbor_group", new_user_group.group_name)
pass
if __name__ == '__main__':
unittest.main()
| 30.053333 | 245 | 0.712067 |
from __future__ import absolute_import
import os
import sys
sys.path.append(os.environ["SWAGGER_CLIENT_PATH"])
import unittest
import testutils
import swagger_client
from swagger_client.rest import ApiException
from swagger_client.models.user_group import UserGroup
from swagger_client.models.configurations import Configurations
from pprint import pprint
class TestUserGroup(unittest.TestCase):
product_api = testutils.GetProductApi("admin", "Harbor12345")
groupId = 0
def setUp(self):
result = self.product_api.configurations_put(configurations=Configurations(ldap_group_attribute_name="cn", ldap_group_base_dn="ou=groups,dc=example,dc=com", ldap_group_search_filter="objectclass=groupOfNames", ldap_group_search_scope=2))
pprint(result)
pass
def tearDown(self):
if self.groupId > 0 :
self.product_api.usergroups_group_id_delete(group_id=self.groupId)
pass
def testAddUpdateUserGroup(self):
user_group = UserGroup(group_name="harbor_group123", group_type=1, ldap_group_dn="cn=harbor_group,ou=groups,dc=example,dc=com")
result = self.product_api.usergroups_post(usergroup=user_group)
pprint(result)
user_groups = self.product_api.usergroups_get()
found = False
for ug in user_groups :
if ug.group_name == "harbor_group123" :
found = True
print("Found usergroup")
pprint(ug)
self.groupId = ug.id
self.assertTrue(found)
result = self.product_api.usergroups_group_id_put(self.groupId, usergroup = UserGroup(group_name = "newharbor_group"))
new_user_group = self.product_api.usergroups_group_id_get(group_id=self.groupId)
self.assertEqual("newharbor_group", new_user_group.group_name)
pass
if __name__ == '__main__':
unittest.main()
| true | true |
f727ce30bcfff6735069c4eb270c2a0dffe87867 | 2,140 | py | Python | Sketch.py | sunkr1995/genetic-drawing | 6e5cc755a55c1994770c3f18fb14f1cc651bb700 | [
"MIT"
] | null | null | null | Sketch.py | sunkr1995/genetic-drawing | 6e5cc755a55c1994770c3f18fb14f1cc651bb700 | [
"MIT"
] | null | null | null | Sketch.py | sunkr1995/genetic-drawing | 6e5cc755a55c1994770c3f18fb14f1cc651bb700 | [
"MIT"
] | null | null | null | '''
Author: your name
Date: 2021-07-02 17:20:23
LastEditTime: 2021-07-08 16:28:05
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: /genetic-drawing/2.py
'''
#coding:utf-8
import cv2
import math
import numpy as np
def dodgeNaive(image, mask):
# determine the shape of the input image
width, height = image.shape[:2]
# prepare output argument with same size as image
blend = np.zeros((width, height), np.uint8)
for col in range(width):
for row in range(height):
# do for every pixel
if mask[col, row] == 255:
# avoid division by zero
blend[col, row] = 255
else:
# shift image pixel value by 8 bits
# divide by the inverse of the mask
tmp = (image[col, row] << 8) / (255 - mask)
# print('tmp={}'.format(tmp.shape))
# make sure resulting value stays within bounds
if tmp.any() > 255:
tmp = 255
blend[col, row] = tmp
return blend
def dodgeV2(image, mask):
return cv2.divide(image, 255 - mask, scale=256)
def burnV2(image, mask):
return 255 - cv2.divide(255 - image, 255 - mask, scale=256)
def rgb_to_sketch(src_image_name, dst_image_name):
img_rgb = cv2.imread(src_image_name)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
# 读取图片时直接转换操作
# img_gray = cv2.imread('example.jpg', cv2.IMREAD_GRAYSCALE)
img_gray_inv = 255 - img_gray
img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(21, 21),
sigmaX=0, sigmaY=0)
img_blend = dodgeV2(img_gray, img_blur)
cv2.imshow('original', img_rgb)
cv2.imshow('gray', img_gray)
cv2.imshow('gray_inv', img_gray_inv)
cv2.imshow('gray_blur', img_blur)
cv2.imshow("pencil sketch", img_blend)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite(dst_image_name, img_blend)
if __name__ == '__main__':
src_image_name = '02.jpg'
dst_image_name = 'sketch_02.jpg'
rgb_to_sketch(src_image_name, dst_image_name)
| 28.918919 | 64 | 0.614019 |
import cv2
import math
import numpy as np
def dodgeNaive(image, mask):
width, height = image.shape[:2]
blend = np.zeros((width, height), np.uint8)
for col in range(width):
for row in range(height):
if mask[col, row] == 255:
blend[col, row] = 255
else:
tmp = (image[col, row] << 8) / (255 - mask)
if tmp.any() > 255:
tmp = 255
blend[col, row] = tmp
return blend
def dodgeV2(image, mask):
return cv2.divide(image, 255 - mask, scale=256)
def burnV2(image, mask):
return 255 - cv2.divide(255 - image, 255 - mask, scale=256)
def rgb_to_sketch(src_image_name, dst_image_name):
img_rgb = cv2.imread(src_image_name)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
img_gray_inv = 255 - img_gray
img_blur = cv2.GaussianBlur(img_gray_inv, ksize=(21, 21),
sigmaX=0, sigmaY=0)
img_blend = dodgeV2(img_gray, img_blur)
cv2.imshow('original', img_rgb)
cv2.imshow('gray', img_gray)
cv2.imshow('gray_inv', img_gray_inv)
cv2.imshow('gray_blur', img_blur)
cv2.imshow("pencil sketch", img_blend)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite(dst_image_name, img_blend)
if __name__ == '__main__':
src_image_name = '02.jpg'
dst_image_name = 'sketch_02.jpg'
rgb_to_sketch(src_image_name, dst_image_name)
| true | true |
f727cfe26e46b219012e5f007bb0788969651bf9 | 1,045 | py | Python | app/core/migrations/0004_recipe.py | samacyc/loanBook | 75f50635bfe15e5fd022e9c3fbf2ed165c51a494 | [
"MIT"
] | null | null | null | app/core/migrations/0004_recipe.py | samacyc/loanBook | 75f50635bfe15e5fd022e9c3fbf2ed165c51a494 | [
"MIT"
] | null | null | null | app/core/migrations/0004_recipe.py | samacyc/loanBook | 75f50635bfe15e5fd022e9c3fbf2ed165c51a494 | [
"MIT"
] | null | null | null | # Generated by Django 2.1.15 on 2020-04-25 00:55
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0003_ingredients'),
]
operations = [
migrations.CreateModel(
name='Recipe',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('time_minutes', models.IntegerField()),
('price', models.DecimalField(decimal_places=2, max_digits=5)),
('link', models.CharField(blank=True, max_length=255)),
('ingredients', models.ManyToManyField(to='core.Ingredients')),
('tags', models.ManyToManyField(to='core.Tag')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| 36.034483 | 118 | 0.604785 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0003_ingredients'),
]
operations = [
migrations.CreateModel(
name='Recipe',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('time_minutes', models.IntegerField()),
('price', models.DecimalField(decimal_places=2, max_digits=5)),
('link', models.CharField(blank=True, max_length=255)),
('ingredients', models.ManyToManyField(to='core.Ingredients')),
('tags', models.ManyToManyField(to='core.Tag')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| true | true |
f727d135c106864dba69965703e7f5f5144d703d | 1,168 | py | Python | tests/util/network.py | zcomputerwiz/gojiv2-blockchain | 3be896d4dcb48a734f8d2a901ab5648201fbd4d7 | [
"Apache-2.0"
] | 2 | 2022-02-09T04:30:19.000Z | 2022-03-19T14:01:43.000Z | tests/util/network.py | zcomputerwiz/goji-blockchain | 3be896d4dcb48a734f8d2a901ab5648201fbd4d7 | [
"Apache-2.0"
] | 1 | 2021-12-30T09:17:47.000Z | 2021-12-30T09:17:47.000Z | tests/util/network.py | zcomputerwiz/gojiv2-blockchain | 3be896d4dcb48a734f8d2a901ab5648201fbd4d7 | [
"Apache-2.0"
] | 1 | 2022-03-15T08:42:52.000Z | 2022-03-15T08:42:52.000Z | import pytest
from goji.util.network import get_host_addr
class TestNetwork:
@pytest.mark.asyncio
async def test_get_host_addr4(self):
# Run these tests forcing IPv4 resolution
prefer_ipv6 = False
assert get_host_addr("127.0.0.1", prefer_ipv6) == "127.0.0.1"
assert get_host_addr("10.11.12.13", prefer_ipv6) == "10.11.12.13"
assert get_host_addr("localhost", prefer_ipv6) == "127.0.0.1"
assert get_host_addr("example.net", prefer_ipv6) == "93.184.216.34"
@pytest.mark.asyncio
async def test_get_host_addr6(self):
# Run these tests forcing IPv6 resolution
prefer_ipv6 = True
assert get_host_addr("::1", prefer_ipv6) == "::1"
assert get_host_addr("2000:1000::1234:abcd", prefer_ipv6) == "2000:1000::1234:abcd"
# ip6-localhost is not always available, and localhost is IPv4 only
# on some systems. Just test neither here.
# assert get_host_addr("ip6-localhost", prefer_ipv6) == "::1"
# assert get_host_addr("localhost", prefer_ipv6) == "::1"
assert get_host_addr("example.net", prefer_ipv6) == "2606:2800:220:1:248:1893:25c8:1946"
| 44.923077 | 96 | 0.662671 | import pytest
from goji.util.network import get_host_addr
class TestNetwork:
@pytest.mark.asyncio
async def test_get_host_addr4(self):
prefer_ipv6 = False
assert get_host_addr("127.0.0.1", prefer_ipv6) == "127.0.0.1"
assert get_host_addr("10.11.12.13", prefer_ipv6) == "10.11.12.13"
assert get_host_addr("localhost", prefer_ipv6) == "127.0.0.1"
assert get_host_addr("example.net", prefer_ipv6) == "93.184.216.34"
@pytest.mark.asyncio
async def test_get_host_addr6(self):
prefer_ipv6 = True
assert get_host_addr("::1", prefer_ipv6) == "::1"
assert get_host_addr("2000:1000::1234:abcd", prefer_ipv6) == "2000:1000::1234:abcd"
assert get_host_addr("example.net", prefer_ipv6) == "2606:2800:220:1:248:1893:25c8:1946"
| true | true |
f727d1701f52f74bac125ca10ff531847da7e541 | 3,111 | py | Python | test/test_session.py | SergeyBurma/B2_Command_Line_Tool | 65d8adf080e1502cd51c78f9bc9ce3b0bc787147 | [
"MIT"
] | 1 | 2020-09-06T09:32:44.000Z | 2020-09-06T09:32:44.000Z | test/test_session.py | SergeyBurma/B2_Command_Line_Tool | 65d8adf080e1502cd51c78f9bc9ce3b0bc787147 | [
"MIT"
] | null | null | null | test/test_session.py | SergeyBurma/B2_Command_Line_Tool | 65d8adf080e1502cd51c78f9bc9ce3b0bc787147 | [
"MIT"
] | null | null | null | ######################################################################
#
# File: test_session.py
#
# Copyright 2018 Backblaze Inc. All Rights Reserved.
#
# License https://www.backblaze.com/using_b2_code.html
#
######################################################################
from b2.exception import InvalidAuthToken, Unauthorized
from b2.raw_api import ALL_CAPABILITIES
from b2.session import B2Session
from .test_base import TestBase
try:
import unittest.mock as mock
except ImportError:
import mock
class TestB2Session(TestBase):
def setUp(self):
self.account_info = mock.MagicMock()
self.account_info.get_account_auth_token.return_value = 'auth_token'
self.api = mock.MagicMock()
self.api.account_info = self.account_info
self.raw_api = mock.MagicMock()
self.raw_api.do_it.__name__ = 'do_it'
self.raw_api.do_it.side_effect = ['ok']
self.session = B2Session(self.api, self.raw_api)
def test_works_first_time(self):
self.assertEqual('ok', self.session.do_it())
def test_works_second_time(self):
self.raw_api.do_it.side_effect = [
InvalidAuthToken('message', 'code'),
'ok',
]
self.assertEqual('ok', self.session.do_it())
def test_fails_second_time(self):
self.raw_api.do_it.side_effect = [
InvalidAuthToken('message', 'code'),
InvalidAuthToken('message', 'code'),
]
with self.assertRaises(InvalidAuthToken):
self.session.do_it()
def test_app_key_info_no_info(self):
self.account_info.get_allowed.return_value = dict(
bucketId=None,
bucketName=None,
capabilities=ALL_CAPABILITIES,
namePrefix=None,
)
self.raw_api.do_it.side_effect = Unauthorized('no_go', 'code')
with self.assertRaisesRegexp(
Unauthorized, r'no_go for application key with no restrictions \(code\)'
):
self.session.do_it()
def test_app_key_info_no_info_no_message(self):
self.account_info.get_allowed.return_value = dict(
bucketId=None,
bucketName=None,
capabilities=ALL_CAPABILITIES,
namePrefix=None,
)
self.raw_api.do_it.side_effect = Unauthorized('', 'code')
with self.assertRaisesRegexp(
Unauthorized, r'unauthorized for application key with no restrictions \(code\)'
):
self.session.do_it()
def test_app_key_info_all_info(self):
self.account_info.get_allowed.return_value = dict(
bucketId='123456',
bucketName='my-bucket',
capabilities=['readFiles'],
namePrefix='prefix/',
)
self.raw_api.do_it.side_effect = Unauthorized('no_go', 'code')
with self.assertRaisesRegexp(
Unauthorized,
r"no_go for application key with capabilities 'readFiles', restricted to bucket 'my-bucket', restricted to files that start with 'prefix/' \(code\)"
):
self.session.do_it()
| 33.451613 | 160 | 0.608807 | true | true | |
f727d21a828f288a73ec9d141abf5a7e7130abba | 16,717 | py | Python | salt/utils/verify.py | jkur/salt | 3e62675550f9869d550d7787800270e632955d2f | [
"Apache-2.0"
] | null | null | null | salt/utils/verify.py | jkur/salt | 3e62675550f9869d550d7787800270e632955d2f | [
"Apache-2.0"
] | null | null | null | salt/utils/verify.py | jkur/salt | 3e62675550f9869d550d7787800270e632955d2f | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
A few checks to make sure the environment is sane
'''
from __future__ import absolute_import
# Original Author: Jeff Schroeder <jeffschroeder@computer.org>
# Import python libs
import os
import re
import sys
import stat
import errno
import socket
import logging
# Import third party libs
if sys.platform.startswith('win'):
import win32file
else:
import resource
# Import salt libs
from salt.log import is_console_configured
from salt.exceptions import SaltClientError
import salt.defaults.exitcodes
import salt.utils
log = logging.getLogger(__name__)
def zmq_version():
'''
ZeroMQ python bindings >= 2.1.9 are required
'''
try:
import zmq
except Exception:
# Return True for local mode
return True
ver = zmq.__version__
# The last matched group can be None if the version
# is something like 3.1 and that will work properly
match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', ver)
# Fallthrough and hope for the best
if not match:
msg = "Using untested zmq python bindings version: '{0}'".format(ver)
if is_console_configured():
log.warn(msg)
else:
sys.stderr.write("WARNING {0}\n".format(msg))
return True
major, minor, point = match.groups()
if major.isdigit():
major = int(major)
if minor.isdigit():
minor = int(minor)
# point very well could be None
if point and point.isdigit():
point = int(point)
if major == 2 and minor == 1:
# zmq 2.1dev could be built against a newer libzmq
if "dev" in ver and not point:
msg = 'Using dev zmq module, please report unexpected results'
if is_console_configured():
log.warn(msg)
else:
sys.stderr.write("WARNING: {0}\n".format(msg))
return True
elif point and point >= 9:
return True
elif major > 2 or (major == 2 and minor > 1):
return True
# If all else fails, gracefully croak and warn the user
log.critical('ZeroMQ python bindings >= 2.1.9 are required')
if 'salt-master' in sys.argv[0]:
msg = ('The Salt Master is unstable using a ZeroMQ version '
'lower than 2.1.11 and requires this fix: http://lists.zeromq.'
'org/pipermail/zeromq-dev/2011-June/012094.html')
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write('CRITICAL {0}\n'.format(msg))
return False
def lookup_family(hostname):
'''
Lookup a hostname and determine its address family. The first address returned
will be AF_INET6 if the system is IPv6-enabled, and AF_INET otherwise.
'''
# If lookups fail, fall back to AF_INET sockets (and v4 addresses).
fallback = socket.AF_INET
try:
hostnames = socket.getaddrinfo(
hostname or None, None, socket.AF_UNSPEC, socket.SOCK_STREAM
)
if not hostnames:
return fallback
h = hostnames[0]
return h[0]
except socket.gaierror:
return fallback
def verify_socket(interface, pub_port, ret_port):
'''
Attempt to bind to the sockets to verify that they are available
'''
addr_family = lookup_family(interface)
pubsock = socket.socket(addr_family, socket.SOCK_STREAM)
retsock = socket.socket(addr_family, socket.SOCK_STREAM)
try:
pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
pubsock.bind((interface, int(pub_port)))
pubsock.close()
retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
retsock.bind((interface, int(ret_port)))
retsock.close()
result = True
except Exception as exc:
if exc.args:
msg = ('Unable to bind socket, error: {0}'.format(str(exc)))
else:
msg = ('Unable to bind socket, this might not be a problem.'
' Is there another salt-master running?')
if is_console_configured():
log.warn(msg)
else:
sys.stderr.write('WARNING: {0}\n'.format(msg))
result = False
finally:
pubsock.close()
retsock.close()
return result
def verify_files(files, user):
'''
Verify that the named files exist and are owned by the named user
'''
if salt.utils.is_windows():
return True
import pwd # after confirming not running Windows
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for fn_ in files:
dirname = os.path.dirname(fn_)
try:
try:
os.makedirs(dirname)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if not os.path.isfile(fn_):
with salt.utils.fopen(fn_, 'w+') as fp_:
fp_.write('')
except OSError as err:
msg = 'Failed to create path "{0}" - {1}\n'
sys.stderr.write(msg.format(fn_, err))
sys.exit(err.errno)
stats = os.stat(fn_)
if uid != stats.st_uid:
try:
os.chown(fn_, uid, -1)
except OSError:
pass
return True
def verify_env(dirs, user, permissive=False, pki_dir=''):
'''
Verify that the named directories are in place and that the environment
can shake the salt
'''
if salt.utils.is_windows():
return True
import pwd # after confirming not running Windows
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
gid = pwnam[3]
groups = salt.utils.get_gid_list(user, include_default=False)
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for dir_ in dirs:
if not dir_:
continue
if not os.path.isdir(dir_):
try:
cumask = os.umask(18) # 077
os.makedirs(dir_)
# If starting the process as root, chown the new dirs
if os.getuid() == 0:
os.chown(dir_, uid, gid)
os.umask(cumask)
except OSError as err:
msg = 'Failed to create directory path "{0}" - {1}\n'
sys.stderr.write(msg.format(dir_, err))
sys.exit(err.errno)
mode = os.stat(dir_)
# If starting the process as root, chown the new dirs
if os.getuid() == 0:
fmode = os.stat(dir_)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
# Allow the directory to be owned by any group root
# belongs to if we say it's ok to be permissive
pass
else:
# chown the file for the new user
os.chown(dir_, uid, gid)
for subdir in [a for a in os.listdir(dir_) if 'jobs' not in a]:
fsubdir = os.path.join(dir_, subdir)
if '{0}jobs'.format(os.path.sep) in fsubdir:
continue
for root, dirs, files in os.walk(fsubdir):
for name in files:
if name.startswith('.'):
continue
path = os.path.join(root, name)
try:
fmode = os.stat(path)
except (IOError, OSError):
pass
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
for name in dirs:
path = os.path.join(root, name)
fmode = os.stat(path)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
# Allow the pki dir to be 700 or 750, but nothing else.
# This prevents other users from writing out keys, while
# allowing the use-case of 3rd-party software (like django)
# to read in what it needs to integrate.
#
# If the permissions aren't correct, default to the more secure 700.
# If acls are enabled, the pki_dir needs to remain readable, this
# is still secure because the private keys are still only readbale
# by the user running the master
if dir_ == pki_dir:
smode = stat.S_IMODE(mode.st_mode)
if smode != 448 and smode != 488:
if os.access(dir_, os.W_OK):
os.chmod(dir_, 448)
else:
msg = 'Unable to securely set the permissions of "{0}".'
msg = msg.format(dir_)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
# Run the extra verification checks
zmq_version()
def check_user(user):
'''
Check user and assign process uid/gid.
'''
if salt.utils.is_windows():
return True
if user == salt.utils.get_user():
return True
import pwd # after confirming not running Windows
try:
pwuser = pwd.getpwnam(user)
try:
if hasattr(os, 'initgroups'):
os.initgroups(user, pwuser.pw_gid)
else:
os.setgroups(salt.utils.get_gid_list(user, include_default=False))
os.setgid(pwuser.pw_gid)
os.setuid(pwuser.pw_uid)
except OSError:
msg = 'Salt configured to run as user "{0}" but unable to switch.'
msg = msg.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
except KeyError:
msg = 'User not found: "{0}"'.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
return True
def list_path_traversal(path):
'''
Returns a full list of directories leading up to, and including, a path.
So list_path_traversal('/path/to/salt') would return:
['/', '/path', '/path/to', '/path/to/salt']
in that order.
This routine has been tested on Windows systems as well.
list_path_traversal('c:\\path\\to\\salt') on Windows would return:
['c:\\', 'c:\\path', 'c:\\path\\to', 'c:\\path\\to\\salt']
'''
out = [path]
(head, tail) = os.path.split(path)
if tail == '':
# paths with trailing separators will return an empty string
out = [head]
(head, tail) = os.path.split(head)
while head != out[0]:
# loop until head is the same two consecutive times
out.insert(0, head)
(head, tail) = os.path.split(head)
return out
def check_path_traversal(path, user='root', skip_perm_errors=False):
'''
Walk from the root up to a directory and verify that the current
user has access to read each directory. This is used for making
sure a user can read all parent directories of the minion's key
before trying to go and generate a new key and raising an IOError
'''
for tpath in list_path_traversal(path):
if not os.access(tpath, os.R_OK):
msg = 'Could not access {0}.'.format(tpath)
if not os.path.exists(tpath):
msg += ' Path does not exist.'
else:
current_user = salt.utils.get_user()
# Make the error message more intelligent based on how
# the user invokes salt-call or whatever other script.
if user != current_user:
msg += ' Try running as user {0}.'.format(user)
else:
msg += ' Please give {0} read permissions.'.format(user)
# We don't need to bail on config file permission errors
# if the CLI
# process is run with the -a flag
if skip_perm_errors:
return
# Propagate this exception up so there isn't a sys.exit()
# in the middle of code that could be imported elsewhere.
raise SaltClientError(msg)
def check_max_open_files(opts):
'''
Check the number of max allowed open files and adjust if needed
'''
mof_c = opts.get('max_open_files', 100000)
if sys.platform.startswith('win'):
# Check the Windows API for more detail on this
# http://msdn.microsoft.com/en-us/library/xt874334(v=vs.71).aspx
# and the python binding http://timgolden.me.uk/pywin32-docs/win32file.html
mof_s = mof_h = win32file._getmaxstdio()
else:
mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE)
accepted_keys_dir = os.path.join(opts.get('pki_dir'), 'minions')
accepted_count = len(os.listdir(accepted_keys_dir))
log.debug(
'This salt-master instance has accepted {0} minion keys.'.format(
accepted_count
)
)
level = logging.INFO
if (accepted_count * 4) <= mof_s:
# We check for the soft value of max open files here because that's the
# value the user chose to raise to.
#
# The number of accepted keys multiplied by four(4) is lower than the
# soft value, everything should be OK
return
msg = (
'The number of accepted minion keys({0}) should be lower than 1/4 '
'of the max open files soft setting({1}). '.format(
accepted_count, mof_s
)
)
if accepted_count >= mof_s:
# This should never occur, it might have already crashed
msg += 'salt-master will crash pretty soon! '
level = logging.CRITICAL
elif (accepted_count * 2) >= mof_s:
# This is way too low, CRITICAL
level = logging.CRITICAL
elif (accepted_count * 3) >= mof_s:
level = logging.WARNING
# The accepted count is more than 3 time, WARN
elif (accepted_count * 4) >= mof_s:
level = logging.INFO
if mof_c < mof_h:
msg += ('According to the system\'s hard limit, there\'s still a '
'margin of {0} to raise the salt\'s max_open_files '
'setting. ').format(mof_h - mof_c)
msg += 'Please consider raising this value.'
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
'''
Accepts the root the path needs to be under and verifies that the path is
under said root. Pass in subdir=True if the path can result in a
subdirectory of the root instead of having to reside directly in the root
'''
if not os.path.isabs(root):
return ''
if not os.path.isabs(path):
path = os.path.join(root, path)
path = os.path.normpath(path)
if subdir:
if path.startswith(root):
return path
else:
if os.path.dirname(path) == os.path.normpath(root):
return path
return ''
def valid_id(opts, id_):
'''
Returns if the passed id is valid
'''
try:
return bool(clean_path(opts['pki_dir'], id_))
except (AttributeError, KeyError) as e:
return False
def safe_py_code(code):
'''
Check a string to see if it has any potentially unsafe routines which
could be executed via python, this routine is used to improve the
safety of modules suct as virtualenv
'''
bads = (
'import',
';',
'subprocess',
'eval',
'open',
'file',
'exec',
'input')
for bad in bads:
if code.count(bad):
return False
return True
| 34.046843 | 83 | 0.562481 |
from __future__ import absolute_import
import os
import re
import sys
import stat
import errno
import socket
import logging
if sys.platform.startswith('win'):
import win32file
else:
import resource
from salt.log import is_console_configured
from salt.exceptions import SaltClientError
import salt.defaults.exitcodes
import salt.utils
log = logging.getLogger(__name__)
def zmq_version():
try:
import zmq
except Exception:
return True
ver = zmq.__version__
match = re.match(r'^(\d+)\.(\d+)(?:\.(\d+))?', ver)
if not match:
msg = "Using untested zmq python bindings version: '{0}'".format(ver)
if is_console_configured():
log.warn(msg)
else:
sys.stderr.write("WARNING {0}\n".format(msg))
return True
major, minor, point = match.groups()
if major.isdigit():
major = int(major)
if minor.isdigit():
minor = int(minor)
if point and point.isdigit():
point = int(point)
if major == 2 and minor == 1:
if "dev" in ver and not point:
msg = 'Using dev zmq module, please report unexpected results'
if is_console_configured():
log.warn(msg)
else:
sys.stderr.write("WARNING: {0}\n".format(msg))
return True
elif point and point >= 9:
return True
elif major > 2 or (major == 2 and minor > 1):
return True
log.critical('ZeroMQ python bindings >= 2.1.9 are required')
if 'salt-master' in sys.argv[0]:
msg = ('The Salt Master is unstable using a ZeroMQ version '
'lower than 2.1.11 and requires this fix: http://lists.zeromq.'
'org/pipermail/zeromq-dev/2011-June/012094.html')
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write('CRITICAL {0}\n'.format(msg))
return False
def lookup_family(hostname):
fallback = socket.AF_INET
try:
hostnames = socket.getaddrinfo(
hostname or None, None, socket.AF_UNSPEC, socket.SOCK_STREAM
)
if not hostnames:
return fallback
h = hostnames[0]
return h[0]
except socket.gaierror:
return fallback
def verify_socket(interface, pub_port, ret_port):
addr_family = lookup_family(interface)
pubsock = socket.socket(addr_family, socket.SOCK_STREAM)
retsock = socket.socket(addr_family, socket.SOCK_STREAM)
try:
pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
pubsock.bind((interface, int(pub_port)))
pubsock.close()
retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
retsock.bind((interface, int(ret_port)))
retsock.close()
result = True
except Exception as exc:
if exc.args:
msg = ('Unable to bind socket, error: {0}'.format(str(exc)))
else:
msg = ('Unable to bind socket, this might not be a problem.'
' Is there another salt-master running?')
if is_console_configured():
log.warn(msg)
else:
sys.stderr.write('WARNING: {0}\n'.format(msg))
result = False
finally:
pubsock.close()
retsock.close()
return result
def verify_files(files, user):
if salt.utils.is_windows():
return True
import pwd
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for fn_ in files:
dirname = os.path.dirname(fn_)
try:
try:
os.makedirs(dirname)
except OSError as err:
if err.errno != errno.EEXIST:
raise
if not os.path.isfile(fn_):
with salt.utils.fopen(fn_, 'w+') as fp_:
fp_.write('')
except OSError as err:
msg = 'Failed to create path "{0}" - {1}\n'
sys.stderr.write(msg.format(fn_, err))
sys.exit(err.errno)
stats = os.stat(fn_)
if uid != stats.st_uid:
try:
os.chown(fn_, uid, -1)
except OSError:
pass
return True
def verify_env(dirs, user, permissive=False, pki_dir=''):
if salt.utils.is_windows():
return True
import pwd
try:
pwnam = pwd.getpwnam(user)
uid = pwnam[2]
gid = pwnam[3]
groups = salt.utils.get_gid_list(user, include_default=False)
except KeyError:
err = ('Failed to prepare the Salt environment for user '
'{0}. The user is not available.\n').format(user)
sys.stderr.write(err)
sys.exit(salt.defaults.exitcodes.EX_NOUSER)
for dir_ in dirs:
if not dir_:
continue
if not os.path.isdir(dir_):
try:
cumask = os.umask(18)
os.makedirs(dir_)
if os.getuid() == 0:
os.chown(dir_, uid, gid)
os.umask(cumask)
except OSError as err:
msg = 'Failed to create directory path "{0}" - {1}\n'
sys.stderr.write(msg.format(dir_, err))
sys.exit(err.errno)
mode = os.stat(dir_)
if os.getuid() == 0:
fmode = os.stat(dir_)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(dir_, uid, gid)
for subdir in [a for a in os.listdir(dir_) if 'jobs' not in a]:
fsubdir = os.path.join(dir_, subdir)
if '{0}jobs'.format(os.path.sep) in fsubdir:
continue
for root, dirs, files in os.walk(fsubdir):
for name in files:
if name.startswith('.'):
continue
path = os.path.join(root, name)
try:
fmode = os.stat(path)
except (IOError, OSError):
pass
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
for name in dirs:
path = os.path.join(root, name)
fmode = os.stat(path)
if fmode.st_uid != uid or fmode.st_gid != gid:
if permissive and fmode.st_gid in groups:
pass
else:
# chown the file for the new user
os.chown(path, uid, gid)
# Allow the pki dir to be 700 or 750, but nothing else.
# This prevents other users from writing out keys, while
# allowing the use-case of 3rd-party software (like django)
# to read in what it needs to integrate.
#
# If the permissions aren't correct, default to the more secure 700.
if dir_ == pki_dir:
smode = stat.S_IMODE(mode.st_mode)
if smode != 448 and smode != 488:
if os.access(dir_, os.W_OK):
os.chmod(dir_, 448)
else:
msg = 'Unable to securely set the permissions of "{0}".'
msg = msg.format(dir_)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
zmq_version()
def check_user(user):
if salt.utils.is_windows():
return True
if user == salt.utils.get_user():
return True
import pwd
try:
pwuser = pwd.getpwnam(user)
try:
if hasattr(os, 'initgroups'):
os.initgroups(user, pwuser.pw_gid)
else:
os.setgroups(salt.utils.get_gid_list(user, include_default=False))
os.setgid(pwuser.pw_gid)
os.setuid(pwuser.pw_uid)
except OSError:
msg = 'Salt configured to run as user "{0}" but unable to switch.'
msg = msg.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
except KeyError:
msg = 'User not found: "{0}"'.format(user)
if is_console_configured():
log.critical(msg)
else:
sys.stderr.write("CRITICAL: {0}\n".format(msg))
return False
return True
def list_path_traversal(path):
out = [path]
(head, tail) = os.path.split(path)
if tail == '':
out = [head]
(head, tail) = os.path.split(head)
while head != out[0]:
out.insert(0, head)
(head, tail) = os.path.split(head)
return out
def check_path_traversal(path, user='root', skip_perm_errors=False):
for tpath in list_path_traversal(path):
if not os.access(tpath, os.R_OK):
msg = 'Could not access {0}.'.format(tpath)
if not os.path.exists(tpath):
msg += ' Path does not exist.'
else:
current_user = salt.utils.get_user()
if user != current_user:
msg += ' Try running as user {0}.'.format(user)
else:
msg += ' Please give {0} read permissions.'.format(user)
# if the CLI
# process is run with the -a flag
if skip_perm_errors:
return
# Propagate this exception up so there isn't a sys.exit()
raise SaltClientError(msg)
def check_max_open_files(opts):
mof_c = opts.get('max_open_files', 100000)
if sys.platform.startswith('win'):
mof_s = mof_h = win32file._getmaxstdio()
else:
mof_s, mof_h = resource.getrlimit(resource.RLIMIT_NOFILE)
accepted_keys_dir = os.path.join(opts.get('pki_dir'), 'minions')
accepted_count = len(os.listdir(accepted_keys_dir))
log.debug(
'This salt-master instance has accepted {0} minion keys.'.format(
accepted_count
)
)
level = logging.INFO
if (accepted_count * 4) <= mof_s:
# value the user chose to raise to.
#
# The number of accepted keys multiplied by four(4) is lower than the
# soft value, everything should be OK
return
msg = (
'The number of accepted minion keys({0}) should be lower than 1/4 '
'of the max open files soft setting({1}). '.format(
accepted_count, mof_s
)
)
if accepted_count >= mof_s:
# This should never occur, it might have already crashed
msg += 'salt-master will crash pretty soon! '
level = logging.CRITICAL
elif (accepted_count * 2) >= mof_s:
# This is way too low, CRITICAL
level = logging.CRITICAL
elif (accepted_count * 3) >= mof_s:
level = logging.WARNING
# The accepted count is more than 3 time, WARN
elif (accepted_count * 4) >= mof_s:
level = logging.INFO
if mof_c < mof_h:
msg += ('According to the system\'s hard limit, there\'s still a '
'margin of {0} to raise the salt\'s max_open_files '
'setting. ').format(mof_h - mof_c)
msg += 'Please consider raising this value.'
log.log(level=level, msg=msg)
def clean_path(root, path, subdir=False):
if not os.path.isabs(root):
return ''
if not os.path.isabs(path):
path = os.path.join(root, path)
path = os.path.normpath(path)
if subdir:
if path.startswith(root):
return path
else:
if os.path.dirname(path) == os.path.normpath(root):
return path
return ''
def valid_id(opts, id_):
try:
return bool(clean_path(opts['pki_dir'], id_))
except (AttributeError, KeyError) as e:
return False
def safe_py_code(code):
bads = (
'import',
';',
'subprocess',
'eval',
'open',
'file',
'exec',
'input')
for bad in bads:
if code.count(bad):
return False
return True
| true | true |
f727d2d7e7376be3e613532b9e1ea017af35747c | 1,794 | py | Python | tests/ml/pipeline_test.py | cyrusradfar/vaex | 6a37bd4509c9a0823b4f01075049f3331fabea77 | [
"MIT"
] | 2 | 2020-12-01T09:41:54.000Z | 2020-12-13T14:10:19.000Z | tests/ml/pipeline_test.py | cyrusradfar/vaex | 6a37bd4509c9a0823b4f01075049f3331fabea77 | [
"MIT"
] | null | null | null | tests/ml/pipeline_test.py | cyrusradfar/vaex | 6a37bd4509c9a0823b4f01075049f3331fabea77 | [
"MIT"
] | null | null | null | import vaex
import vaex.ml
import tempfile
import vaex.ml.datasets
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
def test_pca():
ds = vaex.ml.datasets.load_iris()
pca = vaex.ml.PCA(features=features, n_components=2)
pca.fit(ds)
ds1 = pca.transform(ds)
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([pca])
pipeline.save(path)
pipeline = vaex.ml.Pipeline()
pipeline.load(path)
ds2 = pipeline.transform(ds)
assert ds1.virtual_columns['PCA_1'] == ds2.virtual_columns['PCA_1']
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([ds1.ml.state_transfer()])
pipeline.save(path)
pipeline = vaex.ml.Pipeline()
pipeline.load(path)
ds3 = pipeline.transform(ds)
assert ds1.virtual_columns['PCA_1'] == ds3.virtual_columns['PCA_1']
def test_selections():
ds = vaex.ml.datasets.load_iris()
ds.select('class_ == 1')
count1 = ds.count(selection=True)
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([ds.ml.state_transfer()])
pipeline.save(path)
print(path)
pipeline = vaex.ml.Pipeline()
pipeline.load(path)
ds2 = pipeline.transform(ds)
assert ds2.count(selection=True) == count1
def test_state_transfer():
ds = vaex.ml.datasets.load_iris()
ds['test'] = ds.petal_width * ds.petal_length
test_values = ds.test.evaluate()
state_transfer = ds.ml.state_transfer()
# clean dataset
ds = vaex.ml.datasets.load_iris()
ds = state_transfer.transform(ds)
assert test_values.tolist() == ds.test.evaluate().tolist()
ds1, ds2 = ds.split(0.5)
state_transfer = ds1.ml.state_transfer()
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([state_transfer])
pipeline.save(path)
| 27.181818 | 73 | 0.673356 | import vaex
import vaex.ml
import tempfile
import vaex.ml.datasets
features = ['petal_length', 'petal_width', 'sepal_length', 'sepal_width']
def test_pca():
ds = vaex.ml.datasets.load_iris()
pca = vaex.ml.PCA(features=features, n_components=2)
pca.fit(ds)
ds1 = pca.transform(ds)
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([pca])
pipeline.save(path)
pipeline = vaex.ml.Pipeline()
pipeline.load(path)
ds2 = pipeline.transform(ds)
assert ds1.virtual_columns['PCA_1'] == ds2.virtual_columns['PCA_1']
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([ds1.ml.state_transfer()])
pipeline.save(path)
pipeline = vaex.ml.Pipeline()
pipeline.load(path)
ds3 = pipeline.transform(ds)
assert ds1.virtual_columns['PCA_1'] == ds3.virtual_columns['PCA_1']
def test_selections():
ds = vaex.ml.datasets.load_iris()
ds.select('class_ == 1')
count1 = ds.count(selection=True)
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([ds.ml.state_transfer()])
pipeline.save(path)
print(path)
pipeline = vaex.ml.Pipeline()
pipeline.load(path)
ds2 = pipeline.transform(ds)
assert ds2.count(selection=True) == count1
def test_state_transfer():
ds = vaex.ml.datasets.load_iris()
ds['test'] = ds.petal_width * ds.petal_length
test_values = ds.test.evaluate()
state_transfer = ds.ml.state_transfer()
ds = vaex.ml.datasets.load_iris()
ds = state_transfer.transform(ds)
assert test_values.tolist() == ds.test.evaluate().tolist()
ds1, ds2 = ds.split(0.5)
state_transfer = ds1.ml.state_transfer()
path = tempfile.mktemp('.yaml')
pipeline = vaex.ml.Pipeline([state_transfer])
pipeline.save(path)
| true | true |
f727d359d96619c0985b1970043b681970bc7181 | 937 | py | Python | Project_Tuples_Alpha/moduleForFindingTuplesTime.py | zacandcheese/Keyboard-Biometric-Project | 0cdc0fef65b34624e80a5e96e2457c9cf958fb6d | [
"MIT"
] | 1 | 2017-10-03T14:40:09.000Z | 2017-10-03T14:40:09.000Z | Project_Tuples_Alpha/moduleForFindingTuplesTime.py | zacandcheese/Keyboard-Biometric-Project | 0cdc0fef65b34624e80a5e96e2457c9cf958fb6d | [
"MIT"
] | null | null | null | Project_Tuples_Alpha/moduleForFindingTuplesTime.py | zacandcheese/Keyboard-Biometric-Project | 0cdc0fef65b34624e80a5e96e2457c9cf958fb6d | [
"MIT"
] | 2 | 2019-02-20T02:28:13.000Z | 2021-12-01T19:50:19.000Z | __version__ = '1.0'
__author__ = 'Zachary Nowak'
"""STANDARD LIBRARY IMPORTS"""
from statistics import *
def create_dict(tupleList,pressCharTimeLine,pressTimeLine,dataDict):
keyHistory = ""
timingList = [[] for i in range(len(tupleList))]
"""CREATE A STRING WITH ALL THE EVENTS"""
for char in pressCharTimeLine:
keyHistory += char
"""FIND THE TIME IT TAKES TO TYPE EACH WORD FROM PRESS TO PRESS"""
for string in tupleList:
i = 0
index = tupleList.index(string)
while(keyHistory.find(string.upper(), i))!= -1:
position = keyHistory.find(string.upper(),i)
i = position + len(tupleList[0])
timingList[index].append(pressTimeLine[i - 1] - pressTimeLine[position])
"""ASSIGN THE TUPLE WITH IT'S MEDIAN TOTAL PRESS TIME"""
i = 0
for tuple in timingList:
print("The median is: ", median(tuple))
print("The mean is: ", harmonic_mean(tuple))
dataDict[tupleList[i]] = median(tuple)
i += 1
return dataDict
| 30.225806 | 75 | 0.701174 | __version__ = '1.0'
__author__ = 'Zachary Nowak'
from statistics import *
def create_dict(tupleList,pressCharTimeLine,pressTimeLine,dataDict):
keyHistory = ""
timingList = [[] for i in range(len(tupleList))]
for char in pressCharTimeLine:
keyHistory += char
for string in tupleList:
i = 0
index = tupleList.index(string)
while(keyHistory.find(string.upper(), i))!= -1:
position = keyHistory.find(string.upper(),i)
i = position + len(tupleList[0])
timingList[index].append(pressTimeLine[i - 1] - pressTimeLine[position])
i = 0
for tuple in timingList:
print("The median is: ", median(tuple))
print("The mean is: ", harmonic_mean(tuple))
dataDict[tupleList[i]] = median(tuple)
i += 1
return dataDict
| true | true |
f727d3a4b3cb35b73b91afefa5df649fd90c9c96 | 1,670 | py | Python | test/python/foursquare_test/source_code_analysis/scala/test_scala_unused_import_remover.py | foursquare/source_code_analysis | 4323efdb1b41c3726c8ddf0d7276698400640bfd | [
"Apache-2.0"
] | 5 | 2015-01-28T14:32:27.000Z | 2020-03-23T03:01:34.000Z | test/python/foursquare_test/source_code_analysis/scala/test_scala_unused_import_remover.py | caiocasado/source_code_analysis | 4323efdb1b41c3726c8ddf0d7276698400640bfd | [
"Apache-2.0"
] | 1 | 2015-01-19T20:16:18.000Z | 2015-02-03T02:35:56.000Z | test/python/foursquare_test/source_code_analysis/scala/test_scala_unused_import_remover.py | caiocasado/source_code_analysis | 4323efdb1b41c3726c8ddf0d7276698400640bfd | [
"Apache-2.0"
] | 6 | 2015-01-09T21:05:16.000Z | 2020-10-29T09:53:14.000Z | # coding=utf-8
# Copyright 2011 Foursquare Labs Inc. All Rights Reserved
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import unittest
from foursquare.source_code_analysis.scala.scala_unused_import_remover import ScalaUnusedImportRemover
class ScalaUnusedImportRemoverTest(unittest.TestCase):
def _do_test_remover(self, input_text, expected_text):
remover = ScalaUnusedImportRemover(False)
removed_text = remover.apply_to_text('test.scala', input_text).new_text
self.assertEqual(expected_text, removed_text)
def test_basic_removal(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
if(Foo) {
Baz()
}
""",
"""
import scala.foo.Foo
import com.baz.Baz
if(Foo) {
Baz()
}
""")
def test_no_removal(self):
input_text = """
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
if(Foo) {
Baz()
} else {
Bar
}
"""
self._do_test_remover(input_text, input_text)
def test_all_removal(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
if(x) {
y()
}
""",
"""
if(x) {
y()
}
""")
def test_keep_only_wildcards(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
import boo.biz._
if(x) {
y()
}
""",
"""
import boo.biz._
if(x) {
y()
}
""")
def test_keep_wildcards(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
import boo.biz._
if(Foo) {
y()
}
""",
"""
import scala.foo.Foo
import boo.biz._
if(Foo) {
y()
}
""")
| 14.910714 | 102 | 0.697006 |
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
print_function, unicode_literals)
import unittest
from foursquare.source_code_analysis.scala.scala_unused_import_remover import ScalaUnusedImportRemover
class ScalaUnusedImportRemoverTest(unittest.TestCase):
def _do_test_remover(self, input_text, expected_text):
remover = ScalaUnusedImportRemover(False)
removed_text = remover.apply_to_text('test.scala', input_text).new_text
self.assertEqual(expected_text, removed_text)
def test_basic_removal(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
if(Foo) {
Baz()
}
""",
"""
import scala.foo.Foo
import com.baz.Baz
if(Foo) {
Baz()
}
""")
def test_no_removal(self):
input_text = """
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
if(Foo) {
Baz()
} else {
Bar
}
"""
self._do_test_remover(input_text, input_text)
def test_all_removal(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
if(x) {
y()
}
""",
"""
if(x) {
y()
}
""")
def test_keep_only_wildcards(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
import boo.biz._
if(x) {
y()
}
""",
"""
import boo.biz._
if(x) {
y()
}
""")
def test_keep_wildcards(self):
self._do_test_remover(
"""
import scala.foo.Foo
import com.baz.Baz
import java.bar.Bar
import boo.biz._
if(Foo) {
y()
}
""",
"""
import scala.foo.Foo
import boo.biz._
if(Foo) {
y()
}
""")
| true | true |
f727d3d70ff583c6743d4843417bbc2ecf9584ca | 4,770 | py | Python | stackoverflow/venv/lib/python3.6/site-packages/twisted/positioning/test/test_sentence.py | wusirs/learn_python3_spider | a3301f8112e4ded25c3578162db8c6a263a0693b | [
"MIT"
] | 9,953 | 2019-04-03T23:41:04.000Z | 2022-03-31T11:54:44.000Z | stackoverflow/venv/lib/python3.6/site-packages/twisted/positioning/test/test_sentence.py | W4LKURE/learn_python3_spider | 98dd354a41598b31302641f9a0ea49d1ecfa0fb1 | [
"MIT"
] | 44 | 2019-05-27T10:59:29.000Z | 2022-03-31T14:14:29.000Z | stackoverflow/venv/lib/python3.6/site-packages/twisted/positioning/test/test_sentence.py | W4LKURE/learn_python3_spider | 98dd354a41598b31302641f9a0ea49d1ecfa0fb1 | [
"MIT"
] | 2,803 | 2019-04-06T13:15:33.000Z | 2022-03-31T07:42:01.000Z | # Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for positioning sentences.
"""
from __future__ import absolute_import, division
import itertools
from twisted.positioning import _sentence
from twisted.trial.unittest import TestCase
sentinelValueOne = "someStringValue"
sentinelValueTwo = "someOtherStringValue"
class DummyProtocol(object):
"""
A simple, fake protocol.
"""
@staticmethod
def getSentenceAttributes():
return ["type", sentinelValueOne, sentinelValueTwo]
class DummySentence(_sentence._BaseSentence):
"""
A sentence for L{DummyProtocol}.
"""
ALLOWED_ATTRIBUTES = DummyProtocol.getSentenceAttributes()
class MixinProtocol(_sentence._PositioningSentenceProducerMixin):
"""
A simple, fake protocol that declaratively tells you the sentences
it produces using L{base.PositioningSentenceProducerMixin}.
"""
_SENTENCE_CONTENTS = {
None: [
sentinelValueOne,
sentinelValueTwo,
None # See MixinTests.test_noNoneInSentenceAttributes
],
}
class MixinSentence(_sentence._BaseSentence):
"""
A sentence for L{MixinProtocol}.
"""
ALLOWED_ATTRIBUTES = MixinProtocol.getSentenceAttributes()
class SentenceTestsMixin(object):
"""
Tests for positioning protocols and their respective sentences.
"""
def test_attributeAccess(self):
"""
A sentence attribute gets the correct value, and accessing an
unset attribute (which is specified as being a valid sentence
attribute) gets L{None}.
"""
thisSentinel = object()
sentence = self.sentenceClass({sentinelValueOne: thisSentinel})
self.assertEqual(getattr(sentence, sentinelValueOne), thisSentinel)
self.assertIsNone(getattr(sentence, sentinelValueTwo))
def test_raiseOnMissingAttributeAccess(self):
"""
Accessing a nonexistent attribute raises C{AttributeError}.
"""
sentence = self.sentenceClass({})
self.assertRaises(AttributeError, getattr, sentence, "BOGUS")
def test_raiseOnBadAttributeAccess(self):
"""
Accessing bogus attributes raises C{AttributeError}, *even*
when that attribute actually is in the sentence data.
"""
sentence = self.sentenceClass({"BOGUS": None})
self.assertRaises(AttributeError, getattr, sentence, "BOGUS")
sentenceType = "tummies"
reprTemplate = "<%s (%s) {%s}>"
def _expectedRepr(self, sentenceType="unknown type", dataRepr=""):
"""
Builds the expected repr for a sentence.
@param sentenceType: The name of the sentence type (e.g "GPGGA").
@type sentenceType: C{str}
@param dataRepr: The repr of the data in the sentence.
@type dataRepr: C{str}
@return: The expected repr of the sentence.
@rtype: C{str}
"""
clsName = self.sentenceClass.__name__
return self.reprTemplate % (clsName, sentenceType, dataRepr)
def test_unknownTypeRepr(self):
"""
Test the repr of an empty sentence of unknown type.
"""
sentence = self.sentenceClass({})
expectedRepr = self._expectedRepr()
self.assertEqual(repr(sentence), expectedRepr)
def test_knownTypeRepr(self):
"""
Test the repr of an empty sentence of known type.
"""
sentence = self.sentenceClass({"type": self.sentenceType})
expectedRepr = self._expectedRepr(self.sentenceType)
self.assertEqual(repr(sentence), expectedRepr)
class MixinTests(TestCase, SentenceTestsMixin):
"""
Tests for protocols deriving from L{base.PositioningSentenceProducerMixin}
and their sentences.
"""
def setUp(self):
self.protocol = MixinProtocol()
self.sentenceClass = MixinSentence
def test_noNoneInSentenceAttributes(self):
"""
L{None} does not appear in the sentence attributes of the
protocol, even though it's in the specification.
This is because L{None} is a placeholder for parts of the sentence you
don't really need or want, but there are some bits later on in the
sentence that you do want. The alternative would be to have to specify
things like "_UNUSED0", "_UNUSED1"... which would end up cluttering
the sentence data and eventually adapter state.
"""
sentenceAttributes = self.protocol.getSentenceAttributes()
self.assertNotIn(None, sentenceAttributes)
sentenceContents = self.protocol._SENTENCE_CONTENTS
sentenceSpecAttributes = itertools.chain(*sentenceContents.values())
self.assertIn(None, sentenceSpecAttributes)
| 30 | 78 | 0.674843 |
from __future__ import absolute_import, division
import itertools
from twisted.positioning import _sentence
from twisted.trial.unittest import TestCase
sentinelValueOne = "someStringValue"
sentinelValueTwo = "someOtherStringValue"
class DummyProtocol(object):
@staticmethod
def getSentenceAttributes():
return ["type", sentinelValueOne, sentinelValueTwo]
class DummySentence(_sentence._BaseSentence):
ALLOWED_ATTRIBUTES = DummyProtocol.getSentenceAttributes()
class MixinProtocol(_sentence._PositioningSentenceProducerMixin):
_SENTENCE_CONTENTS = {
None: [
sentinelValueOne,
sentinelValueTwo,
None
],
}
class MixinSentence(_sentence._BaseSentence):
ALLOWED_ATTRIBUTES = MixinProtocol.getSentenceAttributes()
class SentenceTestsMixin(object):
def test_attributeAccess(self):
thisSentinel = object()
sentence = self.sentenceClass({sentinelValueOne: thisSentinel})
self.assertEqual(getattr(sentence, sentinelValueOne), thisSentinel)
self.assertIsNone(getattr(sentence, sentinelValueTwo))
def test_raiseOnMissingAttributeAccess(self):
sentence = self.sentenceClass({})
self.assertRaises(AttributeError, getattr, sentence, "BOGUS")
def test_raiseOnBadAttributeAccess(self):
sentence = self.sentenceClass({"BOGUS": None})
self.assertRaises(AttributeError, getattr, sentence, "BOGUS")
sentenceType = "tummies"
reprTemplate = "<%s (%s) {%s}>"
def _expectedRepr(self, sentenceType="unknown type", dataRepr=""):
clsName = self.sentenceClass.__name__
return self.reprTemplate % (clsName, sentenceType, dataRepr)
def test_unknownTypeRepr(self):
sentence = self.sentenceClass({})
expectedRepr = self._expectedRepr()
self.assertEqual(repr(sentence), expectedRepr)
def test_knownTypeRepr(self):
sentence = self.sentenceClass({"type": self.sentenceType})
expectedRepr = self._expectedRepr(self.sentenceType)
self.assertEqual(repr(sentence), expectedRepr)
class MixinTests(TestCase, SentenceTestsMixin):
def setUp(self):
self.protocol = MixinProtocol()
self.sentenceClass = MixinSentence
def test_noNoneInSentenceAttributes(self):
sentenceAttributes = self.protocol.getSentenceAttributes()
self.assertNotIn(None, sentenceAttributes)
sentenceContents = self.protocol._SENTENCE_CONTENTS
sentenceSpecAttributes = itertools.chain(*sentenceContents.values())
self.assertIn(None, sentenceSpecAttributes)
| true | true |
f727d41d6e60219428f3f297b23ca0f713529146 | 6,573 | py | Python | FatherSon/HelloWorld2_source_code/listing_22-8.py | axetang/AxePython | 3b517fa3123ce2e939680ad1ae14f7e602d446a6 | [
"Apache-2.0"
] | 1 | 2019-01-04T05:47:50.000Z | 2019-01-04T05:47:50.000Z | FatherSon/HelloWorld2_source_code/listing_22-8.py | axetang/AxePython | 3b517fa3123ce2e939680ad1ae14f7e602d446a6 | [
"Apache-2.0"
] | null | null | null | FatherSon/HelloWorld2_source_code/listing_22-8.py | axetang/AxePython | 3b517fa3123ce2e939680ad1ae14f7e602d446a6 | [
"Apache-2.0"
] | null | null | null | # Listing_22-8.py
# Copyright Warren & Csrter Sande, 2013
# Released under MIT license http://www.opensource.org/licenses/mit-license.php
# Version $version ----------------------------
# Hangman game using PyQt
import sys
from PyQt4 import QtCore, QtGui, uic
import random
form_class = uic.loadUiType("hangman.ui")[0]
# Find the locations(s) of guessed letters in the secret word
def find_letters(letter, a_string):
locations = []
start = 0
while a_string.find(letter, start, len(a_string)) != -1:
location = a_string.find(letter, start, len(a_string))
locations.append(location)
start = location + 1
return locations
# Replace dashes with letters when the player guesses a letter correctly
def replace_letters(string, locations, letter):
new_string = ''
for i in range (0, len(string)):
if i in locations:
new_string = new_string + letter
else:
new_string = new_string + string[i]
return new_string
# Replace letters with dashes at the start of the program
def dashes(word):
letters = "abcdefghijklmnopqrstuvwxyz"
new_string = ''
for i in word:
if i in letters:
new_string += "-"
else:
new_string += i
return new_string
class MyWidget(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.btn_guess.clicked.connect(self.btn_guess_clicked) # Connect event handlers
self.actionExit.triggered.connect(self.menuExit_selected) #
self.pieces = [self.head, self.body, self.leftarm, self.leftleg, # Parts of the man
self.rightarm, self.rightleg] #
self.gallows = [self.line1, self.line2, self.line3, self.line4] # Parts of the gallows
self.pieces_shown = 0
self.currentword = ""
#Get the word list
f=open("words.txt", 'r')
self.lines = f.readlines()
f.close()
self.new_game()
def new_game(self):
self.guesses.setText("")
self.currentword = random.choice(self.lines) # Randomly pick a word from the list
self.currentword = self.currentword.strip()
for i in self.pieces: # Hide the man
i.setFrameShadow(QtGui.QFrame.Plain) #
i.setHidden(True) #
for i in self.gallows:
i.setFrameShadow(QtGui.QFrame.Plain)
self.word.setText(dashes(self.currentword)) # Call the function to replace letters with dashes
self.pieces_shown = 0
# Let the player guess a letter or word
def btn_guess_clicked(self):
guess = str(self.guessBox.text())
if str(self.guesses.text()) != "":
self.guesses.setText(str(self.guesses.text())+", "+guess)
else:
self.guesses.setText(guess)
if len(guess) == 1: # Guess a letter
if guess in self.currentword: #
locations = find_letters(guess, self.currentword) #
self.word.setText(replace_letters(str(self.word.text()), #
locations,guess)) #
if str(self.word.text()) == self.currentword: #
self.win() #
else:
self.wrong()
else: # Guess a word
if guess == self.currentword: #
self.win() #
else: #
self.wrong() #
self.guessBox.setText("")
def win(self): #Display a dialog if player wins
QtGui.QMessageBox.information(self,"Hangman","You win!") #
self.new_game() #
# handle a wrong guess
def wrong(self):
self.pieces_shown += 1
for i in range(self.pieces_shown): # Reveal another piece of the man
self.pieces[i].setHidden(False) #
if self.pieces_shown == len(self.pieces):
message = "You lose. The word was " + self.currentword # Player lost
QtGui.QMessageBox.warning(self,"Hangman", message) #
self.new_game()
def menuExit_selected(self):
self.close()
app = QtGui.QApplication(sys.argv)
myapp = MyWidget(None)
myapp.show()
app.exec_()
| 54.775 | 138 | 0.386125 |
import sys
from PyQt4 import QtCore, QtGui, uic
import random
form_class = uic.loadUiType("hangman.ui")[0]
def find_letters(letter, a_string):
locations = []
start = 0
while a_string.find(letter, start, len(a_string)) != -1:
location = a_string.find(letter, start, len(a_string))
locations.append(location)
start = location + 1
return locations
def replace_letters(string, locations, letter):
new_string = ''
for i in range (0, len(string)):
if i in locations:
new_string = new_string + letter
else:
new_string = new_string + string[i]
return new_string
def dashes(word):
letters = "abcdefghijklmnopqrstuvwxyz"
new_string = ''
for i in word:
if i in letters:
new_string += "-"
else:
new_string += i
return new_string
class MyWidget(QtGui.QMainWindow, form_class):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.btn_guess.clicked.connect(self.btn_guess_clicked)
self.actionExit.triggered.connect(self.menuExit_selected)
self.pieces = [self.head, self.body, self.leftarm, self.leftleg,
self.rightarm, self.rightleg]
self.gallows = [self.line1, self.line2, self.line3, self.line4]
self.pieces_shown = 0
self.currentword = ""
f=open("words.txt", 'r')
self.lines = f.readlines()
f.close()
self.new_game()
def new_game(self):
self.guesses.setText("")
self.currentword = random.choice(self.lines)
self.currentword = self.currentword.strip()
for i in self.pieces:
i.setFrameShadow(QtGui.QFrame.Plain)
i.setHidden(True)
for i in self.gallows:
i.setFrameShadow(QtGui.QFrame.Plain)
self.word.setText(dashes(self.currentword))
self.pieces_shown = 0
def btn_guess_clicked(self):
guess = str(self.guessBox.text())
if str(self.guesses.text()) != "":
self.guesses.setText(str(self.guesses.text())+", "+guess)
else:
self.guesses.setText(guess)
if len(guess) == 1:
if guess in self.currentword:
locations = find_letters(guess, self.currentword)
self.word.setText(replace_letters(str(self.word.text()),
locations,guess))
if str(self.word.text()) == self.currentword:
self.win()
else:
self.wrong()
else:
if guess == self.currentword:
self.win()
else:
self.wrong()
self.guessBox.setText("")
def win(self):
QtGui.QMessageBox.information(self,"Hangman","You win!")
self.new_game()
def wrong(self):
self.pieces_shown += 1
for i in range(self.pieces_shown):
self.pieces[i].setHidden(False)
if self.pieces_shown == len(self.pieces):
message = "You lose. The word was " + self.currentword
QtGui.QMessageBox.warning(self,"Hangman", message)
self.new_game()
def menuExit_selected(self):
self.close()
app = QtGui.QApplication(sys.argv)
myapp = MyWidget(None)
myapp.show()
app.exec_()
| true | true |
f727d4361a24d0843a7fbc97eb2728198e8f07f6 | 1,923 | py | Python | models/Gan.py | debashishc/texygan-analysis | f44d559b15da988080bc1a1d84399db04e69d755 | [
"MIT"
] | 881 | 2018-02-06T18:20:34.000Z | 2022-03-29T13:18:12.000Z | models/Gan.py | debashishc/texygan-analysis | f44d559b15da988080bc1a1d84399db04e69d755 | [
"MIT"
] | 48 | 2018-02-13T21:31:24.000Z | 2021-07-03T13:35:21.000Z | models/Gan.py | debashishc/texygan-analysis | f44d559b15da988080bc1a1d84399db04e69d755 | [
"MIT"
] | 224 | 2018-02-07T04:48:31.000Z | 2022-03-18T12:26:25.000Z | from abc import abstractmethod
from utils.utils import init_sess
class Gan:
def __init__(self):
self.oracle = None
self.generator = None
self.discriminator = None
self.gen_data_loader = None
self.dis_data_loader = None
self.oracle_data_loader = None
self.sess = init_sess()
self.metrics = list()
self.epoch = 0
self.pre_epoch_num = 80
self.adversarial_epoch_num = 100
self.log = None
self.reward = None
def set_oracle(self, oracle):
self.oracle = oracle
def set_generator(self, generator):
self.generator = generator
def set_discriminator(self, discriminator):
self.discriminator = discriminator
def set_data_loader(self, gen_loader, dis_loader, oracle_loader):
self.gen_data_loader = gen_loader
self.dis_data_loader = dis_loader
self.oracle_data_loader = oracle_loader
def set_sess(self, sess):
self.sess = sess
def add_metric(self, metric):
self.metrics.append(metric)
def add_epoch(self):
self.epoch += 1
def reset_epoch(self):
# current not in use
return
self.epoch = 0
def evaluate(self):
from time import time
log = "epoch:" + str(self.epoch) + '\t'
scores = list()
scores.append(self.epoch)
for metric in self.metrics:
tic = time()
score = metric.get_score()
log += metric.get_name() + ":" + str(score) + '\t'
toc = time()
print('time elapsed of ' + metric.get_name() + ': ' + str(toc - tic))
scores.append(score)
print(log)
return scores
def check_valid(self):
# TODO
pass
@abstractmethod
def train_oracle(self):
pass
def train_cfg(self):
pass
def train_real(self):
pass
| 24.653846 | 81 | 0.583983 | from abc import abstractmethod
from utils.utils import init_sess
class Gan:
def __init__(self):
self.oracle = None
self.generator = None
self.discriminator = None
self.gen_data_loader = None
self.dis_data_loader = None
self.oracle_data_loader = None
self.sess = init_sess()
self.metrics = list()
self.epoch = 0
self.pre_epoch_num = 80
self.adversarial_epoch_num = 100
self.log = None
self.reward = None
def set_oracle(self, oracle):
self.oracle = oracle
def set_generator(self, generator):
self.generator = generator
def set_discriminator(self, discriminator):
self.discriminator = discriminator
def set_data_loader(self, gen_loader, dis_loader, oracle_loader):
self.gen_data_loader = gen_loader
self.dis_data_loader = dis_loader
self.oracle_data_loader = oracle_loader
def set_sess(self, sess):
self.sess = sess
def add_metric(self, metric):
self.metrics.append(metric)
def add_epoch(self):
self.epoch += 1
def reset_epoch(self):
return
self.epoch = 0
def evaluate(self):
from time import time
log = "epoch:" + str(self.epoch) + '\t'
scores = list()
scores.append(self.epoch)
for metric in self.metrics:
tic = time()
score = metric.get_score()
log += metric.get_name() + ":" + str(score) + '\t'
toc = time()
print('time elapsed of ' + metric.get_name() + ': ' + str(toc - tic))
scores.append(score)
print(log)
return scores
def check_valid(self):
pass
@abstractmethod
def train_oracle(self):
pass
def train_cfg(self):
pass
def train_real(self):
pass
| true | true |
f727d4b7735acda30dc72a1387415a5e055bed03 | 3,028 | py | Python | caillprocess_temp_pickledlist.py | johnmgregoire/JCAPdatavis | 6d77a510e00acf31de9665828d27ea33aba6ab78 | [
"BSD-3-Clause"
] | null | null | null | caillprocess_temp_pickledlist.py | johnmgregoire/JCAPdatavis | 6d77a510e00acf31de9665828d27ea33aba6ab78 | [
"BSD-3-Clause"
] | null | null | null | caillprocess_temp_pickledlist.py | johnmgregoire/JCAPdatavis | 6d77a510e00acf31de9665828d27ea33aba6ab78 | [
"BSD-3-Clause"
] | null | null | null |
import time, copy
import os, os.path
import sys
import numpy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from scipy import optimize
from echem_plate_ui import *
from echem_plate_math import *
import pickle
p='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/2012-9FeCoNiTi_500C_CAill_plate1_dlist.dat'
savefolder='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/2012-9FeCoNiTi_500C_CAill_plate1_illgraphs'
os.chdir(savefolder)
f=open(p, mode='r')
dlist=pickle.load(f)
f.close()
o=numpy.ones(500, dtype='float32')
z=numpy.zeros(500, dtype='float32')
tocat=[z]
for i in range(15):
tocat+=[o, z]
ill=numpy.concatenate(tocat)
#darkinds=numpy.arange(90, 490)
#illinds=numpy.arange(590, 990)
darkinds=numpy.arange(290, 490)
illinds=numpy.arange(790, 990)
darkinds_cyc=[darkinds+i*1000 for i in range(16)]
illinds_cyc=[illinds+i*1000 for i in range(15)]
darkindsplot=numpy.arange(0, 500)
illindsplot=numpy.arange(500, 1000)
darkindsplot_cyc=[darkinds+i*1000 for i in range(16)]
illindsplot_cyc=[illinds+i*1000 for i in range(15)]
getdarkvals=lambda arr:numpy.array([arr[inds].mean() for inds in darkinds_cyc])
getillvals=lambda arr:numpy.array([arr[inds].mean() for inds in illinds_cyc])
o500=numpy.ones(500, dtype='float32')
t_ill=getillvals(dlist[0]['t(s)'])
pylab.figure()
for d in dlist:
if d['Sample']!=1164:
continue
if len(d['I(A)'])<15500:
print 'problem with sample ', d['Sample']
d['Photocurrent(A)']=numpy.nan
d['Photocurrent_std(A)']=numpy.nan
d['Photocurrent_cycs(A)']=numpy.nan
continue
i_ill=getillvals(d['I(A)'])
i_dark=getdarkvals(d['I(A)'])
idiff=i_ill-0.5*(i_dark[:-1]+i_dark[1:])
d['Photocurrent(A)']=idiff.mean()
d['Photocurrent_std(A)']=idiff.std()
d['Photocurrent_cycs(A)']=idiff
pylab.clf()
ax=pylab.subplot(111)
ax2=ax.twinx()
ax.plot(d['t(s)'], d['I(A)'])
d['I(A)_SG']=savgolsmooth(d['I(A)'], nptsoneside=50, order = 2)
ax.plot(d['t(s)'], d['I(A)_SG'], 'k')
ax2.plot(t_ill, idiff, 'ro')
iplt=numpy.concatenate([numpy.concatenate([dv*o500, di*o500]) for dv, di in zip(i_dark, i_ill)]+[i_dark[-1]*o500])
d['till_cycs']=t_ill
d['Idiff_time']=iplt
ax.plot(d['t(s)'], iplt, 'g')
s=`d['Sample']`+', '
for el, v in zip(d['elements'], d['compositions']):
s+=el+'%d' %(100*v)
pylab.title(s)
pylab.savefig('SecondAnalysis_'+`d['Sample']`)
break
#getdarkstd=lambda arr:numpy.array([arr[inds].std() for inds in darkinds_cyc])
#getillstd=lambda arr:numpy.array([arr[inds].std() for inds in illinds_cyc])
#i_darkstd=getdarkstd(d['I(A)_SG'])
#i_illstd=getillstd(d['I(A)_SG'])
#idiffstd=(i_illstd**2+0.25*(i_darkstd[:-1]**2+i_darkstd[1:]**2))**.5
#print idiffstd/idiff
if 1:
import pickle
fld, fn=os.path.split(p)
savep=os.path.join(os.path.join(fld, 'echemplots'), fn[:-4]+'_%d.dat' %d['Sample'])
f=open(savep, mode='w')
pickle.dump(d, f)
f.close()
pylab.show()
| 29.686275 | 129 | 0.6714 |
import time, copy
import os, os.path
import sys
import numpy
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from scipy import optimize
from echem_plate_ui import *
from echem_plate_math import *
import pickle
p='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/2012-9FeCoNiTi_500C_CAill_plate1_dlist.dat'
savefolder='C:/Users/Gregoire/Documents/CaltechWork/echemdrop/2012-9_FeCoNiTi/results/2012-9FeCoNiTi_500C_CAill_plate1_illgraphs'
os.chdir(savefolder)
f=open(p, mode='r')
dlist=pickle.load(f)
f.close()
o=numpy.ones(500, dtype='float32')
z=numpy.zeros(500, dtype='float32')
tocat=[z]
for i in range(15):
tocat+=[o, z]
ill=numpy.concatenate(tocat)
darkinds=numpy.arange(290, 490)
illinds=numpy.arange(790, 990)
darkinds_cyc=[darkinds+i*1000 for i in range(16)]
illinds_cyc=[illinds+i*1000 for i in range(15)]
darkindsplot=numpy.arange(0, 500)
illindsplot=numpy.arange(500, 1000)
darkindsplot_cyc=[darkinds+i*1000 for i in range(16)]
illindsplot_cyc=[illinds+i*1000 for i in range(15)]
getdarkvals=lambda arr:numpy.array([arr[inds].mean() for inds in darkinds_cyc])
getillvals=lambda arr:numpy.array([arr[inds].mean() for inds in illinds_cyc])
o500=numpy.ones(500, dtype='float32')
t_ill=getillvals(dlist[0]['t(s)'])
pylab.figure()
for d in dlist:
if d['Sample']!=1164:
continue
if len(d['I(A)'])<15500:
print 'problem with sample ', d['Sample']
d['Photocurrent(A)']=numpy.nan
d['Photocurrent_std(A)']=numpy.nan
d['Photocurrent_cycs(A)']=numpy.nan
continue
i_ill=getillvals(d['I(A)'])
i_dark=getdarkvals(d['I(A)'])
idiff=i_ill-0.5*(i_dark[:-1]+i_dark[1:])
d['Photocurrent(A)']=idiff.mean()
d['Photocurrent_std(A)']=idiff.std()
d['Photocurrent_cycs(A)']=idiff
pylab.clf()
ax=pylab.subplot(111)
ax2=ax.twinx()
ax.plot(d['t(s)'], d['I(A)'])
d['I(A)_SG']=savgolsmooth(d['I(A)'], nptsoneside=50, order = 2)
ax.plot(d['t(s)'], d['I(A)_SG'], 'k')
ax2.plot(t_ill, idiff, 'ro')
iplt=numpy.concatenate([numpy.concatenate([dv*o500, di*o500]) for dv, di in zip(i_dark, i_ill)]+[i_dark[-1]*o500])
d['till_cycs']=t_ill
d['Idiff_time']=iplt
ax.plot(d['t(s)'], iplt, 'g')
s=`d['Sample']`+', '
for el, v in zip(d['elements'], d['compositions']):
s+=el+'%d' %(100*v)
pylab.title(s)
pylab.savefig('SecondAnalysis_'+`d['Sample']`)
break
if 1:
import pickle
fld, fn=os.path.split(p)
savep=os.path.join(os.path.join(fld, 'echemplots'), fn[:-4]+'_%d.dat' %d['Sample'])
f=open(savep, mode='w')
pickle.dump(d, f)
f.close()
pylab.show()
| false | true |
f727d50e8dc0e67cf07b6f0c64f482507f96fdd0 | 1,306 | py | Python | helloWorld/helloWorldApp/consumers.py | jcheon/reddit_clone | e4efc5dac7b131e564296cb2421b296c860b47bf | [
"MIT"
] | 4 | 2019-10-29T22:49:54.000Z | 2020-02-17T06:14:07.000Z | helloWorld/helloWorldApp/consumers.py | jcheon/reddit_clone | e4efc5dac7b131e564296cb2421b296c860b47bf | [
"MIT"
] | 16 | 2019-11-25T02:39:18.000Z | 2022-02-10T13:28:22.000Z | helloWorld/helloWorldApp/consumers.py | jcheon/reddit_clone | e4efc5dac7b131e564296cb2421b296c860b47bf | [
"MIT"
] | 1 | 2020-02-17T06:14:08.000Z | 2020-02-17T06:14:08.000Z | # chat/consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
# Send message to room group
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
# Receive message from room group
async def chat_message(self, event):
message = event['message']
# Send message to WebSocket
await self.send(text_data=json.dumps({
'message': message
})) | 28.391304 | 71 | 0.607198 |
from channels.generic.websocket import AsyncWebsocketConsumer
import json
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
await self.channel_layer.group_add(
self.room_group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
await self.channel_layer.group_discard(
self.room_group_name,
self.channel_name
)
async def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['message']
await self.channel_layer.group_send(
self.room_group_name,
{
'type': 'chat_message',
'message': message
}
)
async def chat_message(self, event):
message = event['message']
await self.send(text_data=json.dumps({
'message': message
})) | true | true |
f727d5d867163c130092b8569593782b91841822 | 716 | py | Python | robustness/CLEVER/cal_clever.py | asplos2020/DRTest | c3de497142d9b226e518a1a0f95f7350d2f7acd6 | [
"MIT"
] | 1 | 2021-04-01T07:31:17.000Z | 2021-04-01T07:31:17.000Z | robustness/CLEVER/cal_clever.py | Justobe/DRTest | 85c3c9b2a46cafa7184130f2596c5f9eb3b20bff | [
"MIT"
] | null | null | null | robustness/CLEVER/cal_clever.py | Justobe/DRTest | 85c3c9b2a46cafa7184130f2596c5f9eb3b20bff | [
"MIT"
] | 1 | 2020-12-24T12:12:54.000Z | 2020-12-24T12:12:54.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
clever.py
Compute CLEVER score using collected Lipschitz constants
Copyright (C) 2017-2018, IBM Corp.
Copyright (C) 2017, Lily Weng <twweng@mit.edu>
and Huan Zhang <ecezhang@ucdavis.edu>
This program is licenced under the Apache 2.0 licence,
contained in the LICENCE file in this directory.
"""
from clever import clever_score
dataset='mnist'
models=['vgg13']
attacks=['oritest']
istarget='target'
#clever_score(data_folder='lipschitz_mat/target/mnist_lenet1')
for model in models:
for attack in attacks:
clever_score(data_folder='lipschitz_mat/'+istarget+'/'+dataset+'/'+model+'/'+attack+'/'+dataset+'_'+model, untargeted=False)
| 26.518519 | 132 | 0.717877 |
from clever import clever_score
dataset='mnist'
models=['vgg13']
attacks=['oritest']
istarget='target'
for model in models:
for attack in attacks:
clever_score(data_folder='lipschitz_mat/'+istarget+'/'+dataset+'/'+model+'/'+attack+'/'+dataset+'_'+model, untargeted=False)
| true | true |
f727d699f5a615818259e65a2e917920aa02c900 | 6,699 | py | Python | libs/segment_tree.py | yskang/AlgorithmPracticeWithPython | f7129bd1924a7961489198f0ee052d2cd1e9cf40 | [
"MIT"
] | null | null | null | libs/segment_tree.py | yskang/AlgorithmPracticeWithPython | f7129bd1924a7961489198f0ee052d2cd1e9cf40 | [
"MIT"
] | null | null | null | libs/segment_tree.py | yskang/AlgorithmPracticeWithPython | f7129bd1924a7961489198f0ee052d2cd1e9cf40 | [
"MIT"
] | null | null | null | from types import SimpleNamespace
class Segment_Tree:
'''
A Class used to get partial sum of an array and update data
...
Attributes
----------
array : list
a list which to make a segment tree
Methods
-------
init(tree, start, end, node)
make segment tree from the array. don't call this method directly.
sum(left, right, node=1, start=0, end=-1)
return the partial sum of the array.
update(index, diff, node=1, start=0, end=-1)
update the value of the index of array as +diff.
'''
def __init__(self, array):
'''
Parameters
----------
array : list
the array that you want to make tree
'''
self.array = array
self.tree = [SimpleNamespace(value=0, lazy=0) for _ in range(len(self.array) * 4)]
self.init(self.tree, 0, len(self.array)-1, 1)
self.last_index = len(array)-1
def init(self, tree, start, end, node):
'''
Don't Call This Method Directly
'''
if start == end:
tree[node].value = self.array[start]
return tree[node].value
mid = (start + end) // 2
tree[node].value = self.init(tree, start, mid, node * 2) + self.init(tree, mid + 1, end, node * 2 + 1)
return tree[node].value
def sum(self, left, right, node=1, start=0, end=-1):
'''
Parameters
----------
left : int
start index of the part [left, left+1, left+2 .. right-2, right-1, right]
right : int
end index of the part [left, left+1, left+2 .. right-2, right-1, right]
Returns
-------
int
a sum of the part of the array. sum([left, left+1, left+2 .. right-2, right-1, right])
'''
if end == -1:
end = self.last_index
if left > end or right < start:
return 0
if left <= start and end <= right:
return self.tree[node].value
return self.sum(left, right, node*2, start, (start+end)//2) + self.sum(left, right, node*2+1, (start+end)//2+1, end)
def lazy_sum(self, left, right, node=1, start=0, end=-1):
if end == -1:
end = self.last_index
if self.tree[node].lazy != 0:
self.tree[node].value += (end-start+1)*self.tree[node].lazy
if start != end:
self.tree[node*2].lazy += self.tree[node].lazy
self.tree[node*2+1].lazy += self.tree[node].lazy
self.tree[node].lazy = 0
if right < start or end < left:
return 0
if left <= start and end <= right:
return self.tree[node].value
return self.lazy_sum(left, right, node*2, start, (start+end)//2) + self.lazy_sum(left, right, node*2+1, (start+end)//2+1, end)
def update(self, index, diff, node=1, start=0, end=-1):
'''
Parameters
----------
index: int
the index of array. which you want to update value
diff: int
the amount of value which you wnat to add. if you want to make 4 to 10, put diff to 6
'''
if end == -1:
end = self.last_index
if not(start <= index <= end):
return
self.tree[node].value += diff
if start != end:
self.update(index, diff, node*2, start, (start+end)//2)
self.update(index, diff, node*2+1, (start+end)//2+1, end)
def update_range(self, diff, left, right, node=1, start=0, end=-1):
if end == -1:
end = self.last_index
if self.tree[node].lazy != 0:
self.tree[node].value += (end-start+1)*self.tree[node].lazy
if start != end:
self.tree[node*2].lazy += self.tree[node].lazy
self.tree[node*2+1].lazy += self.tree[node].lazy
self.tree[node].lazy = 0
if right < start or end < left:
return
if left <= start and end <= right:
self.tree[node].value += (end-start+1)*diff
if start != end:
self.tree[node*2].lazy += diff
self.tree[node*2+1].lazy += diff
return
self.update_range(diff, left, right, node*2, start, (start+end)//2)
self.update_range(diff, left, right, node*2+1, (start+end)//2+1, end)
self.tree[node].value = self.tree[node*2].value + self.tree[node*2+1].value
# init segment tree of an array from index start to end.
# return index of minimum value of array in range from start to end.
def init_segment_min(array, tree, node, start, end):
if start == end:
tree[node] = start
return tree[node]
mid = (start + end) // 2
left = init_segment_min(array, tree, node * 2, start, mid)
right = init_segment_min(array, tree, node * 2 + 1, mid + 1, end)
if array[left] < array[right]:
tree[node] = left
else:
tree[node] = right
return tree[node]
def find_min(array, tree, node, start, end, left, right):
if left > end or right < start:
return -1
if left <= start and end <= right:
return tree[node]
left_index = find_min(array, tree, node*2, start, (start+end)//2, left, right)
right_index = find_min(array, tree, node*2+1, (start+end)//2+1, end, left, right)
if left_index == -1 and right_index == -1:
return -1
elif left_index == -1:
return right_index
elif right_index == -1:
return left_index
else:
if array[left_index] < array[right_index]:
return left_index
return right_index
if __name__ == '__main__':
a = [3, 5, 6, 7, 2, 9, 4, 5, 2, 8, 1, 5]
# tree = [0 for _ in range(len(a) * 4)]
# tree2 = [0 for _ in range(len(a) * 4)]
# init_segment_sum(a, tree, 0, 11)
# print('a: {}'.format(a))
# print('segment tree(sum): {}'.format(tree))
# print('partial sum of (3~9): {}'.format(segment_sum(tree, 1, 0, 11, 3, 9)))
# print('update a[3] to 8')
# update(tree, 1, 0, 11, 3, 1)
# print('segment tree(sum): {}'.format(tree))
# print('partial sum of (3~9): {}'.format(segment_sum(tree, 1, 0, 11, 3, 9)))
segment = Segment_Tree(a)
print(segment.sum(3, 9))
segment.update(3, 1)
print(segment.sum(3, 9))
a = [1,2,3,4,5,6,7,8,9,10]
segment = Segment_Tree(a)
print(segment.lazy_sum(0, 9))
segment.update_range(10, 0, 4)
print(segment.lazy_sum(0, 9)) | 35.632979 | 135 | 0.526198 | from types import SimpleNamespace
class Segment_Tree:
def __init__(self, array):
self.array = array
self.tree = [SimpleNamespace(value=0, lazy=0) for _ in range(len(self.array) * 4)]
self.init(self.tree, 0, len(self.array)-1, 1)
self.last_index = len(array)-1
def init(self, tree, start, end, node):
if start == end:
tree[node].value = self.array[start]
return tree[node].value
mid = (start + end) // 2
tree[node].value = self.init(tree, start, mid, node * 2) + self.init(tree, mid + 1, end, node * 2 + 1)
return tree[node].value
def sum(self, left, right, node=1, start=0, end=-1):
if end == -1:
end = self.last_index
if left > end or right < start:
return 0
if left <= start and end <= right:
return self.tree[node].value
return self.sum(left, right, node*2, start, (start+end)//2) + self.sum(left, right, node*2+1, (start+end)//2+1, end)
def lazy_sum(self, left, right, node=1, start=0, end=-1):
if end == -1:
end = self.last_index
if self.tree[node].lazy != 0:
self.tree[node].value += (end-start+1)*self.tree[node].lazy
if start != end:
self.tree[node*2].lazy += self.tree[node].lazy
self.tree[node*2+1].lazy += self.tree[node].lazy
self.tree[node].lazy = 0
if right < start or end < left:
return 0
if left <= start and end <= right:
return self.tree[node].value
return self.lazy_sum(left, right, node*2, start, (start+end)//2) + self.lazy_sum(left, right, node*2+1, (start+end)//2+1, end)
def update(self, index, diff, node=1, start=0, end=-1):
if end == -1:
end = self.last_index
if not(start <= index <= end):
return
self.tree[node].value += diff
if start != end:
self.update(index, diff, node*2, start, (start+end)//2)
self.update(index, diff, node*2+1, (start+end)//2+1, end)
def update_range(self, diff, left, right, node=1, start=0, end=-1):
if end == -1:
end = self.last_index
if self.tree[node].lazy != 0:
self.tree[node].value += (end-start+1)*self.tree[node].lazy
if start != end:
self.tree[node*2].lazy += self.tree[node].lazy
self.tree[node*2+1].lazy += self.tree[node].lazy
self.tree[node].lazy = 0
if right < start or end < left:
return
if left <= start and end <= right:
self.tree[node].value += (end-start+1)*diff
if start != end:
self.tree[node*2].lazy += diff
self.tree[node*2+1].lazy += diff
return
self.update_range(diff, left, right, node*2, start, (start+end)//2)
self.update_range(diff, left, right, node*2+1, (start+end)//2+1, end)
self.tree[node].value = self.tree[node*2].value + self.tree[node*2+1].value
def init_segment_min(array, tree, node, start, end):
if start == end:
tree[node] = start
return tree[node]
mid = (start + end) // 2
left = init_segment_min(array, tree, node * 2, start, mid)
right = init_segment_min(array, tree, node * 2 + 1, mid + 1, end)
if array[left] < array[right]:
tree[node] = left
else:
tree[node] = right
return tree[node]
def find_min(array, tree, node, start, end, left, right):
if left > end or right < start:
return -1
if left <= start and end <= right:
return tree[node]
left_index = find_min(array, tree, node*2, start, (start+end)//2, left, right)
right_index = find_min(array, tree, node*2+1, (start+end)//2+1, end, left, right)
if left_index == -1 and right_index == -1:
return -1
elif left_index == -1:
return right_index
elif right_index == -1:
return left_index
else:
if array[left_index] < array[right_index]:
return left_index
return right_index
if __name__ == '__main__':
a = [3, 5, 6, 7, 2, 9, 4, 5, 2, 8, 1, 5]
segment = Segment_Tree(a)
print(segment.sum(3, 9))
segment.update(3, 1)
print(segment.sum(3, 9))
a = [1,2,3,4,5,6,7,8,9,10]
segment = Segment_Tree(a)
print(segment.lazy_sum(0, 9))
segment.update_range(10, 0, 4)
print(segment.lazy_sum(0, 9)) | true | true |
f727d6b9303a121e5f44d4ef4deb26145ae90ae4 | 1,154 | py | Python | single_comment.py | zhao123minghao/sentiment | c534496afa452785e87fedc09e4abb3625673f86 | [
"BSD-2-Clause"
] | null | null | null | single_comment.py | zhao123minghao/sentiment | c534496afa452785e87fedc09e4abb3625673f86 | [
"BSD-2-Clause"
] | null | null | null | single_comment.py | zhao123minghao/sentiment | c534496afa452785e87fedc09e4abb3625673f86 | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import sp
import pp
import fp
import step2
import ts
def sensplit(_src):
return pp.sensplit(_src,pp.sendivs)
argv = sys.argv
if(len(argv) < 2):
print 'we need an arguement'
sys.exit(0)
filename = argv[1]
if(not os.path.isfile(filename)):
print '\t\ttest file don\'t exist'
sys.exit(0)
plist = fp.readfile(filename)
slist = []
for line in plist:
slist += sensplit(line)
r = ''
for line in slist:
r = r + line + '\n'
fp.writefile('__tmp1.txt',r)
if(os.path.isfile('__tmp.txt')):
os.remove('__tmp.txt')
pp.divword('__tmp1.txt','__tmp.txt')
slist = fp.readfile('__tmp.txt')
sl = []
tmp = []
i = 0
length = len(slist)
while( i < length):
sens = slist[i]
i += 1
#print line
line = step2.line_div(sens)
tmp.append(line)
#ts._print(tmp)
rmp = []
for line in tmp:
#print line
rmp += sp.sentence(line)
#print rmp
for line in plist:
print line
for line in rmp:
#print line
if(line == []):
continue
if(line[0] == '' or line[3][0] == ''):
continue
print line[0],line[3][0],line[2][1]*line[3][2] | 18.612903 | 50 | 0.60312 |
import sys
import os
import sp
import pp
import fp
import step2
import ts
def sensplit(_src):
return pp.sensplit(_src,pp.sendivs)
argv = sys.argv
if(len(argv) < 2):
print 'we need an arguement'
sys.exit(0)
filename = argv[1]
if(not os.path.isfile(filename)):
print '\t\ttest file don\'t exist'
sys.exit(0)
plist = fp.readfile(filename)
slist = []
for line in plist:
slist += sensplit(line)
r = ''
for line in slist:
r = r + line + '\n'
fp.writefile('__tmp1.txt',r)
if(os.path.isfile('__tmp.txt')):
os.remove('__tmp.txt')
pp.divword('__tmp1.txt','__tmp.txt')
slist = fp.readfile('__tmp.txt')
sl = []
tmp = []
i = 0
length = len(slist)
while( i < length):
sens = slist[i]
i += 1
#print line
line = step2.line_div(sens)
tmp.append(line)
#ts._print(tmp)
rmp = []
for line in tmp:
#print line
rmp += sp.sentence(line)
#print rmp
for line in plist:
print line
for line in rmp:
#print line
if(line == []):
continue
if(line[0] == '' or line[3][0] == ''):
continue
print line[0],line[3][0],line[2][1]*line[3][2] | false | true |
f727d70b1803aaf3658f028f09b317b8765886e1 | 1,110 | py | Python | DataSynthesizer/datatypes/IntegerAttribute.py | crangelsmith/synthetic-data-tutorial | a997e045fa8d8384a812ba615af55ae418d68439 | [
"MIT"
] | 68 | 2019-03-21T13:39:01.000Z | 2022-01-22T13:53:43.000Z | DataSynthesizer/datatypes/IntegerAttribute.py | crangelsmith/synthetic-data-tutorial | a997e045fa8d8384a812ba615af55ae418d68439 | [
"MIT"
] | 3 | 2019-03-18T13:29:45.000Z | 2021-08-04T11:13:23.000Z | DataSynthesizer/datatypes/IntegerAttribute.py | crangelsmith/synthetic-data-tutorial | a997e045fa8d8384a812ba615af55ae418d68439 | [
"MIT"
] | 23 | 2020-01-14T10:05:03.000Z | 2021-12-08T03:43:10.000Z | from typing import Union
from pandas import Series
from datatypes.AbstractAttribute import AbstractAttribute
from datatypes.utils.DataType import DataType
class IntegerAttribute(AbstractAttribute):
def __init__(self, name: str, is_candidate_key, is_categorical, histogram_size: Union[int, str], data: Series):
super().__init__(name, is_candidate_key, is_categorical, histogram_size, data)
self.is_numerical = True
self.data_type = DataType.INTEGER
def infer_domain(self, categorical_domain=None, numerical_range=None):
super().infer_domain(categorical_domain, numerical_range)
self.min = int(self.min)
self.max = int(self.max)
def infer_distribution(self):
super().infer_distribution()
def generate_values_as_candidate_key(self, n):
return super().generate_values_as_candidate_key(n)
def sample_values_from_binning_indices(self, binning_indices):
column = super().sample_values_from_binning_indices(binning_indices)
column[~column.isnull()] = column[~column.isnull()].astype(int)
return column
| 37 | 115 | 0.741441 | from typing import Union
from pandas import Series
from datatypes.AbstractAttribute import AbstractAttribute
from datatypes.utils.DataType import DataType
class IntegerAttribute(AbstractAttribute):
def __init__(self, name: str, is_candidate_key, is_categorical, histogram_size: Union[int, str], data: Series):
super().__init__(name, is_candidate_key, is_categorical, histogram_size, data)
self.is_numerical = True
self.data_type = DataType.INTEGER
def infer_domain(self, categorical_domain=None, numerical_range=None):
super().infer_domain(categorical_domain, numerical_range)
self.min = int(self.min)
self.max = int(self.max)
def infer_distribution(self):
super().infer_distribution()
def generate_values_as_candidate_key(self, n):
return super().generate_values_as_candidate_key(n)
def sample_values_from_binning_indices(self, binning_indices):
column = super().sample_values_from_binning_indices(binning_indices)
column[~column.isnull()] = column[~column.isnull()].astype(int)
return column
| true | true |
f727d812d6c4a543c146cb1e1a5fbdc9a8873c15 | 45,449 | py | Python | t2t_bert/utils/tensor2tensor/trax/rlax/ppo.py | yyht/bert | 480c909e0835a455606e829310ff949c9dd23549 | [
"Apache-2.0"
] | 34 | 2018-12-19T01:00:57.000Z | 2021-03-26T09:36:37.000Z | t2t_bert/utils/tensor2tensor/trax/rlax/ppo.py | yyht/bert | 480c909e0835a455606e829310ff949c9dd23549 | [
"Apache-2.0"
] | 11 | 2018-12-25T03:37:59.000Z | 2021-08-25T14:43:58.000Z | t2t_bert/utils/tensor2tensor/trax/rlax/ppo.py | yyht/bert | 480c909e0835a455606e829310ff949c9dd23549 | [
"Apache-2.0"
] | 9 | 2018-12-27T08:00:44.000Z | 2020-06-08T03:05:14.000Z | # coding=utf-8
# Copyright 2019 The Tensor2Tensor Authors.
#
# 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.
"""PPO in JAX.
Notation:
B, scalar - batch size
T, scalar - number of time-steps in a trajectory, or the value of the padded
time-step dimension.
OBS, tuple - shape of a singular observation from the environment.
Ex: For CartPole-v0 this is (4,) and Pong-v0 it's (210, 160, 3)
A, scalar - Number of actions, assuming a discrete space.
Policy and Value function signatures:
Policy Function :: [B, T] + OBS -> [B, T, A]
Value Function :: [B, T] + OBS -> [B, T, 1]
Policy and Value Function :: [B, T] + OBS -> ([B, T, A], [B, T, 1])
i.e. the policy net should take a batch of *trajectories* and at each time-step
in each batch deliver a probability distribution over actions.
NOTE: It doesn't return logits, rather the expectation is that it returns
log-probabilities instead.
NOTE: The policy and value functions need to take care to not take into account
future time-steps while deciding the actions (or value) for the current
time-step.
Policy and Value Function produces a tuple of the expected output of a policy
function and a value function.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import os
import time
from absl import logging
import cloudpickle as pickle
import gin
import gym
from jax import grad
from jax import jit
from jax import lax
from jax import numpy as np
from jax import random as jax_random
import numpy as onp
from tensor2tensor.envs import env_problem
from tensor2tensor.envs import env_problem_utils
from tensor2tensor.trax import jaxboard
from tensor2tensor.trax import layers as tl
from tensor2tensor.trax import optimizers as trax_opt
from tensor2tensor.trax import trax
from tensorflow.io import gfile
DEBUG_LOGGING = False
GAMMA = 0.99
LAMBDA = 0.95
EPSILON = 0.1
EPOCHS = 50 # 100
N_OPTIMIZER_STEPS = 100
PRINT_EVERY_OPTIMIZER_STEP = 20
BATCH_TRAJECTORIES = 32
def policy_and_value_net(rng_key,
batch_observations_shape,
observations_dtype,
n_actions,
bottom_layers_fn=(),
two_towers=True):
"""A policy and value net function."""
# Layers.
# Now, with the current logits, one head computes action probabilities and the
# other computes the value function.
# NOTE: The LogSoftmax instead of the Softmax because of numerical stability.
if two_towers:
layers = [
tl.Dup(),
tl.Parallel(
[bottom_layers_fn(), tl.Dense(n_actions), tl.LogSoftmax()],
[bottom_layers_fn(), tl.Dense(1)],
)
]
else:
layers = [
bottom_layers_fn(),
tl.Dup(),
tl.Parallel(
[tl.Dense(n_actions), tl.LogSoftmax()],
[tl.Dense(1)],
)
]
net = tl.Model(layers)
params = net.initialize(batch_observations_shape, observations_dtype, rng_key)
return params, net
def optimizer_fn(net_params, step_size=1e-3):
opt = trax_opt.Adam(step_size=step_size, b1=0.9, b2=0.999, eps=1e-08)
opt_init = lambda x: (x, opt.tree_init(x))
opt_update = lambda i, g, s: opt.tree_update(i, g, s[0], s[1])
get_params = lambda x: x[0]
opt_state = opt_init(net_params)
return opt_state, opt_update, get_params
# Should this be collect 'n' trajectories, or
# Run the env for 'n' steps and take completed trajectories, or
# Any other option?
def collect_trajectories(env,
policy_fn,
n_trajectories=1,
policy=env_problem_utils.GUMBEL_SAMPLING,
max_timestep=None,
epsilon=0.1,
reset=True,
len_history_for_policy=32,
rng=None):
"""Collect trajectories with the given policy net and behaviour.
Args:
env: A gym env interface, for now this is not-batched.
policy_fn: observations(B,T+1) -> log-probabs(B,T+1, A) callable.
n_trajectories: int, number of trajectories.
policy: string, "greedy", "epsilon-greedy", or "categorical-sampling" i.e.
how to use the policy_fn to return an action.
max_timestep: int or None, the index of the maximum time-step at which we
return the trajectory, None for ending a trajectory only when env returns
done.
epsilon: float, the epsilon for `epsilon-greedy` policy.
reset: bool, true if we want to reset the envs. The envs are also reset if
max_max_timestep is None or < 0
len_history_for_policy: int, the maximum history to keep for applying the
policy on.
rng: jax rng, splittable.
Returns:
A tuple (trajectory, number of trajectories that are done)
trajectory: list of (observation, action, reward) tuples, where each element
`i` is a tuple of numpy arrays with shapes as follows:
observation[i] = (B, T_i + 1)
action[i] = (B, T_i)
reward[i] = (B, T_i)
"""
assert isinstance(env, env_problem.EnvProblem)
# This is an env_problem, run its collect function.
trajs, n_done, timing_info = env_problem_utils.play_env_problem_with_policy(
env,
policy_fn,
num_trajectories=n_trajectories,
max_timestep=max_timestep,
policy_sampling=policy,
eps=epsilon,
reset=reset,
len_history_for_policy=len_history_for_policy,
rng=rng)
# Skip returning raw_rewards here, since they aren't used.
# t is the return value of Trajectory.as_numpy, so:
# (observation, action, processed_reward, raw_reward, infos)
return [(t[0], t[1], t[2], t[4]) for t in trajs], n_done, timing_info
# This function can probably be simplified, ask how?
# Can we do something much simpler than lax.pad, maybe np.pad?
# Others?
def get_padding_value(dtype):
"""Returns the padding value given a dtype."""
padding_value = None
if dtype == np.uint8:
padding_value = np.uint8(0)
elif dtype == np.uint16:
padding_value = np.uint16(0)
elif dtype == np.float32 or dtype == np.float64:
padding_value = 0.0
else:
padding_value = 0
assert padding_value is not None
return padding_value
# TODO(afrozm): Use np.pad instead and make jittable?
def pad_trajectories(trajectories, boundary=20):
"""Pad trajectories to a bucket length that is a multiple of boundary.
Args:
trajectories: list[(observation, actions, rewards)], where each observation
is shaped (t+1,) + OBS and actions & rewards are shaped (t,), with the
length of the list being B (batch size).
boundary: int, bucket length, the actions and rewards are padded to integer
multiples of boundary.
Returns:
tuple: (padding lengths, reward_mask, padded_observations, padded_actions,
padded_rewards) where padded_observations is shaped (B, T+1) + OBS and
padded_actions, padded_rewards & reward_mask are shaped (B, T).
Where T is max(t) rounded up to an integer multiple of boundary.
padded_length is how much padding we've added and
reward_mask is 1s for actual rewards and 0s for the padding.
"""
# Let's compute max(t) over all trajectories.
t_max = max(r.shape[0] for (_, _, r, _) in trajectories)
# t_max is rounded to the next multiple of `boundary`
boundary = int(boundary)
bucket_length = boundary * int(np.ceil(float(t_max) / boundary))
# So all obs will be padded to t_max + 1 and actions and rewards to t_max.
padded_observations = []
padded_actions = []
padded_rewards = []
padded_infos = collections.defaultdict(list)
padded_lengths = []
reward_masks = []
for (o, a, r, i) in trajectories:
# Determine the amount to pad, this holds true for obs, actions and rewards.
num_to_pad = bucket_length + 1 - o.shape[0]
padded_lengths.append(num_to_pad)
if num_to_pad == 0:
padded_observations.append(o)
padded_actions.append(a)
padded_rewards.append(r)
reward_masks.append(onp.ones_like(r, dtype=np.int32))
if i:
for k, v in i.items():
padded_infos[k].append(v)
continue
# First pad observations.
padding_config = tuple([(0, num_to_pad, 0)] + [(0, 0, 0)] * (o.ndim - 1))
padding_value = get_padding_value(o.dtype)
action_padding_value = get_padding_value(a.dtype)
reward_padding_value = get_padding_value(r.dtype)
padded_obs = lax.pad(o, padding_value, padding_config)
padded_observations.append(padded_obs)
# Now pad actions and rewards.
assert a.ndim == 1 and r.ndim == 1
padding_config = ((0, num_to_pad, 0),)
padded_action = lax.pad(a, action_padding_value, padding_config)
padded_actions.append(padded_action)
padded_reward = lax.pad(r, reward_padding_value, padding_config)
padded_rewards.append(padded_reward)
# Also create the mask to use later.
reward_mask = onp.ones_like(r, dtype=np.int32)
reward_masks.append(lax.pad(reward_mask, 0, padding_config))
if i:
for k, v in i.items():
# Create a padding configuration for this value.
padding_config = [(0, num_to_pad, 0)] + [(0, 0, 0)] * (v.ndim - 1)
padded_infos[k].append(lax.pad(v, 0.0, tuple(padding_config)))
# Now stack these padded_infos if they exist.
stacked_padded_infos = None
if padded_infos:
stacked_padded_infos = {k: np.stack(v) for k, v in padded_infos.items()}
return padded_lengths, np.stack(reward_masks), np.stack(
padded_observations), np.stack(padded_actions), np.stack(
padded_rewards), stacked_padded_infos
def rewards_to_go(rewards, mask, gamma=0.99):
r"""Computes rewards to go.
Reward to go is defined as follows, the discounted reward that we have to
yet collect, going forward from this point, i.e.:
r2g_t = \sum_{l=0}^{\infty} (\gamma^{l} * reward_{t+l})
Args:
rewards: np.ndarray of shape (B, T) of rewards.
mask: np.ndarray of shape (B, T) of mask for the rewards.
gamma: float, discount factor.
Returns:
rewards to go, np.ndarray of shape (B, T).
"""
B, T = rewards.shape # pylint: disable=invalid-name,unused-variable
masked_rewards = rewards * mask # (B, T)
# The lax.scan version of this is slow, but we still show it here for
# completeness.
# rewards_rev = np.flip(masked_rewards, axis=1) # (B, T) flipped on time.
# rrt = np.transpose(rewards_rev) # (T, B) transpose to scan over time.
#
# def discounting_add(carry, reward):
# x = reward + (gamma * carry)
# return x, x
#
# _, ys = lax.scan(discounting_add,
# np.zeros_like(rrt[0], dtype=np.float32),
# rrt.astype(np.float32))
#
# # ys is (T, B) and T is in reverse order.
# return np.flip(np.transpose(ys), axis=1)
# We use the following recurrence relation, derived from the equation above:
#
# r2g[t+1] = (r2g[t] - r[t]) / gamma
#
# This means we'll need to calculate r2g[0] first and then r2g[1] and so on ..
#
# **However** this leads to overflows for long sequences: r2g[t] - r[t] > 0
# and gamma < 1.0, so the division keeps increasing.
#
# So we just run the recurrence in reverse, i.e.
#
# r2g[t] = r[t] + (gamma*r2g[t+1])
#
# This is much better, but might have lost updates since the (small) rewards
# at earlier time-steps may get added to a (very?) large sum.
# Compute r2g_{T-1} at the start and then compute backwards in time.
r2gs = [masked_rewards[:, -1]]
# Go from T-2 down to 0.
for t in reversed(range(T - 1)):
r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1]))
# The list should have length T.
assert T == len(r2gs)
# First we stack them in the correct way to make it (B, T), but these are
# still from newest (T-1) to oldest (0), so then we flip it on time axis.
return np.flip(np.stack(r2gs, axis=1), axis=1)
@jit
def value_loss_given_predictions(value_prediction,
rewards,
reward_mask,
gamma=0.99,
epsilon=0.2,
value_prediction_old=None):
"""Computes the value loss given the prediction of the value function.
Args:
value_prediction: np.ndarray of shape (B, T+1, 1)
rewards: np.ndarray of shape (B, T) of rewards.
reward_mask: np.ndarray of shape (B, T), the mask over rewards.
gamma: float, discount factor.
epsilon: float, clip-fraction, used if value_value_prediction_old isn't None
value_prediction_old: np.ndarray of shape (B, T+1, 1) of value predictions
using the old parameters. If provided, we incorporate this in the loss as
well. This is from the OpenAI baselines implementation.
Returns:
The average L2 value loss, averaged over instances where reward_mask is 1.
"""
B, T = rewards.shape # pylint: disable=invalid-name
assert (B, T) == reward_mask.shape
assert (B, T + 1, 1) == value_prediction.shape
value_prediction = np.squeeze(value_prediction, axis=2) # (B, T+1)
value_prediction = value_prediction[:, :-1] * reward_mask # (B, T)
r2g = rewards_to_go(rewards, reward_mask, gamma=gamma) # (B, T)
loss = (value_prediction - r2g)**2
# From the baselines implementation.
if value_prediction_old is not None:
value_prediction_old = np.squeeze(value_prediction_old, axis=2) # (B, T+1)
value_prediction_old = value_prediction_old[:, :-1] * reward_mask # (B, T)
v_clipped = value_prediction_old + np.clip(
value_prediction - value_prediction_old, -epsilon, epsilon)
v_clipped_loss = (v_clipped - r2g)**2
loss = np.maximum(v_clipped_loss, loss)
# Take an average on only the points where mask != 0.
return np.sum(loss) / np.sum(reward_mask)
def deltas(predicted_values, rewards, mask, gamma=0.99):
r"""Computes TD-residuals from V(s) and rewards.
Where a `delta`, i.e. a td-residual is defined as:
delta_{b,t} = r_{b,t} + \gamma * v_{b,t+1} - v_{b,t}.
Args:
predicted_values: ndarray of shape (B, T+1). NOTE: Expects axis 2 was
squeezed. These represent V(s_bt) for b < B and t < T+1
rewards: ndarray of shape (B, T) of rewards.
mask: ndarray of shape (B, T) of mask for rewards.
gamma: float, discount factor.
Returns:
ndarray of shape (B, T) of one-step TD-residuals.
"""
# Predicted values at time t, cutting off the last to have shape (B, T).
predicted_values_bt = predicted_values[:, :-1]
# Predicted values at time t+1, by cutting off the first to have shape (B, T)
predicted_values_btplus1 = predicted_values[:, 1:]
# Return the deltas as defined above.
return (rewards +
(gamma * predicted_values_btplus1) - predicted_values_bt) * mask
def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99):
r"""Computes the GAE advantages given the one step TD-residuals.
The formula for a GAE advantage estimator is as follows:
A_{bt} = \sum_{l=0}^{\infty}(\gamma * \lambda)^{l}(\delta_{b,t+l}).
Internally we just call rewards_to_go, since it is the same computation.
Args:
td_deltas: np.ndarray of shape (B, T) of one step TD-residuals.
mask: np.ndarray of shape (B, T) of mask for the residuals. It maybe the
case that the `td_deltas` are already masked correctly since they are
produced by `deltas(...)`
lambda_: float, lambda parameter for GAE estimators.
gamma: float, lambda parameter for GAE estimators.
Returns:
GAE advantage estimates.
"""
return rewards_to_go(td_deltas, mask, lambda_ * gamma)
def chosen_probabs(probab_observations, actions):
"""Picks out the probabilities of the actions along batch and time-steps.
Args:
probab_observations: ndarray of shape `[B, T+1, A]`, where
probab_observations[b, t, i] contains the log-probability of action = i at
the t^th time-step in the b^th trajectory.
actions: ndarray of shape `[B, T]`, with each entry in [0, A) denoting which
action was chosen in the b^th trajectory's t^th time-step.
Returns:
`[B, T]` ndarray with the log-probabilities of the chosen actions.
"""
B, T = actions.shape # pylint: disable=invalid-name
assert (B, T + 1) == probab_observations.shape[:2]
return probab_observations[np.arange(B)[:, None], np.arange(T), actions]
def compute_probab_ratios(p_new, p_old, actions, reward_mask):
"""Computes the probability ratios for each time-step in a trajectory.
Args:
p_new: ndarray of shape [B, T+1, A] of the log-probabilities that the policy
network assigns to all the actions at each time-step in each batch using
the old parameters.
p_old: ndarray of shape [B, T+1, A], same as above, but using old policy
network parameters.
actions: ndarray of shape [B, T] where each element is from [0, A).
reward_mask: ndarray of shape [B, T] masking over probabilities.
Returns:
probab_ratios: ndarray of shape [B, T], where
probab_ratios_{b,t} = p_new_{b,t,action_{b,t}} / p_old_{b,t,action_{b,t}}
"""
B, T = actions.shape # pylint: disable=invalid-name
assert (B, T + 1) == p_old.shape[:2]
assert (B, T + 1) == p_new.shape[:2]
logp_old = chosen_probabs(p_old, actions)
logp_new = chosen_probabs(p_new, actions)
assert (B, T) == logp_old.shape
assert (B, T) == logp_new.shape
# Since these are log-probabilities, we just subtract them.
probab_ratios = np.exp(logp_new - logp_old) * reward_mask
assert (B, T) == probab_ratios.shape
return probab_ratios
def clipped_probab_ratios(probab_ratios, epsilon=0.2):
return np.clip(probab_ratios, 1 - epsilon, 1 + epsilon)
def clipped_objective(probab_ratios, advantages, reward_mask, epsilon=0.2):
return np.minimum(
probab_ratios * advantages,
clipped_probab_ratios(probab_ratios, epsilon=epsilon) *
advantages) * reward_mask
@jit
def ppo_loss_given_predictions(log_probab_actions_new,
log_probab_actions_old,
value_predictions_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
epsilon=0.2):
"""PPO objective, with an eventual minus sign, given predictions."""
B, T = padded_rewards.shape # pylint: disable=invalid-name
assert (B, T) == padded_actions.shape
assert (B, T) == reward_mask.shape
_, _, A = log_probab_actions_old.shape # pylint: disable=invalid-name
assert (B, T + 1, 1) == value_predictions_old.shape
assert (B, T + 1, A) == log_probab_actions_old.shape
assert (B, T + 1, A) == log_probab_actions_new.shape
# (B, T)
td_deltas = deltas(
np.squeeze(value_predictions_old, axis=2), # (B, T+1)
padded_rewards,
reward_mask,
gamma=gamma)
# (B, T)
advantages = gae_advantages(
td_deltas, reward_mask, lambda_=lambda_, gamma=gamma)
# Normalize the advantages.
advantages = (advantages - np.mean(advantages)) / np.std(advantages)
# (B, T)
ratios = compute_probab_ratios(log_probab_actions_new, log_probab_actions_old,
padded_actions, reward_mask)
assert (B, T) == ratios.shape
# (B, T)
objective = clipped_objective(
ratios, advantages, reward_mask, epsilon=epsilon)
assert (B, T) == objective.shape
# ()
average_objective = np.sum(objective) / np.sum(reward_mask)
# Loss is negative objective.
return -average_objective
@jit
def combined_loss_given_predictions(log_probab_actions_new,
log_probab_actions_old,
value_prediction_new,
value_prediction_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
epsilon=0.2,
c1=1.0,
c2=0.01):
"""Computes the combined (clipped loss + value loss) given predictions."""
loss_value = value_loss_given_predictions(
value_prediction_new,
padded_rewards,
reward_mask,
gamma=gamma,
value_prediction_old=value_prediction_old,
epsilon=epsilon)
loss_ppo = ppo_loss_given_predictions(
log_probab_actions_new,
log_probab_actions_old,
value_prediction_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon)
entropy_bonus = masked_entropy(log_probab_actions_new, reward_mask)
return (loss_ppo + (c1 * loss_value) - (c2 * entropy_bonus), loss_ppo,
loss_value, entropy_bonus)
@functools.partial(jit, static_argnums=(3,))
def combined_loss(new_params,
log_probab_actions_old,
value_predictions_old,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
epsilon=0.2,
c1=1.0,
c2=0.01,
rng=None):
"""Computes the combined (clipped loss + value loss) given observations."""
log_probab_actions_new, value_predictions_new = policy_and_value_net_apply(
padded_observations, new_params, rng=rng)
# (combined_loss, ppo_loss, value_loss, entropy_bonus)
return combined_loss_given_predictions(
log_probab_actions_new,
log_probab_actions_old,
value_predictions_new,
value_predictions_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon,
c1=c1,
c2=c2)
@functools.partial(jit, static_argnums=(2, 3, 4))
def policy_and_value_opt_step(i,
opt_state,
opt_update,
get_params,
policy_and_value_net_apply,
log_probab_actions_old,
value_predictions_old,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
c1=1.0,
c2=0.01,
gamma=0.99,
lambda_=0.95,
epsilon=0.1,
rng=None):
"""Policy and Value optimizer step."""
# Combined loss function given the new params.
def policy_and_value_loss(params):
"""Returns the combined loss given just parameters."""
(loss, _, _, _) = combined_loss(
params,
log_probab_actions_old,
value_predictions_old,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
c1=c1,
c2=c2,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon,
rng=rng)
return loss
new_params = get_params(opt_state)
g = grad(policy_and_value_loss)(new_params)
# TODO(afrozm): Maybe clip gradients?
return opt_update(i, g, opt_state)
def get_time(t1, t2=None):
if t2 is None:
t2 = time.time()
return round((t2 - t1) * 1000, 2)
def approximate_kl(log_prob_new, log_prob_old, mask):
"""Computes the approximate KL divergence between the old and new log-probs.
Args:
log_prob_new: (B, T+1, A) log probs new
log_prob_old: (B, T+1, A) log probs old
mask: (B, T)
Returns:
Approximate KL.
"""
diff = log_prob_old - log_prob_new
# Cut the last time-step out.
diff = diff[:, :-1]
# Mask out the irrelevant part.
diff *= mask[:, :, np.newaxis] # make mask (B, T, 1)
# Average on non-masked part.
return np.sum(diff) / np.sum(mask)
def masked_entropy(log_probs, mask):
"""Computes the entropy for the given log-probs.
Args:
log_probs: (B, T+1, A) log probs
mask: (B, T) mask.
Returns:
Entropy.
"""
# Cut the last time-step out.
lp = log_probs[:, :-1]
# Mask out the irrelevant part.
lp *= mask[:, :, np.newaxis] # make mask (B, T, 1)
p = np.exp(lp) * mask[:, :, np.newaxis] # (B, T, 1)
# Average on non-masked part and take negative.
return -(np.sum(lp * p) / np.sum(mask))
def evaluate_policy(eval_env,
get_predictions,
temperatures,
max_timestep=20000,
n_evals=1,
len_history_for_policy=32,
rng=None):
"""Evaluate the policy."""
processed_reward_sums = collections.defaultdict(list)
raw_reward_sums = collections.defaultdict(list)
for eval_rng in jax_random.split(rng, num=n_evals):
for temperature in temperatures:
trajs, _, _ = env_problem_utils.play_env_problem_with_policy(
eval_env,
get_predictions,
num_trajectories=eval_env.batch_size,
max_timestep=max_timestep,
reset=True,
policy_sampling=env_problem_utils.GUMBEL_SAMPLING,
temperature=temperature,
rng=eval_rng,
len_history_for_policy=len_history_for_policy)
processed_reward_sums[temperature].extend(sum(traj[2]) for traj in trajs)
raw_reward_sums[temperature].extend(sum(traj[3]) for traj in trajs)
# Return the mean and standard deviation for each temperature.
def compute_stats(reward_dict):
return {
temperature: {"mean": onp.mean(rewards), "std": onp.std(rewards)}
for (temperature, rewards) in reward_dict.items()
}
return {
"processed": compute_stats(processed_reward_sums),
"raw": compute_stats(raw_reward_sums),
}
def maybe_restore_params(output_dir, policy_and_value_net_params):
"""Maybe restore the params from the checkpoint dir.
Args:
output_dir: Directory where saved model checkpoints are stored.
policy_and_value_net_params: Default params, returned if model is'nt found.
Returns:
triple (restore (bool), params, iter(int)) where iter is the epoch from
which we restored the params, 0 is restore = False.
"""
model_files = gfile.glob(os.path.join(output_dir, "model-??????.pkl"))
for model_file in reversed(sorted(model_files)):
logging.info("Trying to restore model from %s", model_file)
try:
with gfile.GFile(model_file, "rb") as f:
loaded_policy_and_value_net_params = pickle.load(f)
policy_and_value_net_params = loaded_policy_and_value_net_params
model_file_basename = os.path.basename(model_file) # model-??????.pkl
i = int(filter(str.isdigit, model_file_basename))
return True, policy_and_value_net_params, i
except EOFError as e:
logging.error("Unable to load model from: %s with %s", model_file, e)
# Try an older version.
continue
return False, policy_and_value_net_params, 0
def write_eval_reward_summaries(reward_stats_by_mode, summary_writer, epoch):
"""Writes evaluation reward statistics to summary and logs them.
Args:
reward_stats_by_mode: Nested dict of structure:
{
"raw": {
<temperature 1>: {
"mean": <reward mean>,
"std": <reward std>,
},
<temperature 2>: ...
},
"processed": ...
}
summary_writer: jaxboard.SummaryWriter.
epoch: Current epoch number.
"""
for (reward_mode, reward_stats_by_temp) in reward_stats_by_mode.items():
for (temperature, reward_stats) in reward_stats_by_temp.items():
for (stat_name, stat) in reward_stats.items():
summary_writer.scalar(
"eval/{reward_mode}_reward_{stat_name}/"
"temperature_{temperature}".format(reward_mode=reward_mode,
stat_name=stat_name,
temperature=temperature),
stat, step=epoch)
logging.info("Epoch [% 6d] Policy Evaluation (%s reward) "
"[temperature %.2f] = %10.2f (+/- %.2f)",
epoch, reward_mode, temperature,
reward_stats["mean"], reward_stats["std"])
@gin.configurable(blacklist=["output_dir"])
def training_loop(
env,
eval_env,
env_name,
policy_and_value_net_fn,
policy_and_value_optimizer_fn,
output_dir,
epochs=EPOCHS,
n_optimizer_steps=N_OPTIMIZER_STEPS,
print_every_optimizer_steps=PRINT_EVERY_OPTIMIZER_STEP,
target_kl=0.01,
boundary=20,
max_timestep=None,
max_timestep_eval=20000,
random_seed=None,
gamma=GAMMA,
lambda_=LAMBDA,
epsilon=EPSILON,
c1=1.0,
c2=0.01,
eval_every_n=1000,
done_frac_for_policy_save=0.5,
enable_early_stopping=True,
n_evals=1,
len_history_for_policy=4,
eval_temperatures=(1.0, 0.5),
):
"""Runs the training loop for PPO, with fixed policy and value nets.
Args:
env: gym.Env to use for training.
eval_env: gym.Env to use for evaluation.
env_name: Name of the environment.
policy_and_value_net_fn: Function defining the policy and value network.
policy_and_value_optimizer_fn: Function defining the optimizer.
output_dir: Output dir.
epochs: Number of epochs to run for.
n_optimizer_steps: Number of optimizer steps.
print_every_optimizer_steps: How often to log during the policy optimization
process.
target_kl: Policy iteration early stopping.
boundary: We pad trajectories at integer multiples of this number.
max_timestep: If set to an integer, maximum number of time-steps in
a trajectory. Used in the collect procedure.
max_timestep_eval: If set to an integer, maximum number of time-steps in an
evaluation trajectory. Used in the collect procedure.
random_seed: Random seed.
gamma: Reward discount factor.
lambda_: N-step TD-error discount factor in GAE.
epsilon: Random action probability in epsilon-greedy sampling.
c1: Value loss coefficient.
c2: Entropy loss coefficient.
eval_every_n: How frequently to eval the policy.
done_frac_for_policy_save: Fraction of the trajectories that should be done
to checkpoint the policy.
enable_early_stopping: Whether to enable early stopping.
n_evals: Number of times to evaluate.
len_history_for_policy: How much of history to give to the policy.
eval_temperatures: Sequence of temperatures to try for categorical sampling
during evaluation.
"""
gfile.makedirs(output_dir)
# Create summary writers and history.
train_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "train"))
timing_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "timing"))
eval_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "eval"))
train_sw.text("env_name", env_name)
timing_sw.text("env_name", env_name)
eval_sw.text("env_name", env_name)
jax_rng_key = trax.get_random_number_generator_and_set_seed(random_seed)
# Batch Observations Shape = [1, 1] + OBS, because we will eventually call
# policy and value networks on shape [B, T] +_OBS
batch_observations_shape = (1, 1) + env.observation_space.shape
observations_dtype = env.observation_space.dtype
assert isinstance(env.action_space, gym.spaces.Discrete)
n_actions = env.action_space.n
jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2)
# Initialize the policy and value network.
policy_and_value_net_params, policy_and_value_net_apply = (
policy_and_value_net_fn(key1, batch_observations_shape,
observations_dtype, n_actions))
# Maybe restore the policy params. If there is nothing to restore, then
# iteration = 0 and policy_and_value_net_params are returned as is.
restore, policy_and_value_net_params, iteration = (
maybe_restore_params(output_dir, policy_and_value_net_params))
if restore:
logging.info("Restored parameters from iteration [%d]", iteration)
# We should start from the next iteration.
iteration += 1
policy_and_value_net_apply = jit(policy_and_value_net_apply)
# Initialize the optimizers.
policy_and_value_optimizer = (
policy_and_value_optimizer_fn(policy_and_value_net_params))
(policy_and_value_opt_state, policy_and_value_opt_update,
policy_and_value_get_params) = policy_and_value_optimizer
n_trajectories_done = 0
last_saved_at = 0
logging.info("Starting the PPO training loop.")
for i in range(iteration, epochs):
epoch_start_time = time.time()
# Params we'll use to collect the trajectories.
policy_and_value_net_params = policy_and_value_get_params(
policy_and_value_opt_state)
# A function to get the policy and value predictions.
def get_predictions(observations, rng=None):
"""Returns log-probs, value predictions and key back."""
key, key1 = jax_random.split(rng, num=2)
log_probs, value_preds = policy_and_value_net_apply(
observations, policy_and_value_net_params, rng=key1)
return log_probs, value_preds, key
# Evaluate the policy.
policy_eval_start_time = time.time()
if ((i + 1) % eval_every_n == 0) or (i == epochs - 1):
jax_rng_key, key = jax_random.split(jax_rng_key, num=2)
logging.vlog(1, "Epoch [% 6d] evaluating policy.", i)
reward_stats = evaluate_policy(
eval_env,
get_predictions,
temperatures=eval_temperatures,
max_timestep=max_timestep_eval,
n_evals=n_evals,
len_history_for_policy=len_history_for_policy,
rng=key)
write_eval_reward_summaries(reward_stats, eval_sw, epoch=i)
policy_eval_time = get_time(policy_eval_start_time)
trajectory_collection_start_time = time.time()
logging.vlog(1, "Epoch [% 6d] collecting trajectories.", i)
jax_rng_key, key = jax_random.split(jax_rng_key)
trajs, n_done, timing_info = collect_trajectories(
env,
policy_fn=get_predictions,
n_trajectories=env.batch_size,
max_timestep=max_timestep,
rng=key,
len_history_for_policy=len_history_for_policy,
reset=(i == 0) or restore,
epsilon=(10.0 / (i + 10.0))) # this is a different epsilon.
trajectory_collection_time = get_time(trajectory_collection_start_time)
logging.vlog(1, "Collecting trajectories took %0.2f msec.",
trajectory_collection_time)
avg_reward = float(sum(np.sum(traj[2]) for traj in trajs)) / len(trajs)
max_reward = max(np.sum(traj[2]) for traj in trajs)
min_reward = min(np.sum(traj[2]) for traj in trajs)
train_sw.scalar("train/reward_mean_truncated", avg_reward, step=i)
logging.vlog(1, "Rewards avg=[%0.2f], max=[%0.2f], min=[%0.2f], all=%s",
avg_reward, max_reward, min_reward,
[float(np.sum(traj[2])) for traj in trajs])
logging.vlog(1,
"Trajectory Length average=[%0.2f], max=[%0.2f], min=[%0.2f]",
float(sum(len(traj[0]) for traj in trajs)) / len(trajs),
max(len(traj[0]) for traj in trajs),
min(len(traj[0]) for traj in trajs))
logging.vlog(2, "Trajectory Lengths: %s", [len(traj[0]) for traj in trajs])
padding_start_time = time.time()
(_, reward_mask, padded_observations, padded_actions,
padded_rewards, padded_infos) = pad_trajectories(
trajs, boundary=boundary)
padding_time = get_time(padding_start_time)
logging.vlog(1, "Padding trajectories took %0.2f msec.",
get_time(padding_start_time))
logging.vlog(1, "Padded Observations' shape [%s]",
str(padded_observations.shape))
logging.vlog(1, "Padded Actions' shape [%s]", str(padded_actions.shape))
logging.vlog(1, "Padded Rewards' shape [%s]", str(padded_rewards.shape))
# Some assertions.
B, T = padded_actions.shape # pylint: disable=invalid-name
assert (B, T) == padded_rewards.shape
assert (B, T) == reward_mask.shape
assert (B, T + 1) == padded_observations.shape[:2]
assert (B, T + 1) + env.observation_space.shape == padded_observations.shape
log_prob_recompute_start_time = time.time()
assert ("log_prob_actions" in padded_infos and
"value_predictions" in padded_infos)
# These are the actual log-probabs and value predictions seen while picking
# the actions.
actual_log_probabs_traj = padded_infos["log_prob_actions"]
actual_value_predictions_traj = padded_infos["value_predictions"]
assert (B, T) == actual_log_probabs_traj.shape[:2]
A = actual_log_probabs_traj.shape[2] # pylint: disable=invalid-name
assert (B, T, 1) == actual_value_predictions_traj.shape
# TODO(afrozm): log-probabs doesn't need to be (B, T+1, A) it can do with
# (B, T, A), so make that change throughout.
# NOTE: We don't have the log-probabs and value-predictions for the last
# observation, so we re-calculate for everything, but use the original ones
# for all but the last time-step.
jax_rng_key, key = jax_random.split(jax_rng_key)
log_probabs_traj, value_predictions_traj, _ = get_predictions(
padded_observations, rng=key)
assert (B, T + 1, A) == log_probabs_traj.shape
assert (B, T + 1, 1) == value_predictions_traj.shape
# Concatenate the last time-step's log-probabs and value predictions to the
# actual log-probabs and value predictions and use those going forward.
log_probabs_traj = np.concatenate(
(actual_log_probabs_traj, log_probabs_traj[:, -1:, :]), axis=1)
value_predictions_traj = np.concatenate(
(actual_value_predictions_traj, value_predictions_traj[:, -1:, :]),
axis=1)
log_prob_recompute_time = get_time(log_prob_recompute_start_time)
# Linear annealing from 0.1 to 0.0
# epsilon_schedule = epsilon if epochs == 1 else epsilon * (1.0 -
# (i /
# (epochs - 1)))
# Constant epsilon.
epsilon_schedule = epsilon
# Compute value and ppo losses.
jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2)
logging.vlog(2, "Starting to compute P&V loss.")
loss_compute_start_time = time.time()
cur_combined_loss, cur_ppo_loss, cur_value_loss, entropy_bonus = (
combined_loss(
policy_and_value_net_params,
log_probabs_traj,
value_predictions_traj,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon_schedule,
c1=c1,
c2=c2,
rng=key1))
loss_compute_time = get_time(loss_compute_start_time)
logging.vlog(
1,
"Calculating P&V loss [%10.2f(%10.2f, %10.2f, %10.2f)] took %0.2f msec.",
cur_combined_loss, cur_value_loss, cur_ppo_loss, entropy_bonus,
get_time(loss_compute_start_time))
jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2)
logging.vlog(1, "Policy and Value Optimization")
optimization_start_time = time.time()
keys = jax_random.split(key1, num=n_optimizer_steps)
for j in range(n_optimizer_steps):
k1, k2, k3 = jax_random.split(keys[j], num=3)
t = time.time()
# Update the optimizer state.
policy_and_value_opt_state = policy_and_value_opt_step(
j,
policy_and_value_opt_state,
policy_and_value_opt_update,
policy_and_value_get_params,
policy_and_value_net_apply,
log_probabs_traj,
value_predictions_traj,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
c1=c1,
c2=c2,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon_schedule,
rng=k1)
# Compute the approx KL for early stopping.
new_policy_and_value_net_params = policy_and_value_get_params(
policy_and_value_opt_state)
log_probab_actions_new, _ = policy_and_value_net_apply(
padded_observations, new_policy_and_value_net_params, rng=k2)
approx_kl = approximate_kl(log_probab_actions_new, log_probabs_traj,
reward_mask)
early_stopping = enable_early_stopping and approx_kl > 1.5 * target_kl
if early_stopping:
logging.vlog(
1, "Early stopping policy and value optimization at iter: %d, "
"with approx_kl: %0.2f", j, approx_kl)
# We don't return right-away, we want the below to execute on the last
# iteration.
t2 = time.time()
if (((j + 1) % print_every_optimizer_steps == 0) or
(j == n_optimizer_steps - 1) or early_stopping):
# Compute and log the loss.
(loss_combined, loss_ppo, loss_value, entropy_bonus) = (
combined_loss(
new_policy_and_value_net_params,
log_probabs_traj,
value_predictions_traj,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon_schedule,
c1=c1,
c2=c2,
rng=k3))
logging.vlog(1, "One Policy and Value grad desc took: %0.2f msec",
get_time(t, t2))
logging.vlog(
1, "Combined Loss(value, ppo, entropy_bonus) [%10.2f] ->"
" [%10.2f(%10.2f,%10.2f,%10.2f)]", cur_combined_loss, loss_combined,
loss_value, loss_ppo, entropy_bonus)
if early_stopping:
break
optimization_time = get_time(optimization_start_time)
logging.vlog(
1, "Total Combined Loss reduction [%0.2f]%%",
(100 * (cur_combined_loss - loss_combined) / np.abs(cur_combined_loss)))
# Save parameters every time we see the end of at least a fraction of batch
# number of trajectories that are done (not completed -- completed includes
# truncated and done).
# Also don't save too frequently, enforce a minimum gap.
# Or if this is the last iteration.
policy_save_start_time = time.time()
n_trajectories_done += n_done
# TODO(afrozm): Refactor to trax.save_state.
if (((n_trajectories_done >= done_frac_for_policy_save * env.batch_size) and
(i - last_saved_at > eval_every_n) and
(((i + 1) % eval_every_n == 0))) or (i == epochs - 1)):
logging.vlog(1, "Epoch [% 6d] saving model.", i)
old_model_files = gfile.glob(os.path.join(output_dir, "model-??????.pkl"))
params_file = os.path.join(output_dir, "model-%06d.pkl" % i)
with gfile.GFile(params_file, "wb") as f:
pickle.dump(policy_and_value_net_params, f)
# Remove the old model files.
for path in old_model_files:
gfile.remove(path)
# Reset this number.
n_trajectories_done = 0
last_saved_at = i
policy_save_time = get_time(policy_save_start_time)
epoch_time = get_time(epoch_start_time)
logging.info(
"Epoch [% 6d], Reward[min, max, avg] [%5.2f,%5.2f,%5.2f], Combined"
" Loss(value, ppo, entropy) [%2.5f(%2.5f,%2.5f,%2.5f)]", i, min_reward,
max_reward, avg_reward, loss_combined, loss_value, loss_ppo,
entropy_bonus)
timing_dict = {
"epoch": epoch_time,
"policy_eval": policy_eval_time,
"trajectory_collection": trajectory_collection_time,
"padding": padding_time,
"log_prob_recompute": log_prob_recompute_time,
"loss_compute": loss_compute_time,
"optimization": optimization_time,
"policy_save": policy_save_time,
}
timing_dict.update(timing_info)
for k, v in timing_dict.items():
timing_sw.scalar("timing/%s" % k, v, step=i)
max_key_len = max(len(k) for k in timing_dict)
timing_info_list = [
"%s : % 10.2f" % (k.rjust(max_key_len + 1), v)
for k, v in sorted(timing_dict.items())
]
logging.info("Epoch [% 6d], Timings: \n%s", i, "\n".join(timing_info_list))
# Reset restore.
restore = False
# Flush summary writers once in a while.
if (i + 1) % 1000 == 0 or i == epochs - 1:
train_sw.flush()
timing_sw.flush()
eval_sw.flush()
| 36.388311 | 81 | 0.650685 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import functools
import os
import time
from absl import logging
import cloudpickle as pickle
import gin
import gym
from jax import grad
from jax import jit
from jax import lax
from jax import numpy as np
from jax import random as jax_random
import numpy as onp
from tensor2tensor.envs import env_problem
from tensor2tensor.envs import env_problem_utils
from tensor2tensor.trax import jaxboard
from tensor2tensor.trax import layers as tl
from tensor2tensor.trax import optimizers as trax_opt
from tensor2tensor.trax import trax
from tensorflow.io import gfile
DEBUG_LOGGING = False
GAMMA = 0.99
LAMBDA = 0.95
EPSILON = 0.1
EPOCHS = 50
N_OPTIMIZER_STEPS = 100
PRINT_EVERY_OPTIMIZER_STEP = 20
BATCH_TRAJECTORIES = 32
def policy_and_value_net(rng_key,
batch_observations_shape,
observations_dtype,
n_actions,
bottom_layers_fn=(),
two_towers=True):
if two_towers:
layers = [
tl.Dup(),
tl.Parallel(
[bottom_layers_fn(), tl.Dense(n_actions), tl.LogSoftmax()],
[bottom_layers_fn(), tl.Dense(1)],
)
]
else:
layers = [
bottom_layers_fn(),
tl.Dup(),
tl.Parallel(
[tl.Dense(n_actions), tl.LogSoftmax()],
[tl.Dense(1)],
)
]
net = tl.Model(layers)
params = net.initialize(batch_observations_shape, observations_dtype, rng_key)
return params, net
def optimizer_fn(net_params, step_size=1e-3):
opt = trax_opt.Adam(step_size=step_size, b1=0.9, b2=0.999, eps=1e-08)
opt_init = lambda x: (x, opt.tree_init(x))
opt_update = lambda i, g, s: opt.tree_update(i, g, s[0], s[1])
get_params = lambda x: x[0]
opt_state = opt_init(net_params)
return opt_state, opt_update, get_params
def collect_trajectories(env,
policy_fn,
n_trajectories=1,
policy=env_problem_utils.GUMBEL_SAMPLING,
max_timestep=None,
epsilon=0.1,
reset=True,
len_history_for_policy=32,
rng=None):
assert isinstance(env, env_problem.EnvProblem)
trajs, n_done, timing_info = env_problem_utils.play_env_problem_with_policy(
env,
policy_fn,
num_trajectories=n_trajectories,
max_timestep=max_timestep,
policy_sampling=policy,
eps=epsilon,
reset=reset,
len_history_for_policy=len_history_for_policy,
rng=rng)
# t is the return value of Trajectory.as_numpy, so:
# (observation, action, processed_reward, raw_reward, infos)
return [(t[0], t[1], t[2], t[4]) for t in trajs], n_done, timing_info
# This function can probably be simplified, ask how?
# Can we do something much simpler than lax.pad, maybe np.pad?
# Others?
def get_padding_value(dtype):
padding_value = None
if dtype == np.uint8:
padding_value = np.uint8(0)
elif dtype == np.uint16:
padding_value = np.uint16(0)
elif dtype == np.float32 or dtype == np.float64:
padding_value = 0.0
else:
padding_value = 0
assert padding_value is not None
return padding_value
# TODO(afrozm): Use np.pad instead and make jittable?
def pad_trajectories(trajectories, boundary=20):
# Let's compute max(t) over all trajectories.
t_max = max(r.shape[0] for (_, _, r, _) in trajectories)
boundary = int(boundary)
bucket_length = boundary * int(np.ceil(float(t_max) / boundary))
padded_observations = []
padded_actions = []
padded_rewards = []
padded_infos = collections.defaultdict(list)
padded_lengths = []
reward_masks = []
for (o, a, r, i) in trajectories:
num_to_pad = bucket_length + 1 - o.shape[0]
padded_lengths.append(num_to_pad)
if num_to_pad == 0:
padded_observations.append(o)
padded_actions.append(a)
padded_rewards.append(r)
reward_masks.append(onp.ones_like(r, dtype=np.int32))
if i:
for k, v in i.items():
padded_infos[k].append(v)
continue
padding_config = tuple([(0, num_to_pad, 0)] + [(0, 0, 0)] * (o.ndim - 1))
padding_value = get_padding_value(o.dtype)
action_padding_value = get_padding_value(a.dtype)
reward_padding_value = get_padding_value(r.dtype)
padded_obs = lax.pad(o, padding_value, padding_config)
padded_observations.append(padded_obs)
assert a.ndim == 1 and r.ndim == 1
padding_config = ((0, num_to_pad, 0),)
padded_action = lax.pad(a, action_padding_value, padding_config)
padded_actions.append(padded_action)
padded_reward = lax.pad(r, reward_padding_value, padding_config)
padded_rewards.append(padded_reward)
reward_mask = onp.ones_like(r, dtype=np.int32)
reward_masks.append(lax.pad(reward_mask, 0, padding_config))
if i:
for k, v in i.items():
padding_config = [(0, num_to_pad, 0)] + [(0, 0, 0)] * (v.ndim - 1)
padded_infos[k].append(lax.pad(v, 0.0, tuple(padding_config)))
stacked_padded_infos = None
if padded_infos:
stacked_padded_infos = {k: np.stack(v) for k, v in padded_infos.items()}
return padded_lengths, np.stack(reward_masks), np.stack(
padded_observations), np.stack(padded_actions), np.stack(
padded_rewards), stacked_padded_infos
def rewards_to_go(rewards, mask, gamma=0.99):
B, T = rewards.shape
masked_rewards = rewards * mask
ng sequences: r2g[t] - r[t] > 0
# and gamma < 1.0, so the division keeps increasing.
#
# So we just run the recurrence in reverse, i.e.
#
# r2g[t] = r[t] + (gamma*r2g[t+1])
#
# This is much better, but might have lost updates since the (small) rewards
# at earlier time-steps may get added to a (very?) large sum.
# Compute r2g_{T-1} at the start and then compute backwards in time.
r2gs = [masked_rewards[:, -1]]
# Go from T-2 down to 0.
for t in reversed(range(T - 1)):
r2gs.append(masked_rewards[:, t] + (gamma * r2gs[-1]))
# The list should have length T.
assert T == len(r2gs)
# First we stack them in the correct way to make it (B, T), but these are
# still from newest (T-1) to oldest (0), so then we flip it on time axis.
return np.flip(np.stack(r2gs, axis=1), axis=1)
@jit
def value_loss_given_predictions(value_prediction,
rewards,
reward_mask,
gamma=0.99,
epsilon=0.2,
value_prediction_old=None):
B, T = rewards.shape # pylint: disable=invalid-name
assert (B, T) == reward_mask.shape
assert (B, T + 1, 1) == value_prediction.shape
value_prediction = np.squeeze(value_prediction, axis=2) # (B, T+1)
value_prediction = value_prediction[:, :-1] * reward_mask # (B, T)
r2g = rewards_to_go(rewards, reward_mask, gamma=gamma) # (B, T)
loss = (value_prediction - r2g)**2
# From the baselines implementation.
if value_prediction_old is not None:
value_prediction_old = np.squeeze(value_prediction_old, axis=2) # (B, T+1)
value_prediction_old = value_prediction_old[:, :-1] * reward_mask # (B, T)
v_clipped = value_prediction_old + np.clip(
value_prediction - value_prediction_old, -epsilon, epsilon)
v_clipped_loss = (v_clipped - r2g)**2
loss = np.maximum(v_clipped_loss, loss)
# Take an average on only the points where mask != 0.
return np.sum(loss) / np.sum(reward_mask)
def deltas(predicted_values, rewards, mask, gamma=0.99):
# Predicted values at time t, cutting off the last to have shape (B, T).
predicted_values_bt = predicted_values[:, :-1]
# Predicted values at time t+1, by cutting off the first to have shape (B, T)
predicted_values_btplus1 = predicted_values[:, 1:]
# Return the deltas as defined above.
return (rewards +
(gamma * predicted_values_btplus1) - predicted_values_bt) * mask
def gae_advantages(td_deltas, mask, lambda_=0.95, gamma=0.99):
return rewards_to_go(td_deltas, mask, lambda_ * gamma)
def chosen_probabs(probab_observations, actions):
B, T = actions.shape # pylint: disable=invalid-name
assert (B, T + 1) == probab_observations.shape[:2]
return probab_observations[np.arange(B)[:, None], np.arange(T), actions]
def compute_probab_ratios(p_new, p_old, actions, reward_mask):
B, T = actions.shape # pylint: disable=invalid-name
assert (B, T + 1) == p_old.shape[:2]
assert (B, T + 1) == p_new.shape[:2]
logp_old = chosen_probabs(p_old, actions)
logp_new = chosen_probabs(p_new, actions)
assert (B, T) == logp_old.shape
assert (B, T) == logp_new.shape
# Since these are log-probabilities, we just subtract them.
probab_ratios = np.exp(logp_new - logp_old) * reward_mask
assert (B, T) == probab_ratios.shape
return probab_ratios
def clipped_probab_ratios(probab_ratios, epsilon=0.2):
return np.clip(probab_ratios, 1 - epsilon, 1 + epsilon)
def clipped_objective(probab_ratios, advantages, reward_mask, epsilon=0.2):
return np.minimum(
probab_ratios * advantages,
clipped_probab_ratios(probab_ratios, epsilon=epsilon) *
advantages) * reward_mask
@jit
def ppo_loss_given_predictions(log_probab_actions_new,
log_probab_actions_old,
value_predictions_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
epsilon=0.2):
B, T = padded_rewards.shape # pylint: disable=invalid-name
assert (B, T) == padded_actions.shape
assert (B, T) == reward_mask.shape
_, _, A = log_probab_actions_old.shape # pylint: disable=invalid-name
assert (B, T + 1, 1) == value_predictions_old.shape
assert (B, T + 1, A) == log_probab_actions_old.shape
assert (B, T + 1, A) == log_probab_actions_new.shape
# (B, T)
td_deltas = deltas(
np.squeeze(value_predictions_old, axis=2), # (B, T+1)
padded_rewards,
reward_mask,
gamma=gamma)
# (B, T)
advantages = gae_advantages(
td_deltas, reward_mask, lambda_=lambda_, gamma=gamma)
# Normalize the advantages.
advantages = (advantages - np.mean(advantages)) / np.std(advantages)
# (B, T)
ratios = compute_probab_ratios(log_probab_actions_new, log_probab_actions_old,
padded_actions, reward_mask)
assert (B, T) == ratios.shape
# (B, T)
objective = clipped_objective(
ratios, advantages, reward_mask, epsilon=epsilon)
assert (B, T) == objective.shape
# ()
average_objective = np.sum(objective) / np.sum(reward_mask)
# Loss is negative objective.
return -average_objective
@jit
def combined_loss_given_predictions(log_probab_actions_new,
log_probab_actions_old,
value_prediction_new,
value_prediction_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
epsilon=0.2,
c1=1.0,
c2=0.01):
loss_value = value_loss_given_predictions(
value_prediction_new,
padded_rewards,
reward_mask,
gamma=gamma,
value_prediction_old=value_prediction_old,
epsilon=epsilon)
loss_ppo = ppo_loss_given_predictions(
log_probab_actions_new,
log_probab_actions_old,
value_prediction_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon)
entropy_bonus = masked_entropy(log_probab_actions_new, reward_mask)
return (loss_ppo + (c1 * loss_value) - (c2 * entropy_bonus), loss_ppo,
loss_value, entropy_bonus)
@functools.partial(jit, static_argnums=(3,))
def combined_loss(new_params,
log_probab_actions_old,
value_predictions_old,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=0.99,
lambda_=0.95,
epsilon=0.2,
c1=1.0,
c2=0.01,
rng=None):
log_probab_actions_new, value_predictions_new = policy_and_value_net_apply(
padded_observations, new_params, rng=rng)
# (combined_loss, ppo_loss, value_loss, entropy_bonus)
return combined_loss_given_predictions(
log_probab_actions_new,
log_probab_actions_old,
value_predictions_new,
value_predictions_old,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon,
c1=c1,
c2=c2)
@functools.partial(jit, static_argnums=(2, 3, 4))
def policy_and_value_opt_step(i,
opt_state,
opt_update,
get_params,
policy_and_value_net_apply,
log_probab_actions_old,
value_predictions_old,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
c1=1.0,
c2=0.01,
gamma=0.99,
lambda_=0.95,
epsilon=0.1,
rng=None):
# Combined loss function given the new params.
def policy_and_value_loss(params):
(loss, _, _, _) = combined_loss(
params,
log_probab_actions_old,
value_predictions_old,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
c1=c1,
c2=c2,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon,
rng=rng)
return loss
new_params = get_params(opt_state)
g = grad(policy_and_value_loss)(new_params)
# TODO(afrozm): Maybe clip gradients?
return opt_update(i, g, opt_state)
def get_time(t1, t2=None):
if t2 is None:
t2 = time.time()
return round((t2 - t1) * 1000, 2)
def approximate_kl(log_prob_new, log_prob_old, mask):
diff = log_prob_old - log_prob_new
# Cut the last time-step out.
diff = diff[:, :-1]
# Mask out the irrelevant part.
diff *= mask[:, :, np.newaxis] # make mask (B, T, 1)
# Average on non-masked part.
return np.sum(diff) / np.sum(mask)
def masked_entropy(log_probs, mask):
# Cut the last time-step out.
lp = log_probs[:, :-1]
# Mask out the irrelevant part.
lp *= mask[:, :, np.newaxis] # make mask (B, T, 1)
p = np.exp(lp) * mask[:, :, np.newaxis] # (B, T, 1)
# Average on non-masked part and take negative.
return -(np.sum(lp * p) / np.sum(mask))
def evaluate_policy(eval_env,
get_predictions,
temperatures,
max_timestep=20000,
n_evals=1,
len_history_for_policy=32,
rng=None):
processed_reward_sums = collections.defaultdict(list)
raw_reward_sums = collections.defaultdict(list)
for eval_rng in jax_random.split(rng, num=n_evals):
for temperature in temperatures:
trajs, _, _ = env_problem_utils.play_env_problem_with_policy(
eval_env,
get_predictions,
num_trajectories=eval_env.batch_size,
max_timestep=max_timestep,
reset=True,
policy_sampling=env_problem_utils.GUMBEL_SAMPLING,
temperature=temperature,
rng=eval_rng,
len_history_for_policy=len_history_for_policy)
processed_reward_sums[temperature].extend(sum(traj[2]) for traj in trajs)
raw_reward_sums[temperature].extend(sum(traj[3]) for traj in trajs)
# Return the mean and standard deviation for each temperature.
def compute_stats(reward_dict):
return {
temperature: {"mean": onp.mean(rewards), "std": onp.std(rewards)}
for (temperature, rewards) in reward_dict.items()
}
return {
"processed": compute_stats(processed_reward_sums),
"raw": compute_stats(raw_reward_sums),
}
def maybe_restore_params(output_dir, policy_and_value_net_params):
model_files = gfile.glob(os.path.join(output_dir, "model-??????.pkl"))
for model_file in reversed(sorted(model_files)):
logging.info("Trying to restore model from %s", model_file)
try:
with gfile.GFile(model_file, "rb") as f:
loaded_policy_and_value_net_params = pickle.load(f)
policy_and_value_net_params = loaded_policy_and_value_net_params
model_file_basename = os.path.basename(model_file) # model-??????.pkl
i = int(filter(str.isdigit, model_file_basename))
return True, policy_and_value_net_params, i
except EOFError as e:
logging.error("Unable to load model from: %s with %s", model_file, e)
# Try an older version.
continue
return False, policy_and_value_net_params, 0
def write_eval_reward_summaries(reward_stats_by_mode, summary_writer, epoch):
for (reward_mode, reward_stats_by_temp) in reward_stats_by_mode.items():
for (temperature, reward_stats) in reward_stats_by_temp.items():
for (stat_name, stat) in reward_stats.items():
summary_writer.scalar(
"eval/{reward_mode}_reward_{stat_name}/"
"temperature_{temperature}".format(reward_mode=reward_mode,
stat_name=stat_name,
temperature=temperature),
stat, step=epoch)
logging.info("Epoch [% 6d] Policy Evaluation (%s reward) "
"[temperature %.2f] = %10.2f (+/- %.2f)",
epoch, reward_mode, temperature,
reward_stats["mean"], reward_stats["std"])
@gin.configurable(blacklist=["output_dir"])
def training_loop(
env,
eval_env,
env_name,
policy_and_value_net_fn,
policy_and_value_optimizer_fn,
output_dir,
epochs=EPOCHS,
n_optimizer_steps=N_OPTIMIZER_STEPS,
print_every_optimizer_steps=PRINT_EVERY_OPTIMIZER_STEP,
target_kl=0.01,
boundary=20,
max_timestep=None,
max_timestep_eval=20000,
random_seed=None,
gamma=GAMMA,
lambda_=LAMBDA,
epsilon=EPSILON,
c1=1.0,
c2=0.01,
eval_every_n=1000,
done_frac_for_policy_save=0.5,
enable_early_stopping=True,
n_evals=1,
len_history_for_policy=4,
eval_temperatures=(1.0, 0.5),
):
gfile.makedirs(output_dir)
# Create summary writers and history.
train_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "train"))
timing_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "timing"))
eval_sw = jaxboard.SummaryWriter(os.path.join(output_dir, "eval"))
train_sw.text("env_name", env_name)
timing_sw.text("env_name", env_name)
eval_sw.text("env_name", env_name)
jax_rng_key = trax.get_random_number_generator_and_set_seed(random_seed)
# Batch Observations Shape = [1, 1] + OBS, because we will eventually call
# policy and value networks on shape [B, T] +_OBS
batch_observations_shape = (1, 1) + env.observation_space.shape
observations_dtype = env.observation_space.dtype
assert isinstance(env.action_space, gym.spaces.Discrete)
n_actions = env.action_space.n
jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2)
# Initialize the policy and value network.
policy_and_value_net_params, policy_and_value_net_apply = (
policy_and_value_net_fn(key1, batch_observations_shape,
observations_dtype, n_actions))
# Maybe restore the policy params. If there is nothing to restore, then
# iteration = 0 and policy_and_value_net_params are returned as is.
restore, policy_and_value_net_params, iteration = (
maybe_restore_params(output_dir, policy_and_value_net_params))
if restore:
logging.info("Restored parameters from iteration [%d]", iteration)
# We should start from the next iteration.
iteration += 1
policy_and_value_net_apply = jit(policy_and_value_net_apply)
# Initialize the optimizers.
policy_and_value_optimizer = (
policy_and_value_optimizer_fn(policy_and_value_net_params))
(policy_and_value_opt_state, policy_and_value_opt_update,
policy_and_value_get_params) = policy_and_value_optimizer
n_trajectories_done = 0
last_saved_at = 0
logging.info("Starting the PPO training loop.")
for i in range(iteration, epochs):
epoch_start_time = time.time()
# Params we'll use to collect the trajectories.
policy_and_value_net_params = policy_and_value_get_params(
policy_and_value_opt_state)
def get_predictions(observations, rng=None):
key, key1 = jax_random.split(rng, num=2)
log_probs, value_preds = policy_and_value_net_apply(
observations, policy_and_value_net_params, rng=key1)
return log_probs, value_preds, key
policy_eval_start_time = time.time()
if ((i + 1) % eval_every_n == 0) or (i == epochs - 1):
jax_rng_key, key = jax_random.split(jax_rng_key, num=2)
logging.vlog(1, "Epoch [% 6d] evaluating policy.", i)
reward_stats = evaluate_policy(
eval_env,
get_predictions,
temperatures=eval_temperatures,
max_timestep=max_timestep_eval,
n_evals=n_evals,
len_history_for_policy=len_history_for_policy,
rng=key)
write_eval_reward_summaries(reward_stats, eval_sw, epoch=i)
policy_eval_time = get_time(policy_eval_start_time)
trajectory_collection_start_time = time.time()
logging.vlog(1, "Epoch [% 6d] collecting trajectories.", i)
jax_rng_key, key = jax_random.split(jax_rng_key)
trajs, n_done, timing_info = collect_trajectories(
env,
policy_fn=get_predictions,
n_trajectories=env.batch_size,
max_timestep=max_timestep,
rng=key,
len_history_for_policy=len_history_for_policy,
reset=(i == 0) or restore,
epsilon=(10.0 / (i + 10.0)))
trajectory_collection_time = get_time(trajectory_collection_start_time)
logging.vlog(1, "Collecting trajectories took %0.2f msec.",
trajectory_collection_time)
avg_reward = float(sum(np.sum(traj[2]) for traj in trajs)) / len(trajs)
max_reward = max(np.sum(traj[2]) for traj in trajs)
min_reward = min(np.sum(traj[2]) for traj in trajs)
train_sw.scalar("train/reward_mean_truncated", avg_reward, step=i)
logging.vlog(1, "Rewards avg=[%0.2f], max=[%0.2f], min=[%0.2f], all=%s",
avg_reward, max_reward, min_reward,
[float(np.sum(traj[2])) for traj in trajs])
logging.vlog(1,
"Trajectory Length average=[%0.2f], max=[%0.2f], min=[%0.2f]",
float(sum(len(traj[0]) for traj in trajs)) / len(trajs),
max(len(traj[0]) for traj in trajs),
min(len(traj[0]) for traj in trajs))
logging.vlog(2, "Trajectory Lengths: %s", [len(traj[0]) for traj in trajs])
padding_start_time = time.time()
(_, reward_mask, padded_observations, padded_actions,
padded_rewards, padded_infos) = pad_trajectories(
trajs, boundary=boundary)
padding_time = get_time(padding_start_time)
logging.vlog(1, "Padding trajectories took %0.2f msec.",
get_time(padding_start_time))
logging.vlog(1, "Padded Observations' shape [%s]",
str(padded_observations.shape))
logging.vlog(1, "Padded Actions' shape [%s]", str(padded_actions.shape))
logging.vlog(1, "Padded Rewards' shape [%s]", str(padded_rewards.shape))
# Some assertions.
B, T = padded_actions.shape # pylint: disable=invalid-name
assert (B, T) == padded_rewards.shape
assert (B, T) == reward_mask.shape
assert (B, T + 1) == padded_observations.shape[:2]
assert (B, T + 1) + env.observation_space.shape == padded_observations.shape
log_prob_recompute_start_time = time.time()
assert ("log_prob_actions" in padded_infos and
"value_predictions" in padded_infos)
# These are the actual log-probabs and value predictions seen while picking
# the actions.
actual_log_probabs_traj = padded_infos["log_prob_actions"]
actual_value_predictions_traj = padded_infos["value_predictions"]
assert (B, T) == actual_log_probabs_traj.shape[:2]
A = actual_log_probabs_traj.shape[2] # pylint: disable=invalid-name
assert (B, T, 1) == actual_value_predictions_traj.shape
# TODO(afrozm): log-probabs doesn't need to be (B, T+1, A) it can do with
# observation, so we re-calculate for everything, but use the original ones
# for all but the last time-step.
jax_rng_key, key = jax_random.split(jax_rng_key)
log_probabs_traj, value_predictions_traj, _ = get_predictions(
padded_observations, rng=key)
assert (B, T + 1, A) == log_probabs_traj.shape
assert (B, T + 1, 1) == value_predictions_traj.shape
# Concatenate the last time-step's log-probabs and value predictions to the
log_probabs_traj = np.concatenate(
(actual_log_probabs_traj, log_probabs_traj[:, -1:, :]), axis=1)
value_predictions_traj = np.concatenate(
(actual_value_predictions_traj, value_predictions_traj[:, -1:, :]),
axis=1)
log_prob_recompute_time = get_time(log_prob_recompute_start_time)
epsilon_schedule = epsilon
jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2)
logging.vlog(2, "Starting to compute P&V loss.")
loss_compute_start_time = time.time()
cur_combined_loss, cur_ppo_loss, cur_value_loss, entropy_bonus = (
combined_loss(
policy_and_value_net_params,
log_probabs_traj,
value_predictions_traj,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon_schedule,
c1=c1,
c2=c2,
rng=key1))
loss_compute_time = get_time(loss_compute_start_time)
logging.vlog(
1,
"Calculating P&V loss [%10.2f(%10.2f, %10.2f, %10.2f)] took %0.2f msec.",
cur_combined_loss, cur_value_loss, cur_ppo_loss, entropy_bonus,
get_time(loss_compute_start_time))
jax_rng_key, key1 = jax_random.split(jax_rng_key, num=2)
logging.vlog(1, "Policy and Value Optimization")
optimization_start_time = time.time()
keys = jax_random.split(key1, num=n_optimizer_steps)
for j in range(n_optimizer_steps):
k1, k2, k3 = jax_random.split(keys[j], num=3)
t = time.time()
policy_and_value_opt_state = policy_and_value_opt_step(
j,
policy_and_value_opt_state,
policy_and_value_opt_update,
policy_and_value_get_params,
policy_and_value_net_apply,
log_probabs_traj,
value_predictions_traj,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
c1=c1,
c2=c2,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon_schedule,
rng=k1)
new_policy_and_value_net_params = policy_and_value_get_params(
policy_and_value_opt_state)
log_probab_actions_new, _ = policy_and_value_net_apply(
padded_observations, new_policy_and_value_net_params, rng=k2)
approx_kl = approximate_kl(log_probab_actions_new, log_probabs_traj,
reward_mask)
early_stopping = enable_early_stopping and approx_kl > 1.5 * target_kl
if early_stopping:
logging.vlog(
1, "Early stopping policy and value optimization at iter: %d, "
"with approx_kl: %0.2f", j, approx_kl)
# iteration.
t2 = time.time()
if (((j + 1) % print_every_optimizer_steps == 0) or
(j == n_optimizer_steps - 1) or early_stopping):
# Compute and log the loss.
(loss_combined, loss_ppo, loss_value, entropy_bonus) = (
combined_loss(
new_policy_and_value_net_params,
log_probabs_traj,
value_predictions_traj,
policy_and_value_net_apply,
padded_observations,
padded_actions,
padded_rewards,
reward_mask,
gamma=gamma,
lambda_=lambda_,
epsilon=epsilon_schedule,
c1=c1,
c2=c2,
rng=k3))
logging.vlog(1, "One Policy and Value grad desc took: %0.2f msec",
get_time(t, t2))
logging.vlog(
1, "Combined Loss(value, ppo, entropy_bonus) [%10.2f] ->"
" [%10.2f(%10.2f,%10.2f,%10.2f)]", cur_combined_loss, loss_combined,
loss_value, loss_ppo, entropy_bonus)
if early_stopping:
break
optimization_time = get_time(optimization_start_time)
logging.vlog(
1, "Total Combined Loss reduction [%0.2f]%%",
(100 * (cur_combined_loss - loss_combined) / np.abs(cur_combined_loss)))
# Save parameters every time we see the end of at least a fraction of batch
# number of trajectories that are done (not completed -- completed includes
# truncated and done).
# Also don't save too frequently, enforce a minimum gap.
policy_save_start_time = time.time()
n_trajectories_done += n_done
if (((n_trajectories_done >= done_frac_for_policy_save * env.batch_size) and
(i - last_saved_at > eval_every_n) and
(((i + 1) % eval_every_n == 0))) or (i == epochs - 1)):
logging.vlog(1, "Epoch [% 6d] saving model.", i)
old_model_files = gfile.glob(os.path.join(output_dir, "model-??????.pkl"))
params_file = os.path.join(output_dir, "model-%06d.pkl" % i)
with gfile.GFile(params_file, "wb") as f:
pickle.dump(policy_and_value_net_params, f)
for path in old_model_files:
gfile.remove(path)
n_trajectories_done = 0
last_saved_at = i
policy_save_time = get_time(policy_save_start_time)
epoch_time = get_time(epoch_start_time)
logging.info(
"Epoch [% 6d], Reward[min, max, avg] [%5.2f,%5.2f,%5.2f], Combined"
" Loss(value, ppo, entropy) [%2.5f(%2.5f,%2.5f,%2.5f)]", i, min_reward,
max_reward, avg_reward, loss_combined, loss_value, loss_ppo,
entropy_bonus)
timing_dict = {
"epoch": epoch_time,
"policy_eval": policy_eval_time,
"trajectory_collection": trajectory_collection_time,
"padding": padding_time,
"log_prob_recompute": log_prob_recompute_time,
"loss_compute": loss_compute_time,
"optimization": optimization_time,
"policy_save": policy_save_time,
}
timing_dict.update(timing_info)
for k, v in timing_dict.items():
timing_sw.scalar("timing/%s" % k, v, step=i)
max_key_len = max(len(k) for k in timing_dict)
timing_info_list = [
"%s : % 10.2f" % (k.rjust(max_key_len + 1), v)
for k, v in sorted(timing_dict.items())
]
logging.info("Epoch [% 6d], Timings: \n%s", i, "\n".join(timing_info_list))
restore = False
if (i + 1) % 1000 == 0 or i == epochs - 1:
train_sw.flush()
timing_sw.flush()
eval_sw.flush()
| true | true |
f727db28729a6cb29c683b37edffca2af1fdd1c2 | 6,875 | py | Python | dashboard/dashboard_build/preprocess.py | alekzonder/catapult | f1017f0c7bd2b766674888d5e88d42fcc61d632c | [
"BSD-3-Clause"
] | null | null | null | dashboard/dashboard_build/preprocess.py | alekzonder/catapult | f1017f0c7bd2b766674888d5e88d42fcc61d632c | [
"BSD-3-Clause"
] | null | null | null | dashboard/dashboard_build/preprocess.py | alekzonder/catapult | f1017f0c7bd2b766674888d5e88d42fcc61d632c | [
"BSD-3-Clause"
] | null | null | null | # Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import contextlib
import logging
import os
import subprocess
import sys
import time
def _AddToPathIfNeeded(path):
if path not in sys.path:
sys.path.insert(0, path)
@contextlib.contextmanager
def Chdir(path):
pwd = os.getcwd()
try:
yield os.chdir(path)
finally:
os.chdir(pwd)
def PackPinpoint(catapult_path, temp_dir, deployment_paths):
with Chdir(catapult_path):
_AddToPathIfNeeded(os.path.join(catapult_path, 'common', 'node_runner'))
from node_runner import node_util
node_path = node_util.GetNodePath()
node_modules = node_util.GetNodeModulesPath()
def PinpointRelativePath(*components):
return os.path.join('dashboard', 'pinpoint', *components)
# When packing Pinpoint, we need some extra symlinks in the temporary
# directory, so we can find the correct elements at bundle time. This is
# simulating the paths we would be serving as defined in the pinpoint.yaml
# file.
os.symlink(
os.path.join(catapult_path, 'dashboard', 'dashboard', 'pinpoint',
'elements'), os.path.join(temp_dir, 'elements'))
os.symlink(
os.path.join(catapult_path, 'third_party', 'polymer', 'components'),
os.path.join(temp_dir, 'components'))
os.symlink(
os.path.join(catapult_path, 'third_party', 'd3'),
os.path.join(temp_dir, 'd3'))
# We don't yet use any webpack in Pinpoint, so let's use the polymer bundler
# for now.
bundler_cmd = [
node_path,
os.path.join(node_modules, 'polymer-bundler', 'lib', 'bin',
'polymer-bundler.js'),
'--inline-scripts',
'--inline-css',
# Exclude some paths from the bundling.
'--exclude',
'//fonts.googleapis.com/*',
'--exclude',
'//apis.google.com/*',
# Then set up the rest of the options for the bundler.
'--out-dir',
os.path.join(temp_dir, 'bundled'),
'--root',
temp_dir,
'--treeshake',
]
# Change to the temporary directory, and run the bundler from there.
with Chdir(temp_dir):
bundler_cmd.extend(
['--in-file',
PinpointRelativePath('index', 'index.html')])
logging.info('Bundler Command:\n%s', ' '.join(bundler_cmd))
proc = subprocess.Popen(
bundler_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_, bundler_err = proc.communicate()
if proc.returncode != 0:
print('ERROR from bundler:')
print(bundler_err)
raise RuntimeError('Vulcanize failed with exit code', proc.returncode)
deployment_paths.append(os.path.join(temp_dir, 'bundled'))
def PackSPA(catapult_path, temp_dir, deployment_paths):
with Chdir(catapult_path):
dashboard_path = os.path.join(catapult_path, 'dashboard')
app_yaml = os.path.join(dashboard_path, 'app.yaml')
if 'webpack/service-worker.js' not in open(app_yaml).read():
# Only webpack if the service-worker is going to be served.
return
_AddToPathIfNeeded(os.path.join(catapult_path, 'common', 'node_runner'))
from node_runner import node_util
node_modules = node_util.GetNodeModulesPath()
# TODO(crbug.com/918193): Remove this after migrating to lit-element.
js_parse_filename = os.path.join(node_modules, 'hydrolysis', 'lib',
'ast-utils', 'js-parse.js')
subprocess.check_output(
['sed', '-i', 's/ecmaVersion: 6/ecmaVersion: 9/g', js_parse_filename])
spa_path = os.path.join(dashboard_path, 'dashboard', 'spa')
webpack_dir = os.path.join(temp_dir, 'webpack')
config_filename = os.path.join(spa_path, 'webpack.config.js')
webpack_command = os.path.join(node_modules, '.bin', 'webpack-command')
os.environ['WEBPACK_OUTPUT_PATH'] = webpack_dir
os.environ['WEBPACK_NODE_MODULES'] = node_modules
os.environ['WEBPACK_THIRD_PARTY'] = os.path.join(catapult_path,
'third_party')
proc = subprocess.Popen([webpack_command, '--config', config_filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
webpack_out, webpack_err = proc.communicate()
if proc.returncode != 0:
print('ERROR from webpack:')
print(webpack_out)
print(webpack_err)
raise RuntimeError('Webpack failed with exit code', proc.returncode)
vulcanize_cmd = [
os.path.join(node_modules, 'vulcanize', 'bin', 'vulcanize'),
'--strip-comments',
'--inline-scripts',
'--inline-css',
'--exclude=/index.js',
]
for path in sorted(deployment_paths):
isdir = os.path.isdir(path) and not path.endswith('/')
# Some directory names are prefixes of others. Add an explicit slash to
# prevent confusing vulcanize.
vulcanize_cmd.append('--redirect')
vulcanize_cmd.append('/' + os.path.basename(path) +
('/' if isdir else '') + '|' +
path[len(catapult_path) + 1:])
vulcanize_cmd.append(
os.path.join('dashboard', 'dashboard', 'spa', 'index.html'))
proc = subprocess.Popen(
vulcanize_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
html, vulcanize_err = proc.communicate()
if proc.returncode != 0:
print('ERROR from vulcanize:')
print(vulcanize_err)
raise RuntimeError('Vulcanize failed with exit code', proc.returncode)
# Write the html to a temp file.
vulcanized_index = os.path.join(temp_dir, 'index.vulcanized.html')
open(vulcanized_index, 'w').write(html)
minify = os.path.join(node_modules, '..', 'minify')
subprocess.check_output([minify, vulcanized_index])
packed_index_js_filename = os.path.join(webpack_dir, 'index.js')
AddTimestamp(packed_index_js_filename)
minifyjs = os.path.join(node_modules, '..', 'minifyjs')
subprocess.check_output([minifyjs, packed_index_js_filename])
sw_js = os.path.join(webpack_dir, 'service-worker.js')
subprocess.check_output([minifyjs, sw_js])
deployment_paths.append(webpack_dir)
deployment_paths.append(vulcanized_index)
def AddTimestamp(js_name):
# V2SPA displays its version as this timestamp in this format to make it easy
# to check whether a change is visible.
now = time.time()
print('vulcanized',
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(now - (60 * 60 * 7))))
js = open(js_name).read()
with open(js_name, 'w') as fp:
fp.write('window.VULCANIZED_TIMESTAMP=new Date(%d);\n' % (now * 1000))
fp.write(js)
| 36.184211 | 80 | 0.652945 |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import contextlib
import logging
import os
import subprocess
import sys
import time
def _AddToPathIfNeeded(path):
if path not in sys.path:
sys.path.insert(0, path)
@contextlib.contextmanager
def Chdir(path):
pwd = os.getcwd()
try:
yield os.chdir(path)
finally:
os.chdir(pwd)
def PackPinpoint(catapult_path, temp_dir, deployment_paths):
with Chdir(catapult_path):
_AddToPathIfNeeded(os.path.join(catapult_path, 'common', 'node_runner'))
from node_runner import node_util
node_path = node_util.GetNodePath()
node_modules = node_util.GetNodeModulesPath()
def PinpointRelativePath(*components):
return os.path.join('dashboard', 'pinpoint', *components)
os.symlink(
os.path.join(catapult_path, 'dashboard', 'dashboard', 'pinpoint',
'elements'), os.path.join(temp_dir, 'elements'))
os.symlink(
os.path.join(catapult_path, 'third_party', 'polymer', 'components'),
os.path.join(temp_dir, 'components'))
os.symlink(
os.path.join(catapult_path, 'third_party', 'd3'),
os.path.join(temp_dir, 'd3'))
bundler_cmd = [
node_path,
os.path.join(node_modules, 'polymer-bundler', 'lib', 'bin',
'polymer-bundler.js'),
'--inline-scripts',
'--inline-css',
'--exclude',
'//fonts.googleapis.com/*',
'--exclude',
'//apis.google.com/*',
'--out-dir',
os.path.join(temp_dir, 'bundled'),
'--root',
temp_dir,
'--treeshake',
]
with Chdir(temp_dir):
bundler_cmd.extend(
['--in-file',
PinpointRelativePath('index', 'index.html')])
logging.info('Bundler Command:\n%s', ' '.join(bundler_cmd))
proc = subprocess.Popen(
bundler_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_, bundler_err = proc.communicate()
if proc.returncode != 0:
print('ERROR from bundler:')
print(bundler_err)
raise RuntimeError('Vulcanize failed with exit code', proc.returncode)
deployment_paths.append(os.path.join(temp_dir, 'bundled'))
def PackSPA(catapult_path, temp_dir, deployment_paths):
with Chdir(catapult_path):
dashboard_path = os.path.join(catapult_path, 'dashboard')
app_yaml = os.path.join(dashboard_path, 'app.yaml')
if 'webpack/service-worker.js' not in open(app_yaml).read():
return
_AddToPathIfNeeded(os.path.join(catapult_path, 'common', 'node_runner'))
from node_runner import node_util
node_modules = node_util.GetNodeModulesPath()
js_parse_filename = os.path.join(node_modules, 'hydrolysis', 'lib',
'ast-utils', 'js-parse.js')
subprocess.check_output(
['sed', '-i', 's/ecmaVersion: 6/ecmaVersion: 9/g', js_parse_filename])
spa_path = os.path.join(dashboard_path, 'dashboard', 'spa')
webpack_dir = os.path.join(temp_dir, 'webpack')
config_filename = os.path.join(spa_path, 'webpack.config.js')
webpack_command = os.path.join(node_modules, '.bin', 'webpack-command')
os.environ['WEBPACK_OUTPUT_PATH'] = webpack_dir
os.environ['WEBPACK_NODE_MODULES'] = node_modules
os.environ['WEBPACK_THIRD_PARTY'] = os.path.join(catapult_path,
'third_party')
proc = subprocess.Popen([webpack_command, '--config', config_filename],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
webpack_out, webpack_err = proc.communicate()
if proc.returncode != 0:
print('ERROR from webpack:')
print(webpack_out)
print(webpack_err)
raise RuntimeError('Webpack failed with exit code', proc.returncode)
vulcanize_cmd = [
os.path.join(node_modules, 'vulcanize', 'bin', 'vulcanize'),
'--strip-comments',
'--inline-scripts',
'--inline-css',
'--exclude=/index.js',
]
for path in sorted(deployment_paths):
isdir = os.path.isdir(path) and not path.endswith('/')
vulcanize_cmd.append('--redirect')
vulcanize_cmd.append('/' + os.path.basename(path) +
('/' if isdir else '') + '|' +
path[len(catapult_path) + 1:])
vulcanize_cmd.append(
os.path.join('dashboard', 'dashboard', 'spa', 'index.html'))
proc = subprocess.Popen(
vulcanize_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
html, vulcanize_err = proc.communicate()
if proc.returncode != 0:
print('ERROR from vulcanize:')
print(vulcanize_err)
raise RuntimeError('Vulcanize failed with exit code', proc.returncode)
vulcanized_index = os.path.join(temp_dir, 'index.vulcanized.html')
open(vulcanized_index, 'w').write(html)
minify = os.path.join(node_modules, '..', 'minify')
subprocess.check_output([minify, vulcanized_index])
packed_index_js_filename = os.path.join(webpack_dir, 'index.js')
AddTimestamp(packed_index_js_filename)
minifyjs = os.path.join(node_modules, '..', 'minifyjs')
subprocess.check_output([minifyjs, packed_index_js_filename])
sw_js = os.path.join(webpack_dir, 'service-worker.js')
subprocess.check_output([minifyjs, sw_js])
deployment_paths.append(webpack_dir)
deployment_paths.append(vulcanized_index)
def AddTimestamp(js_name):
now = time.time()
print('vulcanized',
time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(now - (60 * 60 * 7))))
js = open(js_name).read()
with open(js_name, 'w') as fp:
fp.write('window.VULCANIZED_TIMESTAMP=new Date(%d);\n' % (now * 1000))
fp.write(js)
| true | true |
f727dba422b880a9a9bc67a389966d3ac11e1460 | 463 | py | Python | econml/tree/__init__.py | lwschm/EconML | 6e7b107e1f8a7a5922489eb81143db8656ff01af | [
"BSD-3-Clause"
] | 1 | 2021-02-08T22:58:39.000Z | 2021-02-08T22:58:39.000Z | econml/tree/__init__.py | Jimmy-INL/EconML | 3e66b9507b43f8af291009d26186283fa4bb4ced | [
"BSD-3-Clause"
] | null | null | null | econml/tree/__init__.py | Jimmy-INL/EconML | 3e66b9507b43f8af291009d26186283fa4bb4ced | [
"BSD-3-Clause"
] | 1 | 2021-08-20T09:06:42.000Z | 2021-08-20T09:06:42.000Z | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from ._criterion import Criterion, RegressionCriterion, MSE
from ._splitter import Splitter, BestSplitter
from ._tree import DepthFirstTreeBuilder
from ._tree import Tree
__all__ = ["Tree",
"Splitter",
"BestSplitter",
"DepthFirstTreeBuilder",
"Criterion",
"RegressionCriterion",
"MSE"]
| 28.9375 | 60 | 0.650108 |
from ._criterion import Criterion, RegressionCriterion, MSE
from ._splitter import Splitter, BestSplitter
from ._tree import DepthFirstTreeBuilder
from ._tree import Tree
__all__ = ["Tree",
"Splitter",
"BestSplitter",
"DepthFirstTreeBuilder",
"Criterion",
"RegressionCriterion",
"MSE"]
| true | true |
f727dd0ea24c6f6c7eef4fa81bae3e2d89fcaac3 | 3,250 | py | Python | Results/ResultUniLex.py | viitormiiguel/AnalysisFinancial | 21d19c4eb200655ffd8605d4c38ab280a4552384 | [
"MIT"
] | null | null | null | Results/ResultUniLex.py | viitormiiguel/AnalysisFinancial | 21d19c4eb200655ffd8605d4c38ab280a4552384 | [
"MIT"
] | null | null | null | Results/ResultUniLex.py | viitormiiguel/AnalysisFinancial | 21d19c4eb200655ffd8605d4c38ab280a4552384 | [
"MIT"
] | 2 | 2020-04-30T18:47:05.000Z | 2021-05-24T15:07:41.000Z | import nltk
import csv
import datetime
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
now = datetime.datetime.now()
today = now.strftime("%Y-%m-%d")
dInfoMoney = 'C:/Users/vitor/Documents/GetDataset/Infomoney/'
dInvesting = 'C:/Users/vitor/Documents/GetDataset/Investing.com/'
dTrading = 'C:/Users/vitor/Documents/GetDataset/TradingView/'
# Resultados Investing.com
r_investing = open(dInvesting + today +'/polarityUniLexPre.csv', 'r', encoding='utf8')
# r_investing = open(dInvesting + today +'/polarityUniLexNo.csv', 'r', encoding='utf8')
posInv = 0
neuInv = 0
negInv = 0
for t in r_investing.readlines():
if 'Positivo' in t:
posInv += 1
if 'Neutro' in t:
neuInv += 1
if 'Negativo' in t:
negInv += 1
print('Investing Pos ', posInv)
print('Investing Neu ', neuInv)
print('Investing Neg ', negInv)
# Resultados InfoMoney
r_infomoney = open(dInfoMoney + today +'/polarityUniLexPre.csv', 'r', encoding='utf8')
# r_infomoney = open(dInfoMoney + today +'/polarityUniLexNo.csv', 'r', encoding='utf8')
posInf = 0
neuInf = 0
negInf = 0
for t in r_infomoney.readlines():
if 'Positivo' in t:
posInf += 1
if 'Neutro' in t:
neuInf += 1
if 'Negativo' in t:
negInf += 1
print('InfoMoney Pos ', posInf)
print('InfoMoney Neu ', neuInf)
print('InfoMoney Neg ', negInf)
# Resultados TradingView
r_tradingview = open(dTrading + today +'/polarityUniLexPre.csv', 'r', encoding='utf8')
# r_tradingview = open(dTrading + today +'/polarityUniLexNo.csv', 'r', encoding='utf8')
posTrd = 0
neuTrd = 0
negTrd = 0
for t in r_tradingview.readlines():
if 'Positivo' in t:
posTrd += 1
if 'Neutro' in t:
neuTrd += 1
if 'Negativo' in t:
negTrd += 1
print('TradingView Pos ', posTrd)
print('TradingView Neu ', neuTrd)
print('TradingView Neg ', negTrd)
raw_data = {'Fonte de Dados': ['Investing.com', 'InfoMoney', 'TradingView'],
'Pos': [posInv, posInf, posTrd],
'Neu': [neuInv, neuInf, neuTrd],
'Neg': [negInv, negInf, negTrd]}
df = pd.DataFrame(raw_data, columns = ['Fonte de Dados', 'Pos', 'Neu', 'Neg'])
df
# Setting the positions and width for the bars
pos = list(range(len(df['Pos'])))
width = 0.25
fig, ax = plt.subplots(figsize=(10,5))
# Create a bar with pre_score data, # in position pos,
plt.bar(pos, df['Pos'], width, alpha=0.5, color='#EE3224', label=df['Fonte de Dados'][0])
# Create a bar with mid_score data, # in position pos + some width buffer,
plt.bar([p + width for p in pos], df['Neu'], width, alpha=0.5, color='#F78F1E', label=df['Fonte de Dados'][1])
# Create a bar with post_score data, # in position pos + some width buffer,
plt.bar([p + width*2 for p in pos], df['Neg'], width, alpha=0.5, color='#FFC222', label=df['Fonte de Dados'][2])
ax.set_title("OpLexicon sem Pré-Processamento")
ax.set_ylabel('N° de Textos')
ax.set_xticks([p + 1 * width for p in pos])
ax.set_xticklabels(df['Fonte de Dados'])
plt.xlim(min(pos)-width, max(pos)+width*4)
plt.ylim([0, max(df['Pos'] + df['Neu'] + df['Neg'])] )
plt.legend(['Positivo', 'Neutro', 'Negativo'], loc='upper left')
plt.grid()
plt.show() | 33.505155 | 114 | 0.641538 | import nltk
import csv
import datetime
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
now = datetime.datetime.now()
today = now.strftime("%Y-%m-%d")
dInfoMoney = 'C:/Users/vitor/Documents/GetDataset/Infomoney/'
dInvesting = 'C:/Users/vitor/Documents/GetDataset/Investing.com/'
dTrading = 'C:/Users/vitor/Documents/GetDataset/TradingView/'
r_investing = open(dInvesting + today +'/polarityUniLexPre.csv', 'r', encoding='utf8')
posInv = 0
neuInv = 0
negInv = 0
for t in r_investing.readlines():
if 'Positivo' in t:
posInv += 1
if 'Neutro' in t:
neuInv += 1
if 'Negativo' in t:
negInv += 1
print('Investing Pos ', posInv)
print('Investing Neu ', neuInv)
print('Investing Neg ', negInv)
r_infomoney = open(dInfoMoney + today +'/polarityUniLexPre.csv', 'r', encoding='utf8')
posInf = 0
neuInf = 0
negInf = 0
for t in r_infomoney.readlines():
if 'Positivo' in t:
posInf += 1
if 'Neutro' in t:
neuInf += 1
if 'Negativo' in t:
negInf += 1
print('InfoMoney Pos ', posInf)
print('InfoMoney Neu ', neuInf)
print('InfoMoney Neg ', negInf)
r_tradingview = open(dTrading + today +'/polarityUniLexPre.csv', 'r', encoding='utf8')
posTrd = 0
neuTrd = 0
negTrd = 0
for t in r_tradingview.readlines():
if 'Positivo' in t:
posTrd += 1
if 'Neutro' in t:
neuTrd += 1
if 'Negativo' in t:
negTrd += 1
print('TradingView Pos ', posTrd)
print('TradingView Neu ', neuTrd)
print('TradingView Neg ', negTrd)
raw_data = {'Fonte de Dados': ['Investing.com', 'InfoMoney', 'TradingView'],
'Pos': [posInv, posInf, posTrd],
'Neu': [neuInv, neuInf, neuTrd],
'Neg': [negInv, negInf, negTrd]}
df = pd.DataFrame(raw_data, columns = ['Fonte de Dados', 'Pos', 'Neu', 'Neg'])
df
pos = list(range(len(df['Pos'])))
width = 0.25
fig, ax = plt.subplots(figsize=(10,5))
os'], width, alpha=0.5, color='#EE3224', label=df['Fonte de Dados'][0])
Neu'], width, alpha=0.5, color='#F78F1E', label=df['Fonte de Dados'][1])
['Neg'], width, alpha=0.5, color='#FFC222', label=df['Fonte de Dados'][2])
ax.set_title("OpLexicon sem Pré-Processamento")
ax.set_ylabel('N° de Textos')
ax.set_xticks([p + 1 * width for p in pos])
ax.set_xticklabels(df['Fonte de Dados'])
plt.xlim(min(pos)-width, max(pos)+width*4)
plt.ylim([0, max(df['Pos'] + df['Neu'] + df['Neg'])] )
plt.legend(['Positivo', 'Neutro', 'Negativo'], loc='upper left')
plt.grid()
plt.show() | true | true |
f727dd3b7d4b012d0f7dec1bce4d8082d376ec1c | 295,763 | py | Python | kubernetes/client/apis/apps_v1beta1_api.py | TomasTomecek/kubernetes-python | c37c074303a13c72662b9201ccc023fb0ca45755 | [
"Apache-2.0"
] | null | null | null | kubernetes/client/apis/apps_v1beta1_api.py | TomasTomecek/kubernetes-python | c37c074303a13c72662b9201ccc023fb0ca45755 | [
"Apache-2.0"
] | 1 | 2021-04-30T20:41:19.000Z | 2021-04-30T20:41:19.000Z | venv/lib/python2.7/site-packages/kubernetes/client/apis/apps_v1beta1_api.py | 784134748/kubernetes-install | 5df59632c2619632e422948b667fb68eab9ff5be | [
"MIT"
] | 1 | 2020-05-09T07:16:55.000Z | 2020-05-09T07:16:55.000Z | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.12.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..api_client import ApiClient
class AppsV1beta1Api(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_namespaced_controller_revision(self, namespace, body, **kwargs):
"""
create a ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_controller_revision(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1ControllerRevision body: (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_controller_revision_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_controller_revision_with_http_info(namespace, body, **kwargs)
return data
def create_namespaced_controller_revision_with_http_info(self, namespace, body, **kwargs):
"""
create a ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_controller_revision_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1ControllerRevision body: (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'body', 'include_uninitialized', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_controller_revision`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_deployment(self, namespace, body, **kwargs):
"""
create a Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_deployment(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Deployment body: (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_deployment_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_deployment_with_http_info(namespace, body, **kwargs)
return data
def create_namespaced_deployment_with_http_info(self, namespace, body, **kwargs):
"""
create a Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_deployment_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Deployment body: (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'body', 'include_uninitialized', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_deployment`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_deployment_rollback(self, name, namespace, body, **kwargs):
"""
create rollback of a Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_deployment_rollback(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the DeploymentRollback (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1DeploymentRollback body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param bool include_uninitialized: If IncludeUninitialized is specified, the object may be returned without completing initialization.
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, **kwargs)
return data
def create_namespaced_deployment_rollback_with_http_info(self, name, namespace, body, **kwargs):
"""
create rollback of a Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the DeploymentRollback (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1DeploymentRollback body: (required)
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param bool include_uninitialized: If IncludeUninitialized is specified, the object may be returned without completing initialization.
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'dry_run', 'include_uninitialized', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_deployment_rollback" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `create_namespaced_deployment_rollback`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_deployment_rollback`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_deployment_rollback`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/rollback', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_stateful_set(self, namespace, body, **kwargs):
"""
create a StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_stateful_set(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1StatefulSet body: (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_stateful_set_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_stateful_set_with_http_info(namespace, body, **kwargs)
return data
def create_namespaced_stateful_set_with_http_info(self, namespace, body, **kwargs):
"""
create a StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_stateful_set_with_http_info(namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1StatefulSet body: (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'body', 'include_uninitialized', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_stateful_set`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_controller_revision(self, namespace, **kwargs):
"""
delete collection of ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_controller_revision(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_controller_revision_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_controller_revision_with_http_info(namespace, **kwargs)
return data
def delete_collection_namespaced_controller_revision_with_http_info(self, namespace, **kwargs):
"""
delete collection of ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_controller_revision_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_deployment(self, namespace, **kwargs):
"""
delete collection of Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_deployment(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs)
return data
def delete_collection_namespaced_deployment_with_http_info(self, namespace, **kwargs):
"""
delete collection of Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_deployment_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs):
"""
delete collection of StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs)
return data
def delete_collection_namespaced_stateful_set_with_http_info(self, namespace, **kwargs):
"""
delete collection of StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_collection_namespaced_stateful_set_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_controller_revision(self, name, namespace, body, **kwargs):
"""
delete a ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_controller_revision(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1DeleteOptions body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.delete_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
return data
def delete_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs):
"""
delete a ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_controller_revision_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1DeleteOptions body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_controller_revision`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_controller_revision`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_deployment(self, name, namespace, body, **kwargs):
"""
delete a Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_deployment(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1DeleteOptions body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.delete_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
return data
def delete_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs):
"""
delete a Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_deployment_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1DeleteOptions body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_deployment`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_deployment`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_stateful_set(self, name, namespace, body, **kwargs):
"""
delete a StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_stateful_set(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1DeleteOptions body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.delete_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
return data
def delete_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs):
"""
delete a StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_stateful_set_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1DeleteOptions body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_stateful_set`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_stateful_set`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_api_resources(self, **kwargs):
"""
get available resources
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_resources(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: V1APIResourceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_api_resources_with_http_info(**kwargs)
else:
(data) = self.get_api_resources_with_http_info(**kwargs)
return data
def get_api_resources_with_http_info(self, **kwargs):
"""
get available resources
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_resources_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: V1APIResourceList
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_resources" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIResourceList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_controller_revision_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_controller_revision_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1ControllerRevisionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_controller_revision_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_controller_revision_for_all_namespaces_with_http_info(**kwargs)
return data
def list_controller_revision_for_all_namespaces_with_http_info(self, **kwargs):
"""
list or watch objects of kind ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_controller_revision_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1ControllerRevisionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['_continue', 'field_selector', 'include_uninitialized', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_controller_revision_for_all_namespaces" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/controllerrevisions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevisionList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_deployment_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_deployment_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: AppsV1beta1DeploymentList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_deployment_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_deployment_for_all_namespaces_with_http_info(**kwargs)
return data
def list_deployment_for_all_namespaces_with_http_info(self, **kwargs):
"""
list or watch objects of kind Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_deployment_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: AppsV1beta1DeploymentList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['_continue', 'field_selector', 'include_uninitialized', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_deployment_for_all_namespaces" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/deployments', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1DeploymentList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_controller_revision(self, namespace, **kwargs):
"""
list or watch objects of kind ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_controller_revision(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1ControllerRevisionList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_controller_revision_with_http_info(namespace, **kwargs)
else:
(data) = self.list_namespaced_controller_revision_with_http_info(namespace, **kwargs)
return data
def list_namespaced_controller_revision_with_http_info(self, namespace, **kwargs):
"""
list or watch objects of kind ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_controller_revision_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1ControllerRevisionList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevisionList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_deployment(self, namespace, **kwargs):
"""
list or watch objects of kind Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_deployment(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: AppsV1beta1DeploymentList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_deployment_with_http_info(namespace, **kwargs)
else:
(data) = self.list_namespaced_deployment_with_http_info(namespace, **kwargs)
return data
def list_namespaced_deployment_with_http_info(self, namespace, **kwargs):
"""
list or watch objects of kind Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_deployment_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: AppsV1beta1DeploymentList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1DeploymentList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_stateful_set(self, namespace, **kwargs):
"""
list or watch objects of kind StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_stateful_set(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1StatefulSetList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs)
else:
(data) = self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs)
return data
def list_namespaced_stateful_set_with_http_info(self, namespace, **kwargs):
"""
list or watch objects of kind StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_stateful_set_with_http_info(namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1StatefulSetList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSetList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_stateful_set_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_stateful_set_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1StatefulSetList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_stateful_set_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_stateful_set_for_all_namespaces_with_http_info(**kwargs)
return data
def list_stateful_set_for_all_namespaces_with_http_info(self, **kwargs):
"""
list or watch objects of kind StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_stateful_set_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool include_uninitialized: If true, partially initialized resources are included in the response.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:return: V1beta1StatefulSetList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['_continue', 'field_selector', 'include_uninitialized', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_stateful_set_for_all_namespaces" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/statefulsets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSetList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_controller_revision(self, name, namespace, body, **kwargs):
"""
partially update the specified ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_controller_revision(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update the specified ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_controller_revision_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_controller_revision`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_controller_revision`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_deployment(self, name, namespace, body, **kwargs):
"""
partially update the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_deployment_scale(self, name, namespace, body, **kwargs):
"""
partially update scale of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_deployment_scale_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update scale of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_deployment_scale" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment_scale`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment_scale`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/scale', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_deployment_status(self, name, namespace, body, **kwargs):
"""
partially update status of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_deployment_status_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update status of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_deployment_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_deployment_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment_status`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_stateful_set(self, name, namespace, body, **kwargs):
"""
partially update the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs):
"""
partially update scale of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update scale of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_stateful_set_scale" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set_scale`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set_scale`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/scale', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_stateful_set_status(self, name, namespace, body, **kwargs):
"""
partially update status of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_stateful_set_status_with_http_info(self, name, namespace, body, **kwargs):
"""
partially update status of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_stateful_set_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set_status`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_controller_revision(self, name, namespace, **kwargs):
"""
read the specified ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_controller_revision(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_controller_revision_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_controller_revision_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_controller_revision_with_http_info(self, name, namespace, **kwargs):
"""
read the specified ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_controller_revision_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_controller_revision`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_deployment(self, name, namespace, **kwargs):
"""
read the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_deployment_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_deployment_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_deployment_with_http_info(self, name, namespace, **kwargs):
"""
read the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_deployment`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_deployment_scale(self, name, namespace, **kwargs):
"""
read scale of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment_scale(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_deployment_scale_with_http_info(self, name, namespace, **kwargs):
"""
read scale of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment_scale_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_deployment_scale" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_deployment_scale`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/scale', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_deployment_status(self, name, namespace, **kwargs):
"""
read status of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_deployment_status_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_deployment_status_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_deployment_status_with_http_info(self, name, namespace, **kwargs):
"""
read status of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_deployment_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_deployment_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_stateful_set(self, name, namespace, **kwargs):
"""
read the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_stateful_set(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_stateful_set_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_stateful_set_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_stateful_set_with_http_info(self, name, namespace, **kwargs):
"""
read the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_stateful_set_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_stateful_set_scale(self, name, namespace, **kwargs):
"""
read scale of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_stateful_set_scale(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_stateful_set_scale_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_stateful_set_scale_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_stateful_set_scale_with_http_info(self, name, namespace, **kwargs):
"""
read scale of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_stateful_set_scale_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_stateful_set_scale" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set_scale`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/scale', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_stateful_set_status(self, name, namespace, **kwargs):
"""
read status of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_stateful_set_status(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_stateful_set_status_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_stateful_set_status_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_stateful_set_status_with_http_info(self, name, namespace, **kwargs):
"""
read status of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_stateful_set_status_with_http_info(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_stateful_set_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_controller_revision(self, name, namespace, body, **kwargs):
"""
replace the specified ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_controller_revision(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1ControllerRevision body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs):
"""
replace the specified ControllerRevision
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_controller_revision_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the ControllerRevision (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1ControllerRevision body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1ControllerRevision
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_controller_revision`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_controller_revision`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_deployment(self, name, namespace, body, **kwargs):
"""
replace the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_deployment(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Deployment body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs):
"""
replace the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_deployment_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Deployment body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_deployment_scale(self, name, namespace, body, **kwargs):
"""
replace scale of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_deployment_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Scale body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_deployment_scale_with_http_info(self, name, namespace, body, **kwargs):
"""
replace scale of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Scale body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_deployment_scale" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment_scale`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment_scale`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/scale', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_deployment_status(self, name, namespace, body, **kwargs):
"""
replace status of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_deployment_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Deployment body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_deployment_status_with_http_info(self, name, namespace, body, **kwargs):
"""
replace status of the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_deployment_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Deployment (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Deployment body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Deployment
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_deployment_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment_status`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_stateful_set(self, name, namespace, body, **kwargs):
"""
replace the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1StatefulSet body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs):
"""
replace the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1StatefulSet body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs):
"""
replace scale of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set_scale(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Scale body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, **kwargs):
"""
replace scale of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the Scale (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param AppsV1beta1Scale body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: AppsV1beta1Scale
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_stateful_set_scale" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set_scale`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set_scale`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/scale', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_stateful_set_status(self, name, namespace, body, **kwargs):
"""
replace status of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set_status(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1StatefulSet body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_stateful_set_status_with_http_info(self, name, namespace, body, **kwargs):
"""
replace status of the specified StatefulSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the StatefulSet (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V1beta1StatefulSet body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:return: V1beta1StatefulSet
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_stateful_set_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set_status`")
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| 64.661784 | 1,390 | 0.651883 |
from __future__ import absolute_import
import sys
import os
import re
from six import iteritems
from ..api_client import ApiClient
class AppsV1beta1Api(object):
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_namespaced_controller_revision(self, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_controller_revision_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_controller_revision_with_http_info(namespace, body, **kwargs)
return data
def create_namespaced_controller_revision_with_http_info(self, namespace, body, **kwargs):
all_params = ['namespace', 'body', 'include_uninitialized', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_controller_revision`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_deployment(self, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_deployment_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_deployment_with_http_info(namespace, body, **kwargs)
return data
def create_namespaced_deployment_with_http_info(self, namespace, body, **kwargs):
all_params = ['namespace', 'body', 'include_uninitialized', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_deployment`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_deployment_rollback(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.create_namespaced_deployment_rollback_with_http_info(name, namespace, body, **kwargs)
return data
def create_namespaced_deployment_rollback_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'dry_run', 'include_uninitialized', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_deployment_rollback" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `create_namespaced_deployment_rollback`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_deployment_rollback`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_deployment_rollback`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/rollback', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def create_namespaced_stateful_set(self, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_stateful_set_with_http_info(namespace, body, **kwargs)
else:
(data) = self.create_namespaced_stateful_set_with_http_info(namespace, body, **kwargs)
return data
def create_namespaced_stateful_set_with_http_info(self, namespace, body, **kwargs):
all_params = ['namespace', 'body', 'include_uninitialized', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_stateful_set`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_controller_revision(self, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_controller_revision_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_controller_revision_with_http_info(namespace, **kwargs)
return data
def delete_collection_namespaced_controller_revision_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_deployment(self, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_deployment_with_http_info(namespace, **kwargs)
return data
def delete_collection_namespaced_deployment_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs)
else:
(data) = self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs)
return data
def delete_collection_namespaced_stateful_set_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_collection_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_collection_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_controller_revision(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.delete_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
return data
def delete_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_controller_revision`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_controller_revision`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_deployment(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.delete_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
return data
def delete_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_deployment`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_deployment`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_stateful_set(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.delete_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
return data
def delete_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_stateful_set`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_stateful_set`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_api_resources(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_api_resources_with_http_info(**kwargs)
else:
(data) = self.get_api_resources_with_http_info(**kwargs)
return data
def get_api_resources_with_http_info(self, **kwargs):
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_resources" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIResourceList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_controller_revision_for_all_namespaces(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_controller_revision_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_controller_revision_for_all_namespaces_with_http_info(**kwargs)
return data
def list_controller_revision_for_all_namespaces_with_http_info(self, **kwargs):
all_params = ['_continue', 'field_selector', 'include_uninitialized', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_controller_revision_for_all_namespaces" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/controllerrevisions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevisionList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_deployment_for_all_namespaces(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_deployment_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_deployment_for_all_namespaces_with_http_info(**kwargs)
return data
def list_deployment_for_all_namespaces_with_http_info(self, **kwargs):
all_params = ['_continue', 'field_selector', 'include_uninitialized', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_deployment_for_all_namespaces" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/deployments', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1DeploymentList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_controller_revision(self, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_controller_revision_with_http_info(namespace, **kwargs)
else:
(data) = self.list_namespaced_controller_revision_with_http_info(namespace, **kwargs)
return data
def list_namespaced_controller_revision_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevisionList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_deployment(self, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_deployment_with_http_info(namespace, **kwargs)
else:
(data) = self.list_namespaced_deployment_with_http_info(namespace, **kwargs)
return data
def list_namespaced_deployment_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1DeploymentList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_stateful_set(self, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs)
else:
(data) = self.list_namespaced_stateful_set_with_http_info(namespace, **kwargs)
return data
def list_namespaced_stateful_set_with_http_info(self, namespace, **kwargs):
all_params = ['namespace', 'include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSetList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_stateful_set_for_all_namespaces(self, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_stateful_set_for_all_namespaces_with_http_info(**kwargs)
else:
(data) = self.list_stateful_set_for_all_namespaces_with_http_info(**kwargs)
return data
def list_stateful_set_for_all_namespaces_with_http_info(self, **kwargs):
all_params = ['_continue', 'field_selector', 'include_uninitialized', 'label_selector', 'limit', 'pretty', 'resource_version', 'timeout_seconds', 'watch']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_stateful_set_for_all_namespaces" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'include_uninitialized' in params:
query_params.append(('includeUninitialized', params['include_uninitialized']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/statefulsets', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSetList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_controller_revision(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_controller_revision`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_controller_revision`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_deployment(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_deployment_scale(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_deployment_scale_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_deployment_scale" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment_scale`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment_scale`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/scale', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_deployment_status(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_deployment_status_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_deployment_status" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_deployment_status`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_deployment_status`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_deployment_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_stateful_set(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_stateful_set_scale" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set_scale`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set_scale`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/scale', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_stateful_set_status(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
return data
def patch_namespaced_stateful_set_status_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_stateful_set_status" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_stateful_set_status`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_stateful_set_status`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_stateful_set_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/status', 'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_controller_revision(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_controller_revision_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_controller_revision_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_controller_revision_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_controller_revision`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_deployment(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_deployment_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_deployment_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_deployment_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_deployment`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_deployment_scale(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_deployment_scale_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_deployment_scale_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_deployment_scale" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_deployment_scale`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/scale', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_deployment_status(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_deployment_status_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_deployment_status_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_deployment_status_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_deployment_status" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_deployment_status`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_deployment_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_stateful_set(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_stateful_set_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_stateful_set_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_stateful_set_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_stateful_set_scale(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_stateful_set_scale_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_stateful_set_scale_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_stateful_set_scale_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_stateful_set_scale" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set_scale`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/scale', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_stateful_set_status(self, name, namespace, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_stateful_set_status_with_http_info(name, namespace, **kwargs)
else:
(data) = self.read_namespaced_stateful_set_status_with_http_info(name, namespace, **kwargs)
return data
def read_namespaced_stateful_set_status_with_http_info(self, name, namespace, **kwargs):
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_stateful_set_status" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_stateful_set_status`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_stateful_set_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/status', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_controller_revision(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_controller_revision_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_controller_revision_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_controller_revision" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_controller_revision`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_controller_revision`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_controller_revision`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/controllerrevisions/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1ControllerRevision',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_deployment(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_deployment_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_deployment_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_deployment" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_deployment_scale(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_deployment_scale_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_deployment_scale_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_deployment_scale" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment_scale`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment_scale`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/scale', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_deployment_status(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_deployment_status_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_deployment_status_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_deployment_status" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_deployment_status`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_deployment_status`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_deployment_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/deployments/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Deployment',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_stateful_set(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_stateful_set_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_stateful_set_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_stateful_set" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_stateful_set_scale(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_stateful_set_scale_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_stateful_set_scale_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_stateful_set_scale" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set_scale`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set_scale`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set_scale`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/scale', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='AppsV1beta1Scale',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_stateful_set_status(self, name, namespace, body, **kwargs):
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_stateful_set_status_with_http_info(name, namespace, body, **kwargs)
return data
def replace_namespaced_stateful_set_status_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty', 'dry_run']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_stateful_set_status" % key
)
params[key] = val
del params['kwargs']
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_stateful_set_status`")
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_stateful_set_status`")
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_stateful_set_status`")
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
auth_settings = ['BearerToken']
return self.api_client.call_api('/apis/apps/v1beta1/namespaces/{namespace}/statefulsets/{name}/status', 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1beta1StatefulSet',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| true | true |
f727dd8d7d3f08eb3d6179104991040375e54f90 | 5,354 | py | Python | test/integration/smoke/test_async_job.py | saliven1970/cloudstack | 4617be458387421bbbfc120c1f054c9939ba52eb | [
"Apache-2.0"
] | 2 | 2021-10-31T01:04:26.000Z | 2021-11-08T09:43:30.000Z | test/integration/smoke/test_async_job.py | saliven1970/cloudstack | 4617be458387421bbbfc120c1f054c9939ba52eb | [
"Apache-2.0"
] | 20 | 2020-12-19T22:32:23.000Z | 2022-02-01T01:07:06.000Z | test/integration/smoke/test_async_job.py | saliven1970/cloudstack | 4617be458387421bbbfc120c1f054c9939ba52eb | [
"Apache-2.0"
] | 2 | 2016-11-10T16:29:26.000Z | 2019-05-20T12:23:35.000Z | # 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.
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import cleanup_resources
from marvin.lib.base import ServiceOffering, DiskOffering, Account, VirtualMachine,\
queryAsyncJobResult, PASS
from marvin.lib.common import get_domain, get_zone, get_test_template
from pytz import timezone
class TestAsyncJob(cloudstackTestCase):
"""
Test queryAsyncJobResult
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestAsyncJob, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
# Get Zone, Domain and templates
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.template = get_test_template(
cls.api_client,
cls.zone.id,
cls.hypervisor
)
# Create service, disk offerings etc
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testdata["service_offering"]
)
cls.disk_offering = DiskOffering.create(
cls.api_client,
cls.testdata["disk_offering"]
)
cls._cleanup = [
cls.service_offering,
cls.disk_offering
]
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as exception:
raise Exception("Warning: Exception during cleanup : %s" % exception)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.hypervisor = self.testClient.getHypervisorInfo()
self.testdata["virtual_machine"]["zoneid"] = self.zone.id
self.testdata["virtual_machine"]["template"] = self.template.id
self.testdata["iso"]["zoneid"] = self.zone.id
self.account = Account.create(
self.apiclient,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup = [self.account]
def tearDown(self):
try:
self.debug("Cleaning up the resources")
cleanup_resources(self.apiclient, self.cleanup)
self.debug("Cleanup complete!")
except Exception as exception:
self.debug("Warning! Exception in tearDown: %s" % exception)
@attr(tags=["advanced", "eip", "advancedns", "basic", "sg"], required_hardware="false")
def test_query_async_job_result(self):
"""
Test queryAsyncJobResult API for expected values
"""
self.debug("Deploying instance in the account: %s" %
self.account.name)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
diskofferingid=self.disk_offering.id,
hypervisor=self.hypervisor
)
response = virtual_machine.getState(
self.apiclient,
VirtualMachine.RUNNING)
self.assertEqual(response[0], PASS, response[1])
cmd = queryAsyncJobResult.queryAsyncJobResultCmd()
cmd.jobid = virtual_machine.jobid
cmd_response = self.apiclient.queryAsyncJobResult(cmd)
db_result = self.dbclient.execute("select * from async_job where uuid='%s'" %
virtual_machine.jobid)
# verify that 'completed' value from api equals 'removed' db column value
completed = cmd_response.completed
removed = timezone('UTC').localize(db_result[0][17])
removed = removed.strftime("%Y-%m-%dT%H:%M:%S%z")
self.assertEqual(completed, removed,
"Expected 'completed' timestamp value %s to be equal to "
"'removed' db column value %s." % (completed, removed))
# verify that api job_status value equals db job_status value
jobstatus_db = db_result[0][8]
jobstatus_api = cmd_response.jobstatus
self.assertEqual(jobstatus_api, jobstatus_db,
"Expected 'jobstatus' api value %s to be equal to "
"'job_status' db column value %s." % (jobstatus_api, jobstatus_db))
| 39.367647 | 92 | 0.649234 |
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.utils import cleanup_resources
from marvin.lib.base import ServiceOffering, DiskOffering, Account, VirtualMachine,\
queryAsyncJobResult, PASS
from marvin.lib.common import get_domain, get_zone, get_test_template
from pytz import timezone
class TestAsyncJob(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestAsyncJob, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.testdata = cls.testClient.getParsedTestDataConfig()
cls.domain = get_domain(cls.api_client)
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.hypervisor = cls.testClient.getHypervisorInfo()
cls.template = get_test_template(
cls.api_client,
cls.zone.id,
cls.hypervisor
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.testdata["service_offering"]
)
cls.disk_offering = DiskOffering.create(
cls.api_client,
cls.testdata["disk_offering"]
)
cls._cleanup = [
cls.service_offering,
cls.disk_offering
]
@classmethod
def tearDownClass(cls):
try:
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as exception:
raise Exception("Warning: Exception during cleanup : %s" % exception)
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.hypervisor = self.testClient.getHypervisorInfo()
self.testdata["virtual_machine"]["zoneid"] = self.zone.id
self.testdata["virtual_machine"]["template"] = self.template.id
self.testdata["iso"]["zoneid"] = self.zone.id
self.account = Account.create(
self.apiclient,
self.testdata["account"],
domainid=self.domain.id
)
self.cleanup = [self.account]
def tearDown(self):
try:
self.debug("Cleaning up the resources")
cleanup_resources(self.apiclient, self.cleanup)
self.debug("Cleanup complete!")
except Exception as exception:
self.debug("Warning! Exception in tearDown: %s" % exception)
@attr(tags=["advanced", "eip", "advancedns", "basic", "sg"], required_hardware="false")
def test_query_async_job_result(self):
self.debug("Deploying instance in the account: %s" %
self.account.name)
virtual_machine = VirtualMachine.create(
self.apiclient,
self.testdata["virtual_machine"],
accountid=self.account.name,
domainid=self.account.domainid,
serviceofferingid=self.service_offering.id,
diskofferingid=self.disk_offering.id,
hypervisor=self.hypervisor
)
response = virtual_machine.getState(
self.apiclient,
VirtualMachine.RUNNING)
self.assertEqual(response[0], PASS, response[1])
cmd = queryAsyncJobResult.queryAsyncJobResultCmd()
cmd.jobid = virtual_machine.jobid
cmd_response = self.apiclient.queryAsyncJobResult(cmd)
db_result = self.dbclient.execute("select * from async_job where uuid='%s'" %
virtual_machine.jobid)
completed = cmd_response.completed
removed = timezone('UTC').localize(db_result[0][17])
removed = removed.strftime("%Y-%m-%dT%H:%M:%S%z")
self.assertEqual(completed, removed,
"Expected 'completed' timestamp value %s to be equal to "
"'removed' db column value %s." % (completed, removed))
jobstatus_db = db_result[0][8]
jobstatus_api = cmd_response.jobstatus
self.assertEqual(jobstatus_api, jobstatus_db,
"Expected 'jobstatus' api value %s to be equal to "
"'job_status' db column value %s." % (jobstatus_api, jobstatus_db))
| true | true |
f727ddec1d4bf396d3560c014f5899414eb5618e | 180 | py | Python | src/app/blueprints/main/controllers.py | Dev-Nebe/student-hub | fe6718aced065dab4bb8d92372bfe098c1a75137 | [
"MIT"
] | 3 | 2020-05-25T19:36:11.000Z | 2021-09-15T09:05:57.000Z | src/app/blueprints/main/controllers.py | Dev-Nebe/student-hub | fe6718aced065dab4bb8d92372bfe098c1a75137 | [
"MIT"
] | 1 | 2021-04-30T21:11:44.000Z | 2021-04-30T21:11:44.000Z | src/app/blueprints/main/controllers.py | Dev-Nebe/student-hub | fe6718aced065dab4bb8d92372bfe098c1a75137 | [
"MIT"
] | null | null | null | from flask import Blueprint, jsonify
main_bp = Blueprint('main', __name__)
@main_bp.route('/')
def api_home():
return jsonify({"message": "Welcome to the Student Hub API"})
| 20 | 65 | 0.705556 | from flask import Blueprint, jsonify
main_bp = Blueprint('main', __name__)
@main_bp.route('/')
def api_home():
return jsonify({"message": "Welcome to the Student Hub API"})
| true | true |
f727e110b2656c38f2c08d157ab83662cd7bb00d | 3,506 | py | Python | tools/validators/instance_validator/tests/instance_parser_test.py | HTKshimo/digitalbuildings | a6dad0282cac7dbe2a31d1b3c9a6dc9adddb5177 | [
"Apache-2.0"
] | null | null | null | tools/validators/instance_validator/tests/instance_parser_test.py | HTKshimo/digitalbuildings | a6dad0282cac7dbe2a31d1b3c9a6dc9adddb5177 | [
"Apache-2.0"
] | null | null | null | tools/validators/instance_validator/tests/instance_parser_test.py | HTKshimo/digitalbuildings | a6dad0282cac7dbe2a31d1b3c9a6dc9adddb5177 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Google LLC
#
# 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
#
# https://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.
"""Tests tools.validators.instance_validator.instance_parser"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import instance_parser
from absl.testing import absltest
_TESTCASE_PATH = os.path.join('.', 'tests', 'fake_instances')
class ParserTest(absltest.TestCase):
def testInstanceValidatorDetectDuplicateKeys(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_duplicate_keys.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectMissingColon(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_missing_colon.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperSpacing(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_spacing.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperTabbing(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_tabbing.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorParseProperFormat(self):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'GOOD',
'good_building_type.yaml'))
self.assertIsNotNone(parse)
def testInstanceValidatorParseProperConnections(self):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'GOOD',
'good_building_connections.yaml'))
self.assertIsNotNone(parse)
def testInstanceValidatorDetectImproperTranslationCompliance(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_translation_compliant.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperTranslationKeys(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_translation_keys.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperUnitsKeys(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_translation_units_format.yaml'))
self.assertIsNone(parse)
if __name__ == '__main__':
absltest.main()
| 34.372549 | 74 | 0.666572 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import instance_parser
from absl.testing import absltest
_TESTCASE_PATH = os.path.join('.', 'tests', 'fake_instances')
class ParserTest(absltest.TestCase):
def testInstanceValidatorDetectDuplicateKeys(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_duplicate_keys.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectMissingColon(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_missing_colon.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperSpacing(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_spacing.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperTabbing(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_tabbing.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorParseProperFormat(self):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'GOOD',
'good_building_type.yaml'))
self.assertIsNotNone(parse)
def testInstanceValidatorParseProperConnections(self):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'GOOD',
'good_building_connections.yaml'))
self.assertIsNotNone(parse)
def testInstanceValidatorDetectImproperTranslationCompliance(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_translation_compliant.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperTranslationKeys(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_translation_keys.yaml'))
self.assertIsNone(parse)
def testInstanceValidatorDetectImproperUnitsKeys(self):
with self.assertRaises(SystemExit):
parse = instance_parser.parse_yaml(
os.path.join(_TESTCASE_PATH,
'BAD',
'bad_translation_units_format.yaml'))
self.assertIsNone(parse)
if __name__ == '__main__':
absltest.main()
| true | true |
f727e15a3cb3d79ce95f8fecbf0b1a12b57e08b8 | 1,268 | py | Python | prova/relazioni/views.py | mary023010/prova_django | a69a37a4f26f21018cef48e5d637dd630ca68877 | [
"MIT"
] | null | null | null | prova/relazioni/views.py | mary023010/prova_django | a69a37a4f26f21018cef48e5d637dd630ca68877 | [
"MIT"
] | null | null | null | prova/relazioni/views.py | mary023010/prova_django | a69a37a4f26f21018cef48e5d637dd630ca68877 | [
"MIT"
] | null | null | null | from django.shortcuts import render, redirect
from django.views.generic.detail import DetailView
from .models import Fly,Airport
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required(login_url='/login/')
def selection_airport(request):
ls_airports = Airport.objects.all()
context = {'airports' : ls_airports}
return render(request,'relazioni/form_prenotazione.html',context)
def visualizza_voli(request):
ls_voli = []
if request.method == 'POST':
aeroporto_partenza = request.POST['a_partenza']
aeroporto_arrivo = request.POST['a_arrivo']
data = request.POST['data']
ls_voli = Fly.objects.filter(Q(aeroporto_partenza=aeroporto_partenza) & Q(aeroporto_arrivo=aeroporto_arrivo) & Q(data_partenza=data))
messages.success(request, 'Ecco tutti i voli disponibili')
voli = []
for index in ls_voli:
volo = Fly.objects.get(code_volo=index)
voli.append(volo)
context = {
'voli': voli,
}
else:
messages.error(request, 'Non ci sono voli disponibili!')
return render(request,'relazioni/voli.html',context)
| 31.7 | 141 | 0.689274 | from django.shortcuts import render, redirect
from django.views.generic.detail import DetailView
from .models import Fly,Airport
from django.db.models import Q
from django.contrib import messages
from django.contrib.auth.decorators import login_required
@login_required(login_url='/login/')
def selection_airport(request):
ls_airports = Airport.objects.all()
context = {'airports' : ls_airports}
return render(request,'relazioni/form_prenotazione.html',context)
def visualizza_voli(request):
ls_voli = []
if request.method == 'POST':
aeroporto_partenza = request.POST['a_partenza']
aeroporto_arrivo = request.POST['a_arrivo']
data = request.POST['data']
ls_voli = Fly.objects.filter(Q(aeroporto_partenza=aeroporto_partenza) & Q(aeroporto_arrivo=aeroporto_arrivo) & Q(data_partenza=data))
messages.success(request, 'Ecco tutti i voli disponibili')
voli = []
for index in ls_voli:
volo = Fly.objects.get(code_volo=index)
voli.append(volo)
context = {
'voli': voli,
}
else:
messages.error(request, 'Non ci sono voli disponibili!')
return render(request,'relazioni/voli.html',context)
| true | true |
f727e2c8e1a28f98877f1994152992973984a11f | 879 | py | Python | recipes/models.py | asis2016/momo-ristorante-v1 | d46c36d1b92212ade34d781c4e2adc91cb52cac7 | [
"MIT"
] | null | null | null | recipes/models.py | asis2016/momo-ristorante-v1 | d46c36d1b92212ade34d781c4e2adc91cb52cac7 | [
"MIT"
] | null | null | null | recipes/models.py | asis2016/momo-ristorante-v1 | d46c36d1b92212ade34d781c4e2adc91cb52cac7 | [
"MIT"
] | null | null | null | import uuid
from django.db import models
from django.urls import reverse
from core.models import (Authorable,
Titleable,
TimeStampedModel)
class Recipe(Authorable, Titleable, TimeStampedModel):
"""
Recipe model as of v.1.0.
"""
CATEGORY = (
('WS', 'Western'),
('TB', 'Tibetan'),
('NP', 'Nepalese')
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
excerpt = models.TextField(max_length=200, blank=True)
content = models.TextField(blank=True)
image = models.ImageField(upload_to='', default='default.png', blank=True)
image_url = models.CharField(max_length=200, blank=True)
def __str__(self):
return str(self.title)
def get_absolute_url(self):
return reverse('dashboard:recipe_detail', args=[str(self.id)])
| 28.354839 | 79 | 0.633675 | import uuid
from django.db import models
from django.urls import reverse
from core.models import (Authorable,
Titleable,
TimeStampedModel)
class Recipe(Authorable, Titleable, TimeStampedModel):
CATEGORY = (
('WS', 'Western'),
('TB', 'Tibetan'),
('NP', 'Nepalese')
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
excerpt = models.TextField(max_length=200, blank=True)
content = models.TextField(blank=True)
image = models.ImageField(upload_to='', default='default.png', blank=True)
image_url = models.CharField(max_length=200, blank=True)
def __str__(self):
return str(self.title)
def get_absolute_url(self):
return reverse('dashboard:recipe_detail', args=[str(self.id)])
| true | true |
f727e34363c19a7e7e17351055f27d2efc065ca3 | 1,932 | py | Python | src/bot/keyboards/claim_parts.py | nchursin/claimant | 890ce1a3ced8db9d2e2fbddb8a3207e82ac05326 | [
"BSD-3-Clause"
] | 3 | 2022-03-03T19:10:25.000Z | 2022-03-03T19:57:15.000Z | src/bot/keyboards/claim_parts.py | nchursin/claimant | 890ce1a3ced8db9d2e2fbddb8a3207e82ac05326 | [
"BSD-3-Clause"
] | 9 | 2022-03-03T18:56:37.000Z | 2022-03-29T18:34:02.000Z | src/bot/keyboards/claim_parts.py | nchursin/claimant | 890ce1a3ced8db9d2e2fbddb8a3207e82ac05326 | [
"BSD-3-Clause"
] | 1 | 2022-03-04T11:59:11.000Z | 2022-03-04T11:59:11.000Z | from typing import List
from aiogram.types import KeyboardButton, ReplyKeyboardMarkup
from keyboards import emojis
from repository import Repository
PART_NAMES: List[str] = ["head", "story", "essence", "proofs", "claims", "additions"]
def get_claim_parts_kb(user_id: int) -> ReplyKeyboardMarkup:
parts_status: dict = get_claim_parts_status(user_id)
claim_parts_kb = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
claim_parts_kb\
.add(KeyboardButton(f"{emojis.top_hat} шапка {emojis.check_mark if parts_status['head'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.speech_balloon} фабула {emojis.check_mark if parts_status['story'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.key} суть нарушения {emojis.check_mark if parts_status['essence'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.page_with_curl} доказательства {emojis.check_mark if parts_status['proofs'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.index_pointing_up} требования {emojis.check_mark if parts_status['claims'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.card_index_dividers} приложения {emojis.check_mark if parts_status['additions'] is True else ''}"))
claim_parts_kb.row(*[KeyboardButton(f"{emojis.left_arrow} к шаблонам"),
KeyboardButton(f"{emojis.inbox_tray} получить")])
return claim_parts_kb
def get_claim_parts_status(user_id: int) -> dict:
repository: Repository = Repository()
claim_data: dict = repository.get_claim_data(user_id)
if "claim_data" not in claim_data.keys():
return {pn: False for pn in PART_NAMES}
parts_status: dict = {}
for part_name in PART_NAMES:
if part_name in claim_data["claim_data"].keys():
parts_status.update(**{part_name: True})
else:
parts_status.update(**{part_name: False})
return parts_status
| 49.538462 | 137 | 0.710145 | from typing import List
from aiogram.types import KeyboardButton, ReplyKeyboardMarkup
from keyboards import emojis
from repository import Repository
PART_NAMES: List[str] = ["head", "story", "essence", "proofs", "claims", "additions"]
def get_claim_parts_kb(user_id: int) -> ReplyKeyboardMarkup:
parts_status: dict = get_claim_parts_status(user_id)
claim_parts_kb = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True)
claim_parts_kb\
.add(KeyboardButton(f"{emojis.top_hat} шапка {emojis.check_mark if parts_status['head'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.speech_balloon} фабула {emojis.check_mark if parts_status['story'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.key} суть нарушения {emojis.check_mark if parts_status['essence'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.page_with_curl} доказательства {emojis.check_mark if parts_status['proofs'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.index_pointing_up} требования {emojis.check_mark if parts_status['claims'] is True else ''}")) \
.add(KeyboardButton(f"{emojis.card_index_dividers} приложения {emojis.check_mark if parts_status['additions'] is True else ''}"))
claim_parts_kb.row(*[KeyboardButton(f"{emojis.left_arrow} к шаблонам"),
KeyboardButton(f"{emojis.inbox_tray} получить")])
return claim_parts_kb
def get_claim_parts_status(user_id: int) -> dict:
repository: Repository = Repository()
claim_data: dict = repository.get_claim_data(user_id)
if "claim_data" not in claim_data.keys():
return {pn: False for pn in PART_NAMES}
parts_status: dict = {}
for part_name in PART_NAMES:
if part_name in claim_data["claim_data"].keys():
parts_status.update(**{part_name: True})
else:
parts_status.update(**{part_name: False})
return parts_status
| true | true |
f727e3458cf9ec525e06fec4d8066046877248f1 | 5,378 | py | Python | modules/REPORT_RESULTS/scripts/select-motifs.py | gruber-sciencelab/MAPP | 81563f676b284c5b283a193a698ce618c044d3b5 | [
"Apache-2.0"
] | null | null | null | modules/REPORT_RESULTS/scripts/select-motifs.py | gruber-sciencelab/MAPP | 81563f676b284c5b283a193a698ce618c044d3b5 | [
"Apache-2.0"
] | null | null | null | modules/REPORT_RESULTS/scripts/select-motifs.py | gruber-sciencelab/MAPP | 81563f676b284c5b283a193a698ce618c044d3b5 | [
"Apache-2.0"
] | 1 | 2022-01-15T04:39:30.000Z | 2022-01-15T04:39:30.000Z | """
##############################################################################
#
# Select top N distinct motifs with highest (statistically significant)
# activity Z-score (for every site separately)
#
# AUTHOR: Maciej_Bak
# AFFILIATION: University_of_Basel
# AFFILIATION: Swiss_Institute_of_Bioinformatics
# CONTACT: maciej.bak@unibas.ch
# CREATED: 04-06-2020
# LICENSE: Apache_2.0
#
##############################################################################
"""
# imports
import time
import logging
import logging.handlers
from argparse import ArgumentParser, RawTextHelpFormatter
import os
import pandas as pd
def parse_arguments():
"""Parser of the command-line arguments."""
parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
parser.add_argument(
"-v",
"--verbosity",
dest="verbosity",
choices=("DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"),
default="ERROR",
help="Verbosity/Log level. Defaults to ERROR",
)
parser.add_argument(
"-l", "--logfile", dest="logfile", help="Store log to this file."
)
parser.add_argument(
"--topN-motifs",
dest="N",
default=1000000, # by default: effectively select all stat. sign. motifs
required=False,
help="Number of top motifs to select.",
)
parser.add_argument(
"--infile-splicing-3ss",
dest="results_3ss",
required=True,
help="Annotated results table (3ss).",
)
parser.add_argument(
"--infile-splicing-5ss",
dest="results_5ss",
required=True,
help="Annotated results table (5ss).",
)
parser.add_argument(
"--infile-polyadenylation-pas",
dest="results_pas",
required=True,
help="Annotated results table (pas).",
)
parser.add_argument(
"--outfile-splicing-3ss-motifs",
dest="motifs_3ss",
required=True,
help="Path for the text file with top motifs (3ss).",
)
parser.add_argument(
"--outfile-splicing-5ss-motifs",
dest="motifs_5ss",
required=True,
help="Path for the text file with top motifs (5ss).",
)
parser.add_argument(
"--outfile-polyadenylation-pas-motifs",
dest="motifs_pas",
required=True,
help="Path for the text file with top motifs (pas).",
)
return parser
##############################################################################
def main():
"""Main body of the script."""
df = pd.read_csv(options.results_3ss, sep="\t", index_col=0)
df = df[df["significance-marker"]]
motifs = []
for ID, row in df.iterrows():
if len(motifs) == int(options.N):
break
m = ID.split("|")[-1]
if m not in motifs:
motifs.append(m)
with open(options.motifs_3ss, "w") as f:
for m in motifs:
f.write(m + os.linesep)
df = pd.read_csv(options.results_5ss, sep="\t", index_col=0)
df = df[df["significance-marker"]]
motifs = []
for ID, row in df.iterrows():
if len(motifs) == int(options.N):
break
m = ID.split("|")[-1]
if m not in motifs:
motifs.append(m)
with open(options.motifs_5ss, "w") as f:
for m in motifs:
f.write(m + os.linesep)
df = pd.read_csv(options.results_pas, sep="\t", index_col=0)
df = df[df["significance-marker"]]
motifs = []
for ID, row in df.iterrows():
if len(motifs) == int(options.N):
break
m = ID.split("|")[-1]
if m not in motifs:
motifs.append(m)
with open(options.motifs_pas, "w") as f:
for m in motifs:
f.write(m + os.linesep)
##############################################################################
if __name__ == "__main__":
try:
# parse the command-line arguments
options = parse_arguments().parse_args()
# set up logging during the execution
formatter = logging.Formatter(
fmt="[%(asctime)s] %(levelname)s - %(message)s",
datefmt="%d-%b-%Y %H:%M:%S",
)
console_handler = logging.StreamHandler()
console_handler.setFormatter(formatter)
logger = logging.getLogger("logger")
logger.setLevel(logging.getLevelName(options.verbosity))
logger.addHandler(console_handler)
if options.logfile is not None:
logfile_handler = logging.handlers.RotatingFileHandler(
options.logfile, maxBytes=50000, backupCount=2
)
logfile_handler.setFormatter(formatter)
logger.addHandler(logfile_handler)
# execute the body of the script
start_time = time.time()
logger.info("Starting script")
main()
seconds = time.time() - start_time
# log the execution time
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
logger.info(
"Successfully finished in {hours}h:{minutes}m:{seconds}s",
hours=int(hours),
minutes=int(minutes),
seconds=int(seconds) if seconds > 1.0 else 1,
)
# log the exception in case it happens
except Exception as e:
logger.exception(str(e))
raise e
| 30.556818 | 86 | 0.554481 |
import time
import logging
import logging.handlers
from argparse import ArgumentParser, RawTextHelpFormatter
import os
import pandas as pd
def parse_arguments():
parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
parser.add_argument(
"-v",
"--verbosity",
dest="verbosity",
choices=("DEBUG", "INFO", "WARN", "ERROR", "CRITICAL"),
default="ERROR",
help="Verbosity/Log level. Defaults to ERROR",
)
parser.add_argument(
"-l", "--logfile", dest="logfile", help="Store log to this file."
)
parser.add_argument(
"--topN-motifs",
dest="N",
default=1000000,
required=False,
help="Number of top motifs to select.",
)
parser.add_argument(
"--infile-splicing-3ss",
dest="results_3ss",
required=True,
help="Annotated results table (3ss).",
)
parser.add_argument(
"--infile-splicing-5ss",
dest="results_5ss",
required=True,
help="Annotated results table (5ss).",
)
parser.add_argument(
"--infile-polyadenylation-pas",
dest="results_pas",
required=True,
help="Annotated results table (pas).",
)
parser.add_argument(
"--outfile-splicing-3ss-motifs",
dest="motifs_3ss",
required=True,
help="Path for the text file with top motifs (3ss).",
)
parser.add_argument(
"--outfile-splicing-5ss-motifs",
dest="motifs_5ss",
required=True,
help="Path for the text file with top motifs (5ss).",
)
parser.add_argument(
"--outfile-polyadenylation-pas-motifs",
dest="motifs_pas",
required=True,
help="Path for the text file with top motifs (pas).",
)
return parser
| true | true |
f727e3880049704ad4f93c71f9dada6ffc47feb8 | 1,530 | py | Python | top10losers/top10losers.py | KevBarbour/cryptobot | 57239c83ca5dd84d2a0e273f20782cf608ce99ba | [
"MIT"
] | null | null | null | top10losers/top10losers.py | KevBarbour/cryptobot | 57239c83ca5dd84d2a0e273f20782cf608ce99ba | [
"MIT"
] | null | null | null | top10losers/top10losers.py | KevBarbour/cryptobot | 57239c83ca5dd84d2a0e273f20782cf608ce99ba | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import requests
from bs4 import BeautifulSoup
import sys
from twython import Twython
import numpy as np
apiKey = '...'
apiSecret = '...'
accessToken = '...'
accessTokenSecret = '...'
#BeautifulSoup scraping algorythm
url = 'https://coinmarketcap.com'
soup = BeautifulSoup(requests.get(url).text, 'lxml')
L=[]
#H =["Rank","Name","M Cap","$/1", "HURR", "DURR", "24 hr"]
F=0
for tr in soup.select('#currencies tr'):
if not tr.select('td'):
continue
for i, td in enumerate(tr.select('td')[:7]) :
txt = td.text.replace('\n',' ').replace('*', '').replace('%','').replace('.com','').replace('chain','').replace('coin','').strip()
L.append(txt)
#dictates how many lines will be read
F=F+1
if F>99:
break
#reshapes array to only include necessary columns and re orders them
A = np.reshape(L, (100,7))
Perm = [1,3,6,2,4,5,0]
A = A[:, Perm]
A = np.delete(A, (1,3,4,5,6), 1)
#sorting array based on percent change
A = sorted(A,key=lambda x: (float(x[1])))
A = A[:10]
#write table to a python file and re reads it, possibly poor method
with open("output10losers.txt", "w") as txt_file:
for line in A:
txt_file.write("#" + " ".join(line) + "%" + "\n" )
T = open("output10losers.txt", "r")
finaltweet = T.read()
tweetStr = "Top 10 #Crypto Losers 24hrs:" + "\n" + finaltweet
#twitter API commands
api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
api.update_status(status=tweetStr)
print("Tweeted: " + tweetStr)
| 26.37931 | 138 | 0.62549 |
import requests
from bs4 import BeautifulSoup
import sys
from twython import Twython
import numpy as np
apiKey = '...'
apiSecret = '...'
accessToken = '...'
accessTokenSecret = '...'
url = 'https://coinmarketcap.com'
soup = BeautifulSoup(requests.get(url).text, 'lxml')
L=[]
F=0
for tr in soup.select('#currencies tr'):
if not tr.select('td'):
continue
for i, td in enumerate(tr.select('td')[:7]) :
txt = td.text.replace('\n',' ').replace('*', '').replace('%','').replace('.com','').replace('chain','').replace('coin','').strip()
L.append(txt)
F=F+1
if F>99:
break
A = np.reshape(L, (100,7))
Perm = [1,3,6,2,4,5,0]
A = A[:, Perm]
A = np.delete(A, (1,3,4,5,6), 1)
A = sorted(A,key=lambda x: (float(x[1])))
A = A[:10]
with open("output10losers.txt", "w") as txt_file:
for line in A:
txt_file.write("#" + " ".join(line) + "%" + "\n" )
T = open("output10losers.txt", "r")
finaltweet = T.read()
tweetStr = "Top 10 #Crypto Losers 24hrs:" + "\n" + finaltweet
api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
api.update_status(status=tweetStr)
print("Tweeted: " + tweetStr)
| true | true |
f727e3d280dbac1f16c6fe5d8782bb4bd6564767 | 59,646 | py | Python | allennlp/nn/util.py | threefoldo/allennlp | 983db284cb46fd18c898dd3b0e04eed6cb932768 | [
"Apache-2.0"
] | 3 | 2019-06-17T21:09:07.000Z | 2022-03-18T05:19:31.000Z | allennlp/nn/util.py | alisdairv/allennlp | 9fcc79566cc148cce9f967a7962ac03bc300f011 | [
"Apache-2.0"
] | null | null | null | allennlp/nn/util.py | alisdairv/allennlp | 9fcc79566cc148cce9f967a7962ac03bc300f011 | [
"Apache-2.0"
] | 1 | 2020-03-12T06:53:53.000Z | 2020-03-12T06:53:53.000Z | """
Assorted utilities for working with neural networks in AllenNLP.
"""
# pylint: disable=too-many-lines
from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar
import logging
import math
import warnings
import torch
from allennlp.common.checks import ConfigurationError
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
T = TypeVar('T')
def has_tensor(obj) -> bool:
"""
Given a possibly complex data structure,
check if it has any torch.Tensors in it.
"""
if isinstance(obj, torch.Tensor):
return True
elif isinstance(obj, dict):
return any(has_tensor(value) for value in obj.values())
elif isinstance(obj, (list, tuple)):
return any(has_tensor(item) for item in obj)
else:
return False
def move_to_device(obj, cuda_device: int):
"""
Given a structure (possibly) containing Tensors on the CPU,
move all the Tensors to the specified GPU (or do nothing, if they should be on the CPU).
"""
if cuda_device < 0 or not has_tensor(obj):
return obj
elif isinstance(obj, torch.Tensor):
return obj.cuda(cuda_device)
elif isinstance(obj, dict):
return {key: move_to_device(value, cuda_device) for key, value in obj.items()}
elif isinstance(obj, list):
return [move_to_device(item, cuda_device) for item in obj]
elif isinstance(obj, tuple):
return tuple([move_to_device(item, cuda_device) for item in obj])
else:
return obj
def batch_tensor_dicts(tensor_dicts: List[Dict[str, torch.Tensor]],
remove_trailing_dimension: bool = False) -> Dict[str, torch.Tensor]:
"""
Takes a list of tensor dictionaries, where each dictionary is assumed to have matching keys,
and returns a single dictionary with all tensors with the same key batched together.
Parameters
----------
tensor_dicts : ``List[Dict[str, torch.Tensor]]``
The list of tensor dictionaries to batch.
remove_trailing_dimension : ``bool``
If ``True``, we will check for a trailing dimension of size 1 on the tensors that are being
batched, and remove it if we find it.
"""
key_to_tensors: Dict[str, List[torch.Tensor]] = defaultdict(list)
for tensor_dict in tensor_dicts:
for key, tensor in tensor_dict.items():
key_to_tensors[key].append(tensor)
batched_tensors = {}
for key, tensor_list in key_to_tensors.items():
batched_tensor = torch.stack(tensor_list)
if remove_trailing_dimension and all(tensor.size(-1) == 1 for tensor in tensor_list):
batched_tensor = batched_tensor.squeeze(-1)
batched_tensors[key] = batched_tensor
return batched_tensors
def get_lengths_from_binary_sequence_mask(mask: torch.Tensor):
"""
Compute sequence lengths for each batch element in a tensor using a
binary mask.
Parameters
----------
mask : torch.Tensor, required.
A 2D binary mask of shape (batch_size, sequence_length) to
calculate the per-batch sequence lengths from.
Returns
-------
A torch.LongTensor of shape (batch_size,) representing the lengths
of the sequences in the batch.
"""
return mask.long().sum(-1)
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
"""
Given a variable of shape ``(batch_size,)`` that represents the sequence lengths of each batch
element, this function returns a ``(batch_size, max_length)`` mask variable. For example, if
our input was ``[2, 2, 3]``, with a ``max_length`` of 4, we'd return
``[[1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0]]``.
We require ``max_length`` here instead of just computing it from the input ``sequence_lengths``
because it lets us avoid finding the max, then copying that value from the GPU to the CPU so
that we can use it to construct a new tensor.
"""
# (batch_size, max_length)
ones = sequence_lengths.new_ones(sequence_lengths.size(0), max_length)
range_tensor = ones.cumsum(dim=1)
return (sequence_lengths.unsqueeze(1) >= range_tensor).long()
def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
"""
Sort a batch first tensor by some specified lengths.
Parameters
----------
tensor : torch.FloatTensor, required.
A batch first Pytorch tensor.
sequence_lengths : torch.LongTensor, required.
A tensor representing the lengths of some dimension of the tensor which
we want to sort by.
Returns
-------
sorted_tensor : torch.FloatTensor
The original tensor sorted along the batch dimension with respect to sequence_lengths.
sorted_sequence_lengths : torch.LongTensor
The original sequence_lengths sorted by decreasing size.
restoration_indices : torch.LongTensor
Indices into the sorted_tensor such that
``sorted_tensor.index_select(0, restoration_indices) == original_tensor``
permuation_index : torch.LongTensor
The indices used to sort the tensor. This is useful if you want to sort many
tensors using the same ordering.
"""
if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):
raise ConfigurationError("Both the tensor and sequence lengths must be torch.Tensors.")
sorted_sequence_lengths, permutation_index = sequence_lengths.sort(0, descending=True)
sorted_tensor = tensor.index_select(0, permutation_index)
index_range = sequence_lengths.new_tensor(torch.arange(0, len(sequence_lengths)))
# This is the equivalent of zipping with index, sorting by the original
# sequence lengths and returning the now sorted indices.
_, reverse_mapping = permutation_index.sort(0, descending=False)
restoration_indices = index_range.index_select(0, reverse_mapping)
return sorted_tensor, sorted_sequence_lengths, restoration_indices, permutation_index
def get_final_encoder_states(encoder_outputs: torch.Tensor,
mask: torch.Tensor,
bidirectional: bool = False) -> torch.Tensor:
"""
Given the output from a ``Seq2SeqEncoder``, with shape ``(batch_size, sequence_length,
encoding_dim)``, this method returns the final hidden state for each element of the batch,
giving a tensor of shape ``(batch_size, encoding_dim)``. This is not as simple as
``encoder_outputs[:, -1]``, because the sequences could have different lengths. We use the
mask (which has shape ``(batch_size, sequence_length)``) to find the final state for each batch
instance.
Additionally, if ``bidirectional`` is ``True``, we will split the final dimension of the
``encoder_outputs`` into two and assume that the first half is for the forward direction of the
encoder and the second half is for the backward direction. We will concatenate the last state
for each encoder dimension, giving ``encoder_outputs[:, -1, :encoding_dim/2]`` concated with
``encoder_outputs[:, 0, encoding_dim/2:]``.
"""
# These are the indices of the last words in the sequences (i.e. length sans padding - 1). We
# are assuming sequences are right padded.
# Shape: (batch_size,)
last_word_indices = mask.sum(1).long() - 1
batch_size, _, encoder_output_dim = encoder_outputs.size()
expanded_indices = last_word_indices.view(-1, 1, 1).expand(batch_size, 1, encoder_output_dim)
# Shape: (batch_size, 1, encoder_output_dim)
final_encoder_output = encoder_outputs.gather(1, expanded_indices)
final_encoder_output = final_encoder_output.squeeze(1) # (batch_size, encoder_output_dim)
if bidirectional:
final_forward_output = final_encoder_output[:, :(encoder_output_dim // 2)]
final_backward_output = encoder_outputs[:, 0, (encoder_output_dim // 2):]
final_encoder_output = torch.cat([final_forward_output, final_backward_output], dim=-1)
return final_encoder_output
def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
"""
Computes and returns an element-wise dropout mask for a given tensor, where
each element in the mask is dropped out with probability dropout_probability.
Note that the mask is NOT applied to the tensor - the tensor is passed to retain
the correct CUDA tensor type for the mask.
Parameters
----------
dropout_probability : float, required.
Probability of dropping a dimension of the input.
tensor_for_masking : torch.Tensor, required.
Returns
-------
A torch.FloatTensor consisting of the binary mask scaled by 1/ (1 - dropout_probability).
This scaling ensures expected values and variances of the output of applying this mask
and the original tensor are the same.
"""
binary_mask = tensor_for_masking.new_tensor(torch.rand(tensor_for_masking.size()) > dropout_probability)
# Scale mask by 1/keep_prob to preserve output statistics.
dropout_mask = binary_mask.float().div(1.0 - dropout_probability)
return dropout_mask
def masked_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
"""
``torch.nn.functional.softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular softmax.
``vector`` can have an arbitrary number of dimensions; the only requirement is that ``mask`` is
broadcastable to ``vector's`` shape. If ``mask`` has fewer dimensions than ``vector``, we will
unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,
do it yourself before passing the mask into this function.
In the case that the input vector is completely masked, this function returns an array
of ``0.0``. This behavior may cause ``NaN`` if this is used as the last layer of a model
that uses categorical cross-entropy loss.
"""
if mask is None:
result = torch.nn.functional.softmax(vector, dim=dim)
else:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
# To limit numerical errors from large vector elements outside the mask, we zero these out.
result = torch.nn.functional.softmax(vector * mask, dim=dim)
result = result * mask
result = result / (result.sum(dim=dim, keepdim=True) + 1e-13)
return result
def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
"""
``torch.nn.functional.log_softmax(vector)`` does not work if some elements of ``vector`` should be
masked. This performs a log_softmax on just the non-masked portions of ``vector``. Passing
``None`` in for the mask is also acceptable; you'll just get a regular log_softmax.
``vector`` can have an arbitrary number of dimensions; the only requirement is that ``mask`` is
broadcastable to ``vector's`` shape. If ``mask`` has fewer dimensions than ``vector``, we will
unsqueeze on dimension 1 until they match. If you need a different unsqueezing of your mask,
do it yourself before passing the mask into this function.
In the case that the input vector is completely masked, the return value of this function is
arbitrary, but not ``nan``. You should be masking the result of whatever computation comes out
of this in that case, anyway, so the specific values returned shouldn't matter. Also, the way
that we deal with this case relies on having single-precision floats; mixing half-precision
floats with fully-masked vectors will likely give you ``nans``.
If your logits are all extremely negative (i.e., the max value in your logit vector is -50 or
lower), the way we handle masking here could mess you up. But if you've got logit values that
extreme, you've got bigger problems than this.
"""
if mask is not None:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
# vector + mask.log() is an easy way to zero out masked elements in logspace, but it
# results in nans when the whole vector is masked. We need a very small value instead of a
# zero in the mask for these cases. log(1 + 1e-45) is still basically 0, so we can safely
# just add 1e-45 before calling mask.log(). We use 1e-45 because 1e-46 is so small it
# becomes 0 - this is just the smallest value we can actually use.
vector = vector + (mask + 1e-45).log()
return torch.nn.functional.log_softmax(vector, dim=dim)
def masked_max(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
min_val: float = -1e7) -> torch.Tensor:
"""
To calculate max along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor``
The vector to calculate max, assume unmasked parts are already zeros
mask : ``torch.Tensor``
The mask of the vector. It must be broadcastable with vector.
dim : ``int``
The dimension to calculate max
keepdim : ``bool``
Whether to keep dimension
min_val : ``float``
The minimal value for paddings
Returns
-------
A ``torch.Tensor`` of including the maximum values.
"""
one_minus_mask = (1.0 - mask).byte()
replaced_vector = vector.masked_fill(one_minus_mask, min_val)
max_value, _ = replaced_vector.max(dim=dim, keepdim=keepdim)
return max_value
def masked_mean(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
eps: float = 1e-8) -> torch.Tensor:
"""
To calculate mean along certain dimensions on masked values
Parameters
----------
vector : ``torch.Tensor``
The vector to calculate mean.
mask : ``torch.Tensor``
The mask of the vector. It must be broadcastable with vector.
dim : ``int``
The dimension to calculate mean
keepdim : ``bool``
Whether to keep dimension
eps : ``float``
A small value to avoid zero division problem.
Returns
-------
A ``torch.Tensor`` of including the mean values.
"""
one_minus_mask = (1.0 - mask).byte()
replaced_vector = vector.masked_fill(one_minus_mask, 0.0)
value_sum = torch.sum(replaced_vector, dim=dim, keepdim=keepdim)
value_count = torch.sum(mask.float(), dim=dim, keepdim=keepdim)
return value_sum / value_count.clamp(min=eps)
def viterbi_decode(tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None):
"""
Perform Viterbi decoding in log space over a sequence given a transition matrix
specifying pairwise (transition) potentials between tags and a matrix of shape
(sequence_length, num_tags) specifying unary potentials for possible tags per
timestep.
Parameters
----------
tag_sequence : torch.Tensor, required.
A tensor of shape (sequence_length, num_tags) representing scores for
a set of tags over a given sequence.
transition_matrix : torch.Tensor, required.
A tensor of shape (num_tags, num_tags) representing the binary potentials
for transitioning between a given pair of tags.
tag_observations : Optional[List[int]], optional, (default = None)
A list of length ``sequence_length`` containing the class ids of observed
elements in the sequence, with unobserved elements being set to -1. Note that
it is possible to provide evidence which results in degenerate labellings if
the sequences of tags you provide as evidence cannot transition between each
other, or those transitions are extremely unlikely. In this situation we log a
warning, but the responsibility for providing self-consistent evidence ultimately
lies with the user.
Returns
-------
viterbi_path : List[int]
The tag indices of the maximum likelihood tag sequence.
viterbi_score : torch.Tensor
The score of the viterbi path.
"""
sequence_length, num_tags = list(tag_sequence.size())
if tag_observations:
if len(tag_observations) != sequence_length:
raise ConfigurationError("Observations were provided, but they were not the same length "
"as the sequence. Found sequence of length: {} and evidence: {}"
.format(sequence_length, tag_observations))
else:
tag_observations = [-1 for _ in range(sequence_length)]
path_scores = []
path_indices = []
if tag_observations[0] != -1:
one_hot = torch.zeros(num_tags)
one_hot[tag_observations[0]] = 100000.
path_scores.append(one_hot)
else:
path_scores.append(tag_sequence[0, :])
# Evaluate the scores for all possible paths.
for timestep in range(1, sequence_length):
# Add pairwise potentials to current scores.
summed_potentials = path_scores[timestep - 1].unsqueeze(-1) + transition_matrix
scores, paths = torch.max(summed_potentials, 0)
# If we have an observation for this timestep, use it
# instead of the distribution over tags.
observation = tag_observations[timestep]
# Warn the user if they have passed
# invalid/extremely unlikely evidence.
if tag_observations[timestep - 1] != -1:
if transition_matrix[tag_observations[timestep - 1], observation] < -10000:
logger.warning("The pairwise potential between tags you have passed as "
"observations is extremely unlikely. Double check your evidence "
"or transition potentials!")
if observation != -1:
one_hot = torch.zeros(num_tags)
one_hot[observation] = 100000.
path_scores.append(one_hot)
else:
path_scores.append(tag_sequence[timestep, :] + scores.squeeze())
path_indices.append(paths.squeeze())
# Construct the most likely sequence backwards.
viterbi_score, best_path = torch.max(path_scores[-1], 0)
viterbi_path = [int(best_path.numpy())]
for backward_timestep in reversed(path_indices):
viterbi_path.append(int(backward_timestep[viterbi_path[-1]]))
# Reverse the backward path.
viterbi_path.reverse()
return viterbi_path, viterbi_score
def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.LongTensor:
"""
Takes the dictionary of tensors produced by a ``TextField`` and returns a mask
with 0 where the tokens are padding, and 1 otherwise. We also handle ``TextFields``
wrapped by an arbitrary number of ``ListFields``, where the number of wrapping ``ListFields``
is given by ``num_wrapping_dims``.
If ``num_wrapping_dims == 0``, the returned mask has shape ``(batch_size, num_tokens)``.
If ``num_wrapping_dims > 0`` then the returned mask has ``num_wrapping_dims`` extra
dimensions, so the shape will be ``(batch_size, ..., num_tokens)``.
There could be several entries in the tensor dictionary with different shapes (e.g., one for
word ids, one for character ids). In order to get a token mask, we use the tensor in
the dictionary with the lowest number of dimensions. After subtracting ``num_wrapping_dims``,
if this tensor has two dimensions we assume it has shape ``(batch_size, ..., num_tokens)``,
and use it for the mask. If instead it has three dimensions, we assume it has shape
``(batch_size, ..., num_tokens, num_features)``, and sum over the last dimension to produce
the mask. Most frequently this will be a character id tensor, but it could also be a
featurized representation of each token, etc.
If the input ``text_field_tensors`` contains the "mask" key, this is returned instead of inferring the mask.
TODO(joelgrus): can we change this?
NOTE: Our functions for generating masks create torch.LongTensors, because using
torch.ByteTensors makes it easy to run into overflow errors
when doing mask manipulation, such as summing to get the lengths of sequences - see below.
>>> mask = torch.ones([260]).byte()
>>> mask.sum() # equals 260.
>>> var_mask = torch.autograd.V(mask)
>>> var_mask.sum() # equals 4, due to 8 bit precision - the sum overflows.
"""
if "mask" in text_field_tensors:
return text_field_tensors["mask"]
tensor_dims = [(tensor.dim(), tensor) for tensor in text_field_tensors.values()]
tensor_dims.sort(key=lambda x: x[0])
smallest_dim = tensor_dims[0][0] - num_wrapping_dims
if smallest_dim == 2:
token_tensor = tensor_dims[0][1]
return (token_tensor != 0).long()
elif smallest_dim == 3:
character_tensor = tensor_dims[0][1]
return ((character_tensor > 0).long().sum(dim=-1) > 0).long()
else:
raise ValueError("Expected a tensor with dimension 2 or 3, found {}".format(smallest_dim))
def last_dim_softmax(tensor: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Takes a tensor with 3 or more dimensions and does a masked softmax over the last dimension. We
assume the tensor has shape ``(batch_size, ..., sequence_length)`` and that the mask (if given)
has shape ``(batch_size, sequence_length)``.
.. deprecated:: 0.6.1
``last_dim_softmax`` was deprecated in favor of just using ``masked_softmax`` in version
0.6.1. It will be removed in version 0.8.
"""
warnings.warn("``last_dim_softmax`` was deprecated in favor of just using ``masked_softmax`` "
"in version 0.6.1. It will be removed in version 0.8.", DeprecationWarning)
return masked_softmax(tensor, mask, dim=-1)
def last_dim_log_softmax(tensor: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Takes a tensor with 3 or more dimensions and does a masked log softmax over the last dimension.
We assume the tensor has shape ``(batch_size, ..., sequence_length)`` and that the mask (if given)
has shape ``(batch_size, sequence_length)``.
.. deprecated:: 0.6.1
``last_dim_log_softmax`` was deprecated in favor of just using ``masked_log_softmax`` in
version 0.6.1. It will be removed in version 0.8.
"""
warnings.warn("``last_dim_log_softmax`` was deprecated in favor of just using "
"``masked_log_softmax`` in version 0.6.1. It will be removed in version 0.8.",
DeprecationWarning)
return masked_log_softmax(tensor, mask, dim=-1)
def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:
"""
Takes a matrix of vectors and a set of weights over the rows in the matrix (which we call an
"attention" vector), and returns a weighted sum of the rows in the matrix. This is the typical
computation performed after an attention mechanism.
Note that while we call this a "matrix" of vectors and an attention "vector", we also handle
higher-order tensors. We always sum over the second-to-last dimension of the "matrix", and we
assume that all dimensions in the "matrix" prior to the last dimension are matched in the
"vector". Non-matched dimensions in the "vector" must be `directly after the batch dimension`.
For example, say I have a "matrix" with dimensions ``(batch_size, num_queries, num_words,
embedding_dim)``. The attention "vector" then must have at least those dimensions, and could
have more. Both:
- ``(batch_size, num_queries, num_words)`` (distribution over words for each query)
- ``(batch_size, num_documents, num_queries, num_words)`` (distribution over words in a
query for each document)
are valid input "vectors", producing tensors of shape:
``(batch_size, num_queries, embedding_dim)`` and
``(batch_size, num_documents, num_queries, embedding_dim)`` respectively.
"""
# We'll special-case a few settings here, where there are efficient (but poorly-named)
# operations in pytorch that already do the computation we need.
if attention.dim() == 2 and matrix.dim() == 3:
return attention.unsqueeze(1).bmm(matrix).squeeze(1)
if attention.dim() == 3 and matrix.dim() == 3:
return attention.bmm(matrix)
if matrix.dim() - 1 < attention.dim():
expanded_size = list(matrix.size())
for i in range(attention.dim() - matrix.dim() + 1):
matrix = matrix.unsqueeze(1)
expanded_size.insert(i + 1, attention.size(i + 1))
matrix = matrix.expand(*expanded_size)
intermediate = attention.unsqueeze(-1).expand_as(matrix) * matrix
return intermediate.sum(dim=-2)
def sequence_cross_entropy_with_logits(logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: torch.FloatTensor,
batch_average: bool = None,
average: str = "batch",
label_smoothing: float = None) -> torch.FloatTensor:
"""
Computes the cross entropy loss of a sequence, weighted with respect to
some user provided weights. Note that the weighting here is not the same as
in the :func:`torch.nn.CrossEntropyLoss()` criterion, which is weighting
classes; here we are weighting the loss contribution from particular elements
in the sequence. This allows loss computations for models which use padding.
Parameters
----------
logits : ``torch.FloatTensor``, required.
A ``torch.FloatTensor`` of size (batch_size, sequence_length, num_classes)
which contains the unnormalized probability for each class.
targets : ``torch.LongTensor``, required.
A ``torch.LongTensor`` of size (batch, sequence_length) which contains the
index of the true class for each corresponding step.
weights : ``torch.FloatTensor``, required.
A ``torch.FloatTensor`` of size (batch, sequence_length)
batch_average : bool, optional, (default = None).
A bool indicating whether the loss should be averaged across the batch,
or returned as a vector of losses per batch element.
.. deprecated:: 0.6.2
``batch_average`` was deprecated and replaced with
the more general ``average`` in version 0.6.2. It will be removed
in version 0.8.
average: str, optional (default = "batch")
If "batch", average the loss across the batches. If "token", average
the loss across each item in the input. If ``None``, return a vector
of losses per batch element.
label_smoothing : ``float``, optional (default = None)
Whether or not to apply label smoothing to the cross-entropy loss.
For example, with a label smoothing value of 0.2, a 4 class classifcation
target would look like ``[0.05, 0.05, 0.85, 0.05]`` if the 3rd class was
the correct label.
Returns
-------
A torch.FloatTensor representing the cross entropy loss.
If ``average=="batch"`` or ``average=="token"``, the returned loss is a scalar.
If ``average is None``, the returned loss is a vector of shape (batch_size,).
"""
if batch_average is not None:
# Maintain old behavior
if batch_average:
warnings.warn("batch_average=True was deprecated and replaced "
"with average='batch' in version 0.6.2. It will be "
"removed in version 0.8.", DeprecationWarning)
average = "batch"
else:
warnings.warn("batch_average=False was deprecated and replaced "
"with average=None in version 0.6.2. It will be "
"removed in version 0.8.", DeprecationWarning)
average = None
if average not in {None, "token", "batch"}:
raise ValueError("Got average f{average}, expected one of "
"None, 'token', or 'batch'")
# shape : (batch * sequence_length, num_classes)
logits_flat = logits.view(-1, logits.size(-1))
# shape : (batch * sequence_length, num_classes)
log_probs_flat = torch.nn.functional.log_softmax(logits_flat, dim=-1)
# shape : (batch * max_len, 1)
targets_flat = targets.view(-1, 1).long()
if label_smoothing is not None and label_smoothing > 0.0:
num_classes = logits.size(-1)
smoothing_value = label_smoothing / num_classes
# Fill all the correct indices with 1 - smoothing value.
one_hot_targets = torch.zeros_like(log_probs_flat).scatter_(-1, targets_flat, 1.0 - label_smoothing)
smoothed_targets = one_hot_targets + smoothing_value
negative_log_likelihood_flat = - log_probs_flat * smoothed_targets
negative_log_likelihood_flat = negative_log_likelihood_flat.sum(-1, keepdim=True)
else:
# Contribution to the negative log likelihood only comes from the exact indices
# of the targets, as the target distributions are one-hot. Here we use torch.gather
# to extract the indices of the num_classes dimension which contribute to the loss.
# shape : (batch * sequence_length, 1)
negative_log_likelihood_flat = - torch.gather(log_probs_flat, dim=1, index=targets_flat)
# shape : (batch, sequence_length)
negative_log_likelihood = negative_log_likelihood_flat.view(*targets.size())
# shape : (batch, sequence_length)
negative_log_likelihood = negative_log_likelihood * weights.float()
if average == "batch":
# shape : (batch_size,)
per_batch_loss = negative_log_likelihood.sum(1) / (weights.sum(1).float() + 1e-13)
num_non_empty_sequences = ((weights.sum(1) > 0).float().sum() + 1e-13)
return per_batch_loss.sum() / num_non_empty_sequences
elif average == "token":
return negative_log_likelihood.sum() / (weights.sum().float() + 1e-13)
else:
# shape : (batch_size,)
per_batch_loss = negative_log_likelihood.sum(1) / (weights.sum(1).float() + 1e-13)
return per_batch_loss
def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor:
"""
Replaces all masked values in ``tensor`` with ``replace_with``. ``mask`` must be broadcastable
to the same shape as ``tensor``. We require that ``tensor.dim() == mask.dim()``, as otherwise we
won't know which dimensions of the mask to unsqueeze.
This just does ``tensor.masked_fill()``, except the pytorch method fills in things with a mask
value of 1, where we want the opposite. You can do this in your own code with
``tensor.masked_fill((1 - mask).byte(), replace_with)``.
"""
if tensor.dim() != mask.dim():
raise ConfigurationError("tensor.dim() (%d) != mask.dim() (%d)" % (tensor.dim(), mask.dim()))
return tensor.masked_fill((1 - mask).byte(), replace_with)
def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
"""
A check for tensor equality (by value). We make sure that the tensors have the same shape,
then check all of the entries in the tensor for equality. We additionally allow the input
tensors to be lists or dictionaries, where we then do the above check on every position in the
list / item in the dictionary. If we find objects that aren't tensors as we're doing that, we
just defer to their equality check.
This is kind of a catch-all method that's designed to make implementing ``__eq__`` methods
easier, in a way that's really only intended to be useful for tests.
"""
# pylint: disable=too-many-return-statements
if isinstance(tensor1, (list, tuple)):
if not isinstance(tensor2, (list, tuple)) or len(tensor1) != len(tensor2):
return False
return all([tensors_equal(t1, t2, tolerance) for t1, t2 in zip(tensor1, tensor2)])
elif isinstance(tensor1, dict):
if not isinstance(tensor2, dict):
return False
if tensor1.keys() != tensor2.keys():
return False
return all([tensors_equal(tensor1[key], tensor2[key], tolerance) for key in tensor1])
elif isinstance(tensor1, torch.Tensor):
if not isinstance(tensor2, torch.Tensor):
return False
if tensor1.size() != tensor2.size():
return False
return ((tensor1 - tensor2).abs().float() < tolerance).all()
else:
try:
return tensor1 == tensor2
except RuntimeError:
print(type(tensor1), type(tensor2))
raise
def device_mapping(cuda_device: int):
"""
In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
you have to supply a `map_location` function. Call this with
the desired `cuda_device` to get the function that `torch.load()` needs.
"""
def inner_device_mapping(storage: torch.Storage, location) -> torch.Storage: # pylint: disable=unused-argument
if cuda_device >= 0:
return storage.cuda(cuda_device)
else:
return storage
return inner_device_mapping
def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
"""
Combines a list of tensors using element-wise operations and concatenation, specified by a
``combination`` string. The string refers to (1-indexed) positions in the input tensor list,
and looks like ``"1,2,1+2,3-1"``.
We allow the following kinds of combinations: ``x``, ``x*y``, ``x+y``, ``x-y``, and ``x/y``,
where ``x`` and ``y`` are positive integers less than or equal to ``len(tensors)``. Each of
the binary operations is performed elementwise. You can give as many combinations as you want
in the ``combination`` string. For example, for the input string ``"1,2,1*2"``, the result
would be ``[1;2;1*2]``, as you would expect, where ``[;]`` is concatenation along the last
dimension.
If you have a fixed, known way to combine tensors that you use in a model, you should probably
just use something like ``torch.cat([x_tensor, y_tensor, x_tensor * y_tensor])``. This
function adds some complexity that is only necessary if you want the specific combination used
to be `configurable`.
If you want to do any element-wise operations, the tensors involved in each element-wise
operation must have the same shape.
This function also accepts ``x`` and ``y`` in place of ``1`` and ``2`` in the combination
string.
"""
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
to_concatenate = [_get_combination(piece, tensors) for piece in combination.split(',')]
return torch.cat(to_concatenate, dim=-1)
def _rindex(sequence: Sequence[T], obj: T) -> int:
"""
Return zero-based index in the sequence of the last item whose value is equal to obj. Raises a
ValueError if there is no such item.
Parameters
----------
sequence : ``Sequence[T]``
obj : ``T``
Returns
-------
zero-based index associated to the position of the last item equal to obj
"""
for i in range(len(sequence) - 1, -1, -1):
if sequence[i] == obj:
return i
raise ValueError(f"Unable to find {obj} in sequence {sequence}.")
def _get_combination(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
if combination.isdigit():
index = int(combination) - 1
return tensors[index]
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor = _get_combination(combination[0], tensors)
second_tensor = _get_combination(combination[2], tensors)
operation = combination[1]
if operation == '*':
return first_tensor * second_tensor
elif operation == '/':
return first_tensor / second_tensor
elif operation == '+':
return first_tensor + second_tensor
elif operation == '-':
return first_tensor - second_tensor
else:
raise ConfigurationError("Invalid operation: " + operation)
def combine_tensors_and_multiply(combination: str,
tensors: List[torch.Tensor],
weights: torch.nn.Parameter) -> torch.Tensor:
"""
Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining.
This is a separate function from ``combine_tensors`` because we try to avoid instantiating
large intermediate tensors during the combination, which is possible because we know that we're
going to be multiplying by a weight vector in the end.
Parameters
----------
combination : ``str``
Same as in :func:`combine_tensors`
tensors : ``List[torch.Tensor]``
A list of tensors to combine, where the integers in the ``combination`` are (1-indexed)
positions in this list of tensors. These tensors are all expected to have either three or
four dimensions, with the final dimension being an embedding. If there are four
dimensions, one of them must have length 1.
weights : ``torch.nn.Parameter``
A vector of weights to use for the combinations. This should have shape (combined_dim,),
as calculated by :func:`get_combined_dim`.
"""
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
pieces = combination.split(',')
tensor_dims = [tensor.size(-1) for tensor in tensors]
combination_dims = [_get_combination_dim(piece, tensor_dims) for piece in pieces]
dims_so_far = 0
to_sum = []
for piece, combination_dim in zip(pieces, combination_dims):
weight = weights[dims_so_far:(dims_so_far + combination_dim)]
dims_so_far += combination_dim
to_sum.append(_get_combination_and_multiply(piece, tensors, weight))
result = to_sum[0]
for result_piece in to_sum[1:]:
result = result + result_piece
return result
def _get_combination_and_multiply(combination: str,
tensors: List[torch.Tensor],
weight: torch.nn.Parameter) -> torch.Tensor:
if combination.isdigit():
index = int(combination) - 1
return torch.matmul(tensors[index], weight)
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor = _get_combination(combination[0], tensors)
second_tensor = _get_combination(combination[2], tensors)
operation = combination[1]
if operation == '*':
if first_tensor.dim() > 4 or second_tensor.dim() > 4:
raise ValueError("Tensors with dim > 4 not currently supported")
if first_tensor.dim() == 4:
expanded_dim = _rindex(first_tensor.size(), 1)
first_tensor = first_tensor.squeeze(expanded_dim)
if second_tensor.dim() == 4:
expanded_dim = _rindex(second_tensor.size(), 1)
second_tensor = second_tensor.squeeze(expanded_dim)
intermediate = first_tensor * weight
return torch.matmul(intermediate, second_tensor.transpose(-1, -2)).squeeze(-1)
elif operation == '/':
if first_tensor.dim() > 4 or second_tensor.dim() > 4:
raise ValueError("Tensors with dim > 4 not currently supported")
if first_tensor.dim() == 4:
expanded_dim = _rindex(first_tensor.size(), 1)
first_tensor = first_tensor.squeeze(expanded_dim)
if second_tensor.dim() == 4:
expanded_dim = _rindex(second_tensor.size(), 1)
second_tensor = second_tensor.squeeze(expanded_dim)
intermediate = first_tensor * weight
return torch.matmul(intermediate, second_tensor.pow(-1).transpose(-1, -2)).squeeze(-1)
elif operation == '+':
return torch.matmul(first_tensor, weight) + torch.matmul(second_tensor, weight)
elif operation == '-':
return torch.matmul(first_tensor, weight) - torch.matmul(second_tensor, weight)
else:
raise ConfigurationError("Invalid operation: " + operation)
def get_combined_dim(combination: str, tensor_dims: List[int]) -> int:
"""
For use with :func:`combine_tensors`. This function computes the resultant dimension when
calling ``combine_tensors(combination, tensors)``, when the tensor dimension is known. This is
necessary for knowing the sizes of weight matrices when building models that use
``combine_tensors``.
Parameters
----------
combination : ``str``
A comma-separated list of combination pieces, like ``"1,2,1*2"``, specified identically to
``combination`` in :func:`combine_tensors`.
tensor_dims : ``List[int]``
A list of tensor dimensions, where each dimension is from the `last axis` of the tensors
that will be input to :func:`combine_tensors`.
"""
if len(tensor_dims) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
return sum([_get_combination_dim(piece, tensor_dims) for piece in combination.split(',')])
def _get_combination_dim(combination: str, tensor_dims: List[int]) -> int:
if combination.isdigit():
index = int(combination) - 1
return tensor_dims[index]
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor_dim = _get_combination_dim(combination[0], tensor_dims)
second_tensor_dim = _get_combination_dim(combination[2], tensor_dims)
operation = combination[1]
if first_tensor_dim != second_tensor_dim:
raise ConfigurationError("Tensor dims must match for operation \"{}\"".format(operation))
return first_tensor_dim
def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
"""
A numerically stable computation of logsumexp. This is mathematically equivalent to
`tensor.exp().sum(dim, keep=keepdim).log()`. This function is typically used for summing log
probabilities.
Parameters
----------
tensor : torch.FloatTensor, required.
A tensor of arbitrary size.
dim : int, optional (default = -1)
The dimension of the tensor to apply the logsumexp to.
keepdim: bool, optional (default = False)
Whether to retain a dimension of size one at the dimension we reduce over.
"""
max_score, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - max_score
else:
stable_vec = tensor - max_score.unsqueeze(dim)
return max_score + (stable_vec.exp().sum(dim, keepdim=keepdim)).log()
def get_device_of(tensor: torch.Tensor) -> int:
"""
Returns the device of the tensor.
"""
if not tensor.is_cuda:
return -1
else:
return tensor.get_device()
def flatten_and_batch_shift_indices(indices: torch.Tensor,
sequence_length: int) -> torch.Tensor:
"""
This is a subroutine for :func:`~batched_index_select`. The given ``indices`` of size
``(batch_size, d_1, ..., d_n)`` indexes into dimension 2 of a target tensor, which has size
``(batch_size, sequence_length, embedding_size)``. This function returns a vector that
correctly indexes into the flattened target. The sequence length of the target must be
provided to compute the appropriate offsets.
.. code-block:: python
indices = torch.ones([2,3], dtype=torch.long)
# Sequence length of the target tensor.
sequence_length = 10
shifted_indices = flatten_and_batch_shift_indices(indices, sequence_length)
# Indices into the second element in the batch are correctly shifted
# to take into account that the target tensor will be flattened before
# the indices are applied.
assert shifted_indices == [1, 1, 1, 11, 11, 11]
Parameters
----------
indices : ``torch.LongTensor``, required.
sequence_length : ``int``, required.
The length of the sequence the indices index into.
This must be the second dimension of the tensor.
Returns
-------
offset_indices : ``torch.LongTensor``
"""
# Shape: (batch_size)
offsets = get_range_vector(indices.size(0), get_device_of(indices)) * sequence_length
for _ in range(len(indices.size()) - 1):
offsets = offsets.unsqueeze(1)
# Shape: (batch_size, d_1, ..., d_n)
offset_indices = indices + offsets
# Shape: (batch_size * d_1 * ... * d_n)
offset_indices = offset_indices.view(-1)
return offset_indices
def batched_index_select(target: torch.Tensor,
indices: torch.LongTensor,
flattened_indices: Optional[torch.LongTensor] = None) -> torch.Tensor:
"""
The given ``indices`` of size ``(batch_size, d_1, ..., d_n)`` indexes into the sequence
dimension (dimension 2) of the target, which has size ``(batch_size, sequence_length,
embedding_size)``.
This function returns selected values in the target with respect to the provided indices, which
have size ``(batch_size, d_1, ..., d_n, embedding_size)``. This can use the optionally
precomputed :func:`~flattened_indices` with size ``(batch_size * d_1 * ... * d_n)`` if given.
An example use case of this function is looking up the start and end indices of spans in a
sequence tensor. This is used in the
:class:`~allennlp.models.coreference_resolution.CoreferenceResolver`. Model to select
contextual word representations corresponding to the start and end indices of mentions. The key
reason this can't be done with basic torch functions is that we want to be able to use look-up
tensors with an arbitrary number of dimensions (for example, in the coref model, we don't know
a-priori how many spans we are looking up).
Parameters
----------
target : ``torch.Tensor``, required.
A 3 dimensional tensor of shape (batch_size, sequence_length, embedding_size).
This is the tensor to be indexed.
indices : ``torch.LongTensor``
A tensor of shape (batch_size, ...), where each element is an index into the
``sequence_length`` dimension of the ``target`` tensor.
flattened_indices : Optional[torch.Tensor], optional (default = None)
An optional tensor representing the result of calling :func:~`flatten_and_batch_shift_indices`
on ``indices``. This is helpful in the case that the indices can be flattened once and
cached for many batch lookups.
Returns
-------
selected_targets : ``torch.Tensor``
A tensor with shape [indices.size(), target.size(-1)] representing the embedded indices
extracted from the batch flattened target tensor.
"""
if flattened_indices is None:
# Shape: (batch_size * d_1 * ... * d_n)
flattened_indices = flatten_and_batch_shift_indices(indices, target.size(1))
# Shape: (batch_size * sequence_length, embedding_size)
flattened_target = target.view(-1, target.size(-1))
# Shape: (batch_size * d_1 * ... * d_n, embedding_size)
flattened_selected = flattened_target.index_select(0, flattened_indices)
selected_shape = list(indices.size()) + [target.size(-1)]
# Shape: (batch_size, d_1, ..., d_n, embedding_size)
selected_targets = flattened_selected.view(*selected_shape)
return selected_targets
def flattened_index_select(target: torch.Tensor,
indices: torch.LongTensor) -> torch.Tensor:
"""
The given ``indices`` of size ``(set_size, subset_size)`` specifies subsets of the ``target``
that each of the set_size rows should select. The `target` has size
``(batch_size, sequence_length, embedding_size)``, and the resulting selected tensor has size
``(batch_size, set_size, subset_size, embedding_size)``.
Parameters
----------
target : ``torch.Tensor``, required.
A Tensor of shape (batch_size, sequence_length, embedding_size).
indices : ``torch.LongTensor``, required.
A LongTensor of shape (set_size, subset_size). All indices must be < sequence_length
as this tensor is an index into the sequence_length dimension of the target.
Returns
-------
selected : ``torch.Tensor``, required.
A Tensor of shape (batch_size, set_size, subset_size, embedding_size).
"""
if indices.dim() != 2:
raise ConfigurationError("Indices passed to flattened_index_select had shape {} but "
"only 2 dimensional inputs are supported.".format(indices.size()))
# Shape: (batch_size, set_size * subset_size, embedding_size)
flattened_selected = target.index_select(1, indices.view(-1))
# Shape: (batch_size, set_size, subset_size, embedding_size)
selected = flattened_selected.view(target.size(0), indices.size(0), indices.size(1), -1)
return selected
def get_range_vector(size: int, device: int) -> torch.Tensor:
"""
Returns a range vector with the desired size, starting at 0. The CUDA implementation
is meant to avoid copy data from CPU to GPU.
"""
if device > -1:
return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1
else:
return torch.arange(0, size, dtype=torch.long)
def bucket_values(distances: torch.Tensor,
num_identity_buckets: int = 4,
num_total_buckets: int = 10) -> torch.Tensor:
"""
Places the given values (designed for distances) into ``num_total_buckets``semi-logscale
buckets, with ``num_identity_buckets`` of these capturing single values.
The default settings will bucket values into the following buckets:
[0, 1, 2, 3, 4, 5-7, 8-15, 16-31, 32-63, 64+].
Parameters
----------
distances : ``torch.Tensor``, required.
A Tensor of any size, to be bucketed.
num_identity_buckets: int, optional (default = 4).
The number of identity buckets (those only holding a single value).
num_total_buckets : int, (default = 10)
The total number of buckets to bucket values into.
Returns
-------
A tensor of the same shape as the input, containing the indices of the buckets
the values were placed in.
"""
# Chunk the values into semi-logscale buckets using .floor().
# This is a semi-logscale bucketing because we divide by log(2) after taking the log.
# We do this to make the buckets more granular in the initial range, where we expect
# most values to fall. We then add (num_identity_buckets - 1) because we want these indices
# to start _after_ the fixed number of buckets which we specified would only hold single values.
logspace_index = (distances.float().log() / math.log(2)).floor().long() + (num_identity_buckets - 1)
# create a mask for values which will go into single number buckets (i.e not a range).
use_identity_mask = (distances <= num_identity_buckets).long()
use_buckets_mask = 1 + (-1 * use_identity_mask)
# Use the original values if they are less than num_identity_buckets, otherwise
# use the logspace indices.
combined_index = use_identity_mask * distances + use_buckets_mask * logspace_index
# Clamp to put anything > num_total_buckets into the final bucket.
return combined_index.clamp(0, num_total_buckets - 1)
def add_sentence_boundary_token_ids(tensor: torch.Tensor,
mask: torch.Tensor,
sentence_begin_token: Any,
sentence_end_token: Any) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Add begin/end of sentence tokens to the batch of sentences.
Given a batch of sentences with size ``(batch_size, timesteps)`` or
``(batch_size, timesteps, dim)`` this returns a tensor of shape
``(batch_size, timesteps + 2)`` or ``(batch_size, timesteps + 2, dim)`` respectively.
Returns both the new tensor and updated mask.
Parameters
----------
tensor : ``torch.Tensor``
A tensor of shape ``(batch_size, timesteps)`` or ``(batch_size, timesteps, dim)``
mask : ``torch.Tensor``
A tensor of shape ``(batch_size, timesteps)``
sentence_begin_token: Any (anything that can be broadcast in torch for assignment)
For 2D input, a scalar with the <S> id. For 3D input, a tensor with length dim.
sentence_end_token: Any (anything that can be broadcast in torch for assignment)
For 2D input, a scalar with the </S> id. For 3D input, a tensor with length dim.
Returns
-------
tensor_with_boundary_tokens : ``torch.Tensor``
The tensor with the appended and prepended boundary tokens. If the input was 2D,
it has shape (batch_size, timesteps + 2) and if the input was 3D, it has shape
(batch_size, timesteps + 2, dim).
new_mask : ``torch.Tensor``
The new mask for the tensor, taking into account the appended tokens
marking the beginning and end of the sentence.
"""
# TODO: matthewp, profile this transfer
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = list(tensor.data.shape)
new_shape = list(tensor_shape)
new_shape[1] = tensor_shape[1] + 2
tensor_with_boundary_tokens = tensor.new_zeros(*new_shape)
if len(tensor_shape) == 2:
tensor_with_boundary_tokens[:, 1:-1] = tensor
tensor_with_boundary_tokens[:, 0] = sentence_begin_token
for i, j in enumerate(sequence_lengths):
tensor_with_boundary_tokens[i, j + 1] = sentence_end_token
new_mask = (tensor_with_boundary_tokens != 0).long()
elif len(tensor_shape) == 3:
tensor_with_boundary_tokens[:, 1:-1, :] = tensor
for i, j in enumerate(sequence_lengths):
tensor_with_boundary_tokens[i, 0, :] = sentence_begin_token
tensor_with_boundary_tokens[i, j + 1, :] = sentence_end_token
new_mask = ((tensor_with_boundary_tokens > 0).long().sum(dim=-1) > 0).long()
else:
raise ValueError("add_sentence_boundary_token_ids only accepts 2D and 3D input")
return tensor_with_boundary_tokens, new_mask
def remove_sentence_boundaries(tensor: torch.Tensor,
mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Remove begin/end of sentence embeddings from the batch of sentences.
Given a batch of sentences with size ``(batch_size, timesteps, dim)``
this returns a tensor of shape ``(batch_size, timesteps - 2, dim)`` after removing
the beginning and end sentence markers. The sentences are assumed to be padded on the right,
with the beginning of each sentence assumed to occur at index 0 (i.e., ``mask[:, 0]`` is assumed
to be 1).
Returns both the new tensor and updated mask.
This function is the inverse of ``add_sentence_boundary_token_ids``.
Parameters
----------
tensor : ``torch.Tensor``
A tensor of shape ``(batch_size, timesteps, dim)``
mask : ``torch.Tensor``
A tensor of shape ``(batch_size, timesteps)``
Returns
-------
tensor_without_boundary_tokens : ``torch.Tensor``
The tensor after removing the boundary tokens of shape ``(batch_size, timesteps - 2, dim)``
new_mask : ``torch.Tensor``
The new mask for the tensor of shape ``(batch_size, timesteps - 2)``.
"""
# TODO: matthewp, profile this transfer
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = list(tensor.data.shape)
new_shape = list(tensor_shape)
new_shape[1] = tensor_shape[1] - 2
tensor_without_boundary_tokens = tensor.new_zeros(*new_shape)
new_mask = tensor.new_zeros((new_shape[0], new_shape[1]), dtype=torch.long)
for i, j in enumerate(sequence_lengths):
if j > 2:
tensor_without_boundary_tokens[i, :(j - 2), :] = tensor[i, 1:(j - 1), :]
new_mask[i, :(j - 2)] = 1
return tensor_without_boundary_tokens, new_mask
def add_positional_features(tensor: torch.Tensor,
min_timescale: float = 1.0,
max_timescale: float = 1.0e4):
# pylint: disable=line-too-long
"""
Implements the frequency-based positional encoding described
in `Attention is all you Need
<https://www.semanticscholar.org/paper/Attention-Is-All-You-Need-Vaswani-Shazeer/0737da0767d77606169cbf4187b83e1ab62f6077>`_ .
Adds sinusoids of different frequencies to a ``Tensor``. A sinusoid of a
different frequency and phase is added to each dimension of the input ``Tensor``.
This allows the attention heads to use absolute and relative positions.
The number of timescales is equal to hidden_dim / 2 within the range
(min_timescale, max_timescale). For each timescale, the two sinusoidal
signals sin(timestep / timescale) and cos(timestep / timescale) are
generated and concatenated along the hidden_dim dimension.
Parameters
----------
tensor : ``torch.Tensor``
a Tensor with shape (batch_size, timesteps, hidden_dim).
min_timescale : ``float``, optional (default = 1.0)
The smallest timescale to use.
max_timescale : ``float``, optional (default = 1.0e4)
The largest timescale to use.
Returns
-------
The input tensor augmented with the sinusoidal frequencies.
"""
_, timesteps, hidden_dim = tensor.size()
timestep_range = get_range_vector(timesteps, get_device_of(tensor)).data.float()
# We're generating both cos and sin frequencies,
# so half for each.
num_timescales = hidden_dim // 2
timescale_range = get_range_vector(num_timescales, get_device_of(tensor)).data.float()
log_timescale_increments = math.log(float(max_timescale) / float(min_timescale)) / float(num_timescales - 1)
inverse_timescales = min_timescale * torch.exp(timescale_range * -log_timescale_increments)
# Broadcasted multiplication - shape (timesteps, num_timescales)
scaled_time = timestep_range.unsqueeze(1) * inverse_timescales.unsqueeze(0)
# shape (timesteps, 2 * num_timescales)
sinusoids = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 1)
if hidden_dim % 2 != 0:
# if the number of dimensions is odd, the cos and sin
# timescales had size (hidden_dim - 1) / 2, so we need
# to add a row of zeros to make up the difference.
sinusoids = torch.cat([sinusoids, sinusoids.new_zeros(timesteps, 1)], 1)
return tensor + sinusoids.unsqueeze(0)
| 46.634871 | 130 | 0.669349 |
from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, Tuple, TypeVar
import logging
import math
import warnings
import torch
from allennlp.common.checks import ConfigurationError
logger = logging.getLogger(__name__)
T = TypeVar('T')
def has_tensor(obj) -> bool:
if isinstance(obj, torch.Tensor):
return True
elif isinstance(obj, dict):
return any(has_tensor(value) for value in obj.values())
elif isinstance(obj, (list, tuple)):
return any(has_tensor(item) for item in obj)
else:
return False
def move_to_device(obj, cuda_device: int):
if cuda_device < 0 or not has_tensor(obj):
return obj
elif isinstance(obj, torch.Tensor):
return obj.cuda(cuda_device)
elif isinstance(obj, dict):
return {key: move_to_device(value, cuda_device) for key, value in obj.items()}
elif isinstance(obj, list):
return [move_to_device(item, cuda_device) for item in obj]
elif isinstance(obj, tuple):
return tuple([move_to_device(item, cuda_device) for item in obj])
else:
return obj
def batch_tensor_dicts(tensor_dicts: List[Dict[str, torch.Tensor]],
remove_trailing_dimension: bool = False) -> Dict[str, torch.Tensor]:
key_to_tensors: Dict[str, List[torch.Tensor]] = defaultdict(list)
for tensor_dict in tensor_dicts:
for key, tensor in tensor_dict.items():
key_to_tensors[key].append(tensor)
batched_tensors = {}
for key, tensor_list in key_to_tensors.items():
batched_tensor = torch.stack(tensor_list)
if remove_trailing_dimension and all(tensor.size(-1) == 1 for tensor in tensor_list):
batched_tensor = batched_tensor.squeeze(-1)
batched_tensors[key] = batched_tensor
return batched_tensors
def get_lengths_from_binary_sequence_mask(mask: torch.Tensor):
return mask.long().sum(-1)
def get_mask_from_sequence_lengths(sequence_lengths: torch.Tensor, max_length: int) -> torch.Tensor:
ones = sequence_lengths.new_ones(sequence_lengths.size(0), max_length)
range_tensor = ones.cumsum(dim=1)
return (sequence_lengths.unsqueeze(1) >= range_tensor).long()
def sort_batch_by_length(tensor: torch.Tensor, sequence_lengths: torch.Tensor):
if not isinstance(tensor, torch.Tensor) or not isinstance(sequence_lengths, torch.Tensor):
raise ConfigurationError("Both the tensor and sequence lengths must be torch.Tensors.")
sorted_sequence_lengths, permutation_index = sequence_lengths.sort(0, descending=True)
sorted_tensor = tensor.index_select(0, permutation_index)
index_range = sequence_lengths.new_tensor(torch.arange(0, len(sequence_lengths)))
_, reverse_mapping = permutation_index.sort(0, descending=False)
restoration_indices = index_range.index_select(0, reverse_mapping)
return sorted_tensor, sorted_sequence_lengths, restoration_indices, permutation_index
def get_final_encoder_states(encoder_outputs: torch.Tensor,
mask: torch.Tensor,
bidirectional: bool = False) -> torch.Tensor:
last_word_indices = mask.sum(1).long() - 1
batch_size, _, encoder_output_dim = encoder_outputs.size()
expanded_indices = last_word_indices.view(-1, 1, 1).expand(batch_size, 1, encoder_output_dim)
final_encoder_output = encoder_outputs.gather(1, expanded_indices)
final_encoder_output = final_encoder_output.squeeze(1)
if bidirectional:
final_forward_output = final_encoder_output[:, :(encoder_output_dim // 2)]
final_backward_output = encoder_outputs[:, 0, (encoder_output_dim // 2):]
final_encoder_output = torch.cat([final_forward_output, final_backward_output], dim=-1)
return final_encoder_output
def get_dropout_mask(dropout_probability: float, tensor_for_masking: torch.Tensor):
binary_mask = tensor_for_masking.new_tensor(torch.rand(tensor_for_masking.size()) > dropout_probability)
dropout_mask = binary_mask.float().div(1.0 - dropout_probability)
return dropout_mask
def masked_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
if mask is None:
result = torch.nn.functional.softmax(vector, dim=dim)
else:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
result = torch.nn.functional.softmax(vector * mask, dim=dim)
result = result * mask
result = result / (result.sum(dim=dim, keepdim=True) + 1e-13)
return result
def masked_log_softmax(vector: torch.Tensor, mask: torch.Tensor, dim: int = -1) -> torch.Tensor:
if mask is not None:
mask = mask.float()
while mask.dim() < vector.dim():
mask = mask.unsqueeze(1)
vector = vector + (mask + 1e-45).log()
return torch.nn.functional.log_softmax(vector, dim=dim)
def masked_max(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
min_val: float = -1e7) -> torch.Tensor:
one_minus_mask = (1.0 - mask).byte()
replaced_vector = vector.masked_fill(one_minus_mask, min_val)
max_value, _ = replaced_vector.max(dim=dim, keepdim=keepdim)
return max_value
def masked_mean(vector: torch.Tensor,
mask: torch.Tensor,
dim: int,
keepdim: bool = False,
eps: float = 1e-8) -> torch.Tensor:
one_minus_mask = (1.0 - mask).byte()
replaced_vector = vector.masked_fill(one_minus_mask, 0.0)
value_sum = torch.sum(replaced_vector, dim=dim, keepdim=keepdim)
value_count = torch.sum(mask.float(), dim=dim, keepdim=keepdim)
return value_sum / value_count.clamp(min=eps)
def viterbi_decode(tag_sequence: torch.Tensor,
transition_matrix: torch.Tensor,
tag_observations: Optional[List[int]] = None):
sequence_length, num_tags = list(tag_sequence.size())
if tag_observations:
if len(tag_observations) != sequence_length:
raise ConfigurationError("Observations were provided, but they were not the same length "
"as the sequence. Found sequence of length: {} and evidence: {}"
.format(sequence_length, tag_observations))
else:
tag_observations = [-1 for _ in range(sequence_length)]
path_scores = []
path_indices = []
if tag_observations[0] != -1:
one_hot = torch.zeros(num_tags)
one_hot[tag_observations[0]] = 100000.
path_scores.append(one_hot)
else:
path_scores.append(tag_sequence[0, :])
for timestep in range(1, sequence_length):
summed_potentials = path_scores[timestep - 1].unsqueeze(-1) + transition_matrix
scores, paths = torch.max(summed_potentials, 0)
observation = tag_observations[timestep]
if tag_observations[timestep - 1] != -1:
if transition_matrix[tag_observations[timestep - 1], observation] < -10000:
logger.warning("The pairwise potential between tags you have passed as "
"observations is extremely unlikely. Double check your evidence "
"or transition potentials!")
if observation != -1:
one_hot = torch.zeros(num_tags)
one_hot[observation] = 100000.
path_scores.append(one_hot)
else:
path_scores.append(tag_sequence[timestep, :] + scores.squeeze())
path_indices.append(paths.squeeze())
viterbi_score, best_path = torch.max(path_scores[-1], 0)
viterbi_path = [int(best_path.numpy())]
for backward_timestep in reversed(path_indices):
viterbi_path.append(int(backward_timestep[viterbi_path[-1]]))
viterbi_path.reverse()
return viterbi_path, viterbi_score
def get_text_field_mask(text_field_tensors: Dict[str, torch.Tensor],
num_wrapping_dims: int = 0) -> torch.LongTensor:
if "mask" in text_field_tensors:
return text_field_tensors["mask"]
tensor_dims = [(tensor.dim(), tensor) for tensor in text_field_tensors.values()]
tensor_dims.sort(key=lambda x: x[0])
smallest_dim = tensor_dims[0][0] - num_wrapping_dims
if smallest_dim == 2:
token_tensor = tensor_dims[0][1]
return (token_tensor != 0).long()
elif smallest_dim == 3:
character_tensor = tensor_dims[0][1]
return ((character_tensor > 0).long().sum(dim=-1) > 0).long()
else:
raise ValueError("Expected a tensor with dimension 2 or 3, found {}".format(smallest_dim))
def last_dim_softmax(tensor: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
warnings.warn("``last_dim_softmax`` was deprecated in favor of just using ``masked_softmax`` "
"in version 0.6.1. It will be removed in version 0.8.", DeprecationWarning)
return masked_softmax(tensor, mask, dim=-1)
def last_dim_log_softmax(tensor: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor:
warnings.warn("``last_dim_log_softmax`` was deprecated in favor of just using "
"``masked_log_softmax`` in version 0.6.1. It will be removed in version 0.8.",
DeprecationWarning)
return masked_log_softmax(tensor, mask, dim=-1)
def weighted_sum(matrix: torch.Tensor, attention: torch.Tensor) -> torch.Tensor:
# operations in pytorch that already do the computation we need.
if attention.dim() == 2 and matrix.dim() == 3:
return attention.unsqueeze(1).bmm(matrix).squeeze(1)
if attention.dim() == 3 and matrix.dim() == 3:
return attention.bmm(matrix)
if matrix.dim() - 1 < attention.dim():
expanded_size = list(matrix.size())
for i in range(attention.dim() - matrix.dim() + 1):
matrix = matrix.unsqueeze(1)
expanded_size.insert(i + 1, attention.size(i + 1))
matrix = matrix.expand(*expanded_size)
intermediate = attention.unsqueeze(-1).expand_as(matrix) * matrix
return intermediate.sum(dim=-2)
def sequence_cross_entropy_with_logits(logits: torch.FloatTensor,
targets: torch.LongTensor,
weights: torch.FloatTensor,
batch_average: bool = None,
average: str = "batch",
label_smoothing: float = None) -> torch.FloatTensor:
if batch_average is not None:
# Maintain old behavior
if batch_average:
warnings.warn("batch_average=True was deprecated and replaced "
"with average='batch' in version 0.6.2. It will be "
"removed in version 0.8.", DeprecationWarning)
average = "batch"
else:
warnings.warn("batch_average=False was deprecated and replaced "
"with average=None in version 0.6.2. It will be "
"removed in version 0.8.", DeprecationWarning)
average = None
if average not in {None, "token", "batch"}:
raise ValueError("Got average f{average}, expected one of "
"None, 'token', or 'batch'")
# shape : (batch * sequence_length, num_classes)
logits_flat = logits.view(-1, logits.size(-1))
# shape : (batch * sequence_length, num_classes)
log_probs_flat = torch.nn.functional.log_softmax(logits_flat, dim=-1)
# shape : (batch * max_len, 1)
targets_flat = targets.view(-1, 1).long()
if label_smoothing is not None and label_smoothing > 0.0:
num_classes = logits.size(-1)
smoothing_value = label_smoothing / num_classes
# Fill all the correct indices with 1 - smoothing value.
one_hot_targets = torch.zeros_like(log_probs_flat).scatter_(-1, targets_flat, 1.0 - label_smoothing)
smoothed_targets = one_hot_targets + smoothing_value
negative_log_likelihood_flat = - log_probs_flat * smoothed_targets
negative_log_likelihood_flat = negative_log_likelihood_flat.sum(-1, keepdim=True)
else:
# Contribution to the negative log likelihood only comes from the exact indices
# of the targets, as the target distributions are one-hot. Here we use torch.gather
# to extract the indices of the num_classes dimension which contribute to the loss.
# shape : (batch * sequence_length, 1)
negative_log_likelihood_flat = - torch.gather(log_probs_flat, dim=1, index=targets_flat)
# shape : (batch, sequence_length)
negative_log_likelihood = negative_log_likelihood_flat.view(*targets.size())
# shape : (batch, sequence_length)
negative_log_likelihood = negative_log_likelihood * weights.float()
if average == "batch":
# shape : (batch_size,)
per_batch_loss = negative_log_likelihood.sum(1) / (weights.sum(1).float() + 1e-13)
num_non_empty_sequences = ((weights.sum(1) > 0).float().sum() + 1e-13)
return per_batch_loss.sum() / num_non_empty_sequences
elif average == "token":
return negative_log_likelihood.sum() / (weights.sum().float() + 1e-13)
else:
# shape : (batch_size,)
per_batch_loss = negative_log_likelihood.sum(1) / (weights.sum(1).float() + 1e-13)
return per_batch_loss
def replace_masked_values(tensor: torch.Tensor, mask: torch.Tensor, replace_with: float) -> torch.Tensor:
if tensor.dim() != mask.dim():
raise ConfigurationError("tensor.dim() (%d) != mask.dim() (%d)" % (tensor.dim(), mask.dim()))
return tensor.masked_fill((1 - mask).byte(), replace_with)
def tensors_equal(tensor1: torch.Tensor, tensor2: torch.Tensor, tolerance: float = 1e-12) -> bool:
# pylint: disable=too-many-return-statements
if isinstance(tensor1, (list, tuple)):
if not isinstance(tensor2, (list, tuple)) or len(tensor1) != len(tensor2):
return False
return all([tensors_equal(t1, t2, tolerance) for t1, t2 in zip(tensor1, tensor2)])
elif isinstance(tensor1, dict):
if not isinstance(tensor2, dict):
return False
if tensor1.keys() != tensor2.keys():
return False
return all([tensors_equal(tensor1[key], tensor2[key], tolerance) for key in tensor1])
elif isinstance(tensor1, torch.Tensor):
if not isinstance(tensor2, torch.Tensor):
return False
if tensor1.size() != tensor2.size():
return False
return ((tensor1 - tensor2).abs().float() < tolerance).all()
else:
try:
return tensor1 == tensor2
except RuntimeError:
print(type(tensor1), type(tensor2))
raise
def device_mapping(cuda_device: int):
def inner_device_mapping(storage: torch.Storage, location) -> torch.Storage: # pylint: disable=unused-argument
if cuda_device >= 0:
return storage.cuda(cuda_device)
else:
return storage
return inner_device_mapping
def combine_tensors(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
to_concatenate = [_get_combination(piece, tensors) for piece in combination.split(',')]
return torch.cat(to_concatenate, dim=-1)
def _rindex(sequence: Sequence[T], obj: T) -> int:
for i in range(len(sequence) - 1, -1, -1):
if sequence[i] == obj:
return i
raise ValueError(f"Unable to find {obj} in sequence {sequence}.")
def _get_combination(combination: str, tensors: List[torch.Tensor]) -> torch.Tensor:
if combination.isdigit():
index = int(combination) - 1
return tensors[index]
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor = _get_combination(combination[0], tensors)
second_tensor = _get_combination(combination[2], tensors)
operation = combination[1]
if operation == '*':
return first_tensor * second_tensor
elif operation == '/':
return first_tensor / second_tensor
elif operation == '+':
return first_tensor + second_tensor
elif operation == '-':
return first_tensor - second_tensor
else:
raise ConfigurationError("Invalid operation: " + operation)
def combine_tensors_and_multiply(combination: str,
tensors: List[torch.Tensor],
weights: torch.nn.Parameter) -> torch.Tensor:
if len(tensors) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
pieces = combination.split(',')
tensor_dims = [tensor.size(-1) for tensor in tensors]
combination_dims = [_get_combination_dim(piece, tensor_dims) for piece in pieces]
dims_so_far = 0
to_sum = []
for piece, combination_dim in zip(pieces, combination_dims):
weight = weights[dims_so_far:(dims_so_far + combination_dim)]
dims_so_far += combination_dim
to_sum.append(_get_combination_and_multiply(piece, tensors, weight))
result = to_sum[0]
for result_piece in to_sum[1:]:
result = result + result_piece
return result
def _get_combination_and_multiply(combination: str,
tensors: List[torch.Tensor],
weight: torch.nn.Parameter) -> torch.Tensor:
if combination.isdigit():
index = int(combination) - 1
return torch.matmul(tensors[index], weight)
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor = _get_combination(combination[0], tensors)
second_tensor = _get_combination(combination[2], tensors)
operation = combination[1]
if operation == '*':
if first_tensor.dim() > 4 or second_tensor.dim() > 4:
raise ValueError("Tensors with dim > 4 not currently supported")
if first_tensor.dim() == 4:
expanded_dim = _rindex(first_tensor.size(), 1)
first_tensor = first_tensor.squeeze(expanded_dim)
if second_tensor.dim() == 4:
expanded_dim = _rindex(second_tensor.size(), 1)
second_tensor = second_tensor.squeeze(expanded_dim)
intermediate = first_tensor * weight
return torch.matmul(intermediate, second_tensor.transpose(-1, -2)).squeeze(-1)
elif operation == '/':
if first_tensor.dim() > 4 or second_tensor.dim() > 4:
raise ValueError("Tensors with dim > 4 not currently supported")
if first_tensor.dim() == 4:
expanded_dim = _rindex(first_tensor.size(), 1)
first_tensor = first_tensor.squeeze(expanded_dim)
if second_tensor.dim() == 4:
expanded_dim = _rindex(second_tensor.size(), 1)
second_tensor = second_tensor.squeeze(expanded_dim)
intermediate = first_tensor * weight
return torch.matmul(intermediate, second_tensor.pow(-1).transpose(-1, -2)).squeeze(-1)
elif operation == '+':
return torch.matmul(first_tensor, weight) + torch.matmul(second_tensor, weight)
elif operation == '-':
return torch.matmul(first_tensor, weight) - torch.matmul(second_tensor, weight)
else:
raise ConfigurationError("Invalid operation: " + operation)
def get_combined_dim(combination: str, tensor_dims: List[int]) -> int:
if len(tensor_dims) > 9:
raise ConfigurationError("Double-digit tensor lists not currently supported")
combination = combination.replace('x', '1').replace('y', '2')
return sum([_get_combination_dim(piece, tensor_dims) for piece in combination.split(',')])
def _get_combination_dim(combination: str, tensor_dims: List[int]) -> int:
if combination.isdigit():
index = int(combination) - 1
return tensor_dims[index]
else:
if len(combination) != 3:
raise ConfigurationError("Invalid combination: " + combination)
first_tensor_dim = _get_combination_dim(combination[0], tensor_dims)
second_tensor_dim = _get_combination_dim(combination[2], tensor_dims)
operation = combination[1]
if first_tensor_dim != second_tensor_dim:
raise ConfigurationError("Tensor dims must match for operation \"{}\"".format(operation))
return first_tensor_dim
def logsumexp(tensor: torch.Tensor,
dim: int = -1,
keepdim: bool = False) -> torch.Tensor:
max_score, _ = tensor.max(dim, keepdim=keepdim)
if keepdim:
stable_vec = tensor - max_score
else:
stable_vec = tensor - max_score.unsqueeze(dim)
return max_score + (stable_vec.exp().sum(dim, keepdim=keepdim)).log()
def get_device_of(tensor: torch.Tensor) -> int:
if not tensor.is_cuda:
return -1
else:
return tensor.get_device()
def flatten_and_batch_shift_indices(indices: torch.Tensor,
sequence_length: int) -> torch.Tensor:
# Shape: (batch_size)
offsets = get_range_vector(indices.size(0), get_device_of(indices)) * sequence_length
for _ in range(len(indices.size()) - 1):
offsets = offsets.unsqueeze(1)
# Shape: (batch_size, d_1, ..., d_n)
offset_indices = indices + offsets
# Shape: (batch_size * d_1 * ... * d_n)
offset_indices = offset_indices.view(-1)
return offset_indices
def batched_index_select(target: torch.Tensor,
indices: torch.LongTensor,
flattened_indices: Optional[torch.LongTensor] = None) -> torch.Tensor:
if flattened_indices is None:
# Shape: (batch_size * d_1 * ... * d_n)
flattened_indices = flatten_and_batch_shift_indices(indices, target.size(1))
# Shape: (batch_size * sequence_length, embedding_size)
flattened_target = target.view(-1, target.size(-1))
# Shape: (batch_size * d_1 * ... * d_n, embedding_size)
flattened_selected = flattened_target.index_select(0, flattened_indices)
selected_shape = list(indices.size()) + [target.size(-1)]
# Shape: (batch_size, d_1, ..., d_n, embedding_size)
selected_targets = flattened_selected.view(*selected_shape)
return selected_targets
def flattened_index_select(target: torch.Tensor,
indices: torch.LongTensor) -> torch.Tensor:
if indices.dim() != 2:
raise ConfigurationError("Indices passed to flattened_index_select had shape {} but "
"only 2 dimensional inputs are supported.".format(indices.size()))
# Shape: (batch_size, set_size * subset_size, embedding_size)
flattened_selected = target.index_select(1, indices.view(-1))
# Shape: (batch_size, set_size, subset_size, embedding_size)
selected = flattened_selected.view(target.size(0), indices.size(0), indices.size(1), -1)
return selected
def get_range_vector(size: int, device: int) -> torch.Tensor:
if device > -1:
return torch.cuda.LongTensor(size, device=device).fill_(1).cumsum(0) - 1
else:
return torch.arange(0, size, dtype=torch.long)
def bucket_values(distances: torch.Tensor,
num_identity_buckets: int = 4,
num_total_buckets: int = 10) -> torch.Tensor:
# Chunk the values into semi-logscale buckets using .floor().
# This is a semi-logscale bucketing because we divide by log(2) after taking the log.
# We do this to make the buckets more granular in the initial range, where we expect
# most values to fall. We then add (num_identity_buckets - 1) because we want these indices
# to start _after_ the fixed number of buckets which we specified would only hold single values.
logspace_index = (distances.float().log() / math.log(2)).floor().long() + (num_identity_buckets - 1)
# create a mask for values which will go into single number buckets (i.e not a range).
use_identity_mask = (distances <= num_identity_buckets).long()
use_buckets_mask = 1 + (-1 * use_identity_mask)
# Use the original values if they are less than num_identity_buckets, otherwise
# use the logspace indices.
combined_index = use_identity_mask * distances + use_buckets_mask * logspace_index
# Clamp to put anything > num_total_buckets into the final bucket.
return combined_index.clamp(0, num_total_buckets - 1)
def add_sentence_boundary_token_ids(tensor: torch.Tensor,
mask: torch.Tensor,
sentence_begin_token: Any,
sentence_end_token: Any) -> Tuple[torch.Tensor, torch.Tensor]:
# TODO: matthewp, profile this transfer
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = list(tensor.data.shape)
new_shape = list(tensor_shape)
new_shape[1] = tensor_shape[1] + 2
tensor_with_boundary_tokens = tensor.new_zeros(*new_shape)
if len(tensor_shape) == 2:
tensor_with_boundary_tokens[:, 1:-1] = tensor
tensor_with_boundary_tokens[:, 0] = sentence_begin_token
for i, j in enumerate(sequence_lengths):
tensor_with_boundary_tokens[i, j + 1] = sentence_end_token
new_mask = (tensor_with_boundary_tokens != 0).long()
elif len(tensor_shape) == 3:
tensor_with_boundary_tokens[:, 1:-1, :] = tensor
for i, j in enumerate(sequence_lengths):
tensor_with_boundary_tokens[i, 0, :] = sentence_begin_token
tensor_with_boundary_tokens[i, j + 1, :] = sentence_end_token
new_mask = ((tensor_with_boundary_tokens > 0).long().sum(dim=-1) > 0).long()
else:
raise ValueError("add_sentence_boundary_token_ids only accepts 2D and 3D input")
return tensor_with_boundary_tokens, new_mask
def remove_sentence_boundaries(tensor: torch.Tensor,
mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
# TODO: matthewp, profile this transfer
sequence_lengths = mask.sum(dim=1).detach().cpu().numpy()
tensor_shape = list(tensor.data.shape)
new_shape = list(tensor_shape)
new_shape[1] = tensor_shape[1] - 2
tensor_without_boundary_tokens = tensor.new_zeros(*new_shape)
new_mask = tensor.new_zeros((new_shape[0], new_shape[1]), dtype=torch.long)
for i, j in enumerate(sequence_lengths):
if j > 2:
tensor_without_boundary_tokens[i, :(j - 2), :] = tensor[i, 1:(j - 1), :]
new_mask[i, :(j - 2)] = 1
return tensor_without_boundary_tokens, new_mask
def add_positional_features(tensor: torch.Tensor,
min_timescale: float = 1.0,
max_timescale: float = 1.0e4):
# pylint: disable=line-too-long
_, timesteps, hidden_dim = tensor.size()
timestep_range = get_range_vector(timesteps, get_device_of(tensor)).data.float()
# We're generating both cos and sin frequencies,
num_timescales = hidden_dim // 2
timescale_range = get_range_vector(num_timescales, get_device_of(tensor)).data.float()
log_timescale_increments = math.log(float(max_timescale) / float(min_timescale)) / float(num_timescales - 1)
inverse_timescales = min_timescale * torch.exp(timescale_range * -log_timescale_increments)
scaled_time = timestep_range.unsqueeze(1) * inverse_timescales.unsqueeze(0)
sinusoids = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], 1)
if hidden_dim % 2 != 0:
sinusoids = torch.cat([sinusoids, sinusoids.new_zeros(timesteps, 1)], 1)
return tensor + sinusoids.unsqueeze(0)
| true | true |
f727e5f78b42c3a1e0eaf2ad37a23824a5767c53 | 828 | py | Python | build_scripts/generate_rc_build_number.py | MATTHEWFRAZER/trochilidae | 35e907ba9dcb1f283f79f4f32d61db6b53a1ca97 | [
"MIT"
] | null | null | null | build_scripts/generate_rc_build_number.py | MATTHEWFRAZER/trochilidae | 35e907ba9dcb1f283f79f4f32d61db6b53a1ca97 | [
"MIT"
] | null | null | null | build_scripts/generate_rc_build_number.py | MATTHEWFRAZER/trochilidae | 35e907ba9dcb1f283f79f4f32d61db6b53a1ca97 | [
"MIT"
] | 1 | 2021-11-12T18:49:15.000Z | 2021-11-12T18:49:15.000Z | #!/usr/bin/python
import subprocess
try:
from subprocess import DEVNULL # py3k
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
version_path = "version.txt"
build_type = "rc"
with open(version_path, "r") as f:
version = f.readline()
build_number = 0
tag = "{0}-{1}.{2}".format(version, build_type, build_number)
# TODO: revisit
# while ideally, I would like separation between one liners and scripts in our build process
# this was the simplest way I could think of to implement this
# because it is done this way, it forces us to pay attention to the order in which we call into this script
while subprocess.call(["git", "rev-parse", "--verify", tag], stdout=DEVNULL, stderr=DEVNULL) == 0:
build_number += 1
tag = "{0}-{1}.{2}".format(version, build_type, build_number)
print(tag) | 28.551724 | 107 | 0.704106 |
import subprocess
try:
from subprocess import DEVNULL
except ImportError:
import os
DEVNULL = open(os.devnull, 'wb')
version_path = "version.txt"
build_type = "rc"
with open(version_path, "r") as f:
version = f.readline()
build_number = 0
tag = "{0}-{1}.{2}".format(version, build_type, build_number)
while subprocess.call(["git", "rev-parse", "--verify", tag], stdout=DEVNULL, stderr=DEVNULL) == 0:
build_number += 1
tag = "{0}-{1}.{2}".format(version, build_type, build_number)
print(tag) | true | true |
f727e839bc9f60bee5264f963b12f7ba8265d8ef | 6,935 | py | Python | dsmr_parser/parsers.py | Smeedy/dsmr_parser | 1ab4cb4b11eec41c559a33d73e70c211216854d1 | [
"MIT"
] | null | null | null | dsmr_parser/parsers.py | Smeedy/dsmr_parser | 1ab4cb4b11eec41c559a33d73e70c211216854d1 | [
"MIT"
] | null | null | null | dsmr_parser/parsers.py | Smeedy/dsmr_parser | 1ab4cb4b11eec41c559a33d73e70c211216854d1 | [
"MIT"
] | null | null | null | import logging
import re
from PyCRC.CRC16 import CRC16
from dsmr_parser.objects import MBusObject, CosemObject
from dsmr_parser.exceptions import ParseContentError, InvalidChecksumError, NoChecksumError
logger = logging.getLogger(__name__)
class TelegramParser(object):
def __init__(self, telegram_specification, apply_checksum_validation=True):
"""
:param telegram_specification: determines how the telegram is parsed
:param apply_checksum_validation: validate checksum if applicable for
telegram DSMR version (v4 and up).
:type telegram_specification: dict
"""
self.telegram_specification = telegram_specification
self.apply_checksum_validation = apply_checksum_validation
def parse(self, telegram_data):
"""
Parse telegram from string to dict.
The telegram str type makes python 2.x integration easier.
:param str telegram_data: full telegram from start ('/') to checksum
('!ABCD') including line endings in between the telegram's lines
:rtype: dict
:returns: Shortened example:
{
..
r'\d-\d:96\.1\.1.+?\r\n': <CosemObject>, # EQUIPMENT_IDENTIFIER
r'\d-\d:1\.8\.1.+?\r\n': <CosemObject>, # ELECTRICITY_USED_TARIFF_1
r'\d-\d:24\.3\.0.+?\r\n.+?\r\n': <MBusObject>, # GAS_METER_READING
..
}
:raises ParseError:
:raises InvalidChecksumError:
"""
if self.apply_checksum_validation \
and self.telegram_specification['checksum_support']:
self.validate_checksum(telegram_data)
telegram = {}
for signature, parser in self.telegram_specification['objects'].items():
match = re.search(signature, telegram_data, re.DOTALL)
# Some signatures are optional and may not be present,
# so only parse lines that match
if match:
telegram[signature] = parser.parse(match.group(0))
return telegram
@staticmethod
def validate_checksum(telegram):
"""
:param str telegram:
:raises ParseError:
:raises InvalidChecksumError:
"""
# Extract the part for which the checksum applies.
checksum_contents = re.search(r'\/.+\!', telegram, re.DOTALL)
# Extract the hexadecimal checksum value itself.
# The line ending '\r\n' for the checksum line can be ignored.
checksum_hex = re.search(r'((?<=\!)[0-9A-Z]{4})+', telegram)
if not checksum_contents:
raise ParseContentError(
'Failed to perform CRC validation because the telegram is '
'incomplete: The content value is missing.'
)
elif checksum_contents and not checksum_hex:
raise NoChecksumError(
'Failed to perform CRC validation because the telegram is '
'incomplete: The CRC is missing.'
)
calculated_crc = CRC16().calculate(checksum_contents.group(0))
expected_crc = int(checksum_hex.group(0), base=16)
if calculated_crc != expected_crc:
raise InvalidChecksumError(
"Invalid telegram. The CRC checksum '{}' does not match the "
"expected '{}'".format(
calculated_crc,
expected_crc
)
)
class DSMRObjectParser(object):
"""
Parses an object (can also be see as a 'line') from a telegram.
"""
def __init__(self, *value_formats):
self.value_formats = value_formats
def _parse(self, line):
# Match value groups, but exclude the parentheses
pattern = re.compile(r'((?<=\()[0-9a-zA-Z\.\*]{0,}(?=\)))+')
values = re.findall(pattern, line)
# Convert empty value groups to None for clarity.
values = [None if value == '' else value for value in values]
if not values or len(values) != len(self.value_formats):
raise ParseError("Invalid '%s' line for '%s'", line, self)
return [self.value_formats[i].parse(value)
for i, value in enumerate(values)]
class MBusParser(DSMRObjectParser):
"""
Gas meter value parser.
These are lines with a timestamp and gas meter value.
Line format:
'ID (TST) (Mv1*U1)'
1 2 3 4
1) OBIS Reduced ID-code
2) Time Stamp (TST) of capture time of measurement value
3) Measurement value 1 (most recent entry of buffer attribute without unit)
4) Unit of measurement values (Unit of capture objects attribute)
"""
def parse(self, line):
return MBusObject(self._parse(line))
class CosemParser(DSMRObjectParser):
"""
Cosem object parser.
These are data objects with a single value that optionally have a unit of
measurement.
Line format:
ID (Mv*U)
1 23 45
1) OBIS Reduced ID-code
2) Separator "(", ASCII 28h
3) COSEM object attribute value
4) Unit of measurement values (Unit of capture objects attribute) - only if
applicable
5) Separator ")", ASCII 29h
"""
def parse(self, line):
return CosemObject(self._parse(line))
class ProfileGenericParser(DSMRObjectParser):
"""
Power failure log parser.
These are data objects with multiple repeating groups of values.
Line format:
ID (z) (ID1) (TST) (Bv1*U1) (TST) (Bvz*Uz)
1 2 3 4 5 6 7 8 9
1) OBIS Reduced ID-code
2) Number of values z (max 10).
3) Identifications of buffer values (OBIS Reduced ID codes of capture objects attribute)
4) Time Stamp (TST) of power failure end time
5) Buffer value 1 (most recent entry of buffer attribute without unit)
6) Unit of buffer values (Unit of capture objects attribute)
7) Time Stamp (TST) of power failure end time
8) Buffer value 2 (oldest entry of buffer attribute without unit)
9) Unit of buffer values (Unit of capture objects attribute)
"""
def parse(self, line):
raise NotImplementedError()
class ValueParser(object):
"""
Parses a single value from DSMRObject's.
Example with coerce_type being int:
(002*A) becomes {'value': 1, 'unit': 'A'}
Example with coerce_type being str:
(42) becomes {'value': '42', 'unit': None}
"""
def __init__(self, coerce_type):
self.coerce_type = coerce_type
def parse(self, value):
unit_of_measurement = None
if value and '*' in value:
value, unit_of_measurement = value.split('*')
# A value group is not required to have a value, and then coercing does
# not apply.
value = self.coerce_type(value) if value is not None else value
return {
'value': value,
'unit': unit_of_measurement
}
| 31.098655 | 92 | 0.617159 | import logging
import re
from PyCRC.CRC16 import CRC16
from dsmr_parser.objects import MBusObject, CosemObject
from dsmr_parser.exceptions import ParseContentError, InvalidChecksumError, NoChecksumError
logger = logging.getLogger(__name__)
class TelegramParser(object):
def __init__(self, telegram_specification, apply_checksum_validation=True):
self.telegram_specification = telegram_specification
self.apply_checksum_validation = apply_checksum_validation
def parse(self, telegram_data):
if self.apply_checksum_validation \
and self.telegram_specification['checksum_support']:
self.validate_checksum(telegram_data)
telegram = {}
for signature, parser in self.telegram_specification['objects'].items():
match = re.search(signature, telegram_data, re.DOTALL)
if match:
telegram[signature] = parser.parse(match.group(0))
return telegram
@staticmethod
def validate_checksum(telegram):
checksum_contents = re.search(r'\/.+\!', telegram, re.DOTALL)
checksum_hex = re.search(r'((?<=\!)[0-9A-Z]{4})+', telegram)
if not checksum_contents:
raise ParseContentError(
'Failed to perform CRC validation because the telegram is '
'incomplete: The content value is missing.'
)
elif checksum_contents and not checksum_hex:
raise NoChecksumError(
'Failed to perform CRC validation because the telegram is '
'incomplete: The CRC is missing.'
)
calculated_crc = CRC16().calculate(checksum_contents.group(0))
expected_crc = int(checksum_hex.group(0), base=16)
if calculated_crc != expected_crc:
raise InvalidChecksumError(
"Invalid telegram. The CRC checksum '{}' does not match the "
"expected '{}'".format(
calculated_crc,
expected_crc
)
)
class DSMRObjectParser(object):
def __init__(self, *value_formats):
self.value_formats = value_formats
def _parse(self, line):
pattern = re.compile(r'((?<=\()[0-9a-zA-Z\.\*]{0,}(?=\)))+')
values = re.findall(pattern, line)
values = [None if value == '' else value for value in values]
if not values or len(values) != len(self.value_formats):
raise ParseError("Invalid '%s' line for '%s'", line, self)
return [self.value_formats[i].parse(value)
for i, value in enumerate(values)]
class MBusParser(DSMRObjectParser):
def parse(self, line):
return MBusObject(self._parse(line))
class CosemParser(DSMRObjectParser):
def parse(self, line):
return CosemObject(self._parse(line))
class ProfileGenericParser(DSMRObjectParser):
def parse(self, line):
raise NotImplementedError()
class ValueParser(object):
def __init__(self, coerce_type):
self.coerce_type = coerce_type
def parse(self, value):
unit_of_measurement = None
if value and '*' in value:
value, unit_of_measurement = value.split('*')
value = self.coerce_type(value) if value is not None else value
return {
'value': value,
'unit': unit_of_measurement
}
| true | true |
f727e89ef20c8fb9be92012ad38858b527ba3813 | 579 | py | Python | src/bot/discord_ext.py | MycroftKang/mulgyeol-mkbot | 77bcfc5c93e02dbc983d2e6a137ddf835d450c29 | [
"MIT"
] | null | null | null | src/bot/discord_ext.py | MycroftKang/mulgyeol-mkbot | 77bcfc5c93e02dbc983d2e6a137ddf835d450c29 | [
"MIT"
] | null | null | null | src/bot/discord_ext.py | MycroftKang/mulgyeol-mkbot | 77bcfc5c93e02dbc983d2e6a137ddf835d450c29 | [
"MIT"
] | null | null | null | discord_extensions = (
"core.controllers.discord.delete",
"core.controllers.discord.join",
"core.controllers.discord.leave",
"core.controllers.discord.logout",
"core.controllers.discord.ping",
"core.controllers.discord.tts",
"core.controllers.discord.poll",
"core.controllers.discord.roulette",
"core.controllers.discord.translate",
"core.controllers.discord.music",
"core.controllers.discord.highlighter",
"core.controllers.discord.tic_tac_toe",
"core.controllers.discord.feedback",
"core.controllers.discord.timezone",
)
| 34.058824 | 43 | 0.721934 | discord_extensions = (
"core.controllers.discord.delete",
"core.controllers.discord.join",
"core.controllers.discord.leave",
"core.controllers.discord.logout",
"core.controllers.discord.ping",
"core.controllers.discord.tts",
"core.controllers.discord.poll",
"core.controllers.discord.roulette",
"core.controllers.discord.translate",
"core.controllers.discord.music",
"core.controllers.discord.highlighter",
"core.controllers.discord.tic_tac_toe",
"core.controllers.discord.feedback",
"core.controllers.discord.timezone",
)
| true | true |
f727e976fa0a94180dd9383f9dc5be94b4aa493a | 8,537 | py | Python | train.py | DylanHooz/uestc_yolov3 | 72ed60aaf68a0ab2dbc8d4dfad7bddffce826dde | [
"MIT"
] | null | null | null | train.py | DylanHooz/uestc_yolov3 | 72ed60aaf68a0ab2dbc8d4dfad7bddffce826dde | [
"MIT"
] | null | null | null | train.py | DylanHooz/uestc_yolov3 | 72ed60aaf68a0ab2dbc8d4dfad7bddffce826dde | [
"MIT"
] | null | null | null | """
Retrain the YOLO model for your own dataset.
"""
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
def _main():
annotation_path = '2007_trainval.txt'
log_dir = 'logs/000/'
classes_path = 'model_data/helmet_classes.txt'
anchors_path = 'model_data/helmet_anchors.txt'
class_names = get_classes(classes_path)
num_classes = len(class_names)
anchors = get_anchors(anchors_path)
input_shape = (416,416) # multiple of 32, hw
is_tiny_version = len(anchors)==6 # default setting
if is_tiny_version:
model = create_tiny_model(input_shape, anchors, num_classes,
freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5')
else:
model = create_model(input_shape, anchors, num_classes,
freeze_body=2, weights_path='model_data/yolo_weights.h5') # make sure you know what you freeze
logging = TensorBoard(log_dir=log_dir)
checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',
monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)
val_split = 0.1
with open(annotation_path) as f:
lines = f.readlines()
np.random.seed(10101)
np.random.shuffle(lines)
np.random.seed(None)
num_val = int(len(lines)*val_split)
num_train = len(lines) - num_val
# Train with frozen layers first, to get a stable loss.
# Adjust num epochs to your dataset. This step is enough to obtain a not bad model.
if True:
model.compile(optimizer=Adam(lr=1e-3), loss={
# use custom yolo_loss Lambda layer.
'yolo_loss': lambda y_true, y_pred: y_pred})
batch_size = 32
print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
steps_per_epoch=max(1, num_train//batch_size),
validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),
validation_steps=max(1, num_val//batch_size),
epochs=50,
initial_epoch=0,
callbacks=[logging, checkpoint])
model.save_weights(log_dir + 'trained_weights_stage_1.h5')
# Unfreeze and continue training, to fine-tune.
# Train longer if the result is not good.
if True:
for i in range(len(model.layers)):
model.layers[i].trainable = True
model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred}) # recompile to apply the change
print('Unfreeze all of the layers.')
batch_size = 16 # note that more GPU memory is required after unfreezing the body
print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
steps_per_epoch=max(1, num_train//batch_size),
validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),
validation_steps=max(1, num_val//batch_size),
epochs=100,
initial_epoch=50,
callbacks=[logging, checkpoint, reduce_lr, early_stopping])
model.save_weights(log_dir + 'trained_weights_final.h5')
# Further training if needed.
def get_classes(classes_path):
'''loads the classes'''
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def get_anchors(anchors_path):
'''loads the anchors from a file'''
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/yolo_weights.h5'):
'''create the training model'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \
num_anchors//3, num_classes+5)) for l in range(3)]
model_body = yolo_body(image_input, num_anchors//3, num_classes)
print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
if load_pretrained:
model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)
print('Load weights {}.'.format(weights_path))
if freeze_body in [1, 2]:
# Freeze darknet53 body or freeze all but 3 output layers.
num = (185, len(model_body.layers)-3)[freeze_body-1]
for i in range(num): model_body.layers[i].trainable = False
print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/tiny_yolo_weights.h5'):
'''create the training model, for Tiny YOLOv3'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \
num_anchors//2, num_classes+5)) for l in range(2)]
model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes)
print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
if load_pretrained:
model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)
print('Load weights {}.'.format(weights_path))
if freeze_body in [1, 2]:
# Freeze the darknet body or freeze all but 2 output layers.
num = (20, len(model_body.layers)-2)[freeze_body-1]
for i in range(num): model_body.layers[i].trainable = False
print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
'''data generator for fit_generator'''
n = len(annotation_lines)
i = 0
while True:
image_data = []
box_data = []
for b in range(batch_size):
if i==0:
np.random.shuffle(annotation_lines)
image, box = get_random_data(annotation_lines[i], input_shape, random=True)
image_data.append(image)
box_data.append(box)
i = (i+1) % n
image_data = np.array(image_data)
box_data = np.array(box_data)
y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
yield [image_data, *y_true], np.zeros(batch_size)
def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):
n = len(annotation_lines)
if n==0 or batch_size<=0: return None
return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
if __name__ == '__main__':
_main()
| 44.463542 | 130 | 0.660536 |
import numpy as np
import keras.backend as K
from keras.layers import Input, Lambda
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import TensorBoard, ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
from yolo3.model import preprocess_true_boxes, yolo_body, tiny_yolo_body, yolo_loss
from yolo3.utils import get_random_data
def _main():
annotation_path = '2007_trainval.txt'
log_dir = 'logs/000/'
classes_path = 'model_data/helmet_classes.txt'
anchors_path = 'model_data/helmet_anchors.txt'
class_names = get_classes(classes_path)
num_classes = len(class_names)
anchors = get_anchors(anchors_path)
input_shape = (416,416)
is_tiny_version = len(anchors)==6
if is_tiny_version:
model = create_tiny_model(input_shape, anchors, num_classes,
freeze_body=2, weights_path='model_data/tiny_yolo_weights.h5')
else:
model = create_model(input_shape, anchors, num_classes,
freeze_body=2, weights_path='model_data/yolo_weights.h5')
logging = TensorBoard(log_dir=log_dir)
checkpoint = ModelCheckpoint(log_dir + 'ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5',
monitor='val_loss', save_weights_only=True, save_best_only=True, period=3)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1)
val_split = 0.1
with open(annotation_path) as f:
lines = f.readlines()
np.random.seed(10101)
np.random.shuffle(lines)
np.random.seed(None)
num_val = int(len(lines)*val_split)
num_train = len(lines) - num_val
if True:
model.compile(optimizer=Adam(lr=1e-3), loss={
'yolo_loss': lambda y_true, y_pred: y_pred})
batch_size = 32
print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
steps_per_epoch=max(1, num_train//batch_size),
validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),
validation_steps=max(1, num_val//batch_size),
epochs=50,
initial_epoch=0,
callbacks=[logging, checkpoint])
model.save_weights(log_dir + 'trained_weights_stage_1.h5')
if True:
for i in range(len(model.layers)):
model.layers[i].trainable = True
model.compile(optimizer=Adam(lr=1e-4), loss={'yolo_loss': lambda y_true, y_pred: y_pred})
print('Unfreeze all of the layers.')
batch_size = 16
print('Train on {} samples, val on {} samples, with batch size {}.'.format(num_train, num_val, batch_size))
model.fit_generator(data_generator_wrapper(lines[:num_train], batch_size, input_shape, anchors, num_classes),
steps_per_epoch=max(1, num_train//batch_size),
validation_data=data_generator_wrapper(lines[num_train:], batch_size, input_shape, anchors, num_classes),
validation_steps=max(1, num_val//batch_size),
epochs=100,
initial_epoch=50,
callbacks=[logging, checkpoint, reduce_lr, early_stopping])
model.save_weights(log_dir + 'trained_weights_final.h5')
def get_classes(classes_path):
with open(classes_path) as f:
class_names = f.readlines()
class_names = [c.strip() for c in class_names]
return class_names
def get_anchors(anchors_path):
with open(anchors_path) as f:
anchors = f.readline()
anchors = [float(x) for x in anchors.split(',')]
return np.array(anchors).reshape(-1, 2)
def create_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/yolo_weights.h5'):
K.clear_session()
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16, 2:8}[l], w//{0:32, 1:16, 2:8}[l], \
num_anchors//3, num_classes+5)) for l in range(3)]
model_body = yolo_body(image_input, num_anchors//3, num_classes)
print('Create YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
if load_pretrained:
model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)
print('Load weights {}.'.format(weights_path))
if freeze_body in [1, 2]:
num = (185, len(model_body.layers)-3)[freeze_body-1]
for i in range(num): model_body.layers[i].trainable = False
print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.5})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/tiny_yolo_weights.h5'):
K.clear_session()
image_input = Input(shape=(None, None, 3))
h, w = input_shape
num_anchors = len(anchors)
y_true = [Input(shape=(h//{0:32, 1:16}[l], w//{0:32, 1:16}[l], \
num_anchors//2, num_classes+5)) for l in range(2)]
model_body = tiny_yolo_body(image_input, num_anchors//2, num_classes)
print('Create Tiny YOLOv3 model with {} anchors and {} classes.'.format(num_anchors, num_classes))
if load_pretrained:
model_body.load_weights(weights_path, by_name=True, skip_mismatch=True)
print('Load weights {}.'.format(weights_path))
if freeze_body in [1, 2]:
num = (20, len(model_body.layers)-2)[freeze_body-1]
for i in range(num): model_body.layers[i].trainable = False
print('Freeze the first {} layers of total {} layers.'.format(num, len(model_body.layers)))
model_loss = Lambda(yolo_loss, output_shape=(1,), name='yolo_loss',
arguments={'anchors': anchors, 'num_classes': num_classes, 'ignore_thresh': 0.7})(
[*model_body.output, *y_true])
model = Model([model_body.input, *y_true], model_loss)
return model
def data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes):
n = len(annotation_lines)
i = 0
while True:
image_data = []
box_data = []
for b in range(batch_size):
if i==0:
np.random.shuffle(annotation_lines)
image, box = get_random_data(annotation_lines[i], input_shape, random=True)
image_data.append(image)
box_data.append(box)
i = (i+1) % n
image_data = np.array(image_data)
box_data = np.array(box_data)
y_true = preprocess_true_boxes(box_data, input_shape, anchors, num_classes)
yield [image_data, *y_true], np.zeros(batch_size)
def data_generator_wrapper(annotation_lines, batch_size, input_shape, anchors, num_classes):
n = len(annotation_lines)
if n==0 or batch_size<=0: return None
return data_generator(annotation_lines, batch_size, input_shape, anchors, num_classes)
if __name__ == '__main__':
_main()
| true | true |
f727ea71d77bc5a71cddd8eb8f7f9da14738cd39 | 165 | py | Python | src/timeatlas/generators/anomaly_generator/__init__.py | fredmontet/timeatlas | 9a439a913ef9a8a1ef9833b42e5fb4e988d7e35e | [
"MIT"
] | 10 | 2020-08-25T09:23:02.000Z | 2021-01-12T14:00:35.000Z | src/timeatlas/generators/anomaly_generator/__init__.py | fredmontet/timeatlas | 9a439a913ef9a8a1ef9833b42e5fb4e988d7e35e | [
"MIT"
] | 140 | 2020-06-30T11:59:47.000Z | 2021-08-23T20:58:43.000Z | src/timeatlas/generators/anomaly_generator/__init__.py | fredmontet/timeatlas | 9a439a913ef9a8a1ef9833b42e5fb4e988d7e35e | [
"MIT"
] | null | null | null | from .anomalies import AnomalyABC
from .labeler import AnomalySetLabeler
from .anomaly_generator import AnomalyGenerator
from .config import AnomalyGeneratorTemplate | 41.25 | 47 | 0.884848 | from .anomalies import AnomalyABC
from .labeler import AnomalySetLabeler
from .anomaly_generator import AnomalyGenerator
from .config import AnomalyGeneratorTemplate | true | true |
f727eacf052868602d35b1841a9c93d769a8fe24 | 4,382 | py | Python | packages/syft/src/syft/core/node/common/action/get_enum_attribute_action.py | jackbandy/PySyft | 0e20e90abab6a7a7ca672d6eedfa1e7f83c4981b | [
"Apache-2.0"
] | null | null | null | packages/syft/src/syft/core/node/common/action/get_enum_attribute_action.py | jackbandy/PySyft | 0e20e90abab6a7a7ca672d6eedfa1e7f83c4981b | [
"Apache-2.0"
] | null | null | null | packages/syft/src/syft/core/node/common/action/get_enum_attribute_action.py | jackbandy/PySyft | 0e20e90abab6a7a7ca672d6eedfa1e7f83c4981b | [
"Apache-2.0"
] | null | null | null | # stdlib
from typing import Dict
from typing import Optional
# third party
from google.protobuf.reflection import GeneratedProtocolMessageType
from nacl.signing import VerifyKey
# syft absolute
import syft as sy
# relative
from ..... import lib
from .....proto.core.node.common.action.get_enum_attribute_pb2 import (
GetEnumAttributeAction as GetEnumAttributeAction_PB,
)
from ....common.serde.serializable import serializable
from ....common.uid import UID
from ....io.address import Address
from ....store.storeable_object import StorableObject
from ...abstract.node import AbstractNode
from .common import ImmediateActionWithoutReply
from .run_class_method_action import RunClassMethodAction
@serializable()
class EnumAttributeAction(ImmediateActionWithoutReply):
def __init__(
self,
path: str,
id_at_location: UID,
address: Address,
msg_id: Optional[UID] = None,
):
super().__init__(address, msg_id=msg_id)
self.id_at_location = id_at_location
self.path = path
def intersect_keys(
self,
left: Dict[VerifyKey, Optional[UID]],
right: Dict[VerifyKey, Optional[UID]],
) -> Dict[VerifyKey, Optional[UID]]:
return RunClassMethodAction.intersect_keys(left, right)
def execute_action(self, node: AbstractNode, verify_key: VerifyKey) -> None:
enum_attribute = node.lib_ast.query(self.path)
result = enum_attribute.solve_get_enum_attribute().value
result = lib.python.primitive_factory.PrimitiveFactory.generate_primitive(
value=result, id=self.id_at_location
)
result = StorableObject(
id=self.id_at_location,
data=result,
)
node.store[self.id_at_location] = result
def _object2proto(self) -> GetEnumAttributeAction_PB:
"""Returns a protobuf serialization of self.
As a requirement of all objects which inherit from Serializable,
this method transforms the current object into the corresponding
Protobuf object so that it can be further serialized.
:return: returns a protobuf object
:rtype: GetOrSetPropertyAction_PB
.. note::
This method is purely an internal method. Please use serialize(object) or one of
the other public serialization methods if you wish to serialize an
object.
"""
return GetEnumAttributeAction_PB(
path=self.path,
id_at_location=sy.serialize(self.id_at_location),
address=sy.serialize(self.address),
msg_id=sy.serialize(self.id),
)
@staticmethod
def _proto2object(
proto: GetEnumAttributeAction_PB,
) -> "EnumAttributeAction":
"""Creates a ObjectWithID from a protobuf
As a requirement of all objects which inherit from Serializable,
this method transforms a protobuf object into an instance of this class.
:return: returns an instance of GetOrSetPropertyAction
:rtype: GetOrSetPropertyAction
.. note::
This method is purely an internal method. Please use syft.deserialize()
if you wish to deserialize an object.
"""
return EnumAttributeAction(
path=proto.path,
id_at_location=sy.deserialize(blob=proto.id_at_location),
address=sy.deserialize(blob=proto.address),
msg_id=sy.deserialize(blob=proto.msg_id),
)
@staticmethod
def get_protobuf_schema() -> GeneratedProtocolMessageType:
"""Return the type of protobuf object which stores a class of this type
As a part of serialization and deserialization, we need the ability to
lookup the protobuf object type directly from the object type. This
static method allows us to do this.
Importantly, this method is also used to create the reverse lookup ability within
the metaclass of Serializable. In the metaclass, it calls this method and then
it takes whatever type is returned from this method and adds an attribute to it
with the type of this class attached to it. See the MetaSerializable class for details.
:return: the type of protobuf object which corresponds to this class.
:rtype: GeneratedProtocolMessageType
"""
return GetEnumAttributeAction_PB
| 38.104348 | 95 | 0.689411 |
from typing import Dict
from typing import Optional
from google.protobuf.reflection import GeneratedProtocolMessageType
from nacl.signing import VerifyKey
import syft as sy
from ..... import lib
from .....proto.core.node.common.action.get_enum_attribute_pb2 import (
GetEnumAttributeAction as GetEnumAttributeAction_PB,
)
from ....common.serde.serializable import serializable
from ....common.uid import UID
from ....io.address import Address
from ....store.storeable_object import StorableObject
from ...abstract.node import AbstractNode
from .common import ImmediateActionWithoutReply
from .run_class_method_action import RunClassMethodAction
@serializable()
class EnumAttributeAction(ImmediateActionWithoutReply):
def __init__(
self,
path: str,
id_at_location: UID,
address: Address,
msg_id: Optional[UID] = None,
):
super().__init__(address, msg_id=msg_id)
self.id_at_location = id_at_location
self.path = path
def intersect_keys(
self,
left: Dict[VerifyKey, Optional[UID]],
right: Dict[VerifyKey, Optional[UID]],
) -> Dict[VerifyKey, Optional[UID]]:
return RunClassMethodAction.intersect_keys(left, right)
def execute_action(self, node: AbstractNode, verify_key: VerifyKey) -> None:
enum_attribute = node.lib_ast.query(self.path)
result = enum_attribute.solve_get_enum_attribute().value
result = lib.python.primitive_factory.PrimitiveFactory.generate_primitive(
value=result, id=self.id_at_location
)
result = StorableObject(
id=self.id_at_location,
data=result,
)
node.store[self.id_at_location] = result
def _object2proto(self) -> GetEnumAttributeAction_PB:
return GetEnumAttributeAction_PB(
path=self.path,
id_at_location=sy.serialize(self.id_at_location),
address=sy.serialize(self.address),
msg_id=sy.serialize(self.id),
)
@staticmethod
def _proto2object(
proto: GetEnumAttributeAction_PB,
) -> "EnumAttributeAction":
return EnumAttributeAction(
path=proto.path,
id_at_location=sy.deserialize(blob=proto.id_at_location),
address=sy.deserialize(blob=proto.address),
msg_id=sy.deserialize(blob=proto.msg_id),
)
@staticmethod
def get_protobuf_schema() -> GeneratedProtocolMessageType:
return GetEnumAttributeAction_PB
| true | true |
f727ec286ffb28b7cbdb0a43ec55f52b2d947849 | 496 | py | Python | package_maker/py2exe/single_file/setup.py | thanhkaist/Qt-Python-Binding-Examples | 25b3313fd03e396014cce0e8f7eec8823b3ebd29 | [
"BSD-3-Clause"
] | 2 | 2019-10-20T05:40:51.000Z | 2019-10-31T17:26:27.000Z | package_maker/py2exe/single_file/setup.py | thanhkaist/Qt-Python-Binding-Examples | 25b3313fd03e396014cce0e8f7eec8823b3ebd29 | [
"BSD-3-Clause"
] | null | null | null | package_maker/py2exe/single_file/setup.py | thanhkaist/Qt-Python-Binding-Examples | 25b3313fd03e396014cce0e8f7eec8823b3ebd29 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import os
import glob
##
from distutils.core import setup
import py2exe
assert py2exe != None
##
osp=os.path
windows = [
{
"script": "btn.py",
"icon_resources": [(1, "gui.ico")],
}
]
options = {
"py2exe": {
"includes": ["PyQt4", "sip"],
"dll_excludes": ["MSVCP90.dll"],
"bundle_files" : 1,
}
}
setup(
name = "foo",
windows = windows,
options = options,
zipfile = None,
) | 16 | 43 | 0.528226 |
import os
import glob
from distutils.core import setup
import py2exe
assert py2exe != None
osp=os.path
windows = [
{
"script": "btn.py",
"icon_resources": [(1, "gui.ico")],
}
]
options = {
"py2exe": {
"includes": ["PyQt4", "sip"],
"dll_excludes": ["MSVCP90.dll"],
"bundle_files" : 1,
}
}
setup(
name = "foo",
windows = windows,
options = options,
zipfile = None,
) | true | true |
f727ecacbdc8f8fdc864e9a7692a7f8384a45b5b | 763 | py | Python | account/forms.py | mateuszwwwrobel/Expense_Tracker_Django | e84bda82433427608e026faa00a634c46a433179 | [
"MIT"
] | null | null | null | account/forms.py | mateuszwwwrobel/Expense_Tracker_Django | e84bda82433427608e026faa00a634c46a433179 | [
"MIT"
] | null | null | null | account/forms.py | mateuszwwwrobel/Expense_Tracker_Django | e84bda82433427608e026faa00a634c46a433179 | [
"MIT"
] | null | null | null | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
"""Custom signup form with additional fields."""
first_name = forms.CharField(max_length=50, required=False,
help_text='Optional. 50 characters or fewer.')
last_name = forms.CharField(max_length=50, required=False,
help_text='Optional. 50 characters or fewer.')
email = forms.EmailField(max_length=254,
help_text='Required. Email confirmation will be send.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
| 40.157895 | 92 | 0.646134 | from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
first_name = forms.CharField(max_length=50, required=False,
help_text='Optional. 50 characters or fewer.')
last_name = forms.CharField(max_length=50, required=False,
help_text='Optional. 50 characters or fewer.')
email = forms.EmailField(max_length=254,
help_text='Required. Email confirmation will be send.')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)
| true | true |
f727ed1dd0b38515ab9c60f47bb34d9f08bb15ec | 253 | py | Python | test.py | essethon/Python_HC_SR501 | 2ccae65651d82875a449e51b77aa5077ae78c19a | [
"MIT"
] | 4 | 2017-12-27T08:00:57.000Z | 2020-07-12T08:32:58.000Z | test.py | essethon/Python_HC_SR501 | 2ccae65651d82875a449e51b77aa5077ae78c19a | [
"MIT"
] | null | null | null | test.py | essethon/Python_HC_SR501 | 2ccae65651d82875a449e51b77aa5077ae78c19a | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import time
import motion_detector
if __name__ == "__main__":
while True:
if motion_detector.motion_detect():
print("Somebody is closing")
else:
print("Nobody")
time.sleep(1)
| 18.071429 | 43 | 0.596838 |
import time
import motion_detector
if __name__ == "__main__":
while True:
if motion_detector.motion_detect():
print("Somebody is closing")
else:
print("Nobody")
time.sleep(1)
| true | true |
f727ed746f16c529677c000a761dd7cf38da957f | 8,929 | py | Python | .history/pages/intro_20220304123207.py | rypaik/Streamlit_Ref | 5ce11cecbe8307238463c126b88b3beed66c99fa | [
"MIT"
] | null | null | null | .history/pages/intro_20220304123207.py | rypaik/Streamlit_Ref | 5ce11cecbe8307238463c126b88b3beed66c99fa | [
"MIT"
] | null | null | null | .history/pages/intro_20220304123207.py | rypaik/Streamlit_Ref | 5ce11cecbe8307238463c126b88b3beed66c99fa | [
"MIT"
] | null | null | null | """
Off Multipage Cheatsheet
https://github.com/daniellewisDL/streamlit-cheat-sheet
@daniellewisDL : https://github.com/daniellewisDL
"""
import streamlit as st
from pathlib import Path
import base64
from modules.toc import *
# Initial page config
st.set_page_config(
page_title='Code Compendium Intro Page',
layout="wide"
# initial_sidebar_state="expanded",
)
# col2.title("Table of contents")
# col2.write("http://localhost:8502/#display-progress-and-status")
# toc.header("Header 1")
# toc.header("Header 2")
# toc.subheader("Subheader 1")
# toc.subheader("Subheader 2")
# toc.generate()
# Thanks to streamlitopedia for the following code snippet
def img_to_bytes(img_path):
img_bytes = Path(img_path).read_bytes()
encoded = base64.b64encode(img_bytes).decode()
return encoded
# sidebar
# def cs_sidebar():
# st.sidebar.markdown('''[<img src='data:image/png;base64,{}' class='img-fluid' width=32 height=32>](https://streamlit.io/)'''.format(img_to_bytes("logomark_website.png")), unsafe_allow_html=True)
# st.sidebar.header('Streamlit cheat sheet')
# st.sidebar.markdown('''
# <small>Summary of the [docs](https://docs.streamlit.io/en/stable/api.html), as of [Streamlit v1.0.0](https://www.streamlit.io/).</small>
# ''', unsafe_allow_html=True)
# st.sidebar.markdown('__How to install and import__')
# st.sidebar.code('$ pip install streamlit')
# st.sidebar.markdown('Import convention')
# st.sidebar.code('>>> import streamlit as st')
# st.sidebar.markdown('__Add widgets to sidebar__')
# st.sidebar.code('''
# st.sidebar.<widget>
# >>> a = st.sidebar.radio(\'R:\',[1,2])
# ''')
# st.sidebar.markdown('__Command line__')
# st.sidebar.code('''
# $ streamlit --help
# $ streamlit run your_script.py
# $ streamlit hello
# $ streamlit config show
# $ streamlit cache clear
# $ streamlit docs
# $ streamlit --version
# ''')
# st.sidebar.markdown('__Pre-release features__')
# st.sidebar.markdown('[Beta and experimental features](https://docs.streamlit.io/en/stable/api.html#beta-and-experimental-features)')
# st.sidebar.code('''
# pip uninstall streamlit
# pip install streamlit-nightly --upgrade
# ''')
# st.sidebar.markdown('''<small>[st.cheat_sheet v1.0.0](https://github.com/daniellewisDL/streamlit-cheat-sheet) | Oct 2021</small>''', unsafe_allow_html=True)
# return None
##########################
# Main body of cheat sheet
##########################
def cs_body():
# col1 = st.columns(1)
st.title("Ryan Paik's Coding Compendium")
st.markdown('''
----------
#### “*You don't learn to walk by following rules. You learn by doing, and by falling over.*”
##### ~ Richard Branson
--------
''')
st.subheader("Welcome to my Code Compendium.")
st.markdown('''
This website/webapp is my personal cheatsheet for of all the code snippets that I have needed over the past 2 years. This ended up being a quick detour into Streamlit while I was building flask api's.
-----
#### **Programming is only as deep as you want to dive in.**
i
This webapp features the basic code snippets from all the "googling" from programming I have done.
I have taken the plunge and have created my own markdown notebooks organizing information from quick solution tidbits to documentation for programming languages.
Please visit my github for practical code and my research notebooks:
*[rypaik (Ryan Paik) · GitHub](https://github.com/rypaik)*
If you would like access to my Gist please email me.
ryanpaik@protonmail.com
-------
##### **Bio:**
Currently a Sophomore at University of Illinois at Urbana-Champaign.
I am working Nights on my Bachelor's of Science in Systems Engineering and Design
##### **Hobbies:**
Trying to become a real guitar hero minus the game system, playing Valorant with the St Mark's crew, getting interesting eats no matter where I am, and playing toss with my baseball field rat of a cousin.
The newest hobby is figuring out what I can build with all the new breakthroughs in technology.
##### **Currently Working On:**
##### Frameworks and Languages:
- Flask, Django, FastAPI, PyTorch, Streamlit, OpenCV, shell scripting, Python, C++
##### Databases:
- Postgres, Redis, MongoDB, and applicable ORMs
##### When I can get up for Air:
- React, swift(ios), Rust, GO!!
- Find a team to get a paper In Arxiv
**This site will be constantly updated as long as I program. Feel free to pass on the URL.**
''')
# col2.subheader('Display interactive widgets')
# col2.code('''
# st.button('Hit me')
# st.download_button('On the dl', data)
# st.checkbox('Check me out')
# st.radio('Radio', [1,2,3])
# st.selectbox('Select', [1,2,3])
# st.multiselect('Multiselect', [1,2,3])
# st.slider('Slide me', min_value=0, max_value=10)
# st.select_slider('Slide to select', options=[1,'2'])
# st.text_input('Enter some text')
# st.number_input('Enter a number')
# st.text_area('Area for textual entry')
# st.date_input('Date input')
# st.time_input('Time entry')
# st.file_uploader('File uploader')
# st.color_picker('Pick a color')
# ''')
# col2.write('Use widgets\' returned values in variables:')
# col2.code('''
# >>> for i in range(int(st.number_input('Num:'))): foo()
# >>> if st.sidebar.selectbox('I:',['f']) == 'f': b()
# >>> my_slider_val = st.slider('Quinn Mallory', 1, 88)
# >>> st.write(slider_val)
# ''')
# # Control flow
# col2.subheader('Control flow')
# col2.code('''
# st.stop()
# ''')
# # Lay out your app
# col2.subheader('Lay out your app')
# col2.code('''
# st.form('my_form_identifier')
# st.form_submit_button('Submit to me')
# st.container()
# st.columns(spec)
# >>> col1, col2 = st.columns(2)
# >>> col1.subheader('Columnisation')
# st.expander('Expander')
# >>> with st.expander('Expand'):
# >>> st.write('Juicy deets')
# ''')
# col2.write('Batch widgets together in a form:')
# col2.code('''
# >>> with st.form(key='my_form'):
# >>> text_input = st.text_input(label='Enter some text')
# >>> submit_button = st.form_submit_button(label='Submit')
# ''')
# # Display code
# col2.subheader('Display code')
# col2.code('''
# st.echo()
# >>> with st.echo():
# >>> st.write('Code will be executed and printed')
# ''')
# # Display progress and status
# col2.subheader('Display progress and status')
# col2.code('''
# st.progress(progress_variable_1_to_100)
# st.spinner()
# >>> with st.spinner(text='In progress'):
# >>> time.sleep(5)
# >>> st.success('Done')
# st.balloons()
# st.error('Error message')
# st.warning('Warning message')
# st.info('Info message')
# st.success('Success message')
# st.exception(e)
# ''')
# # Placeholders, help, and options
# col2.subheader('Placeholders, help, and options')
# col2.code('''
# st.empty()
# >>> my_placeholder = st.empty()
# >>> my_placeholder.text('Replaced!')
# st.help(pandas.DataFrame)
# st.get_option(key)
# st.set_option(key, value)
# st.set_page_config(layout='wide')
# ''')
# # Mutate data
# col2.subheader('Mutate data')
# col2.code('''
# DeltaGenerator.add_rows(data)
# >>> my_table = st.table(df1)
# >>> my_table.add_rows(df2)
# >>> my_chart = st.line_chart(df1)
# >>> my_chart.add_rows(df2)
# ''')
# # Optimize performance
# col2.subheader('Optimize performance')
# col2.code('''
# @st.cache
# >>> @st.cache
# ... def fetch_and_clean_data(url):
# ... # Mutate data at url
# ... return data
# >>> # Executes d1 as first time
# >>> d1 = fetch_and_clean_data(ref1)
# >>> # Does not execute d1; returns cached value, d1==d2
# >>> d2 = fetch_and_clean_data(ref1)
# >>> # Different arg, so function d1 executes
# >>> d3 = fetch_and_clean_data(ref2)
# ''')
# col2.subheader('Other key parts of the API')
# col2.markdown('''
# <small>[State API](https://docs.streamlit.io/en/stable/session_state_api.html)</small><br>
# <small>[Theme option reference](https://docs.streamlit.io/en/stable/theme_options.html)</small><br>
# <small>[Components API reference](https://docs.streamlit.io/en/stable/develop_streamlit_components.html)</small><br>
# <small>[API cheat sheet](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py)</small><br>
# ''', unsafe_allow_html=True)
# Column 3 TOC Generator
# col3.subheader('test')
# toc = Toc(col3)
# # col2.title("Table of contents")
# col3.write("http://localhost:8502/#display-progress-and-status", unsafe_allow_html=True)
# toc.header("Header 1")
# toc.header("Header 2")
# toc.generate()
# toc.subheader("Subheader 1")
# toc.subheader("Subheader 2")
# toc.generate()
# return None
# Run main()
# if __name__ == '__main__':
# main()
# def main():
def app():
# cs_sidebar()
cs_body()
return None
| 28.527157 | 206 | 0.652593 |
import streamlit as st
from pathlib import Path
import base64
from modules.toc import *
st.set_page_config(
page_title='Code Compendium Intro Page',
layout="wide"
)
def img_to_bytes(img_path):
img_bytes = Path(img_path).read_bytes()
encoded = base64.b64encode(img_bytes).decode()
return encoded
# <small>Summary of the [docs](https://docs.streamlit.io/en/stable/api.html), as of [Streamlit v1.0.0](https://www.streamlit.io/).</small>
# ''', unsafe_allow_html=True)
# st.sidebar.<widget>
# >>> a = st.sidebar.radio(\'R:\',[1,2])
# ''')
# $ streamlit --help
# $ streamlit run your_script.py
# $ streamlit hello
# $ streamlit config show
# $ streamlit cache clear
# $ streamlit docs
# $ streamlit --version
# ''')
# pip uninstall streamlit
# pip install streamlit-nightly --upgrade
# ''')
code snippets from all the "googling" from programming I have done.
I have taken the plunge and have created my own markdown notebooks organizing information from quick solution tidbits to documentation for programming languages.
Please visit my github for practical code and my research notebooks:
*[rypaik (Ryan Paik) · GitHub](https://github.com/rypaik)*
If you would like access to my Gist please email me.
ryanpaik@protonmail.com
-------
##### **Bio:**
Currently a Sophomore at University of Illinois at Urbana-Champaign.
I am working Nights on my Bachelor's of Science in Systems Engineering and Design
##### **Hobbies:**
Trying to become a real guitar hero minus the game system, playing Valorant with the St Mark's crew, getting interesting eats no matter where I am, and playing toss with my baseball field rat of a cousin.
The newest hobby is figuring out what I can build with all the new breakthroughs in technology.
##### **Currently Working On:**
##### Frameworks and Languages:
- Flask, Django, FastAPI, PyTorch, Streamlit, OpenCV, shell scripting, Python, C++
##### Databases:
- Postgres, Redis, MongoDB, and applicable ORMs
##### When I can get up for Air:
- React, swift(ios), Rust, GO!!
- Find a team to get a paper In Arxiv
**This site will be constantly updated as long as I program. Feel free to pass on the URL.**
''')
# col2.subheader('Display interactive widgets')
# col2.code('''
# st.button('Hit me')
# st.download_button('On the dl', data)
# st.checkbox('Check me out')
# st.radio('Radio', [1,2,3])
# st.selectbox('Select', [1,2,3])
# st.multiselect('Multiselect', [1,2,3])
# st.slider('Slide me', min_value=0, max_value=10)
# st.select_slider('Slide to select', options=[1,'2'])
# st.text_input('Enter some text')
# st.number_input('Enter a number')
# st.text_area('Area for textual entry')
# st.date_input('Date input')
# st.time_input('Time entry')
# st.file_uploader('File uploader')
# st.color_picker('Pick a color')
# ''')
# col2.write('Use widgets\' returned values in variables:')
# >>> for i in range(int(st.number_input('Num:'))): foo()
# >>> if st.sidebar.selectbox('I:',['f']) == 'f': b()
# >>> my_slider_val = st.slider('Quinn Mallory', 1, 88)
# >>> st.write(slider_val)
# ''')
)
# ''')
form_identifier')
# st.form_submit_button('Submit to me')
# st.container()
# st.columns(spec)
# >>> col1, col2 = st.columns(2)
# >>> col1.subheader('Columnisation')
# st.expander('Expander')
# >>> with st.expander('Expand'):
# >>> st.write('Juicy deets')
# ''')
# >>> with st.form(key='my_form'):
# >>> text_input = st.text_input(label='Enter some text')
# >>> submit_button = st.form_submit_button(label='Submit')
# ''')
)
# >>> with st.echo():
# >>> st.write('Code will be executed and printed')
# ''')
riable_1_to_100)
# st.spinner()
# >>> with st.spinner(text='In progress'):
# >>> time.sleep(5)
# >>> st.success('Done')
# st.balloons()
# st.error('Error message')
# st.warning('Warning message')
# st.info('Info message')
# st.success('Success message')
# st.exception(e)
# ''')
lder = st.empty()
# >>> my_placeholder.text('Replaced!')
# st.help(pandas.DataFrame)
# st.get_option(key)
# st.set_option(key, value)
# st.set_page_config(layout='wide')
# ''')
nerator.add_rows(data)
# >>> my_table = st.table(df1)
# >>> my_table.add_rows(df2)
# >>> my_chart = st.line_chart(df1)
# >>> my_chart.add_rows(df2)
# ''')
@st.cache
# ... def fetch_and_clean_data(url):
# ... # Mutate data at url
# ... return data
# >>> # Executes d1 as first time
# >>> d1 = fetch_and_clean_data(ref1)
# >>> # Does not execute d1; returns cached value, d1==d2
# >>> d2 = fetch_and_clean_data(ref1)
# >>> # Different arg, so function d1 executes
# >>> d3 = fetch_and_clean_data(ref2)
# ''')
# <small>[State API](https://docs.streamlit.io/en/stable/session_state_api.html)</small><br>
# <small>[Theme option reference](https://docs.streamlit.io/en/stable/theme_options.html)</small><br>
# <small>[Components API reference](https://docs.streamlit.io/en/stable/develop_streamlit_components.html)</small><br>
# <small>[API cheat sheet](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py)</small><br>
# ''', unsafe_allow_html=True)
def app():
cs_body()
return None
| true | true |
f727ee1e7b53a6244678c9e08fe4eea5eec42c76 | 509 | py | Python | src/waldur_ansible/playbook_jobs/extension.py | opennode/waldur-ansible | c81c5f0491be02fa9a55a6d5bf9d845750fd1ba9 | [
"MIT"
] | 1 | 2017-09-05T08:09:47.000Z | 2017-09-05T08:09:47.000Z | src/waldur_ansible/playbook_jobs/extension.py | opennode/waldur-ansible | c81c5f0491be02fa9a55a6d5bf9d845750fd1ba9 | [
"MIT"
] | null | null | null | src/waldur_ansible/playbook_jobs/extension.py | opennode/waldur-ansible | c81c5f0491be02fa9a55a6d5bf9d845750fd1ba9 | [
"MIT"
] | 3 | 2017-09-24T03:13:19.000Z | 2018-08-12T07:44:38.000Z | from waldur_core.core import WaldurExtension
class PlaybookJobsExtension(WaldurExtension):
class Settings:
WALDUR_PLAYBOOK_JOBS = {
'PLAYBOOKS_DIR_NAME': 'ansible_playbooks',
'PLAYBOOK_ICON_SIZE': (64, 64),
}
@staticmethod
def django_app():
return 'waldur_ansible.playbook_jobs'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
@staticmethod
def is_assembly():
return True
| 22.130435 | 54 | 0.650295 | from waldur_core.core import WaldurExtension
class PlaybookJobsExtension(WaldurExtension):
class Settings:
WALDUR_PLAYBOOK_JOBS = {
'PLAYBOOKS_DIR_NAME': 'ansible_playbooks',
'PLAYBOOK_ICON_SIZE': (64, 64),
}
@staticmethod
def django_app():
return 'waldur_ansible.playbook_jobs'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
@staticmethod
def is_assembly():
return True
| true | true |
f727eea3db865e0f61cecbb74cf9356d9badf3b1 | 558 | py | Python | pythonaem/error.py | mbloch1986/pythonaem | ce3ac1cb045a3cae912e7a76148130f645f61b91 | [
"Apache-2.0"
] | 3 | 2017-09-18T18:02:42.000Z | 2021-05-19T06:47:46.000Z | pythonaem/error.py | mbloch1986/pythonaem | ce3ac1cb045a3cae912e7a76148130f645f61b91 | [
"Apache-2.0"
] | 1 | 2021-05-19T01:49:04.000Z | 2021-05-19T01:49:04.000Z | pythonaem/error.py | mbloch1986/pythonaem | ce3ac1cb045a3cae912e7a76148130f645f61b91 | [
"Apache-2.0"
] | 5 | 2017-07-13T11:31:38.000Z | 2021-05-19T01:12:47.000Z | """
PythonAEM error, contains a message and PythonAEM Result object
"""
class Error(RuntimeError):
"""
PythonAEM error, contains a message and PythonAEM Result object
useful for debugging the result and response when an error occurs
"""
def __init__(self, message, result):
"""
Initialise a result.
:param message: result message
:param resi;t: PythonAEM Result
:return PythonAEM Error instance
"""
super().__init__()
self.message = message
self.result = result
| 24.26087 | 69 | 0.636201 |
class Error(RuntimeError):
def __init__(self, message, result):
super().__init__()
self.message = message
self.result = result
| true | true |
f727eee784d7ad52a67a2cd8eda72f4b1d6284ef | 407 | py | Python | app/run/migrations/0015_alter_run_pipeline_command.py | Masado/django-app-api-3 | 88def27f1cd8974c62dead282cd04d1384054888 | [
"MIT"
] | null | null | null | app/run/migrations/0015_alter_run_pipeline_command.py | Masado/django-app-api-3 | 88def27f1cd8974c62dead282cd04d1384054888 | [
"MIT"
] | null | null | null | app/run/migrations/0015_alter_run_pipeline_command.py | Masado/django-app-api-3 | 88def27f1cd8974c62dead282cd04d1384054888 | [
"MIT"
] | null | null | null | # Generated by Django 3.2.9 on 2021-11-25 10:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('run', '0014_run_duration'),
]
operations = [
migrations.AlterField(
model_name='run',
name='pipeline_command',
field=models.CharField(blank=True, max_length=600, null=True),
),
]
| 21.421053 | 74 | 0.604423 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('run', '0014_run_duration'),
]
operations = [
migrations.AlterField(
model_name='run',
name='pipeline_command',
field=models.CharField(blank=True, max_length=600, null=True),
),
]
| true | true |
f727ef6eba35c3692bfb36895da54e014a64bb23 | 5,955 | py | Python | Footsites/Footlocker/FootlockerAUMonitor.py | CaioAugustoo/Sneaker-Monitors | b65dbcf549727112dae7b3ed3861a86c7d53dd8a | [
"MIT"
] | 1 | 2021-09-08T16:11:31.000Z | 2021-09-08T16:11:31.000Z | Footsites/Footlocker/FootlockerAUMonitor.py | CaioAugustoo/Sneaker-Monitors | b65dbcf549727112dae7b3ed3861a86c7d53dd8a | [
"MIT"
] | null | null | null | Footsites/Footlocker/FootlockerAUMonitor.py | CaioAugustoo/Sneaker-Monitors | b65dbcf549727112dae7b3ed3861a86c7d53dd8a | [
"MIT"
] | 1 | 2022-02-22T11:42:52.000Z | 2022-02-22T11:42:52.000Z | # No restocks, only releases
import requests
from datetime import datetime
import json
from bs4 import BeautifulSoup
import urllib3
import time
import logging
import dotenv
from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, HardwareType
from fp.fp import FreeProxy
logging.basicConfig(filename='Footlockerlog.log', filemode='a', format='%(asctime)s - %(name)s - %(message)s', level=logging.DEBUG)
software_names = [SoftwareName.CHROME.value]
hardware_type = [HardwareType.MOBILE__PHONE]
user_agent_rotator = UserAgent(software_names=software_names, hardware_type=hardware_type)
CONFIG = dotenv.dotenv_values()
proxyObject = FreeProxy(country_id=['AU'], rand=True)
INSTOCK = []
def test_webhook():
data = {
"username": CONFIG['USERNAME'],
"avatar_url": CONFIG['AVATAR_URL'],
"embeds": [{
"title": "Testing Webhook",
"description": "This is just a quick test to ensure the webhook works. Thanks again for using these montiors!",,
"color": int(CONFIG['COLOUR']),
"footer": {'text': 'Made by Yasser'},
"timestamp": str(datetime.datetime.utcnow())
}]
}
result = rq.post(CONFIG['WEBHOOK'], data=json.dumps(data), headers={"Content-Type": "application/json"})
try:
result.raise_for_status()
except rq.exceptions.HTTPError as err:
logging.error(err)
else:
print("Payload delivered successfully, code {}.".format(result.status_code))
logging.info(msg="Payload delivered successfully, code {}.".format(result.status_code))
def discord_webhook(title, thumbnail, url, price, colour):
"""
Sends a Discord webhook notification to the specified webhook URL
"""
data = {
"username": CONFIG['USERNAME'],
"avatar_url": CONFIG['AVATAR_URL'],
"embeds": [{
"title": title,
"thumbnail": {"url": thumbnail},
"url": f'https://www.footlocker.ca{url}'
"color": int(CONFIG['COLOUR']),
"footer": {'text': 'Made by Yasser'},
"timestamp": str(datetime.utcnow())
"fields": [
{"name": "Colour", "value": colour},
{"name": "Price": "value": price}
]
}]
}
result = requests.post(CONFIG['WEBHOOK'], data=json.dumps(data), headers={"Content-Type": "application/json"})
try:
result.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
logging.error(msg=err)
else:
print("Payload delivered successfully, code {}.".format(result.status_code))
logging.info("Payload delivered successfully, code {}.".format(result.status_code))
def checker(item):
"""
Determines whether the product status has changed
"""
for product in INSTOCK:
if product == item:
return True
return False
def scrape_main_site(headers, proxy):
"""
Scrape the Footlocker site and adds each item to an array
"""
items = []
s = requests.Session()
url = 'https://www.footlocker.com.au/en/men/'
html = s.get(url=url, headers=headers, proxies=proxy, verify=False, timeout=10)
soup = BeautifulSoup(html.text, 'html.parser')
array = soup.find_all('div', {'class': 'fl-category--productlist--item'})
for i in array:
item = [i.find('span', {'class': 'ProductName-primary'}).text,
i.find('span', {'class': 'ProductName-alt'}).text.split(chr(8226))[0],
i.find('span', {'class': 'ProductName-alt'}).text.split(chr(8226))[1],
i.find('img')['src'],
i.find('a', {'class': 'ProductCard-link ProductCard-content'})['href']]
items.append(item)
logging.info(msg='Successfully scraped site')
s.close()
return items
def remove_duplicates(mylist):
"""
Removes duplicate values from a list
"""
return [list(t) for t in set(tuple(element) for element in mylist)]
def comparitor(item, start):
if checker(item):
pass
else:
INSTOCK.append(item)
if start == 0:
print(item)
discord_webhook(
title='',
thumbnail='',
url='',
price='',
colour=''
)
def monitor():
"""
Initiates monitor
"""
print('STARTING MONITOR')
logging.info(msg='Successfully started monitor')
test_webhook()
start = 1
proxy_no = 0
proxy_list = CONFIG['PROXY'].split('%')
proxy = {"http": proxyObject.get()} if proxy_list[0] == "" else {"http": f"http://{proxy_list[proxy_no]}"}
headers = {'User-Agent': user_agent_rotator.get_random_user_agent()}
keywords = CONFIG['KEYWORDS'].split('%')
while True:
try:
items = remove_duplicates(scrape_main_site(headers, proxy))
for item in items:
check = False
if keywords == "":
comparitor(item, start)
else:
for key in keywords:
if key.lower() in item[0].lower():
check = True
break
if check:
comparitor(item, start)
start = 0
time.sleep(float(CONFIG['WEBHOOK']))
except Exception as e:
print(f"Exception found '{e}' - Rotating proxy and user-agent")
logging.error(e)
headers = {'User-Agent': user_agent_rotator.get_random_user_agent()}
if CONFIG['PROXY'] == "":
proxy = {"http": proxyObject.get()}
else:
proxy_no = 0 if proxy_no == (len(proxy_list) - 1) else proxy_no + 1
proxy = {"http": f"http://{proxy_list[proxy_no]}"}
if __name__ == '__main__':
urllib3.disable_warnings()
monitor()
| 32.71978 | 131 | 0.580688 |
import requests
from datetime import datetime
import json
from bs4 import BeautifulSoup
import urllib3
import time
import logging
import dotenv
from random_user_agent.user_agent import UserAgent
from random_user_agent.params import SoftwareName, HardwareType
from fp.fp import FreeProxy
logging.basicConfig(filename='Footlockerlog.log', filemode='a', format='%(asctime)s - %(name)s - %(message)s', level=logging.DEBUG)
software_names = [SoftwareName.CHROME.value]
hardware_type = [HardwareType.MOBILE__PHONE]
user_agent_rotator = UserAgent(software_names=software_names, hardware_type=hardware_type)
CONFIG = dotenv.dotenv_values()
proxyObject = FreeProxy(country_id=['AU'], rand=True)
INSTOCK = []
def test_webhook():
data = {
"username": CONFIG['USERNAME'],
"avatar_url": CONFIG['AVATAR_URL'],
"embeds": [{
"title": "Testing Webhook",
"description": "This is just a quick test to ensure the webhook works. Thanks again for using these montiors!",,
"color": int(CONFIG['COLOUR']),
"footer": {'text': 'Made by Yasser'},
"timestamp": str(datetime.datetime.utcnow())
}]
}
result = rq.post(CONFIG['WEBHOOK'], data=json.dumps(data), headers={"Content-Type": "application/json"})
try:
result.raise_for_status()
except rq.exceptions.HTTPError as err:
logging.error(err)
else:
print("Payload delivered successfully, code {}.".format(result.status_code))
logging.info(msg="Payload delivered successfully, code {}.".format(result.status_code))
def discord_webhook(title, thumbnail, url, price, colour):
"""
Sends a Discord webhook notification to the specified webhook URL
"""
data = {
"username": CONFIG['USERNAME'],
"avatar_url": CONFIG['AVATAR_URL'],
"embeds": [{
"title": title,
"thumbnail": {"url": thumbnail},
"url": f'https://www.footlocker.ca{url}'
"color": int(CONFIG['COLOUR']),
"footer": {'text': 'Made by Yasser'},
"timestamp": str(datetime.utcnow())
"fields": [
{"name": "Colour", "value": colour},
{"name": "Price": "value": price}
]
}]
}
result = requests.post(CONFIG['WEBHOOK'], data=json.dumps(data), headers={"Content-Type": "application/json"})
try:
result.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)
logging.error(msg=err)
else:
print("Payload delivered successfully, code {}.".format(result.status_code))
logging.info("Payload delivered successfully, code {}.".format(result.status_code))
def checker(item):
"""
Determines whether the product status has changed
"""
for product in INSTOCK:
if product == item:
return True
return False
def scrape_main_site(headers, proxy):
"""
Scrape the Footlocker site and adds each item to an array
"""
items = []
s = requests.Session()
url = 'https://www.footlocker.com.au/en/men/'
html = s.get(url=url, headers=headers, proxies=proxy, verify=False, timeout=10)
soup = BeautifulSoup(html.text, 'html.parser')
array = soup.find_all('div', {'class': 'fl-category--productlist--item'})
for i in array:
item = [i.find('span', {'class': 'ProductName-primary'}).text,
i.find('span', {'class': 'ProductName-alt'}).text.split(chr(8226))[0],
i.find('span', {'class': 'ProductName-alt'}).text.split(chr(8226))[1],
i.find('img')['src'],
i.find('a', {'class': 'ProductCard-link ProductCard-content'})['href']]
items.append(item)
logging.info(msg='Successfully scraped site')
s.close()
return items
def remove_duplicates(mylist):
"""
Removes duplicate values from a list
"""
return [list(t) for t in set(tuple(element) for element in mylist)]
def comparitor(item, start):
if checker(item):
pass
else:
INSTOCK.append(item)
if start == 0:
print(item)
discord_webhook(
title='',
thumbnail='',
url='',
price='',
colour=''
)
def monitor():
"""
Initiates monitor
"""
print('STARTING MONITOR')
logging.info(msg='Successfully started monitor')
test_webhook()
start = 1
proxy_no = 0
proxy_list = CONFIG['PROXY'].split('%')
proxy = {"http": proxyObject.get()} if proxy_list[0] == "" else {"http": f"http://{proxy_list[proxy_no]}"}
headers = {'User-Agent': user_agent_rotator.get_random_user_agent()}
keywords = CONFIG['KEYWORDS'].split('%')
while True:
try:
items = remove_duplicates(scrape_main_site(headers, proxy))
for item in items:
check = False
if keywords == "":
comparitor(item, start)
else:
for key in keywords:
if key.lower() in item[0].lower():
check = True
break
if check:
comparitor(item, start)
start = 0
time.sleep(float(CONFIG['WEBHOOK']))
except Exception as e:
print(f"Exception found '{e}' - Rotating proxy and user-agent")
logging.error(e)
headers = {'User-Agent': user_agent_rotator.get_random_user_agent()}
if CONFIG['PROXY'] == "":
proxy = {"http": proxyObject.get()}
else:
proxy_no = 0 if proxy_no == (len(proxy_list) - 1) else proxy_no + 1
proxy = {"http": f"http://{proxy_list[proxy_no]}"}
if __name__ == '__main__':
urllib3.disable_warnings()
monitor()
| false | true |
f727f0ca02c8ddd7cc426b246a89148e585b2b62 | 1,181 | py | Python | daemon/examples/api/switch_inject.py | shanv82/core | 70abb8cc1426ffceb53a03e84edc26f56f9ed4c0 | [
"BSD-2-Clause"
] | null | null | null | daemon/examples/api/switch_inject.py | shanv82/core | 70abb8cc1426ffceb53a03e84edc26f56f9ed4c0 | [
"BSD-2-Clause"
] | null | null | null | daemon/examples/api/switch_inject.py | shanv82/core | 70abb8cc1426ffceb53a03e84edc26f56f9ed4c0 | [
"BSD-2-Clause"
] | null | null | null | #!/usr/bin/python
#
# run iperf to measure the effective throughput between two nodes when
# n nodes are connected to a virtual wlan; run test for testsec
# and repeat for minnodes <= n <= maxnodes with a step size of
# nodestep
from core import load_logging_config
from core.emulator.emudata import IpPrefixes
from core.enumerations import NodeTypes, EventTypes
load_logging_config()
def example(nodes):
# ip generator for example
prefixes = IpPrefixes("10.83.0.0/16")
# create emulator instance for creating sessions and utility methods
coreemu = globals()["coreemu"]
session = coreemu.create_session()
# must be in configuration state for nodes to start, when using "node_add" below
session.set_state(EventTypes.CONFIGURATION_STATE)
# create switch network node
switch = session.add_node(_type=NodeTypes.SWITCH)
# create nodes
for _ in xrange(nodes):
node = session.add_node()
interface = prefixes.create_interface(node)
session.add_link(node.objid, switch.objid, interface_one=interface)
# instantiate session
session.instantiate()
if __name__ in {"__main__", "__builtin__"}:
example(2)
| 29.525 | 84 | 0.731583 |
from core import load_logging_config
from core.emulator.emudata import IpPrefixes
from core.enumerations import NodeTypes, EventTypes
load_logging_config()
def example(nodes):
prefixes = IpPrefixes("10.83.0.0/16")
coreemu = globals()["coreemu"]
session = coreemu.create_session()
session.set_state(EventTypes.CONFIGURATION_STATE)
switch = session.add_node(_type=NodeTypes.SWITCH)
for _ in xrange(nodes):
node = session.add_node()
interface = prefixes.create_interface(node)
session.add_link(node.objid, switch.objid, interface_one=interface)
session.instantiate()
if __name__ in {"__main__", "__builtin__"}:
example(2)
| true | true |
f727f10e73f0dd4907a634b339ec124db37c3bc9 | 20,980 | py | Python | makepanda/makewheel.py | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | makepanda/makewheel.py | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | makepanda/makewheel.py | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | """
Generates a wheel (.whl) file from the output of makepanda.
Since the wheel requires special linking, this will only work if compiled with
the `--wheel` parameter.
Please keep this file work with Panda3D 1.9 until that reaches EOL.
"""
from __future__ import print_function, unicode_literals
from distutils.util import get_platform
import json
import sys
import os
from os.path import join
import shutil
import zipfile
import hashlib
import tempfile
import subprocess
from distutils.sysconfig import get_config_var
from optparse import OptionParser
from makepandacore import ColorText, LocateBinary, ParsePandaVersion, GetExtensionSuffix, SetVerbose, GetVerbose, GetMetadataValue
from base64 import urlsafe_b64encode
default_platform = get_platform()
if default_platform.startswith("linux-"):
# Is this manylinux1?
if os.path.isfile("/lib/libc-2.5.so") and os.path.isdir("/opt/python"):
default_platform = default_platform.replace("linux", "manylinux1")
def get_abi_tag():
if sys.version_info >= (3, 0):
soabi = get_config_var('SOABI')
if soabi and soabi.startswith('cpython-'):
return 'cp' + soabi.split('-')[1]
elif soabi:
return soabi.replace('.', '_').replace('-', '_')
soabi = 'cp%d%d' % (sys.version_info[:2])
debug_flag = get_config_var('Py_DEBUG')
if (debug_flag is None and hasattr(sys, 'gettotalrefcount')) or debug_flag:
soabi += 'd'
malloc_flag = get_config_var('WITH_PYMALLOC')
if malloc_flag is None or malloc_flag:
soabi += 'm'
if sys.version_info < (3, 3):
usize = get_config_var('Py_UNICODE_SIZE')
if (usize is None and sys.maxunicode == 0x10ffff) or usize == 4:
soabi += 'u'
return soabi
def is_exe_file(path):
return os.path.isfile(path) and path.lower().endswith('.exe')
def is_elf_file(path):
base = os.path.basename(path)
return os.path.isfile(path) and '.' not in base and \
open(path, 'rb').read(4) == b'\x7FELF'
def is_mach_o_file(path):
base = os.path.basename(path)
return os.path.isfile(path) and '.' not in base and \
open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\bCA',
b'\xFE\xED\xFA\xCE', b'\xCE\xFA\xED\xFE',
b'\xFE\xED\xFA\xCF', b'\xCF\xFA\xED\xFE')
def is_fat_file(path):
return os.path.isfile(path) and \
open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\bCA')
if sys.platform in ('win32', 'cygwin'):
is_executable = is_exe_file
elif sys.platform == 'darwin':
is_executable = is_mach_o_file
else:
is_executable = is_elf_file
# Other global parameters
PY_VERSION = "cp{0}{1}".format(*sys.version_info)
ABI_TAG = get_abi_tag()
EXCLUDE_EXT = [".pyc", ".pyo", ".N", ".prebuilt", ".xcf", ".plist", ".vcproj", ".sln"]
# Plug-ins to install.
PLUGIN_LIBS = ["pandagl", "pandagles", "pandagles2", "pandadx9", "p3tinydisplay", "p3ptloader", "p3assimp", "p3ffmpeg", "p3openal_audio", "p3fmod_audio"]
WHEEL_DATA = """Wheel-Version: 1.0
Generator: makepanda
Root-Is-Purelib: false
Tag: {0}-{1}-{2}
"""
METADATA = {
"license": GetMetadataValue('license'),
"name": GetMetadataValue('name'),
"metadata_version": "2.0",
"generator": "makepanda",
"summary": GetMetadataValue('description'),
"extensions": {
"python.details": {
"project_urls": {
"Home": GetMetadataValue('url'),
},
"document_names": {
"license": "LICENSE.txt"
},
"contacts": [
{
"role": "author",
"name": GetMetadataValue('author'),
"email": GetMetadataValue('author_email'),
}
]
}
},
"classifiers": GetMetadataValue('classifiers'),
}
PANDA3D_TOOLS_INIT = """import os, sys
import panda3d
if sys.platform in ('win32', 'cygwin'):
path_var = 'PATH'
elif sys.platform == 'darwin':
path_var = 'DYLD_LIBRARY_PATH'
else:
path_var = 'LD_LIBRARY_PATH'
dir = os.path.dirname(panda3d.__file__)
del panda3d
if not os.environ.get(path_var):
os.environ[path_var] = dir
else:
os.environ[path_var] = dir + os.pathsep + os.environ[path_var]
del os, sys, path_var, dir
def _exec_tool(tool):
import os, sys
from subprocess import Popen
tools_dir = os.path.dirname(__file__)
handle = Popen(sys.argv, executable=os.path.join(tools_dir, tool))
try:
try:
return handle.wait()
except KeyboardInterrupt:
# Give the program a chance to handle the signal gracefully.
return handle.wait()
except:
handle.kill()
handle.wait()
raise
# Register all the executables in this directory as global functions.
{0}
"""
def parse_dependencies_windows(data):
""" Parses the given output from dumpbin /dependents to determine the list
of dll's this executable file depends on. """
lines = data.splitlines()
li = 0
while li < len(lines):
line = lines[li]
li += 1
if line.find(' has the following dependencies') != -1:
break
if li < len(lines):
line = lines[li]
if line.strip() == '':
# Skip a blank line.
li += 1
# Now we're finding filenames, until the next blank line.
filenames = []
while li < len(lines):
line = lines[li]
li += 1
line = line.strip()
if line == '':
# We're done.
return filenames
filenames.append(line)
# At least we got some data.
return filenames
def parse_dependencies_unix(data):
""" Parses the given output from otool -XL or ldd to determine the list of
libraries this executable file depends on. """
lines = data.splitlines()
filenames = []
for l in lines:
l = l.strip()
if l != "statically linked":
filenames.append(l.split(' ', 1)[0])
return filenames
def scan_dependencies(pathname):
""" Checks the named file for DLL dependencies, and adds any appropriate
dependencies found into pluginDependencies and dependentFiles. """
if sys.platform == "darwin":
command = ['otool', '-XL', pathname]
elif sys.platform in ("win32", "cygwin"):
command = ['dumpbin', '/dependents', pathname]
else:
command = ['ldd', pathname]
process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
raise subprocess.CalledProcessError(retcode, command[0], output=output)
filenames = None
if sys.platform in ("win32", "cygwin"):
filenames = parse_dependencies_windows(output)
else:
filenames = parse_dependencies_unix(output)
if filenames is None:
sys.exit("Unable to determine dependencies from %s" % (pathname))
if sys.platform == "darwin" and len(filenames) > 0:
# Filter out the library ID.
if os.path.basename(filenames[0]).split('.', 1)[0] == os.path.basename(pathname).split('.', 1)[0]:
del filenames[0]
return filenames
class WheelFile(object):
def __init__(self, name, version, platform):
self.name = name
self.version = version
self.platform = platform
wheel_name = "{0}-{1}-{2}-{3}-{4}.whl".format(
name, version, PY_VERSION, ABI_TAG, platform)
print("Writing %s" % (wheel_name))
self.zip_file = zipfile.ZipFile(wheel_name, 'w', zipfile.ZIP_DEFLATED)
self.records = []
# Used to locate dependency libraries.
self.lib_path = []
self.dep_paths = {}
def consider_add_dependency(self, target_path, dep, search_path=None):
"""Considers adding a dependency library.
Returns the target_path if it was added, which may be different from
target_path if it was already added earlier, or None if it wasn't."""
if dep in self.dep_paths:
# Already considered this.
return self.dep_paths[dep]
self.dep_paths[dep] = None
if dep.lower().startswith("python") or os.path.basename(dep).startswith("libpython"):
# Don't include the Python library.
return
if sys.platform == "darwin" and dep.endswith(".so"):
# Temporary hack for 1.9, which had link deps on modules.
return
source_path = None
if search_path is None:
search_path = self.lib_path
for lib_dir in search_path:
# Ignore static stuff.
path = os.path.join(lib_dir, dep)
if os.path.isfile(path):
source_path = os.path.normpath(path)
break
if not source_path:
# Couldn't find library in the panda3d lib dir.
#print("Ignoring %s" % (dep))
return
self.dep_paths[dep] = target_path
self.write_file(target_path, source_path)
return target_path
def write_file(self, target_path, source_path):
"""Adds the given file to the .whl file."""
# If this is a .so file, we should set the rpath appropriately.
temp = None
ext = os.path.splitext(source_path)[1]
if ext in ('.so', '.dylib') or '.so.' in os.path.basename(source_path) or \
(not ext and is_executable(source_path)):
# Scan and add Unix dependencies.
deps = scan_dependencies(source_path)
for dep in deps:
# Only include dependencies with relative path. Otherwise we
# end up overwriting system files like /lib/ld-linux.so.2!
# Yes, it happened to me.
if '/' not in dep:
target_dep = os.path.dirname(target_path) + '/' + dep
self.consider_add_dependency(target_dep, dep)
suffix = ''
if '.so' in os.path.basename(source_path):
suffix = '.so'
elif ext == '.dylib':
suffix = '.dylib'
temp = tempfile.NamedTemporaryFile(suffix=suffix, prefix='whl', delete=False)
# On macOS, if no fat wheel was requested, extract the right architecture.
if sys.platform == "darwin" and is_fat_file(source_path) and not self.platform.endswith("_intel"):
if self.platform.endswith("_x86_64"):
arch = 'x86_64'
else:
arch = self.platform.split('_')[-1]
subprocess.call(['lipo', source_path, '-extract', arch, '-output', temp.name])
else:
# Otherwise, just copy it over.
temp.write(open(source_path, 'rb').read())
os.fchmod(temp.fileno(), os.fstat(temp.fileno()).st_mode | 0o111)
temp.close()
# Fix things like @loader_path/../lib references
if sys.platform == "darwin":
loader_path = [os.path.dirname(source_path)]
for dep in deps:
if '@loader_path' not in dep:
continue
dep_path = dep.replace('@loader_path', '.')
target_dep = os.path.dirname(target_path) + '/' + os.path.basename(dep)
target_dep = self.consider_add_dependency(target_dep, dep_path, loader_path)
if not target_dep:
# It won't be included, so no use adjusting the path.
continue
new_dep = os.path.join('@loader_path', os.path.relpath(target_dep, os.path.dirname(target_path)))
subprocess.call(["install_name_tool", "-change", dep, new_dep, temp.name])
else:
subprocess.call(["strip", "-s", temp.name])
subprocess.call(["patchelf", "--set-rpath", "$ORIGIN", temp.name])
source_path = temp.name
ext = ext.lower()
if ext in ('.dll', '.pyd', '.exe'):
# Scan and add Win32 dependencies.
for dep in scan_dependencies(source_path):
target_dep = os.path.dirname(target_path) + '/' + dep
self.consider_add_dependency(target_dep, dep)
# Calculate the SHA-256 hash and size.
sha = hashlib.sha256()
fp = open(source_path, 'rb')
size = 0
data = fp.read(1024 * 1024)
while data:
size += len(data)
sha.update(data)
data = fp.read(1024 * 1024)
fp.close()
# Save it in PEP-0376 format for writing out later.
digest = urlsafe_b64encode(sha.digest()).decode('ascii')
digest = digest.rstrip('=')
self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, size))
if GetVerbose():
print("Adding %s from %s" % (target_path, source_path))
self.zip_file.write(source_path, target_path)
#if temp:
# os.unlink(temp.name)
def write_file_data(self, target_path, source_data):
"""Adds the given file from a string."""
sha = hashlib.sha256()
sha.update(source_data.encode())
digest = urlsafe_b64encode(sha.digest()).decode('ascii')
digest = digest.rstrip('=')
self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, len(source_data)))
if GetVerbose():
print("Adding %s from data" % target_path)
self.zip_file.writestr(target_path, source_data)
def write_directory(self, target_dir, source_dir):
"""Adds the given directory recursively to the .whl file."""
for root, dirs, files in os.walk(source_dir):
for file in files:
if os.path.splitext(file)[1] in EXCLUDE_EXT:
continue
source_path = os.path.join(root, file)
target_path = os.path.join(target_dir, os.path.relpath(source_path, source_dir))
target_path = target_path.replace('\\', '/')
self.write_file(target_path, source_path)
def close(self):
# Write the RECORD file.
record_file = "{0}-{1}.dist-info/RECORD".format(self.name, self.version)
self.records.append(record_file + ",,\n")
self.zip_file.writestr(record_file, "".join(self.records))
self.zip_file.close()
def makewheel(version, output_dir, platform=default_platform):
if sys.platform not in ("win32", "darwin") and not sys.platform.startswith("cygwin"):
if not LocateBinary("patchelf"):
raise Exception("patchelf is required when building a Linux wheel.")
platform = platform.replace('-', '_').replace('.', '_')
# Global filepaths
panda3d_dir = join(output_dir, "panda3d")
pandac_dir = join(output_dir, "pandac")
direct_dir = join(output_dir, "direct")
models_dir = join(output_dir, "models")
etc_dir = join(output_dir, "etc")
bin_dir = join(output_dir, "bin")
if sys.platform == "win32":
libs_dir = join(output_dir, "bin")
else:
libs_dir = join(output_dir, "lib")
license_src = "LICENSE"
readme_src = "README.md"
# Update relevant METADATA entries
METADATA['version'] = version
version_classifiers = [
"Programming Language :: Python :: {0}".format(*sys.version_info),
"Programming Language :: Python :: {0}.{1}".format(*sys.version_info),
]
METADATA['classifiers'].extend(version_classifiers)
# Build out the metadata
details = METADATA["extensions"]["python.details"]
homepage = details["project_urls"]["Home"]
author = details["contacts"][0]["name"]
email = details["contacts"][0]["email"]
metadata = ''.join([
"Metadata-Version: {metadata_version}\n" \
"Name: {name}\n" \
"Version: {version}\n" \
"Summary: {summary}\n" \
"License: {license}\n".format(**METADATA),
"Home-page: {0}\n".format(homepage),
"Author: {0}\n".format(author),
"Author-email: {0}\n".format(email),
"Platform: {0}\n".format(platform),
] + ["Classifier: {0}\n".format(c) for c in METADATA['classifiers']])
# Zip it up and name it the right thing
whl = WheelFile('panda3d', version, platform)
whl.lib_path = [libs_dir]
# Add the trees with Python modules.
whl.write_directory('direct', direct_dir)
# Write the panda3d tree. We use a custom empty __init__ since the
# default one adds the bin directory to the PATH, which we don't have.
whl.write_file_data('panda3d/__init__.py', '')
ext_suffix = GetExtensionSuffix()
for file in os.listdir(panda3d_dir):
if file == '__init__.py':
pass
elif file.endswith(ext_suffix) or file.endswith('.py'):
source_path = os.path.join(panda3d_dir, file)
if file.endswith('.pyd') and platform.startswith('cygwin'):
# Rename it to .dll for cygwin Python to be able to load it.
target_path = 'panda3d/' + os.path.splitext(file)[0] + '.dll'
else:
target_path = 'panda3d/' + file
whl.write_file(target_path, source_path)
# Add plug-ins.
for lib in PLUGIN_LIBS:
plugin_name = 'lib' + lib
if sys.platform in ('win32', 'cygwin'):
plugin_name += '.dll'
elif sys.platform == 'darwin':
plugin_name += '.dylib'
else:
plugin_name += '.so'
plugin_path = os.path.join(libs_dir, plugin_name)
if os.path.isfile(plugin_path):
whl.write_file('panda3d/' + plugin_name, plugin_path)
# Add the .data directory, containing additional files.
data_dir = 'panda3d-{0}.data'.format(version)
#whl.write_directory(data_dir + '/data/etc', etc_dir)
#whl.write_directory(data_dir + '/data/models', models_dir)
# Actually, let's not. That seems to install the files to the strangest
# places in the user's filesystem. Let's instead put them in panda3d.
whl.write_directory('panda3d/etc', etc_dir)
whl.write_directory('panda3d/models', models_dir)
# Add the pandac tree for backward compatibility.
for file in os.listdir(pandac_dir):
if file.endswith('.py'):
whl.write_file('pandac/' + file, os.path.join(pandac_dir, file))
# Add a panda3d-tools directory containing the executables.
entry_points = '[console_scripts]\n'
entry_points += 'eggcacher = direct.directscripts.eggcacher:main\n'
entry_points += 'pfreeze = direct.showutil.pfreeze:main\n'
tools_init = ''
for file in os.listdir(bin_dir):
basename = os.path.splitext(file)[0]
if basename in ('eggcacher', 'packpanda'):
continue
source_path = os.path.join(bin_dir, file)
if is_executable(source_path):
# Put the .exe files inside the panda3d-tools directory.
whl.write_file('panda3d_tools/' + file, source_path)
# Tell pip to create a wrapper script.
funcname = basename.replace('-', '_')
entry_points += '{0} = panda3d_tools:{1}\n'.format(basename, funcname)
tools_init += '{0} = lambda: _exec_tool({1!r})\n'.format(funcname, file)
whl.write_file_data('panda3d_tools/__init__.py', PANDA3D_TOOLS_INIT.format(tools_init))
# Add the dist-info directory last.
info_dir = 'panda3d-{0}.dist-info'.format(version)
whl.write_file_data(info_dir + '/entry_points.txt', entry_points)
whl.write_file_data(info_dir + '/metadata.json', json.dumps(METADATA, indent=4, separators=(',', ': ')))
whl.write_file_data(info_dir + '/METADATA', metadata)
whl.write_file_data(info_dir + '/WHEEL', WHEEL_DATA.format(PY_VERSION, ABI_TAG, platform))
whl.write_file(info_dir + '/LICENSE.txt', license_src)
whl.write_file(info_dir + '/README.md', readme_src)
whl.write_file_data(info_dir + '/top_level.txt', 'direct\npanda3d\npandac\npanda3d_tools\n')
whl.close()
if __name__ == "__main__":
version = ParsePandaVersion("dtool/PandaVersion.pp")
parser = OptionParser()
parser.add_option('', '--version', dest = 'version', help = 'Panda3D version number (default: %s)' % (version), default = version)
parser.add_option('', '--outputdir', dest = 'outputdir', help = 'Makepanda\'s output directory (default: built)', default = 'built')
parser.add_option('', '--verbose', dest = 'verbose', help = 'Enable verbose output', action = 'store_true', default = False)
parser.add_option('', '--platform', dest = 'platform', help = 'Override platform tag (default: %s)' % (default_platform), default = get_platform())
(options, args) = parser.parse_args()
SetVerbose(options.verbose)
makewheel(options.version, options.outputdir, options.platform)
| 35.863248 | 153 | 0.60715 | from __future__ import print_function, unicode_literals
from distutils.util import get_platform
import json
import sys
import os
from os.path import join
import shutil
import zipfile
import hashlib
import tempfile
import subprocess
from distutils.sysconfig import get_config_var
from optparse import OptionParser
from makepandacore import ColorText, LocateBinary, ParsePandaVersion, GetExtensionSuffix, SetVerbose, GetVerbose, GetMetadataValue
from base64 import urlsafe_b64encode
default_platform = get_platform()
if default_platform.startswith("linux-"):
if os.path.isfile("/lib/libc-2.5.so") and os.path.isdir("/opt/python"):
default_platform = default_platform.replace("linux", "manylinux1")
def get_abi_tag():
if sys.version_info >= (3, 0):
soabi = get_config_var('SOABI')
if soabi and soabi.startswith('cpython-'):
return 'cp' + soabi.split('-')[1]
elif soabi:
return soabi.replace('.', '_').replace('-', '_')
soabi = 'cp%d%d' % (sys.version_info[:2])
debug_flag = get_config_var('Py_DEBUG')
if (debug_flag is None and hasattr(sys, 'gettotalrefcount')) or debug_flag:
soabi += 'd'
malloc_flag = get_config_var('WITH_PYMALLOC')
if malloc_flag is None or malloc_flag:
soabi += 'm'
if sys.version_info < (3, 3):
usize = get_config_var('Py_UNICODE_SIZE')
if (usize is None and sys.maxunicode == 0x10ffff) or usize == 4:
soabi += 'u'
return soabi
def is_exe_file(path):
return os.path.isfile(path) and path.lower().endswith('.exe')
def is_elf_file(path):
base = os.path.basename(path)
return os.path.isfile(path) and '.' not in base and \
open(path, 'rb').read(4) == b'\x7FELF'
def is_mach_o_file(path):
base = os.path.basename(path)
return os.path.isfile(path) and '.' not in base and \
open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\bCA',
b'\xFE\xED\xFA\xCE', b'\xCE\xFA\xED\xFE',
b'\xFE\xED\xFA\xCF', b'\xCF\xFA\xED\xFE')
def is_fat_file(path):
return os.path.isfile(path) and \
open(path, 'rb').read(4) in (b'\xCA\xFE\xBA\xBE', b'\xBE\xBA\xFE\bCA')
if sys.platform in ('win32', 'cygwin'):
is_executable = is_exe_file
elif sys.platform == 'darwin':
is_executable = is_mach_o_file
else:
is_executable = is_elf_file
PY_VERSION = "cp{0}{1}".format(*sys.version_info)
ABI_TAG = get_abi_tag()
EXCLUDE_EXT = [".pyc", ".pyo", ".N", ".prebuilt", ".xcf", ".plist", ".vcproj", ".sln"]
PLUGIN_LIBS = ["pandagl", "pandagles", "pandagles2", "pandadx9", "p3tinydisplay", "p3ptloader", "p3assimp", "p3ffmpeg", "p3openal_audio", "p3fmod_audio"]
WHEEL_DATA = """Wheel-Version: 1.0
Generator: makepanda
Root-Is-Purelib: false
Tag: {0}-{1}-{2}
"""
METADATA = {
"license": GetMetadataValue('license'),
"name": GetMetadataValue('name'),
"metadata_version": "2.0",
"generator": "makepanda",
"summary": GetMetadataValue('description'),
"extensions": {
"python.details": {
"project_urls": {
"Home": GetMetadataValue('url'),
},
"document_names": {
"license": "LICENSE.txt"
},
"contacts": [
{
"role": "author",
"name": GetMetadataValue('author'),
"email": GetMetadataValue('author_email'),
}
]
}
},
"classifiers": GetMetadataValue('classifiers'),
}
PANDA3D_TOOLS_INIT = """import os, sys
import panda3d
if sys.platform in ('win32', 'cygwin'):
path_var = 'PATH'
elif sys.platform == 'darwin':
path_var = 'DYLD_LIBRARY_PATH'
else:
path_var = 'LD_LIBRARY_PATH'
dir = os.path.dirname(panda3d.__file__)
del panda3d
if not os.environ.get(path_var):
os.environ[path_var] = dir
else:
os.environ[path_var] = dir + os.pathsep + os.environ[path_var]
del os, sys, path_var, dir
def _exec_tool(tool):
import os, sys
from subprocess import Popen
tools_dir = os.path.dirname(__file__)
handle = Popen(sys.argv, executable=os.path.join(tools_dir, tool))
try:
try:
return handle.wait()
except KeyboardInterrupt:
# Give the program a chance to handle the signal gracefully.
return handle.wait()
except:
handle.kill()
handle.wait()
raise
# Register all the executables in this directory as global functions.
{0}
"""
def parse_dependencies_windows(data):
lines = data.splitlines()
li = 0
while li < len(lines):
line = lines[li]
li += 1
if line.find(' has the following dependencies') != -1:
break
if li < len(lines):
line = lines[li]
if line.strip() == '':
li += 1
filenames = []
while li < len(lines):
line = lines[li]
li += 1
line = line.strip()
if line == '':
# We're done.
return filenames
filenames.append(line)
return filenames
def parse_dependencies_unix(data):
lines = data.splitlines()
filenames = []
for l in lines:
l = l.strip()
if l != "statically linked":
filenames.append(l.split(' ', 1)[0])
return filenames
def scan_dependencies(pathname):
if sys.platform == "darwin":
command = ['otool', '-XL', pathname]
elif sys.platform in ("win32", "cygwin"):
command = ['dumpbin', '/dependents', pathname]
else:
command = ['ldd', pathname]
process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
raise subprocess.CalledProcessError(retcode, command[0], output=output)
filenames = None
if sys.platform in ("win32", "cygwin"):
filenames = parse_dependencies_windows(output)
else:
filenames = parse_dependencies_unix(output)
if filenames is None:
sys.exit("Unable to determine dependencies from %s" % (pathname))
if sys.platform == "darwin" and len(filenames) > 0:
if os.path.basename(filenames[0]).split('.', 1)[0] == os.path.basename(pathname).split('.', 1)[0]:
del filenames[0]
return filenames
class WheelFile(object):
def __init__(self, name, version, platform):
self.name = name
self.version = version
self.platform = platform
wheel_name = "{0}-{1}-{2}-{3}-{4}.whl".format(
name, version, PY_VERSION, ABI_TAG, platform)
print("Writing %s" % (wheel_name))
self.zip_file = zipfile.ZipFile(wheel_name, 'w', zipfile.ZIP_DEFLATED)
self.records = []
self.lib_path = []
self.dep_paths = {}
def consider_add_dependency(self, target_path, dep, search_path=None):
if dep in self.dep_paths:
return self.dep_paths[dep]
self.dep_paths[dep] = None
if dep.lower().startswith("python") or os.path.basename(dep).startswith("libpython"):
return
if sys.platform == "darwin" and dep.endswith(".so"):
# Temporary hack for 1.9, which had link deps on modules.
return
source_path = None
if search_path is None:
search_path = self.lib_path
for lib_dir in search_path:
# Ignore static stuff.
path = os.path.join(lib_dir, dep)
if os.path.isfile(path):
source_path = os.path.normpath(path)
break
if not source_path:
# Couldn't find library in the panda3d lib dir.
return
self.dep_paths[dep] = target_path
self.write_file(target_path, source_path)
return target_path
def write_file(self, target_path, source_path):
temp = None
ext = os.path.splitext(source_path)[1]
if ext in ('.so', '.dylib') or '.so.' in os.path.basename(source_path) or \
(not ext and is_executable(source_path)):
deps = scan_dependencies(source_path)
for dep in deps:
if '/' not in dep:
target_dep = os.path.dirname(target_path) + '/' + dep
self.consider_add_dependency(target_dep, dep)
suffix = ''
if '.so' in os.path.basename(source_path):
suffix = '.so'
elif ext == '.dylib':
suffix = '.dylib'
temp = tempfile.NamedTemporaryFile(suffix=suffix, prefix='whl', delete=False)
if sys.platform == "darwin" and is_fat_file(source_path) and not self.platform.endswith("_intel"):
if self.platform.endswith("_x86_64"):
arch = 'x86_64'
else:
arch = self.platform.split('_')[-1]
subprocess.call(['lipo', source_path, '-extract', arch, '-output', temp.name])
else:
temp.write(open(source_path, 'rb').read())
os.fchmod(temp.fileno(), os.fstat(temp.fileno()).st_mode | 0o111)
temp.close()
if sys.platform == "darwin":
loader_path = [os.path.dirname(source_path)]
for dep in deps:
if '@loader_path' not in dep:
continue
dep_path = dep.replace('@loader_path', '.')
target_dep = os.path.dirname(target_path) + '/' + os.path.basename(dep)
target_dep = self.consider_add_dependency(target_dep, dep_path, loader_path)
if not target_dep:
continue
new_dep = os.path.join('@loader_path', os.path.relpath(target_dep, os.path.dirname(target_path)))
subprocess.call(["install_name_tool", "-change", dep, new_dep, temp.name])
else:
subprocess.call(["strip", "-s", temp.name])
subprocess.call(["patchelf", "--set-rpath", "$ORIGIN", temp.name])
source_path = temp.name
ext = ext.lower()
if ext in ('.dll', '.pyd', '.exe'):
# Scan and add Win32 dependencies.
for dep in scan_dependencies(source_path):
target_dep = os.path.dirname(target_path) + '/' + dep
self.consider_add_dependency(target_dep, dep)
# Calculate the SHA-256 hash and size.
sha = hashlib.sha256()
fp = open(source_path, 'rb')
size = 0
data = fp.read(1024 * 1024)
while data:
size += len(data)
sha.update(data)
data = fp.read(1024 * 1024)
fp.close()
# Save it in PEP-0376 format for writing out later.
digest = urlsafe_b64encode(sha.digest()).decode('ascii')
digest = digest.rstrip('=')
self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, size))
if GetVerbose():
print("Adding %s from %s" % (target_path, source_path))
self.zip_file.write(source_path, target_path)
#if temp:
# os.unlink(temp.name)
def write_file_data(self, target_path, source_data):
sha = hashlib.sha256()
sha.update(source_data.encode())
digest = urlsafe_b64encode(sha.digest()).decode('ascii')
digest = digest.rstrip('=')
self.records.append("{0},sha256={1},{2}\n".format(target_path, digest, len(source_data)))
if GetVerbose():
print("Adding %s from data" % target_path)
self.zip_file.writestr(target_path, source_data)
def write_directory(self, target_dir, source_dir):
for root, dirs, files in os.walk(source_dir):
for file in files:
if os.path.splitext(file)[1] in EXCLUDE_EXT:
continue
source_path = os.path.join(root, file)
target_path = os.path.join(target_dir, os.path.relpath(source_path, source_dir))
target_path = target_path.replace('\\', '/')
self.write_file(target_path, source_path)
def close(self):
# Write the RECORD file.
record_file = "{0}-{1}.dist-info/RECORD".format(self.name, self.version)
self.records.append(record_file + ",,\n")
self.zip_file.writestr(record_file, "".join(self.records))
self.zip_file.close()
def makewheel(version, output_dir, platform=default_platform):
if sys.platform not in ("win32", "darwin") and not sys.platform.startswith("cygwin"):
if not LocateBinary("patchelf"):
raise Exception("patchelf is required when building a Linux wheel.")
platform = platform.replace('-', '_').replace('.', '_')
# Global filepaths
panda3d_dir = join(output_dir, "panda3d")
pandac_dir = join(output_dir, "pandac")
direct_dir = join(output_dir, "direct")
models_dir = join(output_dir, "models")
etc_dir = join(output_dir, "etc")
bin_dir = join(output_dir, "bin")
if sys.platform == "win32":
libs_dir = join(output_dir, "bin")
else:
libs_dir = join(output_dir, "lib")
license_src = "LICENSE"
readme_src = "README.md"
# Update relevant METADATA entries
METADATA['version'] = version
version_classifiers = [
"Programming Language :: Python :: {0}".format(*sys.version_info),
"Programming Language :: Python :: {0}.{1}".format(*sys.version_info),
]
METADATA['classifiers'].extend(version_classifiers)
# Build out the metadata
details = METADATA["extensions"]["python.details"]
homepage = details["project_urls"]["Home"]
author = details["contacts"][0]["name"]
email = details["contacts"][0]["email"]
metadata = ''.join([
"Metadata-Version: {metadata_version}\n" \
"Name: {name}\n" \
"Version: {version}\n" \
"Summary: {summary}\n" \
"License: {license}\n".format(**METADATA),
"Home-page: {0}\n".format(homepage),
"Author: {0}\n".format(author),
"Author-email: {0}\n".format(email),
"Platform: {0}\n".format(platform),
] + ["Classifier: {0}\n".format(c) for c in METADATA['classifiers']])
# Zip it up and name it the right thing
whl = WheelFile('panda3d', version, platform)
whl.lib_path = [libs_dir]
# Add the trees with Python modules.
whl.write_directory('direct', direct_dir)
# Write the panda3d tree. We use a custom empty __init__ since the
# default one adds the bin directory to the PATH, which we don't have.
whl.write_file_data('panda3d/__init__.py', '')
ext_suffix = GetExtensionSuffix()
for file in os.listdir(panda3d_dir):
if file == '__init__.py':
pass
elif file.endswith(ext_suffix) or file.endswith('.py'):
source_path = os.path.join(panda3d_dir, file)
if file.endswith('.pyd') and platform.startswith('cygwin'):
target_path = 'panda3d/' + os.path.splitext(file)[0] + '.dll'
else:
target_path = 'panda3d/' + file
whl.write_file(target_path, source_path)
for lib in PLUGIN_LIBS:
plugin_name = 'lib' + lib
if sys.platform in ('win32', 'cygwin'):
plugin_name += '.dll'
elif sys.platform == 'darwin':
plugin_name += '.dylib'
else:
plugin_name += '.so'
plugin_path = os.path.join(libs_dir, plugin_name)
if os.path.isfile(plugin_path):
whl.write_file('panda3d/' + plugin_name, plugin_path)
data_dir = 'panda3d-{0}.data'.format(version)
# places in the user's filesystem. Let's instead put them in panda3d.
whl.write_directory('panda3d/etc', etc_dir)
whl.write_directory('panda3d/models', models_dir)
# Add the pandac tree for backward compatibility.
for file in os.listdir(pandac_dir):
if file.endswith('.py'):
whl.write_file('pandac/' + file, os.path.join(pandac_dir, file))
# Add a panda3d-tools directory containing the executables.
entry_points = '[console_scripts]\n'
entry_points += 'eggcacher = direct.directscripts.eggcacher:main\n'
entry_points += 'pfreeze = direct.showutil.pfreeze:main\n'
tools_init = ''
for file in os.listdir(bin_dir):
basename = os.path.splitext(file)[0]
if basename in ('eggcacher', 'packpanda'):
continue
source_path = os.path.join(bin_dir, file)
if is_executable(source_path):
# Put the .exe files inside the panda3d-tools directory.
whl.write_file('panda3d_tools/' + file, source_path)
# Tell pip to create a wrapper script.
funcname = basename.replace('-', '_')
entry_points += '{0} = panda3d_tools:{1}\n'.format(basename, funcname)
tools_init += '{0} = lambda: _exec_tool({1!r})\n'.format(funcname, file)
whl.write_file_data('panda3d_tools/__init__.py', PANDA3D_TOOLS_INIT.format(tools_init))
# Add the dist-info directory last.
info_dir = 'panda3d-{0}.dist-info'.format(version)
whl.write_file_data(info_dir + '/entry_points.txt', entry_points)
whl.write_file_data(info_dir + '/metadata.json', json.dumps(METADATA, indent=4, separators=(',', ': ')))
whl.write_file_data(info_dir + '/METADATA', metadata)
whl.write_file_data(info_dir + '/WHEEL', WHEEL_DATA.format(PY_VERSION, ABI_TAG, platform))
whl.write_file(info_dir + '/LICENSE.txt', license_src)
whl.write_file(info_dir + '/README.md', readme_src)
whl.write_file_data(info_dir + '/top_level.txt', 'direct\npanda3d\npandac\npanda3d_tools\n')
whl.close()
if __name__ == "__main__":
version = ParsePandaVersion("dtool/PandaVersion.pp")
parser = OptionParser()
parser.add_option('', '--version', dest = 'version', help = 'Panda3D version number (default: %s)' % (version), default = version)
parser.add_option('', '--outputdir', dest = 'outputdir', help = 'Makepanda\'s output directory (default: built)', default = 'built')
parser.add_option('', '--verbose', dest = 'verbose', help = 'Enable verbose output', action = 'store_true', default = False)
parser.add_option('', '--platform', dest = 'platform', help = 'Override platform tag (default: %s)' % (default_platform), default = get_platform())
(options, args) = parser.parse_args()
SetVerbose(options.verbose)
makewheel(options.version, options.outputdir, options.platform)
| true | true |
f727f2af04e77662cb1b105b6ea82138d5057c4d | 435 | py | Python | sigmoid.py | tyburam/python-machine-learning | 7cb346c99d24e959c1af63532603dd118558b16f | [
"MIT"
] | 1 | 2021-04-28T05:40:59.000Z | 2021-04-28T05:40:59.000Z | sigmoid.py | tyburam/python-machine-learning | 7cb346c99d24e959c1af63532603dd118558b16f | [
"MIT"
] | null | null | null | sigmoid.py | tyburam/python-machine-learning | 7cb346c99d24e959c1af63532603dd118558b16f | [
"MIT"
] | null | null | null | #!/usr/bin/python3
import matplotlib.pyplot as plt
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
z = np.arange(-7, 7, 0.01)
phi_z = sigmoid(z)
plt.plot(z, phi_z)
plt.axvline(0.0, color = 'k')
plt.axhspan(0.0, 1.0, facecolor = '1.0', alpha = 1.0, ls = 'dotted')
plt.axhline(0.5, ls = 'dotted', color = 'k')
plt.yticks([0.0, 0.5, 1.0])
plt.ylim(-0.1, 1.1)
plt.xlabel('z')
plt.ylabel('$\phi (z)$')
plt.show() | 20.714286 | 68 | 0.602299 |
import matplotlib.pyplot as plt
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
z = np.arange(-7, 7, 0.01)
phi_z = sigmoid(z)
plt.plot(z, phi_z)
plt.axvline(0.0, color = 'k')
plt.axhspan(0.0, 1.0, facecolor = '1.0', alpha = 1.0, ls = 'dotted')
plt.axhline(0.5, ls = 'dotted', color = 'k')
plt.yticks([0.0, 0.5, 1.0])
plt.ylim(-0.1, 1.1)
plt.xlabel('z')
plt.ylabel('$\phi (z)$')
plt.show() | true | true |
f727f32f70eef26c04e670bca0235c128dc1f09b | 11,477 | py | Python | simplejson/simplejson/tests/test_decoder.py | gollum18/simplejson-test-suite | 3fea15709adb79ef33d7e020e38ec29bf82f2269 | [
"MIT"
] | null | null | null | simplejson/simplejson/tests/test_decoder.py | gollum18/simplejson-test-suite | 3fea15709adb79ef33d7e020e38ec29bf82f2269 | [
"MIT"
] | null | null | null | simplejson/simplejson/tests/test_decoder.py | gollum18/simplejson-test-suite | 3fea15709adb79ef33d7e020e38ec29bf82f2269 | [
"MIT"
] | null | null | null | # Name: test_decoder.py
# Since: April 13th, 2020
# Author: Christen Ford
# Purpose: Implementes unit tests for simplejson.decoder.
from unittest import TestCase
import simplejson.decoder as decoder
import simplejson.errors as errors
class TestDecoder(TestCase):
"""Implements a set of unit tests for the simplejson.decoder
module. These test cases make sane attempts at testing each
class and method found in the decoder module but they
are not exhaustively extensive.
"""
def test_scanstring_correct(self):
"""
Description: Tests that the py_scanstring() function
is able to parse valid JSON. Assumes optional
functional parameters are left at their defaults.
Input: '{'abc': 0, 'def': 1, 'ghi': 2'}'
Output: A tuple of the decoded JSON string and
the index in the string after the ending quote.
Test Case: Corresponds to test TEST-0000.
"""
test_input = '"{"abc": 0, "def": 1, "ghi": 2}"'
decoded_str, last_char_index = decoder.py_scanstring(
s=test_input,
end=1
)
self.assertEqual(decoded_str, "{")
self.assertEqual(last_char_index, 3)
def test_scanstring_malformed(self):
"""
Description: Tests that the py_scanstring() function is
able to properly detect malformed JSON. This test case
may include multiple different strings to ensure
well-rounded error detection.
Input:
(tuple): ("{]", "[}")
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0001.
"""
test_inputs = ('{]', '[}')
for test_input in test_inputs:
self.assertRaises(
decoder.JSONDecodeError,
decoder.py_scanstring,
s=test_input,
end=1
)
def test_scanstring_empty(self):
"""
Description: Tests that the py_scanstring() function is
able to properly detect empty strings.
Input:
(str): ""
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0002.
"""
test_input = ''
self.assertRaises(
errors.JSONDecodeError,
decoder.py_scanstring,
s=test_input,
end=1
)
def test_json_object_correct(self):
"""
Description: Test that the JSONObject() method can properly
decode JSON objects to Python dictionaries.
Input:
(tuple): ("{"abc": 0, "def": 1, "ghi": 2}", 0)
Output:
(dict): ({"abc": 0, "def": 1, "ghi": 2}, 30)
Test Case: Corresponds to test TEST-0003.
"""
test_input = ('{"abc": 0, "def": 1, "ghi": 2}', 1)
out_dict = dict()
out_dict["abc"] = 0
out_dict["def"] = 1
out_dict["ghi"] = 2
test_output = (out_dict, 30)
dcdr = decoder.JSONDecoder()
self.assertEqual(
decoder.JSONObject(
state=test_input,
encoding=dcdr.encoding,
strict=dcdr.strict,
scan_once=dcdr.scan_once,
object_hook=dcdr.object_hook,
object_pairs_hook=dcdr.object_pairs_hook
),
test_output
)
def test_json_object_malformed(self):
"""
Description: Tests that the JSONObject() method can detect
improperly formed JSON object.
Input:
(tuple): ("{"abc": 0, "def": 1, "ghi" :2]", 1)
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0004.
"""
test_input = ('\"{"abc": 0, "def": 1, "ghi": 2]\"', 1)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONObject,
state=test_input,
encoding=dcdr.encoding,
strict = dcdr.strict,
scan_once = dcdr.scan_once,
object_hook = dcdr.object_hook,
object_pairs_hook = dcdr.object_pairs_hook
)
def test_json_object_empty(self):
"""
Description: Tests that the JSONObject() method can detect
empty strings.
Input:
(tuple): ('', 0)
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0005.
"""
test_input = ("", 0)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONObject,
state=test_input,
encoding=dcdr.encoding,
strict = dcdr.strict,
scan_once = dcdr.scan_once,
object_hook = dcdr.object_hook,
object_pairs_hook = dcdr.object_pairs_hook
)
def test_json_array_correct(self):
"""
Description: Tests that the JSONArray method can decode
a properly formed JSONArray.
Input:
(tuple): ("["abc", "def", "ghi"]", 1)
Output:
Test Case: Corresponds to test TEST-0006.
"""
test_input = ('["abc", "def", "ghi"]', 1)
test_output = (['abc', 'def', 'ghi'], 21)
dcdr = decoder.JSONDecoder()
self.assertEqual(
decoder.JSONArray(
test_input,
dcdr.scan_once
),
test_output
)
def test_json_array_malformed(self):
"""
Description: Tests that the JSONArray method can properly
detect a malformed JSON array.
Input:
(str): ("["abc", "def", "ghi"}", 1)
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0007.
"""
test_input = ('["abc", "def", "ghi"}', 1)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONArray,
test_input,
dcdr.scan_once
)
def test_json_array_empty(self):
"""
Description: Tests that the JSONArray() method can
properly detect an empty string.
Input:
(tuple): ("", 0)
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0008.
"""
test_input = ('', 0)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONArray,
test_input,
dcdr.scan_once
)
def test_json_decoder_create_utf(self):
"""
Description: Tests that a JSONDecoder object can be created
to decode JSON strings with the 'utf-8' character encoding.
Input:
(str): "utf-8"
Output:
(JSONDecoder)
Test Case: Corresponds to test TEST-0009.
"""
dcdr = decoder.JSONDecoder(encoding="utf-8")
self.assertEqual(dcdr.encoding, "utf-8")
def test_json_decoder_create_unicode(self):
"""
Description: Tests that a JSONDecoder object can be created
with the unicode character encoding.
Input:
(str): "unicode"
Output:
(JSONDecoder)
TestCase: Corresponds to test TEST-0010.
"""
dcdr = decoder.JSONDecoder(encoding="unicode")
self.assertEqual(dcdr.encoding, "unicode")
def test_json_decoder_create_invalid(self):
"""
Description: Tests that a JSONDecoder object cannot be
created when given an invalid encoding.
Input:
(str): "ISO-8859-1"
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0011.
"""
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONDecoder,
encoding="ISO-8859-1"
)
def test_json_decoder_decode_correct(self):
"""
Description: Tests that the decode() method of the
JSONDecoder class can decode a properly formed JSON
document.
Input:
(str): {"id": "001", "name": "test-012", "items": ["a", "b", "c"]}
Output:
Test Case: Corresponds to test TEST-0012.
"""
test_input = '{"id": "001", "name": "test-012", "items": ["a", "b", "c"]}'
test_output = dict()
test_output["id"] = "001"
test_output["name"] = "test-012"
test_output["items"] = ["a", "b", "c"]
dcdr = decoder.JSONDecoder()
self.assertEqual(dcdr.decode(test_input), test_output)
def test_json_decoder_decode_malformed(self):
"""
Description: Tests that the decode() method of the
JSONDecoder class can properly recognize a malformed JSON
document.
Input:
(str): {"id": "001", "name": "test-012", "items": ["a", "b", "c"]]
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0013.
"""
test_input = '{"id": "001", "name": "test-012", "items": ["a", "b", "c"]]]'
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
dcdr.decode,
test_input
)
def test_json_decoder_decoder_empty(self):
"""
Decsription: Tests that the decode() method of the
JSONDecode class can recognize an empty string.
Input:
(str): ""
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0014.
"""
test_input = ''
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
dcdr.decode,
test_input
)
def test_raw_decoder_decode_correct(self):
"""
Description: Tests that the raw_decode() method of the
JSONDecoder class can properly decode an embedded JSON
document.
Input:
(str): "["abc", "def", "ghi"] This is a test!"
Output:
Test Case: Corresponds to test TEST-0015.
"""
dcdr = decoder.JSONDecoder()
test_input = '["abc", "def", "ghi"] This is a test!'
test_output = (['abc', 'def', 'ghi'], 21)
self.assertEqual(dcdr.raw_decode(test_input), test_output)
def test_raw_decoder_decode_malformed(self):
"""
Description: Tests that the raw_decode() method of the
JSONDecoder class can recognize a malformed JSON document.
Input:
(str): "["abc", "def", "ghi"} This is a test!"
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0016.
"""
dcdr = decoder.JSONDecoder()
test_input = '["abc", "def", "ghi"} This is a test!'
self.assertRaises(
errors.JSONDecodeError,
dcdr.raw_decode,
test_input
)
def test_raw_decoder_decoder_empty(self):
"""
Description: Tests that the raw_decode() method of the
JSONDecoder class can recognize an empty string.
Input:
(str): ""
Output:
(JSONDecodeError)
Test Case: Corresponds to test TEST-0017.
"""
test_input = ''
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
dcdr.raw_decode,
test_input
)
| 26.87822 | 83 | 0.544393 |
from unittest import TestCase
import simplejson.decoder as decoder
import simplejson.errors as errors
class TestDecoder(TestCase):
def test_scanstring_correct(self):
test_input = '"{"abc": 0, "def": 1, "ghi": 2}"'
decoded_str, last_char_index = decoder.py_scanstring(
s=test_input,
end=1
)
self.assertEqual(decoded_str, "{")
self.assertEqual(last_char_index, 3)
def test_scanstring_malformed(self):
test_inputs = ('{]', '[}')
for test_input in test_inputs:
self.assertRaises(
decoder.JSONDecodeError,
decoder.py_scanstring,
s=test_input,
end=1
)
def test_scanstring_empty(self):
test_input = ''
self.assertRaises(
errors.JSONDecodeError,
decoder.py_scanstring,
s=test_input,
end=1
)
def test_json_object_correct(self):
test_input = ('{"abc": 0, "def": 1, "ghi": 2}', 1)
out_dict = dict()
out_dict["abc"] = 0
out_dict["def"] = 1
out_dict["ghi"] = 2
test_output = (out_dict, 30)
dcdr = decoder.JSONDecoder()
self.assertEqual(
decoder.JSONObject(
state=test_input,
encoding=dcdr.encoding,
strict=dcdr.strict,
scan_once=dcdr.scan_once,
object_hook=dcdr.object_hook,
object_pairs_hook=dcdr.object_pairs_hook
),
test_output
)
def test_json_object_malformed(self):
test_input = ('\"{"abc": 0, "def": 1, "ghi": 2]\"', 1)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONObject,
state=test_input,
encoding=dcdr.encoding,
strict = dcdr.strict,
scan_once = dcdr.scan_once,
object_hook = dcdr.object_hook,
object_pairs_hook = dcdr.object_pairs_hook
)
def test_json_object_empty(self):
test_input = ("", 0)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONObject,
state=test_input,
encoding=dcdr.encoding,
strict = dcdr.strict,
scan_once = dcdr.scan_once,
object_hook = dcdr.object_hook,
object_pairs_hook = dcdr.object_pairs_hook
)
def test_json_array_correct(self):
test_input = ('["abc", "def", "ghi"]', 1)
test_output = (['abc', 'def', 'ghi'], 21)
dcdr = decoder.JSONDecoder()
self.assertEqual(
decoder.JSONArray(
test_input,
dcdr.scan_once
),
test_output
)
def test_json_array_malformed(self):
test_input = ('["abc", "def", "ghi"}', 1)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONArray,
test_input,
dcdr.scan_once
)
def test_json_array_empty(self):
test_input = ('', 0)
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONArray,
test_input,
dcdr.scan_once
)
def test_json_decoder_create_utf(self):
dcdr = decoder.JSONDecoder(encoding="utf-8")
self.assertEqual(dcdr.encoding, "utf-8")
def test_json_decoder_create_unicode(self):
dcdr = decoder.JSONDecoder(encoding="unicode")
self.assertEqual(dcdr.encoding, "unicode")
def test_json_decoder_create_invalid(self):
self.assertRaises(
errors.JSONDecodeError,
decoder.JSONDecoder,
encoding="ISO-8859-1"
)
def test_json_decoder_decode_correct(self):
test_input = '{"id": "001", "name": "test-012", "items": ["a", "b", "c"]}'
test_output = dict()
test_output["id"] = "001"
test_output["name"] = "test-012"
test_output["items"] = ["a", "b", "c"]
dcdr = decoder.JSONDecoder()
self.assertEqual(dcdr.decode(test_input), test_output)
def test_json_decoder_decode_malformed(self):
test_input = '{"id": "001", "name": "test-012", "items": ["a", "b", "c"]]]'
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
dcdr.decode,
test_input
)
def test_json_decoder_decoder_empty(self):
test_input = ''
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
dcdr.decode,
test_input
)
def test_raw_decoder_decode_correct(self):
dcdr = decoder.JSONDecoder()
test_input = '["abc", "def", "ghi"] This is a test!'
test_output = (['abc', 'def', 'ghi'], 21)
self.assertEqual(dcdr.raw_decode(test_input), test_output)
def test_raw_decoder_decode_malformed(self):
dcdr = decoder.JSONDecoder()
test_input = '["abc", "def", "ghi"} This is a test!'
self.assertRaises(
errors.JSONDecodeError,
dcdr.raw_decode,
test_input
)
def test_raw_decoder_decoder_empty(self):
test_input = ''
dcdr = decoder.JSONDecoder()
self.assertRaises(
errors.JSONDecodeError,
dcdr.raw_decode,
test_input
)
| true | true |
f727f373f944a10554dfcea5975a2aeb12ec2e24 | 21,937 | py | Python | src/pyrobot/locobot/camera.py | kalyanvasudev/pyrobot | 839ab89a5b3cdd6af9b1e884fa8e8f0007497e32 | [
"MIT"
] | 1 | 2021-12-22T04:14:08.000Z | 2021-12-22T04:14:08.000Z | src/pyrobot/locobot/camera.py | kalyanvasudev/pyrobot | 839ab89a5b3cdd6af9b1e884fa8e8f0007497e32 | [
"MIT"
] | 16 | 2020-01-28T22:49:47.000Z | 2022-03-11T23:51:24.000Z | src/pyrobot/locobot/camera.py | kalyanvasudev/pyrobot | 839ab89a5b3cdd6af9b1e884fa8e8f0007497e32 | [
"MIT"
] | 1 | 2020-09-30T15:14:19.000Z | 2020-09-30T15:14:19.000Z | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import rospkg
import threading
import yaml
from copy import deepcopy
import message_filters
import numpy as np
import pyrobot.util as prutil
import rospy
from cv_bridge import CvBridge, CvBridgeError
from pyrobot.core import Camera
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
from sensor_msgs.msg import JointState
from std_msgs.msg import Float64
from tf import TransformListener
def constrain_within_range(value, MIN, MAX):
return min(max(value, MIN), MAX)
def is_within_range(value, MIN, MAX):
return (value <= MAX) and (value >= MIN)
class SimpleCamera(Camera):
"""
This is camera class that interfaces with the Realsense
camera on the locobot and locobot-lite.
This class does not have the pan and tilt actuation
capabilities for the camera.
"""
def __init__(self, configs):
"""
Constructor of the SimpleCamera class.
:param configs: Camera specific configuration object
:type configs: YACS CfgNode
"""
super(SimpleCamera, self).__init__(configs=configs)
self.cv_bridge = CvBridge()
self.camera_info_lock = threading.RLock()
self.camera_img_lock = threading.RLock()
self._tf_listener = TransformListener()
self.rgb_img = None
self.depth_img = None
self.camera_info = None
self.camera_P = None
rospy.Subscriber(self.configs.CAMERA.ROSTOPIC_CAMERA_INFO_STREAM,
CameraInfo,
self._camera_info_callback)
rgb_topic = self.configs.CAMERA.ROSTOPIC_CAMERA_RGB_STREAM
self.rgb_sub = message_filters.Subscriber(rgb_topic, Image)
depth_topic = self.configs.CAMERA.ROSTOPIC_CAMERA_DEPTH_STREAM
self.depth_sub = message_filters.Subscriber(depth_topic, Image)
img_subs = [self.rgb_sub, self.depth_sub]
self.sync = message_filters.ApproximateTimeSynchronizer(img_subs,
queue_size=10,
slop=0.2)
self.sync.registerCallback(self._sync_callback)
depth_threshold = (self.configs.BASE.VSLAM.DEPTH_MIN,
self.configs.BASE.VSLAM.DEPTH_MAX)
cfg_filename = self.configs.BASE.VSLAM.CFG_FILENAME
self.depth_cam = DepthImgProcessor(subsample_pixs=1,
depth_threshold=depth_threshold,
cfg_filename=cfg_filename)
self.cam_cf = self.configs.BASE.VSLAM.RGB_CAMERA_CENTER_FRAME
self.base_f = self.configs.BASE.VSLAM.VSLAM_BASE_FRAME
def _sync_callback(self, rgb, depth):
self.camera_img_lock.acquire()
try:
self.rgb_img = self.cv_bridge.imgmsg_to_cv2(rgb, "bgr8")
self.rgb_img = self.rgb_img[:, :, ::-1]
self.depth_img = self.cv_bridge.imgmsg_to_cv2(depth, "passthrough")
except CvBridgeError as e:
rospy.logerr(e)
self.camera_img_lock.release()
def _camera_info_callback(self, msg):
self.camera_info_lock.acquire()
self.camera_info = msg
self.camera_P = np.array(msg.P).reshape((3, 4))
self.camera_info_lock.release()
def get_rgb(self):
'''
This function returns the RGB image perceived by the camera.
:rtype: np.ndarray or None
'''
self.camera_img_lock.acquire()
rgb = deepcopy(self.rgb_img)
self.camera_img_lock.release()
return rgb
def get_depth(self):
'''
This function returns the depth image perceived by the camera.
:rtype: np.ndarray or None
'''
self.camera_img_lock.acquire()
depth = deepcopy(self.depth_img)
self.camera_img_lock.release()
return depth
def get_rgb_depth(self):
'''
This function returns both the RGB and depth
images perceived by the camera.
:rtype: np.ndarray or None
'''
self.camera_img_lock.acquire()
rgb = deepcopy(self.rgb_img)
depth = deepcopy(self.depth_img)
self.camera_img_lock.release()
return rgb, depth
def get_intrinsics(self):
"""
This function returns the camera intrinsics.
:rtype: np.ndarray
"""
if self.camera_P is None:
return self.camera_P
self.camera_info_lock.acquire()
P = deepcopy(self.camera_P)
self.camera_info_lock.release()
return P[:3, :3]
def get_current_pcd(self, in_cam=True):
"""
Return the point cloud at current time step (one frame only)
:param in_cam: return points in camera frame,
otherwise, return points in base frame
:type in_cam: bool
:returns: tuple (pts, colors)
pts: point coordinates in world frame (shape: :math:`[N, 3]`)
colors: rgb values for pts_in_cam (shape: :math:`[N, 3]`)
:rtype: tuple(np.ndarray, np.ndarray)
"""
trans, rot, T = self.get_link_transform(self.cam_cf,
self.base_f)
base2cam_trans = np.array(trans).reshape(-1, 1)
base2cam_rot = np.array(rot)
rgb_im, depth_im = self.get_rgb_depth()
pcd_in_cam, colors = self.depth_cam.get_pcd_ic(depth_im=depth_im,
rgb_im=rgb_im)
pts = pcd_in_cam[:3, :].T
if in_cam:
return pts, colors
pts = np.dot(pts, base2cam_rot.T)
pts = pts + base2cam_trans.T
return pts, colors
def pix_to_3dpt(self, rs, cs, in_cam=False):
"""
Get the 3D points of the pixels in RGB images.
:param rs: rows of interest in the RGB image.
It can be a list or 1D numpy array
which contains the row indices.
The default value is None,
which means all rows.
:param cs: columns of interest in the RGB image.
It can be a list or 1D numpy array
which contains the column indices.
The default value is None,
which means all columns.
:param in_cam: return points in camera frame,
otherwise, return points in base frame
:type rs: list or np.ndarray
:type cs: list or np.ndarray
:type in_cam: bool
:returns: tuple (pts, colors)
pts: point coordinates in world frame
(shape: :math:`[N, 3]`)
colors: rgb values for pts_in_cam
(shape: :math:`[N, 3]`)
:rtype: tuple(np.ndarray, np.ndarray)
"""
trans, rot, T = self.get_link_transform(self.cam_cf,
self.base_f)
base2cam_trans = np.array(trans).reshape(-1, 1)
base2cam_rot = np.array(rot)
rgb_im, depth_im = self.get_rgb_depth()
pcd_in_cam = self.depth_cam.get_pix_3dpt(depth_im=depth_im,
rs=rs,
cs=cs)
pts = pcd_in_cam[:3, :].T
colors = rgb_im[rs, cs].reshape(-1, 3)
if in_cam:
return pts, colors
pts = np.dot(pts, base2cam_rot.T)
pts = pts + base2cam_trans.T
return pts, colors
def get_link_transform(self, src, tgt):
"""
Returns the latest transformation from the
target_frame to the source frame,
i.e., the transform of source frame w.r.t
target frame. If the returned
transform is applied to data, it will transform
data in the source_frame into
the target_frame
For more information, please refer to
http://wiki.ros.org/tf/Overview/Using%20Published%20Transforms
:param src: source frame
:param tgt: target frame
:type src: string
:type tgt: string
:returns: tuple(trans, rot, T)
trans: translational vector (shape: :math:`[3,]`)
rot: rotation matrix (shape: :math:`[3, 3]`)
T: transofrmation matrix (shape: :math:`[4, 4]`)
:rtype: tuple(np.ndarray, np.ndarray, np.ndarray)
"""
trans, quat = prutil.get_tf_transform(self._tf_listener,
tgt,
src)
rot = prutil.quat_to_rot_mat(quat)
T = np.eye(4)
T[:3, :3] = rot
T[:3, 3] = trans
return trans, rot, T
class LoCoBotCamera(SimpleCamera):
"""
This is camera class that interfaces with the Realsense
camera and the pan and tilt joints on the robot.
"""
def __init__(self, configs):
"""
Constructor of the LoCoBotCamera class.
:param configs: Object containing configurations for camera,
pan joint and tilt joint.
:type configs: YACS CfgNode
"""
use_camera = rospy.get_param('use_camera', False)
use_sim = rospy.get_param('use_sim', False)
use_camera = use_camera or use_sim
if not use_camera:
rospy.logwarn('Neither use_camera, nor use_sim, is not set'
' to True when the LoCoBot driver is launched.'
'You may not be able to command the camera'
' correctly using PyRobot!!!')
return
super(LoCoBotCamera, self).__init__(configs=configs)
rospy.Subscriber(self.configs.ARM.ROSTOPIC_JOINT_STATES,
JointState,
self._camera_pose_callback)
self.set_pan_pub = rospy.Publisher(
self.configs.CAMERA.ROSTOPIC_SET_PAN, Float64, queue_size=1)
self.set_tilt_pub = rospy.Publisher(
self.configs.CAMERA.ROSTOPIC_SET_TILT, Float64, queue_size=1)
self.pan = None
self.tilt = None
self.tol = 0.01
def _camera_pose_callback(self, msg):
if 'head_pan_joint' in msg.name:
pan_id = msg.name.index('head_pan_joint')
self.pan = msg.position[pan_id]
if 'head_tilt_joint' in msg.name:
tilt_id = msg.name.index('head_tilt_joint')
self.tilt = msg.position[tilt_id]
@property
def state(self):
"""
Return the current pan and tilt joint angles of the robot camera.
:return:
pan_tilt: A list the form [pan angle, tilt angle]
:rtype: list
"""
return self.get_state()
def get_state(self):
"""
Return the current pan and tilt joint angles of the robot camera.
:return:
pan_tilt: A list the form [pan angle, tilt angle]
:rtype: list
"""
return [self.pan, self.tilt]
def get_pan(self):
"""
Return the current pan joint angle of the robot camera.
:return:
pan: Pan joint angle
:rtype: float
"""
return self.pan
def get_tilt(self):
"""
Return the current tilt joint angle of the robot camera.
:return:
tilt: Tilt joint angle
:rtype: float
"""
return self.tilt
def set_pan(self, pan, wait=True):
"""
Sets the pan joint angle to the specified value.
:param pan: value to be set for pan joint
:param wait: wait until the pan angle is set to
the target angle.
:type pan: float
:type wait: bool
"""
pan = constrain_within_range(np.mod(pan + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_PAN,
self.configs.CAMERA.MAX_PAN)
self.set_pan_pub.publish(pan)
if wait:
for i in range(30):
rospy.sleep(0.1)
if np.fabs(self.get_pan() - pan) < self.tol:
break
def set_tilt(self, tilt, wait=True):
"""
Sets the tilt joint angle to the specified value.
:param tilt: value to be set for the tilt joint
:param wait: wait until the tilt angle is set to
the target angle.
:type tilt: float
:type wait: bool
"""
tilt = constrain_within_range(np.mod(tilt + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_TILT,
self.configs.CAMERA.MAX_TILT)
self.set_tilt_pub.publish(tilt)
if wait:
for i in range(30):
rospy.sleep(0.1)
if np.fabs(self.get_tilt() - tilt) < self.tol:
break
def set_pan_tilt(self, pan, tilt, wait=True):
"""
Sets both the pan and tilt joint angles to the specified values.
:param pan: value to be set for pan joint
:param tilt: value to be set for the tilt joint
:param wait: wait until the pan and tilt angles are set to
the target angles.
:type pan: float
:type tilt: float
:type wait: bool
"""
pan = constrain_within_range(np.mod(pan + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_PAN,
self.configs.CAMERA.MAX_PAN)
tilt = constrain_within_range(np.mod(tilt + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_TILT,
self.configs.CAMERA.MAX_TILT)
self.set_pan_pub.publish(pan)
self.set_tilt_pub.publish(tilt)
if wait:
for i in range(30):
rospy.sleep(0.1)
if np.fabs(self.get_pan() - pan) < self.tol and \
np.fabs(self.get_tilt() - tilt) < self.tol:
break
def reset(self):
"""
This function resets the pan and tilt joints by actuating
them to their home configuration.
"""
self.set_pan_tilt(self.configs.CAMERA.RESET_PAN,
self.configs.CAMERA.RESET_TILT)
class DepthImgProcessor:
"""
This class transforms the depth image and rgb image to point cloud
"""
def __init__(self, subsample_pixs=1, depth_threshold=(0, 1.5),
cfg_filename='realsense_d435.yaml'):
"""
The constructor for :class:`DepthImgProcessor` class.
:param subsample_pixs: sample rows and columns for the images
:param depth_threshold: minimum and maximum of valid depth values
:param cfg_filename: configuration file name for ORB-SLAM2
:type subsample_pixs: int
:type depth_threshold: tuple
:type cfg_filename: string
"""
assert (type(depth_threshold) is tuple and
0 < len(depth_threshold) < 3) or \
(depth_threshold is None)
self.subsample_pixs = subsample_pixs
self.depth_threshold = depth_threshold
self.cfg_data = self.read_cfg(cfg_filename)
self.intrinsic_mat = self.get_intrinsic()
self.intrinsic_mat_inv = np.linalg.inv(self.intrinsic_mat)
img_pixs = np.mgrid[0: self.cfg_data['Camera.height']: subsample_pixs,
0: self.cfg_data['Camera.width']: subsample_pixs]
img_pixs = img_pixs.reshape(2, -1)
img_pixs[[0, 1], :] = img_pixs[[1, 0], :]
self.uv_one = np.concatenate((img_pixs,
np.ones((1, img_pixs.shape[1]))))
self.uv_one_in_cam = np.dot(self.intrinsic_mat_inv, self.uv_one)
def get_pix_3dpt(self, depth_im, rs, cs):
"""
:param depth_im: depth image (shape: :math:`[H, W]`)
:param rs: rows of interest. It can be a list or 1D numpy array
which contains the row indices. The default value is None,
which means all rows.
:param cs: columns of interest. It can be a list or 1D numpy array
which contains the column indices.
The default value is None,
which means all columns.
:type depth_im: np.ndarray
:type rs: list or np.ndarray
:type cs: list or np.ndarray
:return: 3D point coordinates of the pixels in
camera frame (shape: :math:`[4, N]`)
:rtype np.ndarray
"""
assert isinstance(rs,
int) or isinstance(rs,
list) or isinstance(rs,
np.ndarray)
assert isinstance(cs,
int) or isinstance(cs,
list) or isinstance(cs,
np.ndarray)
if isinstance(rs, int):
rs = [rs]
if isinstance(cs, int):
cs = [cs]
if isinstance(rs, np.ndarray):
rs = rs.flatten()
if isinstance(cs, np.ndarray):
cs = cs.flatten()
depth_im = depth_im[rs, cs]
depth = depth_im.reshape(-1) / float(self.cfg_data['DepthMapFactor'])
img_pixs = np.stack((rs, cs)).reshape(2, -1)
img_pixs[[0, 1], :] = img_pixs[[1, 0], :]
uv_one = np.concatenate((img_pixs,
np.ones((1, img_pixs.shape[1]))))
uv_one_in_cam = np.dot(self.intrinsic_mat_inv, uv_one)
pts_in_cam = np.multiply(uv_one_in_cam, depth)
pts_in_cam = np.concatenate((pts_in_cam,
np.ones((1, pts_in_cam.shape[1]))),
axis=0)
return pts_in_cam
def get_pcd_ic(self, depth_im, rgb_im=None):
"""
Returns the point cloud (filtered by minimum
and maximum depth threshold)
in camera's coordinate frame
:param depth_im: depth image (shape: :math:`[H, W]`)
:param rgb_im: rgb image (shape: :math:`[H, W, 3]`)
:type depth_im: np.ndarray
:type rgb_im: np.ndarray
:returns: tuple (pts_in_cam, rgb_im)
pts_in_cam: point coordinates in
camera frame (shape: :math:`[4, N]`)
rgb: rgb values for pts_in_cam (shape: :math:`[N, 3]`)
:rtype tuple(np.ndarray, np.ndarray)
"""
# pcd in camera from depth
depth_im = depth_im[0::self.subsample_pixs, 0::self.subsample_pixs]
rgb_im = rgb_im[0::self.subsample_pixs, 0::self.subsample_pixs]
depth = depth_im.reshape(-1) / float(self.cfg_data['DepthMapFactor'])
rgb = None
if rgb_im is not None:
rgb = rgb_im.reshape(-1, 3)
if self.depth_threshold is not None:
valid = depth > self.depth_threshold[0]
if len(self.depth_threshold) > 1:
valid = np.logical_and(valid,
depth < self.depth_threshold[1])
uv_one_in_cam = self.uv_one_in_cam[:, valid]
depth = depth[valid]
rgb = rgb[valid]
else:
uv_one_in_cam = self.uv_one_in_cam
pts_in_cam = np.multiply(uv_one_in_cam, depth)
pts_in_cam = np.concatenate((pts_in_cam,
np.ones((1, pts_in_cam.shape[1]))),
axis=0)
return pts_in_cam, rgb
def get_pcd_iw(self, pts_in_cam, extrinsic_mat):
"""
Returns the point cloud in the world coordinate frame
:param pts_in_cam: point coordinates in
camera frame (shape: :math:`[4, N]`)
:param extrinsic_mat: extrinsic matrix for
the camera (shape: :math:`[4, 4]`)
:type pts_in_cam: np.ndarray
:type extrinsic_mat: np.ndarray
:return: point coordinates in
ORB-SLAM2's world frame (shape: :math:`[N, 3]`)
:rtype: np.ndarray
"""
# pcd in world
pts_in_world = np.dot(extrinsic_mat, pts_in_cam)
pts_in_world = pts_in_world[:3, :].T
return pts_in_world
def read_cfg(self, cfg_filename):
"""
Reads the configuration file
:param cfg_filename: configuration file name for ORB-SLAM2
:type cfg_filename: string
:return: configurations in the configuration file
:rtype: dict
"""
rospack = rospkg.RosPack()
slam_pkg_path = rospack.get_path('orb_slam2_ros')
cfg_path = os.path.join(slam_pkg_path,
'cfg',
cfg_filename)
with open(cfg_path, 'r') as f:
for i in range(1):
f.readline()
cfg_data = yaml.load(f)
return cfg_data
def get_intrinsic(self):
"""
Returns the instrinsic matrix of the camera
:return: the intrinsic matrix (shape: :math:`[3, 3]`)
:rtype: np.ndarray
"""
fx = self.cfg_data['Camera.fx']
fy = self.cfg_data['Camera.fy']
cx = self.cfg_data['Camera.cx']
cy = self.cfg_data['Camera.cy']
Itc = np.array([[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]])
return Itc
| 35.962295 | 79 | 0.548161 |
import os
import rospkg
import threading
import yaml
from copy import deepcopy
import message_filters
import numpy as np
import pyrobot.util as prutil
import rospy
from cv_bridge import CvBridge, CvBridgeError
from pyrobot.core import Camera
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
from sensor_msgs.msg import JointState
from std_msgs.msg import Float64
from tf import TransformListener
def constrain_within_range(value, MIN, MAX):
return min(max(value, MIN), MAX)
def is_within_range(value, MIN, MAX):
return (value <= MAX) and (value >= MIN)
class SimpleCamera(Camera):
def __init__(self, configs):
super(SimpleCamera, self).__init__(configs=configs)
self.cv_bridge = CvBridge()
self.camera_info_lock = threading.RLock()
self.camera_img_lock = threading.RLock()
self._tf_listener = TransformListener()
self.rgb_img = None
self.depth_img = None
self.camera_info = None
self.camera_P = None
rospy.Subscriber(self.configs.CAMERA.ROSTOPIC_CAMERA_INFO_STREAM,
CameraInfo,
self._camera_info_callback)
rgb_topic = self.configs.CAMERA.ROSTOPIC_CAMERA_RGB_STREAM
self.rgb_sub = message_filters.Subscriber(rgb_topic, Image)
depth_topic = self.configs.CAMERA.ROSTOPIC_CAMERA_DEPTH_STREAM
self.depth_sub = message_filters.Subscriber(depth_topic, Image)
img_subs = [self.rgb_sub, self.depth_sub]
self.sync = message_filters.ApproximateTimeSynchronizer(img_subs,
queue_size=10,
slop=0.2)
self.sync.registerCallback(self._sync_callback)
depth_threshold = (self.configs.BASE.VSLAM.DEPTH_MIN,
self.configs.BASE.VSLAM.DEPTH_MAX)
cfg_filename = self.configs.BASE.VSLAM.CFG_FILENAME
self.depth_cam = DepthImgProcessor(subsample_pixs=1,
depth_threshold=depth_threshold,
cfg_filename=cfg_filename)
self.cam_cf = self.configs.BASE.VSLAM.RGB_CAMERA_CENTER_FRAME
self.base_f = self.configs.BASE.VSLAM.VSLAM_BASE_FRAME
def _sync_callback(self, rgb, depth):
self.camera_img_lock.acquire()
try:
self.rgb_img = self.cv_bridge.imgmsg_to_cv2(rgb, "bgr8")
self.rgb_img = self.rgb_img[:, :, ::-1]
self.depth_img = self.cv_bridge.imgmsg_to_cv2(depth, "passthrough")
except CvBridgeError as e:
rospy.logerr(e)
self.camera_img_lock.release()
def _camera_info_callback(self, msg):
self.camera_info_lock.acquire()
self.camera_info = msg
self.camera_P = np.array(msg.P).reshape((3, 4))
self.camera_info_lock.release()
def get_rgb(self):
self.camera_img_lock.acquire()
rgb = deepcopy(self.rgb_img)
self.camera_img_lock.release()
return rgb
def get_depth(self):
self.camera_img_lock.acquire()
depth = deepcopy(self.depth_img)
self.camera_img_lock.release()
return depth
def get_rgb_depth(self):
self.camera_img_lock.acquire()
rgb = deepcopy(self.rgb_img)
depth = deepcopy(self.depth_img)
self.camera_img_lock.release()
return rgb, depth
def get_intrinsics(self):
if self.camera_P is None:
return self.camera_P
self.camera_info_lock.acquire()
P = deepcopy(self.camera_P)
self.camera_info_lock.release()
return P[:3, :3]
def get_current_pcd(self, in_cam=True):
trans, rot, T = self.get_link_transform(self.cam_cf,
self.base_f)
base2cam_trans = np.array(trans).reshape(-1, 1)
base2cam_rot = np.array(rot)
rgb_im, depth_im = self.get_rgb_depth()
pcd_in_cam, colors = self.depth_cam.get_pcd_ic(depth_im=depth_im,
rgb_im=rgb_im)
pts = pcd_in_cam[:3, :].T
if in_cam:
return pts, colors
pts = np.dot(pts, base2cam_rot.T)
pts = pts + base2cam_trans.T
return pts, colors
def pix_to_3dpt(self, rs, cs, in_cam=False):
trans, rot, T = self.get_link_transform(self.cam_cf,
self.base_f)
base2cam_trans = np.array(trans).reshape(-1, 1)
base2cam_rot = np.array(rot)
rgb_im, depth_im = self.get_rgb_depth()
pcd_in_cam = self.depth_cam.get_pix_3dpt(depth_im=depth_im,
rs=rs,
cs=cs)
pts = pcd_in_cam[:3, :].T
colors = rgb_im[rs, cs].reshape(-1, 3)
if in_cam:
return pts, colors
pts = np.dot(pts, base2cam_rot.T)
pts = pts + base2cam_trans.T
return pts, colors
def get_link_transform(self, src, tgt):
trans, quat = prutil.get_tf_transform(self._tf_listener,
tgt,
src)
rot = prutil.quat_to_rot_mat(quat)
T = np.eye(4)
T[:3, :3] = rot
T[:3, 3] = trans
return trans, rot, T
class LoCoBotCamera(SimpleCamera):
def __init__(self, configs):
use_camera = rospy.get_param('use_camera', False)
use_sim = rospy.get_param('use_sim', False)
use_camera = use_camera or use_sim
if not use_camera:
rospy.logwarn('Neither use_camera, nor use_sim, is not set'
' to True when the LoCoBot driver is launched.'
'You may not be able to command the camera'
' correctly using PyRobot!!!')
return
super(LoCoBotCamera, self).__init__(configs=configs)
rospy.Subscriber(self.configs.ARM.ROSTOPIC_JOINT_STATES,
JointState,
self._camera_pose_callback)
self.set_pan_pub = rospy.Publisher(
self.configs.CAMERA.ROSTOPIC_SET_PAN, Float64, queue_size=1)
self.set_tilt_pub = rospy.Publisher(
self.configs.CAMERA.ROSTOPIC_SET_TILT, Float64, queue_size=1)
self.pan = None
self.tilt = None
self.tol = 0.01
def _camera_pose_callback(self, msg):
if 'head_pan_joint' in msg.name:
pan_id = msg.name.index('head_pan_joint')
self.pan = msg.position[pan_id]
if 'head_tilt_joint' in msg.name:
tilt_id = msg.name.index('head_tilt_joint')
self.tilt = msg.position[tilt_id]
@property
def state(self):
return self.get_state()
def get_state(self):
return [self.pan, self.tilt]
def get_pan(self):
return self.pan
def get_tilt(self):
return self.tilt
def set_pan(self, pan, wait=True):
pan = constrain_within_range(np.mod(pan + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_PAN,
self.configs.CAMERA.MAX_PAN)
self.set_pan_pub.publish(pan)
if wait:
for i in range(30):
rospy.sleep(0.1)
if np.fabs(self.get_pan() - pan) < self.tol:
break
def set_tilt(self, tilt, wait=True):
tilt = constrain_within_range(np.mod(tilt + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_TILT,
self.configs.CAMERA.MAX_TILT)
self.set_tilt_pub.publish(tilt)
if wait:
for i in range(30):
rospy.sleep(0.1)
if np.fabs(self.get_tilt() - tilt) < self.tol:
break
def set_pan_tilt(self, pan, tilt, wait=True):
pan = constrain_within_range(np.mod(pan + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_PAN,
self.configs.CAMERA.MAX_PAN)
tilt = constrain_within_range(np.mod(tilt + np.pi,
2 * np.pi) - np.pi,
self.configs.CAMERA.MIN_TILT,
self.configs.CAMERA.MAX_TILT)
self.set_pan_pub.publish(pan)
self.set_tilt_pub.publish(tilt)
if wait:
for i in range(30):
rospy.sleep(0.1)
if np.fabs(self.get_pan() - pan) < self.tol and \
np.fabs(self.get_tilt() - tilt) < self.tol:
break
def reset(self):
self.set_pan_tilt(self.configs.CAMERA.RESET_PAN,
self.configs.CAMERA.RESET_TILT)
class DepthImgProcessor:
def __init__(self, subsample_pixs=1, depth_threshold=(0, 1.5),
cfg_filename='realsense_d435.yaml'):
assert (type(depth_threshold) is tuple and
0 < len(depth_threshold) < 3) or \
(depth_threshold is None)
self.subsample_pixs = subsample_pixs
self.depth_threshold = depth_threshold
self.cfg_data = self.read_cfg(cfg_filename)
self.intrinsic_mat = self.get_intrinsic()
self.intrinsic_mat_inv = np.linalg.inv(self.intrinsic_mat)
img_pixs = np.mgrid[0: self.cfg_data['Camera.height']: subsample_pixs,
0: self.cfg_data['Camera.width']: subsample_pixs]
img_pixs = img_pixs.reshape(2, -1)
img_pixs[[0, 1], :] = img_pixs[[1, 0], :]
self.uv_one = np.concatenate((img_pixs,
np.ones((1, img_pixs.shape[1]))))
self.uv_one_in_cam = np.dot(self.intrinsic_mat_inv, self.uv_one)
def get_pix_3dpt(self, depth_im, rs, cs):
assert isinstance(rs,
int) or isinstance(rs,
list) or isinstance(rs,
np.ndarray)
assert isinstance(cs,
int) or isinstance(cs,
list) or isinstance(cs,
np.ndarray)
if isinstance(rs, int):
rs = [rs]
if isinstance(cs, int):
cs = [cs]
if isinstance(rs, np.ndarray):
rs = rs.flatten()
if isinstance(cs, np.ndarray):
cs = cs.flatten()
depth_im = depth_im[rs, cs]
depth = depth_im.reshape(-1) / float(self.cfg_data['DepthMapFactor'])
img_pixs = np.stack((rs, cs)).reshape(2, -1)
img_pixs[[0, 1], :] = img_pixs[[1, 0], :]
uv_one = np.concatenate((img_pixs,
np.ones((1, img_pixs.shape[1]))))
uv_one_in_cam = np.dot(self.intrinsic_mat_inv, uv_one)
pts_in_cam = np.multiply(uv_one_in_cam, depth)
pts_in_cam = np.concatenate((pts_in_cam,
np.ones((1, pts_in_cam.shape[1]))),
axis=0)
return pts_in_cam
def get_pcd_ic(self, depth_im, rgb_im=None):
depth_im = depth_im[0::self.subsample_pixs, 0::self.subsample_pixs]
rgb_im = rgb_im[0::self.subsample_pixs, 0::self.subsample_pixs]
depth = depth_im.reshape(-1) / float(self.cfg_data['DepthMapFactor'])
rgb = None
if rgb_im is not None:
rgb = rgb_im.reshape(-1, 3)
if self.depth_threshold is not None:
valid = depth > self.depth_threshold[0]
if len(self.depth_threshold) > 1:
valid = np.logical_and(valid,
depth < self.depth_threshold[1])
uv_one_in_cam = self.uv_one_in_cam[:, valid]
depth = depth[valid]
rgb = rgb[valid]
else:
uv_one_in_cam = self.uv_one_in_cam
pts_in_cam = np.multiply(uv_one_in_cam, depth)
pts_in_cam = np.concatenate((pts_in_cam,
np.ones((1, pts_in_cam.shape[1]))),
axis=0)
return pts_in_cam, rgb
def get_pcd_iw(self, pts_in_cam, extrinsic_mat):
pts_in_world = np.dot(extrinsic_mat, pts_in_cam)
pts_in_world = pts_in_world[:3, :].T
return pts_in_world
def read_cfg(self, cfg_filename):
rospack = rospkg.RosPack()
slam_pkg_path = rospack.get_path('orb_slam2_ros')
cfg_path = os.path.join(slam_pkg_path,
'cfg',
cfg_filename)
with open(cfg_path, 'r') as f:
for i in range(1):
f.readline()
cfg_data = yaml.load(f)
return cfg_data
def get_intrinsic(self):
fx = self.cfg_data['Camera.fx']
fy = self.cfg_data['Camera.fy']
cx = self.cfg_data['Camera.cx']
cy = self.cfg_data['Camera.cy']
Itc = np.array([[fx, 0, cx],
[0, fy, cy],
[0, 0, 1]])
return Itc
| true | true |
f727f3abb30dc023a71e5a4bb0a7f4af4c4e0c66 | 8,529 | py | Python | pyglet/input/evdev_constants.py | qbektrix/pyglet | ab3f73dfd37abf75041e86310416b18138c34c33 | [
"BSD-3-Clause"
] | 2 | 2015-06-02T19:14:37.000Z | 2017-09-17T03:49:19.000Z | pyglet/input/evdev_constants.py | qbektrix/pyglet | ab3f73dfd37abf75041e86310416b18138c34c33 | [
"BSD-3-Clause"
] | 1 | 2018-08-27T22:31:16.000Z | 2018-08-27T22:31:16.000Z | pyglet/input/evdev_constants.py | qbektrix/pyglet | ab3f73dfd37abf75041e86310416b18138c34c33 | [
"BSD-3-Clause"
] | 2 | 2016-07-28T18:45:57.000Z | 2020-12-05T06:13:00.000Z | #!/usr/bin/env python
'''Event constants from /usr/include/linux/input.h
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
EV_SYN = 0x00
EV_KEY = 0x01
EV_REL = 0x02
EV_ABS = 0x03
EV_MSC = 0x04
EV_LED = 0x11
EV_SND = 0x12
EV_REP = 0x14
EV_FF = 0x15
EV_PWR = 0x16
EV_FF_STATUS = 0x17
EV_MAX = 0x1f
# Synchronization events.
SYN_REPORT = 0
SYN_CONFIG = 1
# Keys and buttons
KEY_RESERVED = 0
KEY_ESC = 1
KEY_1 = 2
KEY_2 = 3
KEY_3 = 4
KEY_4 = 5
KEY_5 = 6
KEY_6 = 7
KEY_7 = 8
KEY_8 = 9
KEY_9 = 10
KEY_0 = 11
KEY_MINUS = 12
KEY_EQUAL = 13
KEY_BACKSPACE = 14
KEY_TAB = 15
KEY_Q = 16
KEY_W = 17
KEY_E = 18
KEY_R = 19
KEY_T = 20
KEY_Y = 21
KEY_U = 22
KEY_I = 23
KEY_O = 24
KEY_P = 25
KEY_LEFTBRACE = 26
KEY_RIGHTBRACE = 27
KEY_ENTER = 28
KEY_LEFTCTRL = 29
KEY_A = 30
KEY_S = 31
KEY_D = 32
KEY_F = 33
KEY_G = 34
KEY_H = 35
KEY_J = 36
KEY_K = 37
KEY_L = 38
KEY_SEMICOLON = 39
KEY_APOSTROPHE = 40
KEY_GRAVE = 41
KEY_LEFTSHIFT = 42
KEY_BACKSLASH = 43
KEY_Z = 44
KEY_X = 45
KEY_C = 46
KEY_V = 47
KEY_B = 48
KEY_N = 49
KEY_M = 50
KEY_COMMA = 51
KEY_DOT = 52
KEY_SLASH = 53
KEY_RIGHTSHIFT = 54
KEY_KPASTERISK = 55
KEY_LEFTALT = 56
KEY_SPACE = 57
KEY_CAPSLOCK = 58
KEY_F1 = 59
KEY_F2 = 60
KEY_F3 = 61
KEY_F4 = 62
KEY_F5 = 63
KEY_F6 = 64
KEY_F7 = 65
KEY_F8 = 66
KEY_F9 = 67
KEY_F10 = 68
KEY_NUMLOCK = 69
KEY_SCROLLLOCK = 70
KEY_KP7 = 71
KEY_KP8 = 72
KEY_KP9 = 73
KEY_KPMINUS = 74
KEY_KP4 = 75
KEY_KP5 = 76
KEY_KP6 = 77
KEY_KPPLUS = 78
KEY_KP1 = 79
KEY_KP2 = 80
KEY_KP3 = 81
KEY_KP0 = 82
KEY_KPDOT = 83
KEY_ZENKAKUHANKAKU = 85
KEY_102ND = 86
KEY_F11 = 87
KEY_F12 = 88
KEY_RO = 89
KEY_KATAKANA = 90
KEY_HIRAGANA = 91
KEY_HENKAN = 92
KEY_KATAKANAHIRAGANA = 93
KEY_MUHENKAN = 94
KEY_KPJPCOMMA = 95
KEY_KPENTER = 96
KEY_RIGHTCTRL = 97
KEY_KPSLASH = 98
KEY_SYSRQ = 99
KEY_RIGHTALT = 100
KEY_LINEFEED = 101
KEY_HOME = 102
KEY_UP = 103
KEY_PAGEUP = 104
KEY_LEFT = 105
KEY_RIGHT = 106
KEY_END = 107
KEY_DOWN = 108
KEY_PAGEDOWN = 109
KEY_INSERT = 110
KEY_DELETE = 111
KEY_MACRO = 112
KEY_MUTE = 113
KEY_VOLUMEDOWN = 114
KEY_VOLUMEUP = 115
KEY_POWER = 116
KEY_KPEQUAL = 117
KEY_KPPLUSMINUS = 118
KEY_PAUSE = 119
KEY_KPCOMMA = 121
KEY_HANGUEL = 122
KEY_HANJA = 123
KEY_YEN = 124
KEY_LEFTMETA = 125
KEY_RIGHTMETA = 126
KEY_COMPOSE = 127
KEY_STOP = 128
KEY_AGAIN = 129
KEY_PROPS = 130
KEY_UNDO = 131
KEY_FRONT = 132
KEY_COPY = 133
KEY_OPEN = 134
KEY_PASTE = 135
KEY_FIND = 136
KEY_CUT = 137
KEY_HELP = 138
KEY_MENU = 139
KEY_CALC = 140
KEY_SETUP = 141
KEY_SLEEP = 142
KEY_WAKEUP = 143
KEY_FILE = 144
KEY_SENDFILE = 145
KEY_DELETEFILE = 146
KEY_XFER = 147
KEY_PROG1 = 148
KEY_PROG2 = 149
KEY_WWW = 150
KEY_MSDOS = 151
KEY_COFFEE = 152
KEY_DIRECTION = 153
KEY_CYCLEWINDOWS = 154
KEY_MAIL = 155
KEY_BOOKMARKS = 156
KEY_COMPUTER = 157
KEY_BACK = 158
KEY_FORWARD = 159
KEY_CLOSECD = 160
KEY_EJECTCD = 161
KEY_EJECTCLOSECD = 162
KEY_NEXTSONG = 163
KEY_PLAYPAUSE = 164
KEY_PREVIOUSSONG = 165
KEY_STOPCD = 166
KEY_RECORD = 167
KEY_REWIND = 168
KEY_PHONE = 169
KEY_ISO = 170
KEY_CONFIG = 171
KEY_HOMEPAGE = 172
KEY_REFRESH = 173
KEY_EXIT = 174
KEY_MOVE = 175
KEY_EDIT = 176
KEY_SCROLLUP = 177
KEY_SCROLLDOWN = 178
KEY_KPLEFTPAREN = 179
KEY_KPRIGHTPAREN = 180
KEY_F13 = 183
KEY_F14 = 184
KEY_F15 = 185
KEY_F16 = 186
KEY_F17 = 187
KEY_F18 = 188
KEY_F19 = 189
KEY_F20 = 190
KEY_F21 = 191
KEY_F22 = 192
KEY_F23 = 193
KEY_F24 = 194
KEY_PLAYCD = 200
KEY_PAUSECD = 201
KEY_PROG3 = 202
KEY_PROG4 = 203
KEY_SUSPEND = 205
KEY_CLOSE = 206
KEY_PLAY = 207
KEY_FASTFORWARD = 208
KEY_BASSBOOST = 209
KEY_PRINT = 210
KEY_HP = 211
KEY_CAMERA = 212
KEY_SOUND = 213
KEY_QUESTION = 214
KEY_EMAIL = 215
KEY_CHAT = 216
KEY_SEARCH = 217
KEY_CONNECT = 218
KEY_FINANCE = 219
KEY_SPORT = 220
KEY_SHOP = 221
KEY_ALTERASE = 222
KEY_CANCEL = 223
KEY_BRIGHTNESSDOWN = 224
KEY_BRIGHTNESSUP = 225
KEY_MEDIA = 226
KEY_UNKNOWN = 240
BTN_MISC = 0x100
BTN_0 = 0x100
BTN_1 = 0x101
BTN_2 = 0x102
BTN_3 = 0x103
BTN_4 = 0x104
BTN_5 = 0x105
BTN_6 = 0x106
BTN_7 = 0x107
BTN_8 = 0x108
BTN_9 = 0x109
BTN_MOUSE = 0x110
BTN_LEFT = 0x110
BTN_RIGHT = 0x111
BTN_MIDDLE = 0x112
BTN_SIDE = 0x113
BTN_EXTRA = 0x114
BTN_FORWARD = 0x115
BTN_BACK = 0x116
BTN_TASK = 0x117
BTN_JOYSTICK = 0x120
BTN_TRIGGER = 0x120
BTN_THUMB = 0x121
BTN_THUMB2 = 0x122
BTN_TOP = 0x123
BTN_TOP2 = 0x124
BTN_PINKIE = 0x125
BTN_BASE = 0x126
BTN_BASE2 = 0x127
BTN_BASE3 = 0x128
BTN_BASE4 = 0x129
BTN_BASE5 = 0x12a
BTN_BASE6 = 0x12b
BTN_DEAD = 0x12f
BTN_GAMEPAD = 0x130
BTN_A = 0x130
BTN_B = 0x131
BTN_C = 0x132
BTN_X = 0x133
BTN_Y = 0x134
BTN_Z = 0x135
BTN_TL = 0x136
BTN_TR = 0x137
BTN_TL2 = 0x138
BTN_TR2 = 0x139
BTN_SELECT = 0x13a
BTN_START = 0x13b
BTN_MODE = 0x13c
BTN_THUMBL = 0x13d
BTN_THUMBR = 0x13e
BTN_DIGI = 0x140
BTN_TOOL_PEN = 0x140
BTN_TOOL_RUBBER = 0x141
BTN_TOOL_BRUSH = 0x142
BTN_TOOL_PENCIL = 0x143
BTN_TOOL_AIRBRUSH = 0x144
BTN_TOOL_FINGER = 0x145
BTN_TOOL_MOUSE = 0x146
BTN_TOOL_LENS = 0x147
BTN_TOUCH = 0x14a
BTN_STYLUS = 0x14b
BTN_STYLUS2 = 0x14c
BTN_TOOL_DOUBLETAP = 0x14d
BTN_TOOL_TRIPLETAP = 0x14e
BTN_WHEEL = 0x150
BTN_GEAR_DOWN = 0x150
BTN_GEAR_UP = 0x151
KEY_OK = 0x160
KEY_SELECT = 0x161
KEY_GOTO = 0x162
KEY_CLEAR = 0x163
KEY_POWER2 = 0x164
KEY_OPTION = 0x165
KEY_INFO = 0x166
KEY_TIME = 0x167
KEY_VENDOR = 0x168
KEY_ARCHIVE = 0x169
KEY_PROGRAM = 0x16a
KEY_CHANNEL = 0x16b
KEY_FAVORITES = 0x16c
KEY_EPG = 0x16d
KEY_PVR = 0x16e
KEY_MHP = 0x16f
KEY_LANGUAGE = 0x170
KEY_TITLE = 0x171
KEY_SUBTITLE = 0x172
KEY_ANGLE = 0x173
KEY_ZOOM = 0x174
KEY_MODE = 0x175
KEY_KEYBOARD = 0x176
KEY_SCREEN = 0x177
KEY_PC = 0x178
KEY_TV = 0x179
KEY_TV2 = 0x17a
KEY_VCR = 0x17b
KEY_VCR2 = 0x17c
KEY_SAT = 0x17d
KEY_SAT2 = 0x17e
KEY_CD = 0x17f
KEY_TAPE = 0x180
KEY_RADIO = 0x181
KEY_TUNER = 0x182
KEY_PLAYER = 0x183
KEY_TEXT = 0x184
KEY_DVD = 0x185
KEY_AUX = 0x186
KEY_MP3 = 0x187
KEY_AUDIO = 0x188
KEY_VIDEO = 0x189
KEY_DIRECTORY = 0x18a
KEY_LIST = 0x18b
KEY_MEMO = 0x18c
KEY_CALENDAR = 0x18d
KEY_RED = 0x18e
KEY_GREEN = 0x18f
KEY_YELLOW = 0x190
KEY_BLUE = 0x191
KEY_CHANNELUP = 0x192
KEY_CHANNELDOWN = 0x193
KEY_FIRST = 0x194
KEY_LAST = 0x195
KEY_AB = 0x196
KEY_NEXT = 0x197
KEY_RESTART = 0x198
KEY_SLOW = 0x199
KEY_SHUFFLE = 0x19a
KEY_BREAK = 0x19b
KEY_PREVIOUS = 0x19c
KEY_DIGITS = 0x19d
KEY_TEEN = 0x19e
KEY_TWEN = 0x19f
KEY_DEL_EOL = 0x1c0
KEY_DEL_EOS = 0x1c1
KEY_INS_LINE = 0x1c2
KEY_DEL_LINE = 0x1c3
KEY_FN = 0x1d0
KEY_FN_ESC = 0x1d1
KEY_FN_F1 = 0x1d2
KEY_FN_F2 = 0x1d3
KEY_FN_F3 = 0x1d4
KEY_FN_F4 = 0x1d5
KEY_FN_F5 = 0x1d6
KEY_FN_F6 = 0x1d7
KEY_FN_F7 = 0x1d8
KEY_FN_F8 = 0x1d9
KEY_FN_F9 = 0x1da
KEY_FN_F10 = 0x1db
KEY_FN_F11 = 0x1dc
KEY_FN_F12 = 0x1dd
KEY_FN_1 = 0x1de
KEY_FN_2 = 0x1df
KEY_FN_D = 0x1e0
KEY_FN_E = 0x1e1
KEY_FN_F = 0x1e2
KEY_FN_S = 0x1e3
KEY_FN_B = 0x1e4
KEY_MAX = 0x1ff
# Relative axes
REL_X = 0x00
REL_Y = 0x01
REL_Z = 0x02
REL_RX = 0x03
REL_RY = 0x04
REL_RZ = 0x05
REL_HWHEEL = 0x06
REL_DIAL = 0x07
REL_WHEEL = 0x08
REL_MISC = 0x09
REL_MAX = 0x0f
# Absolute axes
ABS_X = 0x00
ABS_Y = 0x01
ABS_Z = 0x02
ABS_RX = 0x03
ABS_RY = 0x04
ABS_RZ = 0x05
ABS_THROTTLE = 0x06
ABS_RUDDER = 0x07
ABS_WHEEL = 0x08
ABS_GAS = 0x09
ABS_BRAKE = 0x0a
ABS_HAT0X = 0x10
ABS_HAT0Y = 0x11
ABS_HAT1X = 0x12
ABS_HAT1Y = 0x13
ABS_HAT2X = 0x14
ABS_HAT2Y = 0x15
ABS_HAT3X = 0x16
ABS_HAT3Y = 0x17
ABS_PRESSURE = 0x18
ABS_DISTANCE = 0x19
ABS_TILT_X = 0x1a
ABS_TILT_Y = 0x1b
ABS_TOOL_WIDTH = 0x1c
ABS_VOLUME = 0x20
ABS_MISC = 0x28
ABS_MAX = 0x3f
# Misc events
MSC_SERIAL = 0x00
MSC_PULSELED = 0x01
MSC_GESTURE = 0x02
MSC_RAW = 0x03
MSC_SCAN = 0x04
MSC_MAX = 0x07
# LEDs
LED_NUML = 0x00
LED_CAPSL = 0x01
LED_SCROLLL = 0x02
LED_COMPOSE = 0x03
LED_KANA = 0x04
LED_SLEEP = 0x05
LED_SUSPEND = 0x06
LED_MUTE = 0x07
LED_MISC = 0x08
LED_MAIL = 0x09
LED_CHARGING = 0x0a
LED_MAX = 0x0f
# Autorepeat values
REP_DELAY = 0x00
REP_PERIOD = 0x01
REP_MAX = 0x01
# Sounds
SND_CLICK = 0x00
SND_BELL = 0x01
SND_TONE = 0x02
SND_MAX = 0x07
# IDs.
ID_BUS = 0
ID_VENDOR = 1
ID_PRODUCT = 2
ID_VERSION = 3
BUS_PCI = 0x01
BUS_ISAPNP = 0x02
BUS_USB = 0x03
BUS_HIL = 0x04
BUS_BLUETOOTH = 0x05
BUS_ISA = 0x10
BUS_I8042 = 0x11
BUS_XTKBD = 0x12
BUS_RS232 = 0x13
BUS_GAMEPORT = 0x14
BUS_PARPORT = 0x15
BUS_AMIGA = 0x16
BUS_ADB = 0x17
BUS_I2C = 0x18
BUS_HOST = 0x19
# Values describing the status of an effect
FF_STATUS_STOPPED = 0x00
FF_STATUS_PLAYING = 0x01
FF_STATUS_MAX = 0x01
_rel_raw_names = {}
_abs_raw_names = {}
_key_raw_names = {}
for _name, _val in locals().copy().items():
if _name.startswith('REL_'):
_rel_raw_names[_val] = _name
elif _name.startswith('ABS_'):
_abs_raw_names[_val] = _name
elif _name.startswith('KEY_') or _name.startswith('BTN_'):
_key_raw_names[_val] = _name
| 15.736162 | 62 | 0.749326 |
__docformat__ = 'restructuredtext'
__version__ = '$Id$'
EV_SYN = 0x00
EV_KEY = 0x01
EV_REL = 0x02
EV_ABS = 0x03
EV_MSC = 0x04
EV_LED = 0x11
EV_SND = 0x12
EV_REP = 0x14
EV_FF = 0x15
EV_PWR = 0x16
EV_FF_STATUS = 0x17
EV_MAX = 0x1f
SYN_REPORT = 0
SYN_CONFIG = 1
KEY_RESERVED = 0
KEY_ESC = 1
KEY_1 = 2
KEY_2 = 3
KEY_3 = 4
KEY_4 = 5
KEY_5 = 6
KEY_6 = 7
KEY_7 = 8
KEY_8 = 9
KEY_9 = 10
KEY_0 = 11
KEY_MINUS = 12
KEY_EQUAL = 13
KEY_BACKSPACE = 14
KEY_TAB = 15
KEY_Q = 16
KEY_W = 17
KEY_E = 18
KEY_R = 19
KEY_T = 20
KEY_Y = 21
KEY_U = 22
KEY_I = 23
KEY_O = 24
KEY_P = 25
KEY_LEFTBRACE = 26
KEY_RIGHTBRACE = 27
KEY_ENTER = 28
KEY_LEFTCTRL = 29
KEY_A = 30
KEY_S = 31
KEY_D = 32
KEY_F = 33
KEY_G = 34
KEY_H = 35
KEY_J = 36
KEY_K = 37
KEY_L = 38
KEY_SEMICOLON = 39
KEY_APOSTROPHE = 40
KEY_GRAVE = 41
KEY_LEFTSHIFT = 42
KEY_BACKSLASH = 43
KEY_Z = 44
KEY_X = 45
KEY_C = 46
KEY_V = 47
KEY_B = 48
KEY_N = 49
KEY_M = 50
KEY_COMMA = 51
KEY_DOT = 52
KEY_SLASH = 53
KEY_RIGHTSHIFT = 54
KEY_KPASTERISK = 55
KEY_LEFTALT = 56
KEY_SPACE = 57
KEY_CAPSLOCK = 58
KEY_F1 = 59
KEY_F2 = 60
KEY_F3 = 61
KEY_F4 = 62
KEY_F5 = 63
KEY_F6 = 64
KEY_F7 = 65
KEY_F8 = 66
KEY_F9 = 67
KEY_F10 = 68
KEY_NUMLOCK = 69
KEY_SCROLLLOCK = 70
KEY_KP7 = 71
KEY_KP8 = 72
KEY_KP9 = 73
KEY_KPMINUS = 74
KEY_KP4 = 75
KEY_KP5 = 76
KEY_KP6 = 77
KEY_KPPLUS = 78
KEY_KP1 = 79
KEY_KP2 = 80
KEY_KP3 = 81
KEY_KP0 = 82
KEY_KPDOT = 83
KEY_ZENKAKUHANKAKU = 85
KEY_102ND = 86
KEY_F11 = 87
KEY_F12 = 88
KEY_RO = 89
KEY_KATAKANA = 90
KEY_HIRAGANA = 91
KEY_HENKAN = 92
KEY_KATAKANAHIRAGANA = 93
KEY_MUHENKAN = 94
KEY_KPJPCOMMA = 95
KEY_KPENTER = 96
KEY_RIGHTCTRL = 97
KEY_KPSLASH = 98
KEY_SYSRQ = 99
KEY_RIGHTALT = 100
KEY_LINEFEED = 101
KEY_HOME = 102
KEY_UP = 103
KEY_PAGEUP = 104
KEY_LEFT = 105
KEY_RIGHT = 106
KEY_END = 107
KEY_DOWN = 108
KEY_PAGEDOWN = 109
KEY_INSERT = 110
KEY_DELETE = 111
KEY_MACRO = 112
KEY_MUTE = 113
KEY_VOLUMEDOWN = 114
KEY_VOLUMEUP = 115
KEY_POWER = 116
KEY_KPEQUAL = 117
KEY_KPPLUSMINUS = 118
KEY_PAUSE = 119
KEY_KPCOMMA = 121
KEY_HANGUEL = 122
KEY_HANJA = 123
KEY_YEN = 124
KEY_LEFTMETA = 125
KEY_RIGHTMETA = 126
KEY_COMPOSE = 127
KEY_STOP = 128
KEY_AGAIN = 129
KEY_PROPS = 130
KEY_UNDO = 131
KEY_FRONT = 132
KEY_COPY = 133
KEY_OPEN = 134
KEY_PASTE = 135
KEY_FIND = 136
KEY_CUT = 137
KEY_HELP = 138
KEY_MENU = 139
KEY_CALC = 140
KEY_SETUP = 141
KEY_SLEEP = 142
KEY_WAKEUP = 143
KEY_FILE = 144
KEY_SENDFILE = 145
KEY_DELETEFILE = 146
KEY_XFER = 147
KEY_PROG1 = 148
KEY_PROG2 = 149
KEY_WWW = 150
KEY_MSDOS = 151
KEY_COFFEE = 152
KEY_DIRECTION = 153
KEY_CYCLEWINDOWS = 154
KEY_MAIL = 155
KEY_BOOKMARKS = 156
KEY_COMPUTER = 157
KEY_BACK = 158
KEY_FORWARD = 159
KEY_CLOSECD = 160
KEY_EJECTCD = 161
KEY_EJECTCLOSECD = 162
KEY_NEXTSONG = 163
KEY_PLAYPAUSE = 164
KEY_PREVIOUSSONG = 165
KEY_STOPCD = 166
KEY_RECORD = 167
KEY_REWIND = 168
KEY_PHONE = 169
KEY_ISO = 170
KEY_CONFIG = 171
KEY_HOMEPAGE = 172
KEY_REFRESH = 173
KEY_EXIT = 174
KEY_MOVE = 175
KEY_EDIT = 176
KEY_SCROLLUP = 177
KEY_SCROLLDOWN = 178
KEY_KPLEFTPAREN = 179
KEY_KPRIGHTPAREN = 180
KEY_F13 = 183
KEY_F14 = 184
KEY_F15 = 185
KEY_F16 = 186
KEY_F17 = 187
KEY_F18 = 188
KEY_F19 = 189
KEY_F20 = 190
KEY_F21 = 191
KEY_F22 = 192
KEY_F23 = 193
KEY_F24 = 194
KEY_PLAYCD = 200
KEY_PAUSECD = 201
KEY_PROG3 = 202
KEY_PROG4 = 203
KEY_SUSPEND = 205
KEY_CLOSE = 206
KEY_PLAY = 207
KEY_FASTFORWARD = 208
KEY_BASSBOOST = 209
KEY_PRINT = 210
KEY_HP = 211
KEY_CAMERA = 212
KEY_SOUND = 213
KEY_QUESTION = 214
KEY_EMAIL = 215
KEY_CHAT = 216
KEY_SEARCH = 217
KEY_CONNECT = 218
KEY_FINANCE = 219
KEY_SPORT = 220
KEY_SHOP = 221
KEY_ALTERASE = 222
KEY_CANCEL = 223
KEY_BRIGHTNESSDOWN = 224
KEY_BRIGHTNESSUP = 225
KEY_MEDIA = 226
KEY_UNKNOWN = 240
BTN_MISC = 0x100
BTN_0 = 0x100
BTN_1 = 0x101
BTN_2 = 0x102
BTN_3 = 0x103
BTN_4 = 0x104
BTN_5 = 0x105
BTN_6 = 0x106
BTN_7 = 0x107
BTN_8 = 0x108
BTN_9 = 0x109
BTN_MOUSE = 0x110
BTN_LEFT = 0x110
BTN_RIGHT = 0x111
BTN_MIDDLE = 0x112
BTN_SIDE = 0x113
BTN_EXTRA = 0x114
BTN_FORWARD = 0x115
BTN_BACK = 0x116
BTN_TASK = 0x117
BTN_JOYSTICK = 0x120
BTN_TRIGGER = 0x120
BTN_THUMB = 0x121
BTN_THUMB2 = 0x122
BTN_TOP = 0x123
BTN_TOP2 = 0x124
BTN_PINKIE = 0x125
BTN_BASE = 0x126
BTN_BASE2 = 0x127
BTN_BASE3 = 0x128
BTN_BASE4 = 0x129
BTN_BASE5 = 0x12a
BTN_BASE6 = 0x12b
BTN_DEAD = 0x12f
BTN_GAMEPAD = 0x130
BTN_A = 0x130
BTN_B = 0x131
BTN_C = 0x132
BTN_X = 0x133
BTN_Y = 0x134
BTN_Z = 0x135
BTN_TL = 0x136
BTN_TR = 0x137
BTN_TL2 = 0x138
BTN_TR2 = 0x139
BTN_SELECT = 0x13a
BTN_START = 0x13b
BTN_MODE = 0x13c
BTN_THUMBL = 0x13d
BTN_THUMBR = 0x13e
BTN_DIGI = 0x140
BTN_TOOL_PEN = 0x140
BTN_TOOL_RUBBER = 0x141
BTN_TOOL_BRUSH = 0x142
BTN_TOOL_PENCIL = 0x143
BTN_TOOL_AIRBRUSH = 0x144
BTN_TOOL_FINGER = 0x145
BTN_TOOL_MOUSE = 0x146
BTN_TOOL_LENS = 0x147
BTN_TOUCH = 0x14a
BTN_STYLUS = 0x14b
BTN_STYLUS2 = 0x14c
BTN_TOOL_DOUBLETAP = 0x14d
BTN_TOOL_TRIPLETAP = 0x14e
BTN_WHEEL = 0x150
BTN_GEAR_DOWN = 0x150
BTN_GEAR_UP = 0x151
KEY_OK = 0x160
KEY_SELECT = 0x161
KEY_GOTO = 0x162
KEY_CLEAR = 0x163
KEY_POWER2 = 0x164
KEY_OPTION = 0x165
KEY_INFO = 0x166
KEY_TIME = 0x167
KEY_VENDOR = 0x168
KEY_ARCHIVE = 0x169
KEY_PROGRAM = 0x16a
KEY_CHANNEL = 0x16b
KEY_FAVORITES = 0x16c
KEY_EPG = 0x16d
KEY_PVR = 0x16e
KEY_MHP = 0x16f
KEY_LANGUAGE = 0x170
KEY_TITLE = 0x171
KEY_SUBTITLE = 0x172
KEY_ANGLE = 0x173
KEY_ZOOM = 0x174
KEY_MODE = 0x175
KEY_KEYBOARD = 0x176
KEY_SCREEN = 0x177
KEY_PC = 0x178
KEY_TV = 0x179
KEY_TV2 = 0x17a
KEY_VCR = 0x17b
KEY_VCR2 = 0x17c
KEY_SAT = 0x17d
KEY_SAT2 = 0x17e
KEY_CD = 0x17f
KEY_TAPE = 0x180
KEY_RADIO = 0x181
KEY_TUNER = 0x182
KEY_PLAYER = 0x183
KEY_TEXT = 0x184
KEY_DVD = 0x185
KEY_AUX = 0x186
KEY_MP3 = 0x187
KEY_AUDIO = 0x188
KEY_VIDEO = 0x189
KEY_DIRECTORY = 0x18a
KEY_LIST = 0x18b
KEY_MEMO = 0x18c
KEY_CALENDAR = 0x18d
KEY_RED = 0x18e
KEY_GREEN = 0x18f
KEY_YELLOW = 0x190
KEY_BLUE = 0x191
KEY_CHANNELUP = 0x192
KEY_CHANNELDOWN = 0x193
KEY_FIRST = 0x194
KEY_LAST = 0x195
KEY_AB = 0x196
KEY_NEXT = 0x197
KEY_RESTART = 0x198
KEY_SLOW = 0x199
KEY_SHUFFLE = 0x19a
KEY_BREAK = 0x19b
KEY_PREVIOUS = 0x19c
KEY_DIGITS = 0x19d
KEY_TEEN = 0x19e
KEY_TWEN = 0x19f
KEY_DEL_EOL = 0x1c0
KEY_DEL_EOS = 0x1c1
KEY_INS_LINE = 0x1c2
KEY_DEL_LINE = 0x1c3
KEY_FN = 0x1d0
KEY_FN_ESC = 0x1d1
KEY_FN_F1 = 0x1d2
KEY_FN_F2 = 0x1d3
KEY_FN_F3 = 0x1d4
KEY_FN_F4 = 0x1d5
KEY_FN_F5 = 0x1d6
KEY_FN_F6 = 0x1d7
KEY_FN_F7 = 0x1d8
KEY_FN_F8 = 0x1d9
KEY_FN_F9 = 0x1da
KEY_FN_F10 = 0x1db
KEY_FN_F11 = 0x1dc
KEY_FN_F12 = 0x1dd
KEY_FN_1 = 0x1de
KEY_FN_2 = 0x1df
KEY_FN_D = 0x1e0
KEY_FN_E = 0x1e1
KEY_FN_F = 0x1e2
KEY_FN_S = 0x1e3
KEY_FN_B = 0x1e4
KEY_MAX = 0x1ff
REL_X = 0x00
REL_Y = 0x01
REL_Z = 0x02
REL_RX = 0x03
REL_RY = 0x04
REL_RZ = 0x05
REL_HWHEEL = 0x06
REL_DIAL = 0x07
REL_WHEEL = 0x08
REL_MISC = 0x09
REL_MAX = 0x0f
ABS_X = 0x00
ABS_Y = 0x01
ABS_Z = 0x02
ABS_RX = 0x03
ABS_RY = 0x04
ABS_RZ = 0x05
ABS_THROTTLE = 0x06
ABS_RUDDER = 0x07
ABS_WHEEL = 0x08
ABS_GAS = 0x09
ABS_BRAKE = 0x0a
ABS_HAT0X = 0x10
ABS_HAT0Y = 0x11
ABS_HAT1X = 0x12
ABS_HAT1Y = 0x13
ABS_HAT2X = 0x14
ABS_HAT2Y = 0x15
ABS_HAT3X = 0x16
ABS_HAT3Y = 0x17
ABS_PRESSURE = 0x18
ABS_DISTANCE = 0x19
ABS_TILT_X = 0x1a
ABS_TILT_Y = 0x1b
ABS_TOOL_WIDTH = 0x1c
ABS_VOLUME = 0x20
ABS_MISC = 0x28
ABS_MAX = 0x3f
MSC_SERIAL = 0x00
MSC_PULSELED = 0x01
MSC_GESTURE = 0x02
MSC_RAW = 0x03
MSC_SCAN = 0x04
MSC_MAX = 0x07
LED_NUML = 0x00
LED_CAPSL = 0x01
LED_SCROLLL = 0x02
LED_COMPOSE = 0x03
LED_KANA = 0x04
LED_SLEEP = 0x05
LED_SUSPEND = 0x06
LED_MUTE = 0x07
LED_MISC = 0x08
LED_MAIL = 0x09
LED_CHARGING = 0x0a
LED_MAX = 0x0f
REP_DELAY = 0x00
REP_PERIOD = 0x01
REP_MAX = 0x01
SND_CLICK = 0x00
SND_BELL = 0x01
SND_TONE = 0x02
SND_MAX = 0x07
ID_BUS = 0
ID_VENDOR = 1
ID_PRODUCT = 2
ID_VERSION = 3
BUS_PCI = 0x01
BUS_ISAPNP = 0x02
BUS_USB = 0x03
BUS_HIL = 0x04
BUS_BLUETOOTH = 0x05
BUS_ISA = 0x10
BUS_I8042 = 0x11
BUS_XTKBD = 0x12
BUS_RS232 = 0x13
BUS_GAMEPORT = 0x14
BUS_PARPORT = 0x15
BUS_AMIGA = 0x16
BUS_ADB = 0x17
BUS_I2C = 0x18
BUS_HOST = 0x19
FF_STATUS_STOPPED = 0x00
FF_STATUS_PLAYING = 0x01
FF_STATUS_MAX = 0x01
_rel_raw_names = {}
_abs_raw_names = {}
_key_raw_names = {}
for _name, _val in locals().copy().items():
if _name.startswith('REL_'):
_rel_raw_names[_val] = _name
elif _name.startswith('ABS_'):
_abs_raw_names[_val] = _name
elif _name.startswith('KEY_') or _name.startswith('BTN_'):
_key_raw_names[_val] = _name
| true | true |
f727f3b193a37188b7de74a5fd1ff300f301659a | 1,439 | py | Python | MoneyChangeAlgorithm/moneychange.py | HeavyWolfPL/SchoolTools | d665d5cbecae7a7d1e7c2406b08471cf0242ed7f | [
"MIT"
] | null | null | null | MoneyChangeAlgorithm/moneychange.py | HeavyWolfPL/SchoolTools | d665d5cbecae7a7d1e7c2406b08471cf0242ed7f | [
"MIT"
] | null | null | null | MoneyChangeAlgorithm/moneychange.py | HeavyWolfPL/SchoolTools | d665d5cbecae7a7d1e7c2406b08471cf0242ed7f | [
"MIT"
] | null | null | null |
monety = input("Podaj posiadane monety, dzieląc je przecinkiem: ")
monety = monety.replace(" ", "")
monety = monety.split(",")
monety = list(map(int, monety))
ilosc = len(monety)
reszta = int(input("Jaką reszte chcesz wydać? "))
licznik = 0
historia = []
while reszta > 0:
if licznik >= ilosc:
print("Nie udało się wydać pełnej reszty. Można wydać tylko " + str(sum(monety)) + " zł.")
exit()
else:
nominal = 0
for i in range(ilosc):
if (monety[i] <= reszta) and (monety[i] > nominal):
nominal = monety[i]
reszta = reszta - nominal
historia.append(nominal)
licznik += 1
historia = str(historia).replace("[", "").replace("]", "")
if licznik != 1:
print("Użyto " + str(licznik) + " monet(y): " + str(historia))
else:
print("Resztę można wydać monetą: " + str(historia) + " zł")
############################
# Wersja 1:1 do wersji C++ #
############################
# ilosc = 3
# monety = [1, 2, 5]
# reszta = int(input("Jaka reszte chcesz wydac? "))
# licznik = 0
# historia = []
# while reszta > 0:
# nominal = 0
# for i in range(ilosc):
# if (monety[i] <= reszta) and (monety[i] > nominal):
# nominal = monety[i]
# reszta = reszta - nominal
# historia.append(nominal)
# licznik += 1
# print("Resztę mozna wydać " + str(licznik) + " monetami")
# print("Użyte monety: " + str(historia))
| 24.389831 | 98 | 0.549687 |
monety = input("Podaj posiadane monety, dzieląc je przecinkiem: ")
monety = monety.replace(" ", "")
monety = monety.split(",")
monety = list(map(int, monety))
ilosc = len(monety)
reszta = int(input("Jaką reszte chcesz wydać? "))
licznik = 0
historia = []
while reszta > 0:
if licznik >= ilosc:
print("Nie udało się wydać pełnej reszty. Można wydać tylko " + str(sum(monety)) + " zł.")
exit()
else:
nominal = 0
for i in range(ilosc):
if (monety[i] <= reszta) and (monety[i] > nominal):
nominal = monety[i]
reszta = reszta - nominal
historia.append(nominal)
licznik += 1
historia = str(historia).replace("[", "").replace("]", "")
if licznik != 1:
print("Użyto " + str(licznik) + " monet(y): " + str(historia))
else:
print("Resztę można wydać monetą: " + str(historia) + " zł")
| true | true |
f727f4410396c7d32520f3d46daef479d465926c | 991 | py | Python | coto/clients/signin/__init__.py | wvanheerde/coto | d7eeb2e98a24b743d879ef5e2da9cbbacc417d8d | [
"Apache-2.0"
] | 42 | 2018-04-13T18:02:04.000Z | 2022-03-30T00:21:26.000Z | coto/clients/signin/__init__.py | wvanheerde/coto | d7eeb2e98a24b743d879ef5e2da9cbbacc417d8d | [
"Apache-2.0"
] | 18 | 2019-02-08T11:50:46.000Z | 2022-03-29T10:12:03.000Z | coto/clients/signin/__init__.py | wvanheerde/coto | d7eeb2e98a24b743d879ef5e2da9cbbacc417d8d | [
"Apache-2.0"
] | 19 | 2019-02-04T14:57:46.000Z | 2022-03-24T13:39:21.000Z | from .. import BaseClient
class Client(BaseClient):
REQUIRES_AUTHENTICATION = False
def __init__(self, session):
super().__init__(session)
self._signin_aws = self.session().client('signin_aws')
self._signin_amazon = self.session().client('signin_amazon')
def signin(self, email, password, mfa_secret=None):
# check account type
account_type = self._signin_aws.get_account_type(email)
if account_type == 'Decoupled':
return self._signin_aws.signin(
email,
password,
mfa_secret,
)
elif account_type == 'Coupled':
return self._signin_amazon.signin(
email,
password,
mfa_secret,
)
elif account_type == 'Unknown':
raise Exception("account {0} not active".format(email))
else:
raise Exception("unsupported account type {0}".format(email))
| 30.030303 | 73 | 0.576186 | from .. import BaseClient
class Client(BaseClient):
REQUIRES_AUTHENTICATION = False
def __init__(self, session):
super().__init__(session)
self._signin_aws = self.session().client('signin_aws')
self._signin_amazon = self.session().client('signin_amazon')
def signin(self, email, password, mfa_secret=None):
account_type = self._signin_aws.get_account_type(email)
if account_type == 'Decoupled':
return self._signin_aws.signin(
email,
password,
mfa_secret,
)
elif account_type == 'Coupled':
return self._signin_amazon.signin(
email,
password,
mfa_secret,
)
elif account_type == 'Unknown':
raise Exception("account {0} not active".format(email))
else:
raise Exception("unsupported account type {0}".format(email))
| true | true |
f727f4f0204f36cf8008b3978cac8641ec0e174c | 216 | py | Python | beneficiaries/beneficiaries/doctype/beneficiary_aid_type/test_beneficiary_aid_type.py | baidalala/beneficiaries | b7299e0a7da91e90c607e70d76994ec0aebae402 | [
"MIT"
] | null | null | null | beneficiaries/beneficiaries/doctype/beneficiary_aid_type/test_beneficiary_aid_type.py | baidalala/beneficiaries | b7299e0a7da91e90c607e70d76994ec0aebae402 | [
"MIT"
] | null | null | null | beneficiaries/beneficiaries/doctype/beneficiary_aid_type/test_beneficiary_aid_type.py | baidalala/beneficiaries | b7299e0a7da91e90c607e70d76994ec0aebae402 | [
"MIT"
] | 1 | 2021-08-31T18:47:58.000Z | 2021-08-31T18:47:58.000Z | # -*- coding: utf-8 -*-
# Copyright (c) 2021, Baida and Contributors
# See license.txt
from __future__ import unicode_literals
# import frappe
import unittest
class TestBeneficiaryAidType(unittest.TestCase):
pass
| 19.636364 | 48 | 0.768519 |
from __future__ import unicode_literals
import unittest
class TestBeneficiaryAidType(unittest.TestCase):
pass
| true | true |
f727f5054ef0bf3d339c999db4daac4c53effb65 | 3,466 | py | Python | enas/cifar10/data_utils.py | j-varun/enas | 1a19ccbd7c06168ae51e0de2986b30ea01cce070 | [
"Apache-2.0"
] | 10 | 2018-05-07T15:59:55.000Z | 2021-04-18T12:51:14.000Z | enas/cifar10/data_utils.py | j-varun/enas | 1a19ccbd7c06168ae51e0de2986b30ea01cce070 | [
"Apache-2.0"
] | 4 | 2018-06-03T16:46:57.000Z | 2018-08-08T21:48:05.000Z | enas/cifar10/data_utils.py | j-varun/enas | 1a19ccbd7c06168ae51e0de2986b30ea01cce070 | [
"Apache-2.0"
] | 4 | 2018-05-25T04:39:56.000Z | 2019-04-29T05:08:25.000Z | import os
import sys
try:
import cPickle as pickle
except ImportError:
import _pickle as pickle
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def _read_data(data_path, train_files):
"""Reads CIFAR-10 format data. Always returns NHWC format.
Returns:
images: np tensor of size [N, H, W, C]
labels: np tensor of size [N]
"""
images, labels = [], []
for file_name in train_files:
print(file_name)
full_name = os.path.join(data_path, file_name)
with open(full_name, 'rb') as finp:
data = pickle.load(finp, encoding='bytes')
batch_images = data[b"data"].astype(np.float32) / 255.0
batch_labels = np.array(data[b"labels"], dtype=np.int32)
images.append(batch_images)
labels.append(batch_labels)
images = np.concatenate(images, axis=0)
labels = np.concatenate(labels, axis=0)
images = np.reshape(images, [-1, 3, 32, 32])
images = np.transpose(images, [0, 2, 3, 1])
return images, labels
def _read_fmnist_data(data_path):
"""Reads Fashion-Mnist data. Returns NHWC format.
Returns:
images: np tensor of size [N, H, W, C]
labels: np tensor of size [N]
"""
images, labels = {},{}
data = input_data.read_data_sets(data_path)
images["train"] = data.train.images.reshape(-1, 1, 28, 28) / 255.0
images["test"] = data.test.images.reshape(-1, 1, 28, 28) / 255.0
images["train"] = np.transpose(images["train"], [0, 2, 3, 1])
images["test"] = np.transpose(images["test"], [0, 2, 3, 1])
labels["train"] = np.array(data.train.labels, dtype = np.int32)
labels["test"] = np.array(data.test.labels, dtype = np.int32)
print("Read and processed data..")
print(labels["test"])
return images, labels
def valid_split_data(images, labels, num_valids=5000):
if num_valids:
images["valid"] = images["train"][-num_valids:]
labels["valid"] = labels["train"][-num_valids:]
images["train"] = images["train"][:-num_valids]
labels["train"] = labels["train"][:-num_valids]
else:
images["valid"], labels["valid"] = None, None
return images, labels
def read_data(data_path, num_valids=5000, dataset = "cifar"):
print("-" * 80)
print("Reading data")
print(os.getcwd())
images, labels = {}, {}
if(dataset == "fmnist"):
print("Fashion-Mnist")
images, labels = _read_fmnist_data(data_path)
images, labels = valid_split_data(images, labels, num_valids)
return images, labels
if dataset == "stacking":
images["path"] = data_path
return images, labels
else:
train_files = [
"data_batch_1",
"data_batch_2",
"data_batch_3",
"data_batch_4",
"data_batch_5",
]
test_file = [
"test_batch",
]
images["train"], labels["train"] = _read_data(data_path, train_files)
images, labels = valid_split_data(images, labels, num_valids)
images["test"], labels["test"] = _read_data(data_path, test_file)
print("Prepropcess: [subtract mean], [divide std]")
mean = np.mean(images["train"], axis=(0, 1, 2), keepdims=True)
std = np.std(images["train"], axis=(0, 1, 2), keepdims=True)
print("mean: {}".format(np.reshape(mean * 255.0, [-1])))
print("std: {}".format(np.reshape(std * 255.0, [-1])))
images["train"] = (images["train"] - mean) / std
if num_valids:
images["valid"] = (images["valid"] - mean) / std
images["test"] = (images["test"] - mean) / std
return images, labels
| 29.372881 | 73 | 0.644547 | import os
import sys
try:
import cPickle as pickle
except ImportError:
import _pickle as pickle
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
def _read_data(data_path, train_files):
images, labels = [], []
for file_name in train_files:
print(file_name)
full_name = os.path.join(data_path, file_name)
with open(full_name, 'rb') as finp:
data = pickle.load(finp, encoding='bytes')
batch_images = data[b"data"].astype(np.float32) / 255.0
batch_labels = np.array(data[b"labels"], dtype=np.int32)
images.append(batch_images)
labels.append(batch_labels)
images = np.concatenate(images, axis=0)
labels = np.concatenate(labels, axis=0)
images = np.reshape(images, [-1, 3, 32, 32])
images = np.transpose(images, [0, 2, 3, 1])
return images, labels
def _read_fmnist_data(data_path):
images, labels = {},{}
data = input_data.read_data_sets(data_path)
images["train"] = data.train.images.reshape(-1, 1, 28, 28) / 255.0
images["test"] = data.test.images.reshape(-1, 1, 28, 28) / 255.0
images["train"] = np.transpose(images["train"], [0, 2, 3, 1])
images["test"] = np.transpose(images["test"], [0, 2, 3, 1])
labels["train"] = np.array(data.train.labels, dtype = np.int32)
labels["test"] = np.array(data.test.labels, dtype = np.int32)
print("Read and processed data..")
print(labels["test"])
return images, labels
def valid_split_data(images, labels, num_valids=5000):
if num_valids:
images["valid"] = images["train"][-num_valids:]
labels["valid"] = labels["train"][-num_valids:]
images["train"] = images["train"][:-num_valids]
labels["train"] = labels["train"][:-num_valids]
else:
images["valid"], labels["valid"] = None, None
return images, labels
def read_data(data_path, num_valids=5000, dataset = "cifar"):
print("-" * 80)
print("Reading data")
print(os.getcwd())
images, labels = {}, {}
if(dataset == "fmnist"):
print("Fashion-Mnist")
images, labels = _read_fmnist_data(data_path)
images, labels = valid_split_data(images, labels, num_valids)
return images, labels
if dataset == "stacking":
images["path"] = data_path
return images, labels
else:
train_files = [
"data_batch_1",
"data_batch_2",
"data_batch_3",
"data_batch_4",
"data_batch_5",
]
test_file = [
"test_batch",
]
images["train"], labels["train"] = _read_data(data_path, train_files)
images, labels = valid_split_data(images, labels, num_valids)
images["test"], labels["test"] = _read_data(data_path, test_file)
print("Prepropcess: [subtract mean], [divide std]")
mean = np.mean(images["train"], axis=(0, 1, 2), keepdims=True)
std = np.std(images["train"], axis=(0, 1, 2), keepdims=True)
print("mean: {}".format(np.reshape(mean * 255.0, [-1])))
print("std: {}".format(np.reshape(std * 255.0, [-1])))
images["train"] = (images["train"] - mean) / std
if num_valids:
images["valid"] = (images["valid"] - mean) / std
images["test"] = (images["test"] - mean) / std
return images, labels
| true | true |
f727f57947e671ebd44b45237afa3f439dc6b3c3 | 8,633 | py | Python | conans/client/rest/auth_manager.py | amatoshka/conan | c2726e8c255adb120b5f7bdee9e3ec0bc90f1d7a | [
"MIT"
] | null | null | null | conans/client/rest/auth_manager.py | amatoshka/conan | c2726e8c255adb120b5f7bdee9e3ec0bc90f1d7a | [
"MIT"
] | null | null | null | conans/client/rest/auth_manager.py | amatoshka/conan | c2726e8c255adb120b5f7bdee9e3ec0bc90f1d7a | [
"MIT"
] | null | null | null | """
Collaborate with RestApiClient to make remote anonymous and authenticated calls.
Uses user_io to request user's login and password and obtain a token for calling authenticated
methods if receives AuthenticationException from RestApiClient.
Flow:
Directly invoke a REST method in RestApiClient, example: get_conan.
if receives AuthenticationException (not open method) will ask user for login and password
and will invoke RestApiClient.get_token() (with LOGIN_RETRIES retries) and retry to call
get_conan with the new token.
"""
import hashlib
from uuid import getnode as get_mac
from conans.client.cmd.user import update_localdb
from conans.errors import AuthenticationException, ConanException, ForbiddenException
from conans.util.log import logger
def input_credentials_if_unauthorized(func):
"""Decorator. Handles AuthenticationException and request user
to input a user and a password"""
LOGIN_RETRIES = 3
def wrapper(self, *args, **kwargs):
try:
# Set custom headers of mac_digest and username
self.set_custom_headers(self.user)
ret = func(self, *args, **kwargs)
return ret
except ForbiddenException:
raise ForbiddenException("Permission denied for user: '%s'" % self.user)
except AuthenticationException:
# User valid but not enough permissions
if self.user is None or self._rest_client.token is None:
# token is None when you change user with user command
# Anonymous is not enough, ask for a user
remote = self.remote
self._user_io.out.info('Please log in to "%s" to perform this action. '
'Execute "conan user" command.' % remote.name)
if "bintray" in remote.url:
self._user_io.out.info('If you don\'t have an account sign up here: '
'https://bintray.com/signup/oss')
return retry_with_new_token(self, *args, **kwargs)
else:
# Token expired or not valid, so clean the token and repeat the call
# (will be anonymous call but exporting who is calling)
logger.info("Token expired or not valid, cleaning the saved token and retrying")
self._store_login((self.user, None))
self._rest_client.token = None
# Set custom headers of mac_digest and username
self.set_custom_headers(self.user)
return wrapper(self, *args, **kwargs)
def retry_with_new_token(self, *args, **kwargs):
"""Try LOGIN_RETRIES to obtain a password from user input for which
we can get a valid token from api_client. If a token is returned,
credentials are stored in localdb and rest method is called"""
for _ in range(LOGIN_RETRIES):
user, password = self._user_io.request_login(self._remote.name, self.user)
try:
token, _, _, _ = self.authenticate(user, password)
except AuthenticationException:
if self.user is None:
self._user_io.out.error('Wrong user or password')
else:
self._user_io.out.error(
'Wrong password for user "%s"' % self.user)
self._user_io.out.info(
'You can change username with "conan user <username>"')
else:
logger.debug("Got token: %s" % str(token))
self._rest_client.token = token
self.user = user
# Set custom headers of mac_digest and username
self.set_custom_headers(user)
return wrapper(self, *args, **kwargs)
raise AuthenticationException("Too many failed login attempts, bye!")
return wrapper
class ConanApiAuthManager(object):
def __init__(self, rest_client, user_io, localdb):
self._user_io = user_io
self._rest_client = rest_client
self._localdb = localdb
self._remote = None
@property
def remote(self):
return self._remote
@remote.setter
def remote(self, remote):
self._remote = remote
self._rest_client.remote_url = remote.url
self._rest_client.verify_ssl = remote.verify_ssl
self.user, self._rest_client.token = self._localdb.get_login(remote.url)
def _store_login(self, login):
try:
self._localdb.set_login(login, self._remote.url)
except Exception as e:
self._user_io.out.error(
'Your credentials could not be stored in local cache\n')
self._user_io.out.debug(str(e) + '\n')
@staticmethod
def get_mac_digest():
sha1 = hashlib.sha1()
sha1.update(str(get_mac()).encode())
return str(sha1.hexdigest())
def set_custom_headers(self, username):
# First identifies our machine, second the username even if it was not
# authenticated
custom_headers = self._rest_client.custom_headers
custom_headers['X-Client-Anonymous-Id'] = self.get_mac_digest()
custom_headers['X-Client-Id'] = str(username or "")
# ######### CONAN API METHODS ##########
@input_credentials_if_unauthorized
def upload_recipe(self, conan_reference, the_files, retry, retry_wait, policy, remote_manifest):
return self._rest_client.upload_recipe(conan_reference, the_files, retry, retry_wait,
policy, remote_manifest)
@input_credentials_if_unauthorized
def upload_package(self, package_reference, the_files, retry, retry_wait, policy):
return self._rest_client.upload_package(package_reference, the_files, retry, retry_wait,
policy)
@input_credentials_if_unauthorized
def get_conan_manifest(self, conan_reference):
return self._rest_client.get_conan_manifest(conan_reference)
@input_credentials_if_unauthorized
def get_package_manifest(self, package_reference):
return self._rest_client.get_package_manifest(package_reference)
@input_credentials_if_unauthorized
def get_package(self, package_reference, dest_folder):
return self._rest_client.get_package(package_reference, dest_folder)
@input_credentials_if_unauthorized
def get_recipe(self, reference, dest_folder):
return self._rest_client.get_recipe(reference, dest_folder)
@input_credentials_if_unauthorized
def get_recipe_sources(self, reference, dest_folder):
return self._rest_client.get_recipe_sources(reference, dest_folder)
@input_credentials_if_unauthorized
def download_files_to_folder(self, urls, dest_folder):
return self._rest_client.download_files_to_folder(urls, dest_folder)
@input_credentials_if_unauthorized
def get_package_info(self, package_reference):
return self._rest_client.get_package_info(package_reference)
@input_credentials_if_unauthorized
def search(self, pattern, ignorecase):
return self._rest_client.search(pattern, ignorecase)
@input_credentials_if_unauthorized
def search_packages(self, reference, query):
return self._rest_client.search_packages(reference, query)
@input_credentials_if_unauthorized
def remove(self, conan_refernce):
return self._rest_client.remove_conanfile(conan_refernce)
@input_credentials_if_unauthorized
def remove_packages(self, conan_reference, package_ids):
return self._rest_client.remove_packages(conan_reference, package_ids)
@input_credentials_if_unauthorized
def get_path(self, conan_reference, path, package_id):
return self._rest_client.get_path(conan_reference, path, package_id)
def authenticate(self, user, password):
if user is None: # The user is already in DB, just need the passwd
prev_user = self._localdb.get_username(self._remote.url)
if prev_user is None:
raise ConanException("User for remote '%s' is not defined" % self._remote.name)
else:
user = prev_user
try:
token = self._rest_client.authenticate(user, password)
except UnicodeDecodeError:
raise ConanException("Password contains not allowed symbols")
# Store result in DB
remote_name, prev_user, user = update_localdb(self._localdb, user, token, self._remote)
return token, remote_name, prev_user, user
| 42.737624 | 100 | 0.664196 |
import hashlib
from uuid import getnode as get_mac
from conans.client.cmd.user import update_localdb
from conans.errors import AuthenticationException, ConanException, ForbiddenException
from conans.util.log import logger
def input_credentials_if_unauthorized(func):
LOGIN_RETRIES = 3
def wrapper(self, *args, **kwargs):
try:
self.set_custom_headers(self.user)
ret = func(self, *args, **kwargs)
return ret
except ForbiddenException:
raise ForbiddenException("Permission denied for user: '%s'" % self.user)
except AuthenticationException:
if self.user is None or self._rest_client.token is None:
remote = self.remote
self._user_io.out.info('Please log in to "%s" to perform this action. '
'Execute "conan user" command.' % remote.name)
if "bintray" in remote.url:
self._user_io.out.info('If you don\'t have an account sign up here: '
'https://bintray.com/signup/oss')
return retry_with_new_token(self, *args, **kwargs)
else:
# Token expired or not valid, so clean the token and repeat the call
# (will be anonymous call but exporting who is calling)
logger.info("Token expired or not valid, cleaning the saved token and retrying")
self._store_login((self.user, None))
self._rest_client.token = None
# Set custom headers of mac_digest and username
self.set_custom_headers(self.user)
return wrapper(self, *args, **kwargs)
def retry_with_new_token(self, *args, **kwargs):
for _ in range(LOGIN_RETRIES):
user, password = self._user_io.request_login(self._remote.name, self.user)
try:
token, _, _, _ = self.authenticate(user, password)
except AuthenticationException:
if self.user is None:
self._user_io.out.error('Wrong user or password')
else:
self._user_io.out.error(
'Wrong password for user "%s"' % self.user)
self._user_io.out.info(
'You can change username with "conan user <username>"')
else:
logger.debug("Got token: %s" % str(token))
self._rest_client.token = token
self.user = user
# Set custom headers of mac_digest and username
self.set_custom_headers(user)
return wrapper(self, *args, **kwargs)
raise AuthenticationException("Too many failed login attempts, bye!")
return wrapper
class ConanApiAuthManager(object):
def __init__(self, rest_client, user_io, localdb):
self._user_io = user_io
self._rest_client = rest_client
self._localdb = localdb
self._remote = None
@property
def remote(self):
return self._remote
@remote.setter
def remote(self, remote):
self._remote = remote
self._rest_client.remote_url = remote.url
self._rest_client.verify_ssl = remote.verify_ssl
self.user, self._rest_client.token = self._localdb.get_login(remote.url)
def _store_login(self, login):
try:
self._localdb.set_login(login, self._remote.url)
except Exception as e:
self._user_io.out.error(
'Your credentials could not be stored in local cache\n')
self._user_io.out.debug(str(e) + '\n')
@staticmethod
def get_mac_digest():
sha1 = hashlib.sha1()
sha1.update(str(get_mac()).encode())
return str(sha1.hexdigest())
def set_custom_headers(self, username):
# First identifies our machine, second the username even if it was not
# authenticated
custom_headers = self._rest_client.custom_headers
custom_headers['X-Client-Anonymous-Id'] = self.get_mac_digest()
custom_headers['X-Client-Id'] = str(username or "")
# ######### CONAN API METHODS ##########
@input_credentials_if_unauthorized
def upload_recipe(self, conan_reference, the_files, retry, retry_wait, policy, remote_manifest):
return self._rest_client.upload_recipe(conan_reference, the_files, retry, retry_wait,
policy, remote_manifest)
@input_credentials_if_unauthorized
def upload_package(self, package_reference, the_files, retry, retry_wait, policy):
return self._rest_client.upload_package(package_reference, the_files, retry, retry_wait,
policy)
@input_credentials_if_unauthorized
def get_conan_manifest(self, conan_reference):
return self._rest_client.get_conan_manifest(conan_reference)
@input_credentials_if_unauthorized
def get_package_manifest(self, package_reference):
return self._rest_client.get_package_manifest(package_reference)
@input_credentials_if_unauthorized
def get_package(self, package_reference, dest_folder):
return self._rest_client.get_package(package_reference, dest_folder)
@input_credentials_if_unauthorized
def get_recipe(self, reference, dest_folder):
return self._rest_client.get_recipe(reference, dest_folder)
@input_credentials_if_unauthorized
def get_recipe_sources(self, reference, dest_folder):
return self._rest_client.get_recipe_sources(reference, dest_folder)
@input_credentials_if_unauthorized
def download_files_to_folder(self, urls, dest_folder):
return self._rest_client.download_files_to_folder(urls, dest_folder)
@input_credentials_if_unauthorized
def get_package_info(self, package_reference):
return self._rest_client.get_package_info(package_reference)
@input_credentials_if_unauthorized
def search(self, pattern, ignorecase):
return self._rest_client.search(pattern, ignorecase)
@input_credentials_if_unauthorized
def search_packages(self, reference, query):
return self._rest_client.search_packages(reference, query)
@input_credentials_if_unauthorized
def remove(self, conan_refernce):
return self._rest_client.remove_conanfile(conan_refernce)
@input_credentials_if_unauthorized
def remove_packages(self, conan_reference, package_ids):
return self._rest_client.remove_packages(conan_reference, package_ids)
@input_credentials_if_unauthorized
def get_path(self, conan_reference, path, package_id):
return self._rest_client.get_path(conan_reference, path, package_id)
def authenticate(self, user, password):
if user is None: # The user is already in DB, just need the passwd
prev_user = self._localdb.get_username(self._remote.url)
if prev_user is None:
raise ConanException("User for remote '%s' is not defined" % self._remote.name)
else:
user = prev_user
try:
token = self._rest_client.authenticate(user, password)
except UnicodeDecodeError:
raise ConanException("Password contains not allowed symbols")
# Store result in DB
remote_name, prev_user, user = update_localdb(self._localdb, user, token, self._remote)
return token, remote_name, prev_user, user
| true | true |
f727f68949533cfb5e6250be94f67cb523575870 | 21,471 | py | Python | src/runner/trainer.py | minhhoangbui/PICK-pytorch | c74d2d1e5d1f8c7e837ea9776146bc84a7ecf30a | [
"MIT"
] | null | null | null | src/runner/trainer.py | minhhoangbui/PICK-pytorch | c74d2d1e5d1f8c7e837ea9776146bc84a7ecf30a | [
"MIT"
] | null | null | null | src/runner/trainer.py | minhhoangbui/PICK-pytorch | c74d2d1e5d1f8c7e837ea9776146bc84a7ecf30a | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# @Author: Wenwen Yu
# @Created Time: 7/12/2020 9:50 PM
import os
import numpy as np
from numpy import inf
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from src.utils import inf_loop
from src.utils.metrics import MetricTracker, SpanBasedF1MetricTracker
from torch.utils.tensorboard import SummaryWriter
# from src.logger import TensorboardWriter
from src.utils.utils import to_union
class Trainer:
"""
Trainer class
"""
def __init__(self, model, optimizer, config, data_loader, iob_labels_vocab_cls,
valid_data_loader=None, lr_scheduler=None, max_len_step=None):
"""
:param model:
:param optimizer:
:param config:
:param data_loader:
:param iob_labels_vocab_cls
:param valid_data_loader:
:param lr_scheduler:
:param max_len_step: controls number of batches(steps) in each epoch.
"""
self.config = config
self.iob_labels_vocab_cls = iob_labels_vocab_cls
self.distributed = config['distributed']
if self.distributed:
self.local_master = (config['local_rank'] == 0)
self.global_master = (dist.get_rank() == 0)
else:
self.local_master = True
self.global_master = True
self.logger = config.get_logger('trainer', config['trainer']['log_verbosity']) if self.local_master else None
# setup GPU device if available, move model into configured device
self.device, self.device_ids = self._prepare_device(config['local_rank'], config['local_world_size'])
self.model = model.to(self.device)
self.optimizer = optimizer
cfg_trainer = config['trainer']
self.epochs = cfg_trainer['epochs']
self.save_period = cfg_trainer['save_period']
monitor_open = cfg_trainer['monitor_open']
if monitor_open:
self.monitor = cfg_trainer.get('monitor', 'off')
else:
self.monitor = 'off'
# configuration to monitor model performance and save best
if self.monitor == 'off':
self.monitor_mode = 'off'
self.monitor_best = 0
else:
self.monitor_mode, self.monitor_metric = self.monitor.split()
assert self.monitor_mode in ['min', 'max']
self.monitor_best = inf if self.monitor_mode == 'min' else -inf
self.early_stop = cfg_trainer.get('early_stop', inf)
self.early_stop = inf if self.early_stop == -1 else self.early_stop
self.start_epoch = 1
if self.local_master:
self.checkpoint_dir = config.save_dir
# setup visualization writer instance
# self.writer = TensorboardWriter(config.log_dir, self.logger, cfg_trainer['tensorboard'])
self.writer = SummaryWriter(config.tensorboard_dir)
# load checkpoint for resume training
if config.resume is not None:
self._resume_checkpoint(config.resume)
# load checkpoint following load to multi-gpu, avoid 'module.' prefix
if self.config['trainer']['sync_batch_norm'] and self.distributed:
self.model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(self.model)
if self.distributed:
self.model = DDP(self.model, device_ids=self.device_ids, output_device=self.device_ids[0],
find_unused_parameters=True)
self.data_loader = data_loader
if max_len_step is None: # max length of iteration step of every epoch
# epoch-based training
self.len_step = len(self.data_loader)
else:
# iteration-based training
self.data_loader = inf_loop(data_loader)
self.len_step = max_len_step
self.valid_data_loader = valid_data_loader
self.do_validation = self.valid_data_loader is not None
self.lr_scheduler = lr_scheduler
log_step = self.config['trainer']['log_step_interval']
self.log_step = log_step if log_step != -1 and 0 < log_step < self.len_step else int(
np.sqrt(data_loader.batch_size))
self.val_epoch_interval = self.config['trainer']['val_epoch_interval']
self.gl_loss_lambda = self.config['trainer']['gl_loss_lambda']
self.train_loss_metrics = MetricTracker('loss', 'gl_loss', 'crf_loss',
writer=self.writer if self.local_master else None)
self.valid_f1_metrics = SpanBasedF1MetricTracker(iob_labels_vocab_cls)
def train(self):
"""
Full training logic, including train and validation.
"""
if self.distributed:
dist.barrier() # Syncing machines before training
not_improved_count = 0
val_result_dict = None
if self.config['evaluate_only']:
print("------Evaluation only------")
val_result_dict = self._valid_epoch(0)
val_res = SpanBasedF1MetricTracker.dict2str(val_result_dict)
self.logger_info('[Step Validation] Epoch:[{}/{}]] \n{}'.
format(0, self.epochs, val_res))
return
for epoch in range(self.start_epoch, self.epochs + 1):
# ensure distribute worker sample different data,
# set different random seed by passing epoch to sampler
if self.distributed:
self.data_loader.sampler.set_epoch(epoch)
result_dict = self._train_epoch(epoch)
# print logged information to the screen
if self.do_validation:
val_result_dict = result_dict['val_result_dict']
val_res = SpanBasedF1MetricTracker.dict2str(val_result_dict)
else:
val_res = ''
# every epoch log information
self.logger_info('[Epoch Validation] Epoch:[{}/{}] Total Loss: {:.6f} '
'GL_Loss: {:.6f} CRF_Loss: {:.6f} \n{}'.
format(epoch, self.epochs, result_dict['loss'],
result_dict['gl_loss'] * self.gl_loss_lambda,
result_dict['crf_loss'], val_res))
# evaluate model performance according to configured metric, check early stop, and
# save best checkpoint as model_best
best = False
if self.monitor_mode != 'off' and self.do_validation:
best, not_improved_count = self._is_best_monitor_metric(best, not_improved_count, val_result_dict)
if not_improved_count > self.early_stop:
self.logger_info("Validation performance didn't improve for {} epochs. "
"Training stops.".format(self.early_stop))
break
if epoch % self.save_period == 0:
self._save_checkpoint(epoch, save_best=best)
def _is_best_monitor_metric(self, best, not_improved_count, val_result_dict):
"""
monitor metric
:param best:
:param not_improved_count:
:param val_result_dict:
:return:
"""
entity_name, metric = self.monitor_metric.split('-')
val_monitor_metric_res = val_result_dict[entity_name][metric]
try:
# check whether model performance improved or not, according to specified metric(monitor_metric)
improved = (self.monitor_mode == 'min' and val_monitor_metric_res <= self.monitor_best) or \
(self.monitor_mode == 'max' and val_monitor_metric_res >= self.monitor_best)
except KeyError:
self.logger_warning("Warning: Metric '{}' is not found. "
"Model performance monitoring is disabled.".format(self.monitor_metric))
self.monitor_mode = 'off'
improved = False
if improved:
self.monitor_best = val_monitor_metric_res
not_improved_count = 0
best = True
else:
not_improved_count += 1
return best, not_improved_count
def _train_epoch(self, epoch):
"""
Training logic for an epoch
:param epoch: Integer, current training epoch.
:return: A log dict that contains average loss and metric in this epoch.
"""
self.model.train()
self.train_loss_metrics.reset()
# step iteration start ##
for step_idx, input_data_item in enumerate(self.data_loader):
step_idx += 1
for key, input_value in input_data_item.items():
if input_value is not None and isinstance(input_value, torch.Tensor):
input_data_item[key] = input_value.to(self.device, non_blocking=True)
if self.config['trainer']['anomaly_detection']:
# This mode will increase the runtime and should only be enabled for debugging
with torch.autograd.detect_anomaly():
self.optimizer.zero_grad()
# model forward
output = self.model(**input_data_item)
# calculate loss
gl_loss = output['gl_loss']
crf_loss = output['crf_loss']
total_loss = torch.sum(crf_loss) + self.gl_loss_lambda * torch.sum(gl_loss)
# backward
total_loss.backward()
# self.average_gradients(self.model)
self.optimizer.step()
else:
self.optimizer.zero_grad()
# model forward
output = self.model(**input_data_item)
# calculate loss
gl_loss = output['gl_loss']
crf_loss = output['crf_loss']
total_loss = torch.sum(crf_loss) + self.gl_loss_lambda * torch.sum(gl_loss)
# backward
total_loss.backward()
# self.average_gradients(self.model)
self.optimizer.step()
# Use a barrier() to make sure that all process have finished forward and backward
if self.distributed:
dist.barrier()
# obtain the sum of all total_loss at all processes
dist.all_reduce(total_loss, op=dist.reduce_op.SUM)
size = dist.get_world_size()
else:
size = 1
gl_loss /= size # averages gl_loss across the whole world
crf_loss /= size # averages crf_loss across the whole world
# calculate average loss across the batch size
avg_gl_loss = torch.mean(gl_loss)
avg_crf_loss = torch.mean(crf_loss)
avg_loss = avg_crf_loss + self.gl_loss_lambda * avg_gl_loss
# update metrics
# self.writer.set_step((epoch - 1) * self.len_step + step_idx - 1) if self.local_master else None
self.train_loss_metrics.update('loss', avg_loss.item(), epoch)
self.train_loss_metrics.update('gl_loss', avg_gl_loss.item() * self.gl_loss_lambda, epoch)
self.train_loss_metrics.update('crf_loss', avg_crf_loss.item(), epoch)
# log messages
if step_idx % self.log_step == 0:
self.logger_info('Train Epoch:[{}/{}] Step:[{}/{}] Total Loss: {:.6f} GL_Loss: {:.6f} CRF_Loss: {:.6f}'.
format(epoch, self.epochs, step_idx, self.len_step,
avg_loss.item(), avg_gl_loss.item() * self.gl_loss_lambda, avg_crf_loss.item()))
# decide whether continue iter
if step_idx == self.len_step + 1:
break
# step iteration end ##
# do validation after val_step_interval iteration
if self.do_validation and epoch % self.val_epoch_interval == 0:
val_result_dict = self._valid_epoch(epoch)
self.logger_info('[Step Validation] Epoch:[{}/{}]] \n{}'.
format(epoch, self.epochs, self.len_step,
SpanBasedF1MetricTracker.dict2str(val_result_dict)))
# check if best metric, if true, then save as model_best checkpoint.
best, not_improved_count = self._is_best_monitor_metric(False, 0, val_result_dict)
if best:
self._save_checkpoint(epoch, best)
# {'loss': avg_loss, 'gl_loss': avg_gl_loss, 'crf_loss': avg_crf_loss}
log = self.train_loss_metrics.result()
# do validation after training an epoch
if self.do_validation:
val_result_dict = self._valid_epoch(epoch)
log['val_result_dict'] = val_result_dict
if self.lr_scheduler is not None:
self.lr_scheduler.step()
self.model.train()
return log
def _valid_epoch(self, epoch):
"""
Validate after training an epoch or regular step, this is a time-consuming procedure if validation data is big.
:param epoch: Integer, current training epoch.
:return: A dict that contains information about validation
"""
self.model.eval()
self.valid_f1_metrics.reset()
with torch.no_grad():
for step_idx, input_data_item in enumerate(self.valid_data_loader):
for key, input_value in input_data_item.items():
if input_value is not None and isinstance(input_value, torch.Tensor):
input_data_item[key] = input_value.to(self.device, non_blocking=True)
output = self.model(**input_data_item)
logits = output['logits']
new_mask = output['new_mask']
if hasattr(self.model, 'module'):
# List[(List[int], torch.Tensor)] contain the tag indices of the maximum likelihood tag sequence.
# and the score of the viterbi path.
best_paths = self.model.module.decoder.crf_layer.viterbi_tags(logits, mask=new_mask,
logits_batch_first=True)
else:
best_paths = self.model.decoder.crf_layer.viterbi_tags(logits, mask=new_mask,
logits_batch_first=True)
predicted_tags = []
for path, score in best_paths:
predicted_tags.append(path)
# self.writer.set_step((epoch - 1) * len(self.valid_data_loader) + step_idx, 'valid') \
# if self.local_master else None
# calculate and update f1 metrics
# (B, N*T, out_dim)
predicted_tags_hard_prob = logits * 0
for i, instance_tags in enumerate(predicted_tags):
for j, tag_id in enumerate(instance_tags):
predicted_tags_hard_prob[i, j, tag_id] = 1
golden_tags = input_data_item['iob_tags_label']
mask = input_data_item['mask']
union_iob_tags = to_union(golden_tags, mask, self.iob_labels_vocab_cls)
if self.distributed:
dist.barrier() #
self.valid_f1_metrics.update(predicted_tags_hard_prob.long(), union_iob_tags, new_mask)
# add histogram of model parameters to the tensorboard
# for name, p in self.model.named_parameters():
# self.writer.add_histogram(name, p, bins='auto')
f1_result_dict = self.valid_f1_metrics.result()
overall_dict = f1_result_dict['overall']
if self.local_master:
for key, value in overall_dict.items():
self.writer.add_scalar(key, value, epoch)
return f1_result_dict
@staticmethod
def average_gradients(model):
"""
Gradient averaging
:param model:
:return:
"""
size = float(dist.get_world_size())
for param in model.parameters():
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM)
param.grad.data /= size
def logger_info(self, msg):
self.logger.info(msg) if self.local_master else None
def logger_warning(self, msg):
self.logger.warning(msg) if self.local_master else None
def _prepare_device(self, local_rank, local_world_size):
"""
setup GPU device if available, move model into configured device
:param local_rank:
:param local_world_size:
:return:
"""
if self.distributed:
n_gpu_per_process = torch.cuda.device_count() // local_world_size
device_ids = list(range(local_rank * n_gpu_per_process, (local_rank + 1) * n_gpu_per_process))
if torch.cuda.is_available() and local_rank != -1:
torch.cuda.set_device(device_ids[0]) # device_ids[0] =local_rank if local_world_size = n_gpu per node
device = 'cuda'
self.logger_info(
f"[Process {os.getpid()}] world_size = {dist.get_world_size()}, "
+ f"rank = {dist.get_rank()}, n_gpu/process = {n_gpu_per_process}, device_ids = {device_ids}"
)
else:
self.logger_warning('Training will be using CPU!')
device = 'cpu'
device = torch.device(device)
return device, device_ids
else:
n_gpu = torch.cuda.device_count()
n_gpu_use = local_world_size
if n_gpu_use > 0 and n_gpu == 0:
self.logger_warning("Warning: There\'s no GPU available on this machine,"
"training will be performed on CPU.")
n_gpu_use = 0
if n_gpu_use > n_gpu:
self.logger_warning("Warning: The number of GPU\'s configured to use is {}, but only {} are available "
"on this machine.".format(n_gpu_use, n_gpu))
n_gpu_use = n_gpu
list_ids = list(range(n_gpu_use))
if n_gpu_use > 0:
torch.cuda.set_device(list_ids[0]) # only use first available gpu as devices
self.logger_warning(f'Training is using GPU {list_ids[0]}!')
device = 'cuda'
else:
self.logger_warning('Training is using CPU!')
device = 'cpu'
device = torch.device(device)
return device, list_ids
def _save_checkpoint(self, epoch, save_best=False):
"""
Saving checkpoints
:param epoch: current epoch number
:param save_best: if True, rename the saved checkpoint to 'model_best.pth'
:return:
"""
# only local master process do save model
if not self.local_master:
return
if hasattr(self.model, 'module'):
arch = type(self.model.module).__name__
state_dict = self.model.module.state_dict()
else:
arch = type(self.model).__name__
state_dict = self.model.state_dict()
state = {
'arch': arch,
'epoch': epoch,
'state_dict': state_dict,
'optimizer': self.optimizer.state_dict(),
'monitor_best': self.monitor_best,
'config': self.config
}
if save_best:
best_path = str(self.checkpoint_dir / 'model_best.pth')
torch.save(state, best_path)
self.logger_info("Saving current best: model_best.pth ...")
else:
filename = str(self.checkpoint_dir / 'checkpoint-epoch{}.pth'.format(epoch))
torch.save(state, filename)
self.logger_info("Saving checkpoint: {} ...".format(filename))
def _resume_checkpoint(self, resume_path):
"""
Resume from saved checkpoints
:param resume_path: Checkpoint path to be resumed
:return:
"""
resume_path = str(resume_path)
self.logger_info("Loading checkpoint: {} ...".format(resume_path))
# map_location = {'cuda:%d' % 0: 'cuda:%d' % self.config['local_rank']}
checkpoint = torch.load(resume_path, map_location=self.device)
self.start_epoch = checkpoint['epoch'] + 1
self.monitor_best = checkpoint['monitor_best']
# load architecture params from checkpoint.
if checkpoint['config']['model_arch'] != self.config['model_arch']:
self.logger_warning("Warning: Architecture configuration given in config file is different from that of "
"checkpoint. This may yield an exception while state_dict is being loaded.")
self.model.load_state_dict(checkpoint['state_dict'])
# load optimizer state from checkpoint only when optimizer type is not changed.
if checkpoint['config']['optimizer']['type'] != self.config['optimizer']['type']:
self.logger_warning("Warning: Optimizer type given in config file is different from that of checkpoint. "
"Optimizer parameters not being resumed.")
else:
self.optimizer.load_state_dict(checkpoint['optimizer'])
self.logger_info("Checkpoint loaded. Resume training from epoch {}".format(self.start_epoch))
| 44.088296 | 120 | 0.589912 |
import os
import numpy as np
from numpy import inf
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from src.utils import inf_loop
from src.utils.metrics import MetricTracker, SpanBasedF1MetricTracker
from torch.utils.tensorboard import SummaryWriter
from src.utils.utils import to_union
class Trainer:
def __init__(self, model, optimizer, config, data_loader, iob_labels_vocab_cls,
valid_data_loader=None, lr_scheduler=None, max_len_step=None):
self.config = config
self.iob_labels_vocab_cls = iob_labels_vocab_cls
self.distributed = config['distributed']
if self.distributed:
self.local_master = (config['local_rank'] == 0)
self.global_master = (dist.get_rank() == 0)
else:
self.local_master = True
self.global_master = True
self.logger = config.get_logger('trainer', config['trainer']['log_verbosity']) if self.local_master else None
self.device, self.device_ids = self._prepare_device(config['local_rank'], config['local_world_size'])
self.model = model.to(self.device)
self.optimizer = optimizer
cfg_trainer = config['trainer']
self.epochs = cfg_trainer['epochs']
self.save_period = cfg_trainer['save_period']
monitor_open = cfg_trainer['monitor_open']
if monitor_open:
self.monitor = cfg_trainer.get('monitor', 'off')
else:
self.monitor = 'off'
if self.monitor == 'off':
self.monitor_mode = 'off'
self.monitor_best = 0
else:
self.monitor_mode, self.monitor_metric = self.monitor.split()
assert self.monitor_mode in ['min', 'max']
self.monitor_best = inf if self.monitor_mode == 'min' else -inf
self.early_stop = cfg_trainer.get('early_stop', inf)
self.early_stop = inf if self.early_stop == -1 else self.early_stop
self.start_epoch = 1
if self.local_master:
self.checkpoint_dir = config.save_dir
self.writer = SummaryWriter(config.tensorboard_dir)
if config.resume is not None:
self._resume_checkpoint(config.resume)
if self.config['trainer']['sync_batch_norm'] and self.distributed:
self.model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(self.model)
if self.distributed:
self.model = DDP(self.model, device_ids=self.device_ids, output_device=self.device_ids[0],
find_unused_parameters=True)
self.data_loader = data_loader
if max_len_step is None:
self.len_step = len(self.data_loader)
else:
self.data_loader = inf_loop(data_loader)
self.len_step = max_len_step
self.valid_data_loader = valid_data_loader
self.do_validation = self.valid_data_loader is not None
self.lr_scheduler = lr_scheduler
log_step = self.config['trainer']['log_step_interval']
self.log_step = log_step if log_step != -1 and 0 < log_step < self.len_step else int(
np.sqrt(data_loader.batch_size))
self.val_epoch_interval = self.config['trainer']['val_epoch_interval']
self.gl_loss_lambda = self.config['trainer']['gl_loss_lambda']
self.train_loss_metrics = MetricTracker('loss', 'gl_loss', 'crf_loss',
writer=self.writer if self.local_master else None)
self.valid_f1_metrics = SpanBasedF1MetricTracker(iob_labels_vocab_cls)
def train(self):
if self.distributed:
dist.barrier()
not_improved_count = 0
val_result_dict = None
if self.config['evaluate_only']:
print("------Evaluation only------")
val_result_dict = self._valid_epoch(0)
val_res = SpanBasedF1MetricTracker.dict2str(val_result_dict)
self.logger_info('[Step Validation] Epoch:[{}/{}]] \n{}'.
format(0, self.epochs, val_res))
return
for epoch in range(self.start_epoch, self.epochs + 1):
if self.distributed:
self.data_loader.sampler.set_epoch(epoch)
result_dict = self._train_epoch(epoch)
if self.do_validation:
val_result_dict = result_dict['val_result_dict']
val_res = SpanBasedF1MetricTracker.dict2str(val_result_dict)
else:
val_res = ''
self.logger_info('[Epoch Validation] Epoch:[{}/{}] Total Loss: {:.6f} '
'GL_Loss: {:.6f} CRF_Loss: {:.6f} \n{}'.
format(epoch, self.epochs, result_dict['loss'],
result_dict['gl_loss'] * self.gl_loss_lambda,
result_dict['crf_loss'], val_res))
best = False
if self.monitor_mode != 'off' and self.do_validation:
best, not_improved_count = self._is_best_monitor_metric(best, not_improved_count, val_result_dict)
if not_improved_count > self.early_stop:
self.logger_info("Validation performance didn't improve for {} epochs. "
"Training stops.".format(self.early_stop))
break
if epoch % self.save_period == 0:
self._save_checkpoint(epoch, save_best=best)
def _is_best_monitor_metric(self, best, not_improved_count, val_result_dict):
entity_name, metric = self.monitor_metric.split('-')
val_monitor_metric_res = val_result_dict[entity_name][metric]
try:
# check whether model performance improved or not, according to specified metric(monitor_metric)
improved = (self.monitor_mode == 'min' and val_monitor_metric_res <= self.monitor_best) or \
(self.monitor_mode == 'max' and val_monitor_metric_res >= self.monitor_best)
except KeyError:
self.logger_warning("Warning: Metric '{}' is not found. "
"Model performance monitoring is disabled.".format(self.monitor_metric))
self.monitor_mode = 'off'
improved = False
if improved:
self.monitor_best = val_monitor_metric_res
not_improved_count = 0
best = True
else:
not_improved_count += 1
return best, not_improved_count
def _train_epoch(self, epoch):
self.model.train()
self.train_loss_metrics.reset()
# step iteration start ##
for step_idx, input_data_item in enumerate(self.data_loader):
step_idx += 1
for key, input_value in input_data_item.items():
if input_value is not None and isinstance(input_value, torch.Tensor):
input_data_item[key] = input_value.to(self.device, non_blocking=True)
if self.config['trainer']['anomaly_detection']:
# This mode will increase the runtime and should only be enabled for debugging
with torch.autograd.detect_anomaly():
self.optimizer.zero_grad()
# model forward
output = self.model(**input_data_item)
# calculate loss
gl_loss = output['gl_loss']
crf_loss = output['crf_loss']
total_loss = torch.sum(crf_loss) + self.gl_loss_lambda * torch.sum(gl_loss)
# backward
total_loss.backward()
# self.average_gradients(self.model)
self.optimizer.step()
else:
self.optimizer.zero_grad()
# model forward
output = self.model(**input_data_item)
# calculate loss
gl_loss = output['gl_loss']
crf_loss = output['crf_loss']
total_loss = torch.sum(crf_loss) + self.gl_loss_lambda * torch.sum(gl_loss)
# backward
total_loss.backward()
# self.average_gradients(self.model)
self.optimizer.step()
# Use a barrier() to make sure that all process have finished forward and backward
if self.distributed:
dist.barrier()
# obtain the sum of all total_loss at all processes
dist.all_reduce(total_loss, op=dist.reduce_op.SUM)
size = dist.get_world_size()
else:
size = 1
gl_loss /= size # averages gl_loss across the whole world
crf_loss /= size # averages crf_loss across the whole world
# calculate average loss across the batch size
avg_gl_loss = torch.mean(gl_loss)
avg_crf_loss = torch.mean(crf_loss)
avg_loss = avg_crf_loss + self.gl_loss_lambda * avg_gl_loss
# update metrics
# self.writer.set_step((epoch - 1) * self.len_step + step_idx - 1) if self.local_master else None
self.train_loss_metrics.update('loss', avg_loss.item(), epoch)
self.train_loss_metrics.update('gl_loss', avg_gl_loss.item() * self.gl_loss_lambda, epoch)
self.train_loss_metrics.update('crf_loss', avg_crf_loss.item(), epoch)
# log messages
if step_idx % self.log_step == 0:
self.logger_info('Train Epoch:[{}/{}] Step:[{}/{}] Total Loss: {:.6f} GL_Loss: {:.6f} CRF_Loss: {:.6f}'.
format(epoch, self.epochs, step_idx, self.len_step,
avg_loss.item(), avg_gl_loss.item() * self.gl_loss_lambda, avg_crf_loss.item()))
# decide whether continue iter
if step_idx == self.len_step + 1:
break
# step iteration end ##
# do validation after val_step_interval iteration
if self.do_validation and epoch % self.val_epoch_interval == 0:
val_result_dict = self._valid_epoch(epoch)
self.logger_info('[Step Validation] Epoch:[{}/{}]] \n{}'.
format(epoch, self.epochs, self.len_step,
SpanBasedF1MetricTracker.dict2str(val_result_dict)))
# check if best metric, if true, then save as model_best checkpoint.
best, not_improved_count = self._is_best_monitor_metric(False, 0, val_result_dict)
if best:
self._save_checkpoint(epoch, best)
# {'loss': avg_loss, 'gl_loss': avg_gl_loss, 'crf_loss': avg_crf_loss}
log = self.train_loss_metrics.result()
# do validation after training an epoch
if self.do_validation:
val_result_dict = self._valid_epoch(epoch)
log['val_result_dict'] = val_result_dict
if self.lr_scheduler is not None:
self.lr_scheduler.step()
self.model.train()
return log
def _valid_epoch(self, epoch):
self.model.eval()
self.valid_f1_metrics.reset()
with torch.no_grad():
for step_idx, input_data_item in enumerate(self.valid_data_loader):
for key, input_value in input_data_item.items():
if input_value is not None and isinstance(input_value, torch.Tensor):
input_data_item[key] = input_value.to(self.device, non_blocking=True)
output = self.model(**input_data_item)
logits = output['logits']
new_mask = output['new_mask']
if hasattr(self.model, 'module'):
# List[(List[int], torch.Tensor)] contain the tag indices of the maximum likelihood tag sequence.
# and the score of the viterbi path.
best_paths = self.model.module.decoder.crf_layer.viterbi_tags(logits, mask=new_mask,
logits_batch_first=True)
else:
best_paths = self.model.decoder.crf_layer.viterbi_tags(logits, mask=new_mask,
logits_batch_first=True)
predicted_tags = []
for path, score in best_paths:
predicted_tags.append(path)
# self.writer.set_step((epoch - 1) * len(self.valid_data_loader) + step_idx, 'valid') \
# if self.local_master else None
# calculate and update f1 metrics
# (B, N*T, out_dim)
predicted_tags_hard_prob = logits * 0
for i, instance_tags in enumerate(predicted_tags):
for j, tag_id in enumerate(instance_tags):
predicted_tags_hard_prob[i, j, tag_id] = 1
golden_tags = input_data_item['iob_tags_label']
mask = input_data_item['mask']
union_iob_tags = to_union(golden_tags, mask, self.iob_labels_vocab_cls)
if self.distributed:
dist.barrier() #
self.valid_f1_metrics.update(predicted_tags_hard_prob.long(), union_iob_tags, new_mask)
# add histogram of model parameters to the tensorboard
# for name, p in self.model.named_parameters():
# self.writer.add_histogram(name, p, bins='auto')
f1_result_dict = self.valid_f1_metrics.result()
overall_dict = f1_result_dict['overall']
if self.local_master:
for key, value in overall_dict.items():
self.writer.add_scalar(key, value, epoch)
return f1_result_dict
@staticmethod
def average_gradients(model):
size = float(dist.get_world_size())
for param in model.parameters():
dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM)
param.grad.data /= size
def logger_info(self, msg):
self.logger.info(msg) if self.local_master else None
def logger_warning(self, msg):
self.logger.warning(msg) if self.local_master else None
def _prepare_device(self, local_rank, local_world_size):
if self.distributed:
n_gpu_per_process = torch.cuda.device_count() // local_world_size
device_ids = list(range(local_rank * n_gpu_per_process, (local_rank + 1) * n_gpu_per_process))
if torch.cuda.is_available() and local_rank != -1:
torch.cuda.set_device(device_ids[0]) # device_ids[0] =local_rank if local_world_size = n_gpu per node
device = 'cuda'
self.logger_info(
f"[Process {os.getpid()}] world_size = {dist.get_world_size()}, "
+ f"rank = {dist.get_rank()}, n_gpu/process = {n_gpu_per_process}, device_ids = {device_ids}"
)
else:
self.logger_warning('Training will be using CPU!')
device = 'cpu'
device = torch.device(device)
return device, device_ids
else:
n_gpu = torch.cuda.device_count()
n_gpu_use = local_world_size
if n_gpu_use > 0 and n_gpu == 0:
self.logger_warning("Warning: There\'s no GPU available on this machine,"
"training will be performed on CPU.")
n_gpu_use = 0
if n_gpu_use > n_gpu:
self.logger_warning("Warning: The number of GPU\'s configured to use is {}, but only {} are available "
"on this machine.".format(n_gpu_use, n_gpu))
n_gpu_use = n_gpu
list_ids = list(range(n_gpu_use))
if n_gpu_use > 0:
torch.cuda.set_device(list_ids[0]) # only use first available gpu as devices
self.logger_warning(f'Training is using GPU {list_ids[0]}!')
device = 'cuda'
else:
self.logger_warning('Training is using CPU!')
device = 'cpu'
device = torch.device(device)
return device, list_ids
def _save_checkpoint(self, epoch, save_best=False):
# only local master process do save model
if not self.local_master:
return
if hasattr(self.model, 'module'):
arch = type(self.model.module).__name__
state_dict = self.model.module.state_dict()
else:
arch = type(self.model).__name__
state_dict = self.model.state_dict()
state = {
'arch': arch,
'epoch': epoch,
'state_dict': state_dict,
'optimizer': self.optimizer.state_dict(),
'monitor_best': self.monitor_best,
'config': self.config
}
if save_best:
best_path = str(self.checkpoint_dir / 'model_best.pth')
torch.save(state, best_path)
self.logger_info("Saving current best: model_best.pth ...")
else:
filename = str(self.checkpoint_dir / 'checkpoint-epoch{}.pth'.format(epoch))
torch.save(state, filename)
self.logger_info("Saving checkpoint: {} ...".format(filename))
def _resume_checkpoint(self, resume_path):
resume_path = str(resume_path)
self.logger_info("Loading checkpoint: {} ...".format(resume_path))
# map_location = {'cuda:%d' % 0: 'cuda:%d' % self.config['local_rank']}
checkpoint = torch.load(resume_path, map_location=self.device)
self.start_epoch = checkpoint['epoch'] + 1
self.monitor_best = checkpoint['monitor_best']
# load architecture params from checkpoint.
if checkpoint['config']['model_arch'] != self.config['model_arch']:
self.logger_warning("Warning: Architecture configuration given in config file is different from that of "
"checkpoint. This may yield an exception while state_dict is being loaded.")
self.model.load_state_dict(checkpoint['state_dict'])
# load optimizer state from checkpoint only when optimizer type is not changed.
if checkpoint['config']['optimizer']['type'] != self.config['optimizer']['type']:
self.logger_warning("Warning: Optimizer type given in config file is different from that of checkpoint. "
"Optimizer parameters not being resumed.")
else:
self.optimizer.load_state_dict(checkpoint['optimizer'])
self.logger_info("Checkpoint loaded. Resume training from epoch {}".format(self.start_epoch))
| true | true |
f727f6cf011e2798bbf44b01f9e61c7dbe87ceb3 | 142 | py | Python | gala/potential/potential/__init__.py | zilishen/gala | f7184e6b09fbc42a349f6b5a2bca6242f1e9936e | [
"MIT"
] | 1 | 2020-11-20T18:27:25.000Z | 2020-11-20T18:27:25.000Z | gala/potential/potential/__init__.py | ltlancas/gala | 2621bb599d67e74a85446abf72d5930ef70ca181 | [
"MIT"
] | 3 | 2021-07-26T15:07:25.000Z | 2021-09-13T15:04:27.000Z | gala/potential/potential/__init__.py | ltlancas/gala | 2621bb599d67e74a85446abf72d5930ef70ca181 | [
"MIT"
] | 1 | 2018-10-23T23:20:20.000Z | 2018-10-23T23:20:20.000Z | from .core import *
from .cpotential import *
from .ccompositepotential import *
from .builtin import *
from .io import *
from .util import *
| 20.285714 | 34 | 0.746479 | from .core import *
from .cpotential import *
from .ccompositepotential import *
from .builtin import *
from .io import *
from .util import *
| true | true |
f727f7ba434ba285d0316a1377f3b4ae81748ed9 | 22,575 | py | Python | scrap_players.py | Toulik1729231/WebScraping1-Using-Python | 42562c66c905f925ea0848b8ae7dfbca6b5a1afd | [
"MIT"
] | null | null | null | scrap_players.py | Toulik1729231/WebScraping1-Using-Python | 42562c66c905f925ea0848b8ae7dfbca6b5a1afd | [
"MIT"
] | null | null | null | scrap_players.py | Toulik1729231/WebScraping1-Using-Python | 42562c66c905f925ea0848b8ae7dfbca6b5a1afd | [
"MIT"
] | null | null | null | import requests
from bs4 import BeautifulSoup
from logger_impl import *
import MongoDao
import pandas as pd
import time
payload = {'key': 'ac9e8cf2dec81949d9ee1235ed6ae3fb', 'url':
'https://httpbin.org/ip'}
def scrapData(scorecardSoup, matchId, matchDesc, matchTypeText, pageUrl, season, Date, venue):
#pageUrl = "http://www.espncricinfo.com/series/11422/scorecard/858491/bangladesh-vs-pakistan-only-t20i-pakistan-tour-of-bangladesh-2015"
try:
"""page = urllib.request.urlopen(pageUrl)
## get match-id and match-name from url
pageUrlArr = pageUrl.split('/')
matchId = pageUrlArr[len(pageUrlArr ) - 2]
matchDesc = pageUrlArr[len(pageUrlArr ) - 1] """
#soup = BeautifulSoup(page, 'html.parser')
soup = scorecardSoup
#print("page html: ", soup.prettify())
scorecardDiv = soup.find_all('article', class_='sub-module scorecard')
playerBatsmanDict = {}
playerBowlerDict = {}
batsmanScorecardParam = ['run_scored', 'balls_faced','M', '4s', '6s', 'strike_rate']
bowlerScorecardParam = ['O', 'M', 'R', 'W', 'Econ', 'WD', 'NB']
teamList = []
teamIDList = []
inningsTeam = []
## print(len(scorecardDiv))
#creating playing team list
for scorecardVal in scorecardDiv:
#print(scorecardVal)
team = scorecardVal.find('h2').get_text()
if matchTypeText == 'Tests':
team = str(team).replace('1st Innings', '').replace('2nd Innings', '')
else:
team = str(team).replace('Innings', '')
if team.strip() in teamList:
break
teamList.append(team.strip())
count = {teamList[0]:0,teamList[1]:0}
for team in teamList:
word = team.split(' ')
if len(word) == 1:
id_ = team[:3]
teamIDList.append(id_)
else:
id_ = ''
for x in word:
id_ = id_ + x[0]
teamIDList.append(id_)
for scorecardVal in scorecardDiv:
team = scorecardVal.find('h2').get_text()
inn = ''
if matchTypeText == 'Tests':
inn = ' '.join(str(team).split(' ')[-2:])
team = str(team).replace('1st Innings', '').replace('2nd Innings', '')
else:
team = str(team).replace('Innings', '')
team = team.strip()
count[team] += 1
## print(count)
logger.info("team: " + team)
#print("batsman div: ", scorecardVal)
batsmanList = scorecardVal.find_all('div', class_='wrap batsmen')
batsmanListNotBatted = scorecardVal.find('div', class_='wrap dnb').find_all('a')
## for bt in batsmanListNotBatted:
## print(bt.get('href'))
## print(bt.get_text())
for batsman in batsmanList:
batsmanDict = {}
#print("batsman data: ", batsman)
batsmanAnchor = batsman.find('div', class_="cell batsmen").find('a')
batsmanLink = batsmanAnchor.get('href')
batsmanName = batsmanAnchor.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
#print("batsman Name: ", batsmanName, " batsmanId: ", cricInfoBatsmanId)
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
#print("batsmanDiv: ", batsmanDiv.get_text())
try:
commentry = batsman.find('div', class_="cell commentary").find('a').get_text()
batsmanDict['commentry'] = commentry
except AttributeError as ae:
batsmanDict['commentry'] = ''
#print("batsman commentry: ", commentry)
#print("commentryDiv: ", commentryDiv.get_text())
batsmanStatsList = batsman.find_all('div', class_="cell runs")
ctr = 0
tempList = []
for batsmanStats in batsmanStatsList:
#print("anchor: ", batsmanStats.get_text())
#param = batsmanScorecardParam[ctr]
#ctr += 1
#batsmanDict[param] = batsmanStats.get_text()
tempList.append(batsmanStats.get_text())
if len(tempList) == 6:
batsmanDict['run_scored'] = tempList[0]
batsmanDict['balls_faced'] = tempList[1]
batsmanDict['M'] = tempList[2]
batsmanDict['4s'] = tempList[3]
batsmanDict['6s'] = tempList[4]
batsmanDict['strike_rate'] = tempList[5]
else:
batsmanDict['run_scored'] = tempList[0]
batsmanDict['balls_faced'] = tempList[1]
batsmanDict['M'] = '-'
batsmanDict['4s'] = tempList[2]
batsmanDict['6s'] = tempList[3]
batsmanDict['strike_rate'] = tempList[4]
batsmanDict['innings'] = inn
key = cricInfoBatsmanId# + "_" + team
if matchTypeText == 'Tests':
key = key + inn[0]
playerBatsmanDict[key] = batsmanDict
#break
## print(batsmanListNotBatted)
for batsmen in batsmanListNotBatted:
batsmanDict={}
batsmanLink = batsmen.get('href')
batsmanName = batsmen.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
batsmanDict['run_scored'] = '-'
batsmanDict['balls_faced'] = '-'
batsmanDict['M'] = '-'
batsmanDict['4s'] = '-'
batsmanDict['6s'] = '-'
batsmanDict['strike_rate'] = '-'
batsmanDict['innings'] = inn
key = cricInfoBatsmanId# + "_" + team
#print('id : ',cricInfoBatsmanId)
#print('key : ',key)
#print(batsmanDict)
if matchTypeText == 'Tests':
key = key+inn[0]
playerBatsmanDict[key] = batsmanDict
#print('Dict added : ',playerBatsmanDict[key])
bowlersTR = scorecardVal.find('tbody').find_all('tr')
#print("bowler section: ", bowlersTR)
for bowlerRow in bowlersTR:
bowlersTD = bowlerRow.find_all('td')
bowlerAnchor = bowlersTD[0].find('a')
bowlerLink = bowlerAnchor.get('href')
bowlerName = bowlerAnchor.get_text()
#print("bowler name: ", bowlerName, " link: ", bowlerLink)
bowlerLinkArr = str(bowlerLink).split('/')
cricInfoBowlerId = bowlerLinkArr[len(bowlerLinkArr) - 1]
cricInfoBowlerId = str(cricInfoBowlerId).replace('.html', '')
logger.info("bowlersTD: " + str(bowlersTD))
logger.info("length bowlersTD: " + str(len(bowlersTD)))
if len(bowlersTD) == 13:
overs = bowlersTD[2].find(text=True)
maidens = bowlersTD[3].find(text=True)
runs = bowlersTD[4].find(text=True)
wickets = bowlersTD[5].find(text=True)
economy = bowlersTD[6].find(text=True)
dotBalls = bowlersTD[7].find(text=True)
ballerFours = bowlersTD[8].find(text=True)
ballerSixes = bowlersTD[9].find(text=True)
wideBalls = bowlersTD[10].find(text=True)
noBalls = bowlersTD[11].find(text=True)
else:
overs = bowlersTD[2].find(text=True)
maidens = bowlersTD[3].find(text=True)
runs = bowlersTD[4].find(text=True)
wickets = bowlersTD[5].find(text=True)
economy = bowlersTD[6].find(text=True)
dotBalls = 0
ballerFours = 0
ballerSixes = 0
wideBalls = bowlersTD[7].find(text=True)
noBalls = bowlersTD[8].find(text=True)
## print('o'+overs)
## print(maidens)
## print(runs)
## print(wickets)
## print(economy)
## print(dotBalls)
## print(ballerFours)
## print(ballerSixes)
## print(wideBalls)
## print(noBalls)
#['O', 'M', 'R', 'W', 'Econ', 'WD', 'NB']
bowlerDict = {}
bowlerDict['short_name'] = bowlerName
bowlerDict['player_cric_info_link'] = bowlerLink
if '.' in overs:
oversArr = overs.split('.')
totalBalls: int = int(oversArr[0]) * 6
totalBalls += int(oversArr[1])
else:
totalBalls: int = int(overs) * 6
# getting the bowling team name
if team == teamList[0]:
bowlingTeam = teamList[1]
else:
bowlingTeam = teamList[0]
bowlerDict['team'] = bowlingTeam
bowlerDict['balls_bowled'] = totalBalls
bowlerDict['maiden_overs'] = maidens
bowlerDict['runs_given'] = runs
bowlerDict['wicket'] = wickets
bowlerDict['econ'] = economy
bowlerDict['dot_delivery'] = dotBalls
bowlerDict['four_delivery'] = ballerFours
bowlerDict['six_delivery'] = ballerSixes
bowlerDict['wide_balls'] = wideBalls
bowlerDict['no_balls'] = noBalls
bowlerDict['innings'] = inn
#print(overs, maidens, runs, wickets, economy, wideBalls, noBalls)
key = cricInfoBowlerId# + "_" + team
if matchTypeText == 'Tests':
key = key+inn[0]
playerBowlerDict[key] = bowlerDict
#print("batsmanDict: ", playerBatsmanDict)
#print("bowlerDict: ", playerBowlerDict)
if matchTypeText == 'Tests' and ((count[teamList[0]] == 2 and count[teamList[1]] == 1) or (count[teamList[0]] == 1 and count[teamList[1]] == 2)):
# if
missing = ''
if count[teamList[0]] == 1:
missing = teamList[0]
elif count[teamList[1]] == 1:
missing = teamList[1]
for scorecardVal in scorecardDiv:
team = scorecardVal.find('h2').get_text()
inn = ' '.join(str(team).split(' ')[-2:])
team = str(team).replace('1st Innings', '').replace('2nd Innings', '')
team = team.strip()
if team == missing:
batsmanList = scorecardVal.find_all('div', class_='wrap batsmen')
batsmanListNotBatted = scorecardVal.find('div', class_='wrap dnb').find_all('a')
for batsman in batsmanList:
batsmanDict = {}
batsmanAnchor = batsman.find('div', class_="cell batsmen").find('a')
batsmanLink = batsmanAnchor.get('href')
batsmanName = batsmanAnchor.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
batsmanDict['run_scored'] = '-'
batsmanDict['balls_faced'] = '-'
batsmanDict['M'] = '-'
batsmanDict['4s'] = '-'
batsmanDict['6s'] = '-'
batsmanDict['strike_rate'] = '-'
batsmanDict['innings'] = '2nd Innings'
## print(batsmanList)
key = cricInfoBatsmanId
batsmanDict['commentry'] = '-'
if matchTypeText == 'Tests':
key = key+'2'
playerBatsmanDict[key] = batsmanDict
for batsmen in batsmanListNotBatted:
batsmanLink = batsmen.get('href')
batsmanName = batsmen.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
batsmanDict['run_scored'] = '-'
batsmanDict['balls_faced'] = '-'
batsmanDict['M'] = '-'
batsmanDict['4s'] = '-'
batsmanDict['6s'] = '-'
batsmanDict['strike_rate'] = '-'
batsmanDict['innings'] = '2nd Innings'
key = cricInfoBatsmanId# + "_" + team
if matchTypeText == 'Tests':
key = key+'2'
playerBatsmanDict[key] = batsmanDict
# checking batsman in bowler map, if found add them in playerBatsmanDict
if matchTypeText == 'Tests':
for batsmanKey, batsmanValue in playerBatsmanDict.items():
if batsmanKey in playerBowlerDict:
if playerBatsmanDict[batsmanKey]['innings'] == playerBowlerDict[batsmanKey]['innings']:
bowlerData = playerBowlerDict[batsmanKey]
fianlDict = {**batsmanValue, **bowlerData}
playerBatsmanDict[batsmanKey] = fianlDict
del playerBowlerDict[batsmanKey]
else:
for batsmanKey, batsmanValue in playerBatsmanDict.items():
if batsmanKey in playerBowlerDict:
bowlerData = playerBowlerDict[batsmanKey]
fianlDict = {**batsmanValue, **bowlerData}
playerBatsmanDict[batsmanKey] = fianlDict
del playerBowlerDict[batsmanKey]
## print("after merging batsmanDict: ", playerBatsmanDict)
## print("after merging bowlerDict: ", playerBowlerDict)
playerFinalDict = {**playerBatsmanDict, **playerBowlerDict}
##
## print("Player final dict: ", playerFinalDict)
##TODO mark player as 'Batsman', 'Bowler', 'WicketKeeper', 'All rounder'
pno = 0
for playerKey, playerValue in playerFinalDict.items():
flag = True
while flag:
try:
pno+=1
if pno <= 5:
shortName = playerValue['short_name']
playerDict = playerFinalDict[playerKey]
if '†' in shortName:
#checking for WicketKeeper positio
playerDict['Position'] = "WK"
elif 'econ' in playerDict:
playerDict['Position'] = "Bowler"
else:
playerDict['Position'] = "Batsman"
#print('Pno : ' + str(pno))
playerDict['match_id'] = matchId + '_' + playerDict['innings'][:2]
playerDict['match_desc'] = matchDesc
playerDict['match_type_text'] = matchTypeText +' '+ playerDict['innings']
playerDict['season'] = season
playerDict['MatchURL'] = pageUrl
playerDict['Match_start_Date'] = Date
playerDict['Venue'] = venue
if playerDict['team'] == teamList[0]:
playerDict['TeamID'] = teamIDList[0]
playerDict['OpponentID'] = teamIDList[1]
else:
playerDict['TeamID'] = teamIDList[1]
playerDict['OpponentID'] = teamIDList[0]
url = playerDict['player_cric_info_link']
page = requests.get(url,params = payload).text
soup = BeautifulSoup(page,'html.parser')
pees = soup.find_all('p',class_='ciPlayerinformationtxt')
val = []
key = []
for pee in pees:
key.append(pee.find('b').get_text())
val.append(pee.find('span').get_text())
if "Full name" in key:
playerDict['Player_Full_Name'] = val[key.index("Full name")]
else:
playerDict['Player_Full_Name'] = '-'
if 'Born' in key:
playerDict['date,place_of_birth'] = val[key.index('Born')].replace('\n','').strip()
else:
playerDict['date,place_of_birth'] = '-'
if 'Nickname' in key:
playerDict['Player_Nickname'] = val[key.index('Nickname')]
else:
playerDict['Player_Nickname'] = '-'
## playerDict['Player_Full_Name'] = data[0]
## playerDict['data,place_of_birth'] = data[1][1:]
## if data[4] == None:
## playerDict['Player_Nickname'] = '-'
## else:
## playerDict['Player_Nickname'] = data[4]
#DOB_PlaceOB = soup.fin_next('p',class_='ciPlayerinformationtxt').find('span').get_text()
# below adding missed parameters in player's dict with default 0 value
if not 'run_scored' in playerDict:
playerDict['run_scored'] = "-"
if not 'balls_faced' in playerDict:
playerDict['balls_faced'] = "-"
if not 'strike_rate' in playerDict:
playerDict['strike_rate'] = "-"
if not 'balls_bowled' in playerDict:
playerDict['balls_bowled'] = "-"
if not 'maiden_overs' in playerDict:
playerDict['maiden_overs'] = "-"
if not 'runs_given' in playerDict:
playerDict['runs_given'] = "-"
if not 'wicket' in playerDict:
playerDict['wicket'] = "-"
if not 'econ' in playerDict:
playerDict['econ'] = "-"
if not 'wide_balls' in playerDict:
playerDict['wide_balls'] = "-"
if not 'no_balls' in playerDict:
playerDict['no_balls'] = "-"
flag = False
else:
pno = 0
time.sleep(10)
except Exception as e:
print('pausing scrapping for 5 mins : '+str(e))
time.sleep(300)
flag = True
# print("Player final dict 2: ", playerFinalDict)
for key, val in playerFinalDict.items():
val['cric_info_id'] = key
val['_id'] = key + "-" + matchId
#print(key)
#MongoDao.insertToPlayerStats(val)
logger.info("players inserted successfully for url: " + pageUrl)
#MongoDao.insertToProcessedUrls(pageUrl)
#print(playerFinalDict.key())
df = pd.DataFrame(playerFinalDict)
return df
except Exception as e:
logger.error("ERROR while processing URL: " + pageUrl)
logger.exception("message")
print("Scrapping : "+str(e))
#print(("ERROR while processing URL: " + pageUrl))
#scrapODI_T20Data('', '', '', "T20", '', '')
| 48.340471 | 154 | 0.454707 | import requests
from bs4 import BeautifulSoup
from logger_impl import *
import MongoDao
import pandas as pd
import time
payload = {'key': 'ac9e8cf2dec81949d9ee1235ed6ae3fb', 'url':
'https://httpbin.org/ip'}
def scrapData(scorecardSoup, matchId, matchDesc, matchTypeText, pageUrl, season, Date, venue):
try:
soup = scorecardSoup
scorecardDiv = soup.find_all('article', class_='sub-module scorecard')
playerBatsmanDict = {}
playerBowlerDict = {}
batsmanScorecardParam = ['run_scored', 'balls_faced','M', '4s', '6s', 'strike_rate']
bowlerScorecardParam = ['O', 'M', 'R', 'W', 'Econ', 'WD', 'NB']
teamList = []
teamIDList = []
inningsTeam = []
in scorecardDiv:
team = scorecardVal.find('h2').get_text()
if matchTypeText == 'Tests':
team = str(team).replace('1st Innings', '').replace('2nd Innings', '')
else:
team = str(team).replace('Innings', '')
if team.strip() in teamList:
break
teamList.append(team.strip())
count = {teamList[0]:0,teamList[1]:0}
for team in teamList:
word = team.split(' ')
if len(word) == 1:
id_ = team[:3]
teamIDList.append(id_)
else:
id_ = ''
for x in word:
id_ = id_ + x[0]
teamIDList.append(id_)
for scorecardVal in scorecardDiv:
team = scorecardVal.find('h2').get_text()
inn = ''
if matchTypeText == 'Tests':
inn = ' '.join(str(team).split(' ')[-2:])
team = str(team).replace('1st Innings', '').replace('2nd Innings', '')
else:
team = str(team).replace('Innings', '')
team = team.strip()
count[team] += 1
team: " + team)
batsmanList = scorecardVal.find_all('div', class_='wrap batsmen')
batsmanListNotBatted = scorecardVal.find('div', class_='wrap dnb').find_all('a')
or = batsman.find('div', class_="cell batsmen").find('a')
batsmanLink = batsmanAnchor.get('href')
batsmanName = batsmanAnchor.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
try:
commentry = batsman.find('div', class_="cell commentary").find('a').get_text()
batsmanDict['commentry'] = commentry
except AttributeError as ae:
batsmanDict['commentry'] = ''
batsmanStatsList = batsman.find_all('div', class_="cell runs")
ctr = 0
tempList = []
for batsmanStats in batsmanStatsList:
tempList.append(batsmanStats.get_text())
if len(tempList) == 6:
batsmanDict['run_scored'] = tempList[0]
batsmanDict['balls_faced'] = tempList[1]
batsmanDict['M'] = tempList[2]
batsmanDict['4s'] = tempList[3]
batsmanDict['6s'] = tempList[4]
batsmanDict['strike_rate'] = tempList[5]
else:
batsmanDict['run_scored'] = tempList[0]
batsmanDict['balls_faced'] = tempList[1]
batsmanDict['M'] = '-'
batsmanDict['4s'] = tempList[2]
batsmanDict['6s'] = tempList[3]
batsmanDict['strike_rate'] = tempList[4]
batsmanDict['innings'] = inn
key = cricInfoBatsmanId
if matchTypeText == 'Tests':
key = key + inn[0]
playerBatsmanDict[key] = batsmanDict
NotBatted:
batsmanDict={}
batsmanLink = batsmen.get('href')
batsmanName = batsmen.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
batsmanDict['run_scored'] = '-'
batsmanDict['balls_faced'] = '-'
batsmanDict['M'] = '-'
batsmanDict['4s'] = '-'
batsmanDict['6s'] = '-'
batsmanDict['strike_rate'] = '-'
batsmanDict['innings'] = inn
key = cricInfoBatsmanId
if matchTypeText == 'Tests':
key = key+inn[0]
playerBatsmanDict[key] = batsmanDict
bowlersTR = scorecardVal.find('tbody').find_all('tr')
for bowlerRow in bowlersTR:
bowlersTD = bowlerRow.find_all('td')
bowlerAnchor = bowlersTD[0].find('a')
bowlerLink = bowlerAnchor.get('href')
bowlerName = bowlerAnchor.get_text()
bowlerLinkArr = str(bowlerLink).split('/')
cricInfoBowlerId = bowlerLinkArr[len(bowlerLinkArr) - 1]
cricInfoBowlerId = str(cricInfoBowlerId).replace('.html', '')
logger.info("bowlersTD: " + str(bowlersTD))
logger.info("length bowlersTD: " + str(len(bowlersTD)))
if len(bowlersTD) == 13:
overs = bowlersTD[2].find(text=True)
maidens = bowlersTD[3].find(text=True)
runs = bowlersTD[4].find(text=True)
wickets = bowlersTD[5].find(text=True)
economy = bowlersTD[6].find(text=True)
dotBalls = bowlersTD[7].find(text=True)
ballerFours = bowlersTD[8].find(text=True)
ballerSixes = bowlersTD[9].find(text=True)
wideBalls = bowlersTD[10].find(text=True)
noBalls = bowlersTD[11].find(text=True)
else:
overs = bowlersTD[2].find(text=True)
maidens = bowlersTD[3].find(text=True)
runs = bowlersTD[4].find(text=True)
wickets = bowlersTD[5].find(text=True)
economy = bowlersTD[6].find(text=True)
dotBalls = 0
ballerFours = 0
ballerSixes = 0
wideBalls = bowlersTD[7].find(text=True)
noBalls = bowlersTD[8].find(text=True)
= int(oversArr[0]) * 6
totalBalls += int(oversArr[1])
else:
totalBalls: int = int(overs) * 6
if team == teamList[0]:
bowlingTeam = teamList[1]
else:
bowlingTeam = teamList[0]
bowlerDict['team'] = bowlingTeam
bowlerDict['balls_bowled'] = totalBalls
bowlerDict['maiden_overs'] = maidens
bowlerDict['runs_given'] = runs
bowlerDict['wicket'] = wickets
bowlerDict['econ'] = economy
bowlerDict['dot_delivery'] = dotBalls
bowlerDict['four_delivery'] = ballerFours
bowlerDict['six_delivery'] = ballerSixes
bowlerDict['wide_balls'] = wideBalls
bowlerDict['no_balls'] = noBalls
bowlerDict['innings'] = inn
key = cricInfoBowlerId
if matchTypeText == 'Tests':
key = key+inn[0]
playerBowlerDict[key] = bowlerDict
if matchTypeText == 'Tests' and ((count[teamList[0]] == 2 and count[teamList[1]] == 1) or (count[teamList[0]] == 1 and count[teamList[1]] == 2)):
missing = ''
if count[teamList[0]] == 1:
missing = teamList[0]
elif count[teamList[1]] == 1:
missing = teamList[1]
for scorecardVal in scorecardDiv:
team = scorecardVal.find('h2').get_text()
inn = ' '.join(str(team).split(' ')[-2:])
team = str(team).replace('1st Innings', '').replace('2nd Innings', '')
team = team.strip()
if team == missing:
batsmanList = scorecardVal.find_all('div', class_='wrap batsmen')
batsmanListNotBatted = scorecardVal.find('div', class_='wrap dnb').find_all('a')
for batsman in batsmanList:
batsmanDict = {}
batsmanAnchor = batsman.find('div', class_="cell batsmen").find('a')
batsmanLink = batsmanAnchor.get('href')
batsmanName = batsmanAnchor.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
batsmanDict['run_scored'] = '-'
batsmanDict['balls_faced'] = '-'
batsmanDict['M'] = '-'
batsmanDict['4s'] = '-'
batsmanDict['6s'] = '-'
batsmanDict['strike_rate'] = '-'
batsmanDict['innings'] = '2nd Innings'
smanId
batsmanDict['commentry'] = '-'
if matchTypeText == 'Tests':
key = key+'2'
playerBatsmanDict[key] = batsmanDict
for batsmen in batsmanListNotBatted:
batsmanLink = batsmen.get('href')
batsmanName = batsmen.get_text()
batsmanLinkArr = str(batsmanLink).split('/')
cricInfoBatsmanId = batsmanLinkArr[len(batsmanLinkArr) - 1]
cricInfoBatsmanId = str(cricInfoBatsmanId).replace('.html', '')
batsmanDict['short_name'] = batsmanName
batsmanDict['player_cric_info_link'] = batsmanLink
batsmanDict['team'] = team
batsmanDict['run_scored'] = '-'
batsmanDict['balls_faced'] = '-'
batsmanDict['M'] = '-'
batsmanDict['4s'] = '-'
batsmanDict['6s'] = '-'
batsmanDict['strike_rate'] = '-'
batsmanDict['innings'] = '2nd Innings'
key = cricInfoBatsmanId
if matchTypeText == 'Tests':
key = key+'2'
playerBatsmanDict[key] = batsmanDict
if matchTypeText == 'Tests':
for batsmanKey, batsmanValue in playerBatsmanDict.items():
if batsmanKey in playerBowlerDict:
if playerBatsmanDict[batsmanKey]['innings'] == playerBowlerDict[batsmanKey]['innings']:
bowlerData = playerBowlerDict[batsmanKey]
fianlDict = {**batsmanValue, **bowlerData}
playerBatsmanDict[batsmanKey] = fianlDict
del playerBowlerDict[batsmanKey]
else:
for batsmanKey, batsmanValue in playerBatsmanDict.items():
if batsmanKey in playerBowlerDict:
bowlerData = playerBowlerDict[batsmanKey]
fianlDict = {**batsmanValue, **bowlerData}
playerBatsmanDict[batsmanKey] = fianlDict
del playerBowlerDict[batsmanKey]
pno+=1
if pno <= 5:
shortName = playerValue['short_name']
playerDict = playerFinalDict[playerKey]
if '†' in shortName:
playerDict['Position'] = "WK"
elif 'econ' in playerDict:
playerDict['Position'] = "Bowler"
else:
playerDict['Position'] = "Batsman"
playerDict['match_id'] = matchId + '_' + playerDict['innings'][:2]
playerDict['match_desc'] = matchDesc
playerDict['match_type_text'] = matchTypeText +' '+ playerDict['innings']
playerDict['season'] = season
playerDict['MatchURL'] = pageUrl
playerDict['Match_start_Date'] = Date
playerDict['Venue'] = venue
if playerDict['team'] == teamList[0]:
playerDict['TeamID'] = teamIDList[0]
playerDict['OpponentID'] = teamIDList[1]
else:
playerDict['TeamID'] = teamIDList[1]
playerDict['OpponentID'] = teamIDList[0]
url = playerDict['player_cric_info_link']
page = requests.get(url,params = payload).text
soup = BeautifulSoup(page,'html.parser')
pees = soup.find_all('p',class_='ciPlayerinformationtxt')
val = []
key = []
for pee in pees:
key.append(pee.find('b').get_text())
val.append(pee.find('span').get_text())
if "Full name" in key:
playerDict['Player_Full_Name'] = val[key.index("Full name")]
else:
playerDict['Player_Full_Name'] = '-'
if 'Born' in key:
playerDict['date,place_of_birth'] = val[key.index('Born')].replace('\n','').strip()
else:
playerDict['date,place_of_birth'] = '-'
if 'Nickname' in key:
playerDict['Player_Nickname'] = val[key.index('Nickname')]
else:
playerDict['Player_Nickname'] = '-'
if not 'run_scored' in playerDict:
playerDict['run_scored'] = "-"
if not 'balls_faced' in playerDict:
playerDict['balls_faced'] = "-"
if not 'strike_rate' in playerDict:
playerDict['strike_rate'] = "-"
if not 'balls_bowled' in playerDict:
playerDict['balls_bowled'] = "-"
if not 'maiden_overs' in playerDict:
playerDict['maiden_overs'] = "-"
if not 'runs_given' in playerDict:
playerDict['runs_given'] = "-"
if not 'wicket' in playerDict:
playerDict['wicket'] = "-"
if not 'econ' in playerDict:
playerDict['econ'] = "-"
if not 'wide_balls' in playerDict:
playerDict['wide_balls'] = "-"
if not 'no_balls' in playerDict:
playerDict['no_balls'] = "-"
flag = False
else:
pno = 0
time.sleep(10)
except Exception as e:
print('pausing scrapping for 5 mins : '+str(e))
time.sleep(300)
flag = True
# print("Player final dict 2: ", playerFinalDict)
for key, val in playerFinalDict.items():
val['cric_info_id'] = key
val['_id'] = key + "-" + matchId
#print(key)
#MongoDao.insertToPlayerStats(val)
logger.info("players inserted successfully for url: " + pageUrl)
#MongoDao.insertToProcessedUrls(pageUrl)
#print(playerFinalDict.key())
df = pd.DataFrame(playerFinalDict)
return df
except Exception as e:
logger.error("ERROR while processing URL: " + pageUrl)
logger.exception("message")
print("Scrapping : "+str(e))
#print(("ERROR while processing URL: " + pageUrl))
#scrapODI_T20Data('', '', '', "T20", '', '')
| true | true |
f727f81a283fdf0533813dc879af7cc5b21230da | 879 | py | Python | armi/meta.py | keckler/armi | b5f95b4795aa21e00fd6786f6994862a4bdccb16 | [
"Apache-2.0"
] | 162 | 2019-11-01T17:35:58.000Z | 2022-03-18T04:22:39.000Z | armi/meta.py | keckler/armi | b5f95b4795aa21e00fd6786f6994862a4bdccb16 | [
"Apache-2.0"
] | 315 | 2019-11-01T17:32:05.000Z | 2022-03-30T03:51:42.000Z | armi/meta.py | keckler/armi | b5f95b4795aa21e00fd6786f6994862a4bdccb16 | [
"Apache-2.0"
] | 55 | 2019-11-01T16:59:59.000Z | 2022-03-25T18:19:06.000Z | # Copyright 2019 TerraPower, LLC
#
# 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.
"""
Metadata describing an ARMI distribution.
"""
# duplicating with setup.py for now. This is because in order to import meta.py, we
# need to run armi.__init__, which does a whole heck of a lot of stuff that setup.py
# shouldn't need. We should clean this up in the future.
__version__ = "0.2.0"
| 38.217391 | 84 | 0.753129 |
__version__ = "0.2.0"
| true | true |
f727fa256e9c15830ec9c93a29d55173626569d5 | 4,224 | py | Python | generate_training_commands.py | dumpmemory/academic-budget-bert | ea000838156e3be251699ad6a3c8b1339c76e987 | [
"Apache-2.0"
] | 146 | 2021-08-01T12:51:04.000Z | 2022-03-27T18:34:11.000Z | generate_training_commands.py | dumpmemory/academic-budget-bert | ea000838156e3be251699ad6a3c8b1339c76e987 | [
"Apache-2.0"
] | 14 | 2021-08-01T12:53:27.000Z | 2022-03-24T09:55:53.000Z | generate_training_commands.py | dumpmemory/academic-budget-bert | ea000838156e3be251699ad6a3c8b1339c76e987 | [
"Apache-2.0"
] | 29 | 2021-08-02T12:04:14.000Z | 2022-03-31T03:56:55.000Z | # coding=utf-8
# Copyright 2021 Intel Corporation. All rights reserved.
#
# 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.
import argparse
import datetime
import random
from itertools import product
import yaml
def get_yaml(file_name):
with open(file_name, "r") as stream:
try:
ym = yaml.safe_load(stream)
return ym
except yaml.YAMLError as e:
print(e)
def get_run_id():
t = datetime.datetime.now()
time_str = t.strftime("%Y%m%d%H%M%S")
random_num = random.randint(10000, 100000)
return f"{time_str}-{random_num}"
def add_run_id_per_command(params_combinations_named):
for comb in params_combinations_named:
comb["current_run_id"] = get_run_id()
return params_combinations_named
def get_hyper_param_combinations_grid(parameters_json):
params = parameters_json["hyperparameters"]
map_index_name = list(params.keys())
all_params_list = [param_values for _, param_values in params.items()]
params_combinations = list(product(*all_params_list))
params_combinations_named = [
{map_index_name[i]: value for i, value in enumerate(comb)} for comb in params_combinations
]
params_combinations_named = add_run_id_per_command(params_combinations_named)
return params_combinations_named
def get_hyper_param_combinations(parameters_json, search_type="grid"):
cases = {"grid": get_hyper_param_combinations_grid}
how_to_get_hyper_param_combinations = cases["grid"]
if search_type in cases:
how_to_get_hyper_param_combinations = cases[search_type]
return how_to_get_hyper_param_combinations(parameters_json)
def add_param(key, value):
if type(value) == bool:
return f"--{key}"
return f"--{key} {value}"
def get_command_from_params(param_list):
return " ".join([add_param(k, v) for k, v in param_list.items()])
def append_command(command, addition):
return f"{command} {addition}"
def add_default_params(parameters_json, job_name):
parameters_json["default_parameters"]["job_name"] = job_name
return parameters_json
def get_command_per_combination(command_init, parameters_json, params_combinations_named):
all_commands = []
command_default = get_command_from_params(parameters_json["default_parameters"])
for comb in params_combinations_named:
command_current = f"{command_init}"
command_current = append_command(command_current, get_command_from_params(comb))
command_current = append_command(command_current, command_default)
all_commands.append(command_current)
return all_commands
def create_experiments(command_init, param_file, job_name, search_type="grid"):
parameters_json = get_yaml(param_file)
parameters_json = add_default_params(parameters_json, job_name)
params_combinations_named = get_hyper_param_combinations(parameters_json, search_type)
all_commands = get_command_per_combination(
command_init, parameters_json, params_combinations_named
)
for command in all_commands:
print(command)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--param_file", help="Hyperparameter and configuration yaml", required=True)
parser.add_argument("--job_name", help="job name", default="bert_large_experiment")
parser.add_argument(
"--init_cmd",
help="initialization command (deepspeed or python directly)",
default="deepspeed run_pretraining.py",
)
parser.add_argument("--search_type", help="hyperparameter search method", default="grid")
args = parser.parse_args()
create_experiments(args.init_cmd, args.param_file, args.job_name, args.search_type)
| 33.792 | 100 | 0.742661 |
import argparse
import datetime
import random
from itertools import product
import yaml
def get_yaml(file_name):
with open(file_name, "r") as stream:
try:
ym = yaml.safe_load(stream)
return ym
except yaml.YAMLError as e:
print(e)
def get_run_id():
t = datetime.datetime.now()
time_str = t.strftime("%Y%m%d%H%M%S")
random_num = random.randint(10000, 100000)
return f"{time_str}-{random_num}"
def add_run_id_per_command(params_combinations_named):
for comb in params_combinations_named:
comb["current_run_id"] = get_run_id()
return params_combinations_named
def get_hyper_param_combinations_grid(parameters_json):
params = parameters_json["hyperparameters"]
map_index_name = list(params.keys())
all_params_list = [param_values for _, param_values in params.items()]
params_combinations = list(product(*all_params_list))
params_combinations_named = [
{map_index_name[i]: value for i, value in enumerate(comb)} for comb in params_combinations
]
params_combinations_named = add_run_id_per_command(params_combinations_named)
return params_combinations_named
def get_hyper_param_combinations(parameters_json, search_type="grid"):
cases = {"grid": get_hyper_param_combinations_grid}
how_to_get_hyper_param_combinations = cases["grid"]
if search_type in cases:
how_to_get_hyper_param_combinations = cases[search_type]
return how_to_get_hyper_param_combinations(parameters_json)
def add_param(key, value):
if type(value) == bool:
return f"--{key}"
return f"--{key} {value}"
def get_command_from_params(param_list):
return " ".join([add_param(k, v) for k, v in param_list.items()])
def append_command(command, addition):
return f"{command} {addition}"
def add_default_params(parameters_json, job_name):
parameters_json["default_parameters"]["job_name"] = job_name
return parameters_json
def get_command_per_combination(command_init, parameters_json, params_combinations_named):
all_commands = []
command_default = get_command_from_params(parameters_json["default_parameters"])
for comb in params_combinations_named:
command_current = f"{command_init}"
command_current = append_command(command_current, get_command_from_params(comb))
command_current = append_command(command_current, command_default)
all_commands.append(command_current)
return all_commands
def create_experiments(command_init, param_file, job_name, search_type="grid"):
parameters_json = get_yaml(param_file)
parameters_json = add_default_params(parameters_json, job_name)
params_combinations_named = get_hyper_param_combinations(parameters_json, search_type)
all_commands = get_command_per_combination(
command_init, parameters_json, params_combinations_named
)
for command in all_commands:
print(command)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--param_file", help="Hyperparameter and configuration yaml", required=True)
parser.add_argument("--job_name", help="job name", default="bert_large_experiment")
parser.add_argument(
"--init_cmd",
help="initialization command (deepspeed or python directly)",
default="deepspeed run_pretraining.py",
)
parser.add_argument("--search_type", help="hyperparameter search method", default="grid")
args = parser.parse_args()
create_experiments(args.init_cmd, args.param_file, args.job_name, args.search_type)
| true | true |
f727fa6638c95253d96d2e8f5ab19ff10be0c38a | 655 | py | Python | App/Config/db.py | pyworksasia/pyworks | 01aefa9e7db4c980dc7518f40a84b99d6137f906 | [
"Apache-2.0"
] | null | null | null | App/Config/db.py | pyworksasia/pyworks | 01aefa9e7db4c980dc7518f40a84b99d6137f906 | [
"Apache-2.0"
] | null | null | null | App/Config/db.py | pyworksasia/pyworks | 01aefa9e7db4c980dc7518f40a84b99d6137f906 | [
"Apache-2.0"
] | null | null | null | from App.Config.app import settings
DATABASES = {
'default': 'mysql',
'mysql': {
'driver': 'mysql',
'host': settings.DB_HOST,
'port': settings.DB_PORT,
'database': settings.DB_DATABASE,
'user': settings.DB_USER,
'password': settings.DB_PASSWORD,
'prefix': settings.DB_PREFIX,
'log_queries': True
},
'postgres': {
'driver': 'postgres',
'host': settings.DB_HOST,
'database': settings.DB_DATABASE,
'user': settings.DB_USER,
'password': settings.DB_PASSWORD,
'prefix': settings.DB_PREFIX,
'port': settings.DB_PORT,
}
} | 27.291667 | 41 | 0.567939 | from App.Config.app import settings
DATABASES = {
'default': 'mysql',
'mysql': {
'driver': 'mysql',
'host': settings.DB_HOST,
'port': settings.DB_PORT,
'database': settings.DB_DATABASE,
'user': settings.DB_USER,
'password': settings.DB_PASSWORD,
'prefix': settings.DB_PREFIX,
'log_queries': True
},
'postgres': {
'driver': 'postgres',
'host': settings.DB_HOST,
'database': settings.DB_DATABASE,
'user': settings.DB_USER,
'password': settings.DB_PASSWORD,
'prefix': settings.DB_PREFIX,
'port': settings.DB_PORT,
}
} | true | true |
f727fb7b85952005743a11740a3245a5d33e2124 | 4,124 | py | Python | scatterauth/views.py | caniko2/django-scatter-auth | 962b352f4deaf91de7daa8a85b8ee82852962032 | [
"MIT"
] | null | null | null | scatterauth/views.py | caniko2/django-scatter-auth | 962b352f4deaf91de7daa8a85b8ee82852962032 | [
"MIT"
] | null | null | null | scatterauth/views.py | caniko2/django-scatter-auth | 962b352f4deaf91de7daa8a85b8ee82852962032 | [
"MIT"
] | null | null | null | import random
import string
import json
from django.shortcuts import render, redirect, reverse
from django.urls.exceptions import NoReverseMatch
from django.contrib.auth import login, authenticate
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse, HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.http.request import split_domain_port
from scatterauth.forms import LoginForm, SignupForm
from scatterauth.settings import app_settings
def get_redirect_url(request):
if request.GET.get('next'):
return request.GET.get('next')
elif request.POST.get('next'):
return request.POST.get('next')
elif settings.LOGIN_REDIRECT_URL:
try:
url = reverse(settings.LOGIN_REDIRECT_URL)
except NoReverseMatch:
url = settings.LOGIN_REDIRECT_URL
return url
@require_http_methods(['POST'])
def login_api(request):
form = LoginForm(request.POST)
if not form.is_valid():
return JsonResponse({'success': False, 'error': json.loads(form.errors.as_json())})
public_key = form.cleaned_data.get('public_key')
nonce = form.cleaned_data.get('nonce')
res = form.cleaned_data.get('res')
if not nonce or not res or not public_key:
return JsonResponse({'error': _(
'Please pass message, signed message, and public key'),
'success': False})
user = authenticate(request, public_key=public_key, nonce=nonce, res=res)
if user:
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return JsonResponse({'success': True, 'redirect_url': get_redirect_url(request)})
else:
error = _("Can't find a user for the provided signature with public key {public_key}").format(
public_key=public_key)
return JsonResponse({'success': False, 'error': error})
@require_http_methods(['POST'])
def signup_api(request):
if not app_settings.SCATTERAUTH_SIGNUP_ENABLED:
return JsonResponse({'success': False, 'error': _("Sorry, signup's are currently disabled")})
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
setattr(user, username, form.cleaned_data['publicKey'])
user.save()
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return JsonResponse({'success': True, 'redirect_url': get_redirect_url(request)})
else:
return JsonResponse({'success': False, 'error': json.loads(form.errors.as_json())})
@require_http_methods(['GET', 'POST'])
def signup_view(request, template_name='scatterauth/signup.html'):
'''
1. Creates an instance of a SignupForm.
2. Checks if the registration is enabled.
3. If the registration is closed or form has errors, returns form with errors
4. If the form is valid, saves the user without saving to DB
5. Sets the user address from the form, saves it to DB
6. Logins the user using scatterauth.backend.ScatterAuthBackend
7. Redirects the user to LOGIN_REDIRECT_URL or 'next' in get or post params
:param request: Django request
:param template_name: Template to render
:return: rendered template with form
'''
form = SignupForm()
if not app_settings.SCATTERAUTH_SIGNUP_ENABLED:
form.add_error(None, _("Sorry, signup's are currently disabled"))
else:
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
pubkey_field = app_settings.SCATTERAUTH_USER_PUBKEY_FIELD
setattr(user, pubkey_field, form.cleaned_data[pubkey_field])
user.save()
print(pubkey_field)
print(user.email)
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return redirect(get_redirect_url(request))
return render(request, template_name, {'form': form})
| 39.653846 | 102 | 0.690592 | import random
import string
import json
from django.shortcuts import render, redirect, reverse
from django.urls.exceptions import NoReverseMatch
from django.contrib.auth import login, authenticate
from django.conf import settings
from django.views.decorators.http import require_http_methods
from django.http import JsonResponse, HttpResponseBadRequest
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.http.request import split_domain_port
from scatterauth.forms import LoginForm, SignupForm
from scatterauth.settings import app_settings
def get_redirect_url(request):
if request.GET.get('next'):
return request.GET.get('next')
elif request.POST.get('next'):
return request.POST.get('next')
elif settings.LOGIN_REDIRECT_URL:
try:
url = reverse(settings.LOGIN_REDIRECT_URL)
except NoReverseMatch:
url = settings.LOGIN_REDIRECT_URL
return url
@require_http_methods(['POST'])
def login_api(request):
form = LoginForm(request.POST)
if not form.is_valid():
return JsonResponse({'success': False, 'error': json.loads(form.errors.as_json())})
public_key = form.cleaned_data.get('public_key')
nonce = form.cleaned_data.get('nonce')
res = form.cleaned_data.get('res')
if not nonce or not res or not public_key:
return JsonResponse({'error': _(
'Please pass message, signed message, and public key'),
'success': False})
user = authenticate(request, public_key=public_key, nonce=nonce, res=res)
if user:
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return JsonResponse({'success': True, 'redirect_url': get_redirect_url(request)})
else:
error = _("Can't find a user for the provided signature with public key {public_key}").format(
public_key=public_key)
return JsonResponse({'success': False, 'error': error})
@require_http_methods(['POST'])
def signup_api(request):
if not app_settings.SCATTERAUTH_SIGNUP_ENABLED:
return JsonResponse({'success': False, 'error': _("Sorry, signup's are currently disabled")})
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
setattr(user, username, form.cleaned_data['publicKey'])
user.save()
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return JsonResponse({'success': True, 'redirect_url': get_redirect_url(request)})
else:
return JsonResponse({'success': False, 'error': json.loads(form.errors.as_json())})
@require_http_methods(['GET', 'POST'])
def signup_view(request, template_name='scatterauth/signup.html'):
form = SignupForm()
if not app_settings.SCATTERAUTH_SIGNUP_ENABLED:
form.add_error(None, _("Sorry, signup's are currently disabled"))
else:
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
pubkey_field = app_settings.SCATTERAUTH_USER_PUBKEY_FIELD
setattr(user, pubkey_field, form.cleaned_data[pubkey_field])
user.save()
print(pubkey_field)
print(user.email)
login(request, user, 'scatterauth.backend.ScatterAuthBackend')
return redirect(get_redirect_url(request))
return render(request, template_name, {'form': form})
| true | true |
f727fd004d9faf9730132464a1939ae041c64ead | 13,745 | py | Python | plugins/modules/nsi_api_v2_0_fres.py | ciena/ciena.mcp | b266a7cbd912c547f6e4877597d67ea9254e5758 | [
"Apache-2.0"
] | 3 | 2021-07-19T23:56:34.000Z | 2021-11-08T14:23:53.000Z | plugins/modules/nsi_api_v2_0_fres.py | ciena/ciena.mcp | b266a7cbd912c547f6e4877597d67ea9254e5758 | [
"Apache-2.0"
] | 1 | 2022-01-19T22:06:49.000Z | 2022-01-24T15:16:53.000Z | plugins/modules/nsi_api_v2_0_fres.py | ciena/ciena.mcp | b266a7cbd912c547f6e4877597d67ea9254e5758 | [
"Apache-2.0"
] | 1 | 2021-11-08T14:25:29.000Z | 2021-11-08T14:25:29.000Z | #!/usr/bin/env python
# Info module template
#############################################
# WARNING #
#############################################
#
# This file is auto generated by
# https://github.com/jgroom33/vmware_rest_code_generator
#
# Do not edit this file manually.
#
# Changes should be made in the swagger used to
# generate this file or in the generator
#
#############################################
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import socket
import json
DOCUMENTATION = """
module: nsi_api_v2_0_fres
short_description: Handle resource of type nsi_api_v2_0_fres
description: Handle resource of type nsi_api_v2_0_fres
options:
childFreId:
description:
- (Optional) The child FRE identifier to return its parents
- Used by I(state=['get'])
type: str
data:
description:
- 'Validate attributes are:'
- ' - C(attributes) (dict): '
- ' - C(id) (str): The unique identifier for the FRE resource'
- ' - C(meta) (dict): A metadata object that contains non-standard meta information'
- ' - C(relationships) (dict): '
- ' - C(type) (str): The FRE resource type'
- Used by I(state=['post'])
type: dict
directionality:
choices:
- bidirectional
- unidirectional
description:
- (Optional) Indicates if unidirectional or bidirectional FREs should be returned
- Used by I(state=['get'])
type: str
endpoint.tpe.concrete:
description:
- Concrete TPE identifier for endpoints
- Used by I(state=['get'])
type: str
exclude:
choices:
- actual
- expectation
description:
- (Optional) The given type would be excluded from get parents call, only combine
with childFreId
- Used by I(state=['get'])
type: str
fields:
description:
- (Optional) List of comma separated fields to be included in the response. Fields
require full path (i.e. data.attributes.field)
- Used by I(state=['get'])
type: str
freExpectations.equipmentIntent.id:
description:
- (Optional) The equipment intent Id
- Used by I(state=['get'])
type: str
freExpectations.serviceIntent.id:
description:
- (Optional) The service intent Id
- Used by I(state=['get'])
type: str
freType:
description:
- 'FRE types in comma separated list The allowed values are: explicitRoute, explicitRouteGroup,
snc, sncGroup'
- Used by I(state=['get'])
type: str
group:
choices:
- dwa
- infrastructure
- packet
- packet_infrastructure
- tdm
description:
- FRE group :<ul><li>dwa for all FREs in OTU4 and all top level FREs in ETHERNET,
DSR, DSR_ETHERNET, OTSi(OCH), ODU2, ODU4<li>infrastructure for all FRE-APs representing
forwarding constructs between ROADM OTS'<li>packet for all L2 nodal and top
level FREs in ETHERNET including infrastructure</ul>
- Used by I(state=['get'])
type: str
identifierKey:
description:
- List of comma separated keys for an identifer object
- Used by I(state=['get'])
type: list
identifierValue:
description:
- List of comma separated values for an identifier object
- Used by I(state=['get'])
type: list
include:
description:
- '(Optional) List of comma separated resources to be side-loaded. The allowed
values are: tpes, expectations'
- Used by I(state=['get'])
type: str
includeMetaData:
description:
- 'MetaData to be included. The allowed values are: layerRate'
- Used by I(state=['get'])
type: str
included:
description:
- Resources related to a FRE, such as FreData, EndPointData, TpeData, EquipmentData,
EquipmentHolderData, FrePlannedData, FreExpectationData, FreDiscoveredData,
ResiliencyControllerData, EncapsulatedResiliencyData
- Used by I(state=['post'])
type: list
layerRate:
description:
- 'FRE layer rates in comma separated list The allowed values are: ETHERNET, OTU2,
OTU4, OTSi, OMS, OS, PHY, OTS, ODU2, ODU4, DSR, DSR_10GE, DSR_100GE, DSR_ETHERNET'
- Used by I(state=['get'])
type: str
limit:
description:
- The size of a returned page
- Used by I(state=['get'])
type: str
links:
description:
- Links related to the resource
- 'Validate attributes are:'
- ' - C(current) (str): The current page of data'
- ' - C(first) (str): The first page of data'
- ' - C(last) (str): The last page of data'
- ' - C(next) (str): The next page of data'
- ' - C(prev) (str): The previous page of data'
- ' - C(self) (str): A `self` member, whose value is a URL for the relationship
itself (a "relationship URL"). This URL allows the client to directly manipulate
the relationship. For example, it would allow a client to remove an `author`
from an `article` without deleting the people resource itself.'
- Used by I(state=['post'])
type: dict
managementName:
description:
- Management Name
- Used by I(state=['get'])
type: str
meta:
description:
- A metadata object that contains non-standard meta information
- 'Validate attributes are:'
- ' - C(absoluteTotal) (int): The unfiltered total number of entities in the data'
- ' - C(aggregations) (list): The aggregated data based on a requested aggregation
name and criteria'
- ' - C(filtered) (bool): Flags whether the current object is filtered using `fields`
query param or not'
- ' - C(missingReferenceIds) (list): The list of missing resource IDs'
- ' - C(missingReferences) (bool): boolean detailing if the GET FRE tree has any
missing references'
- ' - C(total) (int): The total number of entities in the data'
- Used by I(state=['post'])
type: dict
ncId:
description:
- (Deprecated) Network Construct identifier
- Used by I(state=['get'])
type: str
networkConstruct.id:
description:
- Network Construct identifier
- Used by I(state=['get'])
type: str
offset:
description:
- Offset for the second page
- Used by I(state=['get'])
type: str
roadmLineId:
description:
- (Optional) Find services configured over a roadmline based on the roadmline
FRE identifier.
- Used by I(state=['get'])
type: str
searchText:
description:
- (Optional) The searchable text
- Used by I(state=['get'])
type: str
signalContentType:
description:
- (Optional) The identifier indicating type of parent to be returned. If specified,
parent matching the criteria will be returned
- Used by I(state=['get'])
type: str
srlg:
description:
- (Optional) Find roadmlines by srlg values separated by comma. A roadmline is
a FRE between two SAM cards.
- Used by I(state=['get'])
type: str
state:
choices:
- get
- post
description: []
type: str
tpeId:
description:
- TPE identifier for endpoints
- Used by I(state=['get'])
type: str
type:
description:
- 'FRE types in comma separated list. The allowed values are: service, link, roadmline-ap,
roadmline'
- Used by I(state=['get'])
type: str
userLabel:
description:
- User label
- Used by I(state=['get'])
type: str
author: []
version_added: 1.0.0
requirements:
- python >= 3.6
"""
IN_QUERY_PARAMETER = [
"childFreId",
"directionality",
"endpoint.tpe.concrete",
"exclude",
"fields",
"freExpectations.equipmentIntent.id",
"freExpectations.serviceIntent.id",
"freType",
"group",
"identifierKey",
"identifierValue",
"include",
"includeMetaData",
"layerRate",
"limit",
"managementName",
"ncId",
"networkConstruct.id",
"offset",
"roadmLineId",
"searchText",
"signalContentType",
"srlg",
"tpeId",
"type",
"userLabel",
]
from ansible.module_utils.basic import env_fallback
try:
from ansible_module.turbo.module import AnsibleTurboModule as AnsibleModule
except ImportError:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.ciena.mcp.plugins.module_utils.mcp import (
gen_args,
open_session,
update_changed_flag,
)
def prepare_argument_spec():
argument_spec = {
"mcp_hostname": dict(
type="str", required=False, fallback=(env_fallback, ["MCP_HOST"])
),
"mcp_username": dict(
type="str", required=False, fallback=(env_fallback, ["MCP_USER"])
),
"mcp_password": dict(
type="str",
required=False,
no_log=True,
fallback=(env_fallback, ["MCP_PASSWORD"]),
),
}
argument_spec["userLabel"] = {"type": "str", "operationIds": ["get"]}
argument_spec["type"] = {"type": "str", "operationIds": ["get"]}
argument_spec["tpeId"] = {"type": "str", "operationIds": ["get"]}
argument_spec["state"] = {"type": "str", "choices": ["get", "post"]}
argument_spec["srlg"] = {"type": "str", "operationIds": ["get"]}
argument_spec["signalContentType"] = {"type": "str", "operationIds": ["get"]}
argument_spec["searchText"] = {"type": "str", "operationIds": ["get"]}
argument_spec["roadmLineId"] = {"type": "str", "operationIds": ["get"]}
argument_spec["offset"] = {"type": "str", "operationIds": ["get"]}
argument_spec["networkConstruct_id"] = {"type": "str", "operationIds": ["get"]}
argument_spec["ncId"] = {"type": "str", "operationIds": ["get"]}
argument_spec["meta"] = {"type": "dict", "operationIds": ["post"]}
argument_spec["managementName"] = {"type": "str", "operationIds": ["get"]}
argument_spec["links"] = {"type": "dict", "operationIds": ["post"]}
argument_spec["limit"] = {"type": "str", "operationIds": ["get"]}
argument_spec["layerRate"] = {"type": "str", "operationIds": ["get"]}
argument_spec["included"] = {"type": "list", "operationIds": ["post"]}
argument_spec["includeMetaData"] = {"type": "str", "operationIds": ["get"]}
argument_spec["include"] = {"type": "str", "operationIds": ["get"]}
argument_spec["identifierValue"] = {"type": "list", "operationIds": ["get"]}
argument_spec["identifierKey"] = {"type": "list", "operationIds": ["get"]}
argument_spec["group"] = {
"type": "str",
"choices": ["dwa", "infrastructure", "packet", "packet_infrastructure", "tdm"],
"operationIds": ["get"],
}
argument_spec["freType"] = {"type": "str", "operationIds": ["get"]}
argument_spec["freExpectations_serviceIntent_id"] = {
"type": "str",
"operationIds": ["get"],
}
argument_spec["freExpectations_equipmentIntent_id"] = {
"type": "str",
"operationIds": ["get"],
}
argument_spec["fields"] = {"type": "str", "operationIds": ["get"]}
argument_spec["exclude"] = {
"type": "str",
"choices": ["actual", "expectation"],
"operationIds": ["get"],
}
argument_spec["endpoint_tpe_concrete"] = {"type": "str", "operationIds": ["get"]}
argument_spec["directionality"] = {
"type": "str",
"choices": ["bidirectional", "unidirectional"],
"operationIds": ["get"],
}
argument_spec["data"] = {"type": "dict", "operationIds": ["post"]}
argument_spec["childFreId"] = {"type": "str", "operationIds": ["get"]}
return argument_spec
async def main():
module_args = prepare_argument_spec()
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
session = await open_session(
mcp_hostname=module.params["mcp_hostname"],
mcp_username=module.params["mcp_username"],
mcp_password=module.params["mcp_password"],
)
result = await entry_point(module, session)
module.exit_json(**result)
def url(params):
return "https://{mcp_hostname}/nsi/api/v2_0/fres".format(**params)
async def entry_point(module, session):
func = globals()[("_" + module.params["state"])]
return await func(module.params, session)
async def _get(params, session):
_url = "https://{mcp_hostname}/nsi/api/v2_0/fres".format(**params) + gen_args(
params, IN_QUERY_PARAMETER
)
async with session.get(_url) as resp:
content_types = [
"application/json-patch+json",
"application/vnd.api+json",
"application/json",
]
try:
if resp.headers["Content-Type"] in content_types:
_json = await resp.json()
else:
print("response Content-Type not supported")
except KeyError:
_json = {}
return await update_changed_flag(_json, resp.status, "get")
async def _post(params, session):
accepted_fields = ["data", "included", "links", "meta"]
spec = {}
for i in accepted_fields:
if params[i] is not None:
spec[i] = params[i]
_url = "https://{mcp_hostname}/nsi/api/v2_0/fres".format(**params) + gen_args(
params, IN_QUERY_PARAMETER
)
async with session.post(_url, json=spec) as resp:
content_types = [
"application/json-patch+json",
"application/vnd.api+json",
"application/json",
]
try:
if resp.headers["Content-Type"] in content_types:
_json = await resp.json()
else:
print("response Content-Type not supported")
except KeyError:
_json = {}
return await update_changed_flag(_json, resp.status, "post")
if __name__ == "__main__":
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
| 32.72619 | 99 | 0.621462 |
s are: tpes, expectations'
- Used by I(state=['get'])
type: str
includeMetaData:
description:
- 'MetaData to be included. The allowed values are: layerRate'
- Used by I(state=['get'])
type: str
included:
description:
- Resources related to a FRE, such as FreData, EndPointData, TpeData, EquipmentData,
EquipmentHolderData, FrePlannedData, FreExpectationData, FreDiscoveredData,
ResiliencyControllerData, EncapsulatedResiliencyData
- Used by I(state=['post'])
type: list
layerRate:
description:
- 'FRE layer rates in comma separated list The allowed values are: ETHERNET, OTU2,
OTU4, OTSi, OMS, OS, PHY, OTS, ODU2, ODU4, DSR, DSR_10GE, DSR_100GE, DSR_ETHERNET'
- Used by I(state=['get'])
type: str
limit:
description:
- The size of a returned page
- Used by I(state=['get'])
type: str
links:
description:
- Links related to the resource
- 'Validate attributes are:'
- ' - C(current) (str): The current page of data'
- ' - C(first) (str): The first page of data'
- ' - C(last) (str): The last page of data'
- ' - C(next) (str): The next page of data'
- ' - C(prev) (str): The previous page of data'
- ' - C(self) (str): A `self` member, whose value is a URL for the relationship
itself (a "relationship URL"). This URL allows the client to directly manipulate
the relationship. For example, it would allow a client to remove an `author`
from an `article` without deleting the people resource itself.'
- Used by I(state=['post'])
type: dict
managementName:
description:
- Management Name
- Used by I(state=['get'])
type: str
meta:
description:
- A metadata object that contains non-standard meta information
- 'Validate attributes are:'
- ' - C(absoluteTotal) (int): The unfiltered total number of entities in the data'
- ' - C(aggregations) (list): The aggregated data based on a requested aggregation
name and criteria'
- ' - C(filtered) (bool): Flags whether the current object is filtered using `fields`
query param or not'
- ' - C(missingReferenceIds) (list): The list of missing resource IDs'
- ' - C(missingReferences) (bool): boolean detailing if the GET FRE tree has any
missing references'
- ' - C(total) (int): The total number of entities in the data'
- Used by I(state=['post'])
type: dict
ncId:
description:
- (Deprecated) Network Construct identifier
- Used by I(state=['get'])
type: str
networkConstruct.id:
description:
- Network Construct identifier
- Used by I(state=['get'])
type: str
offset:
description:
- Offset for the second page
- Used by I(state=['get'])
type: str
roadmLineId:
description:
- (Optional) Find services configured over a roadmline based on the roadmline
FRE identifier.
- Used by I(state=['get'])
type: str
searchText:
description:
- (Optional) The searchable text
- Used by I(state=['get'])
type: str
signalContentType:
description:
- (Optional) The identifier indicating type of parent to be returned. If specified,
parent matching the criteria will be returned
- Used by I(state=['get'])
type: str
srlg:
description:
- (Optional) Find roadmlines by srlg values separated by comma. A roadmline is
a FRE between two SAM cards.
- Used by I(state=['get'])
type: str
state:
choices:
- get
- post
description: []
type: str
tpeId:
description:
- TPE identifier for endpoints
- Used by I(state=['get'])
type: str
type:
description:
- 'FRE types in comma separated list. The allowed values are: service, link, roadmline-ap,
roadmline'
- Used by I(state=['get'])
type: str
userLabel:
description:
- User label
- Used by I(state=['get'])
type: str
author: []
version_added: 1.0.0
requirements:
- python >= 3.6
"""
IN_QUERY_PARAMETER = [
"childFreId",
"directionality",
"endpoint.tpe.concrete",
"exclude",
"fields",
"freExpectations.equipmentIntent.id",
"freExpectations.serviceIntent.id",
"freType",
"group",
"identifierKey",
"identifierValue",
"include",
"includeMetaData",
"layerRate",
"limit",
"managementName",
"ncId",
"networkConstruct.id",
"offset",
"roadmLineId",
"searchText",
"signalContentType",
"srlg",
"tpeId",
"type",
"userLabel",
]
from ansible.module_utils.basic import env_fallback
try:
from ansible_module.turbo.module import AnsibleTurboModule as AnsibleModule
except ImportError:
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.ciena.mcp.plugins.module_utils.mcp import (
gen_args,
open_session,
update_changed_flag,
)
def prepare_argument_spec():
argument_spec = {
"mcp_hostname": dict(
type="str", required=False, fallback=(env_fallback, ["MCP_HOST"])
),
"mcp_username": dict(
type="str", required=False, fallback=(env_fallback, ["MCP_USER"])
),
"mcp_password": dict(
type="str",
required=False,
no_log=True,
fallback=(env_fallback, ["MCP_PASSWORD"]),
),
}
argument_spec["userLabel"] = {"type": "str", "operationIds": ["get"]}
argument_spec["type"] = {"type": "str", "operationIds": ["get"]}
argument_spec["tpeId"] = {"type": "str", "operationIds": ["get"]}
argument_spec["state"] = {"type": "str", "choices": ["get", "post"]}
argument_spec["srlg"] = {"type": "str", "operationIds": ["get"]}
argument_spec["signalContentType"] = {"type": "str", "operationIds": ["get"]}
argument_spec["searchText"] = {"type": "str", "operationIds": ["get"]}
argument_spec["roadmLineId"] = {"type": "str", "operationIds": ["get"]}
argument_spec["offset"] = {"type": "str", "operationIds": ["get"]}
argument_spec["networkConstruct_id"] = {"type": "str", "operationIds": ["get"]}
argument_spec["ncId"] = {"type": "str", "operationIds": ["get"]}
argument_spec["meta"] = {"type": "dict", "operationIds": ["post"]}
argument_spec["managementName"] = {"type": "str", "operationIds": ["get"]}
argument_spec["links"] = {"type": "dict", "operationIds": ["post"]}
argument_spec["limit"] = {"type": "str", "operationIds": ["get"]}
argument_spec["layerRate"] = {"type": "str", "operationIds": ["get"]}
argument_spec["included"] = {"type": "list", "operationIds": ["post"]}
argument_spec["includeMetaData"] = {"type": "str", "operationIds": ["get"]}
argument_spec["include"] = {"type": "str", "operationIds": ["get"]}
argument_spec["identifierValue"] = {"type": "list", "operationIds": ["get"]}
argument_spec["identifierKey"] = {"type": "list", "operationIds": ["get"]}
argument_spec["group"] = {
"type": "str",
"choices": ["dwa", "infrastructure", "packet", "packet_infrastructure", "tdm"],
"operationIds": ["get"],
}
argument_spec["freType"] = {"type": "str", "operationIds": ["get"]}
argument_spec["freExpectations_serviceIntent_id"] = {
"type": "str",
"operationIds": ["get"],
}
argument_spec["freExpectations_equipmentIntent_id"] = {
"type": "str",
"operationIds": ["get"],
}
argument_spec["fields"] = {"type": "str", "operationIds": ["get"]}
argument_spec["exclude"] = {
"type": "str",
"choices": ["actual", "expectation"],
"operationIds": ["get"],
}
argument_spec["endpoint_tpe_concrete"] = {"type": "str", "operationIds": ["get"]}
argument_spec["directionality"] = {
"type": "str",
"choices": ["bidirectional", "unidirectional"],
"operationIds": ["get"],
}
argument_spec["data"] = {"type": "dict", "operationIds": ["post"]}
argument_spec["childFreId"] = {"type": "str", "operationIds": ["get"]}
return argument_spec
async def main():
module_args = prepare_argument_spec()
module = AnsibleModule(argument_spec=module_args, supports_check_mode=True)
session = await open_session(
mcp_hostname=module.params["mcp_hostname"],
mcp_username=module.params["mcp_username"],
mcp_password=module.params["mcp_password"],
)
result = await entry_point(module, session)
module.exit_json(**result)
def url(params):
return "https://{mcp_hostname}/nsi/api/v2_0/fres".format(**params)
async def entry_point(module, session):
func = globals()[("_" + module.params["state"])]
return await func(module.params, session)
async def _get(params, session):
_url = "https://{mcp_hostname}/nsi/api/v2_0/fres".format(**params) + gen_args(
params, IN_QUERY_PARAMETER
)
async with session.get(_url) as resp:
content_types = [
"application/json-patch+json",
"application/vnd.api+json",
"application/json",
]
try:
if resp.headers["Content-Type"] in content_types:
_json = await resp.json()
else:
print("response Content-Type not supported")
except KeyError:
_json = {}
return await update_changed_flag(_json, resp.status, "get")
async def _post(params, session):
accepted_fields = ["data", "included", "links", "meta"]
spec = {}
for i in accepted_fields:
if params[i] is not None:
spec[i] = params[i]
_url = "https://{mcp_hostname}/nsi/api/v2_0/fres".format(**params) + gen_args(
params, IN_QUERY_PARAMETER
)
async with session.post(_url, json=spec) as resp:
content_types = [
"application/json-patch+json",
"application/vnd.api+json",
"application/json",
]
try:
if resp.headers["Content-Type"] in content_types:
_json = await resp.json()
else:
print("response Content-Type not supported")
except KeyError:
_json = {}
return await update_changed_flag(_json, resp.status, "post")
if __name__ == "__main__":
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
| true | true |
f727fd0a3a3c103e954ea648b1541bbaf0c9e7d8 | 75,787 | py | Python | manticore/platforms/linux.py | CSeq/manticore | 6133a0e2ed98de6a58f3bf574498ec320ccbc43e | [
"Apache-2.0"
] | null | null | null | manticore/platforms/linux.py | CSeq/manticore | 6133a0e2ed98de6a58f3bf574498ec320ccbc43e | [
"Apache-2.0"
] | null | null | null | manticore/platforms/linux.py | CSeq/manticore | 6133a0e2ed98de6a58f3bf574498ec320ccbc43e | [
"Apache-2.0"
] | 1 | 2021-12-26T12:57:01.000Z | 2021-12-26T12:57:01.000Z | import errno
import fcntl
import logging
import os
import random
import struct
import ctypes
from elftools.elf.elffile import ELFFile
from ..utils.helpers import issymbolic
from ..core.cpu.abstractcpu import Interruption, Syscall, ConcretizeArgument
from ..core.cpu.cpufactory import CpuFactory
from ..core.memory import SMemory32, SMemory64, Memory32, Memory64
from ..core.smtlib import Operators, ConstraintSet
from ..platforms.platform import Platform
from ..core.cpu.arm import *
from ..core.executor import SyscallNotImplemented, ProcessExit
from . import linux_syscalls
logger = logging.getLogger("PLATFORM")
class RestartSyscall(Exception):
pass
class Deadlock(Exception):
pass
class BadFd(Exception):
pass
def perms_from_elf(elf_flags):
return [' ', ' x', ' w ', ' wx', 'r ', 'r x', 'rw ', 'rwx'][elf_flags&7]
def perms_from_protflags(prot_flags):
return [' ', 'r ', ' w ', 'rw ', ' x', 'r x', ' wx', 'rwx'][prot_flags&7]
class File(object):
def __init__(self, *args, **kwargs):
# TODO: assert file is seekable otherwise we should save what was
# read/write to the state
self.file = file(*args,**kwargs)
def __getstate__(self):
state = {}
state['name'] = self.name
state['mode'] = self.mode
state['pos'] = self.tell()
return state
def __setstate__(self, state):
name = state['name']
mode = state['mode']
pos = state['pos']
self.file = file(name, mode)
self.seek(pos)
@property
def name(self):
return self.file.name
@property
def mode(self):
return self.file.mode
def stat(self):
return os.fstat(self.fileno())
def ioctl(self, request, argp):
#argp ignored..
return fcntl.fcntl(self, request)
def tell(self, *args):
return self.file.tell(*args)
def seek(self, *args):
return self.file.seek(*args)
def write(self, buf):
for c in buf:
self.file.write(c)
def read(self, *args):
return self.file.read(*args)
def close(self, *args):
return self.file.close(*args)
def fileno(self, *args):
return self.file.fileno(*args)
def is_full(self):
return False
def sync(self):
'''
Flush buffered data. Currently not implemented.
'''
return
class SymbolicFile(File):
'''
Represents a symbolic file.
'''
def __init__(self, constraints, path="sfile", mode='rw', max_size=100,
wildcard='+'):
'''
Builds a symbolic file
:param constraints: the SMT constraints
:param str path: the pathname of the symbolic file
:param str mode: the access permissions of the symbolic file
:param max_size: Maximun amount of bytes of the symbolic file
:param str wildcard: Wildcard to be used in symbolic file
'''
super(SymbolicFile, self).__init__(path, mode)
# read the concrete data using the parent the read() form the File class
data = self.file.read()
self._constraints = constraints
self.pos = 0
self.max_size = min(len(data), max_size)
# build the constraints array
size = len(data)
self.array = constraints.new_array(name=self.name, index_max=size)
symbols_cnt = 0
for i in range(size):
if data[i] != wildcard:
self.array[i] = data[i]
else:
symbols_cnt += 1
if symbols_cnt > max_size:
logger.warning(("Found more wilcards in the file than free ",
"symbolic values allowed (%d > %d)"),
symbols_cnt,
max_size)
else:
logger.debug("Found %d free symbolic values on file %s",
symbols_cnt,
self.name)
def __getstate__(self):
state = {}
state['array'] = self.array
state['pos'] = self.pos
state['max_size'] = self.max_size
return state
def __setstate__(self, state):
self.pos = state['pos']
self.max_size = state['max_size']
self.array = state['array']
@property
def constraints(self):
return self._constraints
def tell(self):
'''
Returns the read/write file offset
:rtype: int
:return: the read/write file offset.
'''
return self.pos
def seek(self, pos):
'''
Returns the read/write file offset
:rtype: int
:return: the read/write file offset.
'''
assert isinstance(pos, (int, long))
self.pos = pos
def read(self, count):
'''
Reads up to C{count} bytes from the file.
:rtype: list
:return: the list of symbolic bytes read
'''
if self.pos > self.max_size:
return []
else:
size = min(count, self.max_size - self.pos)
ret = [self.array[i] for i in xrange(self.pos, self.pos + size)]
self.pos += size
return ret
def write(self, data):
'''
Writes the symbolic bytes in C{data} onto the file.
'''
size = min(len(data), self.max_size - self.pos)
for i in xrange(self.pos, self.pos + size):
self.array[i] = data[i - self.pos]
class Socket(object):
def stat(self):
from collections import namedtuple
stat_result = namedtuple('stat_result', ['st_mode','st_ino','st_dev','st_nlink','st_uid','st_gid','st_size','st_atime','st_mtime','st_ctime', 'st_blksize','st_blocks','st_rdev'])
return stat_result(8592,11,9,1,1000,5,0,1378673920,1378673920,1378653796,0x400,0x8808,0)
@staticmethod
def pair():
a = Socket()
b = Socket()
a.connect(b)
return a, b
def __init__(self):
self.buffer = [] #queue os bytes
self.peer = None
def __repr__(self):
return "SOCKET(%x, %r, %x)" % (hash(self), self.buffer, hash(self.peer))
def is_connected(self):
return self.peer is not None
def is_empty(self):
return not self.buffer
def is_full(self):
return len(self.buffer) > 2 * 1024
def connect(self, peer):
assert not self.is_connected()
assert not peer.is_connected()
self.peer = peer
if peer.peer is None:
peer.peer = self
def read(self, size):
return self.receive(size)
def receive(self, size):
rx_bytes = min(size, len(self.buffer))
ret = []
for i in xrange(rx_bytes):
ret.append(self.buffer.pop())
return ret
def write(self, buf):
assert self.is_connected()
return self.peer._transmit(buf)
def _transmit(self, buf):
for c in buf:
self.buffer.insert(0, c)
return len(buf)
def sync(self):
raise BadFd("Invalid sync() operation on Socket")
def seek(self, *args):
raise BadFd("Invalid lseek() operation on Socket")
class Linux(Platform):
'''
A simple Linux Operating System Platform.
This class emulates the most common Linux system calls
'''
def __init__(self, program, argv=None, envp=None):
'''
Builds a Linux OS platform
:param string program: The path to ELF binary
:param list argv: The argv array; not including binary.
:param list envp: The ENV variables.
:ivar files: List of active file descriptors
:type files: list[Socket] or list[File]
'''
super(Linux, self).__init__(program)
self.program = program
self.clocks = 0
self.files = []
self.syscall_trace = []
if program != None:
self.elf = ELFFile(file(program))
self.arch = {'x86': 'i386', 'x64': 'amd64', 'ARM': 'armv7'}[self.elf.get_machine_arch()]
self._init_cpu(self.arch)
self._init_std_fds()
self._execve(program, argv, envp)
@classmethod
def empty_platform(cls, arch):
'''
Create a platform without an ELF loaded.
:param str arch: The architecture of the new platform
:rtype: Linux
'''
platform = cls(None)
platform._init_cpu(arch)
platform._init_std_fds()
return platform
def _init_std_fds(self):
# open standard files stdin, stdout, stderr
logger.debug("Opening file descriptors (0,1,2) (STDIN, STDOUT, STDERR)")
self.input = Socket()
self.output = Socket()
self.stderr = Socket()
stdin = Socket()
stdout = Socket()
stderr = Socket()
#A transmit to stdin,stdout or stderr will be directed to out
stdin.peer = self.output
stdout.peer = self.output
stderr.peer = self.stderr
#A receive from stdin will get data from input
self.input.peer = stdin
#A receive on stdout or stderr will return no data (rx_bytes: 0)
assert self._open(stdin) == 0
assert self._open(stdout) == 1
assert self._open(stderr) == 2
def _init_cpu(self, arch):
cpu = self._mk_proc(arch)
self.procs = [cpu]
self._current = 0
self._function_abi = CpuFactory.get_function_abi(cpu, 'linux', arch)
self._syscall_abi = CpuFactory.get_syscall_abi(cpu, 'linux', arch)
def _execve(self, program, argv, envp):
'''
Load `program` and establish program state, such as stack and arguments.
:param program str: The ELF binary to load
:param argv list: argv array
:param envp list: envp array
'''
argv = [] if argv is None else argv
envp = [] if envp is None else envp
logger.debug("Loading {} as a {} elf".format(program,self.arch))
self.load(program)
self._arch_specific_init()
self._stack_top = self.current.STACK
self.setup_stack([program]+argv, envp)
nprocs = len(self.procs)
nfiles = len(self.files)
assert nprocs > 0
self.running = range(nprocs)
#Each process can wait for one timeout
self.timers = [ None ] * nprocs
#each fd has a waitlist
self.rwait = [set() for _ in xrange(nfiles)]
self.twait = [set() for _ in xrange(nfiles)]
def _mk_proc(self, arch):
if arch in {'i386', 'armv7'}:
mem = Memory32()
else:
mem = Memory64()
return CpuFactory.get_cpu(mem, arch)
@property
def current(self):
return self.procs[self._current]
def __getstate__(self):
state = {}
state['clocks'] = self.clocks
state['input'] = self.input.buffer
state['output'] = self.output.buffer
# Store the type of file descriptor and the respective contents
state_files = []
for fd in self.files:
if isinstance(fd, Socket):
state_files.append(('Socket', fd.buffer))
else:
state_files.append(('File', fd))
state['files'] = state_files
state['procs'] = self.procs
state['current'] = self._current
state['running'] = self.running
state['rwait'] = self.rwait
state['twait'] = self.twait
state['timers'] = self.timers
state['syscall_trace'] = self.syscall_trace
state['base'] = self.base
state['elf_bss'] = self.elf_bss
state['end_code'] = self.end_code
state['end_data'] = self.end_data
state['elf_brk'] = self.elf_brk
state['auxv'] = self.auxv
state['program'] = self.program
state['functionabi'] = self._function_abi
state['syscallabi'] = self._syscall_abi
state['uname_machine'] = self._uname_machine
if hasattr(self, '_arm_tls_memory'):
state['_arm_tls_memory'] = self._arm_tls_memory
return state
def __setstate__(self, state):
"""
:todo: some asserts
:todo: fix deps? (last line)
"""
self.input = Socket()
self.input.buffer = state['input']
self.output = Socket()
self.output.buffer = state['output']
# fetch each file descriptor (Socket or File())
self.files = []
for ty, buf in state['files']:
if ty == 'Socket':
f = Socket()
f.buffer = buf
self.files.append(f)
else:
self.files.append(buf)
self.files[0].peer = self.output
self.files[1].peer = self.output
self.files[2].peer = self.output
self.input.peer = self.files[0]
self.procs = state['procs']
self._current = state['current']
self.running = state['running']
self.rwait = state['rwait']
self.twait = state['twait']
self.timers = state['timers']
self.clocks = state['clocks']
self.syscall_trace = state['syscall_trace']
self.base = state['base']
self.elf_bss = state['elf_bss']
self.end_code = state['end_code']
self.end_data = state['end_data']
self.elf_brk = state['elf_brk']
self.auxv = state['auxv']
self.program = state['program']
self._function_abi = state['functionabi']
self._syscall_abi = state['syscallabi']
self._uname_machine = state['uname_machine']
if '_arm_tls_memory' in state:
self._arm_tls_memory = state['_arm_tls_memory']
def _init_arm_kernel_helpers(self):
'''
ARM kernel helpers
https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
'''
page_data = bytearray('\xf1\xde\xfd\xe7' * 1024)
# Extracted from a RPi2
preamble = (
'ff0300ea' +
'650400ea' +
'f0ff9fe5' +
'430400ea' +
'220400ea' +
'810400ea' +
'000400ea' +
'870400ea'
).decode('hex')
# XXX(yan): The following implementations of cmpxchg and cmpxchg64 were
# handwritten to not use any exclusive instructions (e.g. ldrexd) or
# locking. For actual implementations, refer to
# arch/arm64/kernel/kuser32.S in the Linux source code.
__kuser_cmpxchg64 = (
'30002de9' + # push {r4, r5}
'08c09de5' + # ldr ip, [sp, #8]
'30009ce8' + # ldm ip, {r4, r5}
'010055e1' + # cmp r5, r1
'00005401' + # cmpeq r4, r0
'0100a013' + # movne r0, #1
'0000a003' + # moveq r0, #0
'0c008c08' + # stmeq ip, {r2, r3}
'3000bde8' + # pop {r4, r5}
'1eff2fe1' # bx lr
).decode('hex')
__kuser_dmb = (
'5bf07ff5' + # dmb ish
'1eff2fe1' # bx lr
).decode('hex')
__kuser_cmpxchg = (
'003092e5' + # ldr r3, [r2]
'000053e1' + # cmp r3, r0
'0000a003' + # moveq r0, #0
'00108205' + # streq r1, [r2]
'0100a013' + # movne r0, #1
'1eff2fe1' # bx lr
).decode('hex')
# Map a TLS segment
self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ')
__kuser_get_tls = (
'04009FE5' + # ldr r0, [pc, #4]
'010090e8' + # ldm r0, {r0}
'1eff2fe1' # bx lr
).decode('hex') + struct.pack('<I', self._arm_tls_memory)
tls_area = '\x00'*12
version = struct.pack('<I', 5)
def update(address, code):
page_data[address:address+len(code)] = code
# Offsets from Documentation/arm/kernel_user_helpers.txt in Linux
update(0x000, preamble)
update(0xf60, __kuser_cmpxchg64)
update(0xfa0, __kuser_dmb)
update(0xfc0, __kuser_cmpxchg)
update(0xfe0, __kuser_get_tls)
update(0xff0, tls_area)
update(0xffc, version)
self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)
def load_vdso(self, bits):
#load vdso #TODO or #IGNORE
vdso_top = {32: 0x7fff0000, 64: 0x7fff00007fff0000}[bits]
vdso_size = len(file('vdso%2d.dump'%bits).read())
vdso_addr = self.memory.mmapFile(self.memory._floor(vdso_top - vdso_size),
vdso_size,
'r x',
{32: 'vdso32.dump', 64: 'vdso64.dump'}[bits],
0)
return vdso_addr
def setup_stack(self, argv, envp):
'''
:param Cpu cpu: The cpu instance
:param argv: list of parameters for the program to execute.
:param envp: list of environment variables for the program to execute.
http://www.phrack.org/issues.html?issue=58&id=5#article
position content size (bytes) + comment
----------------------------------------------------------------------
stack pointer -> [ argc = number of args ] 4
[ argv[0] (pointer) ] 4 (program name)
[ argv[1] (pointer) ] 4
[ argv[..] (pointer) ] 4 * x
[ argv[n - 1] (pointer) ] 4
[ argv[n] (pointer) ] 4 (= NULL)
[ envp[0] (pointer) ] 4
[ envp[1] (pointer) ] 4
[ envp[..] (pointer) ] 4
[ envp[term] (pointer) ] 4 (= NULL)
[ auxv[0] (Elf32_auxv_t) ] 8
[ auxv[1] (Elf32_auxv_t) ] 8
[ auxv[..] (Elf32_auxv_t) ] 8
[ auxv[term] (Elf32_auxv_t) ] 8 (= AT_NULL vector)
[ padding ] 0 - 16
[ argument ASCIIZ strings ] >= 0
[ environment ASCIIZ str. ] >= 0
(0xbffffffc) [ end marker ] 4 (= NULL)
(0xc0000000) < top of stack > 0 (virtual)
----------------------------------------------------------------------
'''
cpu = self.current
# In case setup_stack() is called again, we make sure we're growing the
# stack from the original top
cpu.STACK = self._stack_top
auxv = self.auxv
logger.debug("Setting argv, envp and auxv.")
logger.debug("\tArguments: %s", repr(argv))
if envp:
logger.debug("\tEnvironment:")
for e in envp:
logger.debug("\t\t%s", repr(e))
logger.debug("\tAuxv:")
for name, val in auxv.items():
logger.debug("\t\t%s: %s", name, hex(val))
#We save the argument and environment pointers
argvlst = []
envplst = []
#end envp marker empty string
for evar in envp:
cpu.push_bytes('\x00')
envplst.append(cpu.push_bytes(evar))
for arg in argv:
cpu.push_bytes('\x00')
argvlst.append(cpu.push_bytes(arg))
#Put all auxv strings into the string stack area.
#And replace the value be its pointer
for name, value in auxv.items():
if hasattr(value, '__len__'):
cpu.push_bytes(value)
auxv[name] = cpu.STACK
#The "secure execution" mode of secure_getenv() is controlled by the
#AT_SECURE flag contained in the auxiliary vector passed from the
#kernel to user space.
auxvnames = {
'AT_IGNORE': 1, # Entry should be ignored
'AT_EXECFD': 2, # File descriptor of program
'AT_PHDR': 3, # Program headers for program
'AT_PHENT':4, # Size of program header entry
'AT_PHNUM':5, # Number of program headers
'AT_PAGESZ': 6, # System page size
'AT_BASE': 7, # Base address of interpreter
'AT_FLAGS':8, # Flags
'AT_ENTRY':9, # Entry point of program
'AT_NOTELF': 10, # Program is not ELF
'AT_UID':11, # Real uid
'AT_EUID': 12, # Effective uid
'AT_GID':13, # Real gid
'AT_EGID': 14, # Effective gid
'AT_CLKTCK': 17, # Frequency of times()
'AT_PLATFORM': 15, # String identifying platform.
'AT_HWCAP':16, # Machine-dependent hints about processor capabilities.
'AT_FPUCW':18, # Used FPU control word.
'AT_SECURE': 23, # Boolean, was exec setuid-like?
'AT_BASE_PLATFORM': 24, # String identifying real platforms.
'AT_RANDOM': 25, # Address of 16 random bytes.
'AT_EXECFN': 31, # Filename of executable.
'AT_SYSINFO':32, #Pointer to the global system page used for system calls and other nice things.
'AT_SYSINFO_EHDR': 33, #Pointer to the global system page used for system calls and other nice things.
}
#AT_NULL
cpu.push_int(0)
cpu.push_int(0)
for name, val in auxv.items():
cpu.push_int(val)
cpu.push_int(auxvnames[name])
# NULL ENVP
cpu.push_int(0)
for var in reversed(envplst): # ENVP n
cpu.push_int(var)
envp = cpu.STACK
# NULL ARGV
cpu.push_int(0)
for arg in reversed(argvlst): # Argv n
cpu.push_int(arg)
argv = cpu.STACK
#ARGC
cpu.push_int(len(argvlst))
def load(self, filename):
'''
Loads and an ELF program in memory and prepares the initial CPU state.
Creates the stack and loads the environment variables and the arguments in it.
:param filename: pathname of the file to be executed. (used for auxv)
:raises error:
- 'Not matching cpu': if the program is compiled for a different architecture
- 'Not matching memory': if the program is compiled for a different address size
:todo: define va_randomize and read_implies_exec personality
'''
#load elf See binfmt_elf.c
#read the ELF object file
cpu = self.current
elf = self.elf
arch = self.arch
addressbitsize = {'x86':32, 'x64':64, 'ARM': 32}[elf.get_machine_arch()]
logger.debug("Loading %s as a %s elf"%(filename, arch))
assert elf.header.e_type in ['ET_DYN', 'ET_EXEC', 'ET_CORE']
#Get interpreter elf
interpreter = None
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_INTERP':
continue
interpreter_filename = elf_segment.data()[:-1]
logger.info('Interpreter filename: %s', interpreter_filename)
interpreter = ELFFile(file(interpreter_filename))
break
if not interpreter is None:
assert interpreter.get_machine_arch() == elf.get_machine_arch()
assert interpreter.header.e_type in ['ET_DYN', 'ET_EXEC']
#Stack Executability
executable_stack = False
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_GNU_STACK':
continue
if elf_segment.header.p_flags & 0x01:
executable_stack = True
else:
executable_stack = False
break
base = 0
elf_bss = 0
end_code = 0
end_data = 0
elf_brk = 0
load_addr = 0
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_LOAD':
continue
align = 0x1000 #elf_segment.header.p_align
ELF_PAGEOFFSET = elf_segment.header.p_vaddr & (align-1)
flags = elf_segment.header.p_flags
memsz = elf_segment.header.p_memsz + ELF_PAGEOFFSET
offset = elf_segment.header.p_offset - ELF_PAGEOFFSET
filesz = elf_segment.header.p_filesz + ELF_PAGEOFFSET
vaddr = elf_segment.header.p_vaddr - ELF_PAGEOFFSET
memsz = cpu.memory._ceil(memsz)
if base == 0 and elf.header.e_type == 'ET_DYN':
assert vaddr == 0
if addressbitsize == 32:
base = 0x56555000
else:
base = 0x555555554000
perms = perms_from_elf(flags)
hint = base+vaddr
if hint == 0:
hint = None
logger.debug("Loading elf offset: %08x addr:%08x %08x %s" %(offset, base+vaddr, base+vaddr+memsz, perms))
base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) - vaddr
if load_addr == 0 :
load_addr = base + vaddr
k = base + vaddr + filesz;
if k > elf_bss :
elf_bss = k;
if (flags & 4) and end_code < k: #PF_X
end_code = k
if end_data < k:
end_data = k
k = base + vaddr + memsz
if k > elf_brk:
elf_brk = k
elf_entry = elf.header.e_entry
if elf.header.e_type == 'ET_DYN':
elf_entry += load_addr
entry = elf_entry
real_elf_brk = elf_brk
# We need to explicitly zero any fractional pages
# after the data section (i.e. bss). This would
# contain the junk from the file that should not
# be in memory
#TODO:
#cpu.write_bytes(elf_bss, '\x00'*((elf_bss | (align-1))-elf_bss))
logger.debug("Zeroing main elf fractional pages. From %x to %x.", elf_bss, elf_brk)
logger.debug("Main elf bss:%x"%elf_bss)
logger.debug("Main elf brk %x:"%elf_brk)
#FIXME Need a way to inspect maps and perms so
#we can rollback all to the initial state after zeroing
#if elf_brk-elf_bss > 0:
# saved_perms = cpu.mem.perms(elf_bss)
# cpu.memory.mprotect(cpu.mem._ceil(elf_bss), elf_brk-elf_bss, 'rw ')
# logger.debug("Zeroing main elf fractional pages (%d bytes)", elf_brk-elf_bss)
# cpu.write_bytes(elf_bss, ['\x00'] * (elf_brk-elf_bss))
# cpu.memory.mprotect(cpu.memory._ceil(elf_bss), elf_brk-elf_bss, saved_perms)
if cpu.memory.access_ok(slice(elf_bss, elf_brk), 'w'):
cpu.memory[elf_bss:elf_brk] = '\x00'*(elf_brk-elf_bss)
else:
logger.warning("Failing to zerify the trailing: elf_brk-elf_bss")
stack_size = 0x21000
if addressbitsize == 32:
stack_top = 0xc0000000
else:
stack_top = 0x800000000000
stack_base = stack_top - stack_size
stack = cpu.memory.mmap(stack_base, stack_size, 'rwx', name='stack') + stack_size
assert stack_top == stack
reserved = cpu.memory.mmap(base+vaddr+memsz,0x1000000, ' ')
interpreter_base = 0
if interpreter is not None:
base = 0
elf_bss = 0
end_code = 0
end_data = 0
elf_brk = 0
entry = interpreter.header.e_entry
for elf_segment in interpreter.iter_segments():
if elf_segment.header.p_type != 'PT_LOAD':
continue
align = 0x1000#elf_segment.header.p_align
vaddr = elf_segment.header.p_vaddr
filesz = elf_segment.header.p_filesz
flags = elf_segment.header.p_flags
offset = elf_segment.header.p_offset
memsz = elf_segment.header.p_memsz
ELF_PAGEOFFSET = (vaddr & (align-1))
memsz = memsz + ELF_PAGEOFFSET
offset = offset - ELF_PAGEOFFSET
filesz = filesz + ELF_PAGEOFFSET
vaddr = vaddr - ELF_PAGEOFFSET
memsz = cpu.memory._ceil(memsz)
if base == 0 and interpreter.header.e_type == 'ET_DYN':
assert vaddr == 0
total_size = self._interp_total_size(interpreter)
base = stack_base - total_size
if base == 0:
assert vaddr == 0
perms = perms_from_elf(flags)
hint = base+vaddr
if hint == 0:
hint = None
base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset)
base -= vaddr
logger.debug("Loading interpreter offset: %08x addr:%08x %08x %s%s%s" %(offset, base+vaddr, base+vaddr+memsz, (flags&1 and 'r' or ' '), (flags&2 and 'w' or ' '), (flags&4 and 'x' or ' ')))
k = base + vaddr + filesz;
if k > elf_bss:
elf_bss = k
if (flags & 4) and end_code < k: #PF_X
end_code = k
if end_data < k:
end_data = k
k = base + vaddr+ memsz
if k > elf_brk:
elf_brk = k
if interpreter.header.e_type == 'ET_DYN':
entry += base
interpreter_base = base
logger.debug("Zeroing interpreter elf fractional pages. From %x to %x.", elf_bss, elf_brk)
logger.debug("Interpreter bss:%x", elf_bss)
logger.debug("Interpreter brk %x:", elf_brk)
cpu.memory.mprotect(cpu.memory._floor(elf_bss), elf_brk-elf_bss, 'rw ')
try:
cpu.memory[elf_bss:elf_brk] = '\x00'*(elf_brk-elf_bss)
except Exception, e:
logger.debug("Exception zeroing Interpreter fractional pages: %s"%str(e))
#TODO #FIXME mprotect as it was before zeroing?
#free reserved brk space
cpu.memory.munmap(reserved, 0x1000000)
#load vdso
#vdso_addr = load_vdso(addressbitsize)
cpu.STACK = stack
cpu.PC = entry
logger.debug("Entry point: %016x", entry)
logger.debug("Stack start: %016x", stack)
logger.debug("Brk: %016x", real_elf_brk)
logger.debug("Mappings:")
for m in str(cpu.memory).split('\n'):
logger.debug(" %s", m)
self.base = base
self.elf_bss = elf_bss
self.end_code = end_code
self.end_data = end_data
self.elf_brk = real_elf_brk
at_random = cpu.push_bytes('A'*16)
at_execfn = cpu.push_bytes(filename+'\x00')
self.auxv = {
'AT_PHDR' : load_addr+elf.header.e_phoff, # Program headers for program
'AT_PHENT' : elf.header.e_phentsize, # Size of program header entry
'AT_PHNUM' : elf.header.e_phnum, # Number of program headers
'AT_PAGESZ' : cpu.memory.page_size, # System page size
'AT_BASE' : interpreter_base, # Base address of interpreter
'AT_FLAGS' : elf.header.e_flags, # Flags
'AT_ENTRY' : elf_entry, # Entry point of program
'AT_UID' : 1000, # Real uid
'AT_EUID' : 1000, # Effective uid
'AT_GID' : 1000, # Real gid
'AT_EGID' : 1000, # Effective gid
'AT_CLKTCK' : 100, # Frequency of times()
'AT_HWCAP' : 0, # Machine-dependent hints about processor capabilities.
'AT_RANDOM' : at_random, # Address of 16 random bytes.
'AT_EXECFN' : at_execfn, # Filename of executable.
}
def _open(self, f):
'''
Adds a file descriptor to the current file descriptor list
:rtype: int
:param f: the file descriptor to add.
:return: the index of the file descriptor in the file descr. list
'''
if None in self.files:
fd = self.files.index(None)
self.files[fd] = f
else:
fd = len(self.files)
self.files.append(f)
return fd
def _close(self, fd):
'''
Removes a file descriptor from the file descriptor list
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.
'''
self.files[fd] = None
def _dup(self, fd):
'''
Duplicates a file descriptor
:rtype: int
:param fd: the file descriptor to duplicate.
:return: C{0} on success.
'''
return self._open(self.files[fd])
def _get_fd(self, fd):
if fd < 0 or fd >= len(self.files) or self.files[fd] is None:
raise BadFd()
else:
return self.files[fd]
def sys_umask(self, mask):
'''
umask - Set file creation mode mask
:param int mask: New mask
'''
logger.debug("umask(%o)", mask)
return os.umask(mask)
def sys_chdir(self, path):
'''
chdir - Change current working directory
:param int path: Pointer to path
'''
path_str = self.current.read_string(path)
logger.debug("chdir(%s)", path_str)
try:
os.chdir(path_str)
return 0
except OSError as e:
return e.errno
def sys_lseek(self, fd, offset, whence):
'''
lseek - reposition read/write file offset
The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence
:param self: current CPU.
:param fd: a valid file descriptor
:param offset: the offset in bytes
:param whence: SEEK_SET: The file offset is set to offset bytes.
SEEK_CUR: The file offset is set to its current location plus offset bytes.
SEEK_END: The file offset is set to the size of the file plus offset bytes.
:return: 0 (Success), or EBADF (fd is not a valid file descriptor or is not open)
'''
if self.current.address_bit_size == 32:
signed_offset = ctypes.c_int32(offset).value
else:
signed_offset = ctypes.c_int64(offset).value
try:
self._get_fd(fd).seek(signed_offset, whence)
except BadFd:
logger.info(("LSEEK: Not valid file descriptor on lseek."
"Fd not seekable. Returning EBADF"))
return -errno.EBADF
logger.debug("LSEEK(%d, 0x%08x (%d), %d)", fd, offset, signed_offset, whence)
return 0
def sys_read(self, fd, buf, count):
data = ''
if count != 0:
# TODO check count bytes from buf
if not buf in self.current.memory: # or not self.current.memory.isValid(buf+count):
logger.info("READ: buf points to invalid address. Returning EFAULT")
return -errno.EFAULT
try:
# Read the data and put in tin memory
data = self._get_fd(fd).read(count)
except BadFd:
logger.info(("READ: Not valid file descriptor on read."
" Returning EBADF"))
return -errno.EBADF
self.syscall_trace.append(("_read", fd, data))
self.current.write_bytes(buf, data)
logger.debug("READ(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)",
fd,
buf,
count,
len(data),
repr(data)[:min(count,10)],
len(data))
return len(data)
def sys_write(self, fd, buf, count):
''' write - send bytes through a file descriptor
The write system call writes up to count bytes from the buffer pointed
to by buf to the file descriptor fd. If count is zero, write returns 0
and optionally sets *tx_bytes to zero.
:param fd a valid file descriptor
:param buf a memory buffer
:param count number of bytes to send
:return: 0 Success
EBADF fd is not a valid file descriptor or is not open.
EFAULT buf or tx_bytes points to an invalid address.
'''
data = []
cpu = self.current
if count != 0:
try:
write_fd = self._get_fd(fd)
except BadFd:
logger.error("WRITE: Not valid file descriptor. Returning EBADFD %d", fd)
return -errno.EBADF
# TODO check count bytes from buf
if buf not in cpu.memory or buf + count not in cpu.memory:
logger.debug("WRITE: buf points to invalid address. Returning EFAULT")
return -errno.EFAULT
if fd > 2 and write_fd.is_full():
cpu.PC -= cpu.instruction.size
self.wait([], [fd], None)
raise RestartSyscall()
data = cpu.read_bytes(buf, count)
write_fd.write(data)
for line in ''.join([str(x) for x in data]).split('\n'):
logger.debug("WRITE(%d, 0x%08x, %d) -> <%.48r>",
fd,
buf,
count,
line)
self.syscall_trace.append(("_write", fd, data))
self.signal_transmit(fd)
return len(data)
def sys_access(self, buf, mode):
'''
Checks real user's permissions for a file
:rtype: int
:param buf: a buffer containing the pathname to the file to check its permissions.
:param mode: the access permissions to check.
:return:
- C{0} if the calling process can access the file in the desired mode.
- C{-1} if the calling process can not access the file in the desired mode.
'''
filename = ""
for i in xrange(0, 255):
c = Operators.CHR(self.current.read_int(buf + i, 8))
if c == '\x00':
break
filename += c
logger.debug("access(%s, %x) -> %r",
filename,
mode,
os.access(filename, mode))
if os.access(filename, mode):
return 0
else:
return -1
def sys_newuname(self, old_utsname):
'''
Writes system information in the variable C{old_utsname}.
:rtype: int
:param old_utsname: the buffer to write the system info.
:return: C{0} on success
'''
from datetime import datetime
def pad(s):
return s +'\x00'*(65-len(s))
now = datetime.now().strftime("%a %b %d %H:%M:%S ART %Y")
info = (('sysname', 'Linux'),
('nodename', 'ubuntu'),
('release', '4.4.0-77-generic'),
('version', '#98 SMP ' + now),
('machine', self._uname_machine),
('domainname', ''))
uname_buf = ''.join(pad(pair[1]) for pair in info)
self.current.write_bytes(old_utsname, uname_buf)
logger.debug("sys_newuname(...) -> %s", uname_buf)
return 0
def sys_brk(self, brk):
'''
Changes data segment size (moves the C{elf_brk} to the new address)
:rtype: int
:param brk: the new address for C{elf_brk}.
:return: the value of the new C{elf_brk}.
:raises error:
- "Error in brk!" if there is any error allocating the memory
'''
if brk != 0:
assert brk > self.elf_brk
mem = self.current.memory
size = brk-self.elf_brk
perms = mem.perms(self.elf_brk-1)
if brk > mem._ceil(self.elf_brk):
addr = mem.mmap(mem._ceil(self.elf_brk), size, perms)
assert mem._ceil(self.elf_brk) == addr, "Error in brk!"
self.elf_brk += size
logger.debug("sys_brk(0x%08x) -> 0x%08x", brk, self.elf_brk)
return self.elf_brk
def sys_arch_prctl(self, code, addr):
'''
Sets architecture-specific thread state
:rtype: int
:param code: must be C{ARCH_SET_FS}.
:param addr: the base address of the FS segment.
:return: C{0} on success
:raises error:
- if C{code} is different to C{ARCH_SET_FS}
'''
ARCH_SET_GS = 0x1001
ARCH_SET_FS = 0x1002
ARCH_GET_FS = 0x1003
ARCH_GET_GS = 0x1004
assert code == ARCH_SET_FS
self.current.FS = 0x63
self.current.set_descriptor(self.current.FS, addr, 0x4000, 'rw')
logger.debug("sys_arch_prctl(%04x, %016x) -> 0", code, addr)
return 0
def sys_ioctl(self, fd, request, argp):
if fd > 2:
return self.files[fd].ioctl(request, argp)
else:
return -errno.EINVAL
def _sys_open_get_file(self, filename, flags, mode):
f = File(filename, mode) # TODO (theo) modes, flags
return f
def sys_open(self, buf, flags, mode):
'''
:param buf: address of zero-terminated pathname
:param flags: file access bits
:param mode: file permission mode
'''
filename = self.current.read_string(buf)
try:
if os.path.abspath(filename).startswith('/proc/self'):
if filename == '/proc/self/exe':
filename = os.path.abspath(self.program)
else:
logger.info("FIXME!")
mode = {os.O_RDWR: 'r+', os.O_RDONLY: 'r', os.O_WRONLY: 'w'}[flags&7]
f = self._sys_open_get_file(filename, flags, mode)
logger.debug("Opening file %s for %s real fd %d",
filename, mode, f.fileno())
# FIXME(theo) generic exception
except Exception as e:
logger.info("Could not open file %s. Reason %s" % (filename, str(e)))
return -1
return self._open(f)
def sys_rename(self, oldnamep, newnamep):
'''
Rename filename `oldnamep` to `newnamep`.
:param int oldnamep: pointer to oldname
:param int newnamep: pointer to newname
'''
oldname = self.current.read_string(oldnamep)
newname = self.current.read_string(newnamep)
ret = 0
try:
os.rename(oldname, newname)
except OSError as e:
ret = -e.errno
logger.debug("sys_rename('%s', '%s') -> %s", oldname, newname, ret)
return ret
def sys_fsync(self, fd):
'''
Synchronize a file's in-core state with that on disk.
'''
ret = 0
try:
self.files[fd].sync()
except IndexError:
ret = -errno.EBADF
except BadFd:
ret = -errno.EINVAL
logger.debug("sys_fsync(%d) -> %d", fd, ret)
return ret
def sys_getpid(self, v):
logger.debug("GETPID, warning pid modeled as concrete 1000")
return 1000
def sys_ARM_NR_set_tls(self, val):
if hasattr(self, '_arm_tls_memory'):
self.current.write_int(self._arm_tls_memory, val)
self.current.set_arm_tls(val)
return 0
#Signals..
def sys_kill(self, pid, sig):
logger.debug("KILL, Ignoring Sending signal %d to pid %d", sig, pid)
return 0
def sys_rt_sigaction(self, signum, act, oldact):
"""Wrapper for sys_sigaction"""
return self.sys_sigaction(signum, act, oldact)
def sys_sigaction(self, signum, act, oldact):
logger.debug("SIGACTION, Ignoring changing signal handler for signal %d",
signum)
return 0
def sys_rt_sigprocmask(self, cpu, how, newset, oldset):
'''Wrapper for sys_sigprocmask'''
return self.sys_sigprocmask(cpu, how, newset, oldset)
def sys_sigprocmask(self, cpu, how, newset, oldset):
logger.debug("SIGACTION, Ignoring changing signal mask set cmd:%d", how)
return 0
def sys_close(self, fd):
'''
Closes a file descriptor
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.
'''
if fd > 0 :
self._close(fd)
logger.debug('sys_close(%d)', fd)
return 0
def sys_readlink(self, path, buf, bufsize):
'''
Read
:rtype: int
:param path: the "link path id"
:param buf: the buffer where the bytes will be putted.
:param bufsize: the max size for read the link.
:todo: Out eax number of bytes actually sent | EAGAIN | EBADF | EFAULT | EINTR | errno.EINVAL | EIO | ENOSPC | EPIPE
'''
if bufsize <= 0:
return -errno.EINVAL
filename = self.current.read_string(path)
if filename == '/proc/self/exe':
data = os.path.abspath(self.program)
else:
data = os.readlink(filename)[:bufsize]
self.current.write_bytes(buf, data)
logger.debug("READLINK %d %x %d -> %s",path,buf,bufsize,data)
return len(data)
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):
'''Wrapper for mmap2'''
return self.sys_mmap2(address, size, prot, flags, fd, offset)
def sys_mmap2(self, address, size, prot, flags, fd, offset):
'''
Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
processes mapping the same region, and whether updates are carried
through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset}*0x1000 in the file referred to by the file descriptor C{fd}.
:return:
- C{-1} In case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
- the address of the new mapping.
'''
return self.sys_mmap(address, size, prot, flags, fd, offset*0x1000)
def sys_mmap(self, address, size, prot, flags, fd, offset):
'''
Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
processes mapping the same region, and whether updates are carried
through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:return:
- C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
- the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags).
:todo: handle exception.
'''
if address == 0:
address = None
cpu = self.current
if flags & 0x10 != 0:
cpu.memory.munmap(address,size)
perms = perms_from_protflags(prot)
if flags & 0x20 != 0:
result = cpu.memory.mmap(address, size, perms)
elif fd == 0:
assert offset == 0
result = cpu.memory.mmap(address, size, perms)
data = self.files[fd].read(size)
cpu.write_bytes(result, data)
else:
#FIXME Check if file should be symbolic input and do as with fd0
result = cpu.memory.mmapFile(address, size, perms, self.files[fd].name, offset)
actually_mapped = '0x{:016x}'.format(result)
if address is None or result != address:
address = address or 0
actually_mapped += ' [requested: 0x{:016x}]'.format(address)
if flags & 0x10 != 0 and result != address:
cpu.memory.munmap(result, size)
result = -1
logger.debug("sys_mmap(%s, 0x%x, %s, %x, %d) - (0x%x)",
actually_mapped,
size,
perms,
flags,
fd,
result)
return result
def sys_mprotect(self, start, size, prot):
'''
Sets protection on a region of memory. Changes protection for the calling process's
memory page(s) containing any part of the address range in the interval [C{start}, C{start}+C{size}-1].
:rtype: int
:param start: the starting address to change the permissions.
:param size: the size of the portion of memory to change the permissions.
:param prot: the new access permission for the memory.
:return: C{0} on success.
'''
perms = perms_from_protflags(prot)
ret = self.current.memory.mprotect(start, size, perms)
logger.debug("sys_mprotect(0x%016x, 0x%x, %s) -> %r (%r)", start, size, perms, ret, prot)
return 0
def sys_munmap(self, addr, size):
'''
Unmaps a file from memory. It deletes the mappings for the specified address range
:rtype: int
:param addr: the starting address to unmap.
:param size: the size of the portion to unmap.
:return: C{0} on success.
'''
self.current.memory.munmap(addr, size)
return 0
def sys_getuid(self):
'''
Gets user identity.
:rtype: int
:return: this call returns C{1000} for all the users.
'''
return 1000
def sys_getgid(self):
'''
Gets group identity.
:rtype: int
:return: this call returns C{1000} for all the groups.
'''
return 1000
def sys_geteuid(self):
'''
Gets user identity.
:rtype: int
:return: This call returns C{1000} for all the users.
'''
return 1000
def sys_getegid(self):
'''
Gets group identity.
:rtype: int
:return: this call returns C{1000} for all the groups.
'''
return 1000
def sys_readv(self, fd, iov, count):
'''
Works just like C{sys_read} except that data is read into multiple buffers.
:rtype: int
:param fd: the file descriptor of the file to read.
:param iov: the buffer where the the bytes to read are stored.
:param count: amount of C{iov} buffers to read from the file.
:return: the amount of bytes read in total.
'''
cpu = self.current
ptrsize = cpu.address_bit_size
sizeof_iovec = 2 * (ptrsize // 8)
total = 0
for i in xrange(0, count):
buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)
size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2),
ptrsize)
data = self.files[fd].read(size)
total += len(data)
cpu.write_bytes(buf, data)
self.syscall_trace.append(("_read", fd, data))
logger.debug("READV(%r, %r, %r) -> <%r> (size:%r)",
fd,
buf,
size,
data,
len(data))
return total
def sys_writev(self, fd, iov, count):
'''
Works just like C{sys_write} except that multiple buffers are written out.
:rtype: int
:param fd: the file descriptor of the file to write.
:param iov: the buffer where the the bytes to write are taken.
:param count: amount of C{iov} buffers to write into the file.
:return: the amount of bytes written in total.
'''
cpu = self.current
ptrsize = cpu.address_bit_size
sizeof_iovec = 2 * (ptrsize // 8)
total = 0
for i in xrange(0, count):
buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)
size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize)
data = ""
for j in xrange(0,size):
data += Operators.CHR(cpu.read_int(buf + j, 8))
logger.debug("WRITEV(%r, %r, %r) -> <%r> (size:%r)"%(fd, buf, size, data, len(data)))
self.files[fd].write(data)
self.syscall_trace.append(("_write", fd, data))
total+=size
return total
def sys_set_thread_area(self, user_info):
'''
Sets a thread local storage (TLS) area. Sets the base address of the GS segment.
:rtype: int
:param user_info: the TLS array entry set corresponds to the value of C{u_info->entry_number}.
:return: C{0} on success.
'''
n = self.current.read_int(user_info, 32)
pointer = self.current.read_int(user_info + 4, 32)
m = self.current.read_int(user_info + 8, 32)
flags = self.current.read_int(user_info + 12, 32)
assert n == 0xffffffff
assert flags == 0x51 #TODO: fix
self.current.GS = 0x63
self.current.set_descriptor(self.current.GS, pointer, 0x4000, 'rw')
self.current.write_int(user_info, (0x63 - 3) / 8, 32)
return 0
def sys_getpriority(self, which, who):
'''
System call ignored.
:rtype: int
:return: C{0}
'''
logger.debug("Ignoring sys_get_priority")
return 0
def sys_setpriority(self, which, who, prio):
'''
System call ignored.
:rtype: int
:return: C{0}
'''
logger.debug("Ignoring sys_setpriority")
return 0
def sys_acct(self, path):
'''
System call not implemented.
:rtype: int
:return: C{-1}
'''
logger.debug("BSD account not implemented!")
return -1
def sys_exit(self, error_code):
'Wrapper for sys_exit_group'
return self.sys_exit_group(error_code)
def sys_exit_group(self, error_code):
'''
Exits all threads in a process
:raises Exception: 'Finished'
'''
procid = self.procs.index(self.current)
self.sched()
self.running.remove(procid)
#self.procs[procid] = None
logger.debug("EXIT_GROUP PROC_%02d %s", procid, error_code)
if len(self.running) == 0:
raise ProcessExit(error_code)
return error_code
def sys_ptrace(self, request, pid, addr, data):
logger.debug("sys_ptrace(%016x, %d, %016x, %016x) -> 0", request, pid, addr, data)
return 0
def sys_nanosleep(self, req, rem):
logger.debug("sys_nanosleep(...)")
return 0
def sys_set_tid_address(self, tidptr):
logger.debug("sys_set_tid_address(%016x) -> 0", tidptr)
return 1000 #tha pid
def sys_faccessat(self, dirfd, pathname, mode, flags):
filename = self.current.read_string(pathname)
logger.debug("sys_faccessat(%016x, %s, %x, %x) -> 0", dirfd, filename, mode, flags)
return -1
def sys_set_robust_list(self, head, length):
logger.debug("sys_set_robust_list(%016x, %d) -> -1", head, length)
return -1
def sys_futex(self, uaddr, op, val, timeout, uaddr2, val3):
logger.debug("sys_futex(...) -> -1")
return -1
def sys_getrlimit(self, resource, rlim):
logger.debug("sys_getrlimit(%x, %x) -> -1", resource, rlim)
return -1
def sys_fadvise64(self, fd, offset, length, advice):
logger.debug("sys_fadvise64(%x, %x, %x, %x) -> 0", fd, offset, length, advice)
return 0
def sys_gettimeofday(self, tv, tz):
logger.debug("sys_gettimeofday(%x, %x) -> 0", tv, tz)
return 0
#Distpatchers...
def syscall(self):
'''
Syscall dispatcher.
'''
index = self._syscall_abi.syscall_number()
try:
table = getattr(linux_syscalls, self.current.machine)
name = table.get(index, None)
implementation = getattr(self, name)
except (AttributeError, KeyError):
raise SyscallNotImplemented(self.current.address_bit_size, index, name)
return self._syscall_abi.invoke(implementation)
def sys_clock_gettime(self, clock_id, timespec):
logger.info("sys_clock_time not really implemented")
return 0
def sys_time(self, tloc):
import time
t = time.time()
if tloc != 0 :
self.current.write_int(tloc, int(t), self.current.address_bit_size)
return int(t)
def sched(self):
''' Yield CPU.
This will choose another process from the running list and change
current running process. May give the same cpu if only one running
process.
'''
if len(self.procs) > 1:
logger.debug("SCHED:")
logger.debug("\tProcess: %r", self.procs)
logger.debug("\tRunning: %r", self.running)
logger.debug("\tRWait: %r", self.rwait)
logger.debug("\tTWait: %r", self.twait)
logger.debug("\tTimers: %r", self.timers)
logger.debug("\tCurrent clock: %d", self.clocks)
logger.debug("\tCurrent cpu: %d", self._current)
if len(self.running) == 0:
logger.debug("None running checking if there is some process waiting for a timeout")
if all([x is None for x in self.timers]):
raise Deadlock()
self.clocks = min(filter(lambda x: x is not None, self.timers)) + 1
self.check_timers()
assert len(self.running) != 0, "DEADLOCK!"
self._current = self.running[0]
return
next_index = (self.running.index(self._current) + 1) % len(self.running)
next_running_idx = self.running[next_index]
if len(self.procs) > 1:
logger.debug("\tTransfer control from process %d to %d",
self._current,
next_running_idx)
self._current = next_running_idx
def wait(self, readfds, writefds, timeout):
''' Wait for file descriptors or timeout.
Adds the current process in the correspondent waiting list and
yield the cpu to another running process.
'''
logger.debug("WAIT:")
logger.debug("\tProcess %d is going to wait for [ %r %r %r ]",
self._current,
readfds,
writefds,
timeout)
logger.debug("\tProcess: %r", self.procs)
logger.debug("\tRunning: %r", self.running)
logger.debug("\tRWait: %r", self.rwait)
logger.debug("\tTWait: %r", self.twait)
logger.debug("\tTimers: %r", self.timers)
for fd in readfds:
self.rwait[fd].add(self._current)
for fd in writefds:
self.twait[fd].add(self._current)
if timeout is not None:
self.timers[self._current] = self.clocks + timeout
procid = self._current
#self.sched()
next_index = (self.running.index(procid) + 1) % len(self.running)
self._current = self.running[next_index]
logger.debug("\tTransfer control from process %d to %d", procid, self._current)
logger.debug( "\tREMOVING %r from %r. Current: %r", procid, self.running, self._current)
self.running.remove(procid)
if self._current not in self.running:
logger.debug("\tCurrent not running. Checking for timers...")
self._current = None
self.check_timers()
def awake(self, procid):
''' Remove procid from waitlists and reestablish it in the running list '''
logger.debug("Remove procid:%d from waitlists and reestablish it in the running list", procid)
for wait_list in self.rwait:
if procid in wait_list: wait_list.remove(procid)
for wait_list in self.twait:
if procid in wait_list: wait_list.remove(procid)
self.timers[procid] = None
self.running.append(procid)
if self._current is None:
self._current = procid
def connections(self, fd):
""" File descriptors are connected to each other like pipes. Except
for 0,1,2. If you write to FD(N) then that comes out from FD(N+1)
and vice-versa
"""
if fd in [0, 1, 2]:
return None
if fd % 2:
return fd + 1
else:
return fd - 1
def signal_receive(self, fd):
''' Awake one process waiting to receive data on fd '''
connections = self.connections
if connections(fd) and self.twait[connections(fd)]:
procid = random.sample(self.twait[connections(fd)], 1)[0]
self.awake(procid)
def signal_transmit(self, fd):
''' Awake one process waiting to transmit data on fd '''
connection = self.connections(fd)
if connection is None or connection >= len(self.rwait):
return
procs = self.rwait[connection]
if procs:
procid = random.sample(procs, 1)[0]
self.awake(procid)
def check_timers(self):
''' Awake process if timer has expired '''
if self._current is None:
#Advance the clocks. Go to future!!
advance = min([self.clocks] + filter(lambda x: x is not None, self.timers)) + 1
logger.debug("Advancing the clock from %d to %d", self.clocks, advance)
self.clocks = advance
for procid in range(len(self.timers)):
if self.timers[procid] is not None:
if self.clocks > self.timers[procid]:
self.procs[procid].PC += self.procs[procid].instruction.size
self.awake(procid)
def execute(self):
"""
Execute one cpu instruction in the current thread (only one supported).
:rtype: bool
:return: C{True}
:todo: This is where we could implement a simple schedule.
"""
try:
self.current.execute()
self.clocks += 1
if self.clocks % 10000 == 0:
self.check_timers()
self.sched()
except (Interruption, Syscall):
try:
self.syscall()
except RestartSyscall:
pass
return True
#64bit syscalls
def sys_newfstat(self, fd, buf):
'''
Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(width, ts):
'Note: this is a platform-dependent timespec (8 or 16 bytes)'
return add(width, int(ts)) + add(width, int(ts % 1 * 1e9))
# From linux/arch/x86/include/uapi/asm/stat.h
# Numerous fields are native width-wide
nw = self.current.address_bit_size / 8
bufstat = add(nw, stat.st_dev) # long st_dev
bufstat += add(nw, stat.st_ino) # long st_ino
bufstat += add(nw, stat.st_nlink) # long st_nlink
bufstat += add(4, stat.st_mode) # 32 mode
bufstat += add(4, stat.st_uid) # 32 uid
bufstat += add(4, stat.st_gid) # 32 gid
bufstat += add(4, 0) # 32 _pad
bufstat += add(nw, stat.st_rdev) # long st_rdev
bufstat += add(nw, stat.st_size) # long st_size
bufstat += add(nw, stat.st_blksize) # long st_blksize
bufstat += add(nw, stat.st_blocks) # long st_blocks
bufstat += to_timespec(nw, stat.st_atime) # long st_atime, nsec;
bufstat += to_timespec(nw, stat.st_mtime) # long st_mtime, nsec;
bufstat += to_timespec(nw, stat.st_ctime) # long st_ctime, nsec;
logger.debug("sys_newfstat(%d, ...) -> %d bytes", fd, len(bufstat))
self.current.write_bytes(buf, bufstat)
return 0
def sys_fstat(self, fd, buf):
'''
Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(ts):
return struct.pack('<LL', int(ts), int(ts % 1 * 1e9))
logger.debug("sys_fstat %d", fd)
bufstat = add(8, stat.st_dev) # dev_t st_dev;
bufstat += add(4, 0) # __pad1
bufstat += add(4, stat.st_ino) # unsigned long st_ino;
bufstat += add(4, stat.st_mode) # unsigned short st_mode;
bufstat += add(4, stat.st_nlink) # unsigned short st_nlink;
bufstat += add(4, stat.st_uid) # unsigned short st_uid;
bufstat += add(4, stat.st_gid) # unsigned short st_gid;
bufstat += add(4, stat.st_rdev) # unsigned long st_rdev;
bufstat += add(4, stat.st_size) # unsigned long st_size;
bufstat += add(4, stat.st_blksize)# unsigned long st_blksize;
bufstat += add(4, stat.st_blocks) # unsigned long st_blocks;
bufstat += to_timespec(stat.st_atime) # unsigned long st_atime;
bufstat += to_timespec(stat.st_mtime) # unsigned long st_mtime;
bufstat += to_timespec(stat.st_ctime) # unsigned long st_ctime;
bufstat += add(4, 0) # unsigned long __unused4;
bufstat += add(4, 0) # unsigned long __unused5;
self.current.write_bytes(buf, bufstat)
return 0
def sys_fstat64(self, fd, buf):
'''
Determines information about a file based on its file descriptor (for Linux 64 bits).
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
:todo: Fix device number.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(ts):
return struct.pack('<LL', int(ts), int(ts % 1 * 1e9))
logger.debug("sys_fstat64 %d", fd)
bufstat = add(8, stat.st_dev) # unsigned long long st_dev;
bufstat += add(4, 0) # unsigned char __pad0[4];
bufstat += add(4, stat.st_ino) # unsigned long __st_ino;
bufstat += add(4, stat.st_mode) # unsigned int st_mode;
bufstat += add(4, stat.st_nlink) # unsigned int st_nlink;
bufstat += add(4, stat.st_uid) # unsigned long st_uid;
bufstat += add(4, stat.st_gid) # unsigned long st_gid;
bufstat += add(8, stat.st_rdev) # unsigned long long st_rdev;
bufstat += add(4, 0) # unsigned char __pad3[4];
bufstat += add(4, 0) # unsigned char __pad3[4];
bufstat += add(8, stat.st_size) # long long st_size;
bufstat += add(8, stat.st_blksize) # unsigned long st_blksize;
bufstat += add(8, stat.st_blocks) # unsigned long long st_blocks;
bufstat += to_timespec(stat.st_atime) # unsigned long st_atime;
bufstat += to_timespec(stat.st_mtime) # unsigned long st_mtime;
bufstat += to_timespec(stat.st_ctime) # unsigned long st_ctime;
bufstat += add(8, stat.st_ino) # unsigned long long st_ino;
self.current.write_bytes(buf, bufstat)
return 0
def sys_newstat(self, fd, buf):
'''
Wrapper for stat64()
'''
return self.sys_stat64(fd, buf)
def sys_stat64(self, path, buf):
'''
Determines information about a file based on its filename (for Linux 64 bits).
:rtype: int
:param path: the pathname of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
return self._stat(path, buf, True)
def sys_stat32(self, path, buf):
return self._stat(path, buf, False)
def _stat(self, path, buf, is64bit):
fd = self.sys_open(path, 0, 'r')
if is64bit:
ret = self.sys_fstat64(fd, buf)
else:
ret = self.sys_fstat(fd, buf)
self.sys_close(fd)
return ret
def _arch_specific_init(self):
assert self.arch in {'i386', 'amd64', 'armv7'}
if self.arch == 'i386':
self._uname_machine = 'i386'
elif self.arch == 'amd64':
self._uname_machine = 'x86_64'
elif self.arch == 'armv7':
self._uname_machine = 'armv71'
self._init_arm_kernel_helpers()
# Establish segment registers for x86 architectures
if self.arch in {'i386', 'amd64'}:
x86_defaults = {'CS': 0x23, 'SS': 0x2b, 'DS': 0x2b, 'ES': 0x2b}
for reg, val in x86_defaults.iteritems():
self.current.regfile.write(reg, val)
@staticmethod
def _interp_total_size(interp):
'''
Compute total load size of interpreter.
:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int
'''
load_segs = filter(lambda x: x.header.p_type == 'PT_LOAD', interp.iter_segments())
last = load_segs[-1]
return last.header.p_vaddr + last.header.p_memsz
############################################################################
# Symbolic versions follows
class SLinux(Linux):
"""
Builds a symbolic extension of a Linux OS
:param str programs: path to ELF binary
:param list argv: argv not including binary
:param list envp: environment variables
:param tuple[str] symbolic_files: files to consider symbolic
"""
def __init__(self, programs, argv=None, envp=None, symbolic_files=None):
argv = [] if argv is None else argv
envp = [] if envp is None else envp
symbolic_files = [] if symbolic_files is None else symbolic_files
self._constraints = ConstraintSet()
self.random = 0
self.symbolic_files = symbolic_files
super(SLinux, self).__init__(programs, argv, envp)
def _mk_proc(self, arch):
if arch in {'i386', 'armv7'}:
mem = SMemory32(self.constraints)
else:
mem = SMemory64(self.constraints)
return CpuFactory.get_cpu(mem, arch)
@property
def constraints(self):
return self._constraints
#marshaling/pickle
def __getstate__(self):
state = super(SLinux, self).__getstate__()
state['constraints'] = self.constraints
state['random'] = self.random
state['symbolic_files'] = self.symbolic_files
return state
def __setstate__(self, state):
self._constraints = state['constraints']
self.random = state['random']
self.symbolic_files = state['symbolic_files']
super(SLinux, self).__setstate__(state)
def _sys_open_get_file(self, filename, flags, mode):
if filename in self.symbolic_files:
logger.debug("%s file is considered symbolic", filename)
assert flags & 7 == os.O_RDWR or flags & 7 == os.O_RDONLY, (
"Symbolic files should be readable?")
f = SymbolicFile(self.constraints, filename, mode)
else:
f = super(SLinux, self)._sys_open_get_file(filename, flags, mode)
return f
#Dispatchers...
def sys_read(self, fd, buf, count):
if issymbolic(fd):
logger.debug("Ask to read from a symbolic file descriptor!!")
raise ConcretizeArgument(0)
if issymbolic(buf):
logger.debug("Ask to read to a symbolic buffer")
raise ConcretizeArgument(1)
if issymbolic(count):
logger.debug("Ask to read a symbolic number of bytes ")
raise ConcretizeArgument(2)
return super(SLinux, self).sys_read(fd, buf, count)
def sys_write(self, fd, buf, count):
if issymbolic(fd):
logger.debug("Ask to write to a symbolic file descriptor!!")
raise ConcretizeArgument(0)
if issymbolic(buf):
logger.debug("Ask to write to a symbolic buffer")
raise ConcretizeArgument(1)
if issymbolic(count):
logger.debug("Ask to write a symbolic number of bytes ")
raise ConcretizeArgument(2)
return super(SLinux, self).sys_write(fd, buf, count)
class DecreeEmu(object):
RANDOM = 0
@staticmethod
def cgc_initialize_secret_page(platform):
logger.info("Skipping: cgc_initialize_secret_page()")
return 0
@staticmethod
def cgc_random(platform, buf, count, rnd_bytes):
from . import cgcrandom
if issymbolic(buf):
logger.info("Ask to write random bytes to a symbolic buffer")
raise ConcretizeArgument(0)
if issymbolic(count):
logger.info("Ask to read a symbolic number of random bytes ")
raise ConcretizeArgument(1)
if issymbolic(rnd_bytes):
logger.info("Ask to return rnd size to a symbolic address ")
raise ConcretizeArgument(2)
data = []
for i in xrange(count):
value = cgcrandom.stream[DecreeEmu.RANDOM]
data.append(value)
DecreeEmu.random += 1
cpu = platform.current
cpu.write(buf, data)
if rnd_bytes:
cpu.store(rnd_bytes, len(data), 32)
logger.info("RANDOM(0x%08x, %d, 0x%08x) -> %d", buf, count, rnd_bytes, len(data))
return 0
| 35.816163 | 204 | 0.554752 | import errno
import fcntl
import logging
import os
import random
import struct
import ctypes
from elftools.elf.elffile import ELFFile
from ..utils.helpers import issymbolic
from ..core.cpu.abstractcpu import Interruption, Syscall, ConcretizeArgument
from ..core.cpu.cpufactory import CpuFactory
from ..core.memory import SMemory32, SMemory64, Memory32, Memory64
from ..core.smtlib import Operators, ConstraintSet
from ..platforms.platform import Platform
from ..core.cpu.arm import *
from ..core.executor import SyscallNotImplemented, ProcessExit
from . import linux_syscalls
logger = logging.getLogger("PLATFORM")
class RestartSyscall(Exception):
pass
class Deadlock(Exception):
pass
class BadFd(Exception):
pass
def perms_from_elf(elf_flags):
return [' ', ' x', ' w ', ' wx', 'r ', 'r x', 'rw ', 'rwx'][elf_flags&7]
def perms_from_protflags(prot_flags):
return [' ', 'r ', ' w ', 'rw ', ' x', 'r x', ' wx', 'rwx'][prot_flags&7]
class File(object):
def __init__(self, *args, **kwargs):
self.file = file(*args,**kwargs)
def __getstate__(self):
state = {}
state['name'] = self.name
state['mode'] = self.mode
state['pos'] = self.tell()
return state
def __setstate__(self, state):
name = state['name']
mode = state['mode']
pos = state['pos']
self.file = file(name, mode)
self.seek(pos)
@property
def name(self):
return self.file.name
@property
def mode(self):
return self.file.mode
def stat(self):
return os.fstat(self.fileno())
def ioctl(self, request, argp):
return fcntl.fcntl(self, request)
def tell(self, *args):
return self.file.tell(*args)
def seek(self, *args):
return self.file.seek(*args)
def write(self, buf):
for c in buf:
self.file.write(c)
def read(self, *args):
return self.file.read(*args)
def close(self, *args):
return self.file.close(*args)
def fileno(self, *args):
return self.file.fileno(*args)
def is_full(self):
return False
def sync(self):
'''
Flush buffered data. Currently not implemented.
'''
return
class SymbolicFile(File):
'''
Represents a symbolic file.
'''
def __init__(self, constraints, path="sfile", mode='rw', max_size=100,
wildcard='+'):
'''
Builds a symbolic file
:param constraints: the SMT constraints
:param str path: the pathname of the symbolic file
:param str mode: the access permissions of the symbolic file
:param max_size: Maximun amount of bytes of the symbolic file
:param str wildcard: Wildcard to be used in symbolic file
'''
super(SymbolicFile, self).__init__(path, mode)
data = self.file.read()
self._constraints = constraints
self.pos = 0
self.max_size = min(len(data), max_size)
size = len(data)
self.array = constraints.new_array(name=self.name, index_max=size)
symbols_cnt = 0
for i in range(size):
if data[i] != wildcard:
self.array[i] = data[i]
else:
symbols_cnt += 1
if symbols_cnt > max_size:
logger.warning(("Found more wilcards in the file than free ",
"symbolic values allowed (%d > %d)"),
symbols_cnt,
max_size)
else:
logger.debug("Found %d free symbolic values on file %s",
symbols_cnt,
self.name)
def __getstate__(self):
state = {}
state['array'] = self.array
state['pos'] = self.pos
state['max_size'] = self.max_size
return state
def __setstate__(self, state):
self.pos = state['pos']
self.max_size = state['max_size']
self.array = state['array']
@property
def constraints(self):
return self._constraints
def tell(self):
'''
Returns the read/write file offset
:rtype: int
:return: the read/write file offset.
'''
return self.pos
def seek(self, pos):
'''
Returns the read/write file offset
:rtype: int
:return: the read/write file offset.
'''
assert isinstance(pos, (int, long))
self.pos = pos
def read(self, count):
'''
Reads up to C{count} bytes from the file.
:rtype: list
:return: the list of symbolic bytes read
'''
if self.pos > self.max_size:
return []
else:
size = min(count, self.max_size - self.pos)
ret = [self.array[i] for i in xrange(self.pos, self.pos + size)]
self.pos += size
return ret
def write(self, data):
'''
Writes the symbolic bytes in C{data} onto the file.
'''
size = min(len(data), self.max_size - self.pos)
for i in xrange(self.pos, self.pos + size):
self.array[i] = data[i - self.pos]
class Socket(object):
def stat(self):
from collections import namedtuple
stat_result = namedtuple('stat_result', ['st_mode','st_ino','st_dev','st_nlink','st_uid','st_gid','st_size','st_atime','st_mtime','st_ctime', 'st_blksize','st_blocks','st_rdev'])
return stat_result(8592,11,9,1,1000,5,0,1378673920,1378673920,1378653796,0x400,0x8808,0)
@staticmethod
def pair():
a = Socket()
b = Socket()
a.connect(b)
return a, b
def __init__(self):
self.buffer = []
self.peer = None
def __repr__(self):
return "SOCKET(%x, %r, %x)" % (hash(self), self.buffer, hash(self.peer))
def is_connected(self):
return self.peer is not None
def is_empty(self):
return not self.buffer
def is_full(self):
return len(self.buffer) > 2 * 1024
def connect(self, peer):
assert not self.is_connected()
assert not peer.is_connected()
self.peer = peer
if peer.peer is None:
peer.peer = self
def read(self, size):
return self.receive(size)
def receive(self, size):
rx_bytes = min(size, len(self.buffer))
ret = []
for i in xrange(rx_bytes):
ret.append(self.buffer.pop())
return ret
def write(self, buf):
assert self.is_connected()
return self.peer._transmit(buf)
def _transmit(self, buf):
for c in buf:
self.buffer.insert(0, c)
return len(buf)
def sync(self):
raise BadFd("Invalid sync() operation on Socket")
def seek(self, *args):
raise BadFd("Invalid lseek() operation on Socket")
class Linux(Platform):
'''
A simple Linux Operating System Platform.
This class emulates the most common Linux system calls
'''
def __init__(self, program, argv=None, envp=None):
'''
Builds a Linux OS platform
:param string program: The path to ELF binary
:param list argv: The argv array; not including binary.
:param list envp: The ENV variables.
:ivar files: List of active file descriptors
:type files: list[Socket] or list[File]
'''
super(Linux, self).__init__(program)
self.program = program
self.clocks = 0
self.files = []
self.syscall_trace = []
if program != None:
self.elf = ELFFile(file(program))
self.arch = {'x86': 'i386', 'x64': 'amd64', 'ARM': 'armv7'}[self.elf.get_machine_arch()]
self._init_cpu(self.arch)
self._init_std_fds()
self._execve(program, argv, envp)
@classmethod
def empty_platform(cls, arch):
'''
Create a platform without an ELF loaded.
:param str arch: The architecture of the new platform
:rtype: Linux
'''
platform = cls(None)
platform._init_cpu(arch)
platform._init_std_fds()
return platform
def _init_std_fds(self):
logger.debug("Opening file descriptors (0,1,2) (STDIN, STDOUT, STDERR)")
self.input = Socket()
self.output = Socket()
self.stderr = Socket()
stdin = Socket()
stdout = Socket()
stderr = Socket()
stdin.peer = self.output
stdout.peer = self.output
stderr.peer = self.stderr
self.input.peer = stdin
assert self._open(stdin) == 0
assert self._open(stdout) == 1
assert self._open(stderr) == 2
def _init_cpu(self, arch):
cpu = self._mk_proc(arch)
self.procs = [cpu]
self._current = 0
self._function_abi = CpuFactory.get_function_abi(cpu, 'linux', arch)
self._syscall_abi = CpuFactory.get_syscall_abi(cpu, 'linux', arch)
def _execve(self, program, argv, envp):
'''
Load `program` and establish program state, such as stack and arguments.
:param program str: The ELF binary to load
:param argv list: argv array
:param envp list: envp array
'''
argv = [] if argv is None else argv
envp = [] if envp is None else envp
logger.debug("Loading {} as a {} elf".format(program,self.arch))
self.load(program)
self._arch_specific_init()
self._stack_top = self.current.STACK
self.setup_stack([program]+argv, envp)
nprocs = len(self.procs)
nfiles = len(self.files)
assert nprocs > 0
self.running = range(nprocs)
self.timers = [ None ] * nprocs
self.rwait = [set() for _ in xrange(nfiles)]
self.twait = [set() for _ in xrange(nfiles)]
def _mk_proc(self, arch):
if arch in {'i386', 'armv7'}:
mem = Memory32()
else:
mem = Memory64()
return CpuFactory.get_cpu(mem, arch)
@property
def current(self):
return self.procs[self._current]
def __getstate__(self):
state = {}
state['clocks'] = self.clocks
state['input'] = self.input.buffer
state['output'] = self.output.buffer
state_files = []
for fd in self.files:
if isinstance(fd, Socket):
state_files.append(('Socket', fd.buffer))
else:
state_files.append(('File', fd))
state['files'] = state_files
state['procs'] = self.procs
state['current'] = self._current
state['running'] = self.running
state['rwait'] = self.rwait
state['twait'] = self.twait
state['timers'] = self.timers
state['syscall_trace'] = self.syscall_trace
state['base'] = self.base
state['elf_bss'] = self.elf_bss
state['end_code'] = self.end_code
state['end_data'] = self.end_data
state['elf_brk'] = self.elf_brk
state['auxv'] = self.auxv
state['program'] = self.program
state['functionabi'] = self._function_abi
state['syscallabi'] = self._syscall_abi
state['uname_machine'] = self._uname_machine
if hasattr(self, '_arm_tls_memory'):
state['_arm_tls_memory'] = self._arm_tls_memory
return state
def __setstate__(self, state):
"""
:todo: some asserts
:todo: fix deps? (last line)
"""
self.input = Socket()
self.input.buffer = state['input']
self.output = Socket()
self.output.buffer = state['output']
self.files = []
for ty, buf in state['files']:
if ty == 'Socket':
f = Socket()
f.buffer = buf
self.files.append(f)
else:
self.files.append(buf)
self.files[0].peer = self.output
self.files[1].peer = self.output
self.files[2].peer = self.output
self.input.peer = self.files[0]
self.procs = state['procs']
self._current = state['current']
self.running = state['running']
self.rwait = state['rwait']
self.twait = state['twait']
self.timers = state['timers']
self.clocks = state['clocks']
self.syscall_trace = state['syscall_trace']
self.base = state['base']
self.elf_bss = state['elf_bss']
self.end_code = state['end_code']
self.end_data = state['end_data']
self.elf_brk = state['elf_brk']
self.auxv = state['auxv']
self.program = state['program']
self._function_abi = state['functionabi']
self._syscall_abi = state['syscallabi']
self._uname_machine = state['uname_machine']
if '_arm_tls_memory' in state:
self._arm_tls_memory = state['_arm_tls_memory']
def _init_arm_kernel_helpers(self):
'''
ARM kernel helpers
https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
'''
page_data = bytearray('\xf1\xde\xfd\xe7' * 1024)
preamble = (
'ff0300ea' +
'650400ea' +
'f0ff9fe5' +
'430400ea' +
'220400ea' +
'810400ea' +
'000400ea' +
'870400ea'
).decode('hex')
__kuser_cmpxchg64 = (
'30002de9' +
'08c09de5' + '30009ce8' +
'010055e1' +
'00005401' +
'0100a013' + '0000a003' + '0c008c08' +
'3000bde8' +
'1eff2fe1'
).decode('hex')
__kuser_dmb = (
'5bf07ff5' +
'1eff2fe1'
).decode('hex')
__kuser_cmpxchg = (
'003092e5' +
'000053e1' +
'0000a003' + '00108205' +
'0100a013' + '1eff2fe1'
).decode('hex')
self._arm_tls_memory = self.current.memory.mmap(None, 4, 'rw ')
__kuser_get_tls = (
'04009FE5' + '010090e8' +
'1eff2fe1'
).decode('hex') + struct.pack('<I', self._arm_tls_memory)
tls_area = '\x00'*12
version = struct.pack('<I', 5)
def update(address, code):
page_data[address:address+len(code)] = code
update(0x000, preamble)
update(0xf60, __kuser_cmpxchg64)
update(0xfa0, __kuser_dmb)
update(0xfc0, __kuser_cmpxchg)
update(0xfe0, __kuser_get_tls)
update(0xff0, tls_area)
update(0xffc, version)
self.current.memory.mmap(0xffff0000, len(page_data), 'r x', page_data)
def load_vdso(self, bits):
: 0x7fff0000, 64: 0x7fff00007fff0000}[bits]
vdso_size = len(file('vdso%2d.dump'%bits).read())
vdso_addr = self.memory.mmapFile(self.memory._floor(vdso_top - vdso_size),
vdso_size,
'r x',
{32: 'vdso32.dump', 64: 'vdso64.dump'}[bits],
0)
return vdso_addr
def setup_stack(self, argv, envp):
'''
:param Cpu cpu: The cpu instance
:param argv: list of parameters for the program to execute.
:param envp: list of environment variables for the program to execute.
http://www.phrack.org/issues.html?issue=58&id=5#article
position content size (bytes) + comment
----------------------------------------------------------------------
stack pointer -> [ argc = number of args ] 4
[ argv[0] (pointer) ] 4 (program name)
[ argv[1] (pointer) ] 4
[ argv[..] (pointer) ] 4 * x
[ argv[n - 1] (pointer) ] 4
[ argv[n] (pointer) ] 4 (= NULL)
[ envp[0] (pointer) ] 4
[ envp[1] (pointer) ] 4
[ envp[..] (pointer) ] 4
[ envp[term] (pointer) ] 4 (= NULL)
[ auxv[0] (Elf32_auxv_t) ] 8
[ auxv[1] (Elf32_auxv_t) ] 8
[ auxv[..] (Elf32_auxv_t) ] 8
[ auxv[term] (Elf32_auxv_t) ] 8 (= AT_NULL vector)
[ padding ] 0 - 16
[ argument ASCIIZ strings ] >= 0
[ environment ASCIIZ str. ] >= 0
(0xbffffffc) [ end marker ] 4 (= NULL)
(0xc0000000) < top of stack > 0 (virtual)
----------------------------------------------------------------------
'''
cpu = self.current
# stack from the original top
cpu.STACK = self._stack_top
auxv = self.auxv
logger.debug("Setting argv, envp and auxv.")
logger.debug("\tArguments: %s", repr(argv))
if envp:
logger.debug("\tEnvironment:")
for e in envp:
logger.debug("\t\t%s", repr(e))
logger.debug("\tAuxv:")
for name, val in auxv.items():
logger.debug("\t\t%s: %s", name, hex(val))
#We save the argument and environment pointers
argvlst = []
envplst = []
#end envp marker empty string
for evar in envp:
cpu.push_bytes('\x00')
envplst.append(cpu.push_bytes(evar))
for arg in argv:
cpu.push_bytes('\x00')
argvlst.append(cpu.push_bytes(arg))
#Put all auxv strings into the string stack area.
#And replace the value be its pointer
for name, value in auxv.items():
if hasattr(value, '__len__'):
cpu.push_bytes(value)
auxv[name] = cpu.STACK
#The "secure execution" mode of secure_getenv() is controlled by the
#AT_SECURE flag contained in the auxiliary vector passed from the
#kernel to user space.
auxvnames = {
'AT_IGNORE': 1, # Entry should be ignored
'AT_EXECFD': 2, # File descriptor of program
'AT_PHDR': 3, # Program headers for program
'AT_PHENT':4, # Size of program header entry
'AT_PHNUM':5, # Number of program headers
'AT_PAGESZ': 6, # System page size
'AT_BASE': 7, # Base address of interpreter
'AT_FLAGS':8, # Flags
'AT_ENTRY':9, # Entry point of program
'AT_NOTELF': 10, # Program is not ELF
'AT_UID':11, # Real uid
'AT_EUID': 12, # Effective uid
'AT_GID':13, # Real gid
'AT_EGID': 14, # Effective gid
'AT_CLKTCK': 17, # Frequency of times()
'AT_PLATFORM': 15, # String identifying platform.
'AT_HWCAP':16, # Machine-dependent hints about processor capabilities.
'AT_FPUCW':18, # Used FPU control word.
'AT_SECURE': 23, # Boolean, was exec setuid-like?
'AT_BASE_PLATFORM': 24, # String identifying real platforms.
'AT_RANDOM': 25, # Address of 16 random bytes.
'AT_EXECFN': 31, # Filename of executable.
'AT_SYSINFO':32, #Pointer to the global system page used for system calls and other nice things.
'AT_SYSINFO_EHDR': 33, #Pointer to the global system page used for system calls and other nice things.
}
#AT_NULL
cpu.push_int(0)
cpu.push_int(0)
for name, val in auxv.items():
cpu.push_int(val)
cpu.push_int(auxvnames[name])
# NULL ENVP
cpu.push_int(0)
for var in reversed(envplst): # ENVP n
cpu.push_int(var)
envp = cpu.STACK
# NULL ARGV
cpu.push_int(0)
for arg in reversed(argvlst): # Argv n
cpu.push_int(arg)
argv = cpu.STACK
#ARGC
cpu.push_int(len(argvlst))
def load(self, filename):
'''
Loads and an ELF program in memory and prepares the initial CPU state.
Creates the stack and loads the environment variables and the arguments in it.
:param filename: pathname of the file to be executed. (used for auxv)
:raises error:
- 'Not matching cpu': if the program is compiled for a different architecture
- 'Not matching memory': if the program is compiled for a different address size
:todo: define va_randomize and read_implies_exec personality
'''
#load elf See binfmt_elf.c
#read the ELF object file
cpu = self.current
elf = self.elf
arch = self.arch
addressbitsize = {'x86':32, 'x64':64, 'ARM': 32}[elf.get_machine_arch()]
logger.debug("Loading %s as a %s elf"%(filename, arch))
assert elf.header.e_type in ['ET_DYN', 'ET_EXEC', 'ET_CORE']
#Get interpreter elf
interpreter = None
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_INTERP':
continue
interpreter_filename = elf_segment.data()[:-1]
logger.info('Interpreter filename: %s', interpreter_filename)
interpreter = ELFFile(file(interpreter_filename))
break
if not interpreter is None:
assert interpreter.get_machine_arch() == elf.get_machine_arch()
assert interpreter.header.e_type in ['ET_DYN', 'ET_EXEC']
#Stack Executability
executable_stack = False
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_GNU_STACK':
continue
if elf_segment.header.p_flags & 0x01:
executable_stack = True
else:
executable_stack = False
break
base = 0
elf_bss = 0
end_code = 0
end_data = 0
elf_brk = 0
load_addr = 0
for elf_segment in elf.iter_segments():
if elf_segment.header.p_type != 'PT_LOAD':
continue
align = 0x1000 #elf_segment.header.p_align
ELF_PAGEOFFSET = elf_segment.header.p_vaddr & (align-1)
flags = elf_segment.header.p_flags
memsz = elf_segment.header.p_memsz + ELF_PAGEOFFSET
offset = elf_segment.header.p_offset - ELF_PAGEOFFSET
filesz = elf_segment.header.p_filesz + ELF_PAGEOFFSET
vaddr = elf_segment.header.p_vaddr - ELF_PAGEOFFSET
memsz = cpu.memory._ceil(memsz)
if base == 0 and elf.header.e_type == 'ET_DYN':
assert vaddr == 0
if addressbitsize == 32:
base = 0x56555000
else:
base = 0x555555554000
perms = perms_from_elf(flags)
hint = base+vaddr
if hint == 0:
hint = None
logger.debug("Loading elf offset: %08x addr:%08x %08x %s" %(offset, base+vaddr, base+vaddr+memsz, perms))
base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset) - vaddr
if load_addr == 0 :
load_addr = base + vaddr
k = base + vaddr + filesz;
if k > elf_bss :
elf_bss = k;
if (flags & 4) and end_code < k: #PF_X
end_code = k
if end_data < k:
end_data = k
k = base + vaddr + memsz
if k > elf_brk:
elf_brk = k
elf_entry = elf.header.e_entry
if elf.header.e_type == 'ET_DYN':
elf_entry += load_addr
entry = elf_entry
real_elf_brk = elf_brk
# We need to explicitly zero any fractional pages
# after the data section (i.e. bss). This would
# contain the junk from the file that should not
# be in memory
#TODO:
#cpu.write_bytes(elf_bss, '\x00'*((elf_bss | (align-1))-elf_bss))
logger.debug("Zeroing main elf fractional pages. From %x to %x.", elf_bss, elf_brk)
logger.debug("Main elf bss:%x"%elf_bss)
logger.debug("Main elf brk %x:"%elf_brk)
#FIXME Need a way to inspect maps and perms so
#we can rollback all to the initial state after zeroing
#if elf_brk-elf_bss > 0:
# saved_perms = cpu.mem.perms(elf_bss)
# cpu.memory.mprotect(cpu.mem._ceil(elf_bss), elf_brk-elf_bss, 'rw ')
# logger.debug("Zeroing main elf fractional pages (%d bytes)", elf_brk-elf_bss)
# cpu.write_bytes(elf_bss, ['\x00'] * (elf_brk-elf_bss))
# cpu.memory.mprotect(cpu.memory._ceil(elf_bss), elf_brk-elf_bss, saved_perms)
if cpu.memory.access_ok(slice(elf_bss, elf_brk), 'w'):
cpu.memory[elf_bss:elf_brk] = '\x00'*(elf_brk-elf_bss)
else:
logger.warning("Failing to zerify the trailing: elf_brk-elf_bss")
stack_size = 0x21000
if addressbitsize == 32:
stack_top = 0xc0000000
else:
stack_top = 0x800000000000
stack_base = stack_top - stack_size
stack = cpu.memory.mmap(stack_base, stack_size, 'rwx', name='stack') + stack_size
assert stack_top == stack
reserved = cpu.memory.mmap(base+vaddr+memsz,0x1000000, ' ')
interpreter_base = 0
if interpreter is not None:
base = 0
elf_bss = 0
end_code = 0
end_data = 0
elf_brk = 0
entry = interpreter.header.e_entry
for elf_segment in interpreter.iter_segments():
if elf_segment.header.p_type != 'PT_LOAD':
continue
align = 0x1000#elf_segment.header.p_align
vaddr = elf_segment.header.p_vaddr
filesz = elf_segment.header.p_filesz
flags = elf_segment.header.p_flags
offset = elf_segment.header.p_offset
memsz = elf_segment.header.p_memsz
ELF_PAGEOFFSET = (vaddr & (align-1))
memsz = memsz + ELF_PAGEOFFSET
offset = offset - ELF_PAGEOFFSET
filesz = filesz + ELF_PAGEOFFSET
vaddr = vaddr - ELF_PAGEOFFSET
memsz = cpu.memory._ceil(memsz)
if base == 0 and interpreter.header.e_type == 'ET_DYN':
assert vaddr == 0
total_size = self._interp_total_size(interpreter)
base = stack_base - total_size
if base == 0:
assert vaddr == 0
perms = perms_from_elf(flags)
hint = base+vaddr
if hint == 0:
hint = None
base = cpu.memory.mmapFile(hint, memsz, perms, elf_segment.stream.name, offset)
base -= vaddr
logger.debug("Loading interpreter offset: %08x addr:%08x %08x %s%s%s" %(offset, base+vaddr, base+vaddr+memsz, (flags&1 and 'r' or ' '), (flags&2 and 'w' or ' '), (flags&4 and 'x' or ' ')))
k = base + vaddr + filesz;
if k > elf_bss:
elf_bss = k
if (flags & 4) and end_code < k: #PF_X
end_code = k
if end_data < k:
end_data = k
k = base + vaddr+ memsz
if k > elf_brk:
elf_brk = k
if interpreter.header.e_type == 'ET_DYN':
entry += base
interpreter_base = base
logger.debug("Zeroing interpreter elf fractional pages. From %x to %x.", elf_bss, elf_brk)
logger.debug("Interpreter bss:%x", elf_bss)
logger.debug("Interpreter brk %x:", elf_brk)
cpu.memory.mprotect(cpu.memory._floor(elf_bss), elf_brk-elf_bss, 'rw ')
try:
cpu.memory[elf_bss:elf_brk] = '\x00'*(elf_brk-elf_bss)
except Exception, e:
logger.debug("Exception zeroing Interpreter fractional pages: %s"%str(e))
#TODO #FIXME mprotect as it was before zeroing?
#free reserved brk space
cpu.memory.munmap(reserved, 0x1000000)
#load vdso
#vdso_addr = load_vdso(addressbitsize)
cpu.STACK = stack
cpu.PC = entry
logger.debug("Entry point: %016x", entry)
logger.debug("Stack start: %016x", stack)
logger.debug("Brk: %016x", real_elf_brk)
logger.debug("Mappings:")
for m in str(cpu.memory).split('\n'):
logger.debug(" %s", m)
self.base = base
self.elf_bss = elf_bss
self.end_code = end_code
self.end_data = end_data
self.elf_brk = real_elf_brk
at_random = cpu.push_bytes('A'*16)
at_execfn = cpu.push_bytes(filename+'\x00')
self.auxv = {
'AT_PHDR' : load_addr+elf.header.e_phoff, # Program headers for program
'AT_PHENT' : elf.header.e_phentsize, # Size of program header entry
'AT_PHNUM' : elf.header.e_phnum, # Number of program headers
'AT_PAGESZ' : cpu.memory.page_size, # System page size
'AT_BASE' : interpreter_base, # Base address of interpreter
'AT_FLAGS' : elf.header.e_flags, # Flags
'AT_ENTRY' : elf_entry, # Entry point of program
'AT_UID' : 1000, # Real uid
'AT_EUID' : 1000, # Effective uid
'AT_GID' : 1000, # Real gid
'AT_EGID' : 1000, # Effective gid
'AT_CLKTCK' : 100, # Frequency of times()
'AT_HWCAP' : 0, # Machine-dependent hints about processor capabilities.
'AT_RANDOM' : at_random, # Address of 16 random bytes.
'AT_EXECFN' : at_execfn, # Filename of executable.
}
def _open(self, f):
'''
Adds a file descriptor to the current file descriptor list
:rtype: int
:param f: the file descriptor to add.
:return: the index of the file descriptor in the file descr. list
'''
if None in self.files:
fd = self.files.index(None)
self.files[fd] = f
else:
fd = len(self.files)
self.files.append(f)
return fd
def _close(self, fd):
'''
Removes a file descriptor from the file descriptor list
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.
'''
self.files[fd] = None
def _dup(self, fd):
'''
Duplicates a file descriptor
:rtype: int
:param fd: the file descriptor to duplicate.
:return: C{0} on success.
'''
return self._open(self.files[fd])
def _get_fd(self, fd):
if fd < 0 or fd >= len(self.files) or self.files[fd] is None:
raise BadFd()
else:
return self.files[fd]
def sys_umask(self, mask):
'''
umask - Set file creation mode mask
:param int mask: New mask
'''
logger.debug("umask(%o)", mask)
return os.umask(mask)
def sys_chdir(self, path):
'''
chdir - Change current working directory
:param int path: Pointer to path
'''
path_str = self.current.read_string(path)
logger.debug("chdir(%s)", path_str)
try:
os.chdir(path_str)
return 0
except OSError as e:
return e.errno
def sys_lseek(self, fd, offset, whence):
'''
lseek - reposition read/write file offset
The lseek() function repositions the file offset of the open file description associated
with the file descriptor fd to the argument offset according to the directive whence
:param self: current CPU.
:param fd: a valid file descriptor
:param offset: the offset in bytes
:param whence: SEEK_SET: The file offset is set to offset bytes.
SEEK_CUR: The file offset is set to its current location plus offset bytes.
SEEK_END: The file offset is set to the size of the file plus offset bytes.
:return: 0 (Success), or EBADF (fd is not a valid file descriptor or is not open)
'''
if self.current.address_bit_size == 32:
signed_offset = ctypes.c_int32(offset).value
else:
signed_offset = ctypes.c_int64(offset).value
try:
self._get_fd(fd).seek(signed_offset, whence)
except BadFd:
logger.info(("LSEEK: Not valid file descriptor on lseek."
"Fd not seekable. Returning EBADF"))
return -errno.EBADF
logger.debug("LSEEK(%d, 0x%08x (%d), %d)", fd, offset, signed_offset, whence)
return 0
def sys_read(self, fd, buf, count):
data = ''
if count != 0:
# TODO check count bytes from buf
if not buf in self.current.memory: # or not self.current.memory.isValid(buf+count):
logger.info("READ: buf points to invalid address. Returning EFAULT")
return -errno.EFAULT
try:
# Read the data and put in tin memory
data = self._get_fd(fd).read(count)
except BadFd:
logger.info(("READ: Not valid file descriptor on read."
" Returning EBADF"))
return -errno.EBADF
self.syscall_trace.append(("_read", fd, data))
self.current.write_bytes(buf, data)
logger.debug("READ(%d, 0x%08x, %d, 0x%08x) -> <%s> (size:%d)",
fd,
buf,
count,
len(data),
repr(data)[:min(count,10)],
len(data))
return len(data)
def sys_write(self, fd, buf, count):
''' write - send bytes through a file descriptor
The write system call writes up to count bytes from the buffer pointed
to by buf to the file descriptor fd. If count is zero, write returns 0
and optionally sets *tx_bytes to zero.
:param fd a valid file descriptor
:param buf a memory buffer
:param count number of bytes to send
:return: 0 Success
EBADF fd is not a valid file descriptor or is not open.
EFAULT buf or tx_bytes points to an invalid address.
'''
data = []
cpu = self.current
if count != 0:
try:
write_fd = self._get_fd(fd)
except BadFd:
logger.error("WRITE: Not valid file descriptor. Returning EBADFD %d", fd)
return -errno.EBADF
# TODO check count bytes from buf
if buf not in cpu.memory or buf + count not in cpu.memory:
logger.debug("WRITE: buf points to invalid address. Returning EFAULT")
return -errno.EFAULT
if fd > 2 and write_fd.is_full():
cpu.PC -= cpu.instruction.size
self.wait([], [fd], None)
raise RestartSyscall()
data = cpu.read_bytes(buf, count)
write_fd.write(data)
for line in ''.join([str(x) for x in data]).split('\n'):
logger.debug("WRITE(%d, 0x%08x, %d) -> <%.48r>",
fd,
buf,
count,
line)
self.syscall_trace.append(("_write", fd, data))
self.signal_transmit(fd)
return len(data)
def sys_access(self, buf, mode):
'''
Checks real user's permissions for a file
:rtype: int
:param buf: a buffer containing the pathname to the file to check its permissions.
:param mode: the access permissions to check.
:return:
- C{0} if the calling process can access the file in the desired mode.
- C{-1} if the calling process can not access the file in the desired mode.
'''
filename = ""
for i in xrange(0, 255):
c = Operators.CHR(self.current.read_int(buf + i, 8))
if c == '\x00':
break
filename += c
logger.debug("access(%s, %x) -> %r",
filename,
mode,
os.access(filename, mode))
if os.access(filename, mode):
return 0
else:
return -1
def sys_newuname(self, old_utsname):
'''
Writes system information in the variable C{old_utsname}.
:rtype: int
:param old_utsname: the buffer to write the system info.
:return: C{0} on success
'''
from datetime import datetime
def pad(s):
return s +'\x00'*(65-len(s))
now = datetime.now().strftime("%a %b %d %H:%M:%S ART %Y")
info = (('sysname', 'Linux'),
('nodename', 'ubuntu'),
('release', '4.4.0-77-generic'),
('version', '#98 SMP ' + now),
('machine', self._uname_machine),
('domainname', ''))
uname_buf = ''.join(pad(pair[1]) for pair in info)
self.current.write_bytes(old_utsname, uname_buf)
logger.debug("sys_newuname(...) -> %s", uname_buf)
return 0
def sys_brk(self, brk):
'''
Changes data segment size (moves the C{elf_brk} to the new address)
:rtype: int
:param brk: the new address for C{elf_brk}.
:return: the value of the new C{elf_brk}.
:raises error:
- "Error in brk!" if there is any error allocating the memory
'''
if brk != 0:
assert brk > self.elf_brk
mem = self.current.memory
size = brk-self.elf_brk
perms = mem.perms(self.elf_brk-1)
if brk > mem._ceil(self.elf_brk):
addr = mem.mmap(mem._ceil(self.elf_brk), size, perms)
assert mem._ceil(self.elf_brk) == addr, "Error in brk!"
self.elf_brk += size
logger.debug("sys_brk(0x%08x) -> 0x%08x", brk, self.elf_brk)
return self.elf_brk
def sys_arch_prctl(self, code, addr):
'''
Sets architecture-specific thread state
:rtype: int
:param code: must be C{ARCH_SET_FS}.
:param addr: the base address of the FS segment.
:return: C{0} on success
:raises error:
- if C{code} is different to C{ARCH_SET_FS}
'''
ARCH_SET_GS = 0x1001
ARCH_SET_FS = 0x1002
ARCH_GET_FS = 0x1003
ARCH_GET_GS = 0x1004
assert code == ARCH_SET_FS
self.current.FS = 0x63
self.current.set_descriptor(self.current.FS, addr, 0x4000, 'rw')
logger.debug("sys_arch_prctl(%04x, %016x) -> 0", code, addr)
return 0
def sys_ioctl(self, fd, request, argp):
if fd > 2:
return self.files[fd].ioctl(request, argp)
else:
return -errno.EINVAL
def _sys_open_get_file(self, filename, flags, mode):
f = File(filename, mode)
return f
def sys_open(self, buf, flags, mode):
'''
:param buf: address of zero-terminated pathname
:param flags: file access bits
:param mode: file permission mode
'''
filename = self.current.read_string(buf)
try:
if os.path.abspath(filename).startswith('/proc/self'):
if filename == '/proc/self/exe':
filename = os.path.abspath(self.program)
else:
logger.info("FIXME!")
mode = {os.O_RDWR: 'r+', os.O_RDONLY: 'r', os.O_WRONLY: 'w'}[flags&7]
f = self._sys_open_get_file(filename, flags, mode)
logger.debug("Opening file %s for %s real fd %d",
filename, mode, f.fileno())
except Exception as e:
logger.info("Could not open file %s. Reason %s" % (filename, str(e)))
return -1
return self._open(f)
def sys_rename(self, oldnamep, newnamep):
'''
Rename filename `oldnamep` to `newnamep`.
:param int oldnamep: pointer to oldname
:param int newnamep: pointer to newname
'''
oldname = self.current.read_string(oldnamep)
newname = self.current.read_string(newnamep)
ret = 0
try:
os.rename(oldname, newname)
except OSError as e:
ret = -e.errno
logger.debug("sys_rename('%s', '%s') -> %s", oldname, newname, ret)
return ret
def sys_fsync(self, fd):
'''
Synchronize a file's in-core state with that on disk.
'''
ret = 0
try:
self.files[fd].sync()
except IndexError:
ret = -errno.EBADF
except BadFd:
ret = -errno.EINVAL
logger.debug("sys_fsync(%d) -> %d", fd, ret)
return ret
def sys_getpid(self, v):
logger.debug("GETPID, warning pid modeled as concrete 1000")
return 1000
def sys_ARM_NR_set_tls(self, val):
if hasattr(self, '_arm_tls_memory'):
self.current.write_int(self._arm_tls_memory, val)
self.current.set_arm_tls(val)
return 0
#Signals..
def sys_kill(self, pid, sig):
logger.debug("KILL, Ignoring Sending signal %d to pid %d", sig, pid)
return 0
def sys_rt_sigaction(self, signum, act, oldact):
"""Wrapper for sys_sigaction"""
return self.sys_sigaction(signum, act, oldact)
def sys_sigaction(self, signum, act, oldact):
logger.debug("SIGACTION, Ignoring changing signal handler for signal %d",
signum)
return 0
def sys_rt_sigprocmask(self, cpu, how, newset, oldset):
'''Wrapper for sys_sigprocmask'''
return self.sys_sigprocmask(cpu, how, newset, oldset)
def sys_sigprocmask(self, cpu, how, newset, oldset):
logger.debug("SIGACTION, Ignoring changing signal mask set cmd:%d", how)
return 0
def sys_close(self, fd):
'''
Closes a file descriptor
:rtype: int
:param fd: the file descriptor to close.
:return: C{0} on success.
'''
if fd > 0 :
self._close(fd)
logger.debug('sys_close(%d)', fd)
return 0
def sys_readlink(self, path, buf, bufsize):
'''
Read
:rtype: int
:param path: the "link path id"
:param buf: the buffer where the bytes will be putted.
:param bufsize: the max size for read the link.
:todo: Out eax number of bytes actually sent | EAGAIN | EBADF | EFAULT | EINTR | errno.EINVAL | EIO | ENOSPC | EPIPE
'''
if bufsize <= 0:
return -errno.EINVAL
filename = self.current.read_string(path)
if filename == '/proc/self/exe':
data = os.path.abspath(self.program)
else:
data = os.readlink(filename)[:bufsize]
self.current.write_bytes(buf, data)
logger.debug("READLINK %d %x %d -> %s",path,buf,bufsize,data)
return len(data)
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):
'''Wrapper for mmap2'''
return self.sys_mmap2(address, size, prot, flags, fd, offset)
def sys_mmap2(self, address, size, prot, flags, fd, offset):
'''
Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
processes mapping the same region, and whether updates are carried
through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset}*0x1000 in the file referred to by the file descriptor C{fd}.
:return:
- C{-1} In case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
- the address of the new mapping.
'''
return self.sys_mmap(address, size, prot, flags, fd, offset*0x1000)
def sys_mmap(self, address, size, prot, flags, fd, offset):
'''
Creates a new mapping in the virtual address space of the calling process.
:rtype: int
:param address: the starting address for the new mapping. This address is used as hint unless the
flag contains C{MAP_FIXED}.
:param size: the length of the mapping.
:param prot: the desired memory protection of the mapping.
:param flags: determines whether updates to the mapping are visible to other
processes mapping the same region, and whether updates are carried
through to the underlying file.
:param fd: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:param offset: the contents of a file mapping are initialized using C{size} bytes starting at
offset C{offset} in the file referred to by the file descriptor C{fd}.
:return:
- C{-1} in case you use C{MAP_FIXED} in the flags and the mapping can not be place at the desired address.
- the address of the new mapping (that must be the same as address in case you included C{MAP_FIXED} in flags).
:todo: handle exception.
'''
if address == 0:
address = None
cpu = self.current
if flags & 0x10 != 0:
cpu.memory.munmap(address,size)
perms = perms_from_protflags(prot)
if flags & 0x20 != 0:
result = cpu.memory.mmap(address, size, perms)
elif fd == 0:
assert offset == 0
result = cpu.memory.mmap(address, size, perms)
data = self.files[fd].read(size)
cpu.write_bytes(result, data)
else:
#FIXME Check if file should be symbolic input and do as with fd0
result = cpu.memory.mmapFile(address, size, perms, self.files[fd].name, offset)
actually_mapped = '0x{:016x}'.format(result)
if address is None or result != address:
address = address or 0
actually_mapped += ' [requested: 0x{:016x}]'.format(address)
if flags & 0x10 != 0 and result != address:
cpu.memory.munmap(result, size)
result = -1
logger.debug("sys_mmap(%s, 0x%x, %s, %x, %d) - (0x%x)",
actually_mapped,
size,
perms,
flags,
fd,
result)
return result
def sys_mprotect(self, start, size, prot):
'''
Sets protection on a region of memory. Changes protection for the calling process's
memory page(s) containing any part of the address range in the interval [C{start}, C{start}+C{size}-1].
:rtype: int
:param start: the starting address to change the permissions.
:param size: the size of the portion of memory to change the permissions.
:param prot: the new access permission for the memory.
:return: C{0} on success.
'''
perms = perms_from_protflags(prot)
ret = self.current.memory.mprotect(start, size, perms)
logger.debug("sys_mprotect(0x%016x, 0x%x, %s) -> %r (%r)", start, size, perms, ret, prot)
return 0
def sys_munmap(self, addr, size):
'''
Unmaps a file from memory. It deletes the mappings for the specified address range
:rtype: int
:param addr: the starting address to unmap.
:param size: the size of the portion to unmap.
:return: C{0} on success.
'''
self.current.memory.munmap(addr, size)
return 0
def sys_getuid(self):
'''
Gets user identity.
:rtype: int
:return: this call returns C{1000} for all the users.
'''
return 1000
def sys_getgid(self):
'''
Gets group identity.
:rtype: int
:return: this call returns C{1000} for all the groups.
'''
return 1000
def sys_geteuid(self):
'''
Gets user identity.
:rtype: int
:return: This call returns C{1000} for all the users.
'''
return 1000
def sys_getegid(self):
'''
Gets group identity.
:rtype: int
:return: this call returns C{1000} for all the groups.
'''
return 1000
def sys_readv(self, fd, iov, count):
'''
Works just like C{sys_read} except that data is read into multiple buffers.
:rtype: int
:param fd: the file descriptor of the file to read.
:param iov: the buffer where the the bytes to read are stored.
:param count: amount of C{iov} buffers to read from the file.
:return: the amount of bytes read in total.
'''
cpu = self.current
ptrsize = cpu.address_bit_size
sizeof_iovec = 2 * (ptrsize // 8)
total = 0
for i in xrange(0, count):
buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)
size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2),
ptrsize)
data = self.files[fd].read(size)
total += len(data)
cpu.write_bytes(buf, data)
self.syscall_trace.append(("_read", fd, data))
logger.debug("READV(%r, %r, %r) -> <%r> (size:%r)",
fd,
buf,
size,
data,
len(data))
return total
def sys_writev(self, fd, iov, count):
'''
Works just like C{sys_write} except that multiple buffers are written out.
:rtype: int
:param fd: the file descriptor of the file to write.
:param iov: the buffer where the the bytes to write are taken.
:param count: amount of C{iov} buffers to write into the file.
:return: the amount of bytes written in total.
'''
cpu = self.current
ptrsize = cpu.address_bit_size
sizeof_iovec = 2 * (ptrsize // 8)
total = 0
for i in xrange(0, count):
buf = cpu.read_int(iov + i * sizeof_iovec, ptrsize)
size = cpu.read_int(iov + i * sizeof_iovec + (sizeof_iovec // 2), ptrsize)
data = ""
for j in xrange(0,size):
data += Operators.CHR(cpu.read_int(buf + j, 8))
logger.debug("WRITEV(%r, %r, %r) -> <%r> (size:%r)"%(fd, buf, size, data, len(data)))
self.files[fd].write(data)
self.syscall_trace.append(("_write", fd, data))
total+=size
return total
def sys_set_thread_area(self, user_info):
'''
Sets a thread local storage (TLS) area. Sets the base address of the GS segment.
:rtype: int
:param user_info: the TLS array entry set corresponds to the value of C{u_info->entry_number}.
:return: C{0} on success.
'''
n = self.current.read_int(user_info, 32)
pointer = self.current.read_int(user_info + 4, 32)
m = self.current.read_int(user_info + 8, 32)
flags = self.current.read_int(user_info + 12, 32)
assert n == 0xffffffff
assert flags == 0x51
self.current.GS = 0x63
self.current.set_descriptor(self.current.GS, pointer, 0x4000, 'rw')
self.current.write_int(user_info, (0x63 - 3) / 8, 32)
return 0
def sys_getpriority(self, which, who):
'''
System call ignored.
:rtype: int
:return: C{0}
'''
logger.debug("Ignoring sys_get_priority")
return 0
def sys_setpriority(self, which, who, prio):
'''
System call ignored.
:rtype: int
:return: C{0}
'''
logger.debug("Ignoring sys_setpriority")
return 0
def sys_acct(self, path):
'''
System call not implemented.
:rtype: int
:return: C{-1}
'''
logger.debug("BSD account not implemented!")
return -1
def sys_exit(self, error_code):
'Wrapper for sys_exit_group'
return self.sys_exit_group(error_code)
def sys_exit_group(self, error_code):
'''
Exits all threads in a process
:raises Exception: 'Finished'
'''
procid = self.procs.index(self.current)
self.sched()
self.running.remove(procid)
logger.debug("EXIT_GROUP PROC_%02d %s", procid, error_code)
if len(self.running) == 0:
raise ProcessExit(error_code)
return error_code
def sys_ptrace(self, request, pid, addr, data):
logger.debug("sys_ptrace(%016x, %d, %016x, %016x) -> 0", request, pid, addr, data)
return 0
def sys_nanosleep(self, req, rem):
logger.debug("sys_nanosleep(...)")
return 0
def sys_set_tid_address(self, tidptr):
logger.debug("sys_set_tid_address(%016x) -> 0", tidptr)
return 1000
def sys_faccessat(self, dirfd, pathname, mode, flags):
filename = self.current.read_string(pathname)
logger.debug("sys_faccessat(%016x, %s, %x, %x) -> 0", dirfd, filename, mode, flags)
return -1
def sys_set_robust_list(self, head, length):
logger.debug("sys_set_robust_list(%016x, %d) -> -1", head, length)
return -1
def sys_futex(self, uaddr, op, val, timeout, uaddr2, val3):
logger.debug("sys_futex(...) -> -1")
return -1
def sys_getrlimit(self, resource, rlim):
logger.debug("sys_getrlimit(%x, %x) -> -1", resource, rlim)
return -1
def sys_fadvise64(self, fd, offset, length, advice):
logger.debug("sys_fadvise64(%x, %x, %x, %x) -> 0", fd, offset, length, advice)
return 0
def sys_gettimeofday(self, tv, tz):
logger.debug("sys_gettimeofday(%x, %x) -> 0", tv, tz)
return 0
def syscall(self):
'''
Syscall dispatcher.
'''
index = self._syscall_abi.syscall_number()
try:
table = getattr(linux_syscalls, self.current.machine)
name = table.get(index, None)
implementation = getattr(self, name)
except (AttributeError, KeyError):
raise SyscallNotImplemented(self.current.address_bit_size, index, name)
return self._syscall_abi.invoke(implementation)
def sys_clock_gettime(self, clock_id, timespec):
logger.info("sys_clock_time not really implemented")
return 0
def sys_time(self, tloc):
import time
t = time.time()
if tloc != 0 :
self.current.write_int(tloc, int(t), self.current.address_bit_size)
return int(t)
def sched(self):
''' Yield CPU.
This will choose another process from the running list and change
current running process. May give the same cpu if only one running
process.
'''
if len(self.procs) > 1:
logger.debug("SCHED:")
logger.debug("\tProcess: %r", self.procs)
logger.debug("\tRunning: %r", self.running)
logger.debug("\tRWait: %r", self.rwait)
logger.debug("\tTWait: %r", self.twait)
logger.debug("\tTimers: %r", self.timers)
logger.debug("\tCurrent clock: %d", self.clocks)
logger.debug("\tCurrent cpu: %d", self._current)
if len(self.running) == 0:
logger.debug("None running checking if there is some process waiting for a timeout")
if all([x is None for x in self.timers]):
raise Deadlock()
self.clocks = min(filter(lambda x: x is not None, self.timers)) + 1
self.check_timers()
assert len(self.running) != 0, "DEADLOCK!"
self._current = self.running[0]
return
next_index = (self.running.index(self._current) + 1) % len(self.running)
next_running_idx = self.running[next_index]
if len(self.procs) > 1:
logger.debug("\tTransfer control from process %d to %d",
self._current,
next_running_idx)
self._current = next_running_idx
def wait(self, readfds, writefds, timeout):
''' Wait for file descriptors or timeout.
Adds the current process in the correspondent waiting list and
yield the cpu to another running process.
'''
logger.debug("WAIT:")
logger.debug("\tProcess %d is going to wait for [ %r %r %r ]",
self._current,
readfds,
writefds,
timeout)
logger.debug("\tProcess: %r", self.procs)
logger.debug("\tRunning: %r", self.running)
logger.debug("\tRWait: %r", self.rwait)
logger.debug("\tTWait: %r", self.twait)
logger.debug("\tTimers: %r", self.timers)
for fd in readfds:
self.rwait[fd].add(self._current)
for fd in writefds:
self.twait[fd].add(self._current)
if timeout is not None:
self.timers[self._current] = self.clocks + timeout
procid = self._current
next_index = (self.running.index(procid) + 1) % len(self.running)
self._current = self.running[next_index]
logger.debug("\tTransfer control from process %d to %d", procid, self._current)
logger.debug( "\tREMOVING %r from %r. Current: %r", procid, self.running, self._current)
self.running.remove(procid)
if self._current not in self.running:
logger.debug("\tCurrent not running. Checking for timers...")
self._current = None
self.check_timers()
def awake(self, procid):
''' Remove procid from waitlists and reestablish it in the running list '''
logger.debug("Remove procid:%d from waitlists and reestablish it in the running list", procid)
for wait_list in self.rwait:
if procid in wait_list: wait_list.remove(procid)
for wait_list in self.twait:
if procid in wait_list: wait_list.remove(procid)
self.timers[procid] = None
self.running.append(procid)
if self._current is None:
self._current = procid
def connections(self, fd):
""" File descriptors are connected to each other like pipes. Except
for 0,1,2. If you write to FD(N) then that comes out from FD(N+1)
and vice-versa
"""
if fd in [0, 1, 2]:
return None
if fd % 2:
return fd + 1
else:
return fd - 1
def signal_receive(self, fd):
''' Awake one process waiting to receive data on fd '''
connections = self.connections
if connections(fd) and self.twait[connections(fd)]:
procid = random.sample(self.twait[connections(fd)], 1)[0]
self.awake(procid)
def signal_transmit(self, fd):
''' Awake one process waiting to transmit data on fd '''
connection = self.connections(fd)
if connection is None or connection >= len(self.rwait):
return
procs = self.rwait[connection]
if procs:
procid = random.sample(procs, 1)[0]
self.awake(procid)
def check_timers(self):
''' Awake process if timer has expired '''
if self._current is None:
advance = min([self.clocks] + filter(lambda x: x is not None, self.timers)) + 1
logger.debug("Advancing the clock from %d to %d", self.clocks, advance)
self.clocks = advance
for procid in range(len(self.timers)):
if self.timers[procid] is not None:
if self.clocks > self.timers[procid]:
self.procs[procid].PC += self.procs[procid].instruction.size
self.awake(procid)
def execute(self):
"""
Execute one cpu instruction in the current thread (only one supported).
:rtype: bool
:return: C{True}
:todo: This is where we could implement a simple schedule.
"""
try:
self.current.execute()
self.clocks += 1
if self.clocks % 10000 == 0:
self.check_timers()
self.sched()
except (Interruption, Syscall):
try:
self.syscall()
except RestartSyscall:
pass
return True
def sys_newfstat(self, fd, buf):
'''
Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(width, ts):
'Note: this is a platform-dependent timespec (8 or 16 bytes)'
return add(width, int(ts)) + add(width, int(ts % 1 * 1e9))
nw = self.current.address_bit_size / 8
bufstat = add(nw, stat.st_dev)
bufstat += add(nw, stat.st_ino)
bufstat += add(nw, stat.st_nlink)
bufstat += add(4, stat.st_mode)
bufstat += add(4, stat.st_uid)
bufstat += add(4, stat.st_gid)
bufstat += add(4, 0)
bufstat += add(nw, stat.st_rdev)
bufstat += add(nw, stat.st_size)
bufstat += add(nw, stat.st_blksize)
bufstat += add(nw, stat.st_blocks)
bufstat += to_timespec(nw, stat.st_atime)
bufstat += to_timespec(nw, stat.st_mtime)
bufstat += to_timespec(nw, stat.st_ctime)
logger.debug("sys_newfstat(%d, ...) -> %d bytes", fd, len(bufstat))
self.current.write_bytes(buf, bufstat)
return 0
def sys_fstat(self, fd, buf):
'''
Determines information about a file based on its file descriptor.
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(ts):
return struct.pack('<LL', int(ts), int(ts % 1 * 1e9))
logger.debug("sys_fstat %d", fd)
bufstat = add(8, stat.st_dev)
bufstat += add(4, 0)
bufstat += add(4, stat.st_ino)
bufstat += add(4, stat.st_mode)
bufstat += add(4, stat.st_nlink)
bufstat += add(4, stat.st_uid)
bufstat += add(4, stat.st_gid)
bufstat += add(4, stat.st_rdev)
bufstat += add(4, stat.st_size)
bufstat += add(4, stat.st_blksize)
bufstat += add(4, stat.st_blocks)
bufstat += to_timespec(stat.st_atime)
bufstat += to_timespec(stat.st_mtime)
bufstat += to_timespec(stat.st_ctime)
bufstat += add(4, 0)
bufstat += add(4, 0)
self.current.write_bytes(buf, bufstat)
return 0
def sys_fstat64(self, fd, buf):
'''
Determines information about a file based on its file descriptor (for Linux 64 bits).
:rtype: int
:param fd: the file descriptor of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
:todo: Fix device number.
'''
stat = self.files[fd].stat()
def add(width, val):
fformat = {2:'H', 4:'L', 8:'Q'}[width]
return struct.pack('<'+fformat, val)
def to_timespec(ts):
return struct.pack('<LL', int(ts), int(ts % 1 * 1e9))
logger.debug("sys_fstat64 %d", fd)
bufstat = add(8, stat.st_dev)
bufstat += add(4, 0)
bufstat += add(4, stat.st_ino)
bufstat += add(4, stat.st_mode)
bufstat += add(4, stat.st_nlink)
bufstat += add(4, stat.st_uid)
bufstat += add(4, stat.st_gid)
bufstat += add(8, stat.st_rdev)
bufstat += add(4, 0)
bufstat += add(4, 0)
bufstat += add(8, stat.st_size)
bufstat += add(8, stat.st_blksize)
bufstat += add(8, stat.st_blocks)
bufstat += to_timespec(stat.st_atime)
bufstat += to_timespec(stat.st_mtime)
bufstat += to_timespec(stat.st_ctime)
bufstat += add(8, stat.st_ino)
self.current.write_bytes(buf, bufstat)
return 0
def sys_newstat(self, fd, buf):
'''
Wrapper for stat64()
'''
return self.sys_stat64(fd, buf)
def sys_stat64(self, path, buf):
'''
Determines information about a file based on its filename (for Linux 64 bits).
:rtype: int
:param path: the pathname of the file that is being inquired.
:param buf: a buffer where data about the file will be stored.
:return: C{0} on success.
'''
return self._stat(path, buf, True)
def sys_stat32(self, path, buf):
return self._stat(path, buf, False)
def _stat(self, path, buf, is64bit):
fd = self.sys_open(path, 0, 'r')
if is64bit:
ret = self.sys_fstat64(fd, buf)
else:
ret = self.sys_fstat(fd, buf)
self.sys_close(fd)
return ret
def _arch_specific_init(self):
assert self.arch in {'i386', 'amd64', 'armv7'}
if self.arch == 'i386':
self._uname_machine = 'i386'
elif self.arch == 'amd64':
self._uname_machine = 'x86_64'
elif self.arch == 'armv7':
self._uname_machine = 'armv71'
self._init_arm_kernel_helpers()
if self.arch in {'i386', 'amd64'}:
x86_defaults = {'CS': 0x23, 'SS': 0x2b, 'DS': 0x2b, 'ES': 0x2b}
for reg, val in x86_defaults.iteritems():
self.current.regfile.write(reg, val)
@staticmethod
def _interp_total_size(interp):
'''
Compute total load size of interpreter.
:param ELFFile interp: interpreter ELF .so
:return: total load size of interpreter, not aligned
:rtype: int
'''
load_segs = filter(lambda x: x.header.p_type == 'PT_LOAD', interp.iter_segments())
last = load_segs[-1]
return last.header.p_vaddr + last.header.p_memsz
number of bytes ")
raise ConcretizeArgument(2)
return super(SLinux, self).sys_write(fd, buf, count)
class DecreeEmu(object):
RANDOM = 0
@staticmethod
def cgc_initialize_secret_page(platform):
logger.info("Skipping: cgc_initialize_secret_page()")
return 0
@staticmethod
def cgc_random(platform, buf, count, rnd_bytes):
from . import cgcrandom
if issymbolic(buf):
logger.info("Ask to write random bytes to a symbolic buffer")
raise ConcretizeArgument(0)
if issymbolic(count):
logger.info("Ask to read a symbolic number of random bytes ")
raise ConcretizeArgument(1)
if issymbolic(rnd_bytes):
logger.info("Ask to return rnd size to a symbolic address ")
raise ConcretizeArgument(2)
data = []
for i in xrange(count):
value = cgcrandom.stream[DecreeEmu.RANDOM]
data.append(value)
DecreeEmu.random += 1
cpu = platform.current
cpu.write(buf, data)
if rnd_bytes:
cpu.store(rnd_bytes, len(data), 32)
logger.info("RANDOM(0x%08x, %d, 0x%08x) -> %d", buf, count, rnd_bytes, len(data))
return 0
| false | true |
f727fdadcd3bc9ccad0ae50f7d825827d2eb27e6 | 1,146 | py | Python | manage-api/server/main.py | lisy09/spark-dev-box | ed362cb5b19400a798995e270869df14805600a0 | [
"MIT"
] | null | null | null | manage-api/server/main.py | lisy09/spark-dev-box | ed362cb5b19400a798995e270869df14805600a0 | [
"MIT"
] | null | null | null | manage-api/server/main.py | lisy09/spark-dev-box | ed362cb5b19400a798995e270869df14805600a0 | [
"MIT"
] | null | null | null | from fastapi import FastAPI
import logging
from .routers import routers
from .core.config import get_config, get_gunicorn_config
from .core.logger import setup_logger, StubbedGunicornLogger
import gunicorn.app.base
def createSimpleFastapi():
app = FastAPI()
app.include_router(routers.router)
return app
def createFastapi(conf):
app = createSimpleFastapi()
app.state.config = conf
return app
class GunicornApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == "__main__":
conf = get_config()
setup_logger()
app = createFastapi(conf)
gunicorn_options = get_gunicorn_config(StubbedGunicornLogger)
GunicornApplication(app, gunicorn_options).run() | 27.95122 | 68 | 0.696335 | from fastapi import FastAPI
import logging
from .routers import routers
from .core.config import get_config, get_gunicorn_config
from .core.logger import setup_logger, StubbedGunicornLogger
import gunicorn.app.base
def createSimpleFastapi():
app = FastAPI()
app.include_router(routers.router)
return app
def createFastapi(conf):
app = createSimpleFastapi()
app.state.config = conf
return app
class GunicornApplication(gunicorn.app.base.BaseApplication):
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super().__init__()
def load_config(self):
config = {key: value for key, value in self.options.items()
if key in self.cfg.settings and value is not None}
for key, value in config.items():
self.cfg.set(key.lower(), value)
def load(self):
return self.application
if __name__ == "__main__":
conf = get_config()
setup_logger()
app = createFastapi(conf)
gunicorn_options = get_gunicorn_config(StubbedGunicornLogger)
GunicornApplication(app, gunicorn_options).run() | true | true |
f727fdc01f072843395a369831bd24b9de4f8cb3 | 9,268 | py | Python | skimage/future/graph/graph_cut.py | portugueslab/scikit-image | 0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b | [
"BSD-3-Clause"
] | 2 | 2020-02-24T02:24:43.000Z | 2021-12-19T11:44:34.000Z | skimage/future/graph/graph_cut.py | portugueslab/scikit-image | 0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b | [
"BSD-3-Clause"
] | 30 | 2020-04-15T19:37:40.000Z | 2020-04-22T21:19:35.000Z | skimage/future/graph/graph_cut.py | portugueslab/scikit-image | 0fa3bcb118bb208a0cc7d3e8b96cd96c1ce7a75b | [
"BSD-3-Clause"
] | 2 | 2019-06-16T06:38:28.000Z | 2021-12-19T11:44:48.000Z | try:
import networkx as nx
except ImportError:
from ..._shared.utils import warn
warn('RAGs require networkx')
import numpy as np
from . import _ncut
from . import _ncut_cy
from scipy.sparse import linalg
def cut_threshold(labels, rag, thresh, in_place=True):
"""Combine regions separated by weight less than threshold.
Given an image's labels and its RAG, output new labels by
combining regions whose nodes are separated by a weight less
than the given threshold.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. Regions connected by edges with smaller weights are
combined.
in_place : bool
If set, modifies `rag` in place. The function will remove the edges
with weights less that `thresh`. If set to `False` the function
makes a copy of `rag` before proceeding.
Returns
-------
out : ndarray
The new labelled array.
Examples
--------
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels)
>>> new_labels = graph.cut_threshold(labels, rag, 10)
References
----------
.. [1] Alain Tremeau and Philippe Colantoni
"Regions Adjacency Graph Applied To Color Image Segmentation"
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.11.5274
"""
if not in_place:
rag = rag.copy()
# Because deleting edges while iterating through them produces an error.
to_remove = [(x, y) for x, y, d in rag.edges(data=True)
if d['weight'] >= thresh]
rag.remove_edges_from(to_remove)
comps = nx.connected_components(rag)
# We construct an array which can map old labels to the new ones.
# All the labels within a connected component are assigned to a single
# label in the output.
map_array = np.arange(labels.max() + 1, dtype=labels.dtype)
for i, nodes in enumerate(comps):
for node in nodes:
for label in rag.node[node]['labels']:
map_array[label] = i
return map_array[labels]
def cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True,
max_edge=1.0):
"""Perform Normalized Graph cut on the Region Adjacency Graph.
Given an image's labels and its similarity RAG, recursively perform
a 2-way normalized cut on it. All nodes belonging to a subgraph
that cannot be cut further are assigned a unique label in the
output.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. A subgraph won't be further subdivided if the
value of the N-cut exceeds `thresh`.
num_cuts : int
The number or N-cuts to perform before determining the optimal one.
in_place : bool
If set, modifies `rag` in place. For each node `n` the function will
set a new attribute ``rag.node[n]['ncut label']``.
max_edge : float, optional
The maximum possible value of an edge in the RAG. This corresponds to
an edge between identical regions. This is used to put self
edges in the RAG.
Returns
-------
out : ndarray
The new labeled array.
Examples
--------
>>> from skimage import data, segmentation
>>> from skimage.future import graph
>>> img = data.astronaut()
>>> labels = segmentation.slic(img)
>>> rag = graph.rag_mean_color(img, labels, mode='similarity')
>>> new_labels = graph.cut_normalized(labels, rag)
References
----------
.. [1] Shi, J.; Malik, J., "Normalized cuts and image segmentation",
Pattern Analysis and Machine Intelligence,
IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000.
"""
if not in_place:
rag = rag.copy()
for node in rag.nodes():
rag.add_edge(node, node, weight=max_edge)
_ncut_relabel(rag, thresh, num_cuts)
map_array = np.zeros(labels.max() + 1, dtype=labels.dtype)
# Mapping from old labels to new
for n, d in rag.nodes(data=True):
map_array[d['labels']] = d['ncut label']
return map_array[labels]
def partition_by_cut(cut, rag):
"""Compute resulting subgraphs from given bi-parition.
Parameters
----------
cut : array
A array of booleans. Elements set to `True` belong to one
set.
rag : RAG
The Region Adjacency Graph.
Returns
-------
sub1, sub2 : RAG
The two resulting subgraphs from the bi-partition.
"""
# `cut` is derived from `D` and `W` matrices, which also follow the
# ordering returned by `rag.nodes()` because we use
# nx.to_scipy_sparse_matrix.
# Example
# rag.nodes() = [3, 7, 9, 13]
# cut = [True, False, True, False]
# nodes1 = [3, 9]
# nodes2 = [7, 10]
nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]]
nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]]
sub1 = rag.subgraph(nodes1)
sub2 = rag.subgraph(nodes2)
return sub1, sub2
def get_min_ncut(ev, d, w, num_cuts):
"""Threshold an eigenvector evenly, to determine minimum ncut.
Parameters
----------
ev : array
The eigenvector to threshold.
d : ndarray
The diagonal matrix of the graph.
w : ndarray
The weight matrix of the graph.
num_cuts : int
The number of evenly spaced thresholds to check for.
Returns
-------
mask : array
The array of booleans which denotes the bi-partition.
mcut : float
The value of the minimum ncut.
"""
mcut = np.inf
mn = ev.min()
mx = ev.max()
# If all values in `ev` are equal, it implies that the graph can't be
# further sub-divided. In this case the bi-partition is the the graph
# itself and an empty set.
min_mask = np.zeros_like(ev, dtype=np.bool)
if np.allclose(mn, mx):
return min_mask, mcut
# Refer Shi & Malik 2001, Section 3.1.3, Page 892
# Perform evenly spaced n-cuts and determine the optimal one.
for t in np.linspace(mn, mx, num_cuts, endpoint=False):
mask = ev > t
cost = _ncut.ncut_cost(mask, d, w)
if cost < mcut:
min_mask = mask
mcut = cost
return min_mask, mcut
def _label_all(rag, attr_name):
"""Assign a unique integer to the given attribute in the RAG.
This function assumes that all labels in `rag` are unique. It
picks up a random label from them and assigns it to the `attr_name`
attribute of all the nodes.
rag : RAG
The Region Adjacency Graph.
attr_name : string
The attribute to which a unique integer is assigned.
"""
node = min(rag.nodes())
new_label = rag.node[node]['labels'][0]
for n, d in rag.nodes(data=True):
d[attr_name] = new_label
def _ncut_relabel(rag, thresh, num_cuts):
"""Perform Normalized Graph cut on the Region Adjacency Graph.
Recursively partition the graph into 2, until further subdivision
yields a cut greater than `thresh` or such a cut cannot be computed.
For such a subgraph, indices to labels of all its nodes map to a single
unique value.
Parameters
----------
labels : ndarray
The array of labels.
rag : RAG
The region adjacency graph.
thresh : float
The threshold. A subgraph won't be further subdivided if the
value of the N-cut exceeds `thresh`.
num_cuts : int
The number or N-cuts to perform before determining the optimal one.
map_array : array
The array which maps old labels to new ones. This is modified inside
the function.
"""
d, w = _ncut.DW_matrices(rag)
m = w.shape[0]
if m > 2:
d2 = d.copy()
# Since d is diagonal, we can directly operate on its data
# the inverse of the square root
d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data)
# Refer Shi & Malik 2001, Equation 7, Page 891
vals, vectors = linalg.eigsh(d2 * (d - w) * d2, which='SM',
k=min(100, m - 2))
# Pick second smallest eigenvector.
# Refer Shi & Malik 2001, Section 3.2.3, Page 893
vals, vectors = np.real(vals), np.real(vectors)
index2 = _ncut_cy.argmin2(vals)
ev = vectors[:, index2]
cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts)
if (mcut < thresh):
# Sub divide and perform N-cut again
# Refer Shi & Malik 2001, Section 3.2.5, Page 893
sub1, sub2 = partition_by_cut(cut_mask, rag)
_ncut_relabel(sub1, thresh, num_cuts)
_ncut_relabel(sub2, thresh, num_cuts)
return
# The N-cut wasn't small enough, or could not be computed.
# The remaining graph is a region.
# Assign `ncut label` by picking any label from the existing nodes, since
# `labels` are unique, `new_label` is also unique.
_label_all(rag, 'ncut label')
| 31.416949 | 77 | 0.623867 | try:
import networkx as nx
except ImportError:
from ..._shared.utils import warn
warn('RAGs require networkx')
import numpy as np
from . import _ncut
from . import _ncut_cy
from scipy.sparse import linalg
def cut_threshold(labels, rag, thresh, in_place=True):
if not in_place:
rag = rag.copy()
to_remove = [(x, y) for x, y, d in rag.edges(data=True)
if d['weight'] >= thresh]
rag.remove_edges_from(to_remove)
comps = nx.connected_components(rag)
map_array = np.arange(labels.max() + 1, dtype=labels.dtype)
for i, nodes in enumerate(comps):
for node in nodes:
for label in rag.node[node]['labels']:
map_array[label] = i
return map_array[labels]
def cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True,
max_edge=1.0):
if not in_place:
rag = rag.copy()
for node in rag.nodes():
rag.add_edge(node, node, weight=max_edge)
_ncut_relabel(rag, thresh, num_cuts)
map_array = np.zeros(labels.max() + 1, dtype=labels.dtype)
for n, d in rag.nodes(data=True):
map_array[d['labels']] = d['ncut label']
return map_array[labels]
def partition_by_cut(cut, rag):
nodes1 = [n for i, n in enumerate(rag.nodes()) if cut[i]]
nodes2 = [n for i, n in enumerate(rag.nodes()) if not cut[i]]
sub1 = rag.subgraph(nodes1)
sub2 = rag.subgraph(nodes2)
return sub1, sub2
def get_min_ncut(ev, d, w, num_cuts):
mcut = np.inf
mn = ev.min()
mx = ev.max()
# further sub-divided. In this case the bi-partition is the the graph
# itself and an empty set.
min_mask = np.zeros_like(ev, dtype=np.bool)
if np.allclose(mn, mx):
return min_mask, mcut
# Refer Shi & Malik 2001, Section 3.1.3, Page 892
# Perform evenly spaced n-cuts and determine the optimal one.
for t in np.linspace(mn, mx, num_cuts, endpoint=False):
mask = ev > t
cost = _ncut.ncut_cost(mask, d, w)
if cost < mcut:
min_mask = mask
mcut = cost
return min_mask, mcut
def _label_all(rag, attr_name):
node = min(rag.nodes())
new_label = rag.node[node]['labels'][0]
for n, d in rag.nodes(data=True):
d[attr_name] = new_label
def _ncut_relabel(rag, thresh, num_cuts):
d, w = _ncut.DW_matrices(rag)
m = w.shape[0]
if m > 2:
d2 = d.copy()
# Since d is diagonal, we can directly operate on its data
# the inverse of the square root
d2.data = np.reciprocal(np.sqrt(d2.data, out=d2.data), out=d2.data)
# Refer Shi & Malik 2001, Equation 7, Page 891
vals, vectors = linalg.eigsh(d2 * (d - w) * d2, which='SM',
k=min(100, m - 2))
# Pick second smallest eigenvector.
# Refer Shi & Malik 2001, Section 3.2.3, Page 893
vals, vectors = np.real(vals), np.real(vectors)
index2 = _ncut_cy.argmin2(vals)
ev = vectors[:, index2]
cut_mask, mcut = get_min_ncut(ev, d, w, num_cuts)
if (mcut < thresh):
# Sub divide and perform N-cut again
# Refer Shi & Malik 2001, Section 3.2.5, Page 893
sub1, sub2 = partition_by_cut(cut_mask, rag)
_ncut_relabel(sub1, thresh, num_cuts)
_ncut_relabel(sub2, thresh, num_cuts)
return
# The N-cut wasn't small enough, or could not be computed.
_label_all(rag, 'ncut label')
| true | true |
f727fddd3097c5ec42695160636f977e440b5a91 | 1,058 | py | Python | meijer/tests/test_meijer_list.py | sllawcj/python_Meijer | d8caf2e97ce30df565810bac9dff4d1cccc59022 | [
"MIT"
] | 6 | 2020-03-23T02:58:30.000Z | 2022-01-16T02:41:50.000Z | meijer/tests/test_meijer_list.py | sllawcj/python_Meijer | d8caf2e97ce30df565810bac9dff4d1cccc59022 | [
"MIT"
] | 1 | 2021-12-12T21:45:11.000Z | 2021-12-12T21:45:11.000Z | meijer/tests/test_meijer_list.py | sllawcj/python_Meijer | d8caf2e97ce30df565810bac9dff4d1cccc59022 | [
"MIT"
] | 3 | 2020-11-04T02:35:13.000Z | 2021-11-07T20:46:04.000Z | import pytest
from meijer import __version__
from meijer import Meijer
@pytest.fixture(scope="session")
def meijer():
with Meijer() as m:
m.login()
yield m
@pytest.fixture(scope="session")
def shopping_list(meijer):
shopping_list = meijer.list
shopping_list.clear()
yield shopping_list
shopping_list.clear()
def test_empty_list(shopping_list):
assert shopping_list.count == 0
def test_list_add(shopping_list, session_uuid):
for i in range(10):
shopping_list.add(f"pytest {str(i)} {session_uuid}")
assert shopping_list.count == 10
def test_list_complete(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
def test_list_uncomplete(shopping_list):
for item in shopping_list.items:
if item["isComplete"]:
shopping_list.uncomplete(item)
def test_list_complete2(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
| 22.041667 | 60 | 0.695652 | import pytest
from meijer import __version__
from meijer import Meijer
@pytest.fixture(scope="session")
def meijer():
with Meijer() as m:
m.login()
yield m
@pytest.fixture(scope="session")
def shopping_list(meijer):
shopping_list = meijer.list
shopping_list.clear()
yield shopping_list
shopping_list.clear()
def test_empty_list(shopping_list):
assert shopping_list.count == 0
def test_list_add(shopping_list, session_uuid):
for i in range(10):
shopping_list.add(f"pytest {str(i)} {session_uuid}")
assert shopping_list.count == 10
def test_list_complete(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
def test_list_uncomplete(shopping_list):
for item in shopping_list.items:
if item["isComplete"]:
shopping_list.uncomplete(item)
def test_list_complete2(shopping_list):
for item in shopping_list.items:
if not item["isComplete"]:
shopping_list.complete(item)
| true | true |
f727febcbb7b6a2d542c6088719875fe0507db7e | 377 | py | Python | examples/using_R2018.py | jkjt/ezdxf | 2acc5611b81476ea16b98063b9f55446a9182b81 | [
"MIT"
] | 515 | 2017-01-25T05:46:52.000Z | 2022-03-29T09:52:27.000Z | examples/using_R2018.py | jkjt/ezdxf | 2acc5611b81476ea16b98063b9f55446a9182b81 | [
"MIT"
] | 417 | 2017-01-25T10:01:17.000Z | 2022-03-29T09:22:04.000Z | examples/using_R2018.py | jkjt/ezdxf | 2acc5611b81476ea16b98063b9f55446a9182b81 | [
"MIT"
] | 149 | 2017-02-01T15:52:02.000Z | 2022-03-17T10:33:38.000Z | # Copyright (c) 2017-2021 Manfred Moitzi
# License: MIT License
import ezdxf
doc = ezdxf.new("R2018", setup=True)
modelspace = doc.modelspace()
modelspace.add_circle(
center=(0, 0),
radius=1.5,
dxfattribs={
"layer": "test",
"linetype": "DASHED",
},
)
filename = "circle_R2018.dxf"
doc.saveas(filename)
print(f"DXF file '{filename}' created.")
| 19.842105 | 40 | 0.647215 |
import ezdxf
doc = ezdxf.new("R2018", setup=True)
modelspace = doc.modelspace()
modelspace.add_circle(
center=(0, 0),
radius=1.5,
dxfattribs={
"layer": "test",
"linetype": "DASHED",
},
)
filename = "circle_R2018.dxf"
doc.saveas(filename)
print(f"DXF file '{filename}' created.")
| true | true |
f727fee3fb973a4e34d1c41f7b2d1e4d3582c1bb | 43,980 | py | Python | DCT-Copula-Illustration.py | ibianka/HARK | 8678dbab0a0ace1520ac8f7ff5b33765122619f4 | [
"Apache-2.0"
] | null | null | null | DCT-Copula-Illustration.py | ibianka/HARK | 8678dbab0a0ace1520ac8f7ff5b33765122619f4 | [
"Apache-2.0"
] | null | null | null | DCT-Copula-Illustration.py | ibianka/HARK | 8678dbab0a0ace1520ac8f7ff5b33765122619f4 | [
"Apache-2.0"
] | null | null | null | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.1.3
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # Dimensionality Reduction in [Bayer and Luetticke (2018)](https://cepr.org/active/publications/discussion_papers/dp.php?dpno=13071)
#
# [](https://mybinder.org/v2/gh/econ-ark/HARK/BayerLuetticke?filepath=HARK%2FBayerLuetticke%2FDCT-Copula-Illustration.ipynb)
#
# This companion to the [main notebook](TwoAsset.ipynb) explains in more detail how the authors reduce the dimensionality of their problem
#
# - Based on original slides by Christian Bayer and Ralph Luetticke
# - Original Jupyter notebook by Seungcheol Lee
# - Further edits by Chris Carroll, Tao Wang
#
# %% [markdown]
# ### Preliminaries
#
# In Steady-state Equilibrium (StE) in the model, in any given period, a consumer in state $s$ (which comprises liquid assets $m$, illiquid assets $k$, and human capital $\newcommand{hLev}{h}\hLev$) has two key choices:
# 1. To adjust ('a') or not adjust ('n') their holdings of illiquid assets $k$
# 1. Contingent on that choice, decide the level of consumption, yielding consumption functions:
# * $c_n(s)$ - nonadjusters
# * $c_a(s)$ - adjusters
#
# The usual envelope theorem applies here, so marginal value wrt the liquid asset equals marginal utility with respect to consumption:
# $[\frac{d v}{d m} = \frac{d u}{d c}]$.
# In practice, the authors solve their problem using the marginal value of money $\texttt{Vm} = dv/dm$, but because the marginal utility function is invertible it is trivial to recover $\texttt{c}$ from $(u^{\prime})^{-1}(\texttt{Vm} )$. The consumption function is therefore computed from the $\texttt{Vm}$ function
# %% {"code_folding": [0]}
# Setup stuff
# This is a jupytext paired notebook that autogenerates a corresponding .py file
# which can be executed from a terminal command line via "ipython [name].py"
# But a terminal does not permit inline figures, so we need to test jupyter vs terminal
# Google "how can I check if code is executed in the ipython notebook"
def in_ipynb():
try:
if str(type(get_ipython())) == "<class 'ipykernel.zmqshell.ZMQInteractiveShell'>":
return True
else:
return False
except NameError:
return False
# Determine whether to make the figures inline (for spyder or jupyter)
# vs whatever is the automatic setting that will apply if run from the terminal
if in_ipynb():
# %matplotlib inline generates a syntax error when run from the shell
# so do this instead
get_ipython().run_line_magic('matplotlib', 'inline')
else:
get_ipython().run_line_magic('matplotlib', 'auto')
# The tools for navigating the filesystem
import sys
import os
# Find pathname to this file:
my_file_path = os.path.dirname(os.path.abspath("TwoAsset.ipynb"))
# Relative directory for pickled code
code_dir = os.path.join(my_file_path, "BayerLuetticke_code/TwoAssetCode")
sys.path.insert(0, code_dir)
sys.path.insert(0, my_file_path)
# %% {"code_folding": []}
# Load precalculated Stationary Equilibrium (StE) object EX3SS
import pickle
os.chdir(code_dir) # Go to the directory with pickled code
## EX3SS_20.p is the information in the stationary equilibrium
## (20: the number of illiquid and liquid weath gridpoints)
### The comments above are original, but it seems that there are 30 not 20 points now
EX3SS=pickle.load(open("EX3SS_20.p", "rb"))
# %% [markdown]
# ### Dimensions
#
# The imported StE solution to the problem represents the functions at a set of gridpoints of
# * liquid assets ($n_m$ points), illiquid assets ($n_k$), and human capital ($n_h$)
# * In the code these are $\{\texttt{nm,nk,nh}\}$
#
# So even if the grids are fairly sparse for each state variable, the total number of combinations of the idiosyncratic state gridpoints is large: $n = n_m \times n_k \times n_h$. So, e.g., $\bar{c}$ is a set of size $n$ containing the level of consumption at each possible _combination_ of gridpoints.
#
# In the "real" micro problem, it would almost never happen that a continuous variable like $m$ would end up being exactly equal to one of the prespecified gridpoints. But the functions need to be evaluated at such non-grid points. This is addressed by linear interpolation. That is, if, say, the grid had $m_{8} = 40$ and $m_{9} = 50$ then and a consumer ended up with $m = 45$ then the approximation is that $\tilde{c}(45) = 0.5 \bar{c}_{8} + 0.5 \bar{c}_{9}$.
#
# %% {"code_folding": []}
# Show dimensions of the consumer's problem (state space)
print('c_n is of dimension: ' + str(EX3SS['mutil_c_n'].shape))
print('c_a is of dimension: ' + str(EX3SS['mutil_c_a'].shape))
print('Vk is of dimension:' + str(EX3SS['Vk'].shape))
print('Vm is of dimension:' + str(EX3SS['Vm'].shape))
print('For convenience, these are all constructed from the same exogenous grids:')
print(str(len(EX3SS['grid']['m']))+' gridpoints for liquid assets;')
print(str(len(EX3SS['grid']['k']))+' gridpoints for illiquid assets;')
print(str(len(EX3SS['grid']['h']))+' gridpoints for individual productivity.')
print('')
print('Therefore, the joint distribution is of size: ')
print(str(EX3SS['mpar']['nm'])+
' * '+str(EX3SS['mpar']['nk'])+
' * '+str(EX3SS['mpar']['nh'])+
' = '+ str(EX3SS['mpar']['nm']*EX3SS['mpar']['nk']*EX3SS['mpar']['nh']))
# %% [markdown]
# ### Dimension Reduction
#
# The authors use different dimensionality reduction methods for the consumer's problem and the distribution across idiosyncratic states
# %% [markdown]
# #### Representing the consumer's problem with Basis Functions
#
# The idea is to find an efficient "compressed" representation of our functions (e.g., the consumption function), which BL do using tools originally developed for image compression. The analogy to image compression is that nearby pixels are likely to have identical or very similar colors, so we need only to find an efficient way to represent how the colors _change_ from one pixel to nearby ones. Similarly, consumption at a given point $s_{i}$ is likely to be close to consumption point at another point $s_{j}$ that is "close" in the state space (similar wealth, income, etc), so a function that captures that similarity efficiently can preserve most of the information without keeping all of the points.
#
# Like linear interpolation, the [DCT transformation](https://en.wikipedia.org/wiki/Discrete_cosine_transform) is a method of representing a continuous function using a finite set of numbers. It uses a set of independent [basis functions](https://en.wikipedia.org/wiki/Basis_function) to do this.
#
# But it turns out that some of those basis functions are much more important than others in representing the steady-state functions. Dimension reduction is accomplished by basically ignoring all basis functions that make "small enough" contributions to the representation of the function.
#
# ##### When might this go wrong?
#
# Suppose the consumption function changes in a recession in ways that change behavior radically at some states. Like, suppose unemployment almost never happens in steady state, but it can happen in temporary recessions. Suppose further that, even for employed people, in a recession, _worries_ about unemployment cause many of them to prudently withdraw some of their illiquid assets -- behavior opposite of what people in the same state would be doing during expansions. In that case, the basis functions that represented the steady state function would have had no incentive to be able to represent well the part of the space that is never seen in steady state, so any functions that might help do so might well have been dropped in the dimension reduction stage.
#
# On the whole, it seems unlikely that this kind of thing is a major problem, because the vast majority of the variation that people experience is idiosyncratic. There is always unemployment, for example; it just moves up and down a bit with aggregate shocks, but since the experience of unemployment is in fact well represented in the steady state the method should have no trouble capturing it.
#
# Where the method might have more trouble is in representing economies in which there are multiple equilibria in which behavior is quite different.
# %% [markdown]
# #### For the distribution of agents across states: Copula
#
# The other tool the authors use is the ["copula"](https://en.wikipedia.org/wiki/Copula_(probability_theory)), which allows us to represent the distribution of people across idiosyncratic states efficiently
#
# The copula is computed from the joint distribution of states in StE and will be used to transform the [marginal distributions](https://en.wikipedia.org/wiki/Marginal_distribution) back to joint distributions. (For an illustration of how the assumptions used when modeling asset price distributions using copulas can fail see [Salmon](https://www.wired.com/2009/02/wp-quant/))
#
# * A copula is a representation of the joint distribution expressed using a mapping between the uniform joint CDF and the marginal distributions of the variables
#
# * The crucial assumption is that what aggregate shocks do is to squeeze or distort the steady state distribution, but leave the rank structure of the distribution the same
# * An example of when this might not hold is the following. Suppose that in expansions, the people at the top of the distribution of illiquid assets (the top 1 percent, say) are also at the top 1 percent of liquid assets. But in recessions the bottom 99 percent get angry at the top 1 percent of illiquid asset holders and confiscate part of their liquid assets (the illiquid assets can't be confiscated quickly because they are illiquid). Now the people in the top 99 percent of illiquid assets might be in the _bottom_ 1 percent of liquid assets.
#
# - In this case we just need to represent how the mapping from ranks into levels of assets
#
# - This reduces the number of points for which we need to track transitions from $3600 = 30 \times 30 \times 4$ to $64 = 30+30+4$. Or the total number of points we need to contemplate goes from $3600^2 \approx 13 $million to $64^2=4096$.
# %% {"code_folding": []}
# Get some specs about the copula, which is precomputed in the EX3SS object
print('The copula consists of two parts: gridpoints and values at those gridpoints:'+ \
'\n gridpoints have dimensionality of '+str(EX3SS['Copula']['grid'].shape) + \
'\n where the first element is total number of gridpoints' + \
'\n and the second element is number of idiosyncratic state variables' + \
'\n whose values also are of dimension of '+str(EX3SS['Copula']['value'].shape[0]) + \
'\n each entry of which is the probability that all three of the'
'\n state variables are below the corresponding point.')
# %% {"code_folding": []}
## Import necessary libraries
from __future__ import print_function
import sys
sys.path.insert(0,'../')
import numpy as np
from numpy.linalg import matrix_rank
import scipy as sc
from scipy.stats import norm
from scipy.interpolate import interp1d, interp2d, griddata, RegularGridInterpolator, interpn
import multiprocessing as mp
from multiprocessing import Pool, cpu_count, Process
from math import ceil
import math as mt
from scipy import sparse as sp # used to work with sparse matrices
from scipy import linalg #linear algebra
from math import log, cos, pi, sqrt
import time
from SharedFunc3 import Transition, ExTransitions, GenWeight, MakeGridkm, Tauchen, Fastroot
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scipy.io #scipy input and output
import scipy.fftpack as sf # scipy discrete fourier transforms
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
import seaborn as sns
import copy as cp
# %% {"code_folding": []}
## State reduction and discrete cosine transformation
class StateReduc_Dct:
def __init__(self, par, mpar, grid, Output, targets, Vm, Vk,
joint_distr, Copula, c_n_guess, c_a_guess, psi_guess,
m_n_star, m_a_star, cap_a_star, mutil_c_n, mutil_c_a,mutil_c, P_H):
self.par = par # Parameters of the theoretical model
self.mpar = mpar # Parameters of the numerical representation
self.grid = grid # Discrete grid
self.Output = Output # Results of the calculations
self.targets = targets # Like, debt-to-GDP ratio or other desiderata
self.Vm = Vm # Marginal value from liquid cash-on-hand
self.Vk = Vk # Marginal value of capital
self.joint_distr = joint_distr # Multidimensional histogram
self.Copula = Copula # Encodes rank marginal correlation of joint distribution
self.mutil_c = mutil_c # Marginal utility of consumption
self.P_H = P_H # Transition matrix for macro states (not including distribution)
def StateReduc(self):
"""
input
-----
self: dict, stored results from a StE
output
------
Newly generated
===============
X_ss: ndarray, stacked states, including
Y_ss: ndarray, controls
Gamma_state: ndarray, marginal distributions of individual states
grid: ndarray, discrete grids
targets: ndarray, debt-to-GDP ratio or other desiderata
P_H: transition probability of
indexMUdct: ndarray, indices selected after dct operation on marginal utility of consumption
indexVKdct: ndarray, indices selected after dct operation on marginal value of capital
State: ndarray, dimension equal to reduced states
State_m: ndarray, dimension equal to reduced states
Contr: ndarray, dimension equal to reduced controls
Contr_m: ndarray, dimension equal to reduced controls
Passed down from the input
==========================
Copula: dict, grids and values
joint_distr: ndarray, nk x nm x nh
Output: dict, outputs from the model
par: dict, parameters of the theoretical model
mpar:dict, parameters of the numerical representation
aggrshock: string, type of aggregate shock used to purturb the StE
"""
# Inverse of CRRA on x for utility and marginal utility
invutil = lambda x : ((1-self.par['xi'])*x)**(1./(1-self.par['xi']))
invmutil = lambda x : (1./x)**(1./self.par['xi'])
# X=States
# Marg dist of liquid assets summing over pty and illiquid assets k
Xss=np.asmatrix(np.concatenate((np.sum(np.sum(self.joint_distr.copy(),axis=1),axis =1),
np.transpose(np.sum(np.sum(self.joint_distr.copy(),axis=0),axis=1)),# marg dist k
np.sum(np.sum(self.joint_distr.copy(),axis=1),axis=0), # marg dist pty (\approx income)
[np.log(self.par['RB'])],[ 0.]))).T # Given the constant interest rate
# Y="controls" (according to this literature's odd terminology)
# c = invmarg(marg(c)), so first bit gets consumption policy function
Yss=np.asmatrix(np.concatenate((invmutil(self.mutil_c.copy().flatten(order = 'F')),\
invmutil(self.Vk.copy().flatten(order = 'F')),
[np.log(self.par['Q'])], # Question: Price of the illiquid asset, right?
[ np.log(self.par['PI'])], # Inflation
[ np.log(self.Output)],
[np.log(self.par['G'])], # Gov spending
[np.log(self.par['W'])], # Wage
[np.log(self.par['R'])], # Nominal R
[np.log(self.par['PROFITS'])],
[np.log(self.par['N'])], # Hours worked
[np.log(self.targets['T'])], # Taxes
[np.log(self.grid['K'])], # Kapital
[np.log(self.targets['B'])]))).T # Government debt
# Mapping for Histogram
# Gamma_state matrix reduced set of states
# nm = number of gridpoints for liquid assets
# nk = number of gridpoints for illiquid assets
# nh = number of gridpoints for human capital (pty)
Gamma_state = np.zeros( # Create zero matrix of size [nm + nk + nh,nm + nk + nh - 4]
(self.mpar['nm']+self.mpar['nk']+self.mpar['nh'],
self.mpar['nm']+self.mpar['nk']+self.mpar['nh'] - 4))
# Question: Why 4? 4 = 3+1, 3: sum to 1 for m, k, h and 1: for entrepreneurs
# Impose adding-up conditions:
# In each of the block matrices, probabilities must add to 1
for j in range(self.mpar['nm']-1): # np.squeeze reduces one-dimensional matrix to vector
Gamma_state[0:self.mpar['nm'],j] = -np.squeeze(Xss[0:self.mpar['nm']])
Gamma_state[j,j]=1. - Xss[j] #
Gamma_state[j,j]=Gamma_state[j,j] - np.sum(Gamma_state[0:self.mpar['nm'],j])
bb = self.mpar['nm'] # Question: bb='bottom base'? because bb shorter to type than self.mpar['nm'] everywhere
for j in range(self.mpar['nk']-1):
Gamma_state[bb+np.arange(0,self.mpar['nk'],1), bb+j-1] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nk'],1)])
Gamma_state[bb+j,bb-1+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-1+j] = (Gamma_state[bb+j,bb-1+j] -
np.sum(Gamma_state[bb+np.arange(0,self.mpar['nk']),bb-1+j]))
bb = self.mpar['nm'] + self.mpar['nk']
for j in range(self.mpar['nh']-2):
# Question: Why -2? 1 for h sum to 1 and 1 for entrepreneur Some other symmetry/adding-up condition.
Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1), bb+j-2] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nh']-1,1)])
Gamma_state[bb+j,bb-2+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-2+j] = Gamma_state[bb+j,bb-2+j] - np.sum(Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1),bb-2+j])
# Number of other state variables not including the gridded -- here, just the interest rate
self.mpar['os'] = len(Xss) - (self.mpar['nm']+self.mpar['nk']+self.mpar['nh'])
# For each gridpoint there are two "regular" controls: consumption and illiquid saving
# Counts the number of "other" controls (PROFITS, Q, etc)
self.mpar['oc'] = len(Yss) - 2*(self.mpar['nm']*self.mpar['nk']*self.mpar['nh'])
aggrshock = self.par['aggrshock']
accuracy = self.par['accuracy']
# Do the dct on the steady state marginal utility
# Returns an array of indices for the used basis vectors
indexMUdct = self.do_dct(invmutil(self.mutil_c.copy().flatten(order='F')),
self.mpar,accuracy)
# Do the dct on the steady state marginal value of capital
# Returns an array of indices for the used basis vectors
indexVKdct = self.do_dct(invmutil(self.Vk.copy()),self.mpar,accuracy)
# Calculate the numbers of states and controls
aux = np.shape(Gamma_state)
self.mpar['numstates'] = np.int64(aux[1] + self.mpar['os'])
self.mpar['numcontrols'] = np.int64(len(indexMUdct) +
len(indexVKdct) +
self.mpar['oc'])
# Size of the reduced matrices to be used in the Fsys
# Set to zero because in steady state they are zero
State = np.zeros((self.mpar['numstates'],1))
State_m = State
Contr = np.zeros((self.mpar['numcontrols'],1))
Contr_m = Contr
return {'Xss': Xss, 'Yss':Yss, 'Gamma_state': Gamma_state,
'par':self.par, 'mpar':self.mpar, 'aggrshock':aggrshock,
'Copula':self.Copula,'grid':self.grid,'targets':self.targets,'P_H':self.P_H,
'joint_distr': self.joint_distr, 'Output': self.Output, 'indexMUdct':indexMUdct, 'indexVKdct':indexVKdct,
'State':State, 'State_m':State_m, 'Contr':Contr, 'Contr_m':Contr_m}
# Discrete cosine transformation magic happens here
# sf is scipy.fftpack tool
def do_dct(self, obj, mpar, level):
"""
input
-----
obj: ndarray nm x nk x nh
dimension of states before dct
mpar: dict
parameters in the numerical representaion of the model, e.g. nm, nk and nh
level: float
accuracy level for dct
output
------
index_reduced: ndarray n_dct x 1
an array of indices that select the needed grids after dct
"""
obj = np.reshape(obj.copy(),(mpar['nm'],mpar['nk'],mpar['nh']),order='F')
X1 = sf.dct(obj,norm='ortho',axis=0) # dct is operated along three dimensions axis=0/1/2
X2 = sf.dct(X1.copy(),norm='ortho',axis=1)
X3 = sf.dct(X2.copy(),norm='ortho',axis=2)
# Pick the coefficients that are big
XX = X3.flatten(order='F')
ind = np.argsort(abs(XX.copy()))[::-1]
# i will
i = 1
# Sort from smallest (=best) to biggest (=worst)
# and count how many are 'good enough to keep'
while linalg.norm(XX[ind[:i]].copy())/linalg.norm(XX) < level:
i += 1
needed = i # Question:Isn't this counting the ones that are NOT needed?
index_reduced = np.sort(ind[:i]) # Retrieve the good
return index_reduced
# %% {"code_folding": []}
## Choose an aggregate shock to perturb(one of three shocks: MP, TFP, Uncertainty)
EX3SS['par']['aggrshock'] = 'MP'
EX3SS['par']['rhoS'] = 0.0 # Persistence of variance
EX3SS['par']['sigmaS'] = 0.001 # STD of variance shocks
#EX3SS['par']['aggrshock'] = 'TFP'
#EX3SS['par']['rhoS'] = 0.95
#EX3SS['par']['sigmaS'] = 0.0075
#EX3SS['par']['aggrshock'] = 'Uncertainty'
#EX3SS['par']['rhoS'] = 0.84 # Persistence of variance
#EX3SS['par']['sigmaS'] = 0.54 # STD of variance shocks
# %% {"code_folding": []}
## Choose an accuracy of approximation with DCT
### Determines number of basis functions chosen -- enough to match this accuracy
### EX3SS is precomputed steady-state pulled in above
EX3SS['par']['accuracy'] = 0.99999
# %% {"code_folding": []}
## Implement state reduction and DCT
### Do state reduction on steady state
EX3SR=StateReduc_Dct(**EX3SS) # Takes StE result as input and get ready to invoke state reduction operation
SR=EX3SR.StateReduc() # StateReduc is operated
# %% {"code_folding": [0]}
# Measuring the effectiveness of the state reduction
print('What are the results from the state reduction?')
#print('Newly added attributes after the operation include \n'+str(set(SR.keys())-set(EX3SS.keys())))
print('\n')
print('To achieve an accuracy of '+str(EX3SS['par']['accuracy'])+'\n')
print('The dimension of the policy functions is reduced to '+str(SR['indexMUdct'].shape[0]) \
+' from '+str(EX3SS['mpar']['nm']*EX3SS['mpar']['nk']*EX3SS['mpar']['nh'])
)
print('The dimension of the marginal value functions is reduced to '+str(SR['indexVKdct'].shape[0]) \
+ ' from ' + str(EX3SS['Vk'].shape))
print('The total number of control variables is '+str(SR['Contr'].shape[0])+'='+str(SR['indexMUdct'].shape[0]) + \
'+'+str(SR['indexVKdct'].shape[0])+'+ # of other macro controls')
print('\n')
print('The copula represents the joint distribution with a vector of size '+str(SR['Gamma_state'].shape) )
print('The dimension of states including exogenous state, is ' +str(SR['Xss'].shape[0]))
print('It simply stacks all grids of different\
\n state variables regardless of their joint distributions.\
\n This is due to the assumption that the rank order remains the same.')
print('The total number of state variables is '+str(SR['State'].shape[0]) + '='+\
str(SR['Gamma_state'].shape[1])+'+ the number of macro states (like the interest rate)')
# %% [markdown]
# ### Graphical Illustration
#
# #### Policy/value functions
#
# Taking the consumption function as an example, we plot consumption by adjusters and non-adjusters over a range of $k$ and $m$ that encompasses x percent of the mass of the distribution function.
#
# We plot the functions for the top and bottom values of the wage $h$ distribution
#
# %% {"code_folding": []}
## Graphical illustration
xi = EX3SS['par']['xi']
invmutil = lambda x : (1./x)**(1./xi)
### convert marginal utilities back to consumption function
mut_StE = EX3SS['mutil_c']
mut_n_StE = EX3SS['mutil_c_n'] # marginal utility of non-adjusters
mut_a_StE = EX3SS['mutil_c_a'] # marginal utility of adjusters
c_StE = invmutil(mut_StE)
cn_StE = invmutil(mut_n_StE)
ca_StE = invmutil(mut_a_StE)
### grid values
dim_StE = mut_StE.shape
mgrid = EX3SS['grid']['m']
kgrid = EX3SS['grid']['k']
hgrid = EX3SS['grid']['h']
# %% {"code_folding": []}
## define some functions to be used next
def dct3d(x):
x0=sf.dct(x.copy(),axis=0,norm='ortho')
x1=sf.dct(x0.copy(),axis=1,norm='ortho')
x2=sf.dct(x1.copy(),axis=2,norm='ortho')
return x2
def idct3d(x):
x2 = sf.idct(x.copy(),axis=2,norm='ortho')
x1 = sf.idct(x2.copy(),axis=1,norm='ortho')
x0 = sf.idct(x1.copy(),axis=0,norm='ortho')
return x0
def DCTApprox(fullgrids,dct_index):
dim=fullgrids.shape
dctcoefs = dct3d(fullgrids)
dctcoefs_rdc = np.zeros(dim)
dctcoefs_rdc[dct_index]=dctcoefs[dct_index]
approxgrids = idct3d(dctcoefs_rdc)
return approxgrids
# %% [markdown]
# Depending on the accuracy level, the DCT operation choses the necessary number of basis functions used to approximate consumption function at the full grids. This is illustrated in the p31-p34 in this [slides](https://www.dropbox.com/s/46fdxh0aphazm71/presentation_method.pdf?dl=0). We show this for both 1-dimensional (m or k) or 2-dimenstional grids (m and k) in the following.
# %% {"code_folding": []}
## 2D graph of consumption function: c(m) fixing k and h
## list of accuracy levels
Accuracy_BL = 0.99999 # From BL
Accuracy_Less0 = 0.999
Accuracy_Less1 = 0.99
Accuracy_Less2 = 0.95
acc_lst = np.array([Accuracy_BL,Accuracy_Less0,Accuracy_Less1,Accuracy_Less2])
## c(m) fixing k and h
fig = plt.figure(figsize=(8,8))
fig.suptitle('c at full grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing k and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp) # Takes StE result as input and get ready to invoke state reduction operation
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
# choose the fix grid of h and k
hgrid_fix=2 # fix level of h as an example
kgrid_fix=10 # fix level of k as an example
# get the corresponding c function approximated by dct
cVec = c_a_approx_cp[:,kgrid_fix,hgrid_fix]
## plots
ax = fig.add_subplot(2,2,idx+1)
ax.plot(mgrid,cVec,label='c approximated by DCT')
ax.plot(mgrid,ca_StE[:,kgrid_fix,hgrid_fix],'--',label='c at full grids')
ax.plot(mgrid,cVec,'r*')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel(r'$c(m)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
# %% {"code_folding": []}
## 2D graph of consumption function: c(k) fixing m and h
fig = plt.figure(figsize=(8,8))
fig.suptitle('c at full grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing m and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp) # Takes StE result as input and get ready to invoke state reduction operation
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp= SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
# choose the fix grid of h and m
hgrid_fix=2 # fix level of h as an example
mgrid_fix=10 # fix level of k as an example
# get the corresponding c function approximated by dct
cVec = c_n_approx_cp[mgrid_fix,:,hgrid_fix]
## plots
ax = fig.add_subplot(2,2,idx+1)
ax.plot(kgrid,cVec,label='c approximated by DCT')
ax.plot(kgrid,cn_StE[mgrid_fix,:,hgrid_fix],'--',label='c at full grids')
ax.plot(kgrid,cVec,'r*')
ax.set_xlabel('k',fontsize=13)
ax.set_ylabel(r'$c(k)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
# %% {"code_folding": []}
# Restore the solution corresponding to the original BL accuracy
EX3SS['par']['accuracy'] = Accuracy_BL
EX3SR=StateReduc_Dct(**EX3SS) # Takes StE result as input and get ready to invoke state reduction operation
SR=EX3SR.StateReduc() # StateReduc is operated
## indexMUdct is one dimension, needs to be unraveled to 3 dimensions
mut_rdc_idx_flt = SR['indexMUdct']
mut_rdc_idx = np.unravel_index(mut_rdc_idx_flt,dim_StE,order='F')
nb_dct = len(mut_StE.flatten())
mut_rdc_bool = np.zeros(nb_dct) # boolean array of 30 x 30 x 4
for i in range(nb_dct):
mut_rdc_bool[i]=i in list(SR['indexMUdct'])
mut_rdc_bool_3d = (mut_rdc_bool==1).reshape(dim_StE)
mut_rdc_mask_3d = (mut_rdc_bool).reshape(dim_StE)
# Get the joint distribution calculated elsewhere
joint_distr = EX3SS['joint_distr']
marginal_mk = EX3SS['joint_distr'].sum(axis=2)
# Location at which to cut off the topmost part of the distributions
mass_pct = 0.9
## Again, for BL accuracy level, get dct compressed c functions at all grids
c_n_approx = DCTApprox(cn_StE,mut_rdc_idx)
c_a_approx = DCTApprox(ca_StE,mut_rdc_idx)
# %% {"code_folding": []}
# 3D surface plots of consumption function at full grids and approximated by DCT
## at all grids and grids after dct first for non-adjusters and then for adjusters
## for non-adjusters
## full grids now
## WangTao:
## After plotting for the entire set of gridpoints, next plot only for the bottom mass_pct of the distributions
mmgrid,kkgrid = np.meshgrid(mgrid,kgrid)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of non-adjusters at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,cn_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): non-adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 100)
# %% {"code_folding": []}
## Same thing in a different way: image plots of c functions at full grids and c approximated by DCT
## for non-adjusters
## full grids
mmgrid,kkgrid = np.meshgrid(mgrid,kgrid)
### for adjusters
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of non-adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1)
ax.imshow(np.hstack((cn_StE[:,:,hgrid_fix],c_n_approx[:,:,hgrid_fix])))
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
# %% {"code_folding": []}
## 3D scatter plots of the difference of full-grid c and approximated c
## for non-adjusters
## full grids
mmgrid,kkgrid = np.meshgrid(mgrid,kgrid)
### for adjusters
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of non-adjusters at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
cn_diff = c_n_approx-cn_StE
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.coolwarm, edgecolor='none',
label='Difference of full-grid and approximated consumption function')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 40)
# %% {"code_folding": []}
# Difference of full-grid c and DCT compressed c for difference levels of accuracy
fig = plt.figure(figsize=(14,14))
fig.suptitle('Differences of c at full grids and c approximated by DCT in different accuracy levels(non-adjusters)',
fontsize=(13))
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp) # Takes StE result as input and get ready to invoke state reduction operation
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=1 # fix level of h as an example
## plots
ax = fig.add_subplot(2,2,idx+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff_cp[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.summer, edgecolor='none',
label='Difference of full-grid and approximated consumption functions')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel('Difference of c functions',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_zlim([-8,2])
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.view_init(10, 60)
# %% {"code_folding": []}
# for adjusters
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):adjuster')
ax.plot_surface(mmgrid,kkgrid,ca_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
#ax.set_xlim([0,mmax])
#ax.set_ylim([0,kmax])
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 150)
# %% {"code_folding": []}
# Compare consumption functions of adjusters and non-adjusters approximated by DCT
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters (yellow)/non-adjusters (blue) at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],cmap=cm.winter,
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],cmap=cm.autumn,
label='StE(after dct):adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim(0,mmax)
#ax.set_ylim(0,kmax)
ax.view_init(20, 60)
# %% {"code_folding": []}
## the differences of c functions of adjusters and non-adjusters approximated by DCT.
c_diff_approx=c_n_approx-c_a_approx
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters/non-adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## prepare the reduced grids
hgrid_fix=hgrid_id
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_diff_approx[:,:,hgrid_fix],cmap=cm.coolwarm,
label='StE(after dct):difference of non-adjuster and adjusters')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)-c_a(m,k)$',fontsize=12)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim(0,mmax)
#ax.set_ylim(0,kmax)
ax.view_init(20, 80)
# %% [markdown]
# ##### Observation
#
# - For a given grid value of productivity, the remaining grid points after DCT to represent the whole consumption function are concentrated in low values of $k$ and $m$. This is because the slopes of the surfaces of marginal utility are changing the most in these regions. For larger values of $k$ and $m$ the functions become smooth and only slightly concave, so they can be represented by many fewer points
# - For different grid values of productivity (2 sub plots), the numbers of grid points in the DCT operation differ. From the lowest to highest values of productivity, there are 78, 33, 25 and 18 grid points, respectively. They add up to the total number of gridpoints of 154 after DCT operation, as we noted above for marginal utility function.
# %% [markdown]
# #### Distribution of states
#
# - We first plot the distribution of $k$ fixing $m$ and $h$. Next, we plot the joint distribution of $m$ and $k$ only fixing $h$ in 3-dimenstional space.
# - The joint-distribution can be represented by marginal distributions of $m$, $k$ and $h$ and a copula that describes the correlation between the three states. The former is straightfoward. We plot the copula only. The copula is essentially a multivariate cummulative distribution function where each marginal is uniform. (Translation from the uniform to the appropriate nonuniform distribution is handled at a separate stage).
#
# %% {"code_folding": []}
### Marginalize along h grids
joint_distr = EX3SS['joint_distr']
joint_distr_km = EX3SS['joint_distr'].sum(axis=2)
### Plot distributions in 2 dimensional graph
fig = plt.figure(figsize=(10,10))
plt.suptitle('Marginal distribution of k at different m')
for hgrid_id in range(EX3SS['mpar']['nh']):
ax = plt.subplot(2,2,hgrid_id+1)
ax.set_title(r'$h({})$'.format(hgrid_id))
ax.set_xlabel('k',size=12)
for id in range(EX3SS['mpar']['nm']):
ax.plot(kgrid,joint_distr[id,:,hgrid_id])
# %% {"code_folding": []}
## Plot joint distribution of k and m in 3d graph
fig = plt.figure(figsize=(14,14))
fig.suptitle('Joint distribution of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,joint_distr[:,:,hgrid_fix], rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
plt.gca().invert_yaxis()
#ax.set_zlabel(r'$p(m,k)$',fontsize=10)
ax.set_title(r'$h({})$'.format(hgrid_id))
ax.set_xlim(0,400)
ax.view_init(20, 40)
# %% [markdown]
# Notice the CDFs in StE copula have 4 modes, corresponding to the number of $h$ gridpoints. Each of the four parts of the cdf is a joint-distribution of $m$ and $k$. It can be presented in 3-dimensional graph as below.
# %% {"code_folding": []}
## Plot the copula
cdf=EX3SS['Copula']['value'].reshape(4,30,30) # important: 4,30,30 not 30,30,4?
fig = plt.figure(figsize=(14,14))
fig.suptitle('Copula of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
## plots
ax = fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cdf[hgrid_id,:,:], rstride=1, cstride=1,
cmap='viridis', edgecolor='None')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_id))
## for each h grid, take the 95% mass of m and k as the maximum of the m and k axis
marginal_mk = joint_distr[:,:,hgrid_id]
marginal_m = marginal_mk.sum(axis=0)
marginal_k = marginal_mk.sum(axis=1)
mmax = mgrid[(np.abs(marginal_m.cumsum()-mass_pct*marginal_m.cumsum().max())).argmin()]
kmax = kgrid[(np.abs(marginal_k.cumsum()-mass_pct*marginal_k.cumsum().max())).argmin()]
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
#ax.set_xlim(0,mmax)
#ax.set_ylim(0,kmax)
ax.view_init(30, 60)
# %% [markdown]
# # To Do:
#
# 1. Plot the _difference_ in the _approximation errors_ for adjusters and nonadjusters
# 1. Make color or transparency be determined by the population density from the copula
# 1. Make extra versions of the figures where the color is determined by the population density at that location (given by the copula)
# 1. Differences _between_ adjusters and nonadjusters in consumption are not interesting and should be deleted
# 1. Eliminate "magic numbers"
# 1. Improve comments so a new reader can understand what is being done
# %% [markdown]
# Given the assumption that the copula remains the same after aggregate risk is introduced, we can use the same copula and the marginal distributions to recover the full joint-distribution of the states.
# %% [markdown]
# ### Summary: what do we achieve after the transformation?
#
# - Using the DCT, the dimension of the policy and value functions are reduced from 3600 to 154 and 94, respectively.
# - By marginalizing the joint distribution with the fixed copula assumption, the marginal distribution is of dimension 64 compared to its joint distribution of a dimension of 3600.
#
#
#
| 46.392405 | 769 | 0.670646 |
lse:
return False
except NameError:
return False
if in_ipynb():
get_ipython().run_line_magic('matplotlib', 'inline')
else:
get_ipython().run_line_magic('matplotlib', 'auto')
import sys
import os
my_file_path = os.path.dirname(os.path.abspath("TwoAsset.ipynb"))
code_dir = os.path.join(my_file_path, "BayerLuetticke_code/TwoAssetCode")
sys.path.insert(0, code_dir)
sys.path.insert(0, my_file_path)
import pickle
os.chdir(code_dir)
ese are all constructed from the same exogenous grids:')
print(str(len(EX3SS['grid']['m']))+' gridpoints for liquid assets;')
print(str(len(EX3SS['grid']['k']))+' gridpoints for illiquid assets;')
print(str(len(EX3SS['grid']['h']))+' gridpoints for individual productivity.')
print('')
print('Therefore, the joint distribution is of size: ')
print(str(EX3SS['mpar']['nm'])+
' * '+str(EX3SS['mpar']['nk'])+
' * '+str(EX3SS['mpar']['nh'])+
' = '+ str(EX3SS['mpar']['nm']*EX3SS['mpar']['nk']*EX3SS['mpar']['nh']))
# %% [markdown]
# ### Dimension Reduction
#
# The authors use different dimensionality reduction methods for the consumer's problem and the distribution across idiosyncratic states
ls are likely to have identical or very similar colors, so we need only to find an efficient way to represent how the colors _change_ from one pixel to nearby ones. Similarly, consumption at a given point $s_{i}$ is likely to be close to consumption point at another point $s_{j}$ that is "close" in the state space (similar wealth, income, etc), so a function that captures that similarity efficiently can preserve most of the information without keeping all of the points.
#
# Like linear interpolation, the [DCT transformation](https://en.wikipedia.org/wiki/Discrete_cosine_transform) is a method of representing a continuous function using a finite set of numbers. It uses a set of independent [basis functions](https://en.wikipedia.org/wiki/Basis_function) to do this.
#
# But it turns out that some of those basis functions are much more important than others in representing the steady-state functions. Dimension reduction is accomplished by basically ignoring all basis functions that make "small enough" contributions to the representation of the function.
#
# ##### When might this go wrong?
#
# Suppose the consumption function changes in a recession in ways that change behavior radically at some states. Like, suppose unemployment almost never happens in steady state, but it can happen in temporary recessions. Suppose further that, even for employed people, in a recession, _worries_ about unemployment cause many of them to prudently withdraw some of their illiquid assets -- behavior opposite of what people in the same state would be doing during expansions. In that case, the basis functions that represented the steady state function would have had no incentive to be able to represent well the part of the space that is never seen in steady state, so any functions that might help do so might well have been dropped in the dimension reduction stage.
#
# On the whole, it seems unlikely that this kind of thing is a major problem, because the vast majority of the variation that people experience is idiosyncratic. There is always unemployment, for example; it just moves up and down a bit with aggregate shocks, but since the experience of unemployment is in fact well represented in the steady state the method should have no trouble capturing it.
#
# Where the method might have more trouble is in representing economies in which there are multiple equilibria in which behavior is quite different.
# %% [markdown]
# #### For the distribution of agents across states: Copula
#
# The other tool the authors use is the ["copula"](https://en.wikipedia.org/wiki/Copula_(probability_theory)), which allows us to represent the distribution of people across idiosyncratic states efficiently
#
# The copula is computed from the joint distribution of states in StE and will be used to transform the [marginal distributions](https://en.wikipedia.org/wiki/Marginal_distribution) back to joint distributions. (For an illustration of how the assumptions used when modeling asset price distributions using copulas can fail see [Salmon](https://www.wired.com/2009/02/wp-quant/))
#
# * A copula is a representation of the joint distribution expressed using a mapping between the uniform joint CDF and the marginal distributions of the variables
#
# * The crucial assumption is that what aggregate shocks do is to squeeze or distort the steady state distribution, but leave the rank structure of the distribution the same
# * An example of when this might not hold is the following. Suppose that in expansions, the people at the top of the distribution of illiquid assets (the top 1 percent, say) are also at the top 1 percent of liquid assets. But in recessions the bottom 99 percent get angry at the top 1 percent of illiquid asset holders and confiscate part of their liquid assets (the illiquid assets can't be confiscated quickly because they are illiquid). Now the people in the top 99 percent of illiquid assets might be in the _bottom_ 1 percent of liquid assets.
print('The copula consists of two parts: gridpoints and values at those gridpoints:'+ \
'\n gridpoints have dimensionality of '+str(EX3SS['Copula']['grid'].shape) + \
'\n where the first element is total number of gridpoints' + \
'\n and the second element is number of idiosyncratic state variables' + \
'\n whose values also are of dimension of '+str(EX3SS['Copula']['value'].shape[0]) + \
'\n each entry of which is the probability that all three of the'
'\n state variables are below the corresponding point.')
nt_function
import sys
sys.path.insert(0,'../')
import numpy as np
from numpy.linalg import matrix_rank
import scipy as sc
from scipy.stats import norm
from scipy.interpolate import interp1d, interp2d, griddata, RegularGridInterpolator, interpn
import multiprocessing as mp
from multiprocessing import Pool, cpu_count, Process
from math import ceil
import math as mt
from scipy import sparse as sp
from scipy import linalg
from math import log, cos, pi, sqrt
import time
from SharedFunc3 import Transition, ExTransitions, GenWeight, MakeGridkm, Tauchen, Fastroot
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import scipy.io
import scipy.fftpack as sf
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
import seaborn as sns
import copy as cp
par, mpar, grid, Output, targets, Vm, Vk,
joint_distr, Copula, c_n_guess, c_a_guess, psi_guess,
m_n_star, m_a_star, cap_a_star, mutil_c_n, mutil_c_a,mutil_c, P_H):
self.par = par
self.mpar = mpar
self.grid = grid
self.Output = Output
self.targets = targets
self.Vm = Vm
self.Vk = Vk
self.joint_distr = joint_distr
self.Copula = Copula
self.mutil_c = mutil_c
self.P_H = P_H
def StateReduc(self):
invutil = lambda x : ((1-self.par['xi'])*x)**(1./(1-self.par['xi']))
invmutil = lambda x : (1./x)**(1./self.par['xi'])
Xss=np.asmatrix(np.concatenate((np.sum(np.sum(self.joint_distr.copy(),axis=1),axis =1),
np.transpose(np.sum(np.sum(self.joint_distr.copy(),axis=0),axis=1)),
np.sum(np.sum(self.joint_distr.copy(),axis=1),axis=0),
[np.log(self.par['RB'])],[ 0.]))).T
# c = invmarg(marg(c)), so first bit gets consumption policy function
Yss=np.asmatrix(np.concatenate((invmutil(self.mutil_c.copy().flatten(order = 'F')),\
invmutil(self.Vk.copy().flatten(order = 'F')),
[np.log(self.par['Q'])], # Question: Price of the illiquid asset, right?
[ np.log(self.par['PI'])], # Inflation
[ np.log(self.Output)],
[np.log(self.par['G'])], # Gov spending
[np.log(self.par['W'])], # Wage
[np.log(self.par['R'])], # Nominal R
[np.log(self.par['PROFITS'])],
[np.log(self.par['N'])], # Hours worked
[np.log(self.targets['T'])], # Taxes
[np.log(self.grid['K'])], # Kapital
[np.log(self.targets['B'])]))).T # Government debt
# Mapping for Histogram
# Gamma_state matrix reduced set of states
# nm = number of gridpoints for liquid assets
# nk = number of gridpoints for illiquid assets
# nh = number of gridpoints for human capital (pty)
Gamma_state = np.zeros( # Create zero matrix of size [nm + nk + nh,nm + nk + nh - 4]
(self.mpar['nm']+self.mpar['nk']+self.mpar['nh'],
self.mpar['nm']+self.mpar['nk']+self.mpar['nh'] - 4))
# Question: Why 4? 4 = 3+1, 3: sum to 1 for m, k, h and 1: for entrepreneurs
# Impose adding-up conditions:
# In each of the block matrices, probabilities must add to 1
for j in range(self.mpar['nm']-1): # np.squeeze reduces one-dimensional matrix to vector
Gamma_state[0:self.mpar['nm'],j] = -np.squeeze(Xss[0:self.mpar['nm']])
Gamma_state[j,j]=1. - Xss[j] #
Gamma_state[j,j]=Gamma_state[j,j] - np.sum(Gamma_state[0:self.mpar['nm'],j])
bb = self.mpar['nm'] # Question: bb='bottom base'? because bb shorter to type than self.mpar['nm'] everywhere
for j in range(self.mpar['nk']-1):
Gamma_state[bb+np.arange(0,self.mpar['nk'],1), bb+j-1] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nk'],1)])
Gamma_state[bb+j,bb-1+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-1+j] = (Gamma_state[bb+j,bb-1+j] -
np.sum(Gamma_state[bb+np.arange(0,self.mpar['nk']),bb-1+j]))
bb = self.mpar['nm'] + self.mpar['nk']
for j in range(self.mpar['nh']-2):
# Question: Why -2? 1 for h sum to 1 and 1 for entrepreneur Some other symmetry/adding-up condition.
Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1), bb+j-2] = -np.squeeze(Xss[bb+np.arange(0,self.mpar['nh']-1,1)])
Gamma_state[bb+j,bb-2+j] = 1. - Xss[bb+j]
Gamma_state[bb+j,bb-2+j] = Gamma_state[bb+j,bb-2+j] - np.sum(Gamma_state[bb+np.arange(0,self.mpar['nh']-1,1),bb-2+j])
# Number of other state variables not including the gridded -- here, just the interest rate
self.mpar['os'] = len(Xss) - (self.mpar['nm']+self.mpar['nk']+self.mpar['nh'])
# For each gridpoint there are two "regular" controls: consumption and illiquid saving
# Counts the number of "other" controls (PROFITS, Q, etc)
self.mpar['oc'] = len(Yss) - 2*(self.mpar['nm']*self.mpar['nk']*self.mpar['nh'])
aggrshock = self.par['aggrshock']
accuracy = self.par['accuracy']
# Do the dct on the steady state marginal utility
# Returns an array of indices for the used basis vectors
indexMUdct = self.do_dct(invmutil(self.mutil_c.copy().flatten(order='F')),
self.mpar,accuracy)
# Do the dct on the steady state marginal value of capital
# Returns an array of indices for the used basis vectors
indexVKdct = self.do_dct(invmutil(self.Vk.copy()),self.mpar,accuracy)
# Calculate the numbers of states and controls
aux = np.shape(Gamma_state)
self.mpar['numstates'] = np.int64(aux[1] + self.mpar['os'])
self.mpar['numcontrols'] = np.int64(len(indexMUdct) +
len(indexVKdct) +
self.mpar['oc'])
# Size of the reduced matrices to be used in the Fsys
# Set to zero because in steady state they are zero
State = np.zeros((self.mpar['numstates'],1))
State_m = State
Contr = np.zeros((self.mpar['numcontrols'],1))
Contr_m = Contr
return {'Xss': Xss, 'Yss':Yss, 'Gamma_state': Gamma_state,
'par':self.par, 'mpar':self.mpar, 'aggrshock':aggrshock,
'Copula':self.Copula,'grid':self.grid,'targets':self.targets,'P_H':self.P_H,
'joint_distr': self.joint_distr, 'Output': self.Output, 'indexMUdct':indexMUdct, 'indexVKdct':indexVKdct,
'State':State, 'State_m':State_m, 'Contr':Contr, 'Contr_m':Contr_m}
# Discrete cosine transformation magic happens here
# sf is scipy.fftpack tool
def do_dct(self, obj, mpar, level):
obj = np.reshape(obj.copy(),(mpar['nm'],mpar['nk'],mpar['nh']),order='F')
X1 = sf.dct(obj,norm='ortho',axis=0) # dct is operated along three dimensions axis=0/1/2
X2 = sf.dct(X1.copy(),norm='ortho',axis=1)
X3 = sf.dct(X2.copy(),norm='ortho',axis=2)
# Pick the coefficients that are big
XX = X3.flatten(order='F')
ind = np.argsort(abs(XX.copy()))[::-1]
# i will
i = 1
# Sort from smallest (=best) to biggest (=worst)
# and count how many are 'good enough to keep'
while linalg.norm(XX[ind[:i]].copy())/linalg.norm(XX) < level:
i += 1
needed = i # Question:Isn't this counting the ones that are NOT needed?
index_reduced = np.sort(ind[:i])
return index_reduced
EX3SS['par']['sigmaS'] = 0.001
n of the marginal value functions is reduced to '+str(SR['indexVKdct'].shape[0]) \
+ ' from ' + str(EX3SS['Vk'].shape))
print('The total number of control variables is '+str(SR['Contr'].shape[0])+'='+str(SR['indexMUdct'].shape[0]) + \
'+'+str(SR['indexVKdct'].shape[0])+'+ # of other macro controls')
print('\n')
print('The copula represents the joint distribution with a vector of size '+str(SR['Gamma_state'].shape) )
print('The dimension of states including exogenous state, is ' +str(SR['Xss'].shape[0]))
print('It simply stacks all grids of different\
\n state variables regardless of their joint distributions.\
\n This is due to the assumption that the rank order remains the same.')
print('The total number of state variables is '+str(SR['State'].shape[0]) + '='+\
str(SR['Gamma_state'].shape[1])+'+ the number of macro states (like the interest rate)')
id = EX3SS['grid']['h']
axis=0,norm='ortho')
x1=sf.dct(x0.copy(),axis=1,norm='ortho')
x2=sf.dct(x1.copy(),axis=2,norm='ortho')
return x2
def idct3d(x):
x2 = sf.idct(x.copy(),axis=2,norm='ortho')
x1 = sf.idct(x2.copy(),axis=1,norm='ortho')
x0 = sf.idct(x1.copy(),axis=0,norm='ortho')
return x0
def DCTApprox(fullgrids,dct_index):
dim=fullgrids.shape
dctcoefs = dct3d(fullgrids)
dctcoefs_rdc = np.zeros(dim)
dctcoefs_rdc[dct_index]=dctcoefs[dct_index]
approxgrids = idct3d(dctcoefs_rdc)
return approxgrids
y_Less2 = 0.95
acc_lst = np.array([Accuracy_BL,Accuracy_Less0,Accuracy_Less1,Accuracy_Less2])
size=(8,8))
fig.suptitle('c at full grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing k and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp)
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=2
kgrid_fix=10
cVec = c_a_approx_cp[:,kgrid_fix,hgrid_fix]
= fig.add_subplot(2,2,idx+1)
ax.plot(mgrid,cVec,label='c approximated by DCT')
ax.plot(mgrid,ca_StE[:,kgrid_fix,hgrid_fix],'--',label='c at full grids')
ax.plot(mgrid,cVec,'r*')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel(r'$c(m)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
ll grids and c approximated by DCT in different accuracy levels'
'\n non-adjusters, fixing m and h',
fontsize=(13))
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=0.3)
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp)
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp= SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=2
mgrid_fix=10
cVec = c_n_approx_cp[mgrid_fix,:,hgrid_fix]
= fig.add_subplot(2,2,idx+1)
ax.plot(kgrid,cVec,label='c approximated by DCT')
ax.plot(kgrid,cn_StE[mgrid_fix,:,hgrid_fix],'--',label='c at full grids')
ax.plot(kgrid,cVec,'r*')
ax.set_xlabel('k',fontsize=13)
ax.set_ylabel(r'$c(k)$',fontsize=13)
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.legend(loc=0)
EX3SS['par']['accuracy'] = Accuracy_BL
EX3SR=StateReduc_Dct(**EX3SS)
SR=EX3SR.StateReduc()
ut_rdc_idx_flt,dim_StE,order='F')
nb_dct = len(mut_StE.flatten())
mut_rdc_bool = np.zeros(nb_dct)
for i in range(nb_dct):
mut_rdc_bool[i]=i in list(SR['indexMUdct'])
mut_rdc_bool_3d = (mut_rdc_bool==1).reshape(dim_StE)
mut_rdc_mask_3d = (mut_rdc_bool).reshape(dim_StE)
joint_distr = EX3SS['joint_distr']
marginal_mk = EX3SS['joint_distr'].sum(axis=2)
mass_pct = 0.9
ut_rdc_idx)
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,cn_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): non-adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 100)
t h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1)
ax.imshow(np.hstack((cn_StE[:,:,hgrid_fix],c_n_approx[:,:,hgrid_fix])))
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
ints of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
cn_diff = c_n_approx-cn_StE
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.coolwarm, edgecolor='none',
label='Difference of full-grid and approximated consumption function')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 40)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Differences of c at full grids and c approximated by DCT in different accuracy levels(non-adjusters)',
fontsize=(13))
for idx in range(len(acc_lst)):
EX3SS_cp =cp.deepcopy(EX3SS)
EX3SS_cp['par']['accuracy'] = acc_lst[idx]
EX3SR_cp=StateReduc_Dct(**EX3SS_cp)
SR_cp=EX3SR_cp.StateReduc()
mut_rdc_idx_flt_cp = SR_cp['indexMUdct']
mut_rdc_idx_cp = np.unravel_index(mut_rdc_idx_flt_cp,dim_StE,order='F')
nb_bf_cp = len(mut_rdc_idx_cp[0])
print(str(nb_bf_cp) +" basis functions used.")
c_n_approx_cp = DCTApprox(cn_StE,mut_rdc_idx_cp)
c_a_approx_cp = DCTApprox(ca_StE,mut_rdc_idx_cp)
cn_diff_cp = c_n_approx_cp-cn_StE
hgrid_fix=1
= fig.add_subplot(2,2,idx+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cn_diff_cp[:,:,hgrid_fix], rstride=1,
cstride=1,cmap=cm.summer, edgecolor='none',
label='Difference of full-grid and approximated consumption functions')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel('Difference of c functions',fontsize=13)
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.set_zlim([-8,2])
ax.set_title(r'accuracy=${}$'.format(acc_lst[idx]))
ax.view_init(10, 60)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.scatter(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],marker='v',color='red',
label='StE(after dct):adjuster')
ax.plot_surface(mmgrid,kkgrid,ca_StE[:,:,hgrid_fix],cmap='Blues',
label='StE(before dct): adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
plt.gca().invert_yaxis()
ax.set_title(r'$h({})$'.format(hgrid_fix))
ax.view_init(20, 150)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Consumption of adjusters (yellow)/non-adjusters (blue) at grid points of m and k (for each h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_n_approx[:,:,hgrid_fix],cmap=cm.winter,
label='StE(after dct):non-adjuster')
ax.plot_surface(mmgrid,kkgrid,c_a_approx[:,:,hgrid_fix],cmap=cm.autumn,
label='StE(after dct):adjuster')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_a(m,k)$',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.view_init(20, 60)
e('Consumption of adjusters/non-adjusters at grid points of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,c_diff_approx[:,:,hgrid_fix],cmap=cm.coolwarm,
label='StE(after dct):difference of non-adjuster and adjusters')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_zlabel(r'$c_n(m,k)-c_a(m,k)$',fontsize=12)
ax.set_title(r'$h({})$'.format(hgrid_fix))
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.view_init(20, 80)
ax.set_xlabel('k',size=12)
for id in range(EX3SS['mpar']['nm']):
ax.plot(kgrid,joint_distr[id,:,hgrid_id])
('Joint distribution of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,joint_distr[:,:,hgrid_fix], rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
plt.gca().invert_yaxis()
ax.set_title(r'$h({})$'.format(hgrid_id))
ax.set_xlim(0,400)
ax.view_init(20, 40)
a']['value'].reshape(4,30,30)
fig = plt.figure(figsize=(14,14))
fig.suptitle('Copula of m and k(for different h)',
fontsize=(13))
for hgrid_id in range(EX3SS['mpar']['nh']):
= fig.add_subplot(2,2,hgrid_id+1, projection='3d')
ax.plot_surface(mmgrid,kkgrid,cdf[hgrid_id,:,:], rstride=1, cstride=1,
cmap='viridis', edgecolor='None')
ax.set_xlabel('m',fontsize=13)
ax.set_ylabel('k',fontsize=13)
ax.set_title(r'$h({})$'.format(hgrid_id))
axis=0)
marginal_k = marginal_mk.sum(axis=1)
mmax = mgrid[(np.abs(marginal_m.cumsum()-mass_pct*marginal_m.cumsum().max())).argmin()]
kmax = kgrid[(np.abs(marginal_k.cumsum()-mass_pct*marginal_k.cumsum().max())).argmin()]
plt.gca().invert_yaxis()
plt.gca().invert_xaxis()
ax.view_init(30, 60)
| true | true |
f7280032dc7383b07665e3f89cd4ed34380fc45e | 146 | py | Python | 20180609/python_lines_04_with.py | bijitchakraborty12/MyProjects01 | 503af4cd6e8fa0576add7ac64393f1b4a16456c7 | [
"MIT"
] | null | null | null | 20180609/python_lines_04_with.py | bijitchakraborty12/MyProjects01 | 503af4cd6e8fa0576add7ac64393f1b4a16456c7 | [
"MIT"
] | null | null | null | 20180609/python_lines_04_with.py | bijitchakraborty12/MyProjects01 | 503af4cd6e8fa0576add7ac64393f1b4a16456c7 | [
"MIT"
] | null | null | null |
with open('C:\\Python Practice\\MyProjects01\\MyProjects01\\20180609\\poem_01.txt') as f:
for k in f.readlines():
print(k.strip().split())
| 18.25 | 89 | 0.684932 |
with open('C:\\Python Practice\\MyProjects01\\MyProjects01\\20180609\\poem_01.txt') as f:
for k in f.readlines():
print(k.strip().split())
| true | true |
f728009e660bb4cab8c59f04834fb694b6e46262 | 16,687 | py | Python | espnet2/bin/enh_inference.py | arceushui/Keyword-Spotting-Alibaba | 10e718491075dee8f875c7860385bc4eef22a790 | [
"Apache-2.0"
] | null | null | null | espnet2/bin/enh_inference.py | arceushui/Keyword-Spotting-Alibaba | 10e718491075dee8f875c7860385bc4eef22a790 | [
"Apache-2.0"
] | null | null | null | espnet2/bin/enh_inference.py | arceushui/Keyword-Spotting-Alibaba | 10e718491075dee8f875c7860385bc4eef22a790 | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python3
import argparse
import logging
from pathlib import Path
import sys
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import humanfriendly
import numpy as np
import torch
from tqdm import trange
from typeguard import check_argument_types
from espnet.utils.cli_utils import get_commandline_args
from espnet2.fileio.sound_scp import SoundScpWriter
from espnet2.tasks.enh import EnhancementTask
from espnet2.torch_utils.device_funcs import to_device
from espnet2.torch_utils.set_all_random_seed import set_all_random_seed
from espnet2.utils import config_argparse
from espnet2.utils.types import str2bool
from espnet2.utils.types import str2triple_str
from espnet2.utils.types import str_or_none
EPS = torch.finfo(torch.get_default_dtype()).eps
class SeparateSpeech:
"""SeparateSpeech class
Examples:
>>> import soundfile
>>> separate_speech = SeparateSpeech("enh_config.yml", "enh.pth")
>>> audio, rate = soundfile.read("speech.wav")
>>> separate_speech(audio)
[separated_audio1, separated_audio2, ...]
"""
def __init__(
self,
enh_train_config: Union[Path, str],
enh_model_file: Union[Path, str] = None,
segment_size: Optional[float] = None,
hop_size: Optional[float] = None,
normalize_segment_scale: bool = False,
show_progressbar: bool = False,
ref_channel: Optional[int] = None,
normalize_output_wav: bool = False,
device: str = "cpu",
dtype: str = "float32",
):
assert check_argument_types()
# 1. Build Enh model
enh_model, enh_train_args = EnhancementTask.build_model_from_file(
enh_train_config, enh_model_file, device
)
enh_model.to(dtype=getattr(torch, dtype)).eval()
self.device = device
self.dtype = dtype
self.enh_train_args = enh_train_args
self.enh_model = enh_model
# only used when processing long speech, i.e.
# segment_size is not None and hop_size is not None
self.segment_size = segment_size
self.hop_size = hop_size
self.normalize_segment_scale = normalize_segment_scale
self.normalize_output_wav = normalize_output_wav
self.show_progressbar = show_progressbar
self.num_spk = enh_model.num_spk
task = "enhancement" if self.num_spk == 1 else "separation"
# reference channel for processing multi-channel speech
if ref_channel is not None:
logging.info(
"Overwrite enh_model.separator.ref_channel with {}".format(ref_channel)
)
enh_model.separator.ref_channel = ref_channel
self.ref_channel = ref_channel
else:
self.ref_channel = enh_model.ref_channel
self.segmenting = segment_size is not None and hop_size is not None
if self.segmenting:
logging.info("Perform segment-wise speech %s" % task)
logging.info(
"Segment length = {} sec, hop length = {} sec".format(
segment_size, hop_size
)
)
else:
logging.info("Perform direct speech %s on the input" % task)
@torch.no_grad()
def __call__(
self, speech_mix: Union[torch.Tensor, np.ndarray], fs: int = 8000
) -> List[torch.Tensor]:
"""Inference
Args:
speech_mix: Input speech data (Batch, Nsamples [, Channels])
fs: sample rate
Returns:
[separated_audio1, separated_audio2, ...]
"""
assert check_argument_types()
# Input as audio signal
if isinstance(speech_mix, np.ndarray):
speech_mix = torch.as_tensor(speech_mix)
assert speech_mix.dim() > 1, speech_mix.size()
batch_size = speech_mix.size(0)
speech_mix = speech_mix.to(getattr(torch, self.dtype))
# lenghts: (B,)
lengths = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=speech_mix.size(1)
)
# a. To device
speech_mix = to_device(speech_mix, device=self.device)
lengths = to_device(lengths, device=self.device)
if self.segmenting and lengths[0] > self.segment_size * fs:
# Segment-wise speech enhancement/separation
overlap_length = int(np.round(fs * (self.segment_size - self.hop_size)))
num_segments = int(
np.ceil((speech_mix.size(1) - overlap_length) / (self.hop_size * fs))
)
t = T = int(self.segment_size * fs)
pad_shape = speech_mix[:, :T].shape
enh_waves = []
range_ = trange if self.show_progressbar else range
for i in range_(num_segments):
st = int(i * self.hop_size * fs)
en = st + T
if en >= lengths[0]:
# en - st < T (last segment)
en = lengths[0]
speech_seg = speech_mix.new_zeros(pad_shape)
t = en - st
speech_seg[:, :t] = speech_mix[:, st:en]
else:
t = T
speech_seg = speech_mix[:, st:en] # B x T [x C]
lengths_seg = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=T
)
# b. Enhancement/Separation Forward
feats, f_lens = self.enh_model.encoder(speech_seg, lengths_seg)
feats, _, _ = self.enh_model.separator(feats, f_lens)
processed_wav = [
self.enh_model.decoder(f, lengths_seg)[0] for f in feats
]
if speech_seg.dim() > 2:
# multi-channel speech
speech_seg_ = speech_seg[:, self.ref_channel]
else:
speech_seg_ = speech_seg
if self.normalize_segment_scale:
# normalize the energy of each separated stream
# to match the input energy
processed_wav = [
self.normalize_scale(w, speech_seg_) for w in processed_wav
]
# List[torch.Tensor(num_spk, B, T)]
enh_waves.append(torch.stack(processed_wav, dim=0))
# c. Stitch the enhanced segments together
waves = enh_waves[0]
for i in range(1, num_segments):
# permutation between separated streams in last and current segments
perm = self.cal_permumation(
waves[:, :, -overlap_length:],
enh_waves[i][:, :, :overlap_length],
criterion="si_snr",
)
# repermute separated streams in current segment
for batch in range(batch_size):
enh_waves[i][:, batch] = enh_waves[i][perm[batch], batch]
if i == num_segments - 1:
enh_waves[i][:, :, t:] = 0
enh_waves_res_i = enh_waves[i][:, :, overlap_length:t]
else:
enh_waves_res_i = enh_waves[i][:, :, overlap_length:]
# overlap-and-add (average over the overlapped part)
waves[:, :, -overlap_length:] = (
waves[:, :, -overlap_length:] + enh_waves[i][:, :, :overlap_length]
) / 2
# concatenate the residual parts of the later segment
waves = torch.cat([waves, enh_waves_res_i], dim=2)
# ensure the stitched length is same as input
assert waves.size(2) == speech_mix.size(1), (waves.shape, speech_mix.shape)
waves = torch.unbind(waves, dim=0)
else:
# b. Enhancement/Separation Forward
feats, f_lens = self.enh_model.encoder(speech_mix, lengths)
feats, _, _ = self.enh_model.separator(feats, f_lens)
waves = [self.enh_model.decoder(f, lengths)[0] for f in feats]
assert len(waves) == self.num_spk, len(waves) == self.num_spk
assert len(waves[0]) == batch_size, (len(waves[0]), batch_size)
if self.normalize_output_wav:
waves = [
(w / abs(w).max(dim=1, keepdim=True)[0] * 0.9).cpu().numpy()
for w in waves
] # list[(batch, sample)]
else:
waves = [w.cpu().numpy() for w in waves]
return waves
@staticmethod
@torch.no_grad()
def normalize_scale(enh_wav, ref_ch_wav):
"""Normalize the energy of enh_wav to match that of ref_ch_wav.
Args:
enh_wav (torch.Tensor): (B, Nsamples)
ref_ch_wav (torch.Tensor): (B, Nsamples)
Returns:
enh_wav (torch.Tensor): (B, Nsamples)
"""
ref_energy = torch.sqrt(torch.mean(ref_ch_wav.pow(2), dim=1))
enh_energy = torch.sqrt(torch.mean(enh_wav.pow(2), dim=1))
return enh_wav * (ref_energy / enh_energy)[:, None]
@torch.no_grad()
def cal_permumation(self, ref_wavs, enh_wavs, criterion="si_snr"):
"""Calculate the permutation between seaprated streams in two adjacent segments.
Args:
ref_wavs (List[torch.Tensor]): [(Batch, Nsamples)]
enh_wavs (List[torch.Tensor]): [(Batch, Nsamples)]
criterion (str): one of ("si_snr", "mse", "corr)
Returns:
perm (torch.Tensor): permutation for enh_wavs (Batch, num_spk)
"""
loss_func = {
"si_snr": self.enh_model.si_snr_loss,
"mse": lambda enh, ref: torch.mean((enh - ref).pow(2), dim=1),
"corr": lambda enh, ref: (
(enh * ref).sum(dim=1)
/ (enh.pow(2).sum(dim=1) * ref.pow(2).sum(dim=1) + EPS)
).clamp(min=EPS, max=1 - EPS),
}[criterion]
_, perm = self.enh_model._permutation_loss(ref_wavs, enh_wavs, loss_func)
return perm
def humanfriendly_or_none(value: str):
if value in ("none", "None", "NONE"):
return None
return humanfriendly.parse_size(value)
def inference(
output_dir: str,
batch_size: int,
dtype: str,
fs: int,
ngpu: int,
seed: int,
num_workers: int,
log_level: Union[int, str],
data_path_and_name_and_type: Sequence[Tuple[str, str, str]],
key_file: Optional[str],
enh_train_config: str,
enh_model_file: str,
allow_variable_data_keys: bool,
segment_size: Optional[float],
hop_size: Optional[float],
normalize_segment_scale: bool,
show_progressbar: bool,
ref_channel: Optional[int],
normalize_output_wav: bool,
):
assert check_argument_types()
if batch_size > 1:
raise NotImplementedError("batch decoding is not implemented")
if ngpu > 1:
raise NotImplementedError("only single GPU decoding is supported")
logging.basicConfig(
level=log_level,
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
)
if ngpu >= 1:
device = "cuda"
else:
device = "cpu"
# 1. Set random-seed
set_all_random_seed(seed)
# 2. Build separate_speech
separate_speech = SeparateSpeech(
enh_train_config=enh_train_config,
enh_model_file=enh_model_file,
segment_size=segment_size,
hop_size=hop_size,
normalize_segment_scale=normalize_segment_scale,
show_progressbar=show_progressbar,
ref_channel=ref_channel,
normalize_output_wav=normalize_output_wav,
device=device,
dtype=dtype,
)
# 3. Build data-iterator
loader = EnhancementTask.build_streaming_iterator(
data_path_and_name_and_type,
dtype=dtype,
batch_size=batch_size,
key_file=key_file,
num_workers=num_workers,
preprocess_fn=EnhancementTask.build_preprocess_fn(
separate_speech.enh_train_args, False
),
collate_fn=EnhancementTask.build_collate_fn(
separate_speech.enh_train_args, False
),
allow_variable_data_keys=allow_variable_data_keys,
inference=True,
)
# 4. Start for-loop
writers = []
for i in range(separate_speech.num_spk):
writers.append(
SoundScpWriter(f"{output_dir}/wavs/{i + 1}", f"{output_dir}/spk{i + 1}.scp")
)
for keys, batch in loader:
assert isinstance(batch, dict), type(batch)
assert all(isinstance(s, str) for s in keys), keys
_bs = len(next(iter(batch.values())))
assert len(keys) == _bs, f"{len(keys)} != {_bs}"
batch = {k: v for k, v in batch.items() if not k.endswith("_lengths")}
waves = separate_speech(**batch)
for (spk, w) in enumerate(waves):
for b in range(batch_size):
writers[spk][keys[b]] = fs, w[b]
print(w[b],file=sys.stderr)
for writer in writers:
writer.close()
def get_parser():
parser = config_argparse.ArgumentParser(
description="Frontend inference",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# Note(kamo): Use '_' instead of '-' as separator.
# '-' is confusing if written in yaml.
parser.add_argument(
"--log_level",
type=lambda x: x.upper(),
default="INFO",
choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
help="The verbose level of logging",
)
parser.add_argument("--output_dir", type=str, required=True)
parser.add_argument(
"--ngpu",
type=int,
default=0,
help="The number of gpus. 0 indicates CPU mode",
)
parser.add_argument("--seed", type=int, default=0, help="Random seed")
parser.add_argument(
"--dtype",
default="float32",
choices=["float16", "float32", "float64"],
help="Data type",
)
parser.add_argument(
"--fs", type=humanfriendly_or_none, default=8000, help="Sampling rate"
)
parser.add_argument(
"--num_workers",
type=int,
default=1,
help="The number of workers used for DataLoader",
)
group = parser.add_argument_group("Input data related")
group.add_argument(
"--data_path_and_name_and_type",
type=str2triple_str,
required=True,
action="append",
)
group.add_argument("--key_file", type=str_or_none)
group.add_argument("--allow_variable_data_keys", type=str2bool, default=False)
group = parser.add_argument_group("Output data related")
group.add_argument(
"--normalize_output_wav",
type=str2bool,
default=False,
help="Whether to normalize the predicted wav to [-1~1]",
)
group = parser.add_argument_group("The model configuration related")
group.add_argument("--enh_train_config", type=str, required=True)
group.add_argument("--enh_model_file", type=str, required=True)
group = parser.add_argument_group("Data loading related")
group.add_argument(
"--batch_size",
type=int,
default=1,
help="The batch size for inference",
)
group = parser.add_argument_group("SeparateSpeech related")
group.add_argument(
"--segment_size",
type=float,
default=None,
help="Segment length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--hop_size",
type=float,
default=None,
help="Hop length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--normalize_segment_scale",
type=str2bool,
default=False,
help="Whether to normalize the energy of the separated streams in each segment",
)
group.add_argument(
"--show_progressbar",
type=str2bool,
default=False,
help="Whether to show a progress bar when performing segment-wise speech "
"enhancement/separation",
)
group.add_argument(
"--ref_channel",
type=int,
default=None,
help="If not None, this will overwrite the ref_channel defined in the "
"separator module (for multi-channel speech processing)",
)
return parser
def main(cmd=None):
print(get_commandline_args(), file=sys.stderr)
parser = get_parser()
args = parser.parse_args(cmd)
kwargs = vars(args)
kwargs.pop("config", None)
inference(**kwargs)
if __name__ == "__main__":
main()
| 34.620332 | 88 | 0.597231 |
import argparse
import logging
from pathlib import Path
import sys
from typing import List
from typing import Optional
from typing import Sequence
from typing import Tuple
from typing import Union
import humanfriendly
import numpy as np
import torch
from tqdm import trange
from typeguard import check_argument_types
from espnet.utils.cli_utils import get_commandline_args
from espnet2.fileio.sound_scp import SoundScpWriter
from espnet2.tasks.enh import EnhancementTask
from espnet2.torch_utils.device_funcs import to_device
from espnet2.torch_utils.set_all_random_seed import set_all_random_seed
from espnet2.utils import config_argparse
from espnet2.utils.types import str2bool
from espnet2.utils.types import str2triple_str
from espnet2.utils.types import str_or_none
EPS = torch.finfo(torch.get_default_dtype()).eps
class SeparateSpeech:
def __init__(
self,
enh_train_config: Union[Path, str],
enh_model_file: Union[Path, str] = None,
segment_size: Optional[float] = None,
hop_size: Optional[float] = None,
normalize_segment_scale: bool = False,
show_progressbar: bool = False,
ref_channel: Optional[int] = None,
normalize_output_wav: bool = False,
device: str = "cpu",
dtype: str = "float32",
):
assert check_argument_types()
enh_model, enh_train_args = EnhancementTask.build_model_from_file(
enh_train_config, enh_model_file, device
)
enh_model.to(dtype=getattr(torch, dtype)).eval()
self.device = device
self.dtype = dtype
self.enh_train_args = enh_train_args
self.enh_model = enh_model
self.segment_size = segment_size
self.hop_size = hop_size
self.normalize_segment_scale = normalize_segment_scale
self.normalize_output_wav = normalize_output_wav
self.show_progressbar = show_progressbar
self.num_spk = enh_model.num_spk
task = "enhancement" if self.num_spk == 1 else "separation"
if ref_channel is not None:
logging.info(
"Overwrite enh_model.separator.ref_channel with {}".format(ref_channel)
)
enh_model.separator.ref_channel = ref_channel
self.ref_channel = ref_channel
else:
self.ref_channel = enh_model.ref_channel
self.segmenting = segment_size is not None and hop_size is not None
if self.segmenting:
logging.info("Perform segment-wise speech %s" % task)
logging.info(
"Segment length = {} sec, hop length = {} sec".format(
segment_size, hop_size
)
)
else:
logging.info("Perform direct speech %s on the input" % task)
@torch.no_grad()
def __call__(
self, speech_mix: Union[torch.Tensor, np.ndarray], fs: int = 8000
) -> List[torch.Tensor]:
assert check_argument_types()
if isinstance(speech_mix, np.ndarray):
speech_mix = torch.as_tensor(speech_mix)
assert speech_mix.dim() > 1, speech_mix.size()
batch_size = speech_mix.size(0)
speech_mix = speech_mix.to(getattr(torch, self.dtype))
lengths = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=speech_mix.size(1)
)
speech_mix = to_device(speech_mix, device=self.device)
lengths = to_device(lengths, device=self.device)
if self.segmenting and lengths[0] > self.segment_size * fs:
overlap_length = int(np.round(fs * (self.segment_size - self.hop_size)))
num_segments = int(
np.ceil((speech_mix.size(1) - overlap_length) / (self.hop_size * fs))
)
t = T = int(self.segment_size * fs)
pad_shape = speech_mix[:, :T].shape
enh_waves = []
range_ = trange if self.show_progressbar else range
for i in range_(num_segments):
st = int(i * self.hop_size * fs)
en = st + T
if en >= lengths[0]:
en = lengths[0]
speech_seg = speech_mix.new_zeros(pad_shape)
t = en - st
speech_seg[:, :t] = speech_mix[:, st:en]
else:
t = T
speech_seg = speech_mix[:, st:en]
lengths_seg = speech_mix.new_full(
[batch_size], dtype=torch.long, fill_value=T
)
feats, f_lens = self.enh_model.encoder(speech_seg, lengths_seg)
feats, _, _ = self.enh_model.separator(feats, f_lens)
processed_wav = [
self.enh_model.decoder(f, lengths_seg)[0] for f in feats
]
if speech_seg.dim() > 2:
speech_seg_ = speech_seg[:, self.ref_channel]
else:
speech_seg_ = speech_seg
if self.normalize_segment_scale:
processed_wav = [
self.normalize_scale(w, speech_seg_) for w in processed_wav
]
enh_waves.append(torch.stack(processed_wav, dim=0))
waves = enh_waves[0]
for i in range(1, num_segments):
perm = self.cal_permumation(
waves[:, :, -overlap_length:],
enh_waves[i][:, :, :overlap_length],
criterion="si_snr",
)
for batch in range(batch_size):
enh_waves[i][:, batch] = enh_waves[i][perm[batch], batch]
if i == num_segments - 1:
enh_waves[i][:, :, t:] = 0
enh_waves_res_i = enh_waves[i][:, :, overlap_length:t]
else:
enh_waves_res_i = enh_waves[i][:, :, overlap_length:]
waves[:, :, -overlap_length:] = (
waves[:, :, -overlap_length:] + enh_waves[i][:, :, :overlap_length]
) / 2
waves = torch.cat([waves, enh_waves_res_i], dim=2)
assert waves.size(2) == speech_mix.size(1), (waves.shape, speech_mix.shape)
waves = torch.unbind(waves, dim=0)
else:
feats, f_lens = self.enh_model.encoder(speech_mix, lengths)
feats, _, _ = self.enh_model.separator(feats, f_lens)
waves = [self.enh_model.decoder(f, lengths)[0] for f in feats]
assert len(waves) == self.num_spk, len(waves) == self.num_spk
assert len(waves[0]) == batch_size, (len(waves[0]), batch_size)
if self.normalize_output_wav:
waves = [
(w / abs(w).max(dim=1, keepdim=True)[0] * 0.9).cpu().numpy()
for w in waves
]
else:
waves = [w.cpu().numpy() for w in waves]
return waves
@staticmethod
@torch.no_grad()
def normalize_scale(enh_wav, ref_ch_wav):
ref_energy = torch.sqrt(torch.mean(ref_ch_wav.pow(2), dim=1))
enh_energy = torch.sqrt(torch.mean(enh_wav.pow(2), dim=1))
return enh_wav * (ref_energy / enh_energy)[:, None]
@torch.no_grad()
def cal_permumation(self, ref_wavs, enh_wavs, criterion="si_snr"):
loss_func = {
"si_snr": self.enh_model.si_snr_loss,
"mse": lambda enh, ref: torch.mean((enh - ref).pow(2), dim=1),
"corr": lambda enh, ref: (
(enh * ref).sum(dim=1)
/ (enh.pow(2).sum(dim=1) * ref.pow(2).sum(dim=1) + EPS)
).clamp(min=EPS, max=1 - EPS),
}[criterion]
_, perm = self.enh_model._permutation_loss(ref_wavs, enh_wavs, loss_func)
return perm
def humanfriendly_or_none(value: str):
if value in ("none", "None", "NONE"):
return None
return humanfriendly.parse_size(value)
def inference(
output_dir: str,
batch_size: int,
dtype: str,
fs: int,
ngpu: int,
seed: int,
num_workers: int,
log_level: Union[int, str],
data_path_and_name_and_type: Sequence[Tuple[str, str, str]],
key_file: Optional[str],
enh_train_config: str,
enh_model_file: str,
allow_variable_data_keys: bool,
segment_size: Optional[float],
hop_size: Optional[float],
normalize_segment_scale: bool,
show_progressbar: bool,
ref_channel: Optional[int],
normalize_output_wav: bool,
):
assert check_argument_types()
if batch_size > 1:
raise NotImplementedError("batch decoding is not implemented")
if ngpu > 1:
raise NotImplementedError("only single GPU decoding is supported")
logging.basicConfig(
level=log_level,
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
)
if ngpu >= 1:
device = "cuda"
else:
device = "cpu"
set_all_random_seed(seed)
separate_speech = SeparateSpeech(
enh_train_config=enh_train_config,
enh_model_file=enh_model_file,
segment_size=segment_size,
hop_size=hop_size,
normalize_segment_scale=normalize_segment_scale,
show_progressbar=show_progressbar,
ref_channel=ref_channel,
normalize_output_wav=normalize_output_wav,
device=device,
dtype=dtype,
)
loader = EnhancementTask.build_streaming_iterator(
data_path_and_name_and_type,
dtype=dtype,
batch_size=batch_size,
key_file=key_file,
num_workers=num_workers,
preprocess_fn=EnhancementTask.build_preprocess_fn(
separate_speech.enh_train_args, False
),
collate_fn=EnhancementTask.build_collate_fn(
separate_speech.enh_train_args, False
),
allow_variable_data_keys=allow_variable_data_keys,
inference=True,
)
writers = []
for i in range(separate_speech.num_spk):
writers.append(
SoundScpWriter(f"{output_dir}/wavs/{i + 1}", f"{output_dir}/spk{i + 1}.scp")
)
for keys, batch in loader:
assert isinstance(batch, dict), type(batch)
assert all(isinstance(s, str) for s in keys), keys
_bs = len(next(iter(batch.values())))
assert len(keys) == _bs, f"{len(keys)} != {_bs}"
batch = {k: v for k, v in batch.items() if not k.endswith("_lengths")}
waves = separate_speech(**batch)
for (spk, w) in enumerate(waves):
for b in range(batch_size):
writers[spk][keys[b]] = fs, w[b]
print(w[b],file=sys.stderr)
for writer in writers:
writer.close()
def get_parser():
parser = config_argparse.ArgumentParser(
description="Frontend inference",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--log_level",
type=lambda x: x.upper(),
default="INFO",
choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
help="The verbose level of logging",
)
parser.add_argument("--output_dir", type=str, required=True)
parser.add_argument(
"--ngpu",
type=int,
default=0,
help="The number of gpus. 0 indicates CPU mode",
)
parser.add_argument("--seed", type=int, default=0, help="Random seed")
parser.add_argument(
"--dtype",
default="float32",
choices=["float16", "float32", "float64"],
help="Data type",
)
parser.add_argument(
"--fs", type=humanfriendly_or_none, default=8000, help="Sampling rate"
)
parser.add_argument(
"--num_workers",
type=int,
default=1,
help="The number of workers used for DataLoader",
)
group = parser.add_argument_group("Input data related")
group.add_argument(
"--data_path_and_name_and_type",
type=str2triple_str,
required=True,
action="append",
)
group.add_argument("--key_file", type=str_or_none)
group.add_argument("--allow_variable_data_keys", type=str2bool, default=False)
group = parser.add_argument_group("Output data related")
group.add_argument(
"--normalize_output_wav",
type=str2bool,
default=False,
help="Whether to normalize the predicted wav to [-1~1]",
)
group = parser.add_argument_group("The model configuration related")
group.add_argument("--enh_train_config", type=str, required=True)
group.add_argument("--enh_model_file", type=str, required=True)
group = parser.add_argument_group("Data loading related")
group.add_argument(
"--batch_size",
type=int,
default=1,
help="The batch size for inference",
)
group = parser.add_argument_group("SeparateSpeech related")
group.add_argument(
"--segment_size",
type=float,
default=None,
help="Segment length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--hop_size",
type=float,
default=None,
help="Hop length in seconds for segment-wise speech enhancement/separation",
)
group.add_argument(
"--normalize_segment_scale",
type=str2bool,
default=False,
help="Whether to normalize the energy of the separated streams in each segment",
)
group.add_argument(
"--show_progressbar",
type=str2bool,
default=False,
help="Whether to show a progress bar when performing segment-wise speech "
"enhancement/separation",
)
group.add_argument(
"--ref_channel",
type=int,
default=None,
help="If not None, this will overwrite the ref_channel defined in the "
"separator module (for multi-channel speech processing)",
)
return parser
def main(cmd=None):
print(get_commandline_args(), file=sys.stderr)
parser = get_parser()
args = parser.parse_args(cmd)
kwargs = vars(args)
kwargs.pop("config", None)
inference(**kwargs)
if __name__ == "__main__":
main()
| true | true |
f7280122592f874c88490b185ae803033e4f575c | 2,254 | py | Python | webapp/python-web-multiple-browsers-test/WebappTest.py | elastest/demo-projects | d60fa75b98b3beccba28329e393392405727b492 | [
"Apache-2.0"
] | 3 | 2017-11-30T16:35:38.000Z | 2018-12-18T22:56:41.000Z | webapp/python-web-multiple-browsers-test/WebappTest.py | elastest/demo-projects | d60fa75b98b3beccba28329e393392405727b492 | [
"Apache-2.0"
] | 2 | 2018-12-06T07:58:52.000Z | 2020-12-04T17:21:28.000Z | webapp/python-web-multiple-browsers-test/WebappTest.py | elastest/demo-projects | d60fa75b98b3beccba28329e393392405727b492 | [
"Apache-2.0"
] | 6 | 2018-01-08T11:10:54.000Z | 2019-09-06T07:11:29.000Z | import unittest
import os
import sys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import xmlrunner
import ElasTestBase
class TestWebApp(ElasTestBase.ElasTestBase):
def test_check_title_and_body_not_empty(self):
driver = ElasTestBase.driver
try:
time.sleep(2)
addRow(driver, '', '')
time.sleep(2)
title = getElementById(driver, 'title').text
body = getElementById(driver, 'body').text
print 'Checking Message...'
self.assertNotEqual('', title)
self.assertNotEqual('', body)
except Exception as e:
clearData(driver)
sys.exit(1)
clearData(driver)
def test_find_title_and_body(self):
driver = ElasTestBase.driver
try:
time.sleep(2)
addRow(driver, 'MessageTitle', 'MessageBody')
time.sleep(2)
title = getElementById(driver, 'title').text
body = getElementById(driver, 'body').text
print 'Checking Message...'
self.assertEqual('MessageTitle', title)
self.assertEqual('MessageBody', body)
except Exception as e:
clearData(driver)
sys.exit(1)
clearData(driver)
def getElementById(driver, id, timeout=10):
wait = WebDriverWait(driver, timeout)
return wait.until(EC.presence_of_element_located((By.ID, id)))
def addRow(driver, title, body):
getElementById(driver, 'title-input').send_keys(title)
getElementById(driver, 'body-input').send_keys(body)
print 'Adding Message...'
getElementById(driver, 'submit').click()
def clearData(driver):
print 'Clearing Messages...'
getElementById(driver, 'clearSubmit').click()
if __name__ == '__main__':
file_path = './testresults'
if not os.path.exists(file_path):
os.makedirs(file_path)
file_name = file_path + '/results.xml'
with open(file_name, 'wb') as output:
unittest.main(
testRunner=xmlrunner.XMLTestRunner(output=output),
failfast=False, buffer=False, catchbreak=False)
| 29.657895 | 66 | 0.639752 | import unittest
import os
import sys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import xmlrunner
import ElasTestBase
class TestWebApp(ElasTestBase.ElasTestBase):
def test_check_title_and_body_not_empty(self):
driver = ElasTestBase.driver
try:
time.sleep(2)
addRow(driver, '', '')
time.sleep(2)
title = getElementById(driver, 'title').text
body = getElementById(driver, 'body').text
print 'Checking Message...'
self.assertNotEqual('', title)
self.assertNotEqual('', body)
except Exception as e:
clearData(driver)
sys.exit(1)
clearData(driver)
def test_find_title_and_body(self):
driver = ElasTestBase.driver
try:
time.sleep(2)
addRow(driver, 'MessageTitle', 'MessageBody')
time.sleep(2)
title = getElementById(driver, 'title').text
body = getElementById(driver, 'body').text
print 'Checking Message...'
self.assertEqual('MessageTitle', title)
self.assertEqual('MessageBody', body)
except Exception as e:
clearData(driver)
sys.exit(1)
clearData(driver)
def getElementById(driver, id, timeout=10):
wait = WebDriverWait(driver, timeout)
return wait.until(EC.presence_of_element_located((By.ID, id)))
def addRow(driver, title, body):
getElementById(driver, 'title-input').send_keys(title)
getElementById(driver, 'body-input').send_keys(body)
print 'Adding Message...'
getElementById(driver, 'submit').click()
def clearData(driver):
print 'Clearing Messages...'
getElementById(driver, 'clearSubmit').click()
if __name__ == '__main__':
file_path = './testresults'
if not os.path.exists(file_path):
os.makedirs(file_path)
file_name = file_path + '/results.xml'
with open(file_name, 'wb') as output:
unittest.main(
testRunner=xmlrunner.XMLTestRunner(output=output),
failfast=False, buffer=False, catchbreak=False)
| false | true |
f7280318fec0d22486693a1e350946abf99b5fec | 26,025 | py | Python | jade2/basic/structure/PythonPDB2.py | RosettaCommons/jade2 | 40affc7c4e0f1f6ee07030e72de284e3484946e7 | [
"BSD-3-Clause"
] | 1 | 2019-12-23T21:52:23.000Z | 2019-12-23T21:52:23.000Z | jade2/basic/structure/PythonPDB2.py | RosettaCommons/jade2 | 40affc7c4e0f1f6ee07030e72de284e3484946e7 | [
"BSD-3-Clause"
] | null | null | null | jade2/basic/structure/PythonPDB2.py | RosettaCommons/jade2 | 40affc7c4e0f1f6ee07030e72de284e3484946e7 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T18:59:03.000Z | 2021-01-28T18:59:03.000Z |
## @author Jared Adolf-Bryfogle (jadolfbr@gmail.com)
#Python Imports
import copy
import pandas
import re, logging
from collections import defaultdict
from typing import Union, DefaultDict, List, Any, Dict
from pathlib import Path
from jade2.basic.path import *
class PythonPDB2:
def __init__(self, pdb_file_path: Union[str, Path] = ""):
"""
Lightweight PDB class specifically for manipulating pdbs in scripts and simple apps as well as obtaining subsets of data in the PDB.
2.0 Uses a vector of dictionaries as main pdb_map for easier manipulation of the pdb_map.
Notes:
Not Meant to be fast - written for ease of use!
ALL elements of the pdb_map data are stored as strings!
"""
self.elements = ("id", "atom_number", "atom_name", "alternate_location", \
"three_letter_code", "chain", "residue_number", "i_code", "x", "y", "z", \
"occupancy", "b_factor", "element", "charge")
self.pdb_file_path = str(pdb_file_path)
self.pdb_map: List[DefaultDict[str, str]] = [] #[int line]:[string element]:[string value]
self.header: List[str] = [] #Unparsed header, but the data is held here as a list of strings. - Everything NOT ATOM or HETATM is here
self.remarks: List[str] = [] #Only REMARK lines as strings
if pdb_file_path:
self.read_pdb_into_map()
else:
logging.info("Loading blank PythonPDB")
def set_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
self.pdb_map = pdb_map
####################################################################
# Getters + PDB_Map Subsets
#
#
def get_pdb_map(self) -> List[DefaultDict[str, str]]:
return self.pdb_map
def get_dataframe(self) -> pandas.DataFrame:
"""
Get the PDB Map as a dataframe dataframe
"""
return pandas.DataFrame(self.pdb_map)
def get_header(self) -> List[str]:
"""
Get 'header' of PDB as list of strings
"""
return self.header
def get_remarks(self) -> List[str]:
"""
Get 'REMARK' lines of PDB as a list of strings
"""
return self.remarks
def add_remark(self, remark: str):
remark = "REMARK "+remark
self.remarks.append(remark)
def get_chain(self, chain) -> List[DefaultDict[str, str]]:
"""
Get Chain data as pdb_map subset
"""
chain_data = []
for dat in self.pdb_map:
if dat["chain"] == chain:
chain_data.append(dat)
return chain_data
def rename_chain(self, old_chain, new_chain):
for i in range(0, len(self.pdb_map) ):
#print("CHAIN :",self.pdb_map[i]["chain"],":")
if self.pdb_map[i]["chain"] == old_chain:
#print("Chain found. Attempting to change")
self.pdb_map[i]["chain"] = new_chain
def get_waters(self) -> List[DefaultDict[str, str]]:
"""
Get water data as pdb_map subset
"""
water_data = []
for dat in self.pdb_map:
if dat["three_letter_code"] in ["HOH","TP3","TP5","TIP3","TIP5"]:
water_data.append(dat)
return water_data
def get_hetatms(self) -> List[DefaultDict[str, str]]:
"""
Get hetatm data as pdb_map subset
"""
het_data = []
for dat in self.pdb_map:
if dat["id"] == "HETATM":
het_data.append(dat)
return het_data
def get_bb_data(self) -> List[DefaultDict[str, str]]:
"""
Get pdb_map subset of only N, CA, and C atoms
"""
bb_data = []
for dat in self.pdb_map:
if dat["atom_name"] in ["N", "CA", "C"]:
bb_data.append(dat)
return bb_data
def get_all_residues_of_type(self, name3: str) -> List[DefaultDict[str, str]]:
"""
Get PDB_Map subset of all residues of specific type
"""
res_data = []
for dat in self.pdb_map:
if dat["three_letter_code"] == name3:
res_data.append(dat)
return res_data
def get_residue(self, resnum: int, chain: str, icode: str= "") -> List[DefaultDict[str, str]]:
"""
Get PDB_Map subset of a specific residue
"""
residue = []
for dat in self.pdb_map:
if dat["residue_number"] == str(resnum) and dat["chain"] == chain and dat["icode"] == "":
residue.append(dat)
return residue
####################################################################
# Main
#
#
def read_pdb_into_map(self):
"""
Reads PDB file path into a basic PDB map. All data is held as strings.
"""
FILE = open_file(self.pdb_file_path, 'r')
i = 0
for line in FILE:
line = line.strip()
line = line.strip('\n')
if not line: continue
if re.search("REMARK", line[0:6]):
self.remarks.append(line)
elif (re.search("END", line[0:6]) or re.search("TER", line[0:6])):
#We ignore END and TER for now.
pass
elif (re.search("ATOM", line[0:6]) or re.search("HETATM", line[0:6])):
self.pdb_map.append(defaultdict())
self.pdb_map[i]["id"]=line[0:6].strip()
self.pdb_map[i]["atom_number"]=line[6:11].strip(); self.pdb_map[i]["atom_name"] = line[12:16]
self.pdb_map[i]["alternate_location"]=line[16]; self.pdb_map[i]["three_letter_code"] = line[17:21].strip()
self.pdb_map[i]["chain"] = line[21]; self.pdb_map[i]["residue_number"]= line[22:26].strip()
self.pdb_map[i]["i_code"] = line[26]; self.pdb_map[i]["x"] = line[27:38].strip()
self.pdb_map[i]["y"]= line[38:46].strip(); self.pdb_map[i]["z"]= line[46:54].strip()
self.pdb_map[i]["occupancy"] = line[54:60].strip(); self.pdb_map[i]["b_factor"]=line[60:66].strip()
self.pdb_map[i]["element"]=line[66:78].strip(); self.pdb_map[i]["charge"]=line[78:79].strip()
i +=1
elif (re.search("REMARK", line[0:6])):
self.remarks.append(line)
else:
self.header.append(line)
FILE.close()
def save_PDB(self, filename: Union[Path, str], output_remarks: bool = True, output_header: bool= True) -> Union[Path, str]:
"""
Uses a the pdb_map to save the data as a PDB file.
Returns the filename
"""
#global_variables.current_directory = os.path.dirname(filename)
FILE = open_file(filename, 'w')
if output_remarks:
for line in self.remarks:
FILE.write(line+"\n")
if output_header:
for line in self.header:
FILE.write(line+"\n")
for entry in self.pdb_map:
line = self.morph_line_in_pdb_map_to_pdb_line(entry)
FILE.write(line+"\n")
FILE.close()
print("PDB File Written...")
return filename
def morph_line_in_pdb_map_to_pdb_line(self, entry: DefaultDict[str, str]) -> str:
"""
Oh What fun. ;)
Magic Numbers?: (6,5,4,3,1,4,8,8,8,4,5);
"""
#Here we fix the formating of atom name. If we stripped the atom name.
"""
atom_name = self.pdb_map[line_num]['atom_name']
if len(atom_name)==1:
atom_name=' '+atom_name+' '
elif len(atom_name)==2:
#Note that 2 letter elements like CA (calcium) differ from CA (C-Alpha)
#If calcium, would go @column 13. if C-Alpha, column 14.
atom_name=' '+atom_name+' '
elif len(atom_name)==3:
atom_name=' '+atom_name
elif len(atom_name)==4:
atom_name=atom_name
else:
print "Atom Name missing. Inserting spaces."
atom_name = ' '
"""
#Create the PDB line.
line = (entry['id']).ljust(6)+ (entry['atom_number']).rjust(5)+" "+ entry['atom_name']+ \
(entry['alternate_location'])+ ((entry['three_letter_code']).rjust(3)).ljust(4)+ (entry['chain'])+ \
(entry['residue_number']).rjust(4)+ (entry['i_code']) + \
(entry['x']).rjust(11)+ (entry['y']).rjust(8)+ (entry['z']).rjust(8) + \
(entry['occupancy']).rjust(6)+ (entry['b_factor']).rjust(6)
#Note three letter code is wonky due to DA residues. ljust(4) was not working.
return line
##################
# Addition
#
#
def add_ca_residue(self, x: str, y: str, z: str, restype: str = "ALA", b_fac: float = 0, chain="X"):
"""
Add a residue to the map that is only CA
:param x:
:param y:
:param z:
:param restype:
:param b_fac:
:return: None
"""
pass
####################################################################
# Removal
#
#
def remove_antigen(self):
"""
Remove Antigen from an LH only PDB
"""
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["chain"] not in ['L', 'H']:
self.pdb_map.remove(dat)
def remove_chain(self, chain: str):
"""
Removes chain from pdb_map
"""
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["chain"]==chain:
self.pdb_map.remove(dat)
def remove_residue_type(self, name3: str):
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["three_letter_code"]==name3:
self.pdb_map.remove(dat)
def remove_hetatm_atoms(self):
temp_pdb_map = copy.deepcopy(self.pdb_map)
for dat in temp_pdb_map:
if dat["id"]=="HETATM":
self.pdb_map.remove(dat)
def remove_element_column(self):
"""
Removes the extra stuff in the element column, but not the element itself.
"""
for i in range(0, len(self.pdb_map)):
ele = self.pdb_map[i]["element"]
e = ele[11]
self.pdb_map[i]["element"]=" "+e
print("Extra stuff in Element Columns Removed")
return self.pdb_map
def remove_waters(self):
"""
Removes waters from pdb_map
"""
#codes = ["HOH","TP3","TP5","TIP3","TIP5"]
temp_pdb_map = copy.deepcopy(self.pdb_map) #This is to pop elements
for dat in temp_pdb_map:
if dat["three_letter_code"] in ["HOH","TP3","TP5","TIP3","TIP5"]:
#self.pdb_map.pop(num)
self.pdb_map.remove(dat)
def remove_alternate_residues(self):
"""
Removes any alternate residue codes and renumbers by renumbering from 1 and integrating any inserts.
"""
def get_residue_num(num): return int(self.pdb_map_copy[num]["residue_number"])
def set_residue_num(num, resnum): self.pdb_map[num]["residue_number"]=str(resnum)
def get_chain(num):return self.pdb_map_copy[num]["chain"]
def get_i_code(num):return self.pdb_map_copy[num]["i_code"]
def check_id(num):
if self.pdb_map_copy[num]['id']=="ATOM":
return True
else:
return False
def check_new_residue(old_num, num, insert_residue=False, pdb_map = False):
if insert_residue:
if get_i_code(old_num)==get_i_code(num):
return False
else:
return True
else:
if get_residue_num(old_num)==get_residue_num(num):
return False
else:
return True
def check_new_chain(old_num, num):
if get_chain(old_num)==get_chain(num):
return False
else:
return True
def check_insertion(num):
if not get_i_code(num)==" ":
return True
else:
return False
def renumber_from_one(chain_only, start_num):
resnum = 1
for num in sorted(chain_only):
insert = check_insertion(num)
#print repr(get_residue_num(num))+":"+repr(insert)
#This is so we don't check if it's a new residue with num-1 - Which won't actually be part of the chain!
if num==start_num:
set_residue_num(num, resnum)
#Iterate resnum if new residue
elif check_new_residue(num-1, num, insert):
resnum+=1
set_residue_num(num, resnum)
else:
set_residue_num(num, resnum)
#Set i code at the end, so we can tell if we have new residues or not.
for num in sorted(chain_only):
self.pdb_map[num]["i_code"]=" "
def renumber_from_insert(chain_only, start_num):
pass
self.pdb_map_copy = copy.deepcopy(self.pdb_map)
#Get chains with insertion codes - Now renumbers all chains. Will be an option later.
chains_with_inserts = dict();
for num in range(0, len(self.pdb_map)):
#if get_i_code(num)==" ":
chains_with_inserts[get_chain(num)]=True
#Iterate through all lines/atoms
#Initialize for scope
start_residue=0;
new_start=False
for chain in chains_with_inserts:
print("Renumbering chain "+chain)
chain_only=dict()
for num in range(0, len(self.pdb_map)):
if chain == get_chain(num) and check_id(num):
chain_only[num]=self.pdb_map[num]
lines = sorted(chain_only)
res_start = get_residue_num(lines[0])
renumber_from_one(chain_only, lines[0])
#For now, we only renumber from one.
#else:
#chain_only = renumber_from_insert(chain_only, lines[0])
####################################################################
# General Manipulation
#
#
def change_occupancy(self):
"""
Changes ALL occupancies in a PDB dictionary to 1.00
Returns PDB Dictionary.
"""
check = 0
for key in range(0, len(self.pdb_map)):
if self.pdb_map[key]["occupancy"].rfind("0.00")!=-1:
print("Changing occupancy of residue " + self.pdb_map[key]["residue_number"] + "To 1.00")
check =1
self.pdb_map[key]["occupancy"] = " 1.00"
if check ==1:
print("Occupancy Column OK for PyRosetta...")
def combine_pdb(self, py_pdb: 'PythonPDB2'):
"""
Combines pdb_map from instance of PyPDB to this one. Does not do any checks.
"""
m = py_pdb.get_pdb_map()
for dat in m:
self.pdb_map.append(dat)
def copy_chain_into_pdb_map(self, py_pdb: 'PythonPDB2', chain: str):
"""
Copies all data from one pdb_map of a py_pdb of a chain into the one held in this class. Useful for reordering chains.
"""
m = py_pdb.get_pdb_map()
for dat in m:
if dat["chain"] == chain:
self.pdb_map.append(dat)
def copy_all_but_chains_into_pdb_map(self, py_pdb:'PythonPDB2', chains):
"""
Copies all data from one pdb_map of a py_pdb of all data except the specified chains into this one. Useful for reordering chains.
"""
m = py_pdb.get_pdb_map()
for dat in m:
if not dat["chain"] in chains:
self.pdb_map.append(dat)
def combine_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
"""
Combines pdb_map passed with the PythonPDBs map
"""
for dat in pdb_map:
self.pdb_map.append(dat)
def pdb_alias(self, pairs: Dict[Any, Any], element: str):
"""
Replaces ALL occurances of old element with new from pair.
pair is a dictionary. In C++ it would be an array of pairs. [string old]:[string new]
For Specific functions, please see below.
"""
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num][element] == old:
self.pdb_map[num][element] = pairs[old]
def pdb_atom_alias(self, line_num: int, pair: Dict[Any, Any]):
"""
Replaces atom_names with ones Rosetta is happy with.
pair is a dictionary. In C++ it would be an array of pairs. [string MD atom_name]:[string rosetta atom_name]
"""
for start in pair:
if self.pdb_map[line_num]["atom_name"] == start:
print(self.pdb_map[line_num]["three_letter_code"] + ":" + self.pdb_map[line_num]["atom_name"] + ":" +
pair[start])
self.pdb_map[line_num]["atom_name"] = pair[start]
def pdb_residue_alias(self, pairs: Dict[Any, Any]):
"""
Replaces ALL occurances of old residue with new residue.
pair is a dictionary. In C++ it would be an array of pairs. [string old residue_name]:[string new residue_name]
"""
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["residue_name"] == old:
self.pdb_map[num]["residue_name"] = pairs[old]
def pdb_chain_alias(self, pairs: Dict[Any, Any]):
"""
Replaces ALL occurances of old chain with new chain.
pair is a dictionary. In C++ it would be an array of pairs. [string old chain]:[string new chain]
"""
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["chain"] == old:
self.pdb_map[num]["chain"] = pairs[old]
def clean_PDB(self):
"""
Removes HSD, Waters: Tries to fix atom and residue name inconsistencies.
HAS worked for changing a single MD pdb (NAMD) frame to Rosetta file.
PLEASE Expand if possible to alias all residues for Rosetta compatability.
NOT gaurenteed, but SHOULD work ok.
"""
self.RESIDUES_aliased = False; self.WATER_aliased=False; self.IONS_aliased=False; self.DNA_aliased = False
waters: List[DefaultDict[str, str]] = [] #List of data that have waters
print("Attempting to change residue names, atom names, and water")
for n in range(0, len(self.pdb_map)):
dat = self.pdb_map[n]
#print self.pdb_map[key]["three_letter_code"]
def alias_dna():
if dat["three_letter_code"]=="DA":
self.DNA_aliased=True
dat["three_letter_code"]="A"
elif dat["three_letter_code"]=="DT":
self.DNA_aliased=True
dat["three_letter_code"]="T"
elif dat["three_letter_code"]=="DC":
self.DNA_aliased=True
dat["three_letter_code"]="C"
elif dat["three_letter_code"]=="DG":
self.DNA_aliased=True
dat["three_letter_code"]="G"
else:
return
def alias_water():
if dat["three_letter_code"] in ["HOH", "TIP3", "WAT", "TIP5"]:
self.WATER_aliased=True
dat["three_letter_code"]="TP3" #IO_STRING for TP3 is WAT...Buy still reads TP#?
dat["id"]="HETATM"
waters.append(dat)
#def alias_ions():
#if self.pdb_map[key]["chain"]=="I":
#IONS_aliased= True
#self.pdb_map[key]["id"]="HETATM"
def alias_residues():
if dat["three_letter_code"] == "HSD":
self.RESIDUES_aliased = True
dat["three_letter_code"]="HIS"
def alias_atoms():
if dat["three_letter_code"]== "SER ":
atom_pairs = {" HG1":" HG "}
elif dat["three_letter_code"]=="ILE ":
atom_pairs = {" CD ":" CD1"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LEU ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="VAL ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LYS ":
atom_pairs = {" HZ1":" 1HZ", " HZ2":" 2HZ", " HZ3":" 3HZ"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ARG ":
atom_pairs = {" HH11":" 1HH1", " HH12":" 2HH1", " HH21":" 1HH2", " HH22":" 2HH2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ASN ":
atom_pairs = {"HD21":"1HD2", "HD22":"2HD2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="PRO ":
atom_pairs = {" OT1":" O ", " OT2":" OXT", " HD1":" 1HD", " HD2":" 2HD", " HB1":" 1HB", " HG1":" 1HG", " HG2":" 2HG"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
#Unnessessary, but organized.
alias_water()
#alias_ions()
#alias_residues()
alias_atoms()
alias_dna()
#Removes Waters. Keeps Ions.
#for key in waters:
#self.pdb_map.pop(key)
#Outputs what was found:
if self.RESIDUES_aliased:
print("Residues Changed")
if self.WATER_aliased:
print("Water found...changed to TP3. Remove to decrease calculation time.")
if self.IONS_aliased:
print("Ions found. Most are able to be read into Rosetta")
if self.DNA_aliased:
print("DNA found, changed to single letter code.")
####################################################################
# B Factor Replacements
#
#
def read_file_and_replace_b_factors(self, deliminator: str, filename: str, resnum_column: int=1, chain_column:int=2, data_column: int=3, atomname_column=False):
"""
This function reads a deliminated file with data and inserts the data into the BFactor column. Used to visualize arbitrary data.
Use function options to control which column the data is in as well as where your resnums and chains are located.
If atomname column is given, will insert by atom instead of by residue
"""
INFILE = open_file(filename, 'r')
for line in INFILE:
if line[0] == "#":continue
line = line.strip()
lineSP = line.split(deliminator)
if len(lineSP)<3:
print("Could not read line. Must have resnum, chain, and data columns")
continue
if not atomname_column:
self.replace_residue_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[data_column-1])
else:
if len(lineSP)<4:
print("Could not read line. Must have resnum, chain, atomname, and data columns")
continue
self.replace_atom_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[atomname_column-1], lineSP[data_column-1])
INFILE.close()
def replace_residue_b_factor(self, resnum: int, chain: str, data: float):
"""
Replaces the b factor of each atom in the residue with data.
Can be all string representations or not.
"""
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data) #In case data is an integer.
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
def replace_atom_b_factor(self, resnum: int, chain: str, atomname: str, data: float):
"""
Replaces the b factor of an atom.
Can be all string representations or not.
"""
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data)
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain) and (self.pdb_map[line]["atom_name"]==atomname)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
| 36.914894 | 164 | 0.528108 |
m collections import defaultdict
from typing import Union, DefaultDict, List, Any, Dict
from pathlib import Path
from jade2.basic.path import *
class PythonPDB2:
def __init__(self, pdb_file_path: Union[str, Path] = ""):
self.elements = ("id", "atom_number", "atom_name", "alternate_location", \
"three_letter_code", "chain", "residue_number", "i_code", "x", "y", "z", \
"occupancy", "b_factor", "element", "charge")
self.pdb_file_path = str(pdb_file_path)
self.pdb_map: List[DefaultDict[str, str]] = []
self.header: List[str] = []
self.remarks: List[str] = []
if pdb_file_path:
self.read_pdb_into_map()
else:
logging.info("Loading blank PythonPDB")
def set_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
self.pdb_map = pdb_map
line = (entry['id']).ljust(6)+ (entry['atom_number']).rjust(5)+" "+ entry['atom_name']+ \
(entry['alternate_location'])+ ((entry['three_letter_code']).rjust(3)).ljust(4)+ (entry['chain'])+ \
(entry['residue_number']).rjust(4)+ (entry['i_code']) + \
(entry['x']).rjust(11)+ (entry['y']).rjust(8)+ (entry['z']).rjust(8) + \
(entry['occupancy']).rjust(6)+ (entry['b_factor']).rjust(6)
return line
num(old_num)==get_residue_num(num):
return False
else:
return True
def check_new_chain(old_num, num):
if get_chain(old_num)==get_chain(num):
return False
else:
return True
def check_insertion(num):
if not get_i_code(num)==" ":
return True
else:
return False
def renumber_from_one(chain_only, start_num):
resnum = 1
for num in sorted(chain_only):
insert = check_insertion(num)
if num==start_num:
set_residue_num(num, resnum)
#Iterate resnum if new residue
elif check_new_residue(num-1, num, insert):
resnum+=1
set_residue_num(num, resnum)
else:
set_residue_num(num, resnum)
#Set i code at the end, so we can tell if we have new residues or not.
for num in sorted(chain_only):
self.pdb_map[num]["i_code"]=" "
def renumber_from_insert(chain_only, start_num):
pass
self.pdb_map_copy = copy.deepcopy(self.pdb_map)
#Get chains with insertion codes - Now renumbers all chains. Will be an option later.
chains_with_inserts = dict();
for num in range(0, len(self.pdb_map)):
#if get_i_code(num)==" ":
chains_with_inserts[get_chain(num)]=True
#Iterate through all lines/atoms
#Initialize for scope
start_residue=0;
new_start=False
for chain in chains_with_inserts:
print("Renumbering chain "+chain)
chain_only=dict()
for num in range(0, len(self.pdb_map)):
if chain == get_chain(num) and check_id(num):
chain_only[num]=self.pdb_map[num]
lines = sorted(chain_only)
res_start = get_residue_num(lines[0])
renumber_from_one(chain_only, lines[0])
#For now, we only renumber from one.
#else:
#chain_only = renumber_from_insert(chain_only, lines[0])
####################################################################
# General Manipulation
#
#
def change_occupancy(self):
check = 0
for key in range(0, len(self.pdb_map)):
if self.pdb_map[key]["occupancy"].rfind("0.00")!=-1:
print("Changing occupancy of residue " + self.pdb_map[key]["residue_number"] + "To 1.00")
check =1
self.pdb_map[key]["occupancy"] = " 1.00"
if check ==1:
print("Occupancy Column OK for PyRosetta...")
def combine_pdb(self, py_pdb: 'PythonPDB2'):
m = py_pdb.get_pdb_map()
for dat in m:
self.pdb_map.append(dat)
def copy_chain_into_pdb_map(self, py_pdb: 'PythonPDB2', chain: str):
m = py_pdb.get_pdb_map()
for dat in m:
if dat["chain"] == chain:
self.pdb_map.append(dat)
def copy_all_but_chains_into_pdb_map(self, py_pdb:'PythonPDB2', chains):
m = py_pdb.get_pdb_map()
for dat in m:
if not dat["chain"] in chains:
self.pdb_map.append(dat)
def combine_pdb_map(self, pdb_map: List[DefaultDict[str, str]]):
for dat in pdb_map:
self.pdb_map.append(dat)
def pdb_alias(self, pairs: Dict[Any, Any], element: str):
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num][element] == old:
self.pdb_map[num][element] = pairs[old]
def pdb_atom_alias(self, line_num: int, pair: Dict[Any, Any]):
for start in pair:
if self.pdb_map[line_num]["atom_name"] == start:
print(self.pdb_map[line_num]["three_letter_code"] + ":" + self.pdb_map[line_num]["atom_name"] + ":" +
pair[start])
self.pdb_map[line_num]["atom_name"] = pair[start]
def pdb_residue_alias(self, pairs: Dict[Any, Any]):
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["residue_name"] == old:
self.pdb_map[num]["residue_name"] = pairs[old]
def pdb_chain_alias(self, pairs: Dict[Any, Any]):
for num in range(0, len(self.pdb_map)):
for old in pairs:
if self.pdb_map[num]["chain"] == old:
self.pdb_map[num]["chain"] = pairs[old]
def clean_PDB(self):
self.RESIDUES_aliased = False; self.WATER_aliased=False; self.IONS_aliased=False; self.DNA_aliased = False
waters: List[DefaultDict[str, str]] = [] #List of data that have waters
print("Attempting to change residue names, atom names, and water")
for n in range(0, len(self.pdb_map)):
dat = self.pdb_map[n]
#print self.pdb_map[key]["three_letter_code"]
def alias_dna():
if dat["three_letter_code"]=="DA":
self.DNA_aliased=True
dat["three_letter_code"]="A"
elif dat["three_letter_code"]=="DT":
self.DNA_aliased=True
dat["three_letter_code"]="T"
elif dat["three_letter_code"]=="DC":
self.DNA_aliased=True
dat["three_letter_code"]="C"
elif dat["three_letter_code"]=="DG":
self.DNA_aliased=True
dat["three_letter_code"]="G"
else:
return
def alias_water():
if dat["three_letter_code"] in ["HOH", "TIP3", "WAT", "TIP5"]:
self.WATER_aliased=True
dat["three_letter_code"]="TP3" #IO_STRING for TP3 is WAT...Buy still reads TP#?
dat["id"]="HETATM"
waters.append(dat)
#def alias_ions():
#if self.pdb_map[key]["chain"]=="I":
#IONS_aliased= True
#self.pdb_map[key]["id"]="HETATM"
def alias_residues():
if dat["three_letter_code"] == "HSD":
self.RESIDUES_aliased = True
dat["three_letter_code"]="HIS"
def alias_atoms():
if dat["three_letter_code"]== "SER ":
atom_pairs = {" HG1":" HG "}
elif dat["three_letter_code"]=="ILE ":
atom_pairs = {" CD ":" CD1"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LEU ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="VAL ":
atom_pairs = {" OT1":" O ", " OT2":" OXT"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="LYS ":
atom_pairs = {" HZ1":" 1HZ", " HZ2":" 2HZ", " HZ3":" 3HZ"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ARG ":
atom_pairs = {" HH11":" 1HH1", " HH12":" 2HH1", " HH21":" 1HH2", " HH22":" 2HH2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="ASN ":
atom_pairs = {"HD21":"1HD2", "HD22":"2HD2"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
elif dat["three_letter_code"]=="PRO ":
atom_pairs = {" OT1":" O ", " OT2":" OXT", " HD1":" 1HD", " HD2":" 2HD", " HB1":" 1HB", " HG1":" 1HG", " HG2":" 2HG"}
self.pdb_map = self.pdb_atom_alias(n, atom_pairs)
#Unnessessary, but organized.
alias_water()
#alias_ions()
#alias_residues()
alias_atoms()
alias_dna()
#Removes Waters. Keeps Ions.
#for key in waters:
#self.pdb_map.pop(key)
#Outputs what was found:
if self.RESIDUES_aliased:
print("Residues Changed")
if self.WATER_aliased:
print("Water found...changed to TP3. Remove to decrease calculation time.")
if self.IONS_aliased:
print("Ions found. Most are able to be read into Rosetta")
if self.DNA_aliased:
print("DNA found, changed to single letter code.")
####################################################################
# B Factor Replacements
#
#
def read_file_and_replace_b_factors(self, deliminator: str, filename: str, resnum_column: int=1, chain_column:int=2, data_column: int=3, atomname_column=False):
INFILE = open_file(filename, 'r')
for line in INFILE:
if line[0] == "#":continue
line = line.strip()
lineSP = line.split(deliminator)
if len(lineSP)<3:
print("Could not read line. Must have resnum, chain, and data columns")
continue
if not atomname_column:
self.replace_residue_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[data_column-1])
else:
if len(lineSP)<4:
print("Could not read line. Must have resnum, chain, atomname, and data columns")
continue
self.replace_atom_b_factor(lineSP[resnum_column-1], lineSP[chain_column-1], lineSP[atomname_column-1], lineSP[data_column-1])
INFILE.close()
def replace_residue_b_factor(self, resnum: int, chain: str, data: float):
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data) #In case data is an integer.
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
def replace_atom_b_factor(self, resnum: int, chain: str, atomname: str, data: float):
if type(resnum)!=str:
resnum = str(resnum)
if type(data)!=float:
data=float(data)
#Need to make sure Bfactor column is adjusted correctly.
for line in range(0, len(self.pdb_map)):
if ((self.pdb_map[line]['residue_number']==resnum) and (self.pdb_map[line]['chain']==chain) and (self.pdb_map[line]["atom_name"]==atomname)):
self.pdb_map[line]['b_factor']="%.2f"%data
else:
continue
| true | true |
f728036c65d2fb7c85eff44144bdd6548137164c | 3,985 | py | Python | setup.py | moonso/loqusdb | 3f2ab2bd458f83b1c408e8573036024986d0ed4c | [
"MIT"
] | 4 | 2018-06-04T12:42:45.000Z | 2021-03-29T20:36:12.000Z | setup.py | moonso/loqusdb | 3f2ab2bd458f83b1c408e8573036024986d0ed4c | [
"MIT"
] | 50 | 2016-02-26T07:54:39.000Z | 2021-10-12T07:52:01.000Z | setup.py | moonso/loqusdb | 3f2ab2bd458f83b1c408e8573036024986d0ed4c | [
"MIT"
] | 8 | 2016-02-29T13:50:46.000Z | 2020-04-22T10:15:23.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
"""Based on https://github.com/kennethreitz/setup.py"""
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'loqusdb'
DESCRIPTION = 'Store observations of vcf variants in a mongodb'
URL = 'https://github.com/moonso/loqusdb'
EMAIL = 'mans.magnusson@scilifelab.com'
AUTHOR = 'Måns Magnusson'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = "2.5.2"
# What packages are required for this module to be executed?
REQUIRED = [
'click',
'ped_parser',
'pymongo==3.7.1',
'mongomock==3.18',
'vcftoolbox==1.5',
'cyvcf2<0.10',
'coloredlogs',
'mongo_adapter>=0.2',
'pyyaml',
]
# What packages are optional?
EXTRAS = {
'tests':['pytest'],
}
# The rest you shouldn't have to touch too much :)
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
except FileNotFoundError:
long_description = DESCRIPTION
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
"""Support setup.py upload."""
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
# Where the magic happens:
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
entry_points={
'console_scripts': ["loqusdb = loqusdb.__main__:base_command"],
},
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license='MIT',
keywords = ['vcf', 'variants'],
classifiers=[
# Trove classifiers
# Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
"Operating System :: MacOS :: MacOS X",
"Operating System :: Unix",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Bio-Informatics",
],
# $ setup.py publish support.
cmdclass={
'upload': UploadCommand,
},
)
| 27.673611 | 86 | 0.636386 |
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
NAME = 'loqusdb'
DESCRIPTION = 'Store observations of vcf variants in a mongodb'
URL = 'https://github.com/moonso/loqusdb'
EMAIL = 'mans.magnusson@scilifelab.com'
AUTHOR = 'Måns Magnusson'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = "2.5.2"
REQUIRED = [
'click',
'ped_parser',
'pymongo==3.7.1',
'mongomock==3.18',
'vcftoolbox==1.5',
'cyvcf2<0.10',
'coloredlogs',
'mongo_adapter>=0.2',
'pyyaml',
]
EXTRAS = {
'tests':['pytest'],
}
# ------------------------------------------------
# Except, perhaps the License and Trove Classifiers!
# If you do change the License, remember to change the Trove Classifier for that!
here = os.path.abspath(os.path.dirname(__file__))
# Import the README and use it as the long-description.
# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
try:
with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = '\n' + f.read()
except FileNotFoundError:
long_description = DESCRIPTION
# Load the package's __version__.py module as a dictionary.
about = {}
if not VERSION:
with open(os.path.join(here, NAME, '__version__.py')) as f:
exec(f.read(), about)
else:
about['__version__'] = VERSION
class UploadCommand(Command):
description = 'Build and publish the package.'
user_options = []
@staticmethod
def status(s):
print('\033[1m{0}\033[0m'.format(s))
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
try:
self.status('Removing previous builds…')
rmtree(os.path.join(here, 'dist'))
except OSError:
pass
self.status('Building Source and Wheel (universal) distribution…')
os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable))
self.status('Uploading the package to PyPI via Twine…')
os.system('twine upload dist/*')
self.status('Pushing git tags…')
os.system('git tag v{0}'.format(about['__version__']))
os.system('git push --tags')
sys.exit()
setup(
name=NAME,
version=about['__version__'],
description=DESCRIPTION,
long_description=long_description,
long_description_content_type='text/markdown',
author=AUTHOR,
author_email=EMAIL,
python_requires=REQUIRES_PYTHON,
url=URL,
packages=find_packages(exclude=('tests',)),
entry_points={
'console_scripts': ["loqusdb = loqusdb.__main__:base_command"],
},
install_requires=REQUIRED,
extras_require=EXTRAS,
include_package_data=True,
license='MIT',
keywords = ['vcf', 'variants'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: Implementation :: CPython',
"Operating System :: MacOS :: MacOS X",
"Operating System :: Unix",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Bio-Informatics",
],
cmdclass={
'upload': UploadCommand,
},
)
| true | true |
f728044a58a0b35f5e119349ab2cfafc658bbc58 | 7,909 | py | Python | research/audioset/vggish/vggish_train_demo.py | SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | [
"Apache-2.0"
] | null | null | null | research/audioset/vggish/vggish_train_demo.py | SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | [
"Apache-2.0"
] | null | null | null | research/audioset/vggish/vggish_train_demo.py | SimiaCryptus/models | c652a23a650070b71e286f1ded93726670161940 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 The TensorFlow Authors All Rights Reserved.
#
# 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.
# ==============================================================================
r"""A simple demonstration of running VGGish in training mode.
This is intended as a toy example that demonstrates how to use the VGGish model
definition within a larger model that adds more layers on top, and then train
the larger model. If you let VGGish train as well, then this allows you to
fine-tune the VGGish model parameters for your application. If you don't let
VGGish train, then you use VGGish as a feature extractor for the layers above
it.
For this toy task, we are training a classifier to distinguish between three
classes: sine waves, constant signals, and white noise. We generate synthetic
waveforms from each of these classes, convert into shuffled batches of log mel
spectrogram examples with associated labels, and feed the batches into a model
that includes VGGish at the bottom and a couple of additional layers on top. We
also plumb in labels that are associated with the examples, which feed a label
loss used for training.
Usage:
# Run training for 100 steps using a model checkpoint in the default
# location (vggish_model.ckpt in the current directory). Allow VGGish
# to get fine-tuned.
$ python vggish_train_demo.py --num_batches 100
# Same as before but run for fewer steps and don't change VGGish parameters
# and use a checkpoint in a different location
$ python vggish_train_demo.py --num_batches 50 \
--train_vggish=False \
--checkpoint /path/to/model/checkpoint
"""
from __future__ import print_function
from random import shuffle
import numpy as np
import tensorflow as tf
import vggish_input
import vggish_params
import vggish_slim
flags = tf.app.flags
slim = tf.contrib.slim
flags.DEFINE_integer(
'num_batches', 30,
'Number of batches of examples to feed into the model. Each batch is of '
'variable size and contains shuffled examples of each class of audio.')
flags.DEFINE_boolean(
'train_vggish', True,
'If True, allow VGGish parameters to change during training, thus '
'fine-tuning VGGish. If False, VGGish parameters are fixed, thus using '
'VGGish as a fixed feature extractor.')
flags.DEFINE_string(
'checkpoint', 'vggish_model.ckpt',
'Path to the VGGish checkpoint file.')
FLAGS = flags.FLAGS
_NUM_CLASSES = 3
def _get_examples_batch():
"""Returns a shuffled batch of examples of all audio classes.
Note that this is just a toy function because this is a simple demo intended
to illustrate how the training code might work.
Returns:
a tuple (features, labels) where features is a NumPy array of shape
[batch_size, num_frames, num_bands] where the batch_size is variable and
each row is a log mel spectrogram patch of shape [num_frames, num_bands]
suitable for feeding VGGish, while labels is a NumPy array of shape
[batch_size, num_classes] where each row is a multi-hot label vector that
provides the labels for corresponding rows in features.
"""
# Make a waveform for each class.
num_seconds = 5
sr = 44100 # Sampling rate.
t = np.linspace(0, num_seconds, int(num_seconds * sr)) # Time axis.
# Random sine wave.
freq = np.random.uniform(100, 1000)
sine = np.sin(2 * np.pi * freq * t)
# Random constant signal.
magnitude = np.random.uniform(-1, 1)
const = magnitude * t
# White noise.
noise = np.random.normal(-1, 1, size=t.shape)
# Make examples of each signal and corresponding labels.
# Sine is class index 0, Const class index 1, Noise class index 2.
sine_examples = vggish_input.waveform_to_examples(sine, sr)
sine_labels = np.array([[1, 0, 0]] * sine_examples.shape[0])
const_examples = vggish_input.waveform_to_examples(const, sr)
const_labels = np.array([[0, 1, 0]] * const_examples.shape[0])
noise_examples = vggish_input.waveform_to_examples(noise, sr)
noise_labels = np.array([[0, 0, 1]] * noise_examples.shape[0])
# Shuffle (example, label) pairs across all classes.
all_examples = np.concatenate((sine_examples, const_examples, noise_examples))
all_labels = np.concatenate((sine_labels, const_labels, noise_labels))
labeled_examples = list(zip(all_examples, all_labels))
shuffle(labeled_examples)
# Separate and return the features and labels.
features = [example for (example, _) in labeled_examples]
labels = [label for (_, label) in labeled_examples]
return (features, labels)
def main(_):
with tf.Graph().as_default(), tf.Session() as sess:
# Define VGGish.
embeddings = vggish_slim.define_vggish_slim(FLAGS.train_vggish)
# Define a shallow classification model and associated training ops on top
# of VGGish.
with tf.variable_scope('mymodel'):
# Add a fully connected layer with 100 units.
num_units = 100
fc = slim.fully_connected(embeddings, num_units)
# Add a classifier layer at the end, consisting of parallel logistic
# classifiers, one per class. This allows for multi-class tasks.
logits = slim.fully_connected(
fc, _NUM_CLASSES, activation_fn=None, scope='logits')
tf.sigmoid(logits, name='prediction')
# Add training ops.
with tf.variable_scope('train'):
global_step = tf.Variable(
0, name='global_step', trainable=False,
collections=[tf.GraphKeys.GLOBAL_VARIABLES,
tf.GraphKeys.GLOBAL_STEP])
# Labels are assumed to be fed as a batch multi-hot vectors, with
# a 1 in the position of each positive class label, and 0 elsewhere.
labels = tf.placeholder(
tf.float32, shape=(None, _NUM_CLASSES), name='labels')
# Cross-entropy label loss.
xent = tf.nn.sigmoid_cross_entropy_with_logits(
logits=logits, labels=labels, name='xent')
loss = tf.reduce_mean(xent, name='loss_op')
tf.summary.scalar('loss', loss)
# We use the same optimizer and hyperparameters as used to train VGGish.
optimizer = tf.train.AdamOptimizer(
learning_rate=vggish_params.LEARNING_RATE,
epsilon=vggish_params.ADAM_EPSILON)
optimizer.minimize(loss, global_step=global_step, name='train_op')
# Initialize all variables in the model, and then load the pre-trained
# VGGish checkpoint.
sess.run(tf.global_variables_initializer())
vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)
# Locate all the tensors and ops we need for the training loop.
features_tensor = sess.graph.get_tensor_by_name(
vggish_params.INPUT_TENSOR_NAME)
labels_tensor = sess.graph.get_tensor_by_name('mymodel/train/labels:0')
global_step_tensor = sess.graph.get_tensor_by_name(
'mymodel/train/global_step:0')
loss_tensor = sess.graph.get_tensor_by_name('mymodel/train/loss_op:0')
train_op = sess.graph.get_operation_by_name('mymodel/train/train_op')
# The training loop.
for _ in range(FLAGS.num_batches):
(features, labels) = _get_examples_batch()
[num_steps, loss, _] = sess.run(
[global_step_tensor, loss_tensor, train_op],
feed_dict={features_tensor: features, labels_tensor: labels})
print('Step %d: loss %g' % (num_steps, loss))
if __name__ == '__main__':
tf.app.run()
| 40.979275 | 80 | 0.713491 |
from __future__ import print_function
from random import shuffle
import numpy as np
import tensorflow as tf
import vggish_input
import vggish_params
import vggish_slim
flags = tf.app.flags
slim = tf.contrib.slim
flags.DEFINE_integer(
'num_batches', 30,
'Number of batches of examples to feed into the model. Each batch is of '
'variable size and contains shuffled examples of each class of audio.')
flags.DEFINE_boolean(
'train_vggish', True,
'If True, allow VGGish parameters to change during training, thus '
'fine-tuning VGGish. If False, VGGish parameters are fixed, thus using '
'VGGish as a fixed feature extractor.')
flags.DEFINE_string(
'checkpoint', 'vggish_model.ckpt',
'Path to the VGGish checkpoint file.')
FLAGS = flags.FLAGS
_NUM_CLASSES = 3
def _get_examples_batch():
num_seconds = 5
sr = 44100
t = np.linspace(0, num_seconds, int(num_seconds * sr))
freq = np.random.uniform(100, 1000)
sine = np.sin(2 * np.pi * freq * t)
magnitude = np.random.uniform(-1, 1)
const = magnitude * t
noise = np.random.normal(-1, 1, size=t.shape)
sine_examples = vggish_input.waveform_to_examples(sine, sr)
sine_labels = np.array([[1, 0, 0]] * sine_examples.shape[0])
const_examples = vggish_input.waveform_to_examples(const, sr)
const_labels = np.array([[0, 1, 0]] * const_examples.shape[0])
noise_examples = vggish_input.waveform_to_examples(noise, sr)
noise_labels = np.array([[0, 0, 1]] * noise_examples.shape[0])
all_examples = np.concatenate((sine_examples, const_examples, noise_examples))
all_labels = np.concatenate((sine_labels, const_labels, noise_labels))
labeled_examples = list(zip(all_examples, all_labels))
shuffle(labeled_examples)
features = [example for (example, _) in labeled_examples]
labels = [label for (_, label) in labeled_examples]
return (features, labels)
def main(_):
with tf.Graph().as_default(), tf.Session() as sess:
embeddings = vggish_slim.define_vggish_slim(FLAGS.train_vggish)
with tf.variable_scope('mymodel'):
num_units = 100
fc = slim.fully_connected(embeddings, num_units)
logits = slim.fully_connected(
fc, _NUM_CLASSES, activation_fn=None, scope='logits')
tf.sigmoid(logits, name='prediction')
with tf.variable_scope('train'):
global_step = tf.Variable(
0, name='global_step', trainable=False,
collections=[tf.GraphKeys.GLOBAL_VARIABLES,
tf.GraphKeys.GLOBAL_STEP])
labels = tf.placeholder(
tf.float32, shape=(None, _NUM_CLASSES), name='labels')
xent = tf.nn.sigmoid_cross_entropy_with_logits(
logits=logits, labels=labels, name='xent')
loss = tf.reduce_mean(xent, name='loss_op')
tf.summary.scalar('loss', loss)
optimizer = tf.train.AdamOptimizer(
learning_rate=vggish_params.LEARNING_RATE,
epsilon=vggish_params.ADAM_EPSILON)
optimizer.minimize(loss, global_step=global_step, name='train_op')
sess.run(tf.global_variables_initializer())
vggish_slim.load_vggish_slim_checkpoint(sess, FLAGS.checkpoint)
features_tensor = sess.graph.get_tensor_by_name(
vggish_params.INPUT_TENSOR_NAME)
labels_tensor = sess.graph.get_tensor_by_name('mymodel/train/labels:0')
global_step_tensor = sess.graph.get_tensor_by_name(
'mymodel/train/global_step:0')
loss_tensor = sess.graph.get_tensor_by_name('mymodel/train/loss_op:0')
train_op = sess.graph.get_operation_by_name('mymodel/train/train_op')
for _ in range(FLAGS.num_batches):
(features, labels) = _get_examples_batch()
[num_steps, loss, _] = sess.run(
[global_step_tensor, loss_tensor, train_op],
feed_dict={features_tensor: features, labels_tensor: labels})
print('Step %d: loss %g' % (num_steps, loss))
if __name__ == '__main__':
tf.app.run()
| true | true |
f7280459bb1c11d05d44c03226ca1b7d0dd23522 | 449 | py | Python | python/sprint_12/tmp/code.py | Talgatovich/algorithms-templates | e7c6fd71451304ed0dacc393c3f30ca3f5282d46 | [
"MIT"
] | null | null | null | python/sprint_12/tmp/code.py | Talgatovich/algorithms-templates | e7c6fd71451304ed0dacc393c3f30ca3f5282d46 | [
"MIT"
] | null | null | null | python/sprint_12/tmp/code.py | Talgatovich/algorithms-templates | e7c6fd71451304ed0dacc393c3f30ca3f5282d46 | [
"MIT"
] | null | null | null | # Comment it before submitting
# class Node:
# def __init__(self, value, next_item=None):
# self.value = value
# self.next_item = next_item
def solution(node, idx):
# Your code
# ヽ(´▽`)/
pass
def test():
node3 = Node("node3", None)
node2 = Node("node2", node3)
node1 = Node("node1", node2)
node0 = Node("node0", node1)
new_head = solution(node0, 1)
# result is node0 -> node2 -> node3 | 23.631579 | 50 | 0.581292 |
def solution(node, idx):
pass
def test():
node3 = Node("node3", None)
node2 = Node("node2", node3)
node1 = Node("node1", node2)
node0 = Node("node0", node1)
new_head = solution(node0, 1)
| true | true |
f728047ed3f41d811f58d70ae10b6265a2be9524 | 2,529 | py | Python | tests/test_transport_datagram.py | zentropi/python-zentropi | 96cf714b1e0eeb7ee887298eca0f1c92e8b6958e | [
"BSD-3-Clause"
] | 14 | 2017-04-21T05:47:02.000Z | 2018-10-23T21:28:19.000Z | tests/test_transport_datagram.py | zentropi/python-zentropi | 96cf714b1e0eeb7ee887298eca0f1c92e8b6958e | [
"BSD-3-Clause"
] | 22 | 2017-04-11T23:35:16.000Z | 2017-05-20T04:32:44.000Z | tests/test_transport_datagram.py | zentropi/python-zentropi | 96cf714b1e0eeb7ee887298eca0f1c92e8b6958e | [
"BSD-3-Clause"
] | 5 | 2017-04-05T23:21:05.000Z | 2017-10-29T15:28:05.000Z | import pytest
from zentropi import Agent
from zentropi import Frame
from zentropi.transport import datagram
class MockDatagram(object):
def __init__(self, login_ok=True, send_ok=True, recv_ok=True):
self._login_ok = login_ok
self._send_ok = send_ok
self._recv_ok = recv_ok
self.frame = None
async def connect(self, endpoint):
return self
async def close(self):
pass
async def send(self, data):
if not self._send_ok:
raise ConnectionAbortedError()
frame = Frame.from_json(data.decode('utf-8'))
if frame.name == 'login':
if self._login_ok:
self.frame = frame.reply('login-ok').to_json().encode('utf-8')
else:
self.frame = frame.reply('login-failed').to_json().encode('utf-8')
return
self.frame = data
async def recv(self):
if not self._recv_ok:
raise ConnectionAbortedError()
return self.frame, '127.0.0.1:9999'
@pytest.mark.asyncio
async def test_datagram_transport(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram())
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
assert dt.connected is True
await dt.send(frame)
assert dt.connection.frame
frame_recv = await dt.recv()
assert frame_recv.name == 'test-frame'
await dt.close()
assert dt.connected is False
@pytest.mark.asyncio
@pytest.mark.xfail(raises=PermissionError)
async def test_datagram_transport_login_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(login_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_send_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(send_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_recv_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(recv_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
| 31.6125 | 82 | 0.680506 | import pytest
from zentropi import Agent
from zentropi import Frame
from zentropi.transport import datagram
class MockDatagram(object):
def __init__(self, login_ok=True, send_ok=True, recv_ok=True):
self._login_ok = login_ok
self._send_ok = send_ok
self._recv_ok = recv_ok
self.frame = None
async def connect(self, endpoint):
return self
async def close(self):
pass
async def send(self, data):
if not self._send_ok:
raise ConnectionAbortedError()
frame = Frame.from_json(data.decode('utf-8'))
if frame.name == 'login':
if self._login_ok:
self.frame = frame.reply('login-ok').to_json().encode('utf-8')
else:
self.frame = frame.reply('login-failed').to_json().encode('utf-8')
return
self.frame = data
async def recv(self):
if not self._recv_ok:
raise ConnectionAbortedError()
return self.frame, '127.0.0.1:9999'
@pytest.mark.asyncio
async def test_datagram_transport(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram())
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
assert dt.connected is True
await dt.send(frame)
assert dt.connection.frame
frame_recv = await dt.recv()
assert frame_recv.name == 'test-frame'
await dt.close()
assert dt.connected is False
@pytest.mark.asyncio
@pytest.mark.xfail(raises=PermissionError)
async def test_datagram_transport_login_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(login_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_send_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(send_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
@pytest.mark.asyncio
@pytest.mark.xfail(raises=ConnectionError)
async def test_datagram_transport_recv_fail(monkeypatch):
monkeypatch.setattr(datagram, 'asyncio_dgram', MockDatagram(recv_ok=False))
dt = datagram.DatagramTransport()
frame = Frame('test-frame')
await dt.connect('dgram://127.0.0.1:6789/', 'test-token')
| true | true |
f72805554c757480caa6c16f5ee9bd0c52c96825 | 19,827 | py | Python | ipython/3_Training_Predicting/prnn_cb12_train_predict.py | samuelru/session-knn-ae | c6232667dbe57f82391d487875b52f651ca08a21 | [
"MIT"
] | 6 | 2019-12-08T12:58:02.000Z | 2021-06-29T23:52:03.000Z | ipython/3_Training_Predicting/prnn_cb12_train_predict.py | samuelru/session-knn-ae | c6232667dbe57f82391d487875b52f651ca08a21 | [
"MIT"
] | 1 | 2021-01-20T14:52:02.000Z | 2022-02-24T08:43:11.000Z | ipython/3_Training_Predicting/prnn_cb12_train_predict.py | samuelru/session-knn-ae | c6232667dbe57f82391d487875b52f651ca08a21 | [
"MIT"
] | 5 | 2019-12-08T13:09:03.000Z | 2020-09-04T04:53:51.000Z | from keras.layers import Input, Dense, concatenate
from keras.layers.recurrent import GRU
from keras.utils import plot_model
from keras.models import Model, load_model
from keras.callbacks import ModelCheckpoint
import keras
import pandas as pd
import numpy as np
import keras.backend as K
from keras.utils import to_categorical
from keras.losses import categorical_crossentropy
from multiprocessing import Pool, cpu_count
import pickle
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
dataset = "cb12/"
path = "../../data/"
interim_path = path + dataset + "interim/"
processed_path = path + dataset + "processed/"
model_path = "models/"
model_path_valid = "models/valid/"
def TOP1(y_true, y_pred):
y1 = y_pred * y_true
y2 = K.sum(y1, axis=1)[:, np.newaxis]
y3 = y_true - y1
return (K.sum(K.sigmoid(y_pred - y2)) + y3 * y3) / tf.cast(tf.shape(y_true)[0], tf.float32)
loss = TOP1
def create_prnn_model(left_input_size, right_input_size, batch_size = 512, hidden_units = 100, o_activation='softmax', lr = 0.001):
emb_size = 50
size = emb_size
# left input - item vector
input_left = Input(batch_shape=(batch_size, 1, left_input_size), name='input_left')
gru_left, gru_left_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_left')(input_left)
# right input - feature vector
input_right = Input(batch_shape=(batch_size, 1, right_input_size), name='input_right')
gru_right, gru_right_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_right')(input_right)
# merging both layers and creating the model
merged = concatenate([gru_left, gru_right])
#change softmax per another activation funciton?
output = Dense(left_input_size, activation=o_activation, name='output')(merged)
model = Model(inputs=[input_left, input_right], outputs=output, name='gru4rec')
encoder = Model(inputs=[input_left, input_right], outputs=merged)
# define model's optimizer
#optimizer = optim.Optimizer(optimizer=self.optimizer, lr=self.lr)
#opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
# define model's loss function --> implement here the top1 loss function
# loss_function = loss.LossFunction(loss_type=self.loss_function)
#model.compile(loss=loss_function, optimizer=opt, metrics=['accuracy'])
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
filepath = model_path_valid + 'prnn_cb12_checkpoint.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=2, save_best_only=True, mode='min')
callbacks_list = []
model.summary()
#plot_model(model, show_shapes=True, to_file='rnn-structure.png')
return model, encoder
def get_states(model):
#return the actual states of the layers
return [K.get_value(s) for s,_ in model.state_updates]
def freeze_layer(model, layer_name, lr):
if layer_name == 'gru_left':
# gru left layer will not be trained this mini batch
model.get_layer(layer_name).trainable = False
# but gru right will
model.get_layer('gru_right').trainable = True
elif layer_name == 'gru_right':
# gru right layer will not be trained this mini batch
model.get_layer(layer_name).trainable = False
# but gru left will
model.get_layer('gru_left').trainable = True
else:
raise NotImplementedError
# opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
return model
class SessionDataset:
"""Credit to yhs-968/pyGRU4REC."""
def __init__(self, data, sep='\t', session_key='session_id', item_key='item_id', time_key='created_at', n_samples=-1, itemmap=None, time_sort=False):
"""
Args:
path: path of the csv file
sep: separator for the csv
session_key, item_key, time_key: name of the fields corresponding to the sessions, items, time
n_samples: the number of samples to use. If -1, use the whole dataset.
itemmap: mapping between item IDs and item indices
time_sort: whether to sort the sessions by time or not
"""
self.df = data
self.session_key = session_key
self.item_key = item_key
self.time_key = time_key
self.time_sort = time_sort
self.add_item_indices(itemmap=itemmap)
self.df.sort_values([session_key, time_key], inplace=True)
# Sort the df by time, and then by session ID. That is, df is sorted by session ID and
# clicks within a session are next to each other, where the clicks within a session are time-ordered.
self.click_offsets = self.get_click_offsets()
#array of the positions where there is a change of session.
#len = len(session_idx_arr) + 1
self.session_idx_arr = self.order_session_idx()
#array of sessions [0 1 2 3 4 .... n-1]
def get_click_offsets(self):
"""
Return the offsets of the beginning clicks of each session IDs,
where the offset is calculated against the first click of the first session ID.
"""
offsets = np.zeros(self.df[self.session_key].nunique() + 1, dtype=np.int32)
# group & sort the df by session_key and get the offset values
offsets[1:] = self.df.groupby(self.session_key).size().cumsum()
return offsets
def order_session_idx(self):
""" Order the session indices """
if self.time_sort:
# starting time for each sessions, sorted by session IDs
sessions_start_time = self.df.groupby(self.session_key)[self.time_key].min().values
# order the session indices by session starting times
session_idx_arr = np.argsort(sessions_start_time)
else:
session_idx_arr = np.arange(self.df[self.session_key].nunique())
return session_idx_arr
def add_item_indices(self, itemmap=None):
"""
Add item index column named "item_idx" to the df
Args:
itemmap (pd.DataFrame): mapping between the item Ids and indices
"""
if itemmap is None:
item_ids = self.df[self.item_key].unique() # unique item ids
item2idx = pd.Series(data=np.arange(len(item_ids)),
index=item_ids)
itemmap = pd.DataFrame({self.item_key:item_ids,
'item_idx':item2idx[item_ids].values})
self.itemmap = itemmap
self.df = pd.merge(self.df, self.itemmap, on=self.item_key, how='inner')
@property
def items(self):
return self.itemmap.item_id.unique()
class SessionDataLoader:
"""Credit to yhs-968/pyGRU4REC."""
def __init__(self, dataset, batch_size):
"""
A class for creating session-parallel mini-batches.
Args:
dataset (SessionDataset): the session dataset to generate the batches from
batch_size (int): size of the batch
"""
self.dataset = dataset
self.batch_size = batch_size
self.done_sessions_counter = 0
def __iter__(self):
""" Returns the iterator for producing session-parallel training mini-batches.
Yields:
input (B,): Item indices that will be encoded as one-hot vectors later.
target (B,): a Variable that stores the target item indices
masks: Numpy array indicating the positions of the sessions to be terminated
"""
df = self.dataset.df
session_key='session_id'
item_key='item_id'
time_key='created_at'
self.n_items = df[item_key].nunique()
click_offsets = self.dataset.click_offsets
#print(click_offsets)
session_idx_arr = self.dataset.session_idx_arr
#print(session_idx_arr)
iters = np.arange(self.batch_size)
#iters = np.arange(1)
maxiter = iters.max()
start = click_offsets[session_idx_arr[iters]]
end = click_offsets[session_idx_arr[iters] + 1]
#print(start)
#print(end)
mask = [] # indicator for the sessions to be terminated
finished = False
while not finished:
#minimum lenght of all the sessions
minlen = (end - start).min()
# Item indices (for embedding) for clicks where the first sessions start
idx_target = df.item_idx.values[start]
for i in range(minlen - 1):
# Build inputs & targets
idx_input = idx_target
idx_target = df.item_idx.values[start + i + 1]
inp = idx_input
target = idx_target
yield inp, target, mask
# click indices where a particular session meets second-to-last element
start = start + (minlen - 1)
# see if how many sessions should terminate
mask = np.arange(len(iters))[(end - start) <= 1]
self.done_sessions_counter = len(mask)
for idx in mask:
maxiter += 1
if maxiter >= len(click_offsets) - 1:
finished = True
break
# update the next starting/ending point
iters[idx] = maxiter
start[idx] = click_offsets[session_idx_arr[maxiter]]
end[idx] = click_offsets[session_idx_arr[maxiter] + 1]
def train_prnn(model, lr, loader, layer_freezing_enabled = False, num_epochs = 10):
for epoch in range(0, num_epochs):
print("Epoch: " + str(epoch+1))
epoch_loss = 0
i = 0
for feat, target, mask in loader:
#feat = np array size BATCH_SIZE with the item indexes of the first items of the first BATCH_SIZE sessions
#comvert feat to an array size (BATCH_SIZE, 26723) of one hot encoding the indes with loader.n_items
input_oh = to_categorical(feat, num_classes=loader.n_items)
#convert from shape (BATCH_SIZE, 26723) to (BATCH_SIZE, 1, 26723)
input_oh = np.expand_dims(input_oh, axis=1)
# with the argmax function you get back again the feat/target np array (arg_input = feat)
### arg_input = np.argmax(to_categorical(feat, num_classes=loader.n_items), axis=1)
### arg_output = np.argmax(to_categorical(target, num_classes=loader.n_items), axis=1)
input_feature = np.array([])
for line in feat:
#result = int(mapitem[(mapitem.item_idx == line)].item_id.values)
result = str(mapitem[(mapitem.item_idx == line)].item_id.values[0])
#print(result)
# use empty feature vec if missing
feature_vector = empty_feature_vec
if result in item_encodings.keys():
feature_vector = item_encodings[result]
input_feature = np.append(input_feature, feature_vector)
input_feature = input_feature.reshape(batch_size, 1, feature_size)
#target = np array size BATCH_SIZE with the item indexes of the TARGET items of the feat array items
target_oh = to_categorical(target, num_classes=loader.n_items)
#calculate the loss between the input and the expected output
if layer_freezing_enabled:
if i % 2 is 0:
model = freeze_layer(model, 'gru_left', lr = lr)
else:
model = freeze_layer(model, 'gru_right', lr = lr)
tr_loss = model.train_on_batch([input_oh, input_feature], target_oh)
epoch_loss += tr_loss[0]
i = i + 1
print("Epoch loss: " + str(epoch_loss))
return model
# # Set data for final training
# set data
train_path = '../../data/' + dataset + 'processed/train_14d.csv'
train = pd.read_csv(train_path, sep='\t')[['session_id', 'item_id', 'created_at']]
interactions = pd.read_csv('../../data/' + dataset + 'interim/interactions.csv', header=0, sep='\t')
items = pd.read_csv('../../data/' + dataset + 'interim/items.csv', header=0, sep='\t')
view_fields = ["item_id", "state", "ReqTopic", "DescTopic", "TitTopic"]
common_items = items.merge(interactions, on=['item_id'])[view_fields].drop_duplicates()
item_count = len(train['item_id'].unique())
print(item_count)
session_count = len(train['created_at'].unique())
print(len(common_items))
# CB12 items need to be converted to dummies
common = common_items
common["item_id"] = common["item_id"].astype('str')
common["DescTopic"] = common["DescTopic"].astype('str')
common["TitTopic"] = common["TitTopic"].astype('str')
common["ReqTopic"] = common["ReqTopic"].astype('str')
df2 = pd.DataFrame(index=common.index)
s1 = pd.get_dummies(common["state"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="state").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["ReqTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="ReqTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["state_", "ReqTopic_"], axis=1, errors="ignore")
s1 = pd.get_dummies(common["DescTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="DescTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["TitTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="TitTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["DescTopic_", "TitTopic_"], axis=1, errors="ignore")
common = common.drop(["state", "ReqTopic", "DescTopic", "TitTopic"], axis=1)
df2 = pd.concat([common, df2], axis=1)
one_hot = df2
print(one_hot.shape)
# number of content features per item
feature_size = one_hot.shape[1] - 1
item_encodings = {}
for index, row in one_hot.iterrows():
item_id = row["item_id"]
item_encodings[item_id] = row.values[1:]
print(len(item_encodings))
empty_feature_vec = np.zeros(feature_size, dtype=int)
# load data
batch_size = 512
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
mapitem = loader.dataset.itemmap
# # Train final model
# In[ ]:
# use best params
ls = 1000
act = "softmax"
lr = 0.001
# define model
model, encoder = create_prnn_model(item_count, feature_size, batch_size=batch_size, hidden_units = ls, o_activation = act, lr = lr)
# train model
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
print("Starting to train: " + model_name)
model = train_prnn(model, lr, loader)
pickle.dump(model, open(model_path + model_name, 'wb'), protocol=4)
print("Stored model in: " + model_path + model_name)
# # Generate predictions
def predict_function(sid, test_session, pr, item_idx_map, idx_item_map, cut_off=20,
session_key='session_id', item_key='item_id', time_key='created_at'):
test_session.sort_values([time_key], inplace=True)
# get first and only session_id (as we grouped it before calling this method)
session_id = test_session[session_key].unique()[0]
log_columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"]
log_df = pd.DataFrame(columns = log_columns)
session_length = len(test_session)
il = a = np.zeros((batch_size, 1, len(item_idx_map)))
ir = a = np.zeros((batch_size, 1, 115))
for i in range(session_length -1):
# use current item as reference point (rest is for testing)
current_item_id = test_session[item_key].values[i]
item_vec = np.zeros(len(item_idx_map), dtype=int)
item_idx = item_idx_map[current_item_id]
item_vec[item_idx] = 1
# set vector in batch input
il[i, 0] = item_vec
#item_features = item_encodings[current_item_id]
# use empty feature vec if missing
item_features = empty_feature_vec
if current_item_id in item_encodings.keys():
item_features = item_encodings[result]
#item_features = item_features.reshape(1,1, len(item_features))
ir[i, 0] = item_features
# do batch prediction
pred = model.predict([il, ir], batch_size=batch_size)
# for every subsession prediction
for i in range(session_length-1):
preds = pred[i]
topn_idx_preds = preds.argsort()[-cut_off:][::-1]
predictions = []
# for every recommended item index
for item_idx in topn_idx_preds:
pred_item = idx_item_map[item_idx]
predictions.append(pred_item)
current_input_set = test_session[item_key].values[:i+1]
remaining_test_set = test_session[item_key].values[i+1:]
position = "MID"
if i == 0:
position = "FIRST"
if len(remaining_test_set) == 1:
position = "LAST"
log_df = log_df.append({
"session_id": sid,
"input_items": ','.join(map(str, current_input_set)),
"input_count": len(current_input_set),
"position": position,
"remaining_items": ','.join(map(str, remaining_test_set)),
"remaining_count": len(remaining_test_set),
"predictions": ','.join(map(str, predictions))
}, ignore_index=True)
log_df['input_count'] = log_df['input_count'].astype(int)
log_df['remaining_count'] = log_df['remaining_count'].astype(int)
return log_df
# In[ ]:
import keras.losses
keras.losses.TOP1 = TOP1
print("Preparing train data...")
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
test_path = '../../data/' + dataset + 'processed/test_14d.csv'
test = pd.read_csv(test_path, sep='\t')[['session_id', 'item_id', 'created_at']]
test_dataset = SessionDataset(test)
test_generator = SessionDataLoader(test_dataset, batch_size=batch_size)
session_groups = test.groupby("session_id")
mapitem = loader.dataset.itemmap
item_idx_map = {}
idx_item_map = {}
for index, row in mapitem.iterrows():
item_id = row["item_id"]
item_idx = row["item_idx"]
item_idx_map[item_id] = item_idx
idx_item_map[item_idx] = item_id
predict_path = "../../data/cb12/interim/predict/base/"
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
model = pickle.load(open(model_path + model_name, 'rb'))
print("Loaded: " + model_name)
res_list = []
# predict
report_freq = len(session_groups) // 5
count = 0
for sid, session in session_groups:
pred_df = predict_function(sid, session, model, item_idx_map, idx_item_map)
res_list.append(pred_df)
# reset states
model.get_layer('gru_left').reset_states()
model.get_layer('gru_right').reset_states()
# print progress
count += 1
if count % report_freq == 0:
print("Predicted for " + str(count) + " sessions. " + str(len(session_groups) - count) + " sessions to go." )
# concat results
res = pd.concat(res_list)
res = res.reindex(columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"])
res.to_csv(predict_path + "test_14d_prnn2.csv", sep='\t')
print("Stored predictions: " + predict_path + "test_14d_prnn2.csv")
# In[ ]:
| 37.338983 | 153 | 0.643214 | from keras.layers import Input, Dense, concatenate
from keras.layers.recurrent import GRU
from keras.utils import plot_model
from keras.models import Model, load_model
from keras.callbacks import ModelCheckpoint
import keras
import pandas as pd
import numpy as np
import keras.backend as K
from keras.utils import to_categorical
from keras.losses import categorical_crossentropy
from multiprocessing import Pool, cpu_count
import pickle
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
dataset = "cb12/"
path = "../../data/"
interim_path = path + dataset + "interim/"
processed_path = path + dataset + "processed/"
model_path = "models/"
model_path_valid = "models/valid/"
def TOP1(y_true, y_pred):
y1 = y_pred * y_true
y2 = K.sum(y1, axis=1)[:, np.newaxis]
y3 = y_true - y1
return (K.sum(K.sigmoid(y_pred - y2)) + y3 * y3) / tf.cast(tf.shape(y_true)[0], tf.float32)
loss = TOP1
def create_prnn_model(left_input_size, right_input_size, batch_size = 512, hidden_units = 100, o_activation='softmax', lr = 0.001):
emb_size = 50
size = emb_size
input_left = Input(batch_shape=(batch_size, 1, left_input_size), name='input_left')
gru_left, gru_left_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_left')(input_left)
input_right = Input(batch_shape=(batch_size, 1, right_input_size), name='input_right')
gru_right, gru_right_states = GRU(hidden_units, stateful=True, return_state=True, name='gru_right')(input_right)
merged = concatenate([gru_left, gru_right])
output = Dense(left_input_size, activation=o_activation, name='output')(merged)
model = Model(inputs=[input_left, input_right], outputs=output, name='gru4rec')
encoder = Model(inputs=[input_left, input_right], outputs=merged)
#optimizer = optim.Optimizer(optimizer=self.optimizer, lr=self.lr)
#opt = keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
opt = keras.optimizers.Adagrad(lr=lr)
# define model's loss function --> implement here the top1 loss function
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
filepath = model_path_valid + 'prnn_cb12_checkpoint.h5'
checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=2, save_best_only=True, mode='min')
callbacks_list = []
model.summary()
return model, encoder
def get_states(model):
return [K.get_value(s) for s,_ in model.state_updates]
def freeze_layer(model, layer_name, lr):
if layer_name == 'gru_left':
model.get_layer(layer_name).trainable = False
model.get_layer('gru_right').trainable = True
elif layer_name == 'gru_right':
model.get_layer(layer_name).trainable = False
model.get_layer('gru_left').trainable = True
else:
raise NotImplementedError
opt = keras.optimizers.Adagrad(lr=lr)
model.compile(loss=loss, optimizer=opt, metrics=['accuracy'])
return model
class SessionDataset:
def __init__(self, data, sep='\t', session_key='session_id', item_key='item_id', time_key='created_at', n_samples=-1, itemmap=None, time_sort=False):
self.df = data
self.session_key = session_key
self.item_key = item_key
self.time_key = time_key
self.time_sort = time_sort
self.add_item_indices(itemmap=itemmap)
self.df.sort_values([session_key, time_key], inplace=True)
self.click_offsets = self.get_click_offsets()
self.session_idx_arr = self.order_session_idx()
def get_click_offsets(self):
offsets = np.zeros(self.df[self.session_key].nunique() + 1, dtype=np.int32)
offsets[1:] = self.df.groupby(self.session_key).size().cumsum()
return offsets
def order_session_idx(self):
if self.time_sort:
sessions_start_time = self.df.groupby(self.session_key)[self.time_key].min().values
session_idx_arr = np.argsort(sessions_start_time)
else:
session_idx_arr = np.arange(self.df[self.session_key].nunique())
return session_idx_arr
def add_item_indices(self, itemmap=None):
if itemmap is None:
item_ids = self.df[self.item_key].unique()
item2idx = pd.Series(data=np.arange(len(item_ids)),
index=item_ids)
itemmap = pd.DataFrame({self.item_key:item_ids,
'item_idx':item2idx[item_ids].values})
self.itemmap = itemmap
self.df = pd.merge(self.df, self.itemmap, on=self.item_key, how='inner')
@property
def items(self):
return self.itemmap.item_id.unique()
class SessionDataLoader:
def __init__(self, dataset, batch_size):
self.dataset = dataset
self.batch_size = batch_size
self.done_sessions_counter = 0
def __iter__(self):
df = self.dataset.df
session_key='session_id'
item_key='item_id'
time_key='created_at'
self.n_items = df[item_key].nunique()
click_offsets = self.dataset.click_offsets
session_idx_arr = self.dataset.session_idx_arr
iters = np.arange(self.batch_size)
maxiter = iters.max()
start = click_offsets[session_idx_arr[iters]]
end = click_offsets[session_idx_arr[iters] + 1]
mask = []
finished = False
while not finished:
minlen = (end - start).min()
idx_target = df.item_idx.values[start]
for i in range(minlen - 1):
idx_input = idx_target
idx_target = df.item_idx.values[start + i + 1]
inp = idx_input
target = idx_target
yield inp, target, mask
start = start + (minlen - 1)
mask = np.arange(len(iters))[(end - start) <= 1]
self.done_sessions_counter = len(mask)
for idx in mask:
maxiter += 1
if maxiter >= len(click_offsets) - 1:
finished = True
break
iters[idx] = maxiter
start[idx] = click_offsets[session_idx_arr[maxiter]]
end[idx] = click_offsets[session_idx_arr[maxiter] + 1]
def train_prnn(model, lr, loader, layer_freezing_enabled = False, num_epochs = 10):
for epoch in range(0, num_epochs):
print("Epoch: " + str(epoch+1))
epoch_loss = 0
i = 0
for feat, target, mask in loader:
input_oh = to_categorical(feat, num_classes=loader.n_items)
input_oh = np.expand_dims(input_oh, axis=1)
.keys():
feature_vector = item_encodings[result]
input_feature = np.append(input_feature, feature_vector)
input_feature = input_feature.reshape(batch_size, 1, feature_size)
target_oh = to_categorical(target, num_classes=loader.n_items)
if layer_freezing_enabled:
if i % 2 is 0:
model = freeze_layer(model, 'gru_left', lr = lr)
else:
model = freeze_layer(model, 'gru_right', lr = lr)
tr_loss = model.train_on_batch([input_oh, input_feature], target_oh)
epoch_loss += tr_loss[0]
i = i + 1
print("Epoch loss: " + str(epoch_loss))
return model
' + dataset + 'processed/train_14d.csv'
train = pd.read_csv(train_path, sep='\t')[['session_id', 'item_id', 'created_at']]
interactions = pd.read_csv('../../data/' + dataset + 'interim/interactions.csv', header=0, sep='\t')
items = pd.read_csv('../../data/' + dataset + 'interim/items.csv', header=0, sep='\t')
view_fields = ["item_id", "state", "ReqTopic", "DescTopic", "TitTopic"]
common_items = items.merge(interactions, on=['item_id'])[view_fields].drop_duplicates()
item_count = len(train['item_id'].unique())
print(item_count)
session_count = len(train['created_at'].unique())
print(len(common_items))
common = common_items
common["item_id"] = common["item_id"].astype('str')
common["DescTopic"] = common["DescTopic"].astype('str')
common["TitTopic"] = common["TitTopic"].astype('str')
common["ReqTopic"] = common["ReqTopic"].astype('str')
df2 = pd.DataFrame(index=common.index)
s1 = pd.get_dummies(common["state"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="state").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["ReqTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="ReqTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["state_", "ReqTopic_"], axis=1, errors="ignore")
s1 = pd.get_dummies(common["DescTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="DescTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
s1 = pd.get_dummies(common["TitTopic"].fillna("").str.split(",").apply(pd.Series).stack(), prefix="TitTopic").sum(level=0)
df2 = pd.concat([df2, s1], axis=1)
df2 = df2.drop(["DescTopic_", "TitTopic_"], axis=1, errors="ignore")
common = common.drop(["state", "ReqTopic", "DescTopic", "TitTopic"], axis=1)
df2 = pd.concat([common, df2], axis=1)
one_hot = df2
print(one_hot.shape)
feature_size = one_hot.shape[1] - 1
item_encodings = {}
for index, row in one_hot.iterrows():
item_id = row["item_id"]
item_encodings[item_id] = row.values[1:]
print(len(item_encodings))
empty_feature_vec = np.zeros(feature_size, dtype=int)
batch_size = 512
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
mapitem = loader.dataset.itemmap
t = "softmax"
lr = 0.001
model, encoder = create_prnn_model(item_count, feature_size, batch_size=batch_size, hidden_units = ls, o_activation = act, lr = lr)
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
print("Starting to train: " + model_name)
model = train_prnn(model, lr, loader)
pickle.dump(model, open(model_path + model_name, 'wb'), protocol=4)
print("Stored model in: " + model_path + model_name)
(sid, test_session, pr, item_idx_map, idx_item_map, cut_off=20,
session_key='session_id', item_key='item_id', time_key='created_at'):
test_session.sort_values([time_key], inplace=True)
session_id = test_session[session_key].unique()[0]
log_columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"]
log_df = pd.DataFrame(columns = log_columns)
session_length = len(test_session)
il = a = np.zeros((batch_size, 1, len(item_idx_map)))
ir = a = np.zeros((batch_size, 1, 115))
for i in range(session_length -1):
current_item_id = test_session[item_key].values[i]
item_vec = np.zeros(len(item_idx_map), dtype=int)
item_idx = item_idx_map[current_item_id]
item_vec[item_idx] = 1
il[i, 0] = item_vec
item_features = empty_feature_vec
if current_item_id in item_encodings.keys():
item_features = item_encodings[result]
ir[i, 0] = item_features
pred = model.predict([il, ir], batch_size=batch_size)
for i in range(session_length-1):
preds = pred[i]
topn_idx_preds = preds.argsort()[-cut_off:][::-1]
predictions = []
for item_idx in topn_idx_preds:
pred_item = idx_item_map[item_idx]
predictions.append(pred_item)
current_input_set = test_session[item_key].values[:i+1]
remaining_test_set = test_session[item_key].values[i+1:]
position = "MID"
if i == 0:
position = "FIRST"
if len(remaining_test_set) == 1:
position = "LAST"
log_df = log_df.append({
"session_id": sid,
"input_items": ','.join(map(str, current_input_set)),
"input_count": len(current_input_set),
"position": position,
"remaining_items": ','.join(map(str, remaining_test_set)),
"remaining_count": len(remaining_test_set),
"predictions": ','.join(map(str, predictions))
}, ignore_index=True)
log_df['input_count'] = log_df['input_count'].astype(int)
log_df['remaining_count'] = log_df['remaining_count'].astype(int)
return log_df
import keras.losses
keras.losses.TOP1 = TOP1
print("Preparing train data...")
train_dataset = SessionDataset(train)
loader = SessionDataLoader(train_dataset, batch_size=batch_size)
test_path = '../../data/' + dataset + 'processed/test_14d.csv'
test = pd.read_csv(test_path, sep='\t')[['session_id', 'item_id', 'created_at']]
test_dataset = SessionDataset(test)
test_generator = SessionDataLoader(test_dataset, batch_size=batch_size)
session_groups = test.groupby("session_id")
mapitem = loader.dataset.itemmap
item_idx_map = {}
idx_item_map = {}
for index, row in mapitem.iterrows():
item_id = row["item_id"]
item_idx = row["item_idx"]
item_idx_map[item_id] = item_idx
idx_item_map[item_idx] = item_id
predict_path = "../../data/cb12/interim/predict/base/"
model_name = "cb12_prnn_a_" + act + "_ls_" + str(ls) + "_lr_" + str(lr) + ".model2"
model = pickle.load(open(model_path + model_name, 'rb'))
print("Loaded: " + model_name)
res_list = []
report_freq = len(session_groups) // 5
count = 0
for sid, session in session_groups:
pred_df = predict_function(sid, session, model, item_idx_map, idx_item_map)
res_list.append(pred_df)
model.get_layer('gru_left').reset_states()
model.get_layer('gru_right').reset_states()
count += 1
if count % report_freq == 0:
print("Predicted for " + str(count) + " sessions. " + str(len(session_groups) - count) + " sessions to go." )
res = pd.concat(res_list)
res = res.reindex(columns = ["session_id", "input_items", "input_count", "position", "remaining_items", "remaining_count", "predictions"])
res.to_csv(predict_path + "test_14d_prnn2.csv", sep='\t')
print("Stored predictions: " + predict_path + "test_14d_prnn2.csv")
| true | true |
f728058691d28517eb5f80d44183878ec58ae0fc | 1,050 | py | Python | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python | ace9f577d9700fe290d80822230acb8e87833bc2 | [
"MIT"
] | null | null | null | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python | ace9f577d9700fe290d80822230acb8e87833bc2 | [
"MIT"
] | null | null | null | Structural/object_adapter.py | TheVikingGent/DesignPatterns4Python | ace9f577d9700fe290d80822230acb8e87833bc2 | [
"MIT"
] | null | null | null | # This is the object-based adapter pattern
# It allows us to take an outside class 'StrangeCreature' with a different interface,
# and squeeze that SOB into another hierachy.
# The good thing about the object version of this pattern is that if StrangeCreature had
# a lot of subtypes, we would not need to write an adapter for each subtype.
#(I don't think this is relevant considering Pythons Dynamic Typing, but it's good to know for something like C++ I'm guessing)
import abc
class StrangeCreature(object):
def make_horrible_noise(self):
print("Rawr")
class Animal(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def make_noise(self):
raise NotImplementedError
class Horse(Animal):
def make_noise(self):
print("Vrinsk")
class Platypus(Animal):
_strange_creature = None
def __init__(self):
self._strange_creature = StrangeCreature()
def make_noise(self):
return self._strange_creature.make_horrible_noise()
p = Platypus()
p.make_noise()
h = Horse()
h.make_noise() | 30 | 127 | 0.728571 |
import abc
class StrangeCreature(object):
def make_horrible_noise(self):
print("Rawr")
class Animal(object, metaclass=abc.ABCMeta):
@abc.abstractmethod
def make_noise(self):
raise NotImplementedError
class Horse(Animal):
def make_noise(self):
print("Vrinsk")
class Platypus(Animal):
_strange_creature = None
def __init__(self):
self._strange_creature = StrangeCreature()
def make_noise(self):
return self._strange_creature.make_horrible_noise()
p = Platypus()
p.make_noise()
h = Horse()
h.make_noise() | true | true |
f728064f24ce70cc0b19b13c3a4c9545b7424ef4 | 849 | py | Python | tests/admin/test_pages.py | KaitoRyouga/CTFd | 827a22e8ce9bdfd43ae0689e6cbcf2a6e253e920 | [
"Apache-2.0"
] | null | null | null | tests/admin/test_pages.py | KaitoRyouga/CTFd | 827a22e8ce9bdfd43ae0689e6cbcf2a6e253e920 | [
"Apache-2.0"
] | null | null | null | tests/admin/test_pages.py | KaitoRyouga/CTFd | 827a22e8ce9bdfd43ae0689e6cbcf2a6e253e920 | [
"Apache-2.0"
] | null | null | null | from tests.helpers import create_ctfd, destroy_ctfd, login_as_user
def test_previewing_pages_works():
"""Test that pages can be previewed properly"""
app = create_ctfd()
with app.app_context():
client = login_as_user(app, name="admin", password="password")
with client.session_transaction() as sess:
data = {
"title": "title",
"route": "route",
"content": "content_testing",
"nonce": sess.get("nonce"),
"draft": "y",
"hidden": "y",
"auth_required": "y",
}
r = client.post("/admin/pages/preview", data=data)
assert r.status_code == 200
resp = r.get_data(as_text=True)
assert "content_testing" in resp
destroy_ctfd(app)
| 31.444444 | 71 | 0.530035 | from tests.helpers import create_ctfd, destroy_ctfd, login_as_user
def test_previewing_pages_works():
app = create_ctfd()
with app.app_context():
client = login_as_user(app, name="admin", password="password")
with client.session_transaction() as sess:
data = {
"title": "title",
"route": "route",
"content": "content_testing",
"nonce": sess.get("nonce"),
"draft": "y",
"hidden": "y",
"auth_required": "y",
}
r = client.post("/admin/pages/preview", data=data)
assert r.status_code == 200
resp = r.get_data(as_text=True)
assert "content_testing" in resp
destroy_ctfd(app)
| true | true |
f72806f1b468e69088235a72960fae80ff004757 | 752 | py | Python | phase2_scripts/p2_inference_test25_1M_epoch16.py | socom20/facebook-image-similarity-challenge-2021 | bf4226241be30cdf99180543f214edf571043e8d | [
"MIT"
] | 8 | 2021-12-02T04:05:59.000Z | 2022-02-23T07:57:22.000Z | phase2_scripts/p2_inference_test25_1M_epoch16.py | socom20/facebook-image-similarity-challenge-2021 | bf4226241be30cdf99180543f214edf571043e8d | [
"MIT"
] | 1 | 2021-12-07T07:05:37.000Z | 2021-12-08T02:24:17.000Z | phase2_scripts/p2_inference_test25_1M_epoch16.py | socom20/facebook-image-similarity-challenge-2021 | bf4226241be30cdf99180543f214edf571043e8d | [
"MIT"
] | 4 | 2021-12-12T09:58:01.000Z | 2022-03-29T05:50:57.000Z | #!/usr/bin/env python
# coding: utf-8
# In[1]:
from model_inference import do_inference
# In[ ]:
from modules.Facebook_AF_model_v25 import ArgsT25_NfNetl1_ImageNet, FacebookModel
ckpt_filename = './checkpoints/smp_test25/FacebookModel_epoch=16_trn_loss_epoch=0.9023_trn_acc_epoch=0.0000_val_loss_epoch=0.4303_val_acc_epoch=0.9911.ckpt'
args = ArgsT25_NfNetl1_ImageNet()
args.BATCH_SIZE = 128
args.N_WORKERS = 7
args.DS_INPUT_DIR = f'./all_datasets/dataset'
args.pretrained_bb = False
args.arc_classnum = 40
args.ALL_FOLDERS = ['query_images', 'reference_images', 'training_images']
args.faiss_gpu_id = 0
args.phase_2 = True
model = FacebookModel(args)
_ = model.restore_checkpoint(ckpt_filename)
do_inference(model, args, ckpt_filename)
| 21.485714 | 156 | 0.793883 |
from model_inference import do_inference
from modules.Facebook_AF_model_v25 import ArgsT25_NfNetl1_ImageNet, FacebookModel
ckpt_filename = './checkpoints/smp_test25/FacebookModel_epoch=16_trn_loss_epoch=0.9023_trn_acc_epoch=0.0000_val_loss_epoch=0.4303_val_acc_epoch=0.9911.ckpt'
args = ArgsT25_NfNetl1_ImageNet()
args.BATCH_SIZE = 128
args.N_WORKERS = 7
args.DS_INPUT_DIR = f'./all_datasets/dataset'
args.pretrained_bb = False
args.arc_classnum = 40
args.ALL_FOLDERS = ['query_images', 'reference_images', 'training_images']
args.faiss_gpu_id = 0
args.phase_2 = True
model = FacebookModel(args)
_ = model.restore_checkpoint(ckpt_filename)
do_inference(model, args, ckpt_filename)
| true | true |
f7280780dc6c97a9f7524378205551ce5bb10c36 | 1,601 | py | Python | migrations/versions/0221_nullable_service_branding.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 51 | 2016-04-03T23:36:17.000Z | 2022-03-21T20:04:52.000Z | migrations/versions/0221_nullable_service_branding.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 1,335 | 2015-12-15T14:28:50.000Z | 2022-03-30T16:24:27.000Z | migrations/versions/0221_nullable_service_branding.py | tlwr/notifications-api | 88a6b7729edb9be41ce3e7c027f1452b7b6d00d2 | [
"MIT"
] | 30 | 2016-01-08T19:05:32.000Z | 2021-12-20T16:37:23.000Z | """
Revision ID: 0221_nullable_service_branding
Revises: 0220_email_brand_type_non_null
Create Date: 2018-08-24 13:36:49.346156
"""
from alembic import op
from app.models import BRANDING_ORG, BRANDING_GOVUK
revision = '0221_nullable_service_branding'
down_revision = '0220_email_brand_type_non_null'
def upgrade():
op.drop_constraint('services_branding_fkey', 'services', type_='foreignkey')
op.drop_index('ix_services_history_branding', table_name='services_history')
op.drop_index('ix_services_branding', table_name='services')
op.alter_column('services_history', 'branding', nullable=True)
op.alter_column('services', 'branding', nullable=True)
op.execute("""
update
email_branding
set
brand_type = '{}'
where
brand_type = '{}'
""".format(BRANDING_ORG, BRANDING_GOVUK))
op.execute("""
delete from
branding_type
where
name = '{}'
""".format(BRANDING_GOVUK))
def downgrade():
op.create_index(op.f('ix_services_branding'), 'services', ['branding'], unique=False)
op.create_index(op.f('ix_services_history_branding'), 'services_history', ['branding'], unique=False)
op.create_foreign_key(None, 'services', 'branding_type', ['branding'], ['name'])
op.alter_column('services', 'branding', nullable=False)
op.alter_column('services_history', 'branding', nullable=False)
op.execute("""
insert into
branding_type
(name)
values
('{}')
""".format(BRANDING_GOVUK))
| 27.603448 | 105 | 0.656465 | from alembic import op
from app.models import BRANDING_ORG, BRANDING_GOVUK
revision = '0221_nullable_service_branding'
down_revision = '0220_email_brand_type_non_null'
def upgrade():
op.drop_constraint('services_branding_fkey', 'services', type_='foreignkey')
op.drop_index('ix_services_history_branding', table_name='services_history')
op.drop_index('ix_services_branding', table_name='services')
op.alter_column('services_history', 'branding', nullable=True)
op.alter_column('services', 'branding', nullable=True)
op.execute("""
update
email_branding
set
brand_type = '{}'
where
brand_type = '{}'
""".format(BRANDING_ORG, BRANDING_GOVUK))
op.execute("""
delete from
branding_type
where
name = '{}'
""".format(BRANDING_GOVUK))
def downgrade():
op.create_index(op.f('ix_services_branding'), 'services', ['branding'], unique=False)
op.create_index(op.f('ix_services_history_branding'), 'services_history', ['branding'], unique=False)
op.create_foreign_key(None, 'services', 'branding_type', ['branding'], ['name'])
op.alter_column('services', 'branding', nullable=False)
op.alter_column('services_history', 'branding', nullable=False)
op.execute("""
insert into
branding_type
(name)
values
('{}')
""".format(BRANDING_GOVUK))
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.