repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_add | def gen_add(src1, src2, dst):
"""Return an ADD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.ADD, src1, src2, dst) | python | def gen_add(src1, src2, dst):
"""Return an ADD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.ADD, src1, src2, dst) | [
"def",
"gen_add",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"ADD",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return an ADD instruction. | [
"Return",
"an",
"ADD",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L40-L45 | train | 198,500 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_sub | def gen_sub(src1, src2, dst):
"""Return a SUB instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SUB, src1, src2, dst) | python | def gen_sub(src1, src2, dst):
"""Return a SUB instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SUB, src1, src2, dst) | [
"def",
"gen_sub",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"SUB",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a SUB instruction. | [
"Return",
"a",
"SUB",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L48-L53 | train | 198,501 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_mul | def gen_mul(src1, src2, dst):
"""Return a MUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MUL, src1, src2, dst) | python | def gen_mul(src1, src2, dst):
"""Return a MUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MUL, src1, src2, dst) | [
"def",
"gen_mul",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"MUL",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a MUL instruction. | [
"Return",
"a",
"MUL",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L56-L61 | train | 198,502 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_div | def gen_div(src1, src2, dst):
"""Return a DIV instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.DIV, src1, src2, dst) | python | def gen_div(src1, src2, dst):
"""Return a DIV instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.DIV, src1, src2, dst) | [
"def",
"gen_div",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"DIV",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a DIV instruction. | [
"Return",
"a",
"DIV",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L64-L69 | train | 198,503 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_mod | def gen_mod(src1, src2, dst):
"""Return a MOD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MOD, src1, src2, dst) | python | def gen_mod(src1, src2, dst):
"""Return a MOD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.MOD, src1, src2, dst) | [
"def",
"gen_mod",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"MOD",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a MOD instruction. | [
"Return",
"a",
"MOD",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L72-L77 | train | 198,504 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_bsh | def gen_bsh(src1, src2, dst):
"""Return a BSH instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.BSH, src1, src2, dst) | python | def gen_bsh(src1, src2, dst):
"""Return a BSH instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.BSH, src1, src2, dst) | [
"def",
"gen_bsh",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"BSH",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a BSH instruction. | [
"Return",
"a",
"BSH",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L80-L85 | train | 198,505 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_and | def gen_and(src1, src2, dst):
"""Return an AND instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst) | python | def gen_and(src1, src2, dst):
"""Return an AND instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.AND, src1, src2, dst) | [
"def",
"gen_and",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"AND",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return an AND instruction. | [
"Return",
"an",
"AND",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L90-L95 | train | 198,506 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_or | def gen_or(src1, src2, dst):
"""Return an OR instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.OR, src1, src2, dst) | python | def gen_or(src1, src2, dst):
"""Return an OR instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.OR, src1, src2, dst) | [
"def",
"gen_or",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"OR",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return an OR instruction. | [
"Return",
"an",
"OR",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L98-L103 | train | 198,507 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_xor | def gen_xor(src1, src2, dst):
"""Return a XOR instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.XOR, src1, src2, dst) | python | def gen_xor(src1, src2, dst):
"""Return a XOR instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.XOR, src1, src2, dst) | [
"def",
"gen_xor",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"XOR",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a XOR instruction. | [
"Return",
"a",
"XOR",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L106-L111 | train | 198,508 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_ldm | def gen_ldm(src, dst):
"""Return a LDM instruction.
"""
return ReilBuilder.build(ReilMnemonic.LDM, src, ReilEmptyOperand(), dst) | python | def gen_ldm(src, dst):
"""Return a LDM instruction.
"""
return ReilBuilder.build(ReilMnemonic.LDM, src, ReilEmptyOperand(), dst) | [
"def",
"gen_ldm",
"(",
"src",
",",
"dst",
")",
":",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"LDM",
",",
"src",
",",
"ReilEmptyOperand",
"(",
")",
",",
"dst",
")"
] | Return a LDM instruction. | [
"Return",
"a",
"LDM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L116-L119 | train | 198,509 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_stm | def gen_stm(src, dst):
"""Return a STM instruction.
"""
return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst) | python | def gen_stm(src, dst):
"""Return a STM instruction.
"""
return ReilBuilder.build(ReilMnemonic.STM, src, ReilEmptyOperand(), dst) | [
"def",
"gen_stm",
"(",
"src",
",",
"dst",
")",
":",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"STM",
",",
"src",
",",
"ReilEmptyOperand",
"(",
")",
",",
"dst",
")"
] | Return a STM instruction. | [
"Return",
"a",
"STM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L122-L125 | train | 198,510 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_str | def gen_str(src, dst):
"""Return a STR instruction.
"""
return ReilBuilder.build(ReilMnemonic.STR, src, ReilEmptyOperand(), dst) | python | def gen_str(src, dst):
"""Return a STR instruction.
"""
return ReilBuilder.build(ReilMnemonic.STR, src, ReilEmptyOperand(), dst) | [
"def",
"gen_str",
"(",
"src",
",",
"dst",
")",
":",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"STR",
",",
"src",
",",
"ReilEmptyOperand",
"(",
")",
",",
"dst",
")"
] | Return a STR instruction. | [
"Return",
"a",
"STR",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L128-L131 | train | 198,511 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_bisz | def gen_bisz(src, dst):
"""Return a BISZ instruction.
"""
return ReilBuilder.build(ReilMnemonic.BISZ, src, ReilEmptyOperand(), dst) | python | def gen_bisz(src, dst):
"""Return a BISZ instruction.
"""
return ReilBuilder.build(ReilMnemonic.BISZ, src, ReilEmptyOperand(), dst) | [
"def",
"gen_bisz",
"(",
"src",
",",
"dst",
")",
":",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"BISZ",
",",
"src",
",",
"ReilEmptyOperand",
"(",
")",
",",
"dst",
")"
] | Return a BISZ instruction. | [
"Return",
"a",
"BISZ",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L136-L139 | train | 198,512 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_jcc | def gen_jcc(src, dst):
"""Return a JCC instruction.
"""
return ReilBuilder.build(ReilMnemonic.JCC, src, ReilEmptyOperand(), dst) | python | def gen_jcc(src, dst):
"""Return a JCC instruction.
"""
return ReilBuilder.build(ReilMnemonic.JCC, src, ReilEmptyOperand(), dst) | [
"def",
"gen_jcc",
"(",
"src",
",",
"dst",
")",
":",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"JCC",
",",
"src",
",",
"ReilEmptyOperand",
"(",
")",
",",
"dst",
")"
] | Return a JCC instruction. | [
"Return",
"a",
"JCC",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L142-L145 | train | 198,513 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_unkn | def gen_unkn():
"""Return an UNKN instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNKN, empty_reg, empty_reg, empty_reg) | python | def gen_unkn():
"""Return an UNKN instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNKN, empty_reg, empty_reg, empty_reg) | [
"def",
"gen_unkn",
"(",
")",
":",
"empty_reg",
"=",
"ReilEmptyOperand",
"(",
")",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"UNKN",
",",
"empty_reg",
",",
"empty_reg",
",",
"empty_reg",
")"
] | Return an UNKN instruction. | [
"Return",
"an",
"UNKN",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L150-L155 | train | 198,514 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_undef | def gen_undef():
"""Return an UNDEF instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNDEF, empty_reg, empty_reg, empty_reg) | python | def gen_undef():
"""Return an UNDEF instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.UNDEF, empty_reg, empty_reg, empty_reg) | [
"def",
"gen_undef",
"(",
")",
":",
"empty_reg",
"=",
"ReilEmptyOperand",
"(",
")",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"UNDEF",
",",
"empty_reg",
",",
"empty_reg",
",",
"empty_reg",
")"
] | Return an UNDEF instruction. | [
"Return",
"an",
"UNDEF",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L158-L163 | train | 198,515 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_nop | def gen_nop():
"""Return a NOP instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg) | python | def gen_nop():
"""Return a NOP instruction.
"""
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.NOP, empty_reg, empty_reg, empty_reg) | [
"def",
"gen_nop",
"(",
")",
":",
"empty_reg",
"=",
"ReilEmptyOperand",
"(",
")",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"NOP",
",",
"empty_reg",
",",
"empty_reg",
",",
"empty_reg",
")"
] | Return a NOP instruction. | [
"Return",
"a",
"NOP",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L166-L171 | train | 198,516 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_sext | def gen_sext(src, dst):
"""Return a SEXT instruction.
"""
assert src.size <= dst.size
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.SEXT, src, empty_reg, dst) | python | def gen_sext(src, dst):
"""Return a SEXT instruction.
"""
assert src.size <= dst.size
empty_reg = ReilEmptyOperand()
return ReilBuilder.build(ReilMnemonic.SEXT, src, empty_reg, dst) | [
"def",
"gen_sext",
"(",
"src",
",",
"dst",
")",
":",
"assert",
"src",
".",
"size",
"<=",
"dst",
".",
"size",
"empty_reg",
"=",
"ReilEmptyOperand",
"(",
")",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"SEXT",
",",
"src",
",",
"empt... | Return a SEXT instruction. | [
"Return",
"a",
"SEXT",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L176-L183 | train | 198,517 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_sdiv | def gen_sdiv(src1, src2, dst):
"""Return a SDIV instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SDIV, src1, src2, dst) | python | def gen_sdiv(src1, src2, dst):
"""Return a SDIV instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SDIV, src1, src2, dst) | [
"def",
"gen_sdiv",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"SDIV",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a SDIV instruction. | [
"Return",
"a",
"SDIV",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L186-L191 | train | 198,518 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_smod | def gen_smod(src1, src2, dst):
"""Return a SMOD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMOD, src1, src2, dst) | python | def gen_smod(src1, src2, dst):
"""Return a SMOD instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMOD, src1, src2, dst) | [
"def",
"gen_smod",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"SMOD",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a SMOD instruction. | [
"Return",
"a",
"SMOD",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L194-L199 | train | 198,519 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.gen_smul | def gen_smul(src1, src2, dst):
"""Return a SMUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMUL, src1, src2, dst) | python | def gen_smul(src1, src2, dst):
"""Return a SMUL instruction.
"""
assert src1.size == src2.size
return ReilBuilder.build(ReilMnemonic.SMUL, src1, src2, dst) | [
"def",
"gen_smul",
"(",
"src1",
",",
"src2",
",",
"dst",
")",
":",
"assert",
"src1",
".",
"size",
"==",
"src2",
".",
"size",
"return",
"ReilBuilder",
".",
"build",
"(",
"ReilMnemonic",
".",
"SMUL",
",",
"src1",
",",
"src2",
",",
"dst",
")"
] | Return a SMUL instruction. | [
"Return",
"a",
"SMUL",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L202-L207 | train | 198,520 |
programa-stic/barf-project | barf/core/reil/builder.py | ReilBuilder.build | def build(mnemonic, oprnd1, oprnd2, oprnd3):
"""Return the specified instruction.
"""
ins = ReilInstruction()
ins.mnemonic = mnemonic
ins.operands = [oprnd1, oprnd2, oprnd3]
return ins | python | def build(mnemonic, oprnd1, oprnd2, oprnd3):
"""Return the specified instruction.
"""
ins = ReilInstruction()
ins.mnemonic = mnemonic
ins.operands = [oprnd1, oprnd2, oprnd3]
return ins | [
"def",
"build",
"(",
"mnemonic",
",",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
")",
":",
"ins",
"=",
"ReilInstruction",
"(",
")",
"ins",
".",
"mnemonic",
"=",
"mnemonic",
"ins",
".",
"operands",
"=",
"[",
"oprnd1",
",",
"oprnd2",
",",
"oprnd3",
"]",
"... | Return the specified instruction. | [
"Return",
"the",
"specified",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/builder.py#L212-L220 | train | 198,521 |
programa-stic/barf-project | barf/barf.py | BARF._setup_arch | def _setup_arch(self, arch_mode=None):
"""Set up architecture.
"""
# set up architecture information
self.arch_info = None
if self.binary.architecture == ARCH_X86:
self._setup_x86_arch(arch_mode)
else:
# TODO: add arch to the binary file class.
self._setup_arm_arch(arch_mode) | python | def _setup_arch(self, arch_mode=None):
"""Set up architecture.
"""
# set up architecture information
self.arch_info = None
if self.binary.architecture == ARCH_X86:
self._setup_x86_arch(arch_mode)
else:
# TODO: add arch to the binary file class.
self._setup_arm_arch(arch_mode) | [
"def",
"_setup_arch",
"(",
"self",
",",
"arch_mode",
"=",
"None",
")",
":",
"# set up architecture information",
"self",
".",
"arch_info",
"=",
"None",
"if",
"self",
".",
"binary",
".",
"architecture",
"==",
"ARCH_X86",
":",
"self",
".",
"_setup_x86_arch",
"("... | Set up architecture. | [
"Set",
"up",
"architecture",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L105-L115 | train | 198,522 |
programa-stic/barf-project | barf/barf.py | BARF._setup_arm_arch | def _setup_arm_arch(self, arch_mode=None):
"""Set up ARM architecture.
"""
if arch_mode is None:
arch_mode = ARCH_ARM_MODE_THUMB
self.name = "ARM"
self.arch_info = ArmArchitectureInformation(arch_mode)
self.disassembler = ArmDisassembler(architecture_mode=arch_mode)
self.ir_translator = ArmTranslator(architecture_mode=arch_mode) | python | def _setup_arm_arch(self, arch_mode=None):
"""Set up ARM architecture.
"""
if arch_mode is None:
arch_mode = ARCH_ARM_MODE_THUMB
self.name = "ARM"
self.arch_info = ArmArchitectureInformation(arch_mode)
self.disassembler = ArmDisassembler(architecture_mode=arch_mode)
self.ir_translator = ArmTranslator(architecture_mode=arch_mode) | [
"def",
"_setup_arm_arch",
"(",
"self",
",",
"arch_mode",
"=",
"None",
")",
":",
"if",
"arch_mode",
"is",
"None",
":",
"arch_mode",
"=",
"ARCH_ARM_MODE_THUMB",
"self",
".",
"name",
"=",
"\"ARM\"",
"self",
".",
"arch_info",
"=",
"ArmArchitectureInformation",
"("... | Set up ARM architecture. | [
"Set",
"up",
"ARM",
"architecture",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L117-L126 | train | 198,523 |
programa-stic/barf-project | barf/barf.py | BARF._setup_x86_arch | def _setup_x86_arch(self, arch_mode=None):
"""Set up x86 architecture.
"""
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Set up architecture information
self.name = "x86"
self.arch_info = X86ArchitectureInformation(arch_mode)
self.disassembler = X86Disassembler(arch_mode)
self.ir_translator = X86Translator(arch_mode) | python | def _setup_x86_arch(self, arch_mode=None):
"""Set up x86 architecture.
"""
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Set up architecture information
self.name = "x86"
self.arch_info = X86ArchitectureInformation(arch_mode)
self.disassembler = X86Disassembler(arch_mode)
self.ir_translator = X86Translator(arch_mode) | [
"def",
"_setup_x86_arch",
"(",
"self",
",",
"arch_mode",
"=",
"None",
")",
":",
"if",
"arch_mode",
"is",
"None",
":",
"arch_mode",
"=",
"self",
".",
"binary",
".",
"architecture_mode",
"# Set up architecture information",
"self",
".",
"name",
"=",
"\"x86\"",
"... | Set up x86 architecture. | [
"Set",
"up",
"x86",
"architecture",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L128-L138 | train | 198,524 |
programa-stic/barf-project | barf/barf.py | BARF._setup_core_modules | def _setup_core_modules(self):
"""Set up core modules.
"""
self.ir_emulator = None
self.smt_solver = None
self.smt_translator = None
if self.arch_info:
# Set REIL emulator.
self.ir_emulator = ReilEmulator(self.arch_info)
# Set SMT Solver.
self.smt_solver = None
if SMT_SOLVER not in ("Z3", "CVC4"):
raise Exception("{} SMT solver not supported.".format(SMT_SOLVER))
try:
if SMT_SOLVER == "Z3":
self.smt_solver = Z3Solver()
elif SMT_SOLVER == "CVC4":
self.smt_solver = CVC4Solver()
except SmtSolverNotFound:
logger.warn("{} Solver is not installed. Run 'barf-install-solvers.sh' to install it.".format(SMT_SOLVER))
# Set SMT translator.
self.smt_translator = None
if self.smt_solver:
self.smt_translator = SmtTranslator(self.smt_solver, self.arch_info.address_size)
self.smt_translator.set_arch_alias_mapper(self.arch_info.alias_mapper)
self.smt_translator.set_arch_registers_size(self.arch_info.registers_size) | python | def _setup_core_modules(self):
"""Set up core modules.
"""
self.ir_emulator = None
self.smt_solver = None
self.smt_translator = None
if self.arch_info:
# Set REIL emulator.
self.ir_emulator = ReilEmulator(self.arch_info)
# Set SMT Solver.
self.smt_solver = None
if SMT_SOLVER not in ("Z3", "CVC4"):
raise Exception("{} SMT solver not supported.".format(SMT_SOLVER))
try:
if SMT_SOLVER == "Z3":
self.smt_solver = Z3Solver()
elif SMT_SOLVER == "CVC4":
self.smt_solver = CVC4Solver()
except SmtSolverNotFound:
logger.warn("{} Solver is not installed. Run 'barf-install-solvers.sh' to install it.".format(SMT_SOLVER))
# Set SMT translator.
self.smt_translator = None
if self.smt_solver:
self.smt_translator = SmtTranslator(self.smt_solver, self.arch_info.address_size)
self.smt_translator.set_arch_alias_mapper(self.arch_info.alias_mapper)
self.smt_translator.set_arch_registers_size(self.arch_info.registers_size) | [
"def",
"_setup_core_modules",
"(",
"self",
")",
":",
"self",
".",
"ir_emulator",
"=",
"None",
"self",
".",
"smt_solver",
"=",
"None",
"self",
".",
"smt_translator",
"=",
"None",
"if",
"self",
".",
"arch_info",
":",
"# Set REIL emulator.",
"self",
".",
"ir_em... | Set up core modules. | [
"Set",
"up",
"core",
"modules",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L140-L172 | train | 198,525 |
programa-stic/barf-project | barf/barf.py | BARF._setup_analysis_modules | def _setup_analysis_modules(self):
"""Set up analysis modules.
"""
# Basic block.
self.bb_builder = CFGRecoverer(RecursiveDescent(self.disassembler, self.text_section, self.ir_translator,
self.arch_info))
# Code analyzer.
self.code_analyzer = None
if self.smt_translator:
self.code_analyzer = CodeAnalyzer(self.smt_solver, self.smt_translator, self.arch_info)
# Gadgets classifier.
self.gadget_classifier = GadgetClassifier(self.ir_emulator, self.arch_info)
# Gadgets finder.
self.gadget_finder = GadgetFinder(self.disassembler, self.text_section, self.ir_translator,
self.binary.architecture, self.binary.architecture_mode)
# Gadget verifier.
self.gadget_verifier = None
if self.code_analyzer:
self.gadget_verifier = GadgetVerifier(self.code_analyzer, self.arch_info)
self.emulator = Emulator(self.arch_info, self.ir_emulator, self.ir_translator, self.disassembler) | python | def _setup_analysis_modules(self):
"""Set up analysis modules.
"""
# Basic block.
self.bb_builder = CFGRecoverer(RecursiveDescent(self.disassembler, self.text_section, self.ir_translator,
self.arch_info))
# Code analyzer.
self.code_analyzer = None
if self.smt_translator:
self.code_analyzer = CodeAnalyzer(self.smt_solver, self.smt_translator, self.arch_info)
# Gadgets classifier.
self.gadget_classifier = GadgetClassifier(self.ir_emulator, self.arch_info)
# Gadgets finder.
self.gadget_finder = GadgetFinder(self.disassembler, self.text_section, self.ir_translator,
self.binary.architecture, self.binary.architecture_mode)
# Gadget verifier.
self.gadget_verifier = None
if self.code_analyzer:
self.gadget_verifier = GadgetVerifier(self.code_analyzer, self.arch_info)
self.emulator = Emulator(self.arch_info, self.ir_emulator, self.ir_translator, self.disassembler) | [
"def",
"_setup_analysis_modules",
"(",
"self",
")",
":",
"# Basic block.",
"self",
".",
"bb_builder",
"=",
"CFGRecoverer",
"(",
"RecursiveDescent",
"(",
"self",
".",
"disassembler",
",",
"self",
".",
"text_section",
",",
"self",
".",
"ir_translator",
",",
"self"... | Set up analysis modules. | [
"Set",
"up",
"analysis",
"modules",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L174-L200 | train | 198,526 |
programa-stic/barf-project | barf/barf.py | BARF.open | def open(self, filename):
"""Open a file for analysis.
Args:
filename (str): Name of an executable file.
"""
if filename:
self.binary = BinaryFile(filename)
self.text_section = self.binary.text_section
self._load(arch_mode=self.binary.architecture_mode) | python | def open(self, filename):
"""Open a file for analysis.
Args:
filename (str): Name of an executable file.
"""
if filename:
self.binary = BinaryFile(filename)
self.text_section = self.binary.text_section
self._load(arch_mode=self.binary.architecture_mode) | [
"def",
"open",
"(",
"self",
",",
"filename",
")",
":",
"if",
"filename",
":",
"self",
".",
"binary",
"=",
"BinaryFile",
"(",
"filename",
")",
"self",
".",
"text_section",
"=",
"self",
".",
"binary",
".",
"text_section",
"self",
".",
"_load",
"(",
"arch... | Open a file for analysis.
Args:
filename (str): Name of an executable file. | [
"Open",
"a",
"file",
"for",
"analysis",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L204-L214 | train | 198,527 |
programa-stic/barf-project | barf/barf.py | BARF.disassemble | def disassemble(self, start=None, end=None, arch_mode=None):
"""Disassemble native instructions.
Args:
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
Returns:
(int, Instruction, int): A tuple of the form (address, assembler instruction, instruction size).
"""
if arch_mode is None:
arch_mode = self.binary.architecture_mode
curr_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
while curr_addr < end_addr:
# Fetch the instruction.
encoding = self.__fetch_instr(curr_addr)
# Decode it.
asm_instr = self.disassembler.disassemble(encoding, curr_addr, architecture_mode=arch_mode)
if not asm_instr:
return
yield curr_addr, asm_instr, asm_instr.size
# update instruction pointer
curr_addr += asm_instr.size | python | def disassemble(self, start=None, end=None, arch_mode=None):
"""Disassemble native instructions.
Args:
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
Returns:
(int, Instruction, int): A tuple of the form (address, assembler instruction, instruction size).
"""
if arch_mode is None:
arch_mode = self.binary.architecture_mode
curr_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
while curr_addr < end_addr:
# Fetch the instruction.
encoding = self.__fetch_instr(curr_addr)
# Decode it.
asm_instr = self.disassembler.disassemble(encoding, curr_addr, architecture_mode=arch_mode)
if not asm_instr:
return
yield curr_addr, asm_instr, asm_instr.size
# update instruction pointer
curr_addr += asm_instr.size | [
"def",
"disassemble",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"arch_mode",
"=",
"None",
")",
":",
"if",
"arch_mode",
"is",
"None",
":",
"arch_mode",
"=",
"self",
".",
"binary",
".",
"architecture_mode",
"curr_addr",
"=",
"... | Disassemble native instructions.
Args:
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
Returns:
(int, Instruction, int): A tuple of the form (address, assembler instruction, instruction size). | [
"Disassemble",
"native",
"instructions",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L253-L283 | train | 198,528 |
programa-stic/barf-project | barf/barf.py | BARF.recover_cfg | def recover_cfg(self, start=None, end=None, symbols=None, callback=None, arch_mode=None):
"""Recover CFG.
Args:
start (int): Start address.
end (int): End address.
symbols (dict): Symbol table.
callback (function): A callback function which is called after each successfully recovered CFG.
arch_mode (int): Architecture mode.
Returns:
ControlFlowGraph: A CFG.
"""
# Set architecture in case it wasn't already set.
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Reload modules.
self._load(arch_mode=arch_mode)
# Check start address.
start = start if start else self.binary.entry_point
cfg, _ = self._recover_cfg(start=start, end=end, symbols=symbols, callback=callback)
return cfg | python | def recover_cfg(self, start=None, end=None, symbols=None, callback=None, arch_mode=None):
"""Recover CFG.
Args:
start (int): Start address.
end (int): End address.
symbols (dict): Symbol table.
callback (function): A callback function which is called after each successfully recovered CFG.
arch_mode (int): Architecture mode.
Returns:
ControlFlowGraph: A CFG.
"""
# Set architecture in case it wasn't already set.
if arch_mode is None:
arch_mode = self.binary.architecture_mode
# Reload modules.
self._load(arch_mode=arch_mode)
# Check start address.
start = start if start else self.binary.entry_point
cfg, _ = self._recover_cfg(start=start, end=end, symbols=symbols, callback=callback)
return cfg | [
"def",
"recover_cfg",
"(",
"self",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"symbols",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"arch_mode",
"=",
"None",
")",
":",
"# Set architecture in case it wasn't already set.",
"if",
"arch_mode",
... | Recover CFG.
Args:
start (int): Start address.
end (int): End address.
symbols (dict): Symbol table.
callback (function): A callback function which is called after each successfully recovered CFG.
arch_mode (int): Architecture mode.
Returns:
ControlFlowGraph: A CFG. | [
"Recover",
"CFG",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L285-L310 | train | 198,529 |
programa-stic/barf-project | barf/barf.py | BARF.emulate | def emulate(self, context=None, start=None, end=None, arch_mode=None, hooks=None, max_instrs=None, print_asm=False):
"""Emulate native code.
Args:
context (dict): Processor context (register and/or memory).
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
hooks (dict): Hooks by address.
max_instrs (int): Maximum number of instructions to execute.
print_asm (bool): Print asm.
Returns:
dict: Processor context.
"""
if arch_mode is not None:
# Reload modules.
self._load(arch_mode=arch_mode)
context = context if context else {}
start_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
hooks = hooks if hooks else {}
# Load registers
for reg, val in context.get('registers', {}).items():
self.ir_emulator.registers[reg] = val
# Load memory
# TODO Memory content should be encoded as hex strings so each
# entry can be of different sizes.
for addr, val in context.get('memory', {}).items():
self.ir_emulator.memory.write(addr, 4, val)
# Execute the code.
self.emulator.emulate(start_addr, end_addr, hooks, max_instrs, print_asm)
context_out = {
'registers': {},
'memory': {}
}
# save registers
for reg, val in self.ir_emulator.registers.items():
context_out['registers'][reg] = val
return context_out | python | def emulate(self, context=None, start=None, end=None, arch_mode=None, hooks=None, max_instrs=None, print_asm=False):
"""Emulate native code.
Args:
context (dict): Processor context (register and/or memory).
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
hooks (dict): Hooks by address.
max_instrs (int): Maximum number of instructions to execute.
print_asm (bool): Print asm.
Returns:
dict: Processor context.
"""
if arch_mode is not None:
# Reload modules.
self._load(arch_mode=arch_mode)
context = context if context else {}
start_addr = start if start else self.binary.ea_start
end_addr = end if end else self.binary.ea_end
hooks = hooks if hooks else {}
# Load registers
for reg, val in context.get('registers', {}).items():
self.ir_emulator.registers[reg] = val
# Load memory
# TODO Memory content should be encoded as hex strings so each
# entry can be of different sizes.
for addr, val in context.get('memory', {}).items():
self.ir_emulator.memory.write(addr, 4, val)
# Execute the code.
self.emulator.emulate(start_addr, end_addr, hooks, max_instrs, print_asm)
context_out = {
'registers': {},
'memory': {}
}
# save registers
for reg, val in self.ir_emulator.registers.items():
context_out['registers'][reg] = val
return context_out | [
"def",
"emulate",
"(",
"self",
",",
"context",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"arch_mode",
"=",
"None",
",",
"hooks",
"=",
"None",
",",
"max_instrs",
"=",
"None",
",",
"print_asm",
"=",
"False",
")",
":",
"if"... | Emulate native code.
Args:
context (dict): Processor context (register and/or memory).
start (int): Start address.
end (int): End address.
arch_mode (int): Architecture mode.
hooks (dict): Hooks by address.
max_instrs (int): Maximum number of instructions to execute.
print_asm (bool): Print asm.
Returns:
dict: Processor context. | [
"Emulate",
"native",
"code",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/barf.py#L382-L430 | train | 198,530 |
programa-stic/barf-project | barf/analysis/gadgets/finder.py | GadgetFinder.find | def find(self, start_address, end_address, byte_depth=20, instrs_depth=2):
"""Find gadgets.
"""
self._max_bytes = byte_depth
self._instrs_depth = instrs_depth
if self._architecture == ARCH_X86:
candidates = self._find_x86_candidates(start_address, end_address)
elif self._architecture == ARCH_ARM:
candidates = self._find_arm_candidates(start_address, end_address)
else:
raise Exception("Architecture not supported.")
# Sort and return.
return sorted(candidates, key=lambda g: g.address) | python | def find(self, start_address, end_address, byte_depth=20, instrs_depth=2):
"""Find gadgets.
"""
self._max_bytes = byte_depth
self._instrs_depth = instrs_depth
if self._architecture == ARCH_X86:
candidates = self._find_x86_candidates(start_address, end_address)
elif self._architecture == ARCH_ARM:
candidates = self._find_arm_candidates(start_address, end_address)
else:
raise Exception("Architecture not supported.")
# Sort and return.
return sorted(candidates, key=lambda g: g.address) | [
"def",
"find",
"(",
"self",
",",
"start_address",
",",
"end_address",
",",
"byte_depth",
"=",
"20",
",",
"instrs_depth",
"=",
"2",
")",
":",
"self",
".",
"_max_bytes",
"=",
"byte_depth",
"self",
".",
"_instrs_depth",
"=",
"instrs_depth",
"if",
"self",
".",... | Find gadgets. | [
"Find",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/finder.py#L74-L88 | train | 198,531 |
programa-stic/barf-project | barf/analysis/gadgets/finder.py | GadgetFinder._build_from | def _build_from(self, address, root, base_address, depth=2):
"""Build gadgets recursively.
"""
if depth == 0:
return
end_addr = address
for step in range(1, self._max_bytes + 1):
start_addr = address - step
if start_addr < 0 or start_addr < base_address:
break
raw_bytes = self._mem[start_addr:end_addr]
# TODO: Improve this code.
if self._architecture == ARCH_ARM:
try:
asm_instr = self._disasm.disassemble(raw_bytes, start_addr, architecture_mode=self._architecture_mode)
except InvalidDisassemblerData:
continue
else:
try:
asm_instr = self._disasm.disassemble(raw_bytes, start_addr)
except:
asm_instr = None
if not asm_instr or asm_instr.size != step:
continue
try:
ir_instrs = self._ir_trans.translate(asm_instr)
except:
continue
if self._is_valid_ins(ir_instrs):
asm_instr.ir_instrs = ir_instrs
child = GadgetTreeNode(asm_instr)
root.add_child(child)
self._build_from(address - step, child, base_address, depth - 1) | python | def _build_from(self, address, root, base_address, depth=2):
"""Build gadgets recursively.
"""
if depth == 0:
return
end_addr = address
for step in range(1, self._max_bytes + 1):
start_addr = address - step
if start_addr < 0 or start_addr < base_address:
break
raw_bytes = self._mem[start_addr:end_addr]
# TODO: Improve this code.
if self._architecture == ARCH_ARM:
try:
asm_instr = self._disasm.disassemble(raw_bytes, start_addr, architecture_mode=self._architecture_mode)
except InvalidDisassemblerData:
continue
else:
try:
asm_instr = self._disasm.disassemble(raw_bytes, start_addr)
except:
asm_instr = None
if not asm_instr or asm_instr.size != step:
continue
try:
ir_instrs = self._ir_trans.translate(asm_instr)
except:
continue
if self._is_valid_ins(ir_instrs):
asm_instr.ir_instrs = ir_instrs
child = GadgetTreeNode(asm_instr)
root.add_child(child)
self._build_from(address - step, child, base_address, depth - 1) | [
"def",
"_build_from",
"(",
"self",
",",
"address",
",",
"root",
",",
"base_address",
",",
"depth",
"=",
"2",
")",
":",
"if",
"depth",
"==",
"0",
":",
"return",
"end_addr",
"=",
"address",
"for",
"step",
"in",
"range",
"(",
"1",
",",
"self",
".",
"_... | Build gadgets recursively. | [
"Build",
"gadgets",
"recursively",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/finder.py#L245-L288 | train | 198,532 |
programa-stic/barf-project | barf/analysis/gadgets/finder.py | GadgetFinder._build_gadgets | def _build_gadgets(self, gadget_tree_root):
"""Return a gadgets list.
"""
node_list = self._build_gadgets_rec(gadget_tree_root)
return [RawGadget(n) for n in node_list] | python | def _build_gadgets(self, gadget_tree_root):
"""Return a gadgets list.
"""
node_list = self._build_gadgets_rec(gadget_tree_root)
return [RawGadget(n) for n in node_list] | [
"def",
"_build_gadgets",
"(",
"self",
",",
"gadget_tree_root",
")",
":",
"node_list",
"=",
"self",
".",
"_build_gadgets_rec",
"(",
"gadget_tree_root",
")",
"return",
"[",
"RawGadget",
"(",
"n",
")",
"for",
"n",
"in",
"node_list",
"]"
] | Return a gadgets list. | [
"Return",
"a",
"gadgets",
"list",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/finder.py#L290-L295 | train | 198,533 |
programa-stic/barf-project | barf/analysis/gadgets/finder.py | GadgetFinder._build_gadgets_rec | def _build_gadgets_rec(self, gadget_tree_root):
"""Build a gadgets from a gadgets tree.
"""
root = gadget_tree_root.get_root()
children = gadget_tree_root.get_children()
node_list = []
root_gadget_ins = root
if not children:
node_list += [[root_gadget_ins]]
else:
for child in children:
node_list_rec = self._build_gadgets_rec(child)
node_list += [n + [root_gadget_ins] for n in node_list_rec]
return node_list | python | def _build_gadgets_rec(self, gadget_tree_root):
"""Build a gadgets from a gadgets tree.
"""
root = gadget_tree_root.get_root()
children = gadget_tree_root.get_children()
node_list = []
root_gadget_ins = root
if not children:
node_list += [[root_gadget_ins]]
else:
for child in children:
node_list_rec = self._build_gadgets_rec(child)
node_list += [n + [root_gadget_ins] for n in node_list_rec]
return node_list | [
"def",
"_build_gadgets_rec",
"(",
"self",
",",
"gadget_tree_root",
")",
":",
"root",
"=",
"gadget_tree_root",
".",
"get_root",
"(",
")",
"children",
"=",
"gadget_tree_root",
".",
"get_children",
"(",
")",
"node_list",
"=",
"[",
"]",
"root_gadget_ins",
"=",
"ro... | Build a gadgets from a gadgets tree. | [
"Build",
"a",
"gadgets",
"from",
"a",
"gadgets",
"tree",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/finder.py#L307-L325 | train | 198,534 |
programa-stic/barf-project | barf/analysis/gadgets/finder.py | GadgetFinder._is_valid_ins | def _is_valid_ins(self, ins_ir):
"""Check for instruction validity as a gadgets.
"""
invalid_instrs = [
ReilMnemonic.JCC,
ReilMnemonic.UNDEF,
ReilMnemonic.UNKN,
]
return not any([i.mnemonic in invalid_instrs for i in ins_ir]) | python | def _is_valid_ins(self, ins_ir):
"""Check for instruction validity as a gadgets.
"""
invalid_instrs = [
ReilMnemonic.JCC,
ReilMnemonic.UNDEF,
ReilMnemonic.UNKN,
]
return not any([i.mnemonic in invalid_instrs for i in ins_ir]) | [
"def",
"_is_valid_ins",
"(",
"self",
",",
"ins_ir",
")",
":",
"invalid_instrs",
"=",
"[",
"ReilMnemonic",
".",
"JCC",
",",
"ReilMnemonic",
".",
"UNDEF",
",",
"ReilMnemonic",
".",
"UNKN",
",",
"]",
"return",
"not",
"any",
"(",
"[",
"i",
".",
"mnemonic",
... | Check for instruction validity as a gadgets. | [
"Check",
"for",
"instruction",
"validity",
"as",
"a",
"gadgets",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/gadgets/finder.py#L327-L336 | train | 198,535 |
programa-stic/barf-project | barf/arch/translator.py | InstructionTranslator.translate | def translate(self, instruction):
"""Return REIL representation of an instruction.
"""
try:
trans_instrs = self._translate(instruction)
except Exception:
self._log_translation_exception(instruction)
raise TranslationError("Unknown error")
return trans_instrs | python | def translate(self, instruction):
"""Return REIL representation of an instruction.
"""
try:
trans_instrs = self._translate(instruction)
except Exception:
self._log_translation_exception(instruction)
raise TranslationError("Unknown error")
return trans_instrs | [
"def",
"translate",
"(",
"self",
",",
"instruction",
")",
":",
"try",
":",
"trans_instrs",
"=",
"self",
".",
"_translate",
"(",
"instruction",
")",
"except",
"Exception",
":",
"self",
".",
"_log_translation_exception",
"(",
"instruction",
")",
"raise",
"Transl... | Return REIL representation of an instruction. | [
"Return",
"REIL",
"representation",
"of",
"an",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/translator.py#L104-L114 | train | 198,536 |
programa-stic/barf-project | barf/analysis/codeanalyzer/codeanalyzer.py | CodeAnalyzer.add_instruction | def add_instruction(self, reil_instruction):
"""Add an instruction for analysis.
"""
for expr in self._translator.translate(reil_instruction):
self._solver.add(expr) | python | def add_instruction(self, reil_instruction):
"""Add an instruction for analysis.
"""
for expr in self._translator.translate(reil_instruction):
self._solver.add(expr) | [
"def",
"add_instruction",
"(",
"self",
",",
"reil_instruction",
")",
":",
"for",
"expr",
"in",
"self",
".",
"_translator",
".",
"translate",
"(",
"reil_instruction",
")",
":",
"self",
".",
"_solver",
".",
"add",
"(",
"expr",
")"
] | Add an instruction for analysis. | [
"Add",
"an",
"instruction",
"for",
"analysis",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/codeanalyzer/codeanalyzer.py#L116-L120 | train | 198,537 |
programa-stic/barf-project | barf/analysis/codeanalyzer/codeanalyzer.py | CodeAnalyzer._get_var_name | def _get_var_name(self, register_name, mode):
"""Get variable name for a register considering pre and post mode.
"""
var_name = {
"pre": self._translator.get_name_init(register_name),
"post": self._translator.get_name_curr(register_name),
}
return var_name[mode] | python | def _get_var_name(self, register_name, mode):
"""Get variable name for a register considering pre and post mode.
"""
var_name = {
"pre": self._translator.get_name_init(register_name),
"post": self._translator.get_name_curr(register_name),
}
return var_name[mode] | [
"def",
"_get_var_name",
"(",
"self",
",",
"register_name",
",",
"mode",
")",
":",
"var_name",
"=",
"{",
"\"pre\"",
":",
"self",
".",
"_translator",
".",
"get_name_init",
"(",
"register_name",
")",
",",
"\"post\"",
":",
"self",
".",
"_translator",
".",
"get... | Get variable name for a register considering pre and post mode. | [
"Get",
"variable",
"name",
"for",
"a",
"register",
"considering",
"pre",
"and",
"post",
"mode",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/codeanalyzer/codeanalyzer.py#L141-L149 | train | 198,538 |
programa-stic/barf-project | barf/analysis/symbolic/emulator.py | ReilSymbolicEmulator.__process_instr | def __process_instr(self, instr, avoid, next_addr, initial_state, execution_state, trace_current):
"""Process a REIL instruction.
Args:
instr (ReilInstruction): Instruction to process.
avoid (list): List of addresses to avoid while executing the code.
next_addr (int): Address of the following instruction.
initial_state (State): Initial execution state.
execution_state (Queue): Queue of execution states.
trace_current (list): Current trace.
Returns:
int: Returns the next address to execute.
"""
# Process branch (JCC oprnd0, empty, oprnd2).
if instr.mnemonic == ReilMnemonic.JCC:
not_taken_addr = next_addr
address, index = split_address(instr.address)
logger.debug("[+] Processing branch: {:#08x}:{:02x} : {}".format(address, index, instr))
# Process conditional branch (oprnd0 is a REGISTER).
if isinstance(instr.operands[0], ReilRegisterOperand):
next_ip = self.__process_branch_cond(instr, avoid, initial_state, execution_state, trace_current, not_taken_addr)
# Process unconditional branch (oprnd0 is an INTEGER).
else:
next_ip = self.__process_branch_uncond(instr, trace_current, not_taken_addr)
# Process the rest of the instructions.
else:
trace_current += [(instr, None)]
self.__cpu.execute(instr)
next_ip = next_addr
return next_ip | python | def __process_instr(self, instr, avoid, next_addr, initial_state, execution_state, trace_current):
"""Process a REIL instruction.
Args:
instr (ReilInstruction): Instruction to process.
avoid (list): List of addresses to avoid while executing the code.
next_addr (int): Address of the following instruction.
initial_state (State): Initial execution state.
execution_state (Queue): Queue of execution states.
trace_current (list): Current trace.
Returns:
int: Returns the next address to execute.
"""
# Process branch (JCC oprnd0, empty, oprnd2).
if instr.mnemonic == ReilMnemonic.JCC:
not_taken_addr = next_addr
address, index = split_address(instr.address)
logger.debug("[+] Processing branch: {:#08x}:{:02x} : {}".format(address, index, instr))
# Process conditional branch (oprnd0 is a REGISTER).
if isinstance(instr.operands[0], ReilRegisterOperand):
next_ip = self.__process_branch_cond(instr, avoid, initial_state, execution_state, trace_current, not_taken_addr)
# Process unconditional branch (oprnd0 is an INTEGER).
else:
next_ip = self.__process_branch_uncond(instr, trace_current, not_taken_addr)
# Process the rest of the instructions.
else:
trace_current += [(instr, None)]
self.__cpu.execute(instr)
next_ip = next_addr
return next_ip | [
"def",
"__process_instr",
"(",
"self",
",",
"instr",
",",
"avoid",
",",
"next_addr",
",",
"initial_state",
",",
"execution_state",
",",
"trace_current",
")",
":",
"# Process branch (JCC oprnd0, empty, oprnd2).",
"if",
"instr",
".",
"mnemonic",
"==",
"ReilMnemonic",
... | Process a REIL instruction.
Args:
instr (ReilInstruction): Instruction to process.
avoid (list): List of addresses to avoid while executing the code.
next_addr (int): Address of the following instruction.
initial_state (State): Initial execution state.
execution_state (Queue): Queue of execution states.
trace_current (list): Current trace.
Returns:
int: Returns the next address to execute. | [
"Process",
"a",
"REIL",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/symbolic/emulator.py#L396-L433 | train | 198,539 |
programa-stic/barf-project | barf/analysis/symbolic/emulator.py | ReilSymbolicEmulator.__fa_process_sequence | def __fa_process_sequence(self, sequence, avoid, initial_state, execution_state, trace_current, next_addr):
"""Process a REIL sequence.
Args:
sequence (ReilSequence): A REIL sequence to process.
avoid (list): List of address to avoid.
initial_state: Initial state.
execution_state: Execution state queue.
trace_current (list): Current trace.
next_addr: Address of the next instruction following the current one.
Returns:
Returns the next instruction to execute in case there is one, otherwise returns None.
"""
# TODO: Process execution intra states.
ip = sequence.address
next_ip = None
while ip:
# Fetch next instruction in the sequence.
try:
instr = sequence.fetch(ip)
except ReilSequenceInvalidAddressError:
# At this point, ip should be a native instruction address, therefore
# the index should be zero.
assert split_address(ip)[1] == 0x0
next_ip = ip
break
try:
target_addr = sequence.get_next_address(ip)
except ReilSequenceInvalidAddressError:
# We reached the end of the sequence. Execution continues on the next native instruction
# (it's a REIL address).
target_addr = next_addr
next_ip = self.__process_instr(instr, avoid, target_addr, initial_state, execution_state, trace_current)
# Update instruction pointer.
try:
ip = next_ip if next_ip else sequence.get_next_address(ip)
except ReilSequenceInvalidAddressError:
break
return next_ip | python | def __fa_process_sequence(self, sequence, avoid, initial_state, execution_state, trace_current, next_addr):
"""Process a REIL sequence.
Args:
sequence (ReilSequence): A REIL sequence to process.
avoid (list): List of address to avoid.
initial_state: Initial state.
execution_state: Execution state queue.
trace_current (list): Current trace.
next_addr: Address of the next instruction following the current one.
Returns:
Returns the next instruction to execute in case there is one, otherwise returns None.
"""
# TODO: Process execution intra states.
ip = sequence.address
next_ip = None
while ip:
# Fetch next instruction in the sequence.
try:
instr = sequence.fetch(ip)
except ReilSequenceInvalidAddressError:
# At this point, ip should be a native instruction address, therefore
# the index should be zero.
assert split_address(ip)[1] == 0x0
next_ip = ip
break
try:
target_addr = sequence.get_next_address(ip)
except ReilSequenceInvalidAddressError:
# We reached the end of the sequence. Execution continues on the next native instruction
# (it's a REIL address).
target_addr = next_addr
next_ip = self.__process_instr(instr, avoid, target_addr, initial_state, execution_state, trace_current)
# Update instruction pointer.
try:
ip = next_ip if next_ip else sequence.get_next_address(ip)
except ReilSequenceInvalidAddressError:
break
return next_ip | [
"def",
"__fa_process_sequence",
"(",
"self",
",",
"sequence",
",",
"avoid",
",",
"initial_state",
",",
"execution_state",
",",
"trace_current",
",",
"next_addr",
")",
":",
"# TODO: Process execution intra states.",
"ip",
"=",
"sequence",
".",
"address",
"next_ip",
"... | Process a REIL sequence.
Args:
sequence (ReilSequence): A REIL sequence to process.
avoid (list): List of address to avoid.
initial_state: Initial state.
execution_state: Execution state queue.
trace_current (list): Current trace.
next_addr: Address of the next instruction following the current one.
Returns:
Returns the next instruction to execute in case there is one, otherwise returns None. | [
"Process",
"a",
"REIL",
"sequence",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/symbolic/emulator.py#L516-L561 | train | 198,540 |
programa-stic/barf-project | barf/analysis/symbolic/emulator.py | ReilSymbolicEmulator.__fa_process_container | def __fa_process_container(self, container, find, start, end, avoid, initial_state, execution_state, trace_current,
trace_final):
"""Process a REIL container.
Args:
avoid (list): List of addresses to avoid while executing the code.
container (ReilContainer): REIL container to execute.
end (int): End address.
execution_state (Queue): Queue of execution states.
find (int): Address to find.
initial_state (State): Initial state.
start (int): Start address.
trace_current:
trace_final:
"""
ip = start
while ip:
# NOTE *ip* and *next_addr* variables can be, independently, either intra
# or inter addresses.
# Fetch next instruction.
try:
instr = container.fetch(ip)
except ReilContainerInvalidAddressError:
logger.debug("Exception @ {:#08x}".format(ip))
raise ReilContainerInvalidAddressError
# Compute the address of the following instruction to the fetched one.
try:
next_addr = container.get_next_address(ip)
except Exception:
logger.debug("Exception @ {:#08x}".format(ip))
# TODO Should this be considered an error?
raise ReilContainerInvalidAddressError
# Process the instruction.
next_ip = self.__process_instr(instr, avoid, next_addr, initial_state, execution_state, trace_current)
# # ====================================================================================================== #
# # NOTE This is an attempt to separate intra and inter instruction
# # addresses processing. Here, *ip* and *next_addr* are always inter
# # instruction addresses.
#
# assert split_address(ip)[1] == 0x0
#
# # Compute the address of the following instruction to the fetched one.
# try:
# seq = container.fetch_sequence(ip)
# except ReilContainerInvalidAddressError:
# logger.debug("Exception @ {:#08x}".format(ip))
#
# raise ReilContainerInvalidAddressError
#
# # Fetch next instruction address.
# try:
# next_addr = container.get_next_address(ip + len(seq))
# except Exception:
# logger.debug("Exception @ {:#08x}".format(ip))
#
# # TODO Should this be considered an error?
#
# raise ReilContainerInvalidAddressError
#
# next_ip = self.__process_sequence(seq, avoid, initial_state, execution_state, trace_current, next_addr)
#
# if next_ip:
# assert split_address(next_ip)[1] == 0x0
#
# # ====================================================================================================== #
# Check termination conditions.
if find and next_ip and next_ip == find:
logger.debug("[+] Find address found!")
trace_final.append(list(trace_current))
next_ip = None
if end and next_ip and next_ip == end:
logger.debug("[+] End address found!")
next_ip = None
# Update instruction pointer.
ip = next_ip if next_ip else None
while not ip:
if not execution_state.empty():
# Pop next execution state.
ip, trace_current, registers, memory = execution_state.get()
if split_address(ip)[1] == 0x0:
logger.debug("[+] Popping execution state @ {:#x} (INTER)".format(ip))
else:
logger.debug("[+] Popping execution state @ {:#x} (INTRA)".format(ip))
# Setup cpu and memory.
self.__cpu.registers = registers
self.__cpu.memory = memory
logger.debug("[+] Next address: {:#08x}:{:02x}".format(ip >> 8, ip & 0xff))
else:
logger.debug("[+] No more paths to explore! Exiting...")
break
# Check termination conditions (AGAIN...).
if find and ip == find:
logger.debug("[+] Find address found!")
trace_final.append(list(trace_current))
ip = None
if end and ip == end:
logger.debug("[+] End address found!")
ip = None | python | def __fa_process_container(self, container, find, start, end, avoid, initial_state, execution_state, trace_current,
trace_final):
"""Process a REIL container.
Args:
avoid (list): List of addresses to avoid while executing the code.
container (ReilContainer): REIL container to execute.
end (int): End address.
execution_state (Queue): Queue of execution states.
find (int): Address to find.
initial_state (State): Initial state.
start (int): Start address.
trace_current:
trace_final:
"""
ip = start
while ip:
# NOTE *ip* and *next_addr* variables can be, independently, either intra
# or inter addresses.
# Fetch next instruction.
try:
instr = container.fetch(ip)
except ReilContainerInvalidAddressError:
logger.debug("Exception @ {:#08x}".format(ip))
raise ReilContainerInvalidAddressError
# Compute the address of the following instruction to the fetched one.
try:
next_addr = container.get_next_address(ip)
except Exception:
logger.debug("Exception @ {:#08x}".format(ip))
# TODO Should this be considered an error?
raise ReilContainerInvalidAddressError
# Process the instruction.
next_ip = self.__process_instr(instr, avoid, next_addr, initial_state, execution_state, trace_current)
# # ====================================================================================================== #
# # NOTE This is an attempt to separate intra and inter instruction
# # addresses processing. Here, *ip* and *next_addr* are always inter
# # instruction addresses.
#
# assert split_address(ip)[1] == 0x0
#
# # Compute the address of the following instruction to the fetched one.
# try:
# seq = container.fetch_sequence(ip)
# except ReilContainerInvalidAddressError:
# logger.debug("Exception @ {:#08x}".format(ip))
#
# raise ReilContainerInvalidAddressError
#
# # Fetch next instruction address.
# try:
# next_addr = container.get_next_address(ip + len(seq))
# except Exception:
# logger.debug("Exception @ {:#08x}".format(ip))
#
# # TODO Should this be considered an error?
#
# raise ReilContainerInvalidAddressError
#
# next_ip = self.__process_sequence(seq, avoid, initial_state, execution_state, trace_current, next_addr)
#
# if next_ip:
# assert split_address(next_ip)[1] == 0x0
#
# # ====================================================================================================== #
# Check termination conditions.
if find and next_ip and next_ip == find:
logger.debug("[+] Find address found!")
trace_final.append(list(trace_current))
next_ip = None
if end and next_ip and next_ip == end:
logger.debug("[+] End address found!")
next_ip = None
# Update instruction pointer.
ip = next_ip if next_ip else None
while not ip:
if not execution_state.empty():
# Pop next execution state.
ip, trace_current, registers, memory = execution_state.get()
if split_address(ip)[1] == 0x0:
logger.debug("[+] Popping execution state @ {:#x} (INTER)".format(ip))
else:
logger.debug("[+] Popping execution state @ {:#x} (INTRA)".format(ip))
# Setup cpu and memory.
self.__cpu.registers = registers
self.__cpu.memory = memory
logger.debug("[+] Next address: {:#08x}:{:02x}".format(ip >> 8, ip & 0xff))
else:
logger.debug("[+] No more paths to explore! Exiting...")
break
# Check termination conditions (AGAIN...).
if find and ip == find:
logger.debug("[+] Find address found!")
trace_final.append(list(trace_current))
ip = None
if end and ip == end:
logger.debug("[+] End address found!")
ip = None | [
"def",
"__fa_process_container",
"(",
"self",
",",
"container",
",",
"find",
",",
"start",
",",
"end",
",",
"avoid",
",",
"initial_state",
",",
"execution_state",
",",
"trace_current",
",",
"trace_final",
")",
":",
"ip",
"=",
"start",
"while",
"ip",
":",
"... | Process a REIL container.
Args:
avoid (list): List of addresses to avoid while executing the code.
container (ReilContainer): REIL container to execute.
end (int): End address.
execution_state (Queue): Queue of execution states.
find (int): Address to find.
initial_state (State): Initial state.
start (int): Start address.
trace_current:
trace_final: | [
"Process",
"a",
"REIL",
"container",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/symbolic/emulator.py#L563-L684 | train | 198,541 |
programa-stic/barf-project | barf/analysis/graphs/callgraph.py | CallGraph.find_function_by_name | def find_function_by_name(self, name):
"""Return the cfg of the requested function by name.
"""
cfg_rv = None
for cfg in self._cfgs:
if cfg.name == name:
cfg_rv = cfg
break
return cfg_rv | python | def find_function_by_name(self, name):
"""Return the cfg of the requested function by name.
"""
cfg_rv = None
for cfg in self._cfgs:
if cfg.name == name:
cfg_rv = cfg
break
return cfg_rv | [
"def",
"find_function_by_name",
"(",
"self",
",",
"name",
")",
":",
"cfg_rv",
"=",
"None",
"for",
"cfg",
"in",
"self",
".",
"_cfgs",
":",
"if",
"cfg",
".",
"name",
"==",
"name",
":",
"cfg_rv",
"=",
"cfg",
"break",
"return",
"cfg_rv"
] | Return the cfg of the requested function by name. | [
"Return",
"the",
"cfg",
"of",
"the",
"requested",
"function",
"by",
"name",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/callgraph.py#L98-L106 | train | 198,542 |
programa-stic/barf-project | barf/analysis/graphs/callgraph.py | CallGraph.find_function_by_address | def find_function_by_address(self, address):
"""Return the cfg of the requested function by address.
"""
cfg_rv = None
for cfg in self._cfgs:
if cfg.start_address == address:
cfg_rv = cfg
break
return cfg_rv | python | def find_function_by_address(self, address):
"""Return the cfg of the requested function by address.
"""
cfg_rv = None
for cfg in self._cfgs:
if cfg.start_address == address:
cfg_rv = cfg
break
return cfg_rv | [
"def",
"find_function_by_address",
"(",
"self",
",",
"address",
")",
":",
"cfg_rv",
"=",
"None",
"for",
"cfg",
"in",
"self",
".",
"_cfgs",
":",
"if",
"cfg",
".",
"start_address",
"==",
"address",
":",
"cfg_rv",
"=",
"cfg",
"break",
"return",
"cfg_rv"
] | Return the cfg of the requested function by address. | [
"Return",
"the",
"cfg",
"of",
"the",
"requested",
"function",
"by",
"address",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/callgraph.py#L108-L116 | train | 198,543 |
programa-stic/barf-project | barf/analysis/graphs/controlflowgraph.py | ControlFlowGraph.all_simple_bb_paths | def all_simple_bb_paths(self, start_address, end_address):
"""Return a list of path between start and end address.
"""
bb_start = self._find_basic_block(start_address)
bb_end = self._find_basic_block(end_address)
paths = networkx.all_simple_paths(self._graph, source=bb_start.address, target=bb_end.address)
return ([self._bb_by_addr[addr] for addr in path] for path in paths) | python | def all_simple_bb_paths(self, start_address, end_address):
"""Return a list of path between start and end address.
"""
bb_start = self._find_basic_block(start_address)
bb_end = self._find_basic_block(end_address)
paths = networkx.all_simple_paths(self._graph, source=bb_start.address, target=bb_end.address)
return ([self._bb_by_addr[addr] for addr in path] for path in paths) | [
"def",
"all_simple_bb_paths",
"(",
"self",
",",
"start_address",
",",
"end_address",
")",
":",
"bb_start",
"=",
"self",
".",
"_find_basic_block",
"(",
"start_address",
")",
"bb_end",
"=",
"self",
".",
"_find_basic_block",
"(",
"end_address",
")",
"paths",
"=",
... | Return a list of path between start and end address. | [
"Return",
"a",
"list",
"of",
"path",
"between",
"start",
"and",
"end",
"address",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/controlflowgraph.py#L117-L125 | train | 198,544 |
programa-stic/barf-project | barf/analysis/graphs/controlflowgraph.py | CFGRecover.build | def build(self, start, end, symbols=None):
"""Return the list of basic blocks.
:int start: Start address of the disassembling process.
:int end: End address of the disassembling process.
"""
symbols = {} if not symbols else symbols
# First pass: Recover BBs.
bbs = self._recover_bbs(start, end, symbols)
# Second pass: Split overlapping basic blocks introduced by back edges.
bbs = self._split_bbs(bbs, symbols)
# Third pass: Extract call targets for further analysis.
call_targets = self._extract_call_targets(bbs)
return bbs, call_targets | python | def build(self, start, end, symbols=None):
"""Return the list of basic blocks.
:int start: Start address of the disassembling process.
:int end: End address of the disassembling process.
"""
symbols = {} if not symbols else symbols
# First pass: Recover BBs.
bbs = self._recover_bbs(start, end, symbols)
# Second pass: Split overlapping basic blocks introduced by back edges.
bbs = self._split_bbs(bbs, symbols)
# Third pass: Extract call targets for further analysis.
call_targets = self._extract_call_targets(bbs)
return bbs, call_targets | [
"def",
"build",
"(",
"self",
",",
"start",
",",
"end",
",",
"symbols",
"=",
"None",
")",
":",
"symbols",
"=",
"{",
"}",
"if",
"not",
"symbols",
"else",
"symbols",
"# First pass: Recover BBs.",
"bbs",
"=",
"self",
".",
"_recover_bbs",
"(",
"start",
",",
... | Return the list of basic blocks.
:int start: Start address of the disassembling process.
:int end: End address of the disassembling process. | [
"Return",
"the",
"list",
"of",
"basic",
"blocks",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/analysis/graphs/controlflowgraph.py#L211-L229 | train | 198,545 |
programa-stic/barf-project | barf/core/reil/parser.py | parse_operand | def parse_operand(string, location, tokens):
"""Parse instruction operand.
"""
sizes = {
"dqword": 128,
"pointer": 72,
"qword": 64,
"pointer": 40,
"dword": 32,
"word": 16,
"byte": 8,
"bit": 1,
}
if "immediate" in tokens:
imm_str = "".join(tokens["immediate"])
base = 16 if imm_str.startswith("0x") or imm_str.startswith("-0x") else 10
imm = int(imm_str, base)
oprnd = ReilImmediateOperand(imm)
if "register" in tokens:
if tokens["register"] in ["e", "empty"]:
oprnd = ReilEmptyOperand()
oprnd.size = 0
else:
name = tokens["register"]
oprnd = ReilRegisterOperand(name)
if "size" in tokens:
oprnd.size = int(sizes[tokens["size"]])
return [oprnd] | python | def parse_operand(string, location, tokens):
"""Parse instruction operand.
"""
sizes = {
"dqword": 128,
"pointer": 72,
"qword": 64,
"pointer": 40,
"dword": 32,
"word": 16,
"byte": 8,
"bit": 1,
}
if "immediate" in tokens:
imm_str = "".join(tokens["immediate"])
base = 16 if imm_str.startswith("0x") or imm_str.startswith("-0x") else 10
imm = int(imm_str, base)
oprnd = ReilImmediateOperand(imm)
if "register" in tokens:
if tokens["register"] in ["e", "empty"]:
oprnd = ReilEmptyOperand()
oprnd.size = 0
else:
name = tokens["register"]
oprnd = ReilRegisterOperand(name)
if "size" in tokens:
oprnd.size = int(sizes[tokens["size"]])
return [oprnd] | [
"def",
"parse_operand",
"(",
"string",
",",
"location",
",",
"tokens",
")",
":",
"sizes",
"=",
"{",
"\"dqword\"",
":",
"128",
",",
"\"pointer\"",
":",
"72",
",",
"\"qword\"",
":",
"64",
",",
"\"pointer\"",
":",
"40",
",",
"\"dword\"",
":",
"32",
",",
... | Parse instruction operand. | [
"Parse",
"instruction",
"operand",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/parser.py#L74-L109 | train | 198,546 |
programa-stic/barf-project | barf/core/reil/parser.py | parse_instruction | def parse_instruction(string, location, tokens):
"""Parse instruction.
"""
mnemonic_str = ReilMnemonic.from_string(tokens["mnemonic"])
oprnd1 = tokens["fst_operand"][0]
oprnd2 = tokens["snd_operand"][0]
oprnd3 = tokens["trd_operand"][0]
ins_builder = ReilBuilder()
return ins_builder.build(mnemonic_str, oprnd1, oprnd2, oprnd3) | python | def parse_instruction(string, location, tokens):
"""Parse instruction.
"""
mnemonic_str = ReilMnemonic.from_string(tokens["mnemonic"])
oprnd1 = tokens["fst_operand"][0]
oprnd2 = tokens["snd_operand"][0]
oprnd3 = tokens["trd_operand"][0]
ins_builder = ReilBuilder()
return ins_builder.build(mnemonic_str, oprnd1, oprnd2, oprnd3) | [
"def",
"parse_instruction",
"(",
"string",
",",
"location",
",",
"tokens",
")",
":",
"mnemonic_str",
"=",
"ReilMnemonic",
".",
"from_string",
"(",
"tokens",
"[",
"\"mnemonic\"",
"]",
")",
"oprnd1",
"=",
"tokens",
"[",
"\"fst_operand\"",
"]",
"[",
"0",
"]",
... | Parse instruction. | [
"Parse",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/parser.py#L112-L123 | train | 198,547 |
programa-stic/barf-project | barf/core/reil/parser.py | ReilParser.parse | def parse(self, instrs):
"""Parse an IR instruction.
"""
instrs_reil = []
try:
for instr in instrs:
instr_lower = instr.lower()
# If the instruction to parsed is not in the cache,
# parse it and add it to the cache.
if instr_lower not in self._cache:
self._cache[instr_lower] = instruction.parseString(
instr_lower)[0]
# Retrieve parsed instruction from the cache and clone
# it.
instrs_reil += [copy.deepcopy(self._cache[instr_lower])]
except:
error_msg = "Failed to parse instruction: %s"
logger.error(error_msg, instr, exc_info=True)
return instrs_reil | python | def parse(self, instrs):
"""Parse an IR instruction.
"""
instrs_reil = []
try:
for instr in instrs:
instr_lower = instr.lower()
# If the instruction to parsed is not in the cache,
# parse it and add it to the cache.
if instr_lower not in self._cache:
self._cache[instr_lower] = instruction.parseString(
instr_lower)[0]
# Retrieve parsed instruction from the cache and clone
# it.
instrs_reil += [copy.deepcopy(self._cache[instr_lower])]
except:
error_msg = "Failed to parse instruction: %s"
logger.error(error_msg, instr, exc_info=True)
return instrs_reil | [
"def",
"parse",
"(",
"self",
",",
"instrs",
")",
":",
"instrs_reil",
"=",
"[",
"]",
"try",
":",
"for",
"instr",
"in",
"instrs",
":",
"instr_lower",
"=",
"instr",
".",
"lower",
"(",
")",
"# If the instruction to parsed is not in the cache,",
"# parse it and add i... | Parse an IR instruction. | [
"Parse",
"an",
"IR",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/core/reil/parser.py#L197-L220 | train | 198,548 |
programa-stic/barf-project | barf/arch/arm/parser.py | parse_operand | def parse_operand(string, location, tokens):
"""Parse an ARM instruction operand.
"""
if "immediate_operand" in tokens:
size = arch_info.operand_size
oprnd = ArmImmediateOperand("".join(tokens["immediate_operand"]), size)
if "register_operand" in tokens:
oprnd = process_register(tokens["register_operand"])
# TODO: Figure out where to really store this flag, instead of in the register class
if "wb" in tokens["register_operand"]:
oprnd.wb = True
if "memory_operand" in tokens:
mem_oprnd = tokens["memory_operand"]
if "offset" in mem_oprnd:
index_type = ARM_MEMORY_INDEX_OFFSET
mem_oprnd = mem_oprnd["offset"]
elif "pre" in mem_oprnd:
index_type = ARM_MEMORY_INDEX_PRE
mem_oprnd = mem_oprnd["pre"]
elif "post" in mem_oprnd:
index_type = ARM_MEMORY_INDEX_POST
mem_oprnd = mem_oprnd["post"]
else:
raise Exception("Unknown index type.")
reg_base = process_register(mem_oprnd["base"])
disp = mem_oprnd.get("disp", None)
disp_minus = True if mem_oprnd.get("minus") else False
if disp:
if "shift" in disp:
displ_imm = process_shifted_register(disp["shift"])
elif "reg" in disp:
displ_imm = process_register(disp["reg"])
elif "imm" in disp:
displ_imm = ArmImmediateOperand("".join(disp["imm"]), arch_info.operand_size)
else:
raise Exception("Unknown displacement type.")
else:
displ_imm = None
size = arch_info.operand_size
# TODO: Add sizes for LDR/STR variations (half word, byte, double word)
oprnd = ArmMemoryOperand(reg_base, index_type, displ_imm, disp_minus, size)
if "shifted_register" in tokens:
oprnd = process_shifted_register(tokens["shifted_register"])
if "register_list_operand" in tokens:
parsed_reg_list = tokens["register_list_operand"]
reg_list = []
for reg_range in parsed_reg_list:
start_reg = process_register(reg_range[0])
if len(reg_range) > 1:
end_reg = process_register(reg_range[1])
reg_list.append([start_reg, end_reg])
else:
reg_list.append([start_reg])
oprnd = ArmRegisterListOperand(reg_list, reg_list[0][0].size)
return oprnd | python | def parse_operand(string, location, tokens):
"""Parse an ARM instruction operand.
"""
if "immediate_operand" in tokens:
size = arch_info.operand_size
oprnd = ArmImmediateOperand("".join(tokens["immediate_operand"]), size)
if "register_operand" in tokens:
oprnd = process_register(tokens["register_operand"])
# TODO: Figure out where to really store this flag, instead of in the register class
if "wb" in tokens["register_operand"]:
oprnd.wb = True
if "memory_operand" in tokens:
mem_oprnd = tokens["memory_operand"]
if "offset" in mem_oprnd:
index_type = ARM_MEMORY_INDEX_OFFSET
mem_oprnd = mem_oprnd["offset"]
elif "pre" in mem_oprnd:
index_type = ARM_MEMORY_INDEX_PRE
mem_oprnd = mem_oprnd["pre"]
elif "post" in mem_oprnd:
index_type = ARM_MEMORY_INDEX_POST
mem_oprnd = mem_oprnd["post"]
else:
raise Exception("Unknown index type.")
reg_base = process_register(mem_oprnd["base"])
disp = mem_oprnd.get("disp", None)
disp_minus = True if mem_oprnd.get("minus") else False
if disp:
if "shift" in disp:
displ_imm = process_shifted_register(disp["shift"])
elif "reg" in disp:
displ_imm = process_register(disp["reg"])
elif "imm" in disp:
displ_imm = ArmImmediateOperand("".join(disp["imm"]), arch_info.operand_size)
else:
raise Exception("Unknown displacement type.")
else:
displ_imm = None
size = arch_info.operand_size
# TODO: Add sizes for LDR/STR variations (half word, byte, double word)
oprnd = ArmMemoryOperand(reg_base, index_type, displ_imm, disp_minus, size)
if "shifted_register" in tokens:
oprnd = process_shifted_register(tokens["shifted_register"])
if "register_list_operand" in tokens:
parsed_reg_list = tokens["register_list_operand"]
reg_list = []
for reg_range in parsed_reg_list:
start_reg = process_register(reg_range[0])
if len(reg_range) > 1:
end_reg = process_register(reg_range[1])
reg_list.append([start_reg, end_reg])
else:
reg_list.append([start_reg])
oprnd = ArmRegisterListOperand(reg_list, reg_list[0][0].size)
return oprnd | [
"def",
"parse_operand",
"(",
"string",
",",
"location",
",",
"tokens",
")",
":",
"if",
"\"immediate_operand\"",
"in",
"tokens",
":",
"size",
"=",
"arch_info",
".",
"operand_size",
"oprnd",
"=",
"ArmImmediateOperand",
"(",
"\"\"",
".",
"join",
"(",
"tokens",
... | Parse an ARM instruction operand. | [
"Parse",
"an",
"ARM",
"instruction",
"operand",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/arm/parser.py#L94-L160 | train | 198,549 |
programa-stic/barf-project | barf/arch/arm/parser.py | parse_instruction | def parse_instruction(string, location, tokens):
"""Parse an ARM instruction.
"""
mnemonic_str = tokens.get("mnemonic")
operands = [op for op in tokens.get("operands", [])]
instr = ArmInstruction(
string,
mnemonic_str["ins"],
operands,
arch_info.architecture_mode
)
if "cc" in mnemonic_str:
instr.condition_code = cc_mapper[mnemonic_str["cc"]]
if "uf" in mnemonic_str:
instr.update_flags = True
if "ldm_stm_addr_mode" in mnemonic_str:
instr.ldm_stm_addr_mode = ldm_stm_am_mapper[mnemonic_str["ldm_stm_addr_mode"]]
return instr | python | def parse_instruction(string, location, tokens):
"""Parse an ARM instruction.
"""
mnemonic_str = tokens.get("mnemonic")
operands = [op for op in tokens.get("operands", [])]
instr = ArmInstruction(
string,
mnemonic_str["ins"],
operands,
arch_info.architecture_mode
)
if "cc" in mnemonic_str:
instr.condition_code = cc_mapper[mnemonic_str["cc"]]
if "uf" in mnemonic_str:
instr.update_flags = True
if "ldm_stm_addr_mode" in mnemonic_str:
instr.ldm_stm_addr_mode = ldm_stm_am_mapper[mnemonic_str["ldm_stm_addr_mode"]]
return instr | [
"def",
"parse_instruction",
"(",
"string",
",",
"location",
",",
"tokens",
")",
":",
"mnemonic_str",
"=",
"tokens",
".",
"get",
"(",
"\"mnemonic\"",
")",
"operands",
"=",
"[",
"op",
"for",
"op",
"in",
"tokens",
".",
"get",
"(",
"\"operands\"",
",",
"[",
... | Parse an ARM instruction. | [
"Parse",
"an",
"ARM",
"instruction",
"."
] | 18ed9e5eace55f7bf6015ec57f037c364099021c | https://github.com/programa-stic/barf-project/blob/18ed9e5eace55f7bf6015ec57f037c364099021c/barf/arch/arm/parser.py#L163-L185 | train | 198,550 |
rq/rq-scheduler | rq_scheduler/utils.py | get_next_scheduled_time | def get_next_scheduled_time(cron_string):
"""Calculate the next scheduled time by creating a crontab object
with a cron string"""
itr = croniter.croniter(cron_string, datetime.utcnow())
return itr.get_next(datetime) | python | def get_next_scheduled_time(cron_string):
"""Calculate the next scheduled time by creating a crontab object
with a cron string"""
itr = croniter.croniter(cron_string, datetime.utcnow())
return itr.get_next(datetime) | [
"def",
"get_next_scheduled_time",
"(",
"cron_string",
")",
":",
"itr",
"=",
"croniter",
".",
"croniter",
"(",
"cron_string",
",",
"datetime",
".",
"utcnow",
"(",
")",
")",
"return",
"itr",
".",
"get_next",
"(",
"datetime",
")"
] | Calculate the next scheduled time by creating a crontab object
with a cron string | [
"Calculate",
"the",
"next",
"scheduled",
"time",
"by",
"creating",
"a",
"crontab",
"object",
"with",
"a",
"cron",
"string"
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/utils.py#L22-L26 | train | 198,551 |
rq/rq-scheduler | rq_scheduler/utils.py | rationalize_until | def rationalize_until(until=None):
"""
Rationalizes the `until` argument used by other functions. This function
accepts datetime and timedelta instances as well as integers representing
epoch values.
"""
if until is None:
until = "+inf"
elif isinstance(until, datetime):
until = to_unix(until)
elif isinstance(until, timedelta):
until = to_unix((datetime.utcnow() + until))
return until | python | def rationalize_until(until=None):
"""
Rationalizes the `until` argument used by other functions. This function
accepts datetime and timedelta instances as well as integers representing
epoch values.
"""
if until is None:
until = "+inf"
elif isinstance(until, datetime):
until = to_unix(until)
elif isinstance(until, timedelta):
until = to_unix((datetime.utcnow() + until))
return until | [
"def",
"rationalize_until",
"(",
"until",
"=",
"None",
")",
":",
"if",
"until",
"is",
"None",
":",
"until",
"=",
"\"+inf\"",
"elif",
"isinstance",
"(",
"until",
",",
"datetime",
")",
":",
"until",
"=",
"to_unix",
"(",
"until",
")",
"elif",
"isinstance",
... | Rationalizes the `until` argument used by other functions. This function
accepts datetime and timedelta instances as well as integers representing
epoch values. | [
"Rationalizes",
"the",
"until",
"argument",
"used",
"by",
"other",
"functions",
".",
"This",
"function",
"accepts",
"datetime",
"and",
"timedelta",
"instances",
"as",
"well",
"as",
"integers",
"representing",
"epoch",
"values",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/utils.py#L40-L52 | train | 198,552 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.register_death | def register_death(self):
"""Registers its own death."""
self.log.info('Registering death')
with self.connection.pipeline() as p:
p.hset(self.scheduler_key, 'death', time.time())
p.expire(self.scheduler_key, 60)
p.execute() | python | def register_death(self):
"""Registers its own death."""
self.log.info('Registering death')
with self.connection.pipeline() as p:
p.hset(self.scheduler_key, 'death', time.time())
p.expire(self.scheduler_key, 60)
p.execute() | [
"def",
"register_death",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"info",
"(",
"'Registering death'",
")",
"with",
"self",
".",
"connection",
".",
"pipeline",
"(",
")",
"as",
"p",
":",
"p",
".",
"hset",
"(",
"self",
".",
"scheduler_key",
",",
... | Registers its own death. | [
"Registers",
"its",
"own",
"death",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L60-L66 | train | 198,553 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.acquire_lock | def acquire_lock(self):
"""
Acquire lock before scheduling jobs to prevent another scheduler
from scheduling jobs at the same time.
This function returns True if a lock is acquired. False otherwise.
"""
key = '%s_lock' % self.scheduler_key
now = time.time()
expires = int(self._interval) + 10
self._lock_acquired = self.connection.set(
key, now, ex=expires, nx=True)
return self._lock_acquired | python | def acquire_lock(self):
"""
Acquire lock before scheduling jobs to prevent another scheduler
from scheduling jobs at the same time.
This function returns True if a lock is acquired. False otherwise.
"""
key = '%s_lock' % self.scheduler_key
now = time.time()
expires = int(self._interval) + 10
self._lock_acquired = self.connection.set(
key, now, ex=expires, nx=True)
return self._lock_acquired | [
"def",
"acquire_lock",
"(",
"self",
")",
":",
"key",
"=",
"'%s_lock'",
"%",
"self",
".",
"scheduler_key",
"now",
"=",
"time",
".",
"time",
"(",
")",
"expires",
"=",
"int",
"(",
"self",
".",
"_interval",
")",
"+",
"10",
"self",
".",
"_lock_acquired",
... | Acquire lock before scheduling jobs to prevent another scheduler
from scheduling jobs at the same time.
This function returns True if a lock is acquired. False otherwise. | [
"Acquire",
"lock",
"before",
"scheduling",
"jobs",
"to",
"prevent",
"another",
"scheduler",
"from",
"scheduling",
"jobs",
"at",
"the",
"same",
"time",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L68-L80 | train | 198,554 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.remove_lock | def remove_lock(self):
"""
Remove acquired lock.
"""
key = '%s_lock' % self.scheduler_key
if self._lock_acquired:
self.connection.delete(key) | python | def remove_lock(self):
"""
Remove acquired lock.
"""
key = '%s_lock' % self.scheduler_key
if self._lock_acquired:
self.connection.delete(key) | [
"def",
"remove_lock",
"(",
"self",
")",
":",
"key",
"=",
"'%s_lock'",
"%",
"self",
".",
"scheduler_key",
"if",
"self",
".",
"_lock_acquired",
":",
"self",
".",
"connection",
".",
"delete",
"(",
"key",
")"
] | Remove acquired lock. | [
"Remove",
"acquired",
"lock",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L82-L89 | train | 198,555 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler._install_signal_handlers | def _install_signal_handlers(self):
"""
Installs signal handlers for handling SIGINT and SIGTERM
gracefully.
"""
def stop(signum, frame):
"""
Register scheduler's death and exit
and remove previously acquired lock and exit.
"""
self.log.info('Shutting down RQ scheduler...')
self.register_death()
self.remove_lock()
raise SystemExit()
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | python | def _install_signal_handlers(self):
"""
Installs signal handlers for handling SIGINT and SIGTERM
gracefully.
"""
def stop(signum, frame):
"""
Register scheduler's death and exit
and remove previously acquired lock and exit.
"""
self.log.info('Shutting down RQ scheduler...')
self.register_death()
self.remove_lock()
raise SystemExit()
signal.signal(signal.SIGINT, stop)
signal.signal(signal.SIGTERM, stop) | [
"def",
"_install_signal_handlers",
"(",
"self",
")",
":",
"def",
"stop",
"(",
"signum",
",",
"frame",
")",
":",
"\"\"\"\n Register scheduler's death and exit\n and remove previously acquired lock and exit.\n \"\"\"",
"self",
".",
"log",
".",
"in... | Installs signal handlers for handling SIGINT and SIGTERM
gracefully. | [
"Installs",
"signal",
"handlers",
"for",
"handling",
"SIGINT",
"and",
"SIGTERM",
"gracefully",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L91-L108 | train | 198,556 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler._create_job | def _create_job(self, func, args=None, kwargs=None, commit=True,
result_ttl=None, ttl=None, id=None, description=None,
queue_name=None, timeout=None, meta=None):
"""
Creates an RQ job and saves it to Redis.
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
job = self.job_class.create(
func, args=args, connection=self.connection,
kwargs=kwargs, result_ttl=result_ttl, ttl=ttl, id=id,
description=description, timeout=timeout, meta=meta)
if self._queue is not None:
job.origin = self._queue.name
else:
job.origin = queue_name or self.queue_name
if commit:
job.save()
return job | python | def _create_job(self, func, args=None, kwargs=None, commit=True,
result_ttl=None, ttl=None, id=None, description=None,
queue_name=None, timeout=None, meta=None):
"""
Creates an RQ job and saves it to Redis.
"""
if args is None:
args = ()
if kwargs is None:
kwargs = {}
job = self.job_class.create(
func, args=args, connection=self.connection,
kwargs=kwargs, result_ttl=result_ttl, ttl=ttl, id=id,
description=description, timeout=timeout, meta=meta)
if self._queue is not None:
job.origin = self._queue.name
else:
job.origin = queue_name or self.queue_name
if commit:
job.save()
return job | [
"def",
"_create_job",
"(",
"self",
",",
"func",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"commit",
"=",
"True",
",",
"result_ttl",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"id",
"=",
"None",
",",
"description",
"=",
"None",
",",... | Creates an RQ job and saves it to Redis. | [
"Creates",
"an",
"RQ",
"job",
"and",
"saves",
"it",
"to",
"Redis",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L110-L130 | train | 198,557 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.enqueue_at | def enqueue_at(self, scheduled_time, func, *args, **kwargs):
"""
Pushes a job to the scheduler queue. The scheduled queue is a Redis sorted
set ordered by timestamp - which in this case is job's scheduled execution time.
All args and kwargs are passed onto the job, except for the following kwarg
keys (which affect the job creation itself):
- timeout
- job_id
- job_ttl
- job_result_ttl
- job_description
Usage:
from datetime import datetime
from redis import Redis
from rq.scheduler import Scheduler
from foo import func
redis = Redis()
scheduler = Scheduler(queue_name='default', connection=redis)
scheduler.enqueue_at(datetime(2020, 1, 1), func, 'argument', keyword='argument')
"""
timeout = kwargs.pop('timeout', None)
job_id = kwargs.pop('job_id', None)
job_ttl = kwargs.pop('job_ttl', None)
job_result_ttl = kwargs.pop('job_result_ttl', None)
job_description = kwargs.pop('job_description', None)
meta = kwargs.pop('meta', None)
job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout,
id=job_id, result_ttl=job_result_ttl, ttl=job_ttl,
description=job_description, meta=meta)
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(scheduled_time)})
return job | python | def enqueue_at(self, scheduled_time, func, *args, **kwargs):
"""
Pushes a job to the scheduler queue. The scheduled queue is a Redis sorted
set ordered by timestamp - which in this case is job's scheduled execution time.
All args and kwargs are passed onto the job, except for the following kwarg
keys (which affect the job creation itself):
- timeout
- job_id
- job_ttl
- job_result_ttl
- job_description
Usage:
from datetime import datetime
from redis import Redis
from rq.scheduler import Scheduler
from foo import func
redis = Redis()
scheduler = Scheduler(queue_name='default', connection=redis)
scheduler.enqueue_at(datetime(2020, 1, 1), func, 'argument', keyword='argument')
"""
timeout = kwargs.pop('timeout', None)
job_id = kwargs.pop('job_id', None)
job_ttl = kwargs.pop('job_ttl', None)
job_result_ttl = kwargs.pop('job_result_ttl', None)
job_description = kwargs.pop('job_description', None)
meta = kwargs.pop('meta', None)
job = self._create_job(func, args=args, kwargs=kwargs, timeout=timeout,
id=job_id, result_ttl=job_result_ttl, ttl=job_ttl,
description=job_description, meta=meta)
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(scheduled_time)})
return job | [
"def",
"enqueue_at",
"(",
"self",
",",
"scheduled_time",
",",
"func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"None",
")",
"job_id",
"=",
"kwargs",
".",
"pop",
"(",
"'job_id'",... | Pushes a job to the scheduler queue. The scheduled queue is a Redis sorted
set ordered by timestamp - which in this case is job's scheduled execution time.
All args and kwargs are passed onto the job, except for the following kwarg
keys (which affect the job creation itself):
- timeout
- job_id
- job_ttl
- job_result_ttl
- job_description
Usage:
from datetime import datetime
from redis import Redis
from rq.scheduler import Scheduler
from foo import func
redis = Redis()
scheduler = Scheduler(queue_name='default', connection=redis)
scheduler.enqueue_at(datetime(2020, 1, 1), func, 'argument', keyword='argument') | [
"Pushes",
"a",
"job",
"to",
"the",
"scheduler",
"queue",
".",
"The",
"scheduled",
"queue",
"is",
"a",
"Redis",
"sorted",
"set",
"ordered",
"by",
"timestamp",
"-",
"which",
"in",
"this",
"case",
"is",
"job",
"s",
"scheduled",
"execution",
"time",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L132-L169 | train | 198,558 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.schedule | def schedule(self, scheduled_time, func, args=None, kwargs=None,
interval=None, repeat=None, result_ttl=None, ttl=None,
timeout=None, id=None, description=None, queue_name=None,
meta=None):
"""
Schedule a job to be periodically executed, at a certain interval.
"""
# Set result_ttl to -1 for periodic jobs, if result_ttl not specified
if interval is not None and result_ttl is None:
result_ttl = -1
job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
result_ttl=result_ttl, ttl=ttl, id=id,
description=description, queue_name=queue_name,
timeout=timeout, meta=meta)
if interval is not None:
job.meta['interval'] = int(interval)
if repeat is not None:
job.meta['repeat'] = int(repeat)
if repeat and interval is None:
raise ValueError("Can't repeat a job without interval argument")
job.save()
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(scheduled_time)})
return job | python | def schedule(self, scheduled_time, func, args=None, kwargs=None,
interval=None, repeat=None, result_ttl=None, ttl=None,
timeout=None, id=None, description=None, queue_name=None,
meta=None):
"""
Schedule a job to be periodically executed, at a certain interval.
"""
# Set result_ttl to -1 for periodic jobs, if result_ttl not specified
if interval is not None and result_ttl is None:
result_ttl = -1
job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
result_ttl=result_ttl, ttl=ttl, id=id,
description=description, queue_name=queue_name,
timeout=timeout, meta=meta)
if interval is not None:
job.meta['interval'] = int(interval)
if repeat is not None:
job.meta['repeat'] = int(repeat)
if repeat and interval is None:
raise ValueError("Can't repeat a job without interval argument")
job.save()
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(scheduled_time)})
return job | [
"def",
"schedule",
"(",
"self",
",",
"scheduled_time",
",",
"func",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"interval",
"=",
"None",
",",
"repeat",
"=",
"None",
",",
"result_ttl",
"=",
"None",
",",
"ttl",
"=",
"None",
",",
"timeout... | Schedule a job to be periodically executed, at a certain interval. | [
"Schedule",
"a",
"job",
"to",
"be",
"periodically",
"executed",
"at",
"a",
"certain",
"interval",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L191-L215 | train | 198,559 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.cron | def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,
queue_name=None, id=None, timeout=None, description=None, meta=None):
"""
Schedule a cronjob
"""
scheduled_time = get_next_scheduled_time(cron_string)
# Set result_ttl to -1, as jobs scheduled via cron are periodic ones.
# Otherwise the job would expire after 500 sec.
job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
result_ttl=-1, id=id, queue_name=queue_name,
description=description, timeout=timeout, meta=meta)
job.meta['cron_string'] = cron_string
if repeat is not None:
job.meta['repeat'] = int(repeat)
job.save()
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(scheduled_time)})
return job | python | def cron(self, cron_string, func, args=None, kwargs=None, repeat=None,
queue_name=None, id=None, timeout=None, description=None, meta=None):
"""
Schedule a cronjob
"""
scheduled_time = get_next_scheduled_time(cron_string)
# Set result_ttl to -1, as jobs scheduled via cron are periodic ones.
# Otherwise the job would expire after 500 sec.
job = self._create_job(func, args=args, kwargs=kwargs, commit=False,
result_ttl=-1, id=id, queue_name=queue_name,
description=description, timeout=timeout, meta=meta)
job.meta['cron_string'] = cron_string
if repeat is not None:
job.meta['repeat'] = int(repeat)
job.save()
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(scheduled_time)})
return job | [
"def",
"cron",
"(",
"self",
",",
"cron_string",
",",
"func",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"repeat",
"=",
"None",
",",
"queue_name",
"=",
"None",
",",
"id",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
"description",
... | Schedule a cronjob | [
"Schedule",
"a",
"cronjob"
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L217-L239 | train | 198,560 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.cancel | def cancel(self, job):
"""
Pulls a job from the scheduler queue. This function accepts either a
job_id or a job instance.
"""
if isinstance(job, self.job_class):
self.connection.zrem(self.scheduled_jobs_key, job.id)
else:
self.connection.zrem(self.scheduled_jobs_key, job) | python | def cancel(self, job):
"""
Pulls a job from the scheduler queue. This function accepts either a
job_id or a job instance.
"""
if isinstance(job, self.job_class):
self.connection.zrem(self.scheduled_jobs_key, job.id)
else:
self.connection.zrem(self.scheduled_jobs_key, job) | [
"def",
"cancel",
"(",
"self",
",",
"job",
")",
":",
"if",
"isinstance",
"(",
"job",
",",
"self",
".",
"job_class",
")",
":",
"self",
".",
"connection",
".",
"zrem",
"(",
"self",
".",
"scheduled_jobs_key",
",",
"job",
".",
"id",
")",
"else",
":",
"s... | Pulls a job from the scheduler queue. This function accepts either a
job_id or a job instance. | [
"Pulls",
"a",
"job",
"from",
"the",
"scheduler",
"queue",
".",
"This",
"function",
"accepts",
"either",
"a",
"job_id",
"or",
"a",
"job",
"instance",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L241-L249 | train | 198,561 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.change_execution_time | def change_execution_time(self, job, date_time):
"""
Change a job's execution time.
"""
with self.connection.pipeline() as pipe:
while 1:
try:
pipe.watch(self.scheduled_jobs_key)
if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
raise ValueError('Job not in scheduled jobs queue')
pipe.zadd(self.scheduled_jobs_key, {job.id: to_unix(date_time)})
break
except WatchError:
# If job is still in the queue, retry otherwise job is already executed
# so we raise an error
if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
raise ValueError('Job not in scheduled jobs queue')
continue | python | def change_execution_time(self, job, date_time):
"""
Change a job's execution time.
"""
with self.connection.pipeline() as pipe:
while 1:
try:
pipe.watch(self.scheduled_jobs_key)
if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
raise ValueError('Job not in scheduled jobs queue')
pipe.zadd(self.scheduled_jobs_key, {job.id: to_unix(date_time)})
break
except WatchError:
# If job is still in the queue, retry otherwise job is already executed
# so we raise an error
if pipe.zscore(self.scheduled_jobs_key, job.id) is None:
raise ValueError('Job not in scheduled jobs queue')
continue | [
"def",
"change_execution_time",
"(",
"self",
",",
"job",
",",
"date_time",
")",
":",
"with",
"self",
".",
"connection",
".",
"pipeline",
"(",
")",
"as",
"pipe",
":",
"while",
"1",
":",
"try",
":",
"pipe",
".",
"watch",
"(",
"self",
".",
"scheduled_jobs... | Change a job's execution time. | [
"Change",
"a",
"job",
"s",
"execution",
"time",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L261-L278 | train | 198,562 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.count | def count(self, until=None):
"""
Returns the total number of jobs that are scheduled for all queues.
This function accepts datetime, timedelta instances as well as
integers representing epoch values.
"""
until = rationalize_until(until)
return self.connection.zcount(self.scheduled_jobs_key, 0, until) | python | def count(self, until=None):
"""
Returns the total number of jobs that are scheduled for all queues.
This function accepts datetime, timedelta instances as well as
integers representing epoch values.
"""
until = rationalize_until(until)
return self.connection.zcount(self.scheduled_jobs_key, 0, until) | [
"def",
"count",
"(",
"self",
",",
"until",
"=",
"None",
")",
":",
"until",
"=",
"rationalize_until",
"(",
"until",
")",
"return",
"self",
".",
"connection",
".",
"zcount",
"(",
"self",
".",
"scheduled_jobs_key",
",",
"0",
",",
"until",
")"
] | Returns the total number of jobs that are scheduled for all queues.
This function accepts datetime, timedelta instances as well as
integers representing epoch values. | [
"Returns",
"the",
"total",
"number",
"of",
"jobs",
"that",
"are",
"scheduled",
"for",
"all",
"queues",
".",
"This",
"function",
"accepts",
"datetime",
"timedelta",
"instances",
"as",
"well",
"as",
"integers",
"representing",
"epoch",
"values",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L280-L288 | train | 198,563 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.get_jobs | def get_jobs(self, until=None, with_times=False, offset=None, length=None):
"""
Returns a iterator of job instances that will be queued until the given
time. If no 'until' argument is given all jobs are returned.
If with_times is True, a list of tuples consisting of the job instance
and it's scheduled execution time is returned.
If offset and length are specified, a slice of the list starting at the
specified zero-based offset of the specified length will be returned.
If either of offset or length is specified, then both must be, or
an exception will be raised.
"""
def epoch_to_datetime(epoch):
return from_unix(float(epoch))
until = rationalize_until(until)
job_ids = self.connection.zrangebyscore(self.scheduled_jobs_key, 0,
until, withscores=with_times,
score_cast_func=epoch_to_datetime,
start=offset, num=length)
if not with_times:
job_ids = zip(job_ids, repeat(None))
for job_id, sched_time in job_ids:
job_id = job_id.decode('utf-8')
try:
job = self.job_class.fetch(job_id, connection=self.connection)
except NoSuchJobError:
# Delete jobs that aren't there from scheduler
self.cancel(job_id)
continue
if with_times:
yield (job, sched_time)
else:
yield job | python | def get_jobs(self, until=None, with_times=False, offset=None, length=None):
"""
Returns a iterator of job instances that will be queued until the given
time. If no 'until' argument is given all jobs are returned.
If with_times is True, a list of tuples consisting of the job instance
and it's scheduled execution time is returned.
If offset and length are specified, a slice of the list starting at the
specified zero-based offset of the specified length will be returned.
If either of offset or length is specified, then both must be, or
an exception will be raised.
"""
def epoch_to_datetime(epoch):
return from_unix(float(epoch))
until = rationalize_until(until)
job_ids = self.connection.zrangebyscore(self.scheduled_jobs_key, 0,
until, withscores=with_times,
score_cast_func=epoch_to_datetime,
start=offset, num=length)
if not with_times:
job_ids = zip(job_ids, repeat(None))
for job_id, sched_time in job_ids:
job_id = job_id.decode('utf-8')
try:
job = self.job_class.fetch(job_id, connection=self.connection)
except NoSuchJobError:
# Delete jobs that aren't there from scheduler
self.cancel(job_id)
continue
if with_times:
yield (job, sched_time)
else:
yield job | [
"def",
"get_jobs",
"(",
"self",
",",
"until",
"=",
"None",
",",
"with_times",
"=",
"False",
",",
"offset",
"=",
"None",
",",
"length",
"=",
"None",
")",
":",
"def",
"epoch_to_datetime",
"(",
"epoch",
")",
":",
"return",
"from_unix",
"(",
"float",
"(",
... | Returns a iterator of job instances that will be queued until the given
time. If no 'until' argument is given all jobs are returned.
If with_times is True, a list of tuples consisting of the job instance
and it's scheduled execution time is returned.
If offset and length are specified, a slice of the list starting at the
specified zero-based offset of the specified length will be returned.
If either of offset or length is specified, then both must be, or
an exception will be raised. | [
"Returns",
"a",
"iterator",
"of",
"job",
"instances",
"that",
"will",
"be",
"queued",
"until",
"the",
"given",
"time",
".",
"If",
"no",
"until",
"argument",
"is",
"given",
"all",
"jobs",
"are",
"returned",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L290-L325 | train | 198,564 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.get_queue_for_job | def get_queue_for_job(self, job):
"""
Returns a queue to put job into.
"""
if self._queue is not None:
return self._queue
key = '{0}{1}'.format(self.queue_class.redis_queue_namespace_prefix,
job.origin)
return self.queue_class.from_queue_key(
key, connection=self.connection, job_class=self.job_class) | python | def get_queue_for_job(self, job):
"""
Returns a queue to put job into.
"""
if self._queue is not None:
return self._queue
key = '{0}{1}'.format(self.queue_class.redis_queue_namespace_prefix,
job.origin)
return self.queue_class.from_queue_key(
key, connection=self.connection, job_class=self.job_class) | [
"def",
"get_queue_for_job",
"(",
"self",
",",
"job",
")",
":",
"if",
"self",
".",
"_queue",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_queue",
"key",
"=",
"'{0}{1}'",
".",
"format",
"(",
"self",
".",
"queue_class",
".",
"redis_queue_namespace_prefi... | Returns a queue to put job into. | [
"Returns",
"a",
"queue",
"to",
"put",
"job",
"into",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L336-L345 | train | 198,565 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.enqueue_job | def enqueue_job(self, job):
"""
Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed.
"""
self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin))
interval = job.meta.get('interval', None)
repeat = job.meta.get('repeat', None)
cron_string = job.meta.get('cron_string', None)
# If job is a repeated job, decrement counter
if repeat:
job.meta['repeat'] = int(repeat) - 1
queue = self.get_queue_for_job(job)
queue.enqueue_job(job)
self.connection.zrem(self.scheduled_jobs_key, job.id)
if interval:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
return
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(datetime.utcnow()) + int(interval)})
elif cron_string:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
return
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(get_next_scheduled_time(cron_string))}) | python | def enqueue_job(self, job):
"""
Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed.
"""
self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin))
interval = job.meta.get('interval', None)
repeat = job.meta.get('repeat', None)
cron_string = job.meta.get('cron_string', None)
# If job is a repeated job, decrement counter
if repeat:
job.meta['repeat'] = int(repeat) - 1
queue = self.get_queue_for_job(job)
queue.enqueue_job(job)
self.connection.zrem(self.scheduled_jobs_key, job.id)
if interval:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
return
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(datetime.utcnow()) + int(interval)})
elif cron_string:
# If this is a repeat job and counter has reached 0, don't repeat
if repeat is not None:
if job.meta['repeat'] == 0:
return
self.connection.zadd(self.scheduled_jobs_key,
{job.id: to_unix(get_next_scheduled_time(cron_string))}) | [
"def",
"enqueue_job",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Pushing {0} to {1}'",
".",
"format",
"(",
"job",
".",
"id",
",",
"job",
".",
"origin",
")",
")",
"interval",
"=",
"job",
".",
"meta",
".",
"get",
"(",... | Move a scheduled job to a queue. In addition, it also does puts the job
back into the scheduler if needed. | [
"Move",
"a",
"scheduled",
"job",
"to",
"a",
"queue",
".",
"In",
"addition",
"it",
"also",
"does",
"puts",
"the",
"job",
"back",
"into",
"the",
"scheduler",
"if",
"needed",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L347-L379 | train | 198,566 |
rq/rq-scheduler | rq_scheduler/scheduler.py | Scheduler.enqueue_jobs | def enqueue_jobs(self):
"""
Move scheduled jobs into queues.
"""
self.log.debug('Checking for scheduled jobs')
jobs = self.get_jobs_to_queue()
for job in jobs:
self.enqueue_job(job)
# Refresh scheduler key's expiry
self.connection.expire(self.scheduler_key, int(self._interval) + 10)
return jobs | python | def enqueue_jobs(self):
"""
Move scheduled jobs into queues.
"""
self.log.debug('Checking for scheduled jobs')
jobs = self.get_jobs_to_queue()
for job in jobs:
self.enqueue_job(job)
# Refresh scheduler key's expiry
self.connection.expire(self.scheduler_key, int(self._interval) + 10)
return jobs | [
"def",
"enqueue_jobs",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Checking for scheduled jobs'",
")",
"jobs",
"=",
"self",
".",
"get_jobs_to_queue",
"(",
")",
"for",
"job",
"in",
"jobs",
":",
"self",
".",
"enqueue_job",
"(",
"job",
"... | Move scheduled jobs into queues. | [
"Move",
"scheduled",
"jobs",
"into",
"queues",
"."
] | ee60c19e42a46ba787f762733a0036aa0cf2f7b7 | https://github.com/rq/rq-scheduler/blob/ee60c19e42a46ba787f762733a0036aa0cf2f7b7/rq_scheduler/scheduler.py#L381-L393 | train | 198,567 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | _checkDimensionsListLike | def _checkDimensionsListLike(arrays):
"""Check that each array in a list of arrays has the same size.
"""
dim1 = len(arrays)
dim2, dim3 = arrays[0].shape
for aa in range(1, dim1):
dim2_aa, dim3_aa = arrays[aa].shape
if (dim2_aa != dim2) or (dim3_aa != dim3):
raise _error.InvalidError(_MDPERR["obj_square"])
return dim1, dim2, dim3 | python | def _checkDimensionsListLike(arrays):
"""Check that each array in a list of arrays has the same size.
"""
dim1 = len(arrays)
dim2, dim3 = arrays[0].shape
for aa in range(1, dim1):
dim2_aa, dim3_aa = arrays[aa].shape
if (dim2_aa != dim2) or (dim3_aa != dim3):
raise _error.InvalidError(_MDPERR["obj_square"])
return dim1, dim2, dim3 | [
"def",
"_checkDimensionsListLike",
"(",
"arrays",
")",
":",
"dim1",
"=",
"len",
"(",
"arrays",
")",
"dim2",
",",
"dim3",
"=",
"arrays",
"[",
"0",
"]",
".",
"shape",
"for",
"aa",
"in",
"range",
"(",
"1",
",",
"dim1",
")",
":",
"dim2_aa",
",",
"dim3_... | Check that each array in a list of arrays has the same size. | [
"Check",
"that",
"each",
"array",
"in",
"a",
"list",
"of",
"arrays",
"has",
"the",
"same",
"size",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L94-L104 | train | 198,568 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | _checkRewardsListLike | def _checkRewardsListLike(reward, n_actions, n_states):
"""Check that a list-like reward input is valid.
"""
try:
lenR = len(reward)
if lenR == n_actions:
dim1, dim2, dim3 = _checkDimensionsListLike(reward)
elif lenR == n_states:
dim1 = n_actions
dim2 = dim3 = lenR
else:
raise _error.InvalidError(_MDPERR["R_shape"])
except AttributeError:
raise _error.InvalidError(_MDPERR["R_shape"])
return dim1, dim2, dim3 | python | def _checkRewardsListLike(reward, n_actions, n_states):
"""Check that a list-like reward input is valid.
"""
try:
lenR = len(reward)
if lenR == n_actions:
dim1, dim2, dim3 = _checkDimensionsListLike(reward)
elif lenR == n_states:
dim1 = n_actions
dim2 = dim3 = lenR
else:
raise _error.InvalidError(_MDPERR["R_shape"])
except AttributeError:
raise _error.InvalidError(_MDPERR["R_shape"])
return dim1, dim2, dim3 | [
"def",
"_checkRewardsListLike",
"(",
"reward",
",",
"n_actions",
",",
"n_states",
")",
":",
"try",
":",
"lenR",
"=",
"len",
"(",
"reward",
")",
"if",
"lenR",
"==",
"n_actions",
":",
"dim1",
",",
"dim2",
",",
"dim3",
"=",
"_checkDimensionsListLike",
"(",
... | Check that a list-like reward input is valid. | [
"Check",
"that",
"a",
"list",
"-",
"like",
"reward",
"input",
"is",
"valid",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L107-L122 | train | 198,569 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | isSquare | def isSquare(matrix):
"""Check that ``matrix`` is square.
Returns
=======
is_square : bool
``True`` if ``matrix`` is square, ``False`` otherwise.
"""
try:
try:
dim1, dim2 = matrix.shape
except AttributeError:
dim1, dim2 = _np.array(matrix).shape
except ValueError:
return False
if dim1 == dim2:
return True
return False | python | def isSquare(matrix):
"""Check that ``matrix`` is square.
Returns
=======
is_square : bool
``True`` if ``matrix`` is square, ``False`` otherwise.
"""
try:
try:
dim1, dim2 = matrix.shape
except AttributeError:
dim1, dim2 = _np.array(matrix).shape
except ValueError:
return False
if dim1 == dim2:
return True
return False | [
"def",
"isSquare",
"(",
"matrix",
")",
":",
"try",
":",
"try",
":",
"dim1",
",",
"dim2",
"=",
"matrix",
".",
"shape",
"except",
"AttributeError",
":",
"dim1",
",",
"dim2",
"=",
"_np",
".",
"array",
"(",
"matrix",
")",
".",
"shape",
"except",
"ValueEr... | Check that ``matrix`` is square.
Returns
=======
is_square : bool
``True`` if ``matrix`` is square, ``False`` otherwise. | [
"Check",
"that",
"matrix",
"is",
"square",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L125-L143 | train | 198,570 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | isStochastic | def isStochastic(matrix):
"""Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise.
"""
try:
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
except AttributeError:
matrix = _np.array(matrix)
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
return (absdiff.max() <= 10*_np.spacing(_np.float64(1))) | python | def isStochastic(matrix):
"""Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise.
"""
try:
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
except AttributeError:
matrix = _np.array(matrix)
absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])))
return (absdiff.max() <= 10*_np.spacing(_np.float64(1))) | [
"def",
"isStochastic",
"(",
"matrix",
")",
":",
"try",
":",
"absdiff",
"=",
"(",
"_np",
".",
"abs",
"(",
"matrix",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
"-",
"_np",
".",
"ones",
"(",
"matrix",
".",
"shape",
"[",
"0",
"]",
")",
")",
")",
"ex... | Check that ``matrix`` is row stochastic.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is row stochastic, ``False`` otherwise. | [
"Check",
"that",
"matrix",
"is",
"row",
"stochastic",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L146-L160 | train | 198,571 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | isNonNegative | def isNonNegative(matrix):
"""Check that ``matrix`` is row non-negative.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is non-negative, ``False`` otherwise.
"""
try:
if (matrix >= 0).all():
return True
except (NotImplementedError, AttributeError, TypeError):
try:
if (matrix.data >= 0).all():
return True
except AttributeError:
matrix = _np.array(matrix)
if (matrix.data >= 0).all():
return True
return False | python | def isNonNegative(matrix):
"""Check that ``matrix`` is row non-negative.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is non-negative, ``False`` otherwise.
"""
try:
if (matrix >= 0).all():
return True
except (NotImplementedError, AttributeError, TypeError):
try:
if (matrix.data >= 0).all():
return True
except AttributeError:
matrix = _np.array(matrix)
if (matrix.data >= 0).all():
return True
return False | [
"def",
"isNonNegative",
"(",
"matrix",
")",
":",
"try",
":",
"if",
"(",
"matrix",
">=",
"0",
")",
".",
"all",
"(",
")",
":",
"return",
"True",
"except",
"(",
"NotImplementedError",
",",
"AttributeError",
",",
"TypeError",
")",
":",
"try",
":",
"if",
... | Check that ``matrix`` is row non-negative.
Returns
=======
is_stochastic : bool
``True`` if ``matrix`` is non-negative, ``False`` otherwise. | [
"Check",
"that",
"matrix",
"is",
"row",
"non",
"-",
"negative",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L163-L183 | train | 198,572 |
sawcordwell/pymdptoolbox | src/mdptoolbox/util.py | checkSquareStochastic | def checkSquareStochastic(matrix):
"""Check if ``matrix`` is a square and row-stochastic.
To pass the check the following conditions must be met:
* The matrix should be square, so the number of columns equals the
number of rows.
* The matrix should be row-stochastic so the rows should sum to one.
* Each value in the matrix must be positive.
If the check does not pass then a mdptoolbox.util.Invalid
Arguments
---------
``matrix`` : numpy.ndarray, scipy.sparse.*_matrix
A two dimensional array (matrix).
Notes
-----
Returns None if no error has been detected, else it raises an error.
"""
if not isSquare(matrix):
raise _error.SquareError
if not isStochastic(matrix):
raise _error.StochasticError
if not isNonNegative(matrix):
raise _error.NonNegativeError | python | def checkSquareStochastic(matrix):
"""Check if ``matrix`` is a square and row-stochastic.
To pass the check the following conditions must be met:
* The matrix should be square, so the number of columns equals the
number of rows.
* The matrix should be row-stochastic so the rows should sum to one.
* Each value in the matrix must be positive.
If the check does not pass then a mdptoolbox.util.Invalid
Arguments
---------
``matrix`` : numpy.ndarray, scipy.sparse.*_matrix
A two dimensional array (matrix).
Notes
-----
Returns None if no error has been detected, else it raises an error.
"""
if not isSquare(matrix):
raise _error.SquareError
if not isStochastic(matrix):
raise _error.StochasticError
if not isNonNegative(matrix):
raise _error.NonNegativeError | [
"def",
"checkSquareStochastic",
"(",
"matrix",
")",
":",
"if",
"not",
"isSquare",
"(",
"matrix",
")",
":",
"raise",
"_error",
".",
"SquareError",
"if",
"not",
"isStochastic",
"(",
"matrix",
")",
":",
"raise",
"_error",
".",
"StochasticError",
"if",
"not",
... | Check if ``matrix`` is a square and row-stochastic.
To pass the check the following conditions must be met:
* The matrix should be square, so the number of columns equals the
number of rows.
* The matrix should be row-stochastic so the rows should sum to one.
* Each value in the matrix must be positive.
If the check does not pass then a mdptoolbox.util.Invalid
Arguments
---------
``matrix`` : numpy.ndarray, scipy.sparse.*_matrix
A two dimensional array (matrix).
Notes
-----
Returns None if no error has been detected, else it raises an error. | [
"Check",
"if",
"matrix",
"is",
"a",
"square",
"and",
"row",
"-",
"stochastic",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/util.py#L186-L213 | train | 198,573 |
sawcordwell/pymdptoolbox | src/examples/tictactoe.py | isWon | def isWon(state, who):
"""Test if a tic-tac-toe game has been won.
Assumes that the board is in a legal state.
Will test if the value 1 is in any winning combination.
"""
for w in WINS:
S = sum(1 if (w[k] == 1 and state[k] == who) else 0
for k in range(ACTIONS))
if S == 3:
# We have a win
return True
# There were no wins so return False
return False | python | def isWon(state, who):
"""Test if a tic-tac-toe game has been won.
Assumes that the board is in a legal state.
Will test if the value 1 is in any winning combination.
"""
for w in WINS:
S = sum(1 if (w[k] == 1 and state[k] == who) else 0
for k in range(ACTIONS))
if S == 3:
# We have a win
return True
# There were no wins so return False
return False | [
"def",
"isWon",
"(",
"state",
",",
"who",
")",
":",
"for",
"w",
"in",
"WINS",
":",
"S",
"=",
"sum",
"(",
"1",
"if",
"(",
"w",
"[",
"k",
"]",
"==",
"1",
"and",
"state",
"[",
"k",
"]",
"==",
"who",
")",
"else",
"0",
"for",
"k",
"in",
"range... | Test if a tic-tac-toe game has been won.
Assumes that the board is in a legal state.
Will test if the value 1 is in any winning combination. | [
"Test",
"if",
"a",
"tic",
"-",
"tac",
"-",
"toe",
"game",
"has",
"been",
"won",
".",
"Assumes",
"that",
"the",
"board",
"is",
"in",
"a",
"legal",
"state",
".",
"Will",
"test",
"if",
"the",
"value",
"1",
"is",
"in",
"any",
"winning",
"combination",
... | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/examples/tictactoe.py#L156-L170 | train | 198,574 |
sawcordwell/pymdptoolbox | src/experimental/mdpsql.py | MDP.getPolicyValue | def getPolicyValue(self):
"""Get the policy and value vectors."""
self._cur.execute("SELECT action FROM policy")
r = self._cur.fetchall()
policy = [x[0] for x in r]
self._cur.execute("SELECT value FROM V")
r = self._cur.fetchall()
value = [x[0] for x in r]
return policy, value | python | def getPolicyValue(self):
"""Get the policy and value vectors."""
self._cur.execute("SELECT action FROM policy")
r = self._cur.fetchall()
policy = [x[0] for x in r]
self._cur.execute("SELECT value FROM V")
r = self._cur.fetchall()
value = [x[0] for x in r]
return policy, value | [
"def",
"getPolicyValue",
"(",
"self",
")",
":",
"self",
".",
"_cur",
".",
"execute",
"(",
"\"SELECT action FROM policy\"",
")",
"r",
"=",
"self",
".",
"_cur",
".",
"fetchall",
"(",
")",
"policy",
"=",
"[",
"x",
"[",
"0",
"]",
"for",
"x",
"in",
"r",
... | Get the policy and value vectors. | [
"Get",
"the",
"policy",
"and",
"value",
"vectors",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/experimental/mdpsql.py#L268-L276 | train | 198,575 |
sawcordwell/pymdptoolbox | src/mdptoolbox/example.py | forest | def forest(S=3, r1=4, r2=2, p=0.1, is_sparse=False):
"""Generate a MDP example based on a simple forest management scenario.
This function is used to generate a transition probability
(``A`` × ``S`` × ``S``) array ``P`` and a reward (``S`` × ``A``) matrix
``R`` that model the following problem. A forest is managed by two actions:
'Wait' and 'Cut'. An action is decided each year with first the objective
to maintain an old forest for wildlife and second to make money selling cut
wood. Each year there is a probability ``p`` that a fire burns the forest.
Here is how the problem is modelled.
Let {0, 1 . . . ``S``-1 } be the states of the forest, with ``S``-1 being
the oldest. Let 'Wait' be action 0 and 'Cut' be action 1.
After a fire, the forest is in the youngest state, that is state 0.
The transition matrix ``P`` of the problem can then be defined as follows::
| p 1-p 0.......0 |
| . 0 1-p 0....0 |
P[0,:,:] = | . . 0 . |
| . . . |
| . . 1-p |
| p 0 0....0 1-p |
| 1 0..........0 |
| . . . |
P[1,:,:] = | . . . |
| . . . |
| . . . |
| 1 0..........0 |
The reward matrix R is defined as follows::
| 0 |
| . |
R[:,0] = | . |
| . |
| 0 |
| r1 |
| 0 |
| 1 |
R[:,1] = | . |
| . |
| 1 |
| r2 |
Parameters
---------
S : int, optional
The number of states, which should be an integer greater than 1.
Default: 3.
r1 : float, optional
The reward when the forest is in its oldest state and action 'Wait' is
performed. Default: 4.
r2 : float, optional
The reward when the forest is in its oldest state and action 'Cut' is
performed. Default: 2.
p : float, optional
The probability of wild fire occurence, in the range ]0, 1[. Default:
0.1.
is_sparse : bool, optional
If True, then the probability transition matrices will be returned in
sparse format, otherwise they will be in dense format. Default: False.
Returns
-------
out : tuple
``out[0]`` contains the transition probability matrix P and ``out[1]``
contains the reward matrix R. If ``is_sparse=False`` then P is a numpy
array with a shape of ``(A, S, S)`` and R is a numpy array with a shape
of ``(S, A)``. If ``is_sparse=True`` then P is a tuple of length ``A``
where each ``P[a]`` is a scipy sparse CSR format matrix of shape
``(S, S)``; R remains the same as in the case of ``is_sparse=False``.
Examples
--------
>>> import mdptoolbox.example
>>> P, R = mdptoolbox.example.forest()
>>> P
array([[[ 0.1, 0.9, 0. ],
[ 0.1, 0. , 0.9],
[ 0.1, 0. , 0.9]],
<BLANKLINE>
[[ 1. , 0. , 0. ],
[ 1. , 0. , 0. ],
[ 1. , 0. , 0. ]]])
>>> R
array([[ 0., 0.],
[ 0., 1.],
[ 4., 2.]])
>>> Psp, Rsp = mdptoolbox.example.forest(is_sparse=True)
>>> len(Psp)
2
>>> Psp[0]
<3x3 sparse matrix of type '<... 'numpy.float64'>'
with 6 stored elements in Compressed Sparse Row format>
>>> Psp[1]
<3x3 sparse matrix of type '<... 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
>>> Rsp
array([[ 0., 0.],
[ 0., 1.],
[ 4., 2.]])
>>> (Psp[0].todense() == P[0]).all()
True
>>> (Rsp == R).all()
True
"""
assert S > 1, "The number of states S must be greater than 1."
assert (r1 > 0) and (r2 > 0), "The rewards must be non-negative."
assert 0 <= p <= 1, "The probability p must be in [0; 1]."
# Definition of Transition matrix
if is_sparse:
P = []
rows = list(range(S)) * 2
cols = [0] * S + list(range(1, S)) + [S - 1]
vals = [p] * S + [1-p] * S
P.append(_sp.coo_matrix((vals, (rows, cols)), shape=(S, S)).tocsr())
rows = list(range(S))
cols = [0] * S
vals = [1] * S
P.append(_sp.coo_matrix((vals, (rows, cols)), shape=(S, S)).tocsr())
else:
P = _np.zeros((2, S, S))
P[0, :, :] = (1 - p) * _np.diag(_np.ones(S - 1), 1)
P[0, :, 0] = p
P[0, S - 1, S - 1] = (1 - p)
P[1, :, :] = _np.zeros((S, S))
P[1, :, 0] = 1
# Definition of Reward matrix
R = _np.zeros((S, 2))
R[S - 1, 0] = r1
R[:, 1] = _np.ones(S)
R[0, 1] = 0
R[S - 1, 1] = r2
return(P, R) | python | def forest(S=3, r1=4, r2=2, p=0.1, is_sparse=False):
"""Generate a MDP example based on a simple forest management scenario.
This function is used to generate a transition probability
(``A`` × ``S`` × ``S``) array ``P`` and a reward (``S`` × ``A``) matrix
``R`` that model the following problem. A forest is managed by two actions:
'Wait' and 'Cut'. An action is decided each year with first the objective
to maintain an old forest for wildlife and second to make money selling cut
wood. Each year there is a probability ``p`` that a fire burns the forest.
Here is how the problem is modelled.
Let {0, 1 . . . ``S``-1 } be the states of the forest, with ``S``-1 being
the oldest. Let 'Wait' be action 0 and 'Cut' be action 1.
After a fire, the forest is in the youngest state, that is state 0.
The transition matrix ``P`` of the problem can then be defined as follows::
| p 1-p 0.......0 |
| . 0 1-p 0....0 |
P[0,:,:] = | . . 0 . |
| . . . |
| . . 1-p |
| p 0 0....0 1-p |
| 1 0..........0 |
| . . . |
P[1,:,:] = | . . . |
| . . . |
| . . . |
| 1 0..........0 |
The reward matrix R is defined as follows::
| 0 |
| . |
R[:,0] = | . |
| . |
| 0 |
| r1 |
| 0 |
| 1 |
R[:,1] = | . |
| . |
| 1 |
| r2 |
Parameters
---------
S : int, optional
The number of states, which should be an integer greater than 1.
Default: 3.
r1 : float, optional
The reward when the forest is in its oldest state and action 'Wait' is
performed. Default: 4.
r2 : float, optional
The reward when the forest is in its oldest state and action 'Cut' is
performed. Default: 2.
p : float, optional
The probability of wild fire occurence, in the range ]0, 1[. Default:
0.1.
is_sparse : bool, optional
If True, then the probability transition matrices will be returned in
sparse format, otherwise they will be in dense format. Default: False.
Returns
-------
out : tuple
``out[0]`` contains the transition probability matrix P and ``out[1]``
contains the reward matrix R. If ``is_sparse=False`` then P is a numpy
array with a shape of ``(A, S, S)`` and R is a numpy array with a shape
of ``(S, A)``. If ``is_sparse=True`` then P is a tuple of length ``A``
where each ``P[a]`` is a scipy sparse CSR format matrix of shape
``(S, S)``; R remains the same as in the case of ``is_sparse=False``.
Examples
--------
>>> import mdptoolbox.example
>>> P, R = mdptoolbox.example.forest()
>>> P
array([[[ 0.1, 0.9, 0. ],
[ 0.1, 0. , 0.9],
[ 0.1, 0. , 0.9]],
<BLANKLINE>
[[ 1. , 0. , 0. ],
[ 1. , 0. , 0. ],
[ 1. , 0. , 0. ]]])
>>> R
array([[ 0., 0.],
[ 0., 1.],
[ 4., 2.]])
>>> Psp, Rsp = mdptoolbox.example.forest(is_sparse=True)
>>> len(Psp)
2
>>> Psp[0]
<3x3 sparse matrix of type '<... 'numpy.float64'>'
with 6 stored elements in Compressed Sparse Row format>
>>> Psp[1]
<3x3 sparse matrix of type '<... 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
>>> Rsp
array([[ 0., 0.],
[ 0., 1.],
[ 4., 2.]])
>>> (Psp[0].todense() == P[0]).all()
True
>>> (Rsp == R).all()
True
"""
assert S > 1, "The number of states S must be greater than 1."
assert (r1 > 0) and (r2 > 0), "The rewards must be non-negative."
assert 0 <= p <= 1, "The probability p must be in [0; 1]."
# Definition of Transition matrix
if is_sparse:
P = []
rows = list(range(S)) * 2
cols = [0] * S + list(range(1, S)) + [S - 1]
vals = [p] * S + [1-p] * S
P.append(_sp.coo_matrix((vals, (rows, cols)), shape=(S, S)).tocsr())
rows = list(range(S))
cols = [0] * S
vals = [1] * S
P.append(_sp.coo_matrix((vals, (rows, cols)), shape=(S, S)).tocsr())
else:
P = _np.zeros((2, S, S))
P[0, :, :] = (1 - p) * _np.diag(_np.ones(S - 1), 1)
P[0, :, 0] = p
P[0, S - 1, S - 1] = (1 - p)
P[1, :, :] = _np.zeros((S, S))
P[1, :, 0] = 1
# Definition of Reward matrix
R = _np.zeros((S, 2))
R[S - 1, 0] = r1
R[:, 1] = _np.ones(S)
R[0, 1] = 0
R[S - 1, 1] = r2
return(P, R) | [
"def",
"forest",
"(",
"S",
"=",
"3",
",",
"r1",
"=",
"4",
",",
"r2",
"=",
"2",
",",
"p",
"=",
"0.1",
",",
"is_sparse",
"=",
"False",
")",
":",
"assert",
"S",
">",
"1",
",",
"\"The number of states S must be greater than 1.\"",
"assert",
"(",
"r1",
">... | Generate a MDP example based on a simple forest management scenario.
This function is used to generate a transition probability
(``A`` × ``S`` × ``S``) array ``P`` and a reward (``S`` × ``A``) matrix
``R`` that model the following problem. A forest is managed by two actions:
'Wait' and 'Cut'. An action is decided each year with first the objective
to maintain an old forest for wildlife and second to make money selling cut
wood. Each year there is a probability ``p`` that a fire burns the forest.
Here is how the problem is modelled.
Let {0, 1 . . . ``S``-1 } be the states of the forest, with ``S``-1 being
the oldest. Let 'Wait' be action 0 and 'Cut' be action 1.
After a fire, the forest is in the youngest state, that is state 0.
The transition matrix ``P`` of the problem can then be defined as follows::
| p 1-p 0.......0 |
| . 0 1-p 0....0 |
P[0,:,:] = | . . 0 . |
| . . . |
| . . 1-p |
| p 0 0....0 1-p |
| 1 0..........0 |
| . . . |
P[1,:,:] = | . . . |
| . . . |
| . . . |
| 1 0..........0 |
The reward matrix R is defined as follows::
| 0 |
| . |
R[:,0] = | . |
| . |
| 0 |
| r1 |
| 0 |
| 1 |
R[:,1] = | . |
| . |
| 1 |
| r2 |
Parameters
---------
S : int, optional
The number of states, which should be an integer greater than 1.
Default: 3.
r1 : float, optional
The reward when the forest is in its oldest state and action 'Wait' is
performed. Default: 4.
r2 : float, optional
The reward when the forest is in its oldest state and action 'Cut' is
performed. Default: 2.
p : float, optional
The probability of wild fire occurence, in the range ]0, 1[. Default:
0.1.
is_sparse : bool, optional
If True, then the probability transition matrices will be returned in
sparse format, otherwise they will be in dense format. Default: False.
Returns
-------
out : tuple
``out[0]`` contains the transition probability matrix P and ``out[1]``
contains the reward matrix R. If ``is_sparse=False`` then P is a numpy
array with a shape of ``(A, S, S)`` and R is a numpy array with a shape
of ``(S, A)``. If ``is_sparse=True`` then P is a tuple of length ``A``
where each ``P[a]`` is a scipy sparse CSR format matrix of shape
``(S, S)``; R remains the same as in the case of ``is_sparse=False``.
Examples
--------
>>> import mdptoolbox.example
>>> P, R = mdptoolbox.example.forest()
>>> P
array([[[ 0.1, 0.9, 0. ],
[ 0.1, 0. , 0.9],
[ 0.1, 0. , 0.9]],
<BLANKLINE>
[[ 1. , 0. , 0. ],
[ 1. , 0. , 0. ],
[ 1. , 0. , 0. ]]])
>>> R
array([[ 0., 0.],
[ 0., 1.],
[ 4., 2.]])
>>> Psp, Rsp = mdptoolbox.example.forest(is_sparse=True)
>>> len(Psp)
2
>>> Psp[0]
<3x3 sparse matrix of type '<... 'numpy.float64'>'
with 6 stored elements in Compressed Sparse Row format>
>>> Psp[1]
<3x3 sparse matrix of type '<... 'numpy.int64'>'
with 3 stored elements in Compressed Sparse Row format>
>>> Rsp
array([[ 0., 0.],
[ 0., 1.],
[ 4., 2.]])
>>> (Psp[0].todense() == P[0]).all()
True
>>> (Rsp == R).all()
True | [
"Generate",
"a",
"MDP",
"example",
"based",
"on",
"a",
"simple",
"forest",
"management",
"scenario",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/example.py#L53-L189 | train | 198,576 |
sawcordwell/pymdptoolbox | src/mdptoolbox/example.py | _randDense | def _randDense(states, actions, mask):
"""Generate random dense ``P`` and ``R``. See ``rand`` for details.
"""
# definition of transition matrix : square stochastic matrix
P = _np.zeros((actions, states, states))
# definition of reward matrix (values between -1 and +1)
R = _np.zeros((actions, states, states))
for action in range(actions):
for state in range(states):
# create our own random mask if there is no user supplied one
if mask is None:
m = _np.random.random(states)
r = _np.random.random()
m[m <= r] = 0
m[m > r] = 1
elif mask.shape == (actions, states, states):
m = mask[action][state] # mask[action, state, :]
else:
m = mask[state]
# Make sure that there is atleast one transition in each state
if m.sum() == 0:
m[_np.random.randint(0, states)] = 1
P[action][state] = m * _np.random.random(states)
P[action][state] = P[action][state] / P[action][state].sum()
R[action][state] = (m * (2 * _np.random.random(states) -
_np.ones(states, dtype=int)))
return(P, R) | python | def _randDense(states, actions, mask):
"""Generate random dense ``P`` and ``R``. See ``rand`` for details.
"""
# definition of transition matrix : square stochastic matrix
P = _np.zeros((actions, states, states))
# definition of reward matrix (values between -1 and +1)
R = _np.zeros((actions, states, states))
for action in range(actions):
for state in range(states):
# create our own random mask if there is no user supplied one
if mask is None:
m = _np.random.random(states)
r = _np.random.random()
m[m <= r] = 0
m[m > r] = 1
elif mask.shape == (actions, states, states):
m = mask[action][state] # mask[action, state, :]
else:
m = mask[state]
# Make sure that there is atleast one transition in each state
if m.sum() == 0:
m[_np.random.randint(0, states)] = 1
P[action][state] = m * _np.random.random(states)
P[action][state] = P[action][state] / P[action][state].sum()
R[action][state] = (m * (2 * _np.random.random(states) -
_np.ones(states, dtype=int)))
return(P, R) | [
"def",
"_randDense",
"(",
"states",
",",
"actions",
",",
"mask",
")",
":",
"# definition of transition matrix : square stochastic matrix",
"P",
"=",
"_np",
".",
"zeros",
"(",
"(",
"actions",
",",
"states",
",",
"states",
")",
")",
"# definition of reward matrix (val... | Generate random dense ``P`` and ``R``. See ``rand`` for details. | [
"Generate",
"random",
"dense",
"P",
"and",
"R",
".",
"See",
"rand",
"for",
"details",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/example.py#L192-L219 | train | 198,577 |
sawcordwell/pymdptoolbox | src/mdptoolbox/example.py | _randSparse | def _randSparse(states, actions, mask):
"""Generate random sparse ``P`` and ``R``. See ``rand`` for details.
"""
# definition of transition matrix : square stochastic matrix
P = [None] * actions
# definition of reward matrix (values between -1 and +1)
R = [None] * actions
for action in range(actions):
# it may be more efficient to implement this by constructing lists
# of rows, columns and values then creating a coo_matrix, but this
# works for now
PP = _sp.dok_matrix((states, states))
RR = _sp.dok_matrix((states, states))
for state in range(states):
if mask is None:
m = _np.random.random(states)
m[m <= 2/3.0] = 0
m[m > 2/3.0] = 1
elif mask.shape == (actions, states, states):
m = mask[action][state] # mask[action, state, :]
else:
m = mask[state]
n = int(m.sum()) # m[state, :]
if n == 0:
m[_np.random.randint(0, states)] = 1
n = 1
# find the columns of the vector that have non-zero elements
nz = m.nonzero()
if len(nz) == 1:
cols = nz[0]
else:
cols = nz[1]
vals = _np.random.random(n)
vals = vals / vals.sum()
reward = 2*_np.random.random(n) - _np.ones(n)
PP[state, cols] = vals
RR[state, cols] = reward
# PP.tocsr() takes the same amount of time as PP.tocoo().tocsr()
# so constructing PP and RR as coo_matrix in the first place is
# probably "better"
P[action] = PP.tocsr()
R[action] = RR.tocsr()
return(P, R) | python | def _randSparse(states, actions, mask):
"""Generate random sparse ``P`` and ``R``. See ``rand`` for details.
"""
# definition of transition matrix : square stochastic matrix
P = [None] * actions
# definition of reward matrix (values between -1 and +1)
R = [None] * actions
for action in range(actions):
# it may be more efficient to implement this by constructing lists
# of rows, columns and values then creating a coo_matrix, but this
# works for now
PP = _sp.dok_matrix((states, states))
RR = _sp.dok_matrix((states, states))
for state in range(states):
if mask is None:
m = _np.random.random(states)
m[m <= 2/3.0] = 0
m[m > 2/3.0] = 1
elif mask.shape == (actions, states, states):
m = mask[action][state] # mask[action, state, :]
else:
m = mask[state]
n = int(m.sum()) # m[state, :]
if n == 0:
m[_np.random.randint(0, states)] = 1
n = 1
# find the columns of the vector that have non-zero elements
nz = m.nonzero()
if len(nz) == 1:
cols = nz[0]
else:
cols = nz[1]
vals = _np.random.random(n)
vals = vals / vals.sum()
reward = 2*_np.random.random(n) - _np.ones(n)
PP[state, cols] = vals
RR[state, cols] = reward
# PP.tocsr() takes the same amount of time as PP.tocoo().tocsr()
# so constructing PP and RR as coo_matrix in the first place is
# probably "better"
P[action] = PP.tocsr()
R[action] = RR.tocsr()
return(P, R) | [
"def",
"_randSparse",
"(",
"states",
",",
"actions",
",",
"mask",
")",
":",
"# definition of transition matrix : square stochastic matrix",
"P",
"=",
"[",
"None",
"]",
"*",
"actions",
"# definition of reward matrix (values between -1 and +1)",
"R",
"=",
"[",
"None",
"]"... | Generate random sparse ``P`` and ``R``. See ``rand`` for details. | [
"Generate",
"random",
"sparse",
"P",
"and",
"R",
".",
"See",
"rand",
"for",
"details",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/example.py#L222-L265 | train | 198,578 |
sawcordwell/pymdptoolbox | src/mdptoolbox/example.py | rand | def rand(S, A, is_sparse=False, mask=None):
"""Generate a random Markov Decision Process.
Parameters
----------
S : int
Number of states (> 1)
A : int
Number of actions (> 1)
is_sparse : bool, optional
False to have matrices in dense format, True to have sparse matrices.
Default: False.
mask : array, optional
Array with 0 and 1 (0 indicates a place for a zero probability), shape
can be ``(S, S)`` or ``(A, S, S)``. Default: random.
Returns
-------
out : tuple
``out[0]`` contains the transition probability matrix P and ``out[1]``
contains the reward matrix R. If ``is_sparse=False`` then P is a numpy
array with a shape of ``(A, S, S)`` and R is a numpy array with a shape
of ``(S, A)``. If ``is_sparse=True`` then P and R are tuples of length
``A``, where each ``P[a]`` is a scipy sparse CSR format matrix of shape
``(S, S)`` and each ``R[a]`` is a scipy sparse csr format matrix of
shape ``(S, 1)``.
Examples
--------
>>> import numpy, mdptoolbox.example
>>> numpy.random.seed(0) # Needed to get the output below
>>> P, R = mdptoolbox.example.rand(4, 3)
>>> P
array([[[ 0.21977283, 0.14889403, 0.30343592, 0.32789723],
[ 1. , 0. , 0. , 0. ],
[ 0. , 0.43718772, 0.54480359, 0.01800869],
[ 0.39766289, 0.39997167, 0.12547318, 0.07689227]],
<BLANKLINE>
[[ 1. , 0. , 0. , 0. ],
[ 0.32261337, 0.15483812, 0.32271303, 0.19983549],
[ 0.33816885, 0.2766999 , 0.12960299, 0.25552826],
[ 0.41299411, 0. , 0.58369957, 0.00330633]],
<BLANKLINE>
[[ 0.32343037, 0.15178596, 0.28733094, 0.23745272],
[ 0.36348538, 0.24483321, 0.16114188, 0.23053953],
[ 1. , 0. , 0. , 0. ],
[ 0. , 0. , 1. , 0. ]]])
>>> R
array([[[-0.23311696, 0.58345008, 0.05778984, 0.13608912],
[-0.07704128, 0. , -0. , 0. ],
[ 0. , 0.22419145, 0.23386799, 0.88749616],
[-0.3691433 , -0.27257846, 0.14039354, -0.12279697]],
<BLANKLINE>
[[-0.77924972, 0. , -0. , -0. ],
[ 0.47852716, -0.92162442, -0.43438607, -0.75960688],
[-0.81211898, 0.15189299, 0.8585924 , -0.3628621 ],
[ 0.35563307, -0. , 0.47038804, 0.92437709]],
<BLANKLINE>
[[-0.4051261 , 0.62759564, -0.20698852, 0.76220639],
[-0.9616136 , -0.39685037, 0.32034707, -0.41984479],
[-0.13716313, 0. , -0. , -0. ],
[ 0. , -0. , 0.55810204, 0. ]]])
>>> numpy.random.seed(0) # Needed to get the output below
>>> Psp, Rsp = mdptoolbox.example.rand(100, 5, is_sparse=True)
>>> len(Psp), len(Rsp)
(5, 5)
>>> Psp[0]
<100x100 sparse matrix of type '<... 'numpy.float64'>'
with 3296 stored elements in Compressed Sparse Row format>
>>> Rsp[0]
<100x100 sparse matrix of type '<... 'numpy.float64'>'
with 3296 stored elements in Compressed Sparse Row format>
>>> # The number of non-zero elements (nnz) in P and R are equal
>>> Psp[1].nnz == Rsp[1].nnz
True
"""
# making sure the states and actions are more than one
assert S > 1, "The number of states S must be greater than 1."
assert A > 1, "The number of actions A must be greater than 1."
# if the user hasn't specified a mask, then we will make a random one now
if mask is not None:
# the mask needs to be SxS or AxSxS
try:
assert mask.shape in ((S, S), (A, S, S)), (
"'mask' must have dimensions S×S or A×S×S."
)
except AttributeError:
raise TypeError("'mask' must be a numpy array or matrix.")
# generate the transition and reward matrices based on S, A and mask
if is_sparse:
P, R = _randSparse(S, A, mask)
else:
P, R = _randDense(S, A, mask)
return(P, R) | python | def rand(S, A, is_sparse=False, mask=None):
"""Generate a random Markov Decision Process.
Parameters
----------
S : int
Number of states (> 1)
A : int
Number of actions (> 1)
is_sparse : bool, optional
False to have matrices in dense format, True to have sparse matrices.
Default: False.
mask : array, optional
Array with 0 and 1 (0 indicates a place for a zero probability), shape
can be ``(S, S)`` or ``(A, S, S)``. Default: random.
Returns
-------
out : tuple
``out[0]`` contains the transition probability matrix P and ``out[1]``
contains the reward matrix R. If ``is_sparse=False`` then P is a numpy
array with a shape of ``(A, S, S)`` and R is a numpy array with a shape
of ``(S, A)``. If ``is_sparse=True`` then P and R are tuples of length
``A``, where each ``P[a]`` is a scipy sparse CSR format matrix of shape
``(S, S)`` and each ``R[a]`` is a scipy sparse csr format matrix of
shape ``(S, 1)``.
Examples
--------
>>> import numpy, mdptoolbox.example
>>> numpy.random.seed(0) # Needed to get the output below
>>> P, R = mdptoolbox.example.rand(4, 3)
>>> P
array([[[ 0.21977283, 0.14889403, 0.30343592, 0.32789723],
[ 1. , 0. , 0. , 0. ],
[ 0. , 0.43718772, 0.54480359, 0.01800869],
[ 0.39766289, 0.39997167, 0.12547318, 0.07689227]],
<BLANKLINE>
[[ 1. , 0. , 0. , 0. ],
[ 0.32261337, 0.15483812, 0.32271303, 0.19983549],
[ 0.33816885, 0.2766999 , 0.12960299, 0.25552826],
[ 0.41299411, 0. , 0.58369957, 0.00330633]],
<BLANKLINE>
[[ 0.32343037, 0.15178596, 0.28733094, 0.23745272],
[ 0.36348538, 0.24483321, 0.16114188, 0.23053953],
[ 1. , 0. , 0. , 0. ],
[ 0. , 0. , 1. , 0. ]]])
>>> R
array([[[-0.23311696, 0.58345008, 0.05778984, 0.13608912],
[-0.07704128, 0. , -0. , 0. ],
[ 0. , 0.22419145, 0.23386799, 0.88749616],
[-0.3691433 , -0.27257846, 0.14039354, -0.12279697]],
<BLANKLINE>
[[-0.77924972, 0. , -0. , -0. ],
[ 0.47852716, -0.92162442, -0.43438607, -0.75960688],
[-0.81211898, 0.15189299, 0.8585924 , -0.3628621 ],
[ 0.35563307, -0. , 0.47038804, 0.92437709]],
<BLANKLINE>
[[-0.4051261 , 0.62759564, -0.20698852, 0.76220639],
[-0.9616136 , -0.39685037, 0.32034707, -0.41984479],
[-0.13716313, 0. , -0. , -0. ],
[ 0. , -0. , 0.55810204, 0. ]]])
>>> numpy.random.seed(0) # Needed to get the output below
>>> Psp, Rsp = mdptoolbox.example.rand(100, 5, is_sparse=True)
>>> len(Psp), len(Rsp)
(5, 5)
>>> Psp[0]
<100x100 sparse matrix of type '<... 'numpy.float64'>'
with 3296 stored elements in Compressed Sparse Row format>
>>> Rsp[0]
<100x100 sparse matrix of type '<... 'numpy.float64'>'
with 3296 stored elements in Compressed Sparse Row format>
>>> # The number of non-zero elements (nnz) in P and R are equal
>>> Psp[1].nnz == Rsp[1].nnz
True
"""
# making sure the states and actions are more than one
assert S > 1, "The number of states S must be greater than 1."
assert A > 1, "The number of actions A must be greater than 1."
# if the user hasn't specified a mask, then we will make a random one now
if mask is not None:
# the mask needs to be SxS or AxSxS
try:
assert mask.shape in ((S, S), (A, S, S)), (
"'mask' must have dimensions S×S or A×S×S."
)
except AttributeError:
raise TypeError("'mask' must be a numpy array or matrix.")
# generate the transition and reward matrices based on S, A and mask
if is_sparse:
P, R = _randSparse(S, A, mask)
else:
P, R = _randDense(S, A, mask)
return(P, R) | [
"def",
"rand",
"(",
"S",
",",
"A",
",",
"is_sparse",
"=",
"False",
",",
"mask",
"=",
"None",
")",
":",
"# making sure the states and actions are more than one",
"assert",
"S",
">",
"1",
",",
"\"The number of states S must be greater than 1.\"",
"assert",
"A",
">",
... | Generate a random Markov Decision Process.
Parameters
----------
S : int
Number of states (> 1)
A : int
Number of actions (> 1)
is_sparse : bool, optional
False to have matrices in dense format, True to have sparse matrices.
Default: False.
mask : array, optional
Array with 0 and 1 (0 indicates a place for a zero probability), shape
can be ``(S, S)`` or ``(A, S, S)``. Default: random.
Returns
-------
out : tuple
``out[0]`` contains the transition probability matrix P and ``out[1]``
contains the reward matrix R. If ``is_sparse=False`` then P is a numpy
array with a shape of ``(A, S, S)`` and R is a numpy array with a shape
of ``(S, A)``. If ``is_sparse=True`` then P and R are tuples of length
``A``, where each ``P[a]`` is a scipy sparse CSR format matrix of shape
``(S, S)`` and each ``R[a]`` is a scipy sparse csr format matrix of
shape ``(S, 1)``.
Examples
--------
>>> import numpy, mdptoolbox.example
>>> numpy.random.seed(0) # Needed to get the output below
>>> P, R = mdptoolbox.example.rand(4, 3)
>>> P
array([[[ 0.21977283, 0.14889403, 0.30343592, 0.32789723],
[ 1. , 0. , 0. , 0. ],
[ 0. , 0.43718772, 0.54480359, 0.01800869],
[ 0.39766289, 0.39997167, 0.12547318, 0.07689227]],
<BLANKLINE>
[[ 1. , 0. , 0. , 0. ],
[ 0.32261337, 0.15483812, 0.32271303, 0.19983549],
[ 0.33816885, 0.2766999 , 0.12960299, 0.25552826],
[ 0.41299411, 0. , 0.58369957, 0.00330633]],
<BLANKLINE>
[[ 0.32343037, 0.15178596, 0.28733094, 0.23745272],
[ 0.36348538, 0.24483321, 0.16114188, 0.23053953],
[ 1. , 0. , 0. , 0. ],
[ 0. , 0. , 1. , 0. ]]])
>>> R
array([[[-0.23311696, 0.58345008, 0.05778984, 0.13608912],
[-0.07704128, 0. , -0. , 0. ],
[ 0. , 0.22419145, 0.23386799, 0.88749616],
[-0.3691433 , -0.27257846, 0.14039354, -0.12279697]],
<BLANKLINE>
[[-0.77924972, 0. , -0. , -0. ],
[ 0.47852716, -0.92162442, -0.43438607, -0.75960688],
[-0.81211898, 0.15189299, 0.8585924 , -0.3628621 ],
[ 0.35563307, -0. , 0.47038804, 0.92437709]],
<BLANKLINE>
[[-0.4051261 , 0.62759564, -0.20698852, 0.76220639],
[-0.9616136 , -0.39685037, 0.32034707, -0.41984479],
[-0.13716313, 0. , -0. , -0. ],
[ 0. , -0. , 0.55810204, 0. ]]])
>>> numpy.random.seed(0) # Needed to get the output below
>>> Psp, Rsp = mdptoolbox.example.rand(100, 5, is_sparse=True)
>>> len(Psp), len(Rsp)
(5, 5)
>>> Psp[0]
<100x100 sparse matrix of type '<... 'numpy.float64'>'
with 3296 stored elements in Compressed Sparse Row format>
>>> Rsp[0]
<100x100 sparse matrix of type '<... 'numpy.float64'>'
with 3296 stored elements in Compressed Sparse Row format>
>>> # The number of non-zero elements (nnz) in P and R are equal
>>> Psp[1].nnz == Rsp[1].nnz
True | [
"Generate",
"a",
"random",
"Markov",
"Decision",
"Process",
"."
] | 7c96789cc80e280437005c12065cf70266c11636 | https://github.com/sawcordwell/pymdptoolbox/blob/7c96789cc80e280437005c12065cf70266c11636/src/mdptoolbox/example.py#L268-L362 | train | 198,579 |
devopshq/artifactory | artifactory.py | get_base_url | def get_base_url(config, url):
"""
Look through config and try to find best matching base for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the base for
"""
if not config:
return None
# First, try to search for the best match
for item in config:
if url.startswith(item):
return item
# Then search for indirect match
for item in config:
if without_http_prefix(url).startswith(without_http_prefix(item)):
return item | python | def get_base_url(config, url):
"""
Look through config and try to find best matching base for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the base for
"""
if not config:
return None
# First, try to search for the best match
for item in config:
if url.startswith(item):
return item
# Then search for indirect match
for item in config:
if without_http_prefix(url).startswith(without_http_prefix(item)):
return item | [
"def",
"get_base_url",
"(",
"config",
",",
"url",
")",
":",
"if",
"not",
"config",
":",
"return",
"None",
"# First, try to search for the best match",
"for",
"item",
"in",
"config",
":",
"if",
"url",
".",
"startswith",
"(",
"item",
")",
":",
"return",
"item"... | Look through config and try to find best matching base for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the base for | [
"Look",
"through",
"config",
"and",
"try",
"to",
"find",
"best",
"matching",
"base",
"for",
"url"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L129-L147 | train | 198,580 |
devopshq/artifactory | artifactory.py | get_config_entry | def get_config_entry(config, url):
"""
Look through config and try to find best matching entry for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the config for
"""
if not config:
return None
# First, try to search for the best match
if url in config:
return config[url]
# Then search for indirect match
for item in config:
if without_http_prefix(item) == without_http_prefix(url):
return config[item] | python | def get_config_entry(config, url):
"""
Look through config and try to find best matching entry for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the config for
"""
if not config:
return None
# First, try to search for the best match
if url in config:
return config[url]
# Then search for indirect match
for item in config:
if without_http_prefix(item) == without_http_prefix(url):
return config[item] | [
"def",
"get_config_entry",
"(",
"config",
",",
"url",
")",
":",
"if",
"not",
"config",
":",
"return",
"None",
"# First, try to search for the best match",
"if",
"url",
"in",
"config",
":",
"return",
"config",
"[",
"url",
"]",
"# Then search for indirect match",
"f... | Look through config and try to find best matching entry for 'url'
config - result of read_config() or read_global_config()
url - artifactory url to search the config for | [
"Look",
"through",
"config",
"and",
"try",
"to",
"find",
"best",
"matching",
"entry",
"for",
"url"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L150-L167 | train | 198,581 |
devopshq/artifactory | artifactory.py | sha1sum | def sha1sum(filename):
"""
Calculates sha1 hash of a file
"""
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128 * sha1.block_size), b''):
sha1.update(chunk)
return sha1.hexdigest() | python | def sha1sum(filename):
"""
Calculates sha1 hash of a file
"""
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(128 * sha1.block_size), b''):
sha1.update(chunk)
return sha1.hexdigest() | [
"def",
"sha1sum",
"(",
"filename",
")",
":",
"sha1",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"f",
".",
"read",
"(",
"128",
"*",
... | Calculates sha1 hash of a file | [
"Calculates",
"sha1",
"hash",
"of",
"a",
"file"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L201-L209 | train | 198,582 |
devopshq/artifactory | artifactory.py | walk | def walk(pathobj, topdown=True):
"""
os.walk like function to traverse the URI like a file system.
The only difference is that this function takes and returns Path objects
in places where original implementation will return strings
"""
dirs, nondirs = [], []
for child in pathobj:
relpath = str(child.relative_to(str(pathobj)))
if relpath.startswith('/'):
relpath = relpath[1:]
if relpath.endswith('/'):
relpath = relpath[:-1]
if child.is_dir():
dirs.append(relpath)
else:
nondirs.append(relpath)
if topdown:
yield pathobj, dirs, nondirs
for dir in dirs:
for result in walk(pathobj / dir):
yield result
if not topdown:
yield pathobj, dirs, nondirs | python | def walk(pathobj, topdown=True):
"""
os.walk like function to traverse the URI like a file system.
The only difference is that this function takes and returns Path objects
in places where original implementation will return strings
"""
dirs, nondirs = [], []
for child in pathobj:
relpath = str(child.relative_to(str(pathobj)))
if relpath.startswith('/'):
relpath = relpath[1:]
if relpath.endswith('/'):
relpath = relpath[:-1]
if child.is_dir():
dirs.append(relpath)
else:
nondirs.append(relpath)
if topdown:
yield pathobj, dirs, nondirs
for dir in dirs:
for result in walk(pathobj / dir):
yield result
if not topdown:
yield pathobj, dirs, nondirs | [
"def",
"walk",
"(",
"pathobj",
",",
"topdown",
"=",
"True",
")",
":",
"dirs",
",",
"nondirs",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"child",
"in",
"pathobj",
":",
"relpath",
"=",
"str",
"(",
"child",
".",
"relative_to",
"(",
"str",
"(",
"pathobj",
... | os.walk like function to traverse the URI like a file system.
The only difference is that this function takes and returns Path objects
in places where original implementation will return strings | [
"os",
".",
"walk",
"like",
"function",
"to",
"traverse",
"the",
"URI",
"like",
"a",
"file",
"system",
"."
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1427-L1451 | train | 198,583 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.rest_del | def rest_del(self, url, params=None, session=None, verify=True, cert=None):
"""
Perform a DELETE request to url with requests.session
"""
res = session.delete(url, params=params, verify=verify, cert=cert)
return res.text, res.status_code | python | def rest_del(self, url, params=None, session=None, verify=True, cert=None):
"""
Perform a DELETE request to url with requests.session
"""
res = session.delete(url, params=params, verify=verify, cert=cert)
return res.text, res.status_code | [
"def",
"rest_del",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"session",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"session",
".",
"delete",
"(",
"url",
",",
"params",
"=",
"params",
"... | Perform a DELETE request to url with requests.session | [
"Perform",
"a",
"DELETE",
"request",
"to",
"url",
"with",
"requests",
".",
"session"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L478-L483 | train | 198,584 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.rest_put_stream | def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):
"""
Perform a chunked PUT request to url with requests.session
This is specifically to upload files.
"""
res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)
return res.text, res.status_code | python | def rest_put_stream(self, url, stream, headers=None, session=None, verify=True, cert=None):
"""
Perform a chunked PUT request to url with requests.session
This is specifically to upload files.
"""
res = session.put(url, headers=headers, data=stream, verify=verify, cert=cert)
return res.text, res.status_code | [
"def",
"rest_put_stream",
"(",
"self",
",",
"url",
",",
"stream",
",",
"headers",
"=",
"None",
",",
"session",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"session",
".",
"put",
"(",
"url",
",",
"headers... | Perform a chunked PUT request to url with requests.session
This is specifically to upload files. | [
"Perform",
"a",
"chunked",
"PUT",
"request",
"to",
"url",
"with",
"requests",
".",
"session",
"This",
"is",
"specifically",
"to",
"upload",
"files",
"."
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L485-L491 | train | 198,585 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.rest_get_stream | def rest_get_stream(self, url, session=None, verify=True, cert=None):
"""
Perform a chunked GET request to url with requests.session
This is specifically to download files.
"""
res = session.get(url, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code | python | def rest_get_stream(self, url, session=None, verify=True, cert=None):
"""
Perform a chunked GET request to url with requests.session
This is specifically to download files.
"""
res = session.get(url, stream=True, verify=verify, cert=cert)
return res.raw, res.status_code | [
"def",
"rest_get_stream",
"(",
"self",
",",
"url",
",",
"session",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"session",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"True",
",",
"verify",
"=",
"verify",... | Perform a chunked GET request to url with requests.session
This is specifically to download files. | [
"Perform",
"a",
"chunked",
"GET",
"request",
"to",
"url",
"with",
"requests",
".",
"session",
"This",
"is",
"specifically",
"to",
"download",
"files",
"."
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L493-L499 | train | 198,586 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.is_dir | def is_dir(self, pathobj):
"""
Returns True if given path is a directory
"""
try:
stat = self.stat(pathobj)
return stat.is_dir
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
return False | python | def is_dir(self, pathobj):
"""
Returns True if given path is a directory
"""
try:
stat = self.stat(pathobj)
return stat.is_dir
except OSError as exc:
if exc.errno != errno.ENOENT:
raise
return False | [
"def",
"is_dir",
"(",
"self",
",",
"pathobj",
")",
":",
"try",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"return",
"stat",
".",
"is_dir",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"!=",
"errno",
".",
"ENOEN... | Returns True if given path is a directory | [
"Returns",
"True",
"if",
"given",
"path",
"is",
"a",
"directory"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L560-L571 | train | 198,587 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.listdir | def listdir(self, pathobj):
"""
Returns a list of immediate sub-directories and files in path
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: %s" % str(pathobj))
return stat.children | python | def listdir(self, pathobj):
"""
Returns a list of immediate sub-directories and files in path
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: %s" % str(pathobj))
return stat.children | [
"def",
"listdir",
"(",
"self",
",",
"pathobj",
")",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"if",
"not",
"stat",
".",
"is_dir",
":",
"raise",
"OSError",
"(",
"20",
",",
"\"Not a directory: %s\"",
"%",
"str",
"(",
"pathobj",
")",
"... | Returns a list of immediate sub-directories and files in path | [
"Returns",
"a",
"list",
"of",
"immediate",
"sub",
"-",
"directories",
"and",
"files",
"in",
"path"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L586-L595 | train | 198,588 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.mkdir | def mkdir(self, pathobj, _):
"""
Creates remote directory
Note that this operation is not recursive
"""
if not pathobj.drive or not pathobj.root:
raise RuntimeError("Full path required: '%s'" % str(pathobj))
if pathobj.exists():
raise OSError(17, "File exists: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_put(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if not code == 201:
raise RuntimeError("%s %d" % (text, code)) | python | def mkdir(self, pathobj, _):
"""
Creates remote directory
Note that this operation is not recursive
"""
if not pathobj.drive or not pathobj.root:
raise RuntimeError("Full path required: '%s'" % str(pathobj))
if pathobj.exists():
raise OSError(17, "File exists: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_put(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if not code == 201:
raise RuntimeError("%s %d" % (text, code)) | [
"def",
"mkdir",
"(",
"self",
",",
"pathobj",
",",
"_",
")",
":",
"if",
"not",
"pathobj",
".",
"drive",
"or",
"not",
"pathobj",
".",
"root",
":",
"raise",
"RuntimeError",
"(",
"\"Full path required: '%s'\"",
"%",
"str",
"(",
"pathobj",
")",
")",
"if",
"... | Creates remote directory
Note that this operation is not recursive | [
"Creates",
"remote",
"directory",
"Note",
"that",
"this",
"operation",
"is",
"not",
"recursive"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L597-L612 | train | 198,589 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.rmdir | def rmdir(self, pathobj):
"""
Removes a directory
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_del(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if code not in [200, 202, 204]:
raise RuntimeError("Failed to delete directory: '%s'" % text) | python | def rmdir(self, pathobj):
"""
Removes a directory
"""
stat = self.stat(pathobj)
if not stat.is_dir:
raise OSError(20, "Not a directory: '%s'" % str(pathobj))
url = str(pathobj) + '/'
text, code = self.rest_del(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if code not in [200, 202, 204]:
raise RuntimeError("Failed to delete directory: '%s'" % text) | [
"def",
"rmdir",
"(",
"self",
",",
"pathobj",
")",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"if",
"not",
"stat",
".",
"is_dir",
":",
"raise",
"OSError",
"(",
"20",
",",
"\"Not a directory: '%s'\"",
"%",
"str",
"(",
"pathobj",
")",
"... | Removes a directory | [
"Removes",
"a",
"directory"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L614-L628 | train | 198,590 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.touch | def touch(self, pathobj):
"""
Create an empty file
"""
if not pathobj.drive or not pathobj.root:
raise RuntimeError('Full path required')
if pathobj.exists():
return
url = str(pathobj)
text, code = self.rest_put(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if not code == 201:
raise RuntimeError("%s %d" % (text, code)) | python | def touch(self, pathobj):
"""
Create an empty file
"""
if not pathobj.drive or not pathobj.root:
raise RuntimeError('Full path required')
if pathobj.exists():
return
url = str(pathobj)
text, code = self.rest_put(url, session=pathobj.session, verify=pathobj.verify, cert=pathobj.cert)
if not code == 201:
raise RuntimeError("%s %d" % (text, code)) | [
"def",
"touch",
"(",
"self",
",",
"pathobj",
")",
":",
"if",
"not",
"pathobj",
".",
"drive",
"or",
"not",
"pathobj",
".",
"root",
":",
"raise",
"RuntimeError",
"(",
"'Full path required'",
")",
"if",
"pathobj",
".",
"exists",
"(",
")",
":",
"return",
"... | Create an empty file | [
"Create",
"an",
"empty",
"file"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L646-L660 | train | 198,591 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.owner | def owner(self, pathobj):
"""
Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.modified_by
else:
return 'nobody' | python | def owner(self, pathobj):
"""
Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.modified_by
else:
return 'nobody' | [
"def",
"owner",
"(",
"self",
",",
"pathobj",
")",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"if",
"not",
"stat",
".",
"is_dir",
":",
"return",
"stat",
".",
"modified_by",
"else",
":",
"return",
"'nobody'"
] | Returns file owner
This makes little sense for Artifactory, but to be consistent
with pathlib, we return modified_by instead, if available | [
"Returns",
"file",
"owner",
"This",
"makes",
"little",
"sense",
"for",
"Artifactory",
"but",
"to",
"be",
"consistent",
"with",
"pathlib",
"we",
"return",
"modified_by",
"instead",
"if",
"available"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L662-L673 | train | 198,592 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.creator | def creator(self, pathobj):
"""
Returns file creator
This makes little sense for Artifactory, but to be consistent
with pathlib, we return created_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.created_by
else:
return 'nobody' | python | def creator(self, pathobj):
"""
Returns file creator
This makes little sense for Artifactory, but to be consistent
with pathlib, we return created_by instead, if available
"""
stat = self.stat(pathobj)
if not stat.is_dir:
return stat.created_by
else:
return 'nobody' | [
"def",
"creator",
"(",
"self",
",",
"pathobj",
")",
":",
"stat",
"=",
"self",
".",
"stat",
"(",
"pathobj",
")",
"if",
"not",
"stat",
".",
"is_dir",
":",
"return",
"stat",
".",
"created_by",
"else",
":",
"return",
"'nobody'"
] | Returns file creator
This makes little sense for Artifactory, but to be consistent
with pathlib, we return created_by instead, if available | [
"Returns",
"file",
"creator",
"This",
"makes",
"little",
"sense",
"for",
"Artifactory",
"but",
"to",
"be",
"consistent",
"with",
"pathlib",
"we",
"return",
"created_by",
"instead",
"if",
"available"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L675-L686 | train | 198,593 |
devopshq/artifactory | artifactory.py | _ArtifactoryAccessor.copy | def copy(self, src, dst, suppress_layouts=False):
"""
Copy artifact from src to dst
"""
url = '/'.join([src.drive,
'api/copy',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/'),
'suppressLayouts': int(suppress_layouts)}
text, code = self.rest_post(url,
params=params,
session=src.session,
verify=src.verify,
cert=src.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text) | python | def copy(self, src, dst, suppress_layouts=False):
"""
Copy artifact from src to dst
"""
url = '/'.join([src.drive,
'api/copy',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/'),
'suppressLayouts': int(suppress_layouts)}
text, code = self.rest_post(url,
params=params,
session=src.session,
verify=src.verify,
cert=src.cert)
if code not in [200, 201]:
raise RuntimeError("%s" % text) | [
"def",
"copy",
"(",
"self",
",",
"src",
",",
"dst",
",",
"suppress_layouts",
"=",
"False",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"src",
".",
"drive",
",",
"'api/copy'",
",",
"str",
"(",
"src",
".",
"relative_to",
"(",
"src",
".",
"d... | Copy artifact from src to dst | [
"Copy",
"artifact",
"from",
"src",
"to",
"dst"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L733-L751 | train | 198,594 |
devopshq/artifactory | artifactory.py | ArtifactoryPath.touch | def touch(self, mode=0o666, exist_ok=True):
"""
Create a file if it doesn't exist.
Mode is ignored by Artifactory.
"""
if self.exists() and not exist_ok:
raise OSError(17, "File exists", str(self))
self._accessor.touch(self) | python | def touch(self, mode=0o666, exist_ok=True):
"""
Create a file if it doesn't exist.
Mode is ignored by Artifactory.
"""
if self.exists() and not exist_ok:
raise OSError(17, "File exists", str(self))
self._accessor.touch(self) | [
"def",
"touch",
"(",
"self",
",",
"mode",
"=",
"0o666",
",",
"exist_ok",
"=",
"True",
")",
":",
"if",
"self",
".",
"exists",
"(",
")",
"and",
"not",
"exist_ok",
":",
"raise",
"OSError",
"(",
"17",
",",
"\"File exists\"",
",",
"str",
"(",
"self",
")... | Create a file if it doesn't exist.
Mode is ignored by Artifactory. | [
"Create",
"a",
"file",
"if",
"it",
"doesn",
"t",
"exist",
".",
"Mode",
"is",
"ignored",
"by",
"Artifactory",
"."
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1144-L1152 | train | 198,595 |
devopshq/artifactory | artifactory.py | ArtifactoryPath.deploy | def deploy(self, fobj, md5=None, sha1=None, parameters={}):
"""
Upload the given file object to this path
"""
return self._accessor.deploy(self, fobj, md5, sha1, parameters) | python | def deploy(self, fobj, md5=None, sha1=None, parameters={}):
"""
Upload the given file object to this path
"""
return self._accessor.deploy(self, fobj, md5, sha1, parameters) | [
"def",
"deploy",
"(",
"self",
",",
"fobj",
",",
"md5",
"=",
"None",
",",
"sha1",
"=",
"None",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"return",
"self",
".",
"_accessor",
".",
"deploy",
"(",
"self",
",",
"fobj",
",",
"md5",
",",
"sha1",
",",
... | Upload the given file object to this path | [
"Upload",
"the",
"given",
"file",
"object",
"to",
"this",
"path"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1175-L1179 | train | 198,596 |
devopshq/artifactory | artifactory.py | ArtifactoryPath.deploy_file | def deploy_file(self,
file_name,
calc_md5=True,
calc_sha1=True,
parameters={}):
"""
Upload the given file to this path
"""
if calc_md5:
md5 = md5sum(file_name)
if calc_sha1:
sha1 = sha1sum(file_name)
target = self
if self.is_dir():
target = self / pathlib.Path(file_name).name
with open(file_name, 'rb') as fobj:
target.deploy(fobj, md5, sha1, parameters) | python | def deploy_file(self,
file_name,
calc_md5=True,
calc_sha1=True,
parameters={}):
"""
Upload the given file to this path
"""
if calc_md5:
md5 = md5sum(file_name)
if calc_sha1:
sha1 = sha1sum(file_name)
target = self
if self.is_dir():
target = self / pathlib.Path(file_name).name
with open(file_name, 'rb') as fobj:
target.deploy(fobj, md5, sha1, parameters) | [
"def",
"deploy_file",
"(",
"self",
",",
"file_name",
",",
"calc_md5",
"=",
"True",
",",
"calc_sha1",
"=",
"True",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"if",
"calc_md5",
":",
"md5",
"=",
"md5sum",
"(",
"file_name",
")",
"if",
"calc_sha1",
":",
... | Upload the given file to this path | [
"Upload",
"the",
"given",
"file",
"to",
"this",
"path"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1181-L1200 | train | 198,597 |
devopshq/artifactory | artifactory.py | ArtifactoryPath.deploy_deb | def deploy_deb(self,
file_name,
distribution,
component,
architecture,
parameters={}):
"""
Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file that will be deployed
distribution -- debian distribution (e.g. 'wheezy')
component -- repository component (e.g. 'main')
architecture -- package architecture (e.g. 'i386')
parameters -- attach any additional metadata
"""
params = {
'deb.distribution': distribution,
'deb.component': component,
'deb.architecture': architecture
}
params.update(parameters)
self.deploy_file(file_name, parameters=params) | python | def deploy_deb(self,
file_name,
distribution,
component,
architecture,
parameters={}):
"""
Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file that will be deployed
distribution -- debian distribution (e.g. 'wheezy')
component -- repository component (e.g. 'main')
architecture -- package architecture (e.g. 'i386')
parameters -- attach any additional metadata
"""
params = {
'deb.distribution': distribution,
'deb.component': component,
'deb.architecture': architecture
}
params.update(parameters)
self.deploy_file(file_name, parameters=params) | [
"def",
"deploy_deb",
"(",
"self",
",",
"file_name",
",",
"distribution",
",",
"component",
",",
"architecture",
",",
"parameters",
"=",
"{",
"}",
")",
":",
"params",
"=",
"{",
"'deb.distribution'",
":",
"distribution",
",",
"'deb.component'",
":",
"component",... | Convenience method to deploy .deb packages
Keyword arguments:
file_name -- full path to local file that will be deployed
distribution -- debian distribution (e.g. 'wheezy')
component -- repository component (e.g. 'main')
architecture -- package architecture (e.g. 'i386')
parameters -- attach any additional metadata | [
"Convenience",
"method",
"to",
"deploy",
".",
"deb",
"packages"
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1202-L1225 | train | 198,598 |
devopshq/artifactory | artifactory.py | ArtifactoryPath.move | def move(self, dst):
"""
Move artifact from this path to destinaiton.
"""
if self.drive != dst.drive:
raise NotImplementedError(
"Moving between instances is not implemented yet")
self._accessor.move(self, dst) | python | def move(self, dst):
"""
Move artifact from this path to destinaiton.
"""
if self.drive != dst.drive:
raise NotImplementedError(
"Moving between instances is not implemented yet")
self._accessor.move(self, dst) | [
"def",
"move",
"(",
"self",
",",
"dst",
")",
":",
"if",
"self",
".",
"drive",
"!=",
"dst",
".",
"drive",
":",
"raise",
"NotImplementedError",
"(",
"\"Moving between instances is not implemented yet\"",
")",
"self",
".",
"_accessor",
".",
"move",
"(",
"self",
... | Move artifact from this path to destinaiton. | [
"Move",
"artifact",
"from",
"this",
"path",
"to",
"destinaiton",
"."
] | b9ec08cd72527d7d43159fe45c3a98a0b0838534 | https://github.com/devopshq/artifactory/blob/b9ec08cd72527d7d43159fe45c3a98a0b0838534/artifactory.py#L1280-L1288 | train | 198,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.