text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(mnemonic, oprnd1, oprnd2, oprnd3):
"""Return the specified instruction. """ |
ins = ReilInstruction()
ins.mnemonic = mnemonic
ins.operands = [oprnd1, oprnd2, oprnd3]
return ins |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_instruction(self, reil_instruction):
"""Add an instruction for analysis. """ |
for expr in self._translator.translate(reil_instruction):
self._solver.add(expr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_lock(self):
""" Remove acquired lock. """ |
key = '%s_lock' % self.scheduler_key
if self._lock_acquired:
self.connection.delete(key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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))}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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[0,:,:] = | . . 0 . | | . . . | | . . 1-p | | . . . | P[1,:,:] = | . . . | | . . . | | . . . | 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 -------- 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. ]]]) array([[ 0., 0.], [ 0., 1.], [ 4., 2.]]) 2 with 6 stored elements in Compressed Sparse Row format> with 3 stored elements in Compressed Sparse Row format> array([[ 0., 0.], [ 0., 1.], [ 4., 2.]]) True 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 -------- 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. ]]]) 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. ]]]) (5, 5) with 3296 stored elements in Compressed Sparse Row format> with 3296 stored elements in Compressed Sparse Row format> 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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' |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def del_properties(self, properties, recursive=None):
""" Delete properties listed in properties properties - iterable contains the property names to delete. If it is an str it will be casted to tuple. recursive - on folders property attachment is recursive by default. It is possible to force recursive behavior. """ |
return self._accessor.del_properties(self, properties, recursive) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_aql_text(*args):
""" Create AQL querty from string or list or dict arguments """ |
aql_query_text = ""
for arg in args:
if isinstance(arg, dict):
arg = "({})".format(json.dumps(arg))
elif isinstance(arg, list):
arg = "({})".format(json.dumps(arg)).replace("[", "").replace("]", "")
aql_query_text += arg
return aql_query_text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_watch(self, path, superficial=False):
"""Remove our tracking information and call inotify to stop watching the given path. When a directory is removed, we'll just have to remove our tracking since inotify already cleans-up the watch. """ |
wd = self.__watches.get(path)
if wd is None:
return
_LOGGER.debug("Removing watch for watch-handle (%d): [%s]",
wd, path)
del self.__watches[path]
self.remove_watch_with_id(wd) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _handle_inotify_event(self, wd):
"""Handle a series of events coming-in from inotify.""" |
b = os.read(wd, 1024)
if not b:
return
self.__buffer += b
while 1:
length = len(self.__buffer)
if length < _STRUCT_HEADER_LENGTH:
_LOGGER.debug("Not enough bytes for a header.")
return
# We have, at least, a whole-header in the buffer.
peek_slice = self.__buffer[:_STRUCT_HEADER_LENGTH]
header_raw = struct.unpack(
_HEADER_STRUCT_FORMAT,
peek_slice)
header = _INOTIFY_EVENT(*header_raw)
type_names = self._get_event_names(header.mask)
_LOGGER.debug("Events received in stream: {}".format(type_names))
event_length = (_STRUCT_HEADER_LENGTH + header.len)
if length < event_length:
return
filename = self.__buffer[_STRUCT_HEADER_LENGTH:event_length]
# Our filename is 16-byte aligned and right-padded with NULs.
filename_bytes = filename.rstrip(b'\0')
self.__buffer = self.__buffer[event_length:]
path = self.__watches_r.get(header.wd)
if path is not None:
filename_unicode = filename_bytes.decode('utf8')
yield (header, type_names, path, filename_unicode)
buffer_length = len(self.__buffer)
if buffer_length < _STRUCT_HEADER_LENGTH:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def event_gen( self, timeout_s=None, yield_nones=True, filter_predicate=None, terminal_events=_DEFAULT_TERMINAL_EVENTS):
"""Yield one event after another. If `timeout_s` is provided, we'll break when no event is received for that many seconds. """ |
# We will either return due to the optional filter or because of a
# timeout. The former will always set this. The latter will never set
# this.
self.__last_success_return = None
last_hit_s = time.time()
while True:
block_duration_s = self.__get_block_duration()
# Poll, but manage signal-related errors.
try:
events = self.__epoll.poll(block_duration_s)
except IOError as e:
if e.errno != EINTR:
raise
if timeout_s is not None:
time_since_event_s = time.time() - last_hit_s
if time_since_event_s > timeout_s:
break
continue
# Process events.
for fd, event_type in events:
# (fd) looks to always match the inotify FD.
names = self._get_event_names(event_type)
_LOGGER.debug("Events received from epoll: {}".format(names))
for (header, type_names, path, filename) \
in self._handle_inotify_event(fd):
last_hit_s = time.time()
e = (header, type_names, path, filename)
for type_name in type_names:
if filter_predicate is not None and \
filter_predicate(type_name, e) is False:
self.__last_success_return = (type_name, e)
return
elif type_name in terminal_events:
raise TerminalEventException(type_name, e)
yield e
if timeout_s is not None:
time_since_event_s = time.time() - last_hit_s
if time_since_event_s > timeout_s:
break
if yield_nones is True:
yield None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_project(from_client, to_client, from_project, to_project, copy_machine_group=False):
""" copy project, logstore, machine group and logtail config to target project, will create the target project if it doesn't exist :type from_client: LogClient :param from_client: logclient instance :type to_client: LogClient :param to_client: logclient instance :type from_project: string :param from_project: project name :type to_project: string :param to_project: project name :type copy_machine_group: bool :param copy_machine_group: if copy machine group resources, False by default. :return: """ |
# copy project
ret = from_client.get_project(from_project)
try:
ret = to_client.create_project(to_project, ret.get_description())
except LogException as ex:
if ex.get_error_code() == 'ProjectAlreadyExist':
# don't create the project as it already exists
pass
else:
raise
default_fetch_size = 100
# list logstore and copy them
offset, size = 0, default_fetch_size
while True:
ret = from_client.list_logstore(from_project, offset=offset, size=size)
count = ret.get_logstores_count()
total = ret.get_logstores_total()
for logstore_name in ret.get_logstores():
# copy logstore
ret = from_client.get_logstore(from_project, logstore_name)
res_shard = from_client.list_shards(from_project, logstore_name)
expected_rwshard_count = len([shard for shard in res_shard.shards if shard['status'].lower() == 'readwrite'])
ret = to_client.create_logstore(to_project, logstore_name, ret.get_ttl(),
min(expected_rwshard_count, MAX_INIT_SHARD_COUNT),
enable_tracking=ret.get_enable_tracking(),
append_meta=ret.append_meta,
auto_split=ret.auto_split,
max_split_shard=ret.max_split_shard,
preserve_storage=ret.preserve_storage
)
# copy index
try:
ret = from_client.get_index_config(from_project, logstore_name)
ret = to_client.create_index(to_project, logstore_name, ret.get_index_config())
except LogException as ex:
if ex.get_error_code() == 'IndexConfigNotExist':
pass
else:
raise
offset += count
if count < size or offset >= total:
break
# list logtail config and copy them
offset, size = 0, default_fetch_size
while True:
ret = from_client.list_logtail_config(from_project, offset=offset, size=size)
count = ret.get_configs_count()
total = ret.get_configs_total()
for config_name in ret.get_configs():
ret = from_client.get_logtail_config(from_project, config_name)
ret = to_client.create_logtail_config(to_project, ret.logtail_config)
offset += count
if count < size or offset >= total:
break
# list machine group and copy them
offset, size = 0, default_fetch_size
while copy_machine_group:
ret = from_client.list_machine_group(from_project, offset=offset, size=size)
count = ret.get_machine_group_count()
total = ret.get_machine_group_total()
for group_name in ret.get_machine_group():
ret = from_client.get_machine_group(from_project, group_name)
ret = to_client.create_machine_group(to_project, ret.get_machine_group())
# list all applied config and copy the relationship
ret = from_client.get_machine_group_applied_configs(from_project, group_name)
for config_name in ret.get_configs():
to_client.apply_config_to_machine_group(to_project, config_name, group_name)
offset += count
if count < size or offset >= total:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_logstore(from_client, from_project, from_logstore, to_logstore, to_project=None, to_client=None):
""" copy logstore, index, logtail config to target logstore, machine group are not included yet. the target logstore will be crated if not existing :type from_client: LogClient :param from_client: logclient instance :type from_project: string :param from_project: project name :type from_logstore: string :param from_logstore: logstore name :type to_logstore: string :param to_logstore: target logstore name :type to_project: string :param to_project: project name, copy to same project if not being specified, will try to create it if not being specified :type to_client: LogClient :param to_client: logclient instance, use it to operate on the "to_project" if being specified :return: """ |
# check client
if to_project is not None:
# copy to a different project in different client
to_client = to_client or from_client
# check if target project exists or not
ret = from_client.get_project(from_project)
try:
ret = to_client.create_project(to_project, ret.get_description())
except LogException as ex:
if ex.get_error_code() == 'ProjectAlreadyExist':
# don't create the project as it already exists
pass
else:
raise
to_project = to_project or from_project
to_client = to_client or from_client
# return if logstore are the same one
if from_client is to_client and from_project == to_project and from_logstore == to_logstore:
return
# copy logstore
ret = from_client.get_logstore(from_project, from_logstore)
res_shard = from_client.list_shards(from_project, from_logstore)
expected_rwshard_count = len([shard for shard in res_shard.shards if shard['status'].lower() == 'readwrite'])
try:
ret = to_client.create_logstore(to_project, to_logstore,
ttl=ret.get_ttl(),
shard_count=min(expected_rwshard_count, MAX_INIT_SHARD_COUNT),
enable_tracking=ret.get_enable_tracking(),
append_meta=ret.append_meta,
auto_split=ret.auto_split,
max_split_shard=ret.max_split_shard,
preserve_storage=ret.preserve_storage)
except LogException as ex:
if ex.get_error_code() == 'LogStoreAlreadyExist':
# update logstore's settings
ret = to_client.update_logstore(to_project, to_logstore,
ttl=ret.get_ttl(),
enable_tracking=ret.get_enable_tracking(),
append_meta=ret.append_meta,
auto_split=ret.auto_split,
max_split_shard=ret.max_split_shard,
preserve_storage=ret.preserve_storage
)
# arrange shard to expected count
res = arrange_shard(to_client, to_project, to_logstore, min(expected_rwshard_count, MAX_INIT_SHARD_COUNT))
else:
raise
# copy index
try:
ret = from_client.get_index_config(from_project, from_logstore)
ret = to_client.create_index(to_project, to_logstore, ret.get_index_config())
except LogException as ex:
if ex.get_error_code() == 'IndexConfigNotExist':
# source has no index
pass
elif ex.get_error_code() == 'IndexAlreadyExist':
# target already has index, overwrite it
ret = to_client.update_index(to_project, to_logstore, ret.get_index_config())
pass
else:
raise
# list logtail config linked to the logstore and copy them
default_fetch_size = 100
offset, size = 0, default_fetch_size
while True:
ret = from_client.list_logtail_config(from_project, offset=offset, size=size)
count = ret.get_configs_count()
total = ret.get_configs_total()
for config_name in ret.get_configs():
ret = from_client.get_logtail_config(from_project, config_name)
config = ret.logtail_config
if config.logstore_name != from_logstore:
continue
config.config_name = to_logstore + '_' + config_name
config.logstore_name = to_logstore
ret = to_client.create_logtail_config(to_project, config)
offset += count
if count < size or offset >= total:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _split_one_shard_to_multiple(client, project, logstore, shard_info, count, current_shard_count):
"""return new_rw_shards_list, increased_shard_count """ |
distance = shard_info['length'] // count
if distance <= 0 or count <= 1:
return [shard_info['info']], 0
rw_shards, increased_shard_count = {shard_info['id']: shard_info['info']}, 0
for x in range(1, count):
new_hash = shard_info['start'] + distance * x
new_hash = hex(new_hash)[2:].strip('lL')
new_hash = '0' * (TOTAL_HASH_LENGTH - len(new_hash)) + new_hash
try:
if x == 1:
res = client.split_shard(project, logstore, shard_info['id'], new_hash)
else:
res = client.split_shard(project, logstore, current_shard_count - 1, new_hash)
# new rw_shards
for shard in res.shards:
if shard['status'] == 'readonly':
del rw_shards[shard['shardID']]
else:
rw_shards[shard['shardID']] = shard
current_shard_count += res.count - 1
increased_shard_count += res.count - 1
logger.info("split shard: project={0}, logstore={1}, shard_info={2}, count={3}, current_shard_count={4}".format(project, logstore, shard_info, count, current_shard_count))
except Exception as ex:
print(ex)
print(x, project, logstore, shard_info, count, current_shard_count)
raise
return rw_shards.values(), increased_shard_count |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_host_ip(logHost):
""" If it is not match your local ip, you should fill the PutLogsRequest
parameter source by yourself.
""" |
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((logHost, 80))
ip = s.getsockname()[0]
return ip
except Exception:
return '127.0.0.1'
finally:
if s:
s.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_common_reg_log_config(json_value):
"""Generate common logtail config from loaded json value :param json_value: :return: """ |
input_detail = copy.deepcopy(json_value['inputDetail'])
output_detail = json_value['outputDetail']
logSample = json_value.get('logSample', '')
config_name = json_value['configName']
logstore_name = output_detail['logstoreName']
endpoint = output_detail.get('endpoint', '')
log_path = input_detail['logPath']
file_pattern = input_detail['filePattern']
time_format = input_detail['timeFormat']
log_begin_regex = input_detail.get('logBeginRegex', '')
log_parse_regex = input_detail.get('regex', '')
reg_keys = input_detail['key']
topic_format = input_detail['topicFormat']
filter_keys = input_detail['filterKey']
filter_keys_reg = input_detail['filterRegex']
log_type = input_detail.get('logType')
for item in ('logPath', 'filePattern', 'timeFormat', 'logBeginRegex', 'regex', 'key',
'topicFormat', 'filterKey', 'filterRegex', 'logType'):
if item in input_detail:
del input_detail[item]
config = CommonRegLogConfigDetail(config_name, logstore_name, endpoint, log_path, file_pattern, time_format,
log_begin_regex, log_parse_regex, reg_keys,
topic_format, filter_keys, filter_keys_reg, logSample,
log_type, **input_detail)
return config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_apsara_log_config(json_value):
"""Generate apsara logtail config from loaded json value :param json_value: :return: """ |
input_detail = json_value['inputDetail']
output_detail = json_value['outputDetail']
config_name = json_value['configName']
logSample = json_value.get('logSample', '')
logstore_name = output_detail['logstoreName']
endpoint = output_detail.get('endpoint', '')
log_path = input_detail['logPath']
file_pattern = input_detail['filePattern']
log_begin_regex = input_detail.get('logBeginRegex', '')
topic_format = input_detail['topicFormat']
filter_keys = input_detail['filterKey']
filter_keys_reg = input_detail['filterRegex']
config = ApsaraLogConfigDetail(config_name, logstore_name, endpoint, log_path, file_pattern,
log_begin_regex, topic_format, filter_keys, filter_keys_reg, logSample)
return config |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_logtail_config(json_value):
"""Generate logtail config from loaded json value :param json_value: :return: """ |
logger.warning("aliyun.log.LogtailConfigHelper is deprecated and will be removed in future version."
"Use LogtailConfigGenerator instead")
if json_value['inputDetail']['logType'] == 'apsara_log':
return LogtailConfigHelper.generate_apsara_log_config(json_value)
return LogtailConfigHelper.generate_common_reg_log_config(json_value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_batch_requests(self, timeout=None):
"""try to get request as fast as possible, once empty and stop falg or time-out, just return Empty""" |
reqs = []
s = time()
while len(reqs) < self.batch_size and (time() - s) < timeout:
try:
req = self.queue.get(block=False)
self.queue.task_done()
reqs.append(req)
except Empty as ex:
if self.stop_flag:
break
else:
sleep(0.1)
if not reqs:
raise Empty
elif len(reqs) <= 1:
return reqs[0]
else:
logitems = []
req = reqs[0]
for req in reqs:
logitems.extend(req.get_log_items())
ret = PutLogsRequest(self.project, self.log_store, req.topic, logitems=logitems)
ret.__record__ = req.__record__
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mmGetPlotUnionSDRActivity(self, title="Union SDR Activity Raster", showReset=False, resetShading=0.25):
""" Returns plot of the activity of union SDR bits. @param title an optional title for the figure @param showReset if true, the first set of activities after a reset will have a gray background @param resetShading If showReset is true, this float specifies the intensity of the reset background with 0.0 being white and 1.0 being black @return (Plot) plot """ |
unionSDRTrace = self.mmGetTraceUnionSDR().data
columnCount = self.getNumColumns()
activityType = "Union SDR Activity"
return self.mmGetCellTracePlot(unionSDRTrace, columnCount, activityType,
title=title, showReset=showReset,
resetShading=resetShading) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mmGetMetricStabilityConfusion(self):
""" For each iteration that doesn't follow a reset, looks at every other iteration for the same world that doesn't follow a reset, and computes the number of bits that show up in one or the other set of active cells for that iteration, but not both. This metric returns the distribution of those numbers. @return (Metric) Stability confusion metric """ |
self._mmComputeSequenceRepresentationData()
numbers = self._mmData["stabilityConfusion"]
return Metric(self, "stability confusion", numbers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mmGetPlotStability(self, title="Stability", showReset=False, resetShading=0.25):
""" Returns plot of the overlap metric between union SDRs within a sequence. @param title an optional title for the figure @return (Plot) plot """ |
plot = Plot(self, title)
self._mmComputeSequenceRepresentationData()
data = self._mmData["stabilityConfusion"]
plot.addGraph(sorted(data, reverse=True),
position=211,
xlabel="Time steps", ylabel="Overlap")
plot.addHistogram(data,
position=212,
bins=100,
xlabel="Overlap", ylabel="# time steps")
return plot |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mmGetMetricDistinctnessConfusion(self):
""" For each iteration that doesn't follow a reset, looks at every other iteration for every other world that doesn't follow a reset, and computes the number of bits that show up in both sets of active cells those that iteration. This metric returns the distribution of those numbers. @return (Metric) Distinctness confusion metric """ |
self._mmComputeSequenceRepresentationData()
numbers = self._mmData["distinctnessConfusion"]
return Metric(self, "distinctness confusion", numbers) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mmUpdateDutyCycles(self):
""" Update the duty cycle variables internally tracked by the TM mixin. """ |
period = self.getDutyCyclePeriod()
unionSDRArray = numpy.zeros(self.getNumColumns())
unionSDRArray[list(self._mmTraces["unionSDR"].data[-1])] = 1
self._mmData["unionSDRDutyCycle"] = \
UnionTemporalPoolerMonitorMixin._mmUpdateDutyCyclesHelper(
self._mmData["unionSDRDutyCycle"], unionSDRArray, period)
self._mmData["persistenceDutyCycle"] = \
UnionTemporalPoolerMonitorMixin._mmUpdateDutyCyclesHelper(
self._mmData["persistenceDutyCycle"], self._poolingActivation, period) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mmComputeSequenceRepresentationData(self):
""" Calculates values for the overlap distance matrix, stability within a sequence, and distinctness between sequences. These values are cached so that they do need to be recomputed for calls to each of several accessor methods that use these values. """ |
if not self._sequenceRepresentationDataStale:
return
unionSDRTrace = self.mmGetTraceUnionSDR()
sequenceLabelsTrace = self.mmGetTraceSequenceLabels()
resetsTrace = self.mmGetTraceResets()
n = len(unionSDRTrace.data)
overlapMatrix = numpy.empty((n, n), dtype=uintType)
stabilityConfusionUnionSDR = []
distinctnessConfusionUnionSDR = []
for i in xrange(n):
for j in xrange(i+1):
overlapUnionSDR = len(unionSDRTrace.data[i] & unionSDRTrace.data[j])
overlapMatrix[i][j] = overlapUnionSDR
overlapMatrix[j][i] = overlapUnionSDR
if (i != j and
sequenceLabelsTrace.data[i] is not None and
not resetsTrace.data[i] and
sequenceLabelsTrace.data[j] is not None and
not resetsTrace.data[j]):
if sequenceLabelsTrace.data[i] == sequenceLabelsTrace.data[j]:
stabilityConfusionUnionSDR.append(overlapUnionSDR)
else:
distinctnessConfusionUnionSDR.append(overlapUnionSDR)
self._mmData["overlap"] = overlapMatrix
self._mmData["stabilityConfusion"] = stabilityConfusionUnionSDR
self._mmData["distinctnessConfusion"] = distinctnessConfusionUnionSDR
self._sequenceRepresentationDataStale = False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def registerResearchRegion(regionTypeName, moduleName=None):
""" Register this region so that NuPIC can later find it. @param regionTypeName: (str) type name of the region. E.g LanguageSensor. @param moduleName: (str) location of the region class, only needed if registering a region that is outside the expected "regions/" dir. """ |
global _PY_REGIONS
if moduleName is None:
# the region is located in the regions/ directory
moduleName = "htmresearch.regions." + regionTypeName
if regionTypeName not in _PY_REGIONS:
# Add new region class to the network.
module = __import__(moduleName, {}, {}, regionTypeName)
unregisteredClass = getattr(module, regionTypeName)
Network.registerRegion(unregisteredClass)
# Add region to list of registered PyRegions
_PY_REGIONS.append(regionTypeName) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loadNumpyImages(self, path, key=None):
""" Loads images using numpy. :param path: (string) Path to data file :param key: (string) Object key in data file if it's a dict Also stores image dimensions to later the original images. If there are multiple channels, self.numChannels will store the number of channels, otherwise it will be set to None. """ |
data = np.load(path)
if isinstance(data, dict):
if key is None:
raise ValueError("Images are stored as a dict, a key must be provided!")
try:
data = data[key]
except KeyError:
raise KeyError("Wrong key for provided data.")
if not isinstance(data, np.ndarray):
raise TypeError("Data must be stored as a dict or numpy array.")
self._initializeDimensions(data)
return data |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.