id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
6,100
llllllllll/codetransformer
codetransformer/transformers/interpolated_strings.py
interpolated_strings.types
def types(self): """ Tuple containing types transformed by this transformer. """ out = [] if self._transform_bytes: out.append(bytes) if self._transform_str: out.append(str) return tuple(out)
python
def types(self): out = [] if self._transform_bytes: out.append(bytes) if self._transform_str: out.append(str) return tuple(out)
[ "def", "types", "(", "self", ")", ":", "out", "=", "[", "]", "if", "self", ".", "_transform_bytes", ":", "out", ".", "append", "(", "bytes", ")", "if", "self", ".", "_transform_str", ":", "out", ".", "append", "(", "str", ")", "return", "tuple", "(...
Tuple containing types transformed by this transformer.
[ "Tuple", "containing", "types", "transformed", "by", "this", "transformer", "." ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L55-L64
6,101
llllllllll/codetransformer
codetransformer/transformers/interpolated_strings.py
interpolated_strings._transform_constant_sequence
def _transform_constant_sequence(self, seq): """ Transform a frozenset or tuple. """ should_transform = is_a(self.types) if not any(filter(should_transform, flatten(seq))): # Tuple doesn't contain any transformable strings. Ignore. yield LOAD_CONST(seq) return for const in seq: if should_transform(const): yield from self.transform_stringlike(const) elif isinstance(const, (tuple, frozenset)): yield from self._transform_constant_sequence(const) else: yield LOAD_CONST(const) if isinstance(seq, tuple): yield BUILD_TUPLE(len(seq)) else: assert isinstance(seq, frozenset) yield BUILD_TUPLE(len(seq)) yield LOAD_CONST(frozenset) yield ROT_TWO() yield CALL_FUNCTION(1)
python
def _transform_constant_sequence(self, seq): should_transform = is_a(self.types) if not any(filter(should_transform, flatten(seq))): # Tuple doesn't contain any transformable strings. Ignore. yield LOAD_CONST(seq) return for const in seq: if should_transform(const): yield from self.transform_stringlike(const) elif isinstance(const, (tuple, frozenset)): yield from self._transform_constant_sequence(const) else: yield LOAD_CONST(const) if isinstance(seq, tuple): yield BUILD_TUPLE(len(seq)) else: assert isinstance(seq, frozenset) yield BUILD_TUPLE(len(seq)) yield LOAD_CONST(frozenset) yield ROT_TWO() yield CALL_FUNCTION(1)
[ "def", "_transform_constant_sequence", "(", "self", ",", "seq", ")", ":", "should_transform", "=", "is_a", "(", "self", ".", "types", ")", "if", "not", "any", "(", "filter", "(", "should_transform", ",", "flatten", "(", "seq", ")", ")", ")", ":", "# Tupl...
Transform a frozenset or tuple.
[ "Transform", "a", "frozenset", "or", "tuple", "." ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L81-L107
6,102
llllllllll/codetransformer
codetransformer/transformers/interpolated_strings.py
interpolated_strings.transform_stringlike
def transform_stringlike(self, const): """ Yield instructions to process a str or bytes constant. """ yield LOAD_CONST(const) if isinstance(const, bytes): yield from self.bytes_instrs elif isinstance(const, str): yield from self.str_instrs
python
def transform_stringlike(self, const): yield LOAD_CONST(const) if isinstance(const, bytes): yield from self.bytes_instrs elif isinstance(const, str): yield from self.str_instrs
[ "def", "transform_stringlike", "(", "self", ",", "const", ")", ":", "yield", "LOAD_CONST", "(", "const", ")", "if", "isinstance", "(", "const", ",", "bytes", ")", ":", "yield", "from", "self", ".", "bytes_instrs", "elif", "isinstance", "(", "const", ",", ...
Yield instructions to process a str or bytes constant.
[ "Yield", "instructions", "to", "process", "a", "str", "or", "bytes", "constant", "." ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L109-L117
6,103
llllllllll/codetransformer
codetransformer/instructions.py
Instruction.steal
def steal(self, instr): """Steal the jump index off of `instr`. This makes anything that would have jumped to `instr` jump to this Instruction instead. Parameters ---------- instr : Instruction The instruction to steal the jump sources from. Returns ------- self : Instruction The instruction that owns this method. Notes ----- This mutates self and ``instr`` inplace. """ instr._stolen_by = self for jmp in instr._target_of: jmp.arg = self self._target_of = instr._target_of instr._target_of = set() return self
python
def steal(self, instr): instr._stolen_by = self for jmp in instr._target_of: jmp.arg = self self._target_of = instr._target_of instr._target_of = set() return self
[ "def", "steal", "(", "self", ",", "instr", ")", ":", "instr", ".", "_stolen_by", "=", "self", "for", "jmp", "in", "instr", ".", "_target_of", ":", "jmp", ".", "arg", "=", "self", "self", ".", "_target_of", "=", "instr", ".", "_target_of", "instr", "....
Steal the jump index off of `instr`. This makes anything that would have jumped to `instr` jump to this Instruction instead. Parameters ---------- instr : Instruction The instruction to steal the jump sources from. Returns ------- self : Instruction The instruction that owns this method. Notes ----- This mutates self and ``instr`` inplace.
[ "Steal", "the", "jump", "index", "off", "of", "instr", "." ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L161-L186
6,104
llllllllll/codetransformer
codetransformer/instructions.py
Instruction.from_opcode
def from_opcode(cls, opcode, arg=_no_arg): """ Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Returns ------- intsr : Instruction An instance of the instruction named by ``opcode``. """ return type(cls)(opname[opcode], (cls,), {}, opcode=opcode)(arg)
python
def from_opcode(cls, opcode, arg=_no_arg): return type(cls)(opname[opcode], (cls,), {}, opcode=opcode)(arg)
[ "def", "from_opcode", "(", "cls", ",", "opcode", ",", "arg", "=", "_no_arg", ")", ":", "return", "type", "(", "cls", ")", "(", "opname", "[", "opcode", "]", ",", "(", "cls", ",", ")", ",", "{", "}", ",", "opcode", "=", "opcode", ")", "(", "arg"...
Create an instruction from an opcode and raw argument. Parameters ---------- opcode : int Opcode for the instruction to create. arg : int, optional The argument for the instruction. Returns ------- intsr : Instruction An instance of the instruction named by ``opcode``.
[ "Create", "an", "instruction", "from", "an", "opcode", "and", "raw", "argument", "." ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L189-L205
6,105
llllllllll/codetransformer
codetransformer/instructions.py
Instruction.stack_effect
def stack_effect(self): """ The net effect of executing this instruction on the interpreter stack. Instructions that pop values off the stack have negative stack effect equal to the number of popped values. Instructions that push values onto the stack have positive stack effect equal to the number of popped values. Examples -------- - LOAD_{FAST,NAME,GLOBAL,DEREF} push one value onto the stack. They have a stack_effect of 1. - POP_JUMP_IF_{TRUE,FALSE} always pop one value off the stack. They have a stack effect of -1. - BINARY_* instructions pop two instructions off the stack, apply a binary operator, and push the resulting value onto the stack. They have a stack effect of -1 (-2 values consumed + 1 value pushed). """ if self.opcode == NOP.opcode: # noqa # dis.stack_effect is broken here return 0 return stack_effect( self.opcode, *((self.arg if isinstance(self.arg, int) else 0,) if self.have_arg else ()) )
python
def stack_effect(self): if self.opcode == NOP.opcode: # noqa # dis.stack_effect is broken here return 0 return stack_effect( self.opcode, *((self.arg if isinstance(self.arg, int) else 0,) if self.have_arg else ()) )
[ "def", "stack_effect", "(", "self", ")", ":", "if", "self", ".", "opcode", "==", "NOP", ".", "opcode", ":", "# noqa", "# dis.stack_effect is broken here", "return", "0", "return", "stack_effect", "(", "self", ".", "opcode", ",", "*", "(", "(", "self", ".",...
The net effect of executing this instruction on the interpreter stack. Instructions that pop values off the stack have negative stack effect equal to the number of popped values. Instructions that push values onto the stack have positive stack effect equal to the number of popped values. Examples -------- - LOAD_{FAST,NAME,GLOBAL,DEREF} push one value onto the stack. They have a stack_effect of 1. - POP_JUMP_IF_{TRUE,FALSE} always pop one value off the stack. They have a stack effect of -1. - BINARY_* instructions pop two instructions off the stack, apply a binary operator, and push the resulting value onto the stack. They have a stack effect of -1 (-2 values consumed + 1 value pushed).
[ "The", "net", "effect", "of", "executing", "this", "instruction", "on", "the", "interpreter", "stack", "." ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L208-L236
6,106
llllllllll/codetransformer
codetransformer/instructions.py
Instruction.equiv
def equiv(self, instr): """Check equivalence of instructions. This checks against the types and the arguments of the instructions Parameters ---------- instr : Instruction The instruction to check against. Returns ------- is_equiv : bool If the instructions are equivalent. Notes ----- This is a separate concept from instruction identity. Two separate instructions can be equivalent without being the same exact instance. This means that two equivalent instructions can be at different points in the bytecode or be targeted by different jumps. """ return type(self) == type(instr) and self.arg == instr.arg
python
def equiv(self, instr): return type(self) == type(instr) and self.arg == instr.arg
[ "def", "equiv", "(", "self", ",", "instr", ")", ":", "return", "type", "(", "self", ")", "==", "type", "(", "instr", ")", "and", "self", ".", "arg", "==", "instr", ".", "arg" ]
Check equivalence of instructions. This checks against the types and the arguments of the instructions Parameters ---------- instr : Instruction The instruction to check against. Returns ------- is_equiv : bool If the instructions are equivalent. Notes ----- This is a separate concept from instruction identity. Two separate instructions can be equivalent without being the same exact instance. This means that two equivalent instructions can be at different points in the bytecode or be targeted by different jumps.
[ "Check", "equivalence", "of", "instructions", ".", "This", "checks", "against", "the", "types", "and", "the", "arguments", "of", "the", "instructions" ]
c5f551e915df45adc7da7e0b1b635f0cc6a1bb27
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L238-L259
6,107
jedie/DragonPy
boot_dragonpy.py
EnvSubprocess._get_python_cmd
def _get_python_cmd(self): """ return the python executable in the virtualenv. Try first sys.executable but use fallbacks. """ file_names = ["pypy.exe", "python.exe", "python"] executable = sys.executable if executable is not None: executable = os.path.split(executable)[1] file_names.insert(0, executable) return self._get_bin_file(*file_names)
python
def _get_python_cmd(self): file_names = ["pypy.exe", "python.exe", "python"] executable = sys.executable if executable is not None: executable = os.path.split(executable)[1] file_names.insert(0, executable) return self._get_bin_file(*file_names)
[ "def", "_get_python_cmd", "(", "self", ")", ":", "file_names", "=", "[", "\"pypy.exe\"", ",", "\"python.exe\"", ",", "\"python\"", "]", "executable", "=", "sys", ".", "executable", "if", "executable", "is", "not", "None", ":", "executable", "=", "os", ".", ...
return the python executable in the virtualenv. Try first sys.executable but use fallbacks.
[ "return", "the", "python", "executable", "in", "the", "virtualenv", ".", "Try", "first", "sys", ".", "executable", "but", "use", "fallbacks", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1901-L1912
6,108
jedie/DragonPy
PyDC/PyDC/__init__.py
convert
def convert(source_file, destination_file, cfg): """ convert in every way. """ source_ext = os.path.splitext(source_file)[1] source_ext = source_ext.lower() dest_ext = os.path.splitext(destination_file)[1] dest_ext = dest_ext.lower() if source_ext not in (".wav", ".cas", ".bas"): raise AssertionError( "Source file type %r not supported." % repr(source_ext) ) if dest_ext not in (".wav", ".cas", ".bas"): raise AssertionError( "Destination file type %r not supported." % repr(dest_ext) ) print "Convert %s -> %s" % (source_ext, dest_ext) c = Cassette(cfg) if source_ext == ".wav": c.add_from_wav(source_file) elif source_ext == ".cas": c.add_from_cas(source_file) elif source_ext == ".bas": c.add_from_bas(source_file) else: raise RuntimeError # Should never happen c.print_debug_info() if dest_ext == ".wav": c.write_wave(destination_file) elif dest_ext == ".cas": c.write_cas(destination_file) elif dest_ext == ".bas": c.write_bas(destination_file) else: raise RuntimeError
python
def convert(source_file, destination_file, cfg): source_ext = os.path.splitext(source_file)[1] source_ext = source_ext.lower() dest_ext = os.path.splitext(destination_file)[1] dest_ext = dest_ext.lower() if source_ext not in (".wav", ".cas", ".bas"): raise AssertionError( "Source file type %r not supported." % repr(source_ext) ) if dest_ext not in (".wav", ".cas", ".bas"): raise AssertionError( "Destination file type %r not supported." % repr(dest_ext) ) print "Convert %s -> %s" % (source_ext, dest_ext) c = Cassette(cfg) if source_ext == ".wav": c.add_from_wav(source_file) elif source_ext == ".cas": c.add_from_cas(source_file) elif source_ext == ".bas": c.add_from_bas(source_file) else: raise RuntimeError # Should never happen c.print_debug_info() if dest_ext == ".wav": c.write_wave(destination_file) elif dest_ext == ".cas": c.write_cas(destination_file) elif dest_ext == ".bas": c.write_bas(destination_file) else: raise RuntimeError
[ "def", "convert", "(", "source_file", ",", "destination_file", ",", "cfg", ")", ":", "source_ext", "=", "os", ".", "path", ".", "splitext", "(", "source_file", ")", "[", "1", "]", "source_ext", "=", "source_ext", ".", "lower", "(", ")", "dest_ext", "=", ...
convert in every way.
[ "convert", "in", "every", "way", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/__init__.py#L29-L70
6,109
jedie/DragonPy
basic_editor/scrolled_text.py
ScrolledText.save_position
def save_position(self): """ save cursor and scroll position """ # save text cursor position: self.old_text_pos = self.index(tkinter.INSERT) # save scroll position: self.old_first, self.old_last = self.yview()
python
def save_position(self): # save text cursor position: self.old_text_pos = self.index(tkinter.INSERT) # save scroll position: self.old_first, self.old_last = self.yview()
[ "def", "save_position", "(", "self", ")", ":", "# save text cursor position:", "self", ".", "old_text_pos", "=", "self", ".", "index", "(", "tkinter", ".", "INSERT", ")", "# save scroll position:", "self", ".", "old_first", ",", "self", ".", "old_last", "=", "...
save cursor and scroll position
[ "save", "cursor", "and", "scroll", "position" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/scrolled_text.py#L92-L99
6,110
jedie/DragonPy
basic_editor/scrolled_text.py
ScrolledText.restore_position
def restore_position(self): """ restore cursor and scroll position """ # restore text cursor position: self.mark_set(tkinter.INSERT, self.old_text_pos) # restore scroll position: self.yview_moveto(self.old_first)
python
def restore_position(self): # restore text cursor position: self.mark_set(tkinter.INSERT, self.old_text_pos) # restore scroll position: self.yview_moveto(self.old_first)
[ "def", "restore_position", "(", "self", ")", ":", "# restore text cursor position:", "self", ".", "mark_set", "(", "tkinter", ".", "INSERT", ",", "self", ".", "old_text_pos", ")", "# restore scroll position:", "self", ".", "yview_moveto", "(", "self", ".", "old_fi...
restore cursor and scroll position
[ "restore", "cursor", "and", "scroll", "position" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/scrolled_text.py#L101-L108
6,111
jedie/DragonPy
dragonpy/components/rom.py
ROMFile.download
def download(self): """ Request url and return his content The Requested content will be cached into the default temp directory. """ if os.path.isfile(self.archive_path): print("Use %r" % self.archive_path) with open(self.archive_path, "rb") as f: content = f.read() else: print("Request: %r..." % self.URL) # Warning: HTTPS requests do not do any verification of the server's certificate. f = urlopen(self.URL) content = f.read() with open(self.archive_path, "wb") as out_file: out_file.write(content) # Check SHA hash: current_sha1 = hashlib.sha1(content).hexdigest() assert current_sha1 == self.DOWNLOAD_SHA1, "Download sha1 value is wrong! SHA1 is: %r" % current_sha1 print("Download SHA1: %r, ok." % current_sha1)
python
def download(self): if os.path.isfile(self.archive_path): print("Use %r" % self.archive_path) with open(self.archive_path, "rb") as f: content = f.read() else: print("Request: %r..." % self.URL) # Warning: HTTPS requests do not do any verification of the server's certificate. f = urlopen(self.URL) content = f.read() with open(self.archive_path, "wb") as out_file: out_file.write(content) # Check SHA hash: current_sha1 = hashlib.sha1(content).hexdigest() assert current_sha1 == self.DOWNLOAD_SHA1, "Download sha1 value is wrong! SHA1 is: %r" % current_sha1 print("Download SHA1: %r, ok." % current_sha1)
[ "def", "download", "(", "self", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "archive_path", ")", ":", "print", "(", "\"Use %r\"", "%", "self", ".", "archive_path", ")", "with", "open", "(", "self", ".", "archive_path", ",", "\...
Request url and return his content The Requested content will be cached into the default temp directory.
[ "Request", "url", "and", "return", "his", "content", "The", "Requested", "content", "will", "be", "cached", "into", "the", "default", "temp", "directory", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/rom.py#L139-L159
6,112
jedie/DragonPy
dragonpy/core/gui.py
BaseTkinterGUI.paste_clipboard
def paste_clipboard(self, event): """ Send the clipboard content as user input to the CPU. """ log.critical("paste clipboard") clipboard = self.root.clipboard_get() for line in clipboard.splitlines(): log.critical("paste line: %s", repr(line)) self.add_user_input(line + "\r")
python
def paste_clipboard(self, event): log.critical("paste clipboard") clipboard = self.root.clipboard_get() for line in clipboard.splitlines(): log.critical("paste line: %s", repr(line)) self.add_user_input(line + "\r")
[ "def", "paste_clipboard", "(", "self", ",", "event", ")", ":", "log", ".", "critical", "(", "\"paste clipboard\"", ")", "clipboard", "=", "self", ".", "root", ".", "clipboard_get", "(", ")", "for", "line", "in", "clipboard", ".", "splitlines", "(", ")", ...
Send the clipboard content as user input to the CPU.
[ "Send", "the", "clipboard", "content", "as", "user", "input", "to", "the", "CPU", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui.py#L219-L227
6,113
jedie/DragonPy
dragonpy/core/gui.py
DragonTkinterGUI.display_callback
def display_callback(self, cpu_cycles, op_address, address, value): """ called via memory write_byte_middleware """ self.display.write_byte(cpu_cycles, op_address, address, value) return value
python
def display_callback(self, cpu_cycles, op_address, address, value): self.display.write_byte(cpu_cycles, op_address, address, value) return value
[ "def", "display_callback", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ",", "value", ")", ":", "self", ".", "display", ".", "write_byte", "(", "cpu_cycles", ",", "op_address", ",", "address", ",", "value", ")", "return", "value" ]
called via memory write_byte_middleware
[ "called", "via", "memory", "write_byte_middleware" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui.py#L346-L349
6,114
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.read_PIA0_A_data
def read_PIA0_A_data(self, cpu_cycles, op_address, address): """ read from 0xff00 -> PIA 0 A side Data reg. bit 7 | PA7 | joystick comparison input bit 6 | PA6 | keyboard matrix row 7 bit 5 | PA5 | keyboard matrix row 6 bit 4 | PA4 | keyboard matrix row 5 bit 3 | PA3 | keyboard matrix row 4 & left joystick switch 2 bit 2 | PA2 | keyboard matrix row 3 & right joystick switch 2 bit 1 | PA1 | keyboard matrix row 2 & left joystick switch 1 bit 0 | PA0 | keyboard matrix row 1 & right joystick switch 1 """ pia0b = self.pia_0_B_data.value # $ff02 # FIXME: Find a way to handle CoCo and Dragon in the same way! if self.cfg.CONFIG_NAME == COCO2B: # log.critical("\t count: %i", self.input_repead) if self.input_repead == 7: try: self.current_input_char = self.user_input_queue.get_nowait() except queue.Empty: self.current_input_char = None else: log.critical( "\tget new key from queue: %s", repr(self.current_input_char)) elif self.input_repead == 18: # log.critical("\tForce send 'no key pressed'") self.current_input_char = None elif self.input_repead > 20: self.input_repead = 0 self.input_repead += 1 else: # Dragon if pia0b == self.cfg.PIA0B_KEYBOARD_START: # FIXME if self.empty_key_toggle: # Work-a-round for "poor" dragon keyboard scan routine: # The scan routine in ROM ignores key pressed directly behind # one another if they are in the same row! # See "Inside the Dragon" book, page 203 ;) # # Here with the empty_key_toggle, we always send a "no key pressed" # after every key press back and then we send the next key from # the self.user_input_queue # # TODO: We can check the row of the previous key press and only # force a 'no key pressed' if the row is the same self.empty_key_toggle = False self.current_input_char = None # log.critical("\tForce send 'no key pressed'") else: try: self.current_input_char = self.user_input_queue.get_nowait() except queue.Empty: # log.critical("\tinput_queue is empty")) self.current_input_char = None else: # log.critical("\tget new key from queue: %s", repr(self.current_input_char)) self.empty_key_toggle = True if self.current_input_char is None: # log.critical("\tno key pressed") result = 0xff self.empty_key_toggle = False else: # log.critical("\tsend %s", repr(self.current_input_char)) result = self.cfg.pia_keymatrix_result( self.current_input_char, pia0b) # if not is_bit_set(pia0b, bit=7): # bit 7 | PA7 | joystick comparison input # result = clear_bit(result, bit=7) # if self.current_input_char is not None: # log.critical( # "%04x| read $%04x ($ff02 is $%02x %s) send $%02x %s back\t|%s", # op_address, address, # pia0b, '{0:08b}'.format(pia0b), # result, '{0:08b}'.format(result), # self.cfg.mem_info.get_shortest(op_address) # ) return result
python
def read_PIA0_A_data(self, cpu_cycles, op_address, address): pia0b = self.pia_0_B_data.value # $ff02 # FIXME: Find a way to handle CoCo and Dragon in the same way! if self.cfg.CONFIG_NAME == COCO2B: # log.critical("\t count: %i", self.input_repead) if self.input_repead == 7: try: self.current_input_char = self.user_input_queue.get_nowait() except queue.Empty: self.current_input_char = None else: log.critical( "\tget new key from queue: %s", repr(self.current_input_char)) elif self.input_repead == 18: # log.critical("\tForce send 'no key pressed'") self.current_input_char = None elif self.input_repead > 20: self.input_repead = 0 self.input_repead += 1 else: # Dragon if pia0b == self.cfg.PIA0B_KEYBOARD_START: # FIXME if self.empty_key_toggle: # Work-a-round for "poor" dragon keyboard scan routine: # The scan routine in ROM ignores key pressed directly behind # one another if they are in the same row! # See "Inside the Dragon" book, page 203 ;) # # Here with the empty_key_toggle, we always send a "no key pressed" # after every key press back and then we send the next key from # the self.user_input_queue # # TODO: We can check the row of the previous key press and only # force a 'no key pressed' if the row is the same self.empty_key_toggle = False self.current_input_char = None # log.critical("\tForce send 'no key pressed'") else: try: self.current_input_char = self.user_input_queue.get_nowait() except queue.Empty: # log.critical("\tinput_queue is empty")) self.current_input_char = None else: # log.critical("\tget new key from queue: %s", repr(self.current_input_char)) self.empty_key_toggle = True if self.current_input_char is None: # log.critical("\tno key pressed") result = 0xff self.empty_key_toggle = False else: # log.critical("\tsend %s", repr(self.current_input_char)) result = self.cfg.pia_keymatrix_result( self.current_input_char, pia0b) # if not is_bit_set(pia0b, bit=7): # bit 7 | PA7 | joystick comparison input # result = clear_bit(result, bit=7) # if self.current_input_char is not None: # log.critical( # "%04x| read $%04x ($ff02 is $%02x %s) send $%02x %s back\t|%s", # op_address, address, # pia0b, '{0:08b}'.format(pia0b), # result, '{0:08b}'.format(result), # self.cfg.mem_info.get_shortest(op_address) # ) return result
[ "def", "read_PIA0_A_data", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ")", ":", "pia0b", "=", "self", ".", "pia_0_B_data", ".", "value", "# $ff02", "# FIXME: Find a way to handle CoCo and Dragon in the same way!", "if", "self", ".", "cfg", "....
read from 0xff00 -> PIA 0 A side Data reg. bit 7 | PA7 | joystick comparison input bit 6 | PA6 | keyboard matrix row 7 bit 5 | PA5 | keyboard matrix row 6 bit 4 | PA4 | keyboard matrix row 5 bit 3 | PA3 | keyboard matrix row 4 & left joystick switch 2 bit 2 | PA2 | keyboard matrix row 3 & right joystick switch 2 bit 1 | PA1 | keyboard matrix row 2 & left joystick switch 1 bit 0 | PA0 | keyboard matrix row 1 & right joystick switch 1
[ "read", "from", "0xff00", "-", ">", "PIA", "0", "A", "side", "Data", "reg", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L218-L299
6,115
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.write_PIA0_A_data
def write_PIA0_A_data(self, cpu_cycles, op_address, address, value): """ write to 0xff00 -> PIA 0 A side Data reg. """ log.error("%04x| write $%02x (%s) to $%04x -> PIA 0 A side Data reg.\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) self.pia_0_A_register.set(value)
python
def write_PIA0_A_data(self, cpu_cycles, op_address, address, value): log.error("%04x| write $%02x (%s) to $%04x -> PIA 0 A side Data reg.\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) self.pia_0_A_register.set(value)
[ "def", "write_PIA0_A_data", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ",", "value", ")", ":", "log", ".", "error", "(", "\"%04x| write $%02x (%s) to $%04x -> PIA 0 A side Data reg.\\t|%s\"", ",", "op_address", ",", "value", ",", "byte2bit_stri...
write to 0xff00 -> PIA 0 A side Data reg.
[ "write", "to", "0xff00", "-", ">", "PIA", "0", "A", "side", "Data", "reg", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L301-L307
6,116
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.read_PIA0_A_control
def read_PIA0_A_control(self, cpu_cycles, op_address, address): """ read from 0xff01 -> PIA 0 A side control register """ value = 0xb3 log.error( "%04x| read $%04x (PIA 0 A side Control reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) return value
python
def read_PIA0_A_control(self, cpu_cycles, op_address, address): value = 0xb3 log.error( "%04x| read $%04x (PIA 0 A side Control reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) return value
[ "def", "read_PIA0_A_control", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ")", ":", "value", "=", "0xb3", "log", ".", "error", "(", "\"%04x| read $%04x (PIA 0 A side Control reg.) send $%02x (%s) back.\\t|%s\"", ",", "op_address", ",", "address", ...
read from 0xff01 -> PIA 0 A side control register
[ "read", "from", "0xff01", "-", ">", "PIA", "0", "A", "side", "control", "register" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L309-L319
6,117
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.write_PIA0_A_control
def write_PIA0_A_control(self, cpu_cycles, op_address, address, value): """ write to 0xff01 -> PIA 0 A side control register TODO: Handle IRQ bit 7 | IRQ 1 (HSYNC) flag bit 6 | IRQ 2 flag(not used) bit 5 | Control line 2 (CA2) is an output = 1 bit 4 | Control line 2 (CA2) set by bit 3 = 1 bit 3 | select line LSB of analog multiplexor (MUX): 0 = control line 2 LO / 1 = control line 2 HI bit 2 | set data direction: 0 = $FF00 is DDR / 1 = $FF00 is normal data lines bit 1 | control line 1 (CA1): IRQ polarity 0 = IRQ on HI to LO / 1 = IRQ on LO to HI bit 0 | HSYNC IRQ: 0 = disabled IRQ / 1 = enabled IRQ """ log.error( "%04x| write $%02x (%s) to $%04x -> PIA 0 A side Control reg.\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) if not is_bit_set(value, bit=2): self.pia_0_A_register.select_pdr() else: self.pia_0_A_register.deselect_pdr()
python
def write_PIA0_A_control(self, cpu_cycles, op_address, address, value): log.error( "%04x| write $%02x (%s) to $%04x -> PIA 0 A side Control reg.\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) if not is_bit_set(value, bit=2): self.pia_0_A_register.select_pdr() else: self.pia_0_A_register.deselect_pdr()
[ "def", "write_PIA0_A_control", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ",", "value", ")", ":", "log", ".", "error", "(", "\"%04x| write $%02x (%s) to $%04x -> PIA 0 A side Control reg.\\t|%s\"", ",", "op_address", ",", "value", ",", "byte2bi...
write to 0xff01 -> PIA 0 A side control register TODO: Handle IRQ bit 7 | IRQ 1 (HSYNC) flag bit 6 | IRQ 2 flag(not used) bit 5 | Control line 2 (CA2) is an output = 1 bit 4 | Control line 2 (CA2) set by bit 3 = 1 bit 3 | select line LSB of analog multiplexor (MUX): 0 = control line 2 LO / 1 = control line 2 HI bit 2 | set data direction: 0 = $FF00 is DDR / 1 = $FF00 is normal data lines bit 1 | control line 1 (CA1): IRQ polarity 0 = IRQ on HI to LO / 1 = IRQ on LO to HI bit 0 | HSYNC IRQ: 0 = disabled IRQ / 1 = enabled IRQ
[ "write", "to", "0xff01", "-", ">", "PIA", "0", "A", "side", "control", "register" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L321-L344
6,118
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.read_PIA0_B_data
def read_PIA0_B_data(self, cpu_cycles, op_address, address): """ read from 0xff02 -> PIA 0 B side Data reg. bit 7 | PB7 | keyboard matrix column 8 bit 6 | PB6 | keyboard matrix column 7 / ram size output bit 5 | PB5 | keyboard matrix column 6 bit 4 | PB4 | keyboard matrix column 5 bit 3 | PB3 | keyboard matrix column 4 bit 2 | PB2 | keyboard matrix column 3 bit 1 | PB1 | keyboard matrix column 2 bit 0 | PB0 | keyboard matrix column 1 bits 0-7 also printer data lines """ value = self.pia_0_B_data.value # $ff02 log.debug( "%04x| read $%04x (PIA 0 B side Data reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) return value
python
def read_PIA0_B_data(self, cpu_cycles, op_address, address): value = self.pia_0_B_data.value # $ff02 log.debug( "%04x| read $%04x (PIA 0 B side Data reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) return value
[ "def", "read_PIA0_B_data", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ")", ":", "value", "=", "self", ".", "pia_0_B_data", ".", "value", "# $ff02", "log", ".", "debug", "(", "\"%04x| read $%04x (PIA 0 B side Data reg.) send $%02x (%s) back.\\t|...
read from 0xff02 -> PIA 0 B side Data reg. bit 7 | PB7 | keyboard matrix column 8 bit 6 | PB6 | keyboard matrix column 7 / ram size output bit 5 | PB5 | keyboard matrix column 6 bit 4 | PB4 | keyboard matrix column 5 bit 3 | PB3 | keyboard matrix column 4 bit 2 | PB2 | keyboard matrix column 3 bit 1 | PB1 | keyboard matrix column 2 bit 0 | PB0 | keyboard matrix column 1 bits 0-7 also printer data lines
[ "read", "from", "0xff02", "-", ">", "PIA", "0", "B", "side", "Data", "reg", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L346-L367
6,119
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.read_PIA0_B_control
def read_PIA0_B_control(self, cpu_cycles, op_address, address): """ read from 0xff03 -> PIA 0 B side Control reg. """ value = self.pia_0_B_control.value log.error( "%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) return value
python
def read_PIA0_B_control(self, cpu_cycles, op_address, address): value = self.pia_0_B_control.value log.error( "%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\t|%s", op_address, address, value, byte2bit_string(value), self.cfg.mem_info.get_shortest(op_address) ) return value
[ "def", "read_PIA0_B_control", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ")", ":", "value", "=", "self", ".", "pia_0_B_control", ".", "value", "log", ".", "error", "(", "\"%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\\t|%s\"...
read from 0xff03 -> PIA 0 B side Control reg.
[ "read", "from", "0xff03", "-", ">", "PIA", "0", "B", "side", "Control", "reg", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L379-L389
6,120
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.write_PIA0_B_control
def write_PIA0_B_control(self, cpu_cycles, op_address, address, value): """ write to 0xff03 -> PIA 0 B side Control reg. TODO: Handle IRQ bit 7 | IRQ 1 (VSYNC) flag bit 6 | IRQ 2 flag(not used) bit 5 | Control line 2 (CB2) is an output = 1 bit 4 | Control line 2 (CB2) set by bit 3 = 1 bit 3 | select line MSB of analog multiplexor (MUX): 0 = control line 2 LO / 1 = control line 2 HI bit 2 | set data direction: 0 = $FF02 is DDR / 1 = $FF02 is normal data lines bit 1 | control line 1 (CB1): IRQ polarity 0 = IRQ on HI to LO / 1 = IRQ on LO to HI bit 0 | VSYNC IRQ: 0 = disable IRQ / 1 = enable IRQ """ log.critical( "%04x| write $%02x (%s) to $%04x -> PIA 0 B side Control reg.\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) if is_bit_set(value, bit=0): log.critical( "%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: enable\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) self.cpu.irq_enabled = True value = set_bit(value, bit=7) else: log.critical( "%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: disable\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) self.cpu.irq_enabled = False if not is_bit_set(value, bit=2): self.pia_0_B_control.select_pdr() else: self.pia_0_B_control.deselect_pdr() self.pia_0_B_control.set(value)
python
def write_PIA0_B_control(self, cpu_cycles, op_address, address, value): log.critical( "%04x| write $%02x (%s) to $%04x -> PIA 0 B side Control reg.\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) if is_bit_set(value, bit=0): log.critical( "%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: enable\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) self.cpu.irq_enabled = True value = set_bit(value, bit=7) else: log.critical( "%04x| write $%02x (%s) to $%04x -> VSYNC IRQ: disable\t|%s", op_address, value, byte2bit_string(value), address, self.cfg.mem_info.get_shortest(op_address) ) self.cpu.irq_enabled = False if not is_bit_set(value, bit=2): self.pia_0_B_control.select_pdr() else: self.pia_0_B_control.deselect_pdr() self.pia_0_B_control.set(value)
[ "def", "write_PIA0_B_control", "(", "self", ",", "cpu_cycles", ",", "op_address", ",", "address", ",", "value", ")", ":", "log", ".", "critical", "(", "\"%04x| write $%02x (%s) to $%04x -> PIA 0 B side Control reg.\\t|%s\"", ",", "op_address", ",", "value", ",", "byte...
write to 0xff03 -> PIA 0 B side Control reg. TODO: Handle IRQ bit 7 | IRQ 1 (VSYNC) flag bit 6 | IRQ 2 flag(not used) bit 5 | Control line 2 (CB2) is an output = 1 bit 4 | Control line 2 (CB2) set by bit 3 = 1 bit 3 | select line MSB of analog multiplexor (MUX): 0 = control line 2 LO / 1 = control line 2 HI bit 2 | set data direction: 0 = $FF02 is DDR / 1 = $FF02 is normal data lines bit 1 | control line 1 (CB1): IRQ polarity 0 = IRQ on HI to LO / 1 = IRQ on LO to HI bit 0 | VSYNC IRQ: 0 = disable IRQ / 1 = enable IRQ
[ "write", "to", "0xff03", "-", ">", "PIA", "0", "B", "side", "Control", "reg", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L391-L433
6,121
jedie/DragonPy
dragonpy/core/machine.py
Machine.inject_basic_program
def inject_basic_program(self, ascii_listing): """ save the given ASCII BASIC program listing into the emulator RAM. """ program_start = self.cpu.memory.read_word( self.machine_api.PROGRAM_START_ADDR ) tokens = self.machine_api.ascii_listing2program_dump(ascii_listing) self.cpu.memory.load(program_start, tokens) log.critical("BASIC program injected into Memory.") # Update the BASIC addresses: program_end = program_start + len(tokens) self.cpu.memory.write_word(self.machine_api.VARIABLES_START_ADDR, program_end) self.cpu.memory.write_word(self.machine_api.ARRAY_START_ADDR, program_end) self.cpu.memory.write_word(self.machine_api.FREE_SPACE_START_ADDR, program_end) log.critical("BASIC addresses updated.")
python
def inject_basic_program(self, ascii_listing): program_start = self.cpu.memory.read_word( self.machine_api.PROGRAM_START_ADDR ) tokens = self.machine_api.ascii_listing2program_dump(ascii_listing) self.cpu.memory.load(program_start, tokens) log.critical("BASIC program injected into Memory.") # Update the BASIC addresses: program_end = program_start + len(tokens) self.cpu.memory.write_word(self.machine_api.VARIABLES_START_ADDR, program_end) self.cpu.memory.write_word(self.machine_api.ARRAY_START_ADDR, program_end) self.cpu.memory.write_word(self.machine_api.FREE_SPACE_START_ADDR, program_end) log.critical("BASIC addresses updated.")
[ "def", "inject_basic_program", "(", "self", ",", "ascii_listing", ")", ":", "program_start", "=", "self", ".", "cpu", ".", "memory", ".", "read_word", "(", "self", ".", "machine_api", ".", "PROGRAM_START_ADDR", ")", "tokens", "=", "self", ".", "machine_api", ...
save the given ASCII BASIC program listing into the emulator RAM.
[ "save", "the", "given", "ASCII", "BASIC", "program", "listing", "into", "the", "emulator", "RAM", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/machine.py#L95-L111
6,122
jedie/DragonPy
PyDC/PyDC/wave2bitstream.py
Wave2Bitstream.sync
def sync(self, length): """ synchronized weave sync trigger """ # go in wave stream to the first bit try: self.next() except StopIteration: print "Error: no bits identified!" sys.exit(-1) log.info("First bit is at: %s" % self.pformat_pos()) log.debug("enable half sinus scan") self.half_sinus = True # Toggle sync test by consuming one half sinus sample # self.iter_trigger_generator.next() # Test sync # get "half sinus cycle" test data test_durations = itertools.islice(self.iter_duration_generator, length) # It's a tuple like: [(frame_no, duration)...] test_durations = list(test_durations) diff1, diff2 = diff_info(test_durations) log.debug("sync diff info: %i vs. %i" % (diff1, diff2)) if diff1 > diff2: log.info("\nbit-sync one step.") self.iter_trigger_generator.next() log.debug("Synced.") else: log.info("\nNo bit-sync needed.") self.half_sinus = False log.debug("disable half sinus scan")
python
def sync(self, length): # go in wave stream to the first bit try: self.next() except StopIteration: print "Error: no bits identified!" sys.exit(-1) log.info("First bit is at: %s" % self.pformat_pos()) log.debug("enable half sinus scan") self.half_sinus = True # Toggle sync test by consuming one half sinus sample # self.iter_trigger_generator.next() # Test sync # get "half sinus cycle" test data test_durations = itertools.islice(self.iter_duration_generator, length) # It's a tuple like: [(frame_no, duration)...] test_durations = list(test_durations) diff1, diff2 = diff_info(test_durations) log.debug("sync diff info: %i vs. %i" % (diff1, diff2)) if diff1 > diff2: log.info("\nbit-sync one step.") self.iter_trigger_generator.next() log.debug("Synced.") else: log.info("\nNo bit-sync needed.") self.half_sinus = False log.debug("disable half sinus scan")
[ "def", "sync", "(", "self", ",", "length", ")", ":", "# go in wave stream to the first bit", "try", ":", "self", ".", "next", "(", ")", "except", "StopIteration", ":", "print", "\"Error: no bits identified!\"", "sys", ".", "exit", "(", "-", "1", ")", "log", ...
synchronized weave sync trigger
[ "synchronized", "weave", "sync", "trigger" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L206-L242
6,123
jedie/DragonPy
PyDC/PyDC/wave2bitstream.py
Wave2Bitstream.iter_duration
def iter_duration(self, iter_trigger): """ yield the duration of two frames in a row. """ print process_info = ProcessInfo(self.frame_count, use_last_rates=4) start_time = time.time() next_status = start_time + 0.25 old_pos = next(iter_trigger) for pos in iter_trigger: duration = pos - old_pos # log.log(5, "Duration: %s" % duration) yield duration old_pos = pos if time.time() > next_status: next_status = time.time() + 1 self._print_status(process_info) self._print_status(process_info) print
python
def iter_duration(self, iter_trigger): print process_info = ProcessInfo(self.frame_count, use_last_rates=4) start_time = time.time() next_status = start_time + 0.25 old_pos = next(iter_trigger) for pos in iter_trigger: duration = pos - old_pos # log.log(5, "Duration: %s" % duration) yield duration old_pos = pos if time.time() > next_status: next_status = time.time() + 1 self._print_status(process_info) self._print_status(process_info) print
[ "def", "iter_duration", "(", "self", ",", "iter_trigger", ")", ":", "print", "process_info", "=", "ProcessInfo", "(", "self", ".", "frame_count", ",", "use_last_rates", "=", "4", ")", "start_time", "=", "time", ".", "time", "(", ")", "next_status", "=", "s...
yield the duration of two frames in a row.
[ "yield", "the", "duration", "of", "two", "frames", "in", "a", "row", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L347-L368
6,124
jedie/DragonPy
PyDC/PyDC/wave2bitstream.py
Wave2Bitstream.iter_trigger
def iter_trigger(self, iter_wave_values): """ trigger middle crossing of the wave sinus curve """ window_size = (2 * self.cfg.END_COUNT) + self.cfg.MID_COUNT # sinus curve goes from negative into positive: pos_null_transit = [(0, self.cfg.END_COUNT), (self.cfg.END_COUNT, 0)] # sinus curve goes from positive into negative: neg_null_transit = [(self.cfg.END_COUNT, 0), (0, self.cfg.END_COUNT)] if self.cfg.MID_COUNT > 3: mid_index = int(round(self.cfg.MID_COUNT / 2.0)) else: mid_index = 0 in_pos = False for values in iter_window(iter_wave_values, window_size): # Split the window previous_values = values[:self.cfg.END_COUNT] # e.g.: 123----- mid_values = values[self.cfg.END_COUNT:self.cfg.END_COUNT + self.cfg.MID_COUNT] # e.g.: ---45--- next_values = values[-self.cfg.END_COUNT:] # e.g.: -----678 # get only the value and strip the frame_no # e.g.: (frame_no, value) tuple -> value list previous_values = [i[1] for i in previous_values] next_values = [i[1] for i in next_values] # Count sign from previous and next values sign_info = [ count_sign(previous_values, 0), count_sign(next_values, 0) ] # log.log(5, "sign info: %s" % repr(sign_info)) # yield the mid crossing if in_pos == False and sign_info == pos_null_transit: log.log(5, "sinus curve goes from negative into positive") # log.debug(" %s | %s | %s" % (previous_values, mid_values, next_values)) yield mid_values[mid_index][0] in_pos = True elif in_pos == True and sign_info == neg_null_transit: if self.half_sinus: log.log(5, "sinus curve goes from positive into negative") # log.debug(" %s | %s | %s" % (previous_values, mid_values, next_values)) yield mid_values[mid_index][0] in_pos = False
python
def iter_trigger(self, iter_wave_values): window_size = (2 * self.cfg.END_COUNT) + self.cfg.MID_COUNT # sinus curve goes from negative into positive: pos_null_transit = [(0, self.cfg.END_COUNT), (self.cfg.END_COUNT, 0)] # sinus curve goes from positive into negative: neg_null_transit = [(self.cfg.END_COUNT, 0), (0, self.cfg.END_COUNT)] if self.cfg.MID_COUNT > 3: mid_index = int(round(self.cfg.MID_COUNT / 2.0)) else: mid_index = 0 in_pos = False for values in iter_window(iter_wave_values, window_size): # Split the window previous_values = values[:self.cfg.END_COUNT] # e.g.: 123----- mid_values = values[self.cfg.END_COUNT:self.cfg.END_COUNT + self.cfg.MID_COUNT] # e.g.: ---45--- next_values = values[-self.cfg.END_COUNT:] # e.g.: -----678 # get only the value and strip the frame_no # e.g.: (frame_no, value) tuple -> value list previous_values = [i[1] for i in previous_values] next_values = [i[1] for i in next_values] # Count sign from previous and next values sign_info = [ count_sign(previous_values, 0), count_sign(next_values, 0) ] # log.log(5, "sign info: %s" % repr(sign_info)) # yield the mid crossing if in_pos == False and sign_info == pos_null_transit: log.log(5, "sinus curve goes from negative into positive") # log.debug(" %s | %s | %s" % (previous_values, mid_values, next_values)) yield mid_values[mid_index][0] in_pos = True elif in_pos == True and sign_info == neg_null_transit: if self.half_sinus: log.log(5, "sinus curve goes from positive into negative") # log.debug(" %s | %s | %s" % (previous_values, mid_values, next_values)) yield mid_values[mid_index][0] in_pos = False
[ "def", "iter_trigger", "(", "self", ",", "iter_wave_values", ")", ":", "window_size", "=", "(", "2", "*", "self", ".", "cfg", ".", "END_COUNT", ")", "+", "self", ".", "cfg", ".", "MID_COUNT", "# sinus curve goes from negative into positive:", "pos_null_transit", ...
trigger middle crossing of the wave sinus curve
[ "trigger", "middle", "crossing", "of", "the", "wave", "sinus", "curve" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L370-L417
6,125
jedie/DragonPy
PyDC/PyDC/wave2bitstream.py
Wave2Bitstream.iter_wave_values
def iter_wave_values(self): """ yield frame numer + volume value from the WAVE file """ typecode = self.get_typecode(self.samplewidth) if log.level >= 5: if self.cfg.AVG_COUNT > 1: # merge samples -> log output in iter_avg_wave_values tlm = None else: tlm = TextLevelMeter(self.max_value, 79) # Use only a read size which is a quare divider of the samplewidth # Otherwise array.array will raise: ValueError: string length not a multiple of item size divider = int(round(float(WAVE_READ_SIZE) / self.samplewidth)) read_size = self.samplewidth * divider if read_size != WAVE_READ_SIZE: log.info("Real use wave read size: %i Bytes" % read_size) get_wave_block_func = functools.partial(self.wavefile.readframes, read_size) skip_count = 0 manually_audioop_bias = self.samplewidth == 1 and audioop is None for frames in iter(get_wave_block_func, ""): if self.samplewidth == 1: if audioop is None: log.warning("use audioop.bias() work-a-round for missing audioop.") else: # 8 bit samples are unsigned, see: # http://docs.python.org/2/library/audioop.html#audioop.lin2lin frames = audioop.bias(frames, 1, 128) try: values = array.array(typecode, frames) except ValueError, err: # e.g.: # ValueError: string length not a multiple of item size # Work-a-round: Skip the last frames of this block frame_count = len(frames) divider = int(math.floor(float(frame_count) / self.samplewidth)) new_count = self.samplewidth * divider frames = frames[:new_count] # skip frames log.error( "Can't make array from %s frames: Value error: %s (Skip %i and use %i frames)" % ( frame_count, err, frame_count - new_count, len(frames) )) values = array.array(typecode, frames) for value in values: self.wave_pos += 1 # Absolute position in the frame stream if manually_audioop_bias: # audioop.bias can't be used. # See: http://hg.python.org/cpython/file/482590320549/Modules/audioop.c#l957 value = value % 0xff - 128 # if abs(value) < self.min_volume: # # log.log(5, "Ignore to lower amplitude") # skip_count += 1 # continue yield (self.wave_pos, value) log.info("Skip %i samples that are lower than %i" % ( skip_count, self.min_volume )) log.info("Last readed Frame is: %s" % self.pformat_pos())
python
def iter_wave_values(self): typecode = self.get_typecode(self.samplewidth) if log.level >= 5: if self.cfg.AVG_COUNT > 1: # merge samples -> log output in iter_avg_wave_values tlm = None else: tlm = TextLevelMeter(self.max_value, 79) # Use only a read size which is a quare divider of the samplewidth # Otherwise array.array will raise: ValueError: string length not a multiple of item size divider = int(round(float(WAVE_READ_SIZE) / self.samplewidth)) read_size = self.samplewidth * divider if read_size != WAVE_READ_SIZE: log.info("Real use wave read size: %i Bytes" % read_size) get_wave_block_func = functools.partial(self.wavefile.readframes, read_size) skip_count = 0 manually_audioop_bias = self.samplewidth == 1 and audioop is None for frames in iter(get_wave_block_func, ""): if self.samplewidth == 1: if audioop is None: log.warning("use audioop.bias() work-a-round for missing audioop.") else: # 8 bit samples are unsigned, see: # http://docs.python.org/2/library/audioop.html#audioop.lin2lin frames = audioop.bias(frames, 1, 128) try: values = array.array(typecode, frames) except ValueError, err: # e.g.: # ValueError: string length not a multiple of item size # Work-a-round: Skip the last frames of this block frame_count = len(frames) divider = int(math.floor(float(frame_count) / self.samplewidth)) new_count = self.samplewidth * divider frames = frames[:new_count] # skip frames log.error( "Can't make array from %s frames: Value error: %s (Skip %i and use %i frames)" % ( frame_count, err, frame_count - new_count, len(frames) )) values = array.array(typecode, frames) for value in values: self.wave_pos += 1 # Absolute position in the frame stream if manually_audioop_bias: # audioop.bias can't be used. # See: http://hg.python.org/cpython/file/482590320549/Modules/audioop.c#l957 value = value % 0xff - 128 # if abs(value) < self.min_volume: # # log.log(5, "Ignore to lower amplitude") # skip_count += 1 # continue yield (self.wave_pos, value) log.info("Skip %i samples that are lower than %i" % ( skip_count, self.min_volume )) log.info("Last readed Frame is: %s" % self.pformat_pos())
[ "def", "iter_wave_values", "(", "self", ")", ":", "typecode", "=", "self", ".", "get_typecode", "(", "self", ".", "samplewidth", ")", "if", "log", ".", "level", ">=", "5", ":", "if", "self", ".", "cfg", ".", "AVG_COUNT", ">", "1", ":", "# merge samples...
yield frame numer + volume value from the WAVE file
[ "yield", "frame", "numer", "+", "volume", "value", "from", "the", "WAVE", "file" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L441-L510
6,126
jedie/DragonPy
dragonpy/utils/hex2bin.py
iter_steps
def iter_steps(g, steps): """ iterate over 'g' in blocks with a length of the given 'step' count. >>> for v in iter_steps([1,2,3,4,5], steps=2): v [1, 2] [3, 4] [5] >>> for v in iter_steps([1,2,3,4,5,6,7,8,9], steps=3): v [1, 2, 3] [4, 5, 6] [7, 8, 9] 12345678 12345678 12345678 >>> bits = [int(i) for i in "0101010101010101111000"] >>> for v in iter_steps(bits, steps=8): v [0, 1, 0, 1, 0, 1, 0, 1] [0, 1, 0, 1, 0, 1, 0, 1] [1, 1, 1, 0, 0, 0] """ values = [] for value in g: values.append(value) if len(values) == steps: yield list(values) values = [] if values: yield list(values)
python
def iter_steps(g, steps): values = [] for value in g: values.append(value) if len(values) == steps: yield list(values) values = [] if values: yield list(values)
[ "def", "iter_steps", "(", "g", ",", "steps", ")", ":", "values", "=", "[", "]", "for", "value", "in", "g", ":", "values", ".", "append", "(", "value", ")", "if", "len", "(", "values", ")", "==", "steps", ":", "yield", "list", "(", "values", ")", ...
iterate over 'g' in blocks with a length of the given 'step' count. >>> for v in iter_steps([1,2,3,4,5], steps=2): v [1, 2] [3, 4] [5] >>> for v in iter_steps([1,2,3,4,5,6,7,8,9], steps=3): v [1, 2, 3] [4, 5, 6] [7, 8, 9] 12345678 12345678 12345678 >>> bits = [int(i) for i in "0101010101010101111000"] >>> for v in iter_steps(bits, steps=8): v [0, 1, 0, 1, 0, 1, 0, 1] [0, 1, 0, 1, 0, 1, 0, 1] [1, 1, 1, 0, 0, 0]
[ "iterate", "over", "g", "in", "blocks", "with", "a", "length", "of", "the", "given", "step", "count", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/hex2bin.py#L18-L46
6,127
jedie/DragonPy
dragonpy/components/periphery.py
TkPeripheryBase._new_output_char
def _new_output_char(self, char): """ insert in text field """ self.text.config(state=tkinter.NORMAL) self.text.insert("end", char) self.text.see("end") self.text.config(state=tkinter.DISABLED)
python
def _new_output_char(self, char): self.text.config(state=tkinter.NORMAL) self.text.insert("end", char) self.text.see("end") self.text.config(state=tkinter.DISABLED)
[ "def", "_new_output_char", "(", "self", ",", "char", ")", ":", "self", ".", "text", ".", "config", "(", "state", "=", "tkinter", ".", "NORMAL", ")", "self", ".", "text", ".", "insert", "(", "\"end\"", ",", "char", ")", "self", ".", "text", ".", "se...
insert in text field
[ "insert", "in", "text", "field" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/periphery.py#L209-L214
6,128
jedie/DragonPy
dragonpy/components/periphery.py
InputPollThread.check_cpu_interval
def check_cpu_interval(self, cpu_process): """ work-a-round for blocking input """ try: # log.critical("check_cpu_interval()") if not cpu_process.is_alive(): log.critical("raise SystemExit, because CPU is not alive.") _thread.interrupt_main() raise SystemExit("Kill pager.getch()") except KeyboardInterrupt: _thread.interrupt_main() else: t = threading.Timer(1.0, self.check_cpu_interval, args=[cpu_process]) t.start()
python
def check_cpu_interval(self, cpu_process): try: # log.critical("check_cpu_interval()") if not cpu_process.is_alive(): log.critical("raise SystemExit, because CPU is not alive.") _thread.interrupt_main() raise SystemExit("Kill pager.getch()") except KeyboardInterrupt: _thread.interrupt_main() else: t = threading.Timer(1.0, self.check_cpu_interval, args=[cpu_process]) t.start()
[ "def", "check_cpu_interval", "(", "self", ",", "cpu_process", ")", ":", "try", ":", "# log.critical(\"check_cpu_interval()\")", "if", "not", "cpu_process", ".", "is_alive", "(", ")", ":", "log", ".", "critical", "(", "\"raise SystemExit, because CPU is not al...
work-a-round for blocking input
[ "work", "-", "a", "-", "round", "for", "blocking", "input" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/periphery.py#L249-L263
6,129
jedie/DragonPy
dragonpy/Dragon32/gui_config.py
BaseTkinterGUIConfig.command_max_delay
def command_max_delay(self, event=None): """ CPU burst max running time - self.runtime_cfg.max_delay """ try: max_delay = self.max_delay_var.get() except ValueError: max_delay = self.runtime_cfg.max_delay if max_delay < 0: max_delay = self.runtime_cfg.max_delay if max_delay > 0.1: max_delay = self.runtime_cfg.max_delay self.runtime_cfg.max_delay = max_delay self.max_delay_var.set(self.runtime_cfg.max_delay)
python
def command_max_delay(self, event=None): try: max_delay = self.max_delay_var.get() except ValueError: max_delay = self.runtime_cfg.max_delay if max_delay < 0: max_delay = self.runtime_cfg.max_delay if max_delay > 0.1: max_delay = self.runtime_cfg.max_delay self.runtime_cfg.max_delay = max_delay self.max_delay_var.set(self.runtime_cfg.max_delay)
[ "def", "command_max_delay", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "max_delay", "=", "self", ".", "max_delay_var", ".", "get", "(", ")", "except", "ValueError", ":", "max_delay", "=", "self", ".", "runtime_cfg", ".", "max_delay", "...
CPU burst max running time - self.runtime_cfg.max_delay
[ "CPU", "burst", "max", "running", "time", "-", "self", ".", "runtime_cfg", ".", "max_delay" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L228-L242
6,130
jedie/DragonPy
dragonpy/Dragon32/gui_config.py
BaseTkinterGUIConfig.command_inner_burst_op_count
def command_inner_burst_op_count(self, event=None): """ CPU burst max running time - self.runtime_cfg.inner_burst_op_count """ try: inner_burst_op_count = self.inner_burst_op_count_var.get() except ValueError: inner_burst_op_count = self.runtime_cfg.inner_burst_op_count if inner_burst_op_count < 1: inner_burst_op_count = self.runtime_cfg.inner_burst_op_count self.runtime_cfg.inner_burst_op_count = inner_burst_op_count self.inner_burst_op_count_var.set(self.runtime_cfg.inner_burst_op_count)
python
def command_inner_burst_op_count(self, event=None): try: inner_burst_op_count = self.inner_burst_op_count_var.get() except ValueError: inner_burst_op_count = self.runtime_cfg.inner_burst_op_count if inner_burst_op_count < 1: inner_burst_op_count = self.runtime_cfg.inner_burst_op_count self.runtime_cfg.inner_burst_op_count = inner_burst_op_count self.inner_burst_op_count_var.set(self.runtime_cfg.inner_burst_op_count)
[ "def", "command_inner_burst_op_count", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "inner_burst_op_count", "=", "self", ".", "inner_burst_op_count_var", ".", "get", "(", ")", "except", "ValueError", ":", "inner_burst_op_count", "=", "self", "."...
CPU burst max running time - self.runtime_cfg.inner_burst_op_count
[ "CPU", "burst", "max", "running", "time", "-", "self", ".", "runtime_cfg", ".", "inner_burst_op_count" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L244-L255
6,131
jedie/DragonPy
dragonpy/Dragon32/gui_config.py
BaseTkinterGUIConfig.command_max_burst_count
def command_max_burst_count(self, event=None): """ max CPU burst op count - self.runtime_cfg.max_burst_count """ try: max_burst_count = self.max_burst_count_var.get() except ValueError: max_burst_count = self.runtime_cfg.max_burst_count if max_burst_count < 1: max_burst_count = self.runtime_cfg.max_burst_count self.runtime_cfg.max_burst_count = max_burst_count self.max_burst_count_var.set(self.runtime_cfg.max_burst_count)
python
def command_max_burst_count(self, event=None): try: max_burst_count = self.max_burst_count_var.get() except ValueError: max_burst_count = self.runtime_cfg.max_burst_count if max_burst_count < 1: max_burst_count = self.runtime_cfg.max_burst_count self.runtime_cfg.max_burst_count = max_burst_count self.max_burst_count_var.set(self.runtime_cfg.max_burst_count)
[ "def", "command_max_burst_count", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "max_burst_count", "=", "self", ".", "max_burst_count_var", ".", "get", "(", ")", "except", "ValueError", ":", "max_burst_count", "=", "self", ".", "runtime_cfg", ...
max CPU burst op count - self.runtime_cfg.max_burst_count
[ "max", "CPU", "burst", "op", "count", "-", "self", ".", "runtime_cfg", ".", "max_burst_count" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L257-L268
6,132
jedie/DragonPy
dragonpy/Dragon32/gui_config.py
BaseTkinterGUIConfig.command_max_run_time
def command_max_run_time(self, event=None): """ CPU burst max running time - self.runtime_cfg.max_run_time """ try: max_run_time = self.max_run_time_var.get() except ValueError: max_run_time = self.runtime_cfg.max_run_time self.runtime_cfg.max_run_time = max_run_time self.max_run_time_var.set(self.runtime_cfg.max_run_time)
python
def command_max_run_time(self, event=None): try: max_run_time = self.max_run_time_var.get() except ValueError: max_run_time = self.runtime_cfg.max_run_time self.runtime_cfg.max_run_time = max_run_time self.max_run_time_var.set(self.runtime_cfg.max_run_time)
[ "def", "command_max_run_time", "(", "self", ",", "event", "=", "None", ")", ":", "try", ":", "max_run_time", "=", "self", ".", "max_run_time_var", ".", "get", "(", ")", "except", "ValueError", ":", "max_run_time", "=", "self", ".", "runtime_cfg", ".", "max...
CPU burst max running time - self.runtime_cfg.max_run_time
[ "CPU", "burst", "max", "running", "time", "-", "self", ".", "runtime_cfg", ".", "max_run_time" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L270-L278
6,133
jedie/DragonPy
dragonpy/utils/pager.py
prompt
def prompt(pagenum): """ Show default prompt to continue and process keypress. It assumes terminal/console understands carriage return \r character. """ prompt = "Page -%s-. Press any key to continue . . . " % pagenum echo(prompt) if getch() in [ESC_, CTRL_C_, 'q', 'Q']: return False echo('\r' + ' '*(len(prompt)-1) + '\r')
python
def prompt(pagenum): prompt = "Page -%s-. Press any key to continue . . . " % pagenum echo(prompt) if getch() in [ESC_, CTRL_C_, 'q', 'Q']: return False echo('\r' + ' '*(len(prompt)-1) + '\r')
[ "def", "prompt", "(", "pagenum", ")", ":", "prompt", "=", "\"Page -%s-. Press any key to continue . . . \"", "%", "pagenum", "echo", "(", "prompt", ")", "if", "getch", "(", ")", "in", "[", "ESC_", ",", "CTRL_C_", ",", "'q'", ",", "'Q'", "]", ":", "return",...
Show default prompt to continue and process keypress. It assumes terminal/console understands carriage return \r character.
[ "Show", "default", "prompt", "to", "continue", "and", "process", "keypress", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L311-L321
6,134
jedie/DragonPy
dragonpy/utils/pager.py
page
def page(content, pagecallback=prompt): """ Output `content`, call `pagecallback` after every page with page number as a parameter. `pagecallback` may return False to terminate pagination. Default callback shows prompt, waits for keypress and aborts on 'q', ESC or Ctrl-C. """ width = getwidth() height = getheight() pagenum = 1 try: try: line = content.next().rstrip("\r\n") except AttributeError: # Python 3 compatibility line = content.__next__().rstrip("\r\n") except StopIteration: pagecallback(pagenum) return while True: # page cycle linesleft = height-1 # leave the last line for the prompt callback while linesleft: linelist = [line[i:i+width] for i in range(0, len(line), width)] if not linelist: linelist = [''] lines2print = min(len(linelist), linesleft) for i in range(lines2print): if WINDOWS and len(line) == width: # avoid extra blank line by skipping linefeed print echo(linelist[i]) else: print((linelist[i])) linesleft -= lines2print linelist = linelist[lines2print:] if linelist: # prepare symbols left on the line for the next iteration line = ''.join(linelist) continue else: try: try: line = content.next().rstrip("\r\n") except AttributeError: # Python 3 compatibility line = content.__next__().rstrip("\r\n") except StopIteration: pagecallback(pagenum) return if pagecallback(pagenum) == False: return pagenum += 1
python
def page(content, pagecallback=prompt): width = getwidth() height = getheight() pagenum = 1 try: try: line = content.next().rstrip("\r\n") except AttributeError: # Python 3 compatibility line = content.__next__().rstrip("\r\n") except StopIteration: pagecallback(pagenum) return while True: # page cycle linesleft = height-1 # leave the last line for the prompt callback while linesleft: linelist = [line[i:i+width] for i in range(0, len(line), width)] if not linelist: linelist = [''] lines2print = min(len(linelist), linesleft) for i in range(lines2print): if WINDOWS and len(line) == width: # avoid extra blank line by skipping linefeed print echo(linelist[i]) else: print((linelist[i])) linesleft -= lines2print linelist = linelist[lines2print:] if linelist: # prepare symbols left on the line for the next iteration line = ''.join(linelist) continue else: try: try: line = content.next().rstrip("\r\n") except AttributeError: # Python 3 compatibility line = content.__next__().rstrip("\r\n") except StopIteration: pagecallback(pagenum) return if pagecallback(pagenum) == False: return pagenum += 1
[ "def", "page", "(", "content", ",", "pagecallback", "=", "prompt", ")", ":", "width", "=", "getwidth", "(", ")", "height", "=", "getheight", "(", ")", "pagenum", "=", "1", "try", ":", "try", ":", "line", "=", "content", ".", "next", "(", ")", ".", ...
Output `content`, call `pagecallback` after every page with page number as a parameter. `pagecallback` may return False to terminate pagination. Default callback shows prompt, waits for keypress and aborts on 'q', ESC or Ctrl-C.
[ "Output", "content", "call", "pagecallback", "after", "every", "page", "with", "page", "number", "as", "a", "parameter", ".", "pagecallback", "may", "return", "False", "to", "terminate", "pagination", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L323-L377
6,135
jedie/DragonPy
dragonpy/sbc09/create_trace.py
reformat_v09_trace
def reformat_v09_trace(raw_trace, max_lines=None): """ reformat v09 trace simmilar to XRoar one and add CC and Memory-Information. Note: v09 traces contains the register info line one trace line later! We reoder it as XRoar done: addr+Opcode with resulted registers """ print() print("Reformat v09 trace...") mem_info = SBC09MemInfo(sys.stderr) result = [] next_update = time.time() + 1 old_line = None for line_no, line in enumerate(raw_trace.splitlines()): if max_lines is not None and line_no >= max_lines: msg = "max lines %i arraived -> Abort." % max_lines print(msg) result.append(msg) break if time.time() > next_update: print("reformat %i trace lines..." % line_no) next_update = time.time() + 1 try: pc = int(line[3:7], 16) op_code = int(line[10:15].strip().replace(" ", ""), 16) cc = int(line[57:59], 16) a = int(line[46:48], 16) b = int(line[51:53], 16) x = int(line[18:22], 16) y = int(line[25:29], 16) u = int(line[32:36], 16) s = int(line[39:43], 16) except ValueError as err: print("Error in line %i: %s" % (line_no, err)) print("Content on line %i:" % line_no) print("-"*79) print(repr(line)) print("-"*79) continue op_data = MC6809OP_DATA_DICT[op_code] mnemonic = op_data["mnemonic"] cc_txt = cc_value2txt(cc) mem = mem_info.get_shortest(pc) # print op_data register_line = "cc=%02x a=%02x b=%02x dp=?? x=%04x y=%04x u=%04x s=%04x| %s" % ( cc, a, b, x, y, u, s, cc_txt ) if old_line is None: line = "(init with: %s)" % register_line else: line = old_line % register_line old_line = "%04x| %-11s %-27s %%s | %s" % ( pc, "%x" % op_code, mnemonic, mem ) result.append(line) print("Done, %i trace lines converted." % line_no) # print raw_trace[:700] return result
python
def reformat_v09_trace(raw_trace, max_lines=None): print() print("Reformat v09 trace...") mem_info = SBC09MemInfo(sys.stderr) result = [] next_update = time.time() + 1 old_line = None for line_no, line in enumerate(raw_trace.splitlines()): if max_lines is not None and line_no >= max_lines: msg = "max lines %i arraived -> Abort." % max_lines print(msg) result.append(msg) break if time.time() > next_update: print("reformat %i trace lines..." % line_no) next_update = time.time() + 1 try: pc = int(line[3:7], 16) op_code = int(line[10:15].strip().replace(" ", ""), 16) cc = int(line[57:59], 16) a = int(line[46:48], 16) b = int(line[51:53], 16) x = int(line[18:22], 16) y = int(line[25:29], 16) u = int(line[32:36], 16) s = int(line[39:43], 16) except ValueError as err: print("Error in line %i: %s" % (line_no, err)) print("Content on line %i:" % line_no) print("-"*79) print(repr(line)) print("-"*79) continue op_data = MC6809OP_DATA_DICT[op_code] mnemonic = op_data["mnemonic"] cc_txt = cc_value2txt(cc) mem = mem_info.get_shortest(pc) # print op_data register_line = "cc=%02x a=%02x b=%02x dp=?? x=%04x y=%04x u=%04x s=%04x| %s" % ( cc, a, b, x, y, u, s, cc_txt ) if old_line is None: line = "(init with: %s)" % register_line else: line = old_line % register_line old_line = "%04x| %-11s %-27s %%s | %s" % ( pc, "%x" % op_code, mnemonic, mem ) result.append(line) print("Done, %i trace lines converted." % line_no) # print raw_trace[:700] return result
[ "def", "reformat_v09_trace", "(", "raw_trace", ",", "max_lines", "=", "None", ")", ":", "print", "(", ")", "print", "(", "\"Reformat v09 trace...\"", ")", "mem_info", "=", "SBC09MemInfo", "(", "sys", ".", "stderr", ")", "result", "=", "[", "]", "next_update"...
reformat v09 trace simmilar to XRoar one and add CC and Memory-Information. Note: v09 traces contains the register info line one trace line later! We reoder it as XRoar done: addr+Opcode with resulted registers
[ "reformat", "v09", "trace", "simmilar", "to", "XRoar", "one", "and", "add", "CC", "and", "Memory", "-", "Information", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/sbc09/create_trace.py#L88-L157
6,136
jedie/DragonPy
PyDC/PyDC/utils.py
human_duration
def human_duration(t): """ Converts a time duration into a friendly text representation. >>> human_duration("type error") Traceback (most recent call last): ... TypeError: human_duration() argument must be integer or float >>> human_duration(0.01) u'10.0 ms' >>> human_duration(0.9) u'900.0 ms' >>> human_duration(65.5) u'1.1 min' >>> human_duration((60 * 60)-1) u'59.0 min' >>> human_duration(60*60) u'1.0 hours' >>> human_duration(1.05*60*60) u'1.1 hours' >>> human_duration(2.54 * 60 * 60 * 24 * 365) u'2.5 years' """ if not isinstance(t, (int, float)): raise TypeError("human_duration() argument must be integer or float") chunks = ( (60 * 60 * 24 * 365, u'years'), (60 * 60 * 24 * 30, u'months'), (60 * 60 * 24 * 7, u'weeks'), (60 * 60 * 24, u'days'), (60 * 60, u'hours'), ) if t < 1: return u"%.1f ms" % round(t * 1000, 1) if t < 60: return u"%.1f sec" % round(t, 1) if t < 60 * 60: return u"%.1f min" % round(t / 60, 1) for seconds, name in chunks: count = t / seconds if count >= 1: count = round(count, 1) break return u"%(number).1f %(type)s" % {'number': count, 'type': name}
python
def human_duration(t): if not isinstance(t, (int, float)): raise TypeError("human_duration() argument must be integer or float") chunks = ( (60 * 60 * 24 * 365, u'years'), (60 * 60 * 24 * 30, u'months'), (60 * 60 * 24 * 7, u'weeks'), (60 * 60 * 24, u'days'), (60 * 60, u'hours'), ) if t < 1: return u"%.1f ms" % round(t * 1000, 1) if t < 60: return u"%.1f sec" % round(t, 1) if t < 60 * 60: return u"%.1f min" % round(t / 60, 1) for seconds, name in chunks: count = t / seconds if count >= 1: count = round(count, 1) break return u"%(number).1f %(type)s" % {'number': count, 'type': name}
[ "def", "human_duration", "(", "t", ")", ":", "if", "not", "isinstance", "(", "t", ",", "(", "int", ",", "float", ")", ")", ":", "raise", "TypeError", "(", "\"human_duration() argument must be integer or float\"", ")", "chunks", "=", "(", "(", "60", "*", "6...
Converts a time duration into a friendly text representation. >>> human_duration("type error") Traceback (most recent call last): ... TypeError: human_duration() argument must be integer or float >>> human_duration(0.01) u'10.0 ms' >>> human_duration(0.9) u'900.0 ms' >>> human_duration(65.5) u'1.1 min' >>> human_duration((60 * 60)-1) u'59.0 min' >>> human_duration(60*60) u'1.0 hours' >>> human_duration(1.05*60*60) u'1.1 hours' >>> human_duration(2.54 * 60 * 60 * 24 * 365) u'2.5 years'
[ "Converts", "a", "time", "duration", "into", "a", "friendly", "text", "representation", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L29-L76
6,137
jedie/DragonPy
PyDC/PyDC/utils.py
average
def average(old_avg, current_value, count): """ Calculate the average. Count must start with 0 >>> average(None, 3.23, 0) 3.23 >>> average(0, 1, 0) 1.0 >>> average(2.5, 5, 4) 3.0 """ if old_avg is None: return current_value return (float(old_avg) * count + current_value) / (count + 1)
python
def average(old_avg, current_value, count): if old_avg is None: return current_value return (float(old_avg) * count + current_value) / (count + 1)
[ "def", "average", "(", "old_avg", ",", "current_value", ",", "count", ")", ":", "if", "old_avg", "is", "None", ":", "return", "current_value", "return", "(", "float", "(", "old_avg", ")", "*", "count", "+", "current_value", ")", "/", "(", "count", "+", ...
Calculate the average. Count must start with 0 >>> average(None, 3.23, 0) 3.23 >>> average(0, 1, 0) 1.0 >>> average(2.5, 5, 4) 3.0
[ "Calculate", "the", "average", ".", "Count", "must", "start", "with", "0" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L111-L124
6,138
jedie/DragonPy
PyDC/PyDC/utils.py
iter_window
def iter_window(g, window_size): """ interate over 'g' bit-by-bit and yield a window with the given 'window_size' width. >>> for v in iter_window([1,2,3,4], window_size=2): v [1, 2] [2, 3] [3, 4] >>> for v in iter_window([1,2,3,4,5], window_size=3): v [1, 2, 3] [2, 3, 4] [3, 4, 5] >>> for v in iter_window([1,2,3,4], window_size=2): ... v ... v.append(True) [1, 2] [2, 3] [3, 4] """ values = collections.deque(maxlen=window_size) for value in g: values.append(value) if len(values) == window_size: yield list(values)
python
def iter_window(g, window_size): values = collections.deque(maxlen=window_size) for value in g: values.append(value) if len(values) == window_size: yield list(values)
[ "def", "iter_window", "(", "g", ",", "window_size", ")", ":", "values", "=", "collections", ".", "deque", "(", "maxlen", "=", "window_size", ")", "for", "value", "in", "g", ":", "values", ".", "append", "(", "value", ")", "if", "len", "(", "values", ...
interate over 'g' bit-by-bit and yield a window with the given 'window_size' width. >>> for v in iter_window([1,2,3,4], window_size=2): v [1, 2] [2, 3] [3, 4] >>> for v in iter_window([1,2,3,4,5], window_size=3): v [1, 2, 3] [2, 3, 4] [3, 4, 5] >>> for v in iter_window([1,2,3,4], window_size=2): ... v ... v.append(True) [1, 2] [2, 3] [3, 4]
[ "interate", "over", "g", "bit", "-", "by", "-", "bit", "and", "yield", "a", "window", "with", "the", "given", "window_size", "width", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L158-L182
6,139
jedie/DragonPy
PyDC/PyDC/utils.py
get_word
def get_word(byte_iterator): """ return a uint16 value >>> g=iter([0x1e, 0x12]) >>> v=get_word(g) >>> v 7698 >>> hex(v) '0x1e12' """ byte_values = list(itertools.islice(byte_iterator, 2)) try: word = (byte_values[0] << 8) | byte_values[1] except TypeError, err: raise TypeError("Can't build word from %s: %s" % (repr(byte_values), err)) return word
python
def get_word(byte_iterator): byte_values = list(itertools.islice(byte_iterator, 2)) try: word = (byte_values[0] << 8) | byte_values[1] except TypeError, err: raise TypeError("Can't build word from %s: %s" % (repr(byte_values), err)) return word
[ "def", "get_word", "(", "byte_iterator", ")", ":", "byte_values", "=", "list", "(", "itertools", ".", "islice", "(", "byte_iterator", ",", "2", ")", ")", "try", ":", "word", "=", "(", "byte_values", "[", "0", "]", "<<", "8", ")", "|", "byte_values", ...
return a uint16 value >>> g=iter([0x1e, 0x12]) >>> v=get_word(g) >>> v 7698 >>> hex(v) '0x1e12'
[ "return", "a", "uint16", "value" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L654-L670
6,140
jedie/DragonPy
dragonpy/utils/starter.py
_run
def _run(*args, **kwargs): """ Run current executable via subprocess and given args """ verbose = kwargs.pop("verbose", False) if verbose: click.secho(" ".join([repr(i) for i in args]), bg='blue', fg='white') executable = args[0] if not os.path.isfile(executable): raise RuntimeError("First argument %r is not a existing file!" % executable) if not os.access(executable, os.X_OK): raise RuntimeError("First argument %r exist, but is not executeable!" % executable) return subprocess.Popen(args, **kwargs)
python
def _run(*args, **kwargs): verbose = kwargs.pop("verbose", False) if verbose: click.secho(" ".join([repr(i) for i in args]), bg='blue', fg='white') executable = args[0] if not os.path.isfile(executable): raise RuntimeError("First argument %r is not a existing file!" % executable) if not os.access(executable, os.X_OK): raise RuntimeError("First argument %r exist, but is not executeable!" % executable) return subprocess.Popen(args, **kwargs)
[ "def", "_run", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "verbose", "=", "kwargs", ".", "pop", "(", "\"verbose\"", ",", "False", ")", "if", "verbose", ":", "click", ".", "secho", "(", "\" \"", ".", "join", "(", "[", "repr", "(", "i", ...
Run current executable via subprocess and given args
[ "Run", "current", "executable", "via", "subprocess", "and", "given", "args" ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/starter.py#L53-L67
6,141
jedie/DragonPy
PyDC/PyDC/CassetteObjects.py
FileContent.add_block_data
def add_block_data(self, block_length, data): """ add a block of tokenized BASIC source code lines. >>> cfg = Dragon32Config >>> fc = FileContent(cfg) >>> block = [ ... 0x1e,0x12,0x0,0xa,0x80,0x20,0x49,0x20,0xcb,0x20,0x31,0x20,0xbc,0x20,0x31,0x30,0x0, ... 0x0,0x0] >>> len(block) 19 >>> fc.add_block_data(19,iter(block)) 19 Bytes parsed >>> fc.print_code_lines() 10 FOR I = 1 TO 10 >>> block = iter([ ... 0x1e,0x29,0x0,0x14,0x87,0x20,0x49,0x3b,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22,0x0, ... 0x0,0x0]) >>> fc.add_block_data(999,block) 25 Bytes parsed ERROR: Block length value 999 is not equal to parsed bytes! >>> fc.print_code_lines() 10 FOR I = 1 TO 10 20 PRINT I;"HELLO WORLD!" >>> block = iter([ ... 0x1e,0x31,0x0,0x1e,0x8b,0x20,0x49,0x0, ... 0x0,0x0]) >>> fc.add_block_data(10,block) 10 Bytes parsed >>> fc.print_code_lines() 10 FOR I = 1 TO 10 20 PRINT I;"HELLO WORLD!" 30 NEXT I Test function tokens in code >>> fc = FileContent(cfg) >>> data = iter([ ... 0x1e,0x4a,0x0,0x1e,0x58,0xcb,0x58,0xc3,0x4c,0xc5,0xff,0x88,0x28,0x52,0x29,0x3a,0x59,0xcb,0x59,0xc3,0x4c,0xc5,0xff,0x89,0x28,0x52,0x29,0x0, ... 0x0,0x0 ... ]) >>> fc.add_block_data(30, data) 30 Bytes parsed >>> fc.print_code_lines() 30 X=X+L*SIN(R):Y=Y+L*COS(R) Test high line numbers >>> fc = FileContent(cfg) >>> data = [ ... 0x1e,0x1a,0x0,0x1,0x87,0x20,0x22,0x4c,0x49,0x4e,0x45,0x20,0x4e,0x55,0x4d,0x42,0x45,0x52,0x20,0x54,0x45,0x53,0x54,0x22,0x0, ... 0x1e,0x23,0x0,0xa,0x87,0x20,0x31,0x30,0x0, ... 0x1e,0x2d,0x0,0x64,0x87,0x20,0x31,0x30,0x30,0x0, ... 0x1e,0x38,0x3,0xe8,0x87,0x20,0x31,0x30,0x30,0x30,0x0, ... 0x1e,0x44,0x27,0x10,0x87,0x20,0x31,0x30,0x30,0x30,0x30,0x0, ... 0x1e,0x50,0x80,0x0,0x87,0x20,0x33,0x32,0x37,0x36,0x38,0x0, ... 0x1e,0x62,0xf9,0xff,0x87,0x20,0x22,0x45,0x4e,0x44,0x22,0x3b,0x36,0x33,0x39,0x39,0x39,0x0,0x0,0x0 ... ] >>> len(data) 99 >>> fc.add_block_data(99, iter(data)) 99 Bytes parsed >>> fc.print_code_lines() 1 PRINT "LINE NUMBER TEST" 10 PRINT 10 100 PRINT 100 1000 PRINT 1000 10000 PRINT 10000 32768 PRINT 32768 63999 PRINT "END";63999 """ # data = list(data) # # print repr(data) # print_as_hex_list(data) # print_codepoint_stream(data) # sys.exit() # create from codepoint list a iterator data = iter(data) byte_count = 0 while True: try: line_pointer = get_word(data) except (StopIteration, IndexError), err: log.error("No line pointer information in code line data. (%s)" % err) break # print "line_pointer:", repr(line_pointer) byte_count += 2 if not line_pointer: # arrived [0x00, 0x00] -> end of block break try: line_number = get_word(data) except (StopIteration, IndexError), err: log.error("No line number information in code line data. (%s)" % err) break # print "line_number:", repr(line_number) byte_count += 2 # data = list(data) # print_as_hex_list(data) # print_codepoint_stream(data) # data = iter(data) # get the code line: # new iterator to get all characters until 0x00 arraived code = iter(data.next, 0x00) code = list(code) # for len() byte_count += len(code) + 1 # from 0x00 consumed in iter() # print_as_hex_list(code) # print_codepoint_stream(code) # convert to a plain ASCII string code = bytes2codeline(code) self.code_lines.append( CodeLine(line_pointer, line_number, code) ) print "%i Bytes parsed" % byte_count if block_length != byte_count: print "ERROR: Block length value %i is not equal to parsed bytes!" % block_length
python
def add_block_data(self, block_length, data): # data = list(data) # # print repr(data) # print_as_hex_list(data) # print_codepoint_stream(data) # sys.exit() # create from codepoint list a iterator data = iter(data) byte_count = 0 while True: try: line_pointer = get_word(data) except (StopIteration, IndexError), err: log.error("No line pointer information in code line data. (%s)" % err) break # print "line_pointer:", repr(line_pointer) byte_count += 2 if not line_pointer: # arrived [0x00, 0x00] -> end of block break try: line_number = get_word(data) except (StopIteration, IndexError), err: log.error("No line number information in code line data. (%s)" % err) break # print "line_number:", repr(line_number) byte_count += 2 # data = list(data) # print_as_hex_list(data) # print_codepoint_stream(data) # data = iter(data) # get the code line: # new iterator to get all characters until 0x00 arraived code = iter(data.next, 0x00) code = list(code) # for len() byte_count += len(code) + 1 # from 0x00 consumed in iter() # print_as_hex_list(code) # print_codepoint_stream(code) # convert to a plain ASCII string code = bytes2codeline(code) self.code_lines.append( CodeLine(line_pointer, line_number, code) ) print "%i Bytes parsed" % byte_count if block_length != byte_count: print "ERROR: Block length value %i is not equal to parsed bytes!" % block_length
[ "def", "add_block_data", "(", "self", ",", "block_length", ",", "data", ")", ":", "# data = list(data)", "# # print repr(data)", "# print_as_hex_list(data)", "# print_codepoint_stream(data)", "# sys.exit()", "# create from codepoint list a iterat...
add a block of tokenized BASIC source code lines. >>> cfg = Dragon32Config >>> fc = FileContent(cfg) >>> block = [ ... 0x1e,0x12,0x0,0xa,0x80,0x20,0x49,0x20,0xcb,0x20,0x31,0x20,0xbc,0x20,0x31,0x30,0x0, ... 0x0,0x0] >>> len(block) 19 >>> fc.add_block_data(19,iter(block)) 19 Bytes parsed >>> fc.print_code_lines() 10 FOR I = 1 TO 10 >>> block = iter([ ... 0x1e,0x29,0x0,0x14,0x87,0x20,0x49,0x3b,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22,0x0, ... 0x0,0x0]) >>> fc.add_block_data(999,block) 25 Bytes parsed ERROR: Block length value 999 is not equal to parsed bytes! >>> fc.print_code_lines() 10 FOR I = 1 TO 10 20 PRINT I;"HELLO WORLD!" >>> block = iter([ ... 0x1e,0x31,0x0,0x1e,0x8b,0x20,0x49,0x0, ... 0x0,0x0]) >>> fc.add_block_data(10,block) 10 Bytes parsed >>> fc.print_code_lines() 10 FOR I = 1 TO 10 20 PRINT I;"HELLO WORLD!" 30 NEXT I Test function tokens in code >>> fc = FileContent(cfg) >>> data = iter([ ... 0x1e,0x4a,0x0,0x1e,0x58,0xcb,0x58,0xc3,0x4c,0xc5,0xff,0x88,0x28,0x52,0x29,0x3a,0x59,0xcb,0x59,0xc3,0x4c,0xc5,0xff,0x89,0x28,0x52,0x29,0x0, ... 0x0,0x0 ... ]) >>> fc.add_block_data(30, data) 30 Bytes parsed >>> fc.print_code_lines() 30 X=X+L*SIN(R):Y=Y+L*COS(R) Test high line numbers >>> fc = FileContent(cfg) >>> data = [ ... 0x1e,0x1a,0x0,0x1,0x87,0x20,0x22,0x4c,0x49,0x4e,0x45,0x20,0x4e,0x55,0x4d,0x42,0x45,0x52,0x20,0x54,0x45,0x53,0x54,0x22,0x0, ... 0x1e,0x23,0x0,0xa,0x87,0x20,0x31,0x30,0x0, ... 0x1e,0x2d,0x0,0x64,0x87,0x20,0x31,0x30,0x30,0x0, ... 0x1e,0x38,0x3,0xe8,0x87,0x20,0x31,0x30,0x30,0x30,0x0, ... 0x1e,0x44,0x27,0x10,0x87,0x20,0x31,0x30,0x30,0x30,0x30,0x0, ... 0x1e,0x50,0x80,0x0,0x87,0x20,0x33,0x32,0x37,0x36,0x38,0x0, ... 0x1e,0x62,0xf9,0xff,0x87,0x20,0x22,0x45,0x4e,0x44,0x22,0x3b,0x36,0x33,0x39,0x39,0x39,0x0,0x0,0x0 ... ] >>> len(data) 99 >>> fc.add_block_data(99, iter(data)) 99 Bytes parsed >>> fc.print_code_lines() 1 PRINT "LINE NUMBER TEST" 10 PRINT 10 100 PRINT 100 1000 PRINT 1000 10000 PRINT 10000 32768 PRINT 32768 63999 PRINT "END";63999
[ "add", "a", "block", "of", "tokenized", "BASIC", "source", "code", "lines", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/CassetteObjects.py#L81-L212
6,142
jedie/DragonPy
PyDC/PyDC/CassetteObjects.py
FileContent.add_ascii_block
def add_ascii_block(self, block_length, data): """ add a block of ASCII BASIC source code lines. >>> data = [ ... 0xd, ... 0x31,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x54,0x45,0x53,0x54,0x22, ... 0xd, ... 0x32,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22, ... 0xd ... ] >>> len(data) 41 >>> fc = FileContent(Dragon32Config) >>> fc.add_ascii_block(41, iter(data)) 41 Bytes parsed >>> fc.print_code_lines() 10 PRINT "TEST" 20 PRINT "HELLO WORLD!" """ data = iter(data) data.next() # Skip first \r byte_count = 1 # incl. first \r while True: code = iter(data.next, 0xd) # until \r code = "".join([chr(c) for c in code]) if not code: log.warning("code ended.") break byte_count += len(code) + 1 # and \r consumed in iter() try: line_number, code = code.split(" ", 1) except ValueError, err: print "\nERROR: Splitting linenumber in %s: %s" % (repr(code), err) break try: line_number = int(line_number) except ValueError, err: print "\nERROR: Part '%s' is not a line number!" % repr(line_number) continue self.code_lines.append( CodeLine(None, line_number, code) ) print "%i Bytes parsed" % byte_count if block_length != byte_count: log.error( "Block length value %i is not equal to parsed bytes!" % block_length )
python
def add_ascii_block(self, block_length, data): data = iter(data) data.next() # Skip first \r byte_count = 1 # incl. first \r while True: code = iter(data.next, 0xd) # until \r code = "".join([chr(c) for c in code]) if not code: log.warning("code ended.") break byte_count += len(code) + 1 # and \r consumed in iter() try: line_number, code = code.split(" ", 1) except ValueError, err: print "\nERROR: Splitting linenumber in %s: %s" % (repr(code), err) break try: line_number = int(line_number) except ValueError, err: print "\nERROR: Part '%s' is not a line number!" % repr(line_number) continue self.code_lines.append( CodeLine(None, line_number, code) ) print "%i Bytes parsed" % byte_count if block_length != byte_count: log.error( "Block length value %i is not equal to parsed bytes!" % block_length )
[ "def", "add_ascii_block", "(", "self", ",", "block_length", ",", "data", ")", ":", "data", "=", "iter", "(", "data", ")", "data", ".", "next", "(", ")", "# Skip first \\r", "byte_count", "=", "1", "# incl. first \\r", "while", "True", ":", "code", "=", "...
add a block of ASCII BASIC source code lines. >>> data = [ ... 0xd, ... 0x31,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x54,0x45,0x53,0x54,0x22, ... 0xd, ... 0x32,0x30,0x20,0x50,0x52,0x49,0x4e,0x54,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22, ... 0xd ... ] >>> len(data) 41 >>> fc = FileContent(Dragon32Config) >>> fc.add_ascii_block(41, iter(data)) 41 Bytes parsed >>> fc.print_code_lines() 10 PRINT "TEST" 20 PRINT "HELLO WORLD!"
[ "add", "a", "block", "of", "ASCII", "BASIC", "source", "code", "lines", "." ]
6659e5b5133aab26979a498ee7453495773a4f6c
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/CassetteObjects.py#L214-L268
6,143
mansam/validator.py
validator/__init__.py
validate
def validate(validation, dictionary): """ Validate that a dictionary passes a set of key-based validators. If all of the keys in the dictionary are within the parameters specified by the validation mapping, then the validation passes. :param validation: a mapping of keys to validators :type validation: dict :param dictionary: dictionary to be validated :type dictionary: dict :return: a tuple containing a bool indicating success or failure and a mapping of fields to error messages. """ errors = defaultdict(list) for key in validation: if isinstance(validation[key], (list, tuple)): if Required in validation[key]: if not Required(key, dictionary): errors[key] = ["must be present"] continue _validate_list_helper(validation, dictionary, key, errors) else: v = validation[key] if v == Required: if not Required(key, dictionary): errors[key] = ["must be present"] else: _validate_and_store_errs(v, dictionary, key, errors) if len(errors) > 0: # `errors` gets downgraded from defaultdict to dict # because it makes for prettier output return ValidationResult(valid=False, errors=dict(errors)) else: return ValidationResult(valid=True, errors={})
python
def validate(validation, dictionary): errors = defaultdict(list) for key in validation: if isinstance(validation[key], (list, tuple)): if Required in validation[key]: if not Required(key, dictionary): errors[key] = ["must be present"] continue _validate_list_helper(validation, dictionary, key, errors) else: v = validation[key] if v == Required: if not Required(key, dictionary): errors[key] = ["must be present"] else: _validate_and_store_errs(v, dictionary, key, errors) if len(errors) > 0: # `errors` gets downgraded from defaultdict to dict # because it makes for prettier output return ValidationResult(valid=False, errors=dict(errors)) else: return ValidationResult(valid=True, errors={})
[ "def", "validate", "(", "validation", ",", "dictionary", ")", ":", "errors", "=", "defaultdict", "(", "list", ")", "for", "key", "in", "validation", ":", "if", "isinstance", "(", "validation", "[", "key", "]", ",", "(", "list", ",", "tuple", ")", ")", ...
Validate that a dictionary passes a set of key-based validators. If all of the keys in the dictionary are within the parameters specified by the validation mapping, then the validation passes. :param validation: a mapping of keys to validators :type validation: dict :param dictionary: dictionary to be validated :type dictionary: dict :return: a tuple containing a bool indicating success or failure and a mapping of fields to error messages.
[ "Validate", "that", "a", "dictionary", "passes", "a", "set", "of", "key", "-", "based", "validators", ".", "If", "all", "of", "the", "keys", "in", "the", "dictionary", "are", "within", "the", "parameters", "specified", "by", "the", "validation", "mapping", ...
247f99c539c5c9aef3e5a6063026c687b8499090
https://github.com/mansam/validator.py/blob/247f99c539c5c9aef3e5a6063026c687b8499090/validator/__init__.py#L635-L675
6,144
mansam/validator.py
validator/ext/__init__.py
ArgSpec
def ArgSpec(*args, **kwargs): """ Validate a function based on the given argspec. # Example: validations = { "foo": [ArgSpec("a", "b", c", bar="baz")] } def pass_func(a, b, c, bar="baz"): pass def fail_func(b, c, a, baz="bar"): pass passes = {"foo": pass_func} fails = {"foo": fail_func} """ def argspec_lambda(value): argspec = getargspec(value) argspec_kw_vals = () if argspec.defaults is not None: argspec_kw_vals = argspec.defaults kw_vals = {} arg_offset = 0 arg_len = len(argspec.args) - 1 for val in argspec_kw_vals[::-1]: kw_vals[argspec.args[arg_len - arg_offset]] = val arg_offset += 1 if kwargs == kw_vals: if len(args) != arg_len - arg_offset + 1: return False index = 0 for arg in args: if argspec.args[index] != arg: return False index += 1 return True return False argspec_lambda.err_message = "must match argspec ({0}) {{{1}}}".format(args, kwargs) # as little sense as negating this makes, best to just be consistent. argspec_lambda.not_message = "must not match argspec ({0}) {{{1}}}".format(args, kwargs) return argspec_lambda
python
def ArgSpec(*args, **kwargs): def argspec_lambda(value): argspec = getargspec(value) argspec_kw_vals = () if argspec.defaults is not None: argspec_kw_vals = argspec.defaults kw_vals = {} arg_offset = 0 arg_len = len(argspec.args) - 1 for val in argspec_kw_vals[::-1]: kw_vals[argspec.args[arg_len - arg_offset]] = val arg_offset += 1 if kwargs == kw_vals: if len(args) != arg_len - arg_offset + 1: return False index = 0 for arg in args: if argspec.args[index] != arg: return False index += 1 return True return False argspec_lambda.err_message = "must match argspec ({0}) {{{1}}}".format(args, kwargs) # as little sense as negating this makes, best to just be consistent. argspec_lambda.not_message = "must not match argspec ({0}) {{{1}}}".format(args, kwargs) return argspec_lambda
[ "def", "ArgSpec", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "argspec_lambda", "(", "value", ")", ":", "argspec", "=", "getargspec", "(", "value", ")", "argspec_kw_vals", "=", "(", ")", "if", "argspec", ".", "defaults", "is", "not", ...
Validate a function based on the given argspec. # Example: validations = { "foo": [ArgSpec("a", "b", c", bar="baz")] } def pass_func(a, b, c, bar="baz"): pass def fail_func(b, c, a, baz="bar"): pass passes = {"foo": pass_func} fails = {"foo": fail_func}
[ "Validate", "a", "function", "based", "on", "the", "given", "argspec", "." ]
247f99c539c5c9aef3e5a6063026c687b8499090
https://github.com/mansam/validator.py/blob/247f99c539c5c9aef3e5a6063026c687b8499090/validator/ext/__init__.py#L35-L76
6,145
quantifiedcode/checkmate
checkmate/contrib/plugins/git/models.py
GitRepository.get_snapshots
def get_snapshots(self,**kwargs): """ Returns a list of snapshots in a given repository. """ commits = self.repository.get_commits(**kwargs) snapshots = [] for commit in commits: for key in ('committer_date','author_date'): commit[key] = datetime.datetime.fromtimestamp(commit[key+'_ts']) snapshot = GitSnapshot(commit) hasher = Hasher() hasher.add(snapshot.sha) snapshot.hash = hasher.digest.hexdigest() snapshot.project = self.project snapshot.pk = uuid.uuid4().hex snapshots.append(snapshot) return snapshots
python
def get_snapshots(self,**kwargs): commits = self.repository.get_commits(**kwargs) snapshots = [] for commit in commits: for key in ('committer_date','author_date'): commit[key] = datetime.datetime.fromtimestamp(commit[key+'_ts']) snapshot = GitSnapshot(commit) hasher = Hasher() hasher.add(snapshot.sha) snapshot.hash = hasher.digest.hexdigest() snapshot.project = self.project snapshot.pk = uuid.uuid4().hex snapshots.append(snapshot) return snapshots
[ "def", "get_snapshots", "(", "self", ",", "*", "*", "kwargs", ")", ":", "commits", "=", "self", ".", "repository", ".", "get_commits", "(", "*", "*", "kwargs", ")", "snapshots", "=", "[", "]", "for", "commit", "in", "commits", ":", "for", "key", "in"...
Returns a list of snapshots in a given repository.
[ "Returns", "a", "list", "of", "snapshots", "in", "a", "given", "repository", "." ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/contrib/plugins/git/models.py#L70-L86
6,146
quantifiedcode/checkmate
checkmate/lib/code/environment.py
diff_objects
def diff_objects(objects_a,objects_b,key,comparator = None,with_unchanged = False): """ Returns a "diff" between two lists of objects. :param key: The key that identifies objects with identical location in each set, such as files with the same path or code objects with the same URL. :param comparator: Comparison functions that decides if two objects are identical. """ objects_by_key = {'a' :defaultdict(list), 'b' : defaultdict(list)} for name,objects in ('a',objects_a),('b',objects_b): d = objects_by_key[name] for obj in objects: d[key(obj)].append(obj) added_objects = [obj for key,objs in objects_by_key['b'].items() if key not in objects_by_key['a'] for obj in objs] deleted_objects = [obj for key,objs in objects_by_key['a'].items() if key not in objects_by_key['b'] for obj in objs] joint_keys = [key for key in objects_by_key['a'] if key in objects_by_key['b']] modified_objects = [] #we go through the keys that exist in both object sets for key in joint_keys: objects_a = objects_by_key['a'][key] objects_b = objects_by_key['b'][key] if len(objects_a) > 1 or len(objects_b) > 1: #this is an ambiguous situation: we have more than one object for the same #key, so we have to decide which ones have been added or not #we try to remove identical objects from the set objects_a_copy = objects_a[:] objects_b_copy = objects_b[:] #for the next step, we need a comparator if comparator: #we iterate through the list and try to find different objects... for obj_a in objects_a: for obj_b in objects_b_copy: if comparator(obj_a,obj_b) == 0: #these objects are identical, we remove them from both sets... objects_a_copy.remove(obj_a) objects_b_copy.remove(obj_b) break #here we cannot distinguish objects... if len(objects_b_copy) > len(objects_a_copy): #we arbitrarily mark the last objects in objects_b as added added_objects.extend(objects_b_copy[len(objects_a_copy):]) elif len(objects_a_copy) > len(objects_b_copy): #we arbitrarily mark the last objects in objects_a as deleted deleted_objects.extend(objects_a_copy[len(objects_b_copy):]) else: if comparator and comparator(objects_a[0],objects_b[0]) != 0: #these objects are different modified_objects.append(objects_a[0]) result = { 'added' : added_objects, 'deleted' : deleted_objects, 'modified' : modified_objects, } if with_unchanged: unchanged_objects = [objects_b_by_key[key] for key in joint_keys if not objects_b_by_key[key] in modified_objects] result['unchanged'] = unchanged_objects return result
python
def diff_objects(objects_a,objects_b,key,comparator = None,with_unchanged = False): objects_by_key = {'a' :defaultdict(list), 'b' : defaultdict(list)} for name,objects in ('a',objects_a),('b',objects_b): d = objects_by_key[name] for obj in objects: d[key(obj)].append(obj) added_objects = [obj for key,objs in objects_by_key['b'].items() if key not in objects_by_key['a'] for obj in objs] deleted_objects = [obj for key,objs in objects_by_key['a'].items() if key not in objects_by_key['b'] for obj in objs] joint_keys = [key for key in objects_by_key['a'] if key in objects_by_key['b']] modified_objects = [] #we go through the keys that exist in both object sets for key in joint_keys: objects_a = objects_by_key['a'][key] objects_b = objects_by_key['b'][key] if len(objects_a) > 1 or len(objects_b) > 1: #this is an ambiguous situation: we have more than one object for the same #key, so we have to decide which ones have been added or not #we try to remove identical objects from the set objects_a_copy = objects_a[:] objects_b_copy = objects_b[:] #for the next step, we need a comparator if comparator: #we iterate through the list and try to find different objects... for obj_a in objects_a: for obj_b in objects_b_copy: if comparator(obj_a,obj_b) == 0: #these objects are identical, we remove them from both sets... objects_a_copy.remove(obj_a) objects_b_copy.remove(obj_b) break #here we cannot distinguish objects... if len(objects_b_copy) > len(objects_a_copy): #we arbitrarily mark the last objects in objects_b as added added_objects.extend(objects_b_copy[len(objects_a_copy):]) elif len(objects_a_copy) > len(objects_b_copy): #we arbitrarily mark the last objects in objects_a as deleted deleted_objects.extend(objects_a_copy[len(objects_b_copy):]) else: if comparator and comparator(objects_a[0],objects_b[0]) != 0: #these objects are different modified_objects.append(objects_a[0]) result = { 'added' : added_objects, 'deleted' : deleted_objects, 'modified' : modified_objects, } if with_unchanged: unchanged_objects = [objects_b_by_key[key] for key in joint_keys if not objects_b_by_key[key] in modified_objects] result['unchanged'] = unchanged_objects return result
[ "def", "diff_objects", "(", "objects_a", ",", "objects_b", ",", "key", ",", "comparator", "=", "None", ",", "with_unchanged", "=", "False", ")", ":", "objects_by_key", "=", "{", "'a'", ":", "defaultdict", "(", "list", ")", ",", "'b'", ":", "defaultdict", ...
Returns a "diff" between two lists of objects. :param key: The key that identifies objects with identical location in each set, such as files with the same path or code objects with the same URL. :param comparator: Comparison functions that decides if two objects are identical.
[ "Returns", "a", "diff", "between", "two", "lists", "of", "objects", "." ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/lib/code/environment.py#L46-L123
6,147
quantifiedcode/checkmate
checkmate/lib/code/environment.py
CodeEnvironment.save_file_revisions
def save_file_revisions(self,snapshot,file_revisions): """ We convert various items in the file revision to documents, so that we can easily search and retrieve them... """ annotations = defaultdict(list) for file_revision in file_revisions: issues_results = {} for analyzer_name,results in file_revision.results.items(): if 'issues' in results: issues_results[analyzer_name] = results['issues'] del results['issues'] if len(issues_results) > 1000: issues_results[analyzer_name] = [{ 'code' : 'TooManyIssues', 'analyzer' : analyzer_name, }] with self.project.backend.transaction(): self.project.backend.save(file_revision) def location_sorter(issue): if issue['location'] and issue['location'][0] and issue['location'][0][0]: return issue['location'][0][0][0] return 0 with self.project.backend.transaction(): for analyzer_name,issues in issues_results.items(): grouped_issues = group_issues_by_fingerprint(issues) for issue_dict in grouped_issues: hasher = Hasher() hasher.add(analyzer_name) hasher.add(issue_dict['code']) hasher.add(issue_dict['fingerprint']) issue_dict['hash'] = hasher.digest.hexdigest() try: #we check if the issue already exists issue = self.project.backend.get(Issue,{'hash' : issue_dict['hash'], 'project' : self.project }) except Issue.DoesNotExist: #if not, we create it d = issue_dict.copy() d['analyzer'] = analyzer_name if 'location' in d: del d['location'] if 'occurrences' in d: del d['occurrences'] issue = Issue(d) issue.project = self.project self.project.backend.save(issue) for occurrence in issue_dict['occurrences']: hasher = Hasher() hasher.add(file_revision.hash) hasher.add(issue.hash) hasher.add(occurrence.get('from_row')) hasher.add(occurrence.get('from_column')) hasher.add(occurrence.get('to_row')) hasher.add(occurrence.get('to_column')) hasher.add(occurrence.get('sequence')) occurrence['hash'] = hasher.digest.hexdigest() try: #we check if the occurrence already exists occurrence = self.project.backend.get(IssueOccurrence,{'hash' : occurrence['hash'], 'issue' : issue }) except IssueOccurrence.DoesNotExist: #if not, we create it occurrence = IssueOccurrence(occurrence) occurrence.issue = issue occurrence.file_revision = file_revision self.project.backend.save(occurrence) annotations['occurrences'].append(occurrence) annotations['issues'].append(issue) return annotations
python
def save_file_revisions(self,snapshot,file_revisions): annotations = defaultdict(list) for file_revision in file_revisions: issues_results = {} for analyzer_name,results in file_revision.results.items(): if 'issues' in results: issues_results[analyzer_name] = results['issues'] del results['issues'] if len(issues_results) > 1000: issues_results[analyzer_name] = [{ 'code' : 'TooManyIssues', 'analyzer' : analyzer_name, }] with self.project.backend.transaction(): self.project.backend.save(file_revision) def location_sorter(issue): if issue['location'] and issue['location'][0] and issue['location'][0][0]: return issue['location'][0][0][0] return 0 with self.project.backend.transaction(): for analyzer_name,issues in issues_results.items(): grouped_issues = group_issues_by_fingerprint(issues) for issue_dict in grouped_issues: hasher = Hasher() hasher.add(analyzer_name) hasher.add(issue_dict['code']) hasher.add(issue_dict['fingerprint']) issue_dict['hash'] = hasher.digest.hexdigest() try: #we check if the issue already exists issue = self.project.backend.get(Issue,{'hash' : issue_dict['hash'], 'project' : self.project }) except Issue.DoesNotExist: #if not, we create it d = issue_dict.copy() d['analyzer'] = analyzer_name if 'location' in d: del d['location'] if 'occurrences' in d: del d['occurrences'] issue = Issue(d) issue.project = self.project self.project.backend.save(issue) for occurrence in issue_dict['occurrences']: hasher = Hasher() hasher.add(file_revision.hash) hasher.add(issue.hash) hasher.add(occurrence.get('from_row')) hasher.add(occurrence.get('from_column')) hasher.add(occurrence.get('to_row')) hasher.add(occurrence.get('to_column')) hasher.add(occurrence.get('sequence')) occurrence['hash'] = hasher.digest.hexdigest() try: #we check if the occurrence already exists occurrence = self.project.backend.get(IssueOccurrence,{'hash' : occurrence['hash'], 'issue' : issue }) except IssueOccurrence.DoesNotExist: #if not, we create it occurrence = IssueOccurrence(occurrence) occurrence.issue = issue occurrence.file_revision = file_revision self.project.backend.save(occurrence) annotations['occurrences'].append(occurrence) annotations['issues'].append(issue) return annotations
[ "def", "save_file_revisions", "(", "self", ",", "snapshot", ",", "file_revisions", ")", ":", "annotations", "=", "defaultdict", "(", "list", ")", "for", "file_revision", "in", "file_revisions", ":", "issues_results", "=", "{", "}", "for", "analyzer_name", ",", ...
We convert various items in the file revision to documents, so that we can easily search and retrieve them...
[ "We", "convert", "various", "items", "in", "the", "file", "revision", "to", "documents", "so", "that", "we", "can", "easily", "search", "and", "retrieve", "them", "..." ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/lib/code/environment.py#L691-L774
6,148
quantifiedcode/checkmate
checkmate/helpers/settings.py
update
def update(d,ud): """ Recursively merge the values of ud into d. """ if ud is None: return for key,value in ud.items(): if not key in d: d[key] = value elif isinstance(value,dict): update(d[key],value) else: d[key] = value
python
def update(d,ud): if ud is None: return for key,value in ud.items(): if not key in d: d[key] = value elif isinstance(value,dict): update(d[key],value) else: d[key] = value
[ "def", "update", "(", "d", ",", "ud", ")", ":", "if", "ud", "is", "None", ":", "return", "for", "key", ",", "value", "in", "ud", ".", "items", "(", ")", ":", "if", "not", "key", "in", "d", ":", "d", "[", "key", "]", "=", "value", "elif", "i...
Recursively merge the values of ud into d.
[ "Recursively", "merge", "the", "values", "of", "ud", "into", "d", "." ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/helpers/settings.py#L2-L14
6,149
quantifiedcode/checkmate
checkmate/contrib/plugins/git/commands/init.py
Command.find_git_repository
def find_git_repository(self, path): """ Tries to find a directory with a .git repository """ while path is not None: git_path = os.path.join(path,'.git') if os.path.exists(git_path) and os.path.isdir(git_path): return path path = os.path.dirname(path) return None
python
def find_git_repository(self, path): while path is not None: git_path = os.path.join(path,'.git') if os.path.exists(git_path) and os.path.isdir(git_path): return path path = os.path.dirname(path) return None
[ "def", "find_git_repository", "(", "self", ",", "path", ")", ":", "while", "path", "is", "not", "None", ":", "git_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'.git'", ")", "if", "os", ".", "path", ".", "exists", "(", "git_path", ...
Tries to find a directory with a .git repository
[ "Tries", "to", "find", "a", "directory", "with", "a", ".", "git", "repository" ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/contrib/plugins/git/commands/init.py#L26-L35
6,150
quantifiedcode/checkmate
checkmate/helpers/hashing.py
get_hash
def get_hash(node,fields = None,exclude = ['pk','_id'],target = 'pk'): """ Here we generate a unique hash for a given node in the syntax tree. """ hasher = Hasher() def add_to_hash(value): if isinstance(value,dict): if target in value: add_to_hash(value[target]) else: attribute_list = [] for key,v in sorted(value.items(),key = lambda x: x[0]): if (fields is not None and key not in fields) \ or (exclude is not None and key in exclude): continue add_to_hash(key) add_to_hash(v) elif isinstance(value,(tuple,list)) and value and isinstance(value[0],(dict,node_class)): for i,v in enumerate(value): hasher.add(i) add_to_hash(v) else: hasher.add(value) add_to_hash(node) return hasher.digest.hexdigest()
python
def get_hash(node,fields = None,exclude = ['pk','_id'],target = 'pk'): hasher = Hasher() def add_to_hash(value): if isinstance(value,dict): if target in value: add_to_hash(value[target]) else: attribute_list = [] for key,v in sorted(value.items(),key = lambda x: x[0]): if (fields is not None and key not in fields) \ or (exclude is not None and key in exclude): continue add_to_hash(key) add_to_hash(v) elif isinstance(value,(tuple,list)) and value and isinstance(value[0],(dict,node_class)): for i,v in enumerate(value): hasher.add(i) add_to_hash(v) else: hasher.add(value) add_to_hash(node) return hasher.digest.hexdigest()
[ "def", "get_hash", "(", "node", ",", "fields", "=", "None", ",", "exclude", "=", "[", "'pk'", ",", "'_id'", "]", ",", "target", "=", "'pk'", ")", ":", "hasher", "=", "Hasher", "(", ")", "def", "add_to_hash", "(", "value", ")", ":", "if", "isinstanc...
Here we generate a unique hash for a given node in the syntax tree.
[ "Here", "we", "generate", "a", "unique", "hash", "for", "a", "given", "node", "in", "the", "syntax", "tree", "." ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/helpers/hashing.py#L35-L65
6,151
quantifiedcode/checkmate
checkmate/contrib/plugins/python/pylint/analyzer.py
Reporter.add_message
def add_message(self, msg_id, location, msg): """Client API to send a message""" self._messages.append((msg_id,location,msg))
python
def add_message(self, msg_id, location, msg): self._messages.append((msg_id,location,msg))
[ "def", "add_message", "(", "self", ",", "msg_id", ",", "location", ",", "msg", ")", ":", "self", ".", "_messages", ".", "append", "(", "(", "msg_id", ",", "location", ",", "msg", ")", ")" ]
Client API to send a message
[ "Client", "API", "to", "send", "a", "message" ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/contrib/plugins/python/pylint/analyzer.py#L99-L102
6,152
quantifiedcode/checkmate
checkmate/lib/analysis/base.py
BaseAnalyzer.get_fingerprint_from_code
def get_fingerprint_from_code(self,file_revision,location, extra_data=None): """ This function generates a fingerprint from a series of code snippets. Can be used by derived analyzers to generate fingerprints based on code if nothing better is available. """ code = file_revision.get_file_content() if not isinstance(code,unicode): code = unicode(code,errors = 'ignore') lines = code.split(u"\n") s = "" for l in location: ((from_row,from_column),(to_row,to_column)) = l if from_column is None: continue if from_row == to_row: s+=lines[from_row-1][from_column:to_column] else: if to_row < from_row: raise ValueError("from_row must be smaller than to_row") s+=lines[from_row-1][from_column:] current_row = from_row+1 while current_row < to_row: s+=lines[current_row-1] current_row+=1 s+=lines[current_row-1][:to_column] hasher = Hasher() hasher.add(s) if extra_data is not None: hasher.add(extra_data) return hasher.digest.hexdigest()
python
def get_fingerprint_from_code(self,file_revision,location, extra_data=None): code = file_revision.get_file_content() if not isinstance(code,unicode): code = unicode(code,errors = 'ignore') lines = code.split(u"\n") s = "" for l in location: ((from_row,from_column),(to_row,to_column)) = l if from_column is None: continue if from_row == to_row: s+=lines[from_row-1][from_column:to_column] else: if to_row < from_row: raise ValueError("from_row must be smaller than to_row") s+=lines[from_row-1][from_column:] current_row = from_row+1 while current_row < to_row: s+=lines[current_row-1] current_row+=1 s+=lines[current_row-1][:to_column] hasher = Hasher() hasher.add(s) if extra_data is not None: hasher.add(extra_data) return hasher.digest.hexdigest()
[ "def", "get_fingerprint_from_code", "(", "self", ",", "file_revision", ",", "location", ",", "extra_data", "=", "None", ")", ":", "code", "=", "file_revision", ".", "get_file_content", "(", ")", "if", "not", "isinstance", "(", "code", ",", "unicode", ")", ":...
This function generates a fingerprint from a series of code snippets. Can be used by derived analyzers to generate fingerprints based on code if nothing better is available.
[ "This", "function", "generates", "a", "fingerprint", "from", "a", "series", "of", "code", "snippets", "." ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/lib/analysis/base.py#L34-L68
6,153
quantifiedcode/checkmate
checkmate/lib/models.py
Project.get_issue_classes
def get_issue_classes(self,backend = None,enabled = True,sort = None,**kwargs): """ Retrieves the issue classes for a given backend :param backend: A backend to use. If None, the default backend will be used :param enabled: Whether to retrieve enabled or disabled issue classes. Passing `None` will retrieve all issue classes. """ if backend is None: backend = self.backend query = {'project_issue_classes.project' : self} if enabled is not None: query['project_issue_classes.enabled'] = enabled issue_classes = backend.filter(self.IssueClass,query, **kwargs) if sort is not None: issue_classes = issue_classes.sort(sort) return issue_classes
python
def get_issue_classes(self,backend = None,enabled = True,sort = None,**kwargs): if backend is None: backend = self.backend query = {'project_issue_classes.project' : self} if enabled is not None: query['project_issue_classes.enabled'] = enabled issue_classes = backend.filter(self.IssueClass,query, **kwargs) if sort is not None: issue_classes = issue_classes.sort(sort) return issue_classes
[ "def", "get_issue_classes", "(", "self", ",", "backend", "=", "None", ",", "enabled", "=", "True", ",", "sort", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "backend", "is", "None", ":", "backend", "=", "self", ".", "backend", "query", "=", ...
Retrieves the issue classes for a given backend :param backend: A backend to use. If None, the default backend will be used :param enabled: Whether to retrieve enabled or disabled issue classes. Passing `None` will retrieve all issue classes.
[ "Retrieves", "the", "issue", "classes", "for", "a", "given", "backend" ]
1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2
https://github.com/quantifiedcode/checkmate/blob/1a4d010c8ef25c678d8d14dc8e37a9bed1883ca2/checkmate/lib/models.py#L413-L435
6,154
thombashi/pathvalidate
pathvalidate/_symbol.py
replace_symbol
def replace_symbol(text, replacement_text="", is_replace_consecutive_chars=False, is_strip=False): """ Replace all of the symbols in the ``text``. :param str text: Input text. :param str replacement_text: Replacement text. :return: A replacement string. :rtype: str :Examples: :ref:`example-sanitize-symbol` """ try: new_text = __RE_SYMBOL.sub(replacement_text, preprocess(text)) except (TypeError, AttributeError): raise TypeError("text must be a string") if not replacement_text: return new_text if is_replace_consecutive_chars: new_text = re.sub("{}+".format(re.escape(replacement_text)), replacement_text, new_text) if is_strip: new_text = new_text.strip(replacement_text) return new_text
python
def replace_symbol(text, replacement_text="", is_replace_consecutive_chars=False, is_strip=False): try: new_text = __RE_SYMBOL.sub(replacement_text, preprocess(text)) except (TypeError, AttributeError): raise TypeError("text must be a string") if not replacement_text: return new_text if is_replace_consecutive_chars: new_text = re.sub("{}+".format(re.escape(replacement_text)), replacement_text, new_text) if is_strip: new_text = new_text.strip(replacement_text) return new_text
[ "def", "replace_symbol", "(", "text", ",", "replacement_text", "=", "\"\"", ",", "is_replace_consecutive_chars", "=", "False", ",", "is_strip", "=", "False", ")", ":", "try", ":", "new_text", "=", "__RE_SYMBOL", ".", "sub", "(", "replacement_text", ",", "prepr...
Replace all of the symbols in the ``text``. :param str text: Input text. :param str replacement_text: Replacement text. :return: A replacement string. :rtype: str :Examples: :ref:`example-sanitize-symbol`
[ "Replace", "all", "of", "the", "symbols", "in", "the", "text", "." ]
22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef
https://github.com/thombashi/pathvalidate/blob/22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef/pathvalidate/_symbol.py#L50-L78
6,155
thombashi/pathvalidate
pathvalidate/_file.py
validate_filename
def validate_filename(filename, platform=None, min_len=1, max_len=_DEFAULT_MAX_FILENAME_LEN): """Verifying whether the ``filename`` is a valid file name or not. Args: filename (str): Filename to validate. platform (str, optional): .. include:: platform.txt min_len (int, optional): Minimum length of the ``filename``. The value must be greater or equal to one. Defaults to ``1``. max_len (int, optional): Maximum length the ``filename``. The value must be lower than: - ``Linux``: 4096 - ``macOS``: 1024 - ``Windows``: 260 - ``Universal``: 260 Defaults to ``255``. Raises: InvalidLengthError: If the ``filename`` is longer than ``max_len`` characters. InvalidCharError: If the ``filename`` includes invalid character(s) for a filename: |invalid_filename_chars|. The following characters are also invalid for Windows platform: |invalid_win_filename_chars|. ReservedNameError: If the ``filename`` equals reserved name by OS. Windows reserved name is as follows: ``"CON"``, ``"PRN"``, ``"AUX"``, ``"NUL"``, ``"COM[1-9]"``, ``"LPT[1-9]"``. Example: :ref:`example-validate-filename` See Also: `Naming Files, Paths, and Namespaces (Windows) <https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx>`__ """ FileNameSanitizer(platform=platform, min_len=min_len, max_len=max_len).validate(filename)
python
def validate_filename(filename, platform=None, min_len=1, max_len=_DEFAULT_MAX_FILENAME_LEN): FileNameSanitizer(platform=platform, min_len=min_len, max_len=max_len).validate(filename)
[ "def", "validate_filename", "(", "filename", ",", "platform", "=", "None", ",", "min_len", "=", "1", ",", "max_len", "=", "_DEFAULT_MAX_FILENAME_LEN", ")", ":", "FileNameSanitizer", "(", "platform", "=", "platform", ",", "min_len", "=", "min_len", ",", "max_le...
Verifying whether the ``filename`` is a valid file name or not. Args: filename (str): Filename to validate. platform (str, optional): .. include:: platform.txt min_len (int, optional): Minimum length of the ``filename``. The value must be greater or equal to one. Defaults to ``1``. max_len (int, optional): Maximum length the ``filename``. The value must be lower than: - ``Linux``: 4096 - ``macOS``: 1024 - ``Windows``: 260 - ``Universal``: 260 Defaults to ``255``. Raises: InvalidLengthError: If the ``filename`` is longer than ``max_len`` characters. InvalidCharError: If the ``filename`` includes invalid character(s) for a filename: |invalid_filename_chars|. The following characters are also invalid for Windows platform: |invalid_win_filename_chars|. ReservedNameError: If the ``filename`` equals reserved name by OS. Windows reserved name is as follows: ``"CON"``, ``"PRN"``, ``"AUX"``, ``"NUL"``, ``"COM[1-9]"``, ``"LPT[1-9]"``. Example: :ref:`example-validate-filename` See Also: `Naming Files, Paths, and Namespaces (Windows) <https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx>`__
[ "Verifying", "whether", "the", "filename", "is", "a", "valid", "file", "name", "or", "not", "." ]
22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef
https://github.com/thombashi/pathvalidate/blob/22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef/pathvalidate/_file.py#L432-L474
6,156
thombashi/pathvalidate
pathvalidate/_file.py
validate_filepath
def validate_filepath(file_path, platform=None, min_len=1, max_len=None): """Verifying whether the ``file_path`` is a valid file path or not. Args: file_path (str): File path to validate. platform (str, optional): .. include:: platform.txt min_len (int, optional): Minimum length of the ``file_path``. The value must be greater or equal to one. Defaults to ``1``. max_len (int, optional): Maximum length of the ``file_path`` length. If the value is |None|, in the default, automatically determined by the ``platform``: - ``Linux``: 4096 - ``macOS``: 1024 - ``Windows``: 260 Raises: NullNameError: If the ``file_path`` is empty. InvalidCharError: If the ``file_path`` includes invalid char(s): |invalid_file_path_chars|. The following characters are also invalid for Windows platform: |invalid_win_file_path_chars| InvalidLengthError: If the ``file_path`` is longer than ``max_len`` characters. Example: :ref:`example-validate-file-path` See Also: `Naming Files, Paths, and Namespaces (Windows) <https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx>`__ """ FilePathSanitizer(platform=platform, min_len=min_len, max_len=max_len).validate(file_path)
python
def validate_filepath(file_path, platform=None, min_len=1, max_len=None): FilePathSanitizer(platform=platform, min_len=min_len, max_len=max_len).validate(file_path)
[ "def", "validate_filepath", "(", "file_path", ",", "platform", "=", "None", ",", "min_len", "=", "1", ",", "max_len", "=", "None", ")", ":", "FilePathSanitizer", "(", "platform", "=", "platform", ",", "min_len", "=", "min_len", ",", "max_len", "=", "max_le...
Verifying whether the ``file_path`` is a valid file path or not. Args: file_path (str): File path to validate. platform (str, optional): .. include:: platform.txt min_len (int, optional): Minimum length of the ``file_path``. The value must be greater or equal to one. Defaults to ``1``. max_len (int, optional): Maximum length of the ``file_path`` length. If the value is |None|, in the default, automatically determined by the ``platform``: - ``Linux``: 4096 - ``macOS``: 1024 - ``Windows``: 260 Raises: NullNameError: If the ``file_path`` is empty. InvalidCharError: If the ``file_path`` includes invalid char(s): |invalid_file_path_chars|. The following characters are also invalid for Windows platform: |invalid_win_file_path_chars| InvalidLengthError: If the ``file_path`` is longer than ``max_len`` characters. Example: :ref:`example-validate-file-path` See Also: `Naming Files, Paths, and Namespaces (Windows) <https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx>`__
[ "Verifying", "whether", "the", "file_path", "is", "a", "valid", "file", "path", "or", "not", "." ]
22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef
https://github.com/thombashi/pathvalidate/blob/22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef/pathvalidate/_file.py#L477-L515
6,157
thombashi/pathvalidate
pathvalidate/_file.py
sanitize_filename
def sanitize_filename( filename, replacement_text="", platform=None, max_len=_DEFAULT_MAX_FILENAME_LEN ): """Make a valid filename from a string. To make a valid filename the function does: - Replace invalid characters as file names included in the ``filename`` with the ``replacement_text``. Invalid characters are: - unprintable characters - |invalid_filename_chars| - for Windows only: |invalid_win_filename_chars| - Append underscore (``"_"``) at the tail of the name if sanitized name is one of the reserved names by the operating system. Args: filename (str or PathLike object): Filename to sanitize. replacement_text (str, optional): Replacement text for invalid characters. Defaults to ``""``. platform (str, optional): .. include:: platform.txt max_len (int, optional): The upper limit of the ``filename`` length. Truncate the name length if the ``filename`` length exceeds this value. Defaults to ``255``. Returns: Same type as the ``filename`` (str or PathLike object): Sanitized filename. Raises: ValueError: If the ``filename`` is an invalid filename. Example: :ref:`example-sanitize-filename` """ return FileNameSanitizer(platform=platform, max_len=max_len).sanitize( filename, replacement_text )
python
def sanitize_filename( filename, replacement_text="", platform=None, max_len=_DEFAULT_MAX_FILENAME_LEN ): return FileNameSanitizer(platform=platform, max_len=max_len).sanitize( filename, replacement_text )
[ "def", "sanitize_filename", "(", "filename", ",", "replacement_text", "=", "\"\"", ",", "platform", "=", "None", ",", "max_len", "=", "_DEFAULT_MAX_FILENAME_LEN", ")", ":", "return", "FileNameSanitizer", "(", "platform", "=", "platform", ",", "max_len", "=", "ma...
Make a valid filename from a string. To make a valid filename the function does: - Replace invalid characters as file names included in the ``filename`` with the ``replacement_text``. Invalid characters are: - unprintable characters - |invalid_filename_chars| - for Windows only: |invalid_win_filename_chars| - Append underscore (``"_"``) at the tail of the name if sanitized name is one of the reserved names by the operating system. Args: filename (str or PathLike object): Filename to sanitize. replacement_text (str, optional): Replacement text for invalid characters. Defaults to ``""``. platform (str, optional): .. include:: platform.txt max_len (int, optional): The upper limit of the ``filename`` length. Truncate the name length if the ``filename`` length exceeds this value. Defaults to ``255``. Returns: Same type as the ``filename`` (str or PathLike object): Sanitized filename. Raises: ValueError: If the ``filename`` is an invalid filename. Example: :ref:`example-sanitize-filename`
[ "Make", "a", "valid", "filename", "from", "a", "string", "." ]
22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef
https://github.com/thombashi/pathvalidate/blob/22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef/pathvalidate/_file.py#L533-L575
6,158
thombashi/pathvalidate
pathvalidate/_file.py
sanitize_filepath
def sanitize_filepath(file_path, replacement_text="", platform=None, max_len=None): """Make a valid file path from a string. Replace invalid characters for a file path within the ``file_path`` with the ``replacement_text``. Invalid characters are as followings: |invalid_file_path_chars|, |invalid_win_file_path_chars| (and non printable characters). Args: file_path (str or PathLike object): File path to sanitize. replacement_text (str, optional): Replacement text for invalid characters. Defaults to ``""``. platform (str, optional): .. include:: platform.txt max_len (int, optional): The upper limit of the ``file_path`` length. Truncate the name if the ``file_path`` length exceedd this value. If the value is |None|, the default value automatically determined by the execution platform: - ``Linux``: 4096 - ``macOS``: 1024 - ``Windows``: 260 Returns: Same type as the argument (str or PathLike object): Sanitized filepath. Raises: ValueError: If the ``file_path`` is an invalid file path. Example: :ref:`example-sanitize-file-path` """ return FilePathSanitizer(platform=platform, max_len=max_len).sanitize( file_path, replacement_text )
python
def sanitize_filepath(file_path, replacement_text="", platform=None, max_len=None): return FilePathSanitizer(platform=platform, max_len=max_len).sanitize( file_path, replacement_text )
[ "def", "sanitize_filepath", "(", "file_path", ",", "replacement_text", "=", "\"\"", ",", "platform", "=", "None", ",", "max_len", "=", "None", ")", ":", "return", "FilePathSanitizer", "(", "platform", "=", "platform", ",", "max_len", "=", "max_len", ")", "."...
Make a valid file path from a string. Replace invalid characters for a file path within the ``file_path`` with the ``replacement_text``. Invalid characters are as followings: |invalid_file_path_chars|, |invalid_win_file_path_chars| (and non printable characters). Args: file_path (str or PathLike object): File path to sanitize. replacement_text (str, optional): Replacement text for invalid characters. Defaults to ``""``. platform (str, optional): .. include:: platform.txt max_len (int, optional): The upper limit of the ``file_path`` length. Truncate the name if the ``file_path`` length exceedd this value. If the value is |None|, the default value automatically determined by the execution platform: - ``Linux``: 4096 - ``macOS``: 1024 - ``Windows``: 260 Returns: Same type as the argument (str or PathLike object): Sanitized filepath. Raises: ValueError: If the ``file_path`` is an invalid file path. Example: :ref:`example-sanitize-file-path`
[ "Make", "a", "valid", "file", "path", "from", "a", "string", "." ]
22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef
https://github.com/thombashi/pathvalidate/blob/22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef/pathvalidate/_file.py#L578-L617
6,159
thombashi/pathvalidate
pathvalidate/_ltsv.py
sanitize_ltsv_label
def sanitize_ltsv_label(label, replacement_text=""): """ Replace all of the symbols in text. :param str label: Input text. :param str replacement_text: Replacement text. :return: A replacement string. :rtype: str """ validate_null_string(label, error_msg="label is empty") return __RE_INVALID_LTSV_LABEL.sub(replacement_text, preprocess(label))
python
def sanitize_ltsv_label(label, replacement_text=""): validate_null_string(label, error_msg="label is empty") return __RE_INVALID_LTSV_LABEL.sub(replacement_text, preprocess(label))
[ "def", "sanitize_ltsv_label", "(", "label", ",", "replacement_text", "=", "\"\"", ")", ":", "validate_null_string", "(", "label", ",", "error_msg", "=", "\"label is empty\"", ")", "return", "__RE_INVALID_LTSV_LABEL", ".", "sub", "(", "replacement_text", ",", "prepro...
Replace all of the symbols in text. :param str label: Input text. :param str replacement_text: Replacement text. :return: A replacement string. :rtype: str
[ "Replace", "all", "of", "the", "symbols", "in", "text", "." ]
22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef
https://github.com/thombashi/pathvalidate/blob/22d64038fb08c04aa9d0e8dd9fd1a955c1a9bfef/pathvalidate/_ltsv.py#L38-L50
6,160
labtocat/beautifier
beautifier/__init__.py
Url.domain
def domain(self): """ Return domain from the url """ remove_pac = self.cleanup.replace( "https://", "").replace("http://", "").replace("www.", "") try: return remove_pac.split('/')[0] except: return None
python
def domain(self): remove_pac = self.cleanup.replace( "https://", "").replace("http://", "").replace("www.", "") try: return remove_pac.split('/')[0] except: return None
[ "def", "domain", "(", "self", ")", ":", "remove_pac", "=", "self", ".", "cleanup", ".", "replace", "(", "\"https://\"", ",", "\"\"", ")", ".", "replace", "(", "\"http://\"", ",", "\"\"", ")", ".", "replace", "(", "\"www.\"", ",", "\"\"", ")", "try", ...
Return domain from the url
[ "Return", "domain", "from", "the", "url" ]
5827edc2d6dc057e5f1f57596037fc94201ca8e7
https://github.com/labtocat/beautifier/blob/5827edc2d6dc057e5f1f57596037fc94201ca8e7/beautifier/__init__.py#L58-L67
6,161
ccubed/PyMoe
Pymoe/Kitsu/user.py
KitsuUser.search
def search(self, term): """ Search for a user by name. :param str term: What to search for. :return: The results as a SearchWrapper iterator or None if no results. :rtype: SearchWrapper or None """ r = requests.get(self.apiurl + "/users", params={"filter[name]": term}, headers=self.header) if r.status_code != 200: raise ServerError jsd = r.json() if jsd['meta']['count']: return SearchWrapper(jsd['data'], jsd['links']['next'] if 'next' in jsd['links'] else None, self.header) else: return None
python
def search(self, term): r = requests.get(self.apiurl + "/users", params={"filter[name]": term}, headers=self.header) if r.status_code != 200: raise ServerError jsd = r.json() if jsd['meta']['count']: return SearchWrapper(jsd['data'], jsd['links']['next'] if 'next' in jsd['links'] else None, self.header) else: return None
[ "def", "search", "(", "self", ",", "term", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"/users\"", ",", "params", "=", "{", "\"filter[name]\"", ":", "term", "}", ",", "headers", "=", "self", ".", "header", ")", "i...
Search for a user by name. :param str term: What to search for. :return: The results as a SearchWrapper iterator or None if no results. :rtype: SearchWrapper or None
[ "Search", "for", "a", "user", "by", "name", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/user.py#L11-L29
6,162
ccubed/PyMoe
Pymoe/Kitsu/user.py
KitsuUser.create
def create(self, data): """ Create a user. Please review the attributes required. You need only provide the attributes. :param data: A dictionary of the required attributes :return: Dictionary returned by server or a ServerError exception :rtype: Dictionary or Exception """ final_dict = {"data": {"type": "users", "attributes": data}} r = requests.post(self.apiurl + "/users", json=final_dict, headers=self.header) if r.status_code != 200: raise ServerError return r.json()
python
def create(self, data): final_dict = {"data": {"type": "users", "attributes": data}} r = requests.post(self.apiurl + "/users", json=final_dict, headers=self.header) if r.status_code != 200: raise ServerError return r.json()
[ "def", "create", "(", "self", ",", "data", ")", ":", "final_dict", "=", "{", "\"data\"", ":", "{", "\"type\"", ":", "\"users\"", ",", "\"attributes\"", ":", "data", "}", "}", "r", "=", "requests", ".", "post", "(", "self", ".", "apiurl", "+", "\"/use...
Create a user. Please review the attributes required. You need only provide the attributes. :param data: A dictionary of the required attributes :return: Dictionary returned by server or a ServerError exception :rtype: Dictionary or Exception
[ "Create", "a", "user", ".", "Please", "review", "the", "attributes", "required", ".", "You", "need", "only", "provide", "the", "attributes", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/user.py#L31-L45
6,163
ccubed/PyMoe
Pymoe/Kitsu/user.py
KitsuUser.get
def get(self, uid): """ Get a user's information by their id. :param uid str: User ID :return: The user's information or None :rtype: Dictionary or None """ r = requests.get(self.apiurl + "/users/{}".format(uid), headers=self.header) if r.status_code != 200: raise ServerError jsd = r.json() if jsd['data']: return jsd['data'] else: return None
python
def get(self, uid): r = requests.get(self.apiurl + "/users/{}".format(uid), headers=self.header) if r.status_code != 200: raise ServerError jsd = r.json() if jsd['data']: return jsd['data'] else: return None
[ "def", "get", "(", "self", ",", "uid", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"/users/{}\"", ".", "format", "(", "uid", ")", ",", "headers", "=", "self", ".", "header", ")", "if", "r", ".", "status_code", "...
Get a user's information by their id. :param uid str: User ID :return: The user's information or None :rtype: Dictionary or None
[ "Get", "a", "user", "s", "information", "by", "their", "id", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/user.py#L47-L65
6,164
ccubed/PyMoe
Pymoe/Kitsu/user.py
KitsuUser.update
def update(self, uid, data, token): """ Update a user's data. Requires an auth token. :param uid str: User ID to update :param data dict: The dictionary of data attributes to change. Just the attributes. :param token str: The authorization token for this user :return: True or Exception :rtype: Bool or ServerError """ final_dict = {"data": {"id": uid, "type": "users", "attributes": data}} final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.patch(self.apiurl + "/users/{}".format(uid), json=final_dict, headers=final_headers) if r.status_code != 200: raise ServerError return True
python
def update(self, uid, data, token): final_dict = {"data": {"id": uid, "type": "users", "attributes": data}} final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.patch(self.apiurl + "/users/{}".format(uid), json=final_dict, headers=final_headers) if r.status_code != 200: raise ServerError return True
[ "def", "update", "(", "self", ",", "uid", ",", "data", ",", "token", ")", ":", "final_dict", "=", "{", "\"data\"", ":", "{", "\"id\"", ":", "uid", ",", "\"type\"", ":", "\"users\"", ",", "\"attributes\"", ":", "data", "}", "}", "final_headers", "=", ...
Update a user's data. Requires an auth token. :param uid str: User ID to update :param data dict: The dictionary of data attributes to change. Just the attributes. :param token str: The authorization token for this user :return: True or Exception :rtype: Bool or ServerError
[ "Update", "a", "user", "s", "data", ".", "Requires", "an", "auth", "token", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/user.py#L67-L85
6,165
ccubed/PyMoe
Pymoe/VNDB/__init__.py
VNDB.get
def get(self, stype, flags, filters, options=None): """ Send a request to the API to return results related to Visual Novels. :param str stype: What are we searching for? One of: vn, release, producer, character, votelist, vnlist, wishlist :param flags: See the D11 docs. A comma separated list of flags for what data to return. Can be list or str. :param str filters: A string with the one filter to search by (apparently you only get one). This is kind of special. You need to pass them in the form <filter><op>"<term>" for strings or <filter><op><number> for numbers. This is counter intuitive. Also, per the docs, <filter>=<number> doesn't do what we think, use >, >= or < and <=. I will attempt to properly format this if not done so when called. :param dict options: A dictionary of options to customize the search by. Optional, defaults to None. :return dict: A dictionary containing a pages and data key. data contains a list of dictionaries with data on your results. If pages is true, you can call this command again with the same parameters and pass a page option to get more data. Otherwise no further results exist for this query. :raises ServerError: Raises a ServerError if an error is returned. """ if not isinstance(flags, str): if isinstance(flags, list): finflags = ",".join(flags) else: raise SyntaxError("Flags should be a list or comma separated string") else: finflags = flags if not isinstance(filters, str): raise SyntaxError("Filters needs to be a string in the format Filter<op>Value. The simplest form is search=\"<Term>\".") if stype not in self.stypes: raise SyntaxError("{} not a valid Search type.".format(stype)) if '"' not in filters or "'" not in filters: newfilters = self.helperpat.split(filters) newfilters = [x.strip() for x in newfilters] newfilters[1] = '"' + newfilters[1] + '"' op = self.helperpat.search(filters) newfilters = op.group(0).join(newfilters) command = '{} {} ({}){}'.format(stype, finflags, newfilters, ' ' + ujson.dumps(options) if options is not None else '') else: command = '{} {} ({}){}'.format(stype, finflags, filters, ' ' + ujson.dumps(options) if options is not None else '') data = self.connection.send_command('get', command) if 'id' in data: raise ServerError(data['msg'], data['id']) else: return {'pages': data.get('more', default=False), 'data': data['items']}
python
def get(self, stype, flags, filters, options=None): if not isinstance(flags, str): if isinstance(flags, list): finflags = ",".join(flags) else: raise SyntaxError("Flags should be a list or comma separated string") else: finflags = flags if not isinstance(filters, str): raise SyntaxError("Filters needs to be a string in the format Filter<op>Value. The simplest form is search=\"<Term>\".") if stype not in self.stypes: raise SyntaxError("{} not a valid Search type.".format(stype)) if '"' not in filters or "'" not in filters: newfilters = self.helperpat.split(filters) newfilters = [x.strip() for x in newfilters] newfilters[1] = '"' + newfilters[1] + '"' op = self.helperpat.search(filters) newfilters = op.group(0).join(newfilters) command = '{} {} ({}){}'.format(stype, finflags, newfilters, ' ' + ujson.dumps(options) if options is not None else '') else: command = '{} {} ({}){}'.format(stype, finflags, filters, ' ' + ujson.dumps(options) if options is not None else '') data = self.connection.send_command('get', command) if 'id' in data: raise ServerError(data['msg'], data['id']) else: return {'pages': data.get('more', default=False), 'data': data['items']}
[ "def", "get", "(", "self", ",", "stype", ",", "flags", ",", "filters", ",", "options", "=", "None", ")", ":", "if", "not", "isinstance", "(", "flags", ",", "str", ")", ":", "if", "isinstance", "(", "flags", ",", "list", ")", ":", "finflags", "=", ...
Send a request to the API to return results related to Visual Novels. :param str stype: What are we searching for? One of: vn, release, producer, character, votelist, vnlist, wishlist :param flags: See the D11 docs. A comma separated list of flags for what data to return. Can be list or str. :param str filters: A string with the one filter to search by (apparently you only get one). This is kind of special. You need to pass them in the form <filter><op>"<term>" for strings or <filter><op><number> for numbers. This is counter intuitive. Also, per the docs, <filter>=<number> doesn't do what we think, use >, >= or < and <=. I will attempt to properly format this if not done so when called. :param dict options: A dictionary of options to customize the search by. Optional, defaults to None. :return dict: A dictionary containing a pages and data key. data contains a list of dictionaries with data on your results. If pages is true, you can call this command again with the same parameters and pass a page option to get more data. Otherwise no further results exist for this query. :raises ServerError: Raises a ServerError if an error is returned.
[ "Send", "a", "request", "to", "the", "API", "to", "return", "results", "related", "to", "Visual", "Novels", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/VNDB/__init__.py#L34-L80
6,166
ccubed/PyMoe
Pymoe/VNDB/__init__.py
VNDB.set
def set(self, stype, sid, fields): """ Send a request to the API to modify something in the database if logged in. :param str stype: What are we modifying? One of: votelist, vnlist, wishlist :param int sid: The ID that we're modifying. :param dict fields: A dictionary of the fields and their values :raises ServerError: Raises a ServerError if an error is returned :return bool: True if successful, error otherwise """ if stype not in ['votelist', 'vnlist', 'wishlist']: raise SyntaxError("{} is not a valid type for set. Should be one of: votelist, vnlist or wishlist.".format(stype)) command = "{} {} {}".format(stype, id, ujson.dumps(fields)) data = self.connection.send_command('set', command) if 'id' in data: raise ServerError(data['msg'], data['id']) else: return True
python
def set(self, stype, sid, fields): if stype not in ['votelist', 'vnlist', 'wishlist']: raise SyntaxError("{} is not a valid type for set. Should be one of: votelist, vnlist or wishlist.".format(stype)) command = "{} {} {}".format(stype, id, ujson.dumps(fields)) data = self.connection.send_command('set', command) if 'id' in data: raise ServerError(data['msg'], data['id']) else: return True
[ "def", "set", "(", "self", ",", "stype", ",", "sid", ",", "fields", ")", ":", "if", "stype", "not", "in", "[", "'votelist'", ",", "'vnlist'", ",", "'wishlist'", "]", ":", "raise", "SyntaxError", "(", "\"{} is not a valid type for set. Should be one of: votelist,...
Send a request to the API to modify something in the database if logged in. :param str stype: What are we modifying? One of: votelist, vnlist, wishlist :param int sid: The ID that we're modifying. :param dict fields: A dictionary of the fields and their values :raises ServerError: Raises a ServerError if an error is returned :return bool: True if successful, error otherwise
[ "Send", "a", "request", "to", "the", "API", "to", "modify", "something", "in", "the", "database", "if", "logged", "in", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/VNDB/__init__.py#L82-L101
6,167
ccubed/PyMoe
Pymoe/Anilist/get.py
AGet.anime
def anime(self, item_id): """ The function to retrieve an anime's details. :param int item_id: the anime's ID :return: dict or None :rtype: dict or NoneType """ query_string = """\ query ($id: Int) { Media(id: $id, type: ANIME) { title { romaji english } startDate { year month day } endDate { year month day } coverImage { large } bannerImage format status episodes season description averageScore meanScore genres synonyms nextAiringEpisode { airingAt timeUntilAiring episode } } } """ vars = {"id": item_id} r = requests.post(self.settings['apiurl'], headers=self.settings['header'], json={'query': query_string, 'variables': vars}) jsd = r.text try: jsd = json.loads(jsd) except ValueError: return None else: return jsd
python
def anime(self, item_id): query_string = """\ query ($id: Int) { Media(id: $id, type: ANIME) { title { romaji english } startDate { year month day } endDate { year month day } coverImage { large } bannerImage format status episodes season description averageScore meanScore genres synonyms nextAiringEpisode { airingAt timeUntilAiring episode } } } """ vars = {"id": item_id} r = requests.post(self.settings['apiurl'], headers=self.settings['header'], json={'query': query_string, 'variables': vars}) jsd = r.text try: jsd = json.loads(jsd) except ValueError: return None else: return jsd
[ "def", "anime", "(", "self", ",", "item_id", ")", ":", "query_string", "=", "\"\"\"\\\n query ($id: Int) {\n Media(id: $id, type: ANIME) {\n title {\n romaji\n english\n }\n ...
The function to retrieve an anime's details. :param int item_id: the anime's ID :return: dict or None :rtype: dict or NoneType
[ "The", "function", "to", "retrieve", "an", "anime", "s", "details", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Anilist/get.py#L8-L65
6,168
ccubed/PyMoe
Pymoe/Anilist/get.py
AGet.review
def review(self, item_id, html = True): """ With the change to v2 of the api, reviews have their own IDs. This accepts the ID of the review. You can set html to False if you want the review body returned without html formatting. The API Default is true. :param item_id: the Id of the review :param html: do you want the body returned with html formatting? :return: json object :rtype: json object containing review information """ query_string = """\ query ($id: Int, $html: Boolean) { Review (id: $id) { summary body(asHtml: $html) score rating ratingAmount createdAt updatedAt private media { id } user { id name avatar { large } } } } """ vars = {"id": item_id, "html": html} r = requests.post(self.settings['apiurl'], headers=self.settings['header'], json={'query': query_string, 'variables': vars}) jsd = r.text try: jsd = json.loads(jsd) except ValueError: return None else: return jsd
python
def review(self, item_id, html = True): query_string = """\ query ($id: Int, $html: Boolean) { Review (id: $id) { summary body(asHtml: $html) score rating ratingAmount createdAt updatedAt private media { id } user { id name avatar { large } } } } """ vars = {"id": item_id, "html": html} r = requests.post(self.settings['apiurl'], headers=self.settings['header'], json={'query': query_string, 'variables': vars}) jsd = r.text try: jsd = json.loads(jsd) except ValueError: return None else: return jsd
[ "def", "review", "(", "self", ",", "item_id", ",", "html", "=", "True", ")", ":", "query_string", "=", "\"\"\"\\\n query ($id: Int, $html: Boolean) {\n Review (id: $id) {\n summary\n body(asHtml: $html)\n ...
With the change to v2 of the api, reviews have their own IDs. This accepts the ID of the review. You can set html to False if you want the review body returned without html formatting. The API Default is true. :param item_id: the Id of the review :param html: do you want the body returned with html formatting? :return: json object :rtype: json object containing review information
[ "With", "the", "change", "to", "v2", "of", "the", "api", "reviews", "have", "their", "own", "IDs", ".", "This", "accepts", "the", "ID", "of", "the", "review", ".", "You", "can", "set", "html", "to", "False", "if", "you", "want", "the", "review", "bod...
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Anilist/get.py#L219-L265
6,169
ccubed/PyMoe
Pymoe/Kitsu/mappings.py
KitsuMappings.get
def get(self, external_site: str, external_id: int): """ Get a kitsu mapping by external site ID :param str external_site: string representing the external site :param int external_id: ID of the entry in the external site. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` """ r = requests.get(self.apiurl + "/mappings", params={"filter[externalSite]": external_site, "filter[externalId]": external_id}, headers=self.header) if r.status_code != 200: raise ServerError jsd = r.json() if len(jsd['data']) < 1: return None r = requests.get(jsd['data'][0]['relationships']['item']['links']['related'], headers=self.header) if r.status_code != 200: return jsd else: return r.json()
python
def get(self, external_site: str, external_id: int): r = requests.get(self.apiurl + "/mappings", params={"filter[externalSite]": external_site, "filter[externalId]": external_id}, headers=self.header) if r.status_code != 200: raise ServerError jsd = r.json() if len(jsd['data']) < 1: return None r = requests.get(jsd['data'][0]['relationships']['item']['links']['related'], headers=self.header) if r.status_code != 200: return jsd else: return r.json()
[ "def", "get", "(", "self", ",", "external_site", ":", "str", ",", "external_id", ":", "int", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"/mappings\"", ",", "params", "=", "{", "\"filter[externalSite]\"", ":", "external...
Get a kitsu mapping by external site ID :param str external_site: string representing the external site :param int external_id: ID of the entry in the external site. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError`
[ "Get", "a", "kitsu", "mapping", "by", "external", "site", "ID" ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/mappings.py#L11-L36
6,170
ccubed/PyMoe
Pymoe/Kitsu/auth.py
KitsuAuth.authenticate
def authenticate(self, username, password): """ Obtain an oauth token. Pass username and password. Get a token back. If KitsuAuth is set to remember your tokens for this session, it will store the token under the username given. :param username: username :param password: password :param alias: A list of alternative names for a person if using the KitsuAuth token storage :return: A tuple of (token, expiration time in unix time stamp, refresh_token) or ServerError """ r = requests.post(self.apiurl + "/token", params={"grant_type": "password", "username": username, "password": password, "client_id": self.cid, "client_secret": self.csecret}) if r.status_code != 200: raise ServerError jsd = r.json() if self.remember: self.token_storage[username] = {'token': jsd['access_token'], 'refresh': jsd['refresh_token'], 'expiration': int(jsd['created_at']) + int(jsd['expires_in'])} return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at']), jsd['refresh_token']
python
def authenticate(self, username, password): r = requests.post(self.apiurl + "/token", params={"grant_type": "password", "username": username, "password": password, "client_id": self.cid, "client_secret": self.csecret}) if r.status_code != 200: raise ServerError jsd = r.json() if self.remember: self.token_storage[username] = {'token': jsd['access_token'], 'refresh': jsd['refresh_token'], 'expiration': int(jsd['created_at']) + int(jsd['expires_in'])} return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at']), jsd['refresh_token']
[ "def", "authenticate", "(", "self", ",", "username", ",", "password", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "apiurl", "+", "\"/token\"", ",", "params", "=", "{", "\"grant_type\"", ":", "\"password\"", ",", "\"username\"", ":", "u...
Obtain an oauth token. Pass username and password. Get a token back. If KitsuAuth is set to remember your tokens for this session, it will store the token under the username given. :param username: username :param password: password :param alias: A list of alternative names for a person if using the KitsuAuth token storage :return: A tuple of (token, expiration time in unix time stamp, refresh_token) or ServerError
[ "Obtain", "an", "oauth", "token", ".", "Pass", "username", "and", "password", ".", "Get", "a", "token", "back", ".", "If", "KitsuAuth", "is", "set", "to", "remember", "your", "tokens", "for", "this", "session", "it", "will", "store", "the", "token", "und...
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/auth.py#L25-L48
6,171
ccubed/PyMoe
Pymoe/Kitsu/auth.py
KitsuAuth.refresh
def refresh(self, refresh_token): """ Renew an oauth token given an appropriate refresh token. :param refresh_token: The Refresh Token :return: A tuple of (token, expiration time in unix time stamp) """ r = requests.post(self.apiurl + "/token", params={"grant_type": "refresh_token", "client_id": self.cid, "client_secret": self.csecret, "refresh_token": refresh_token}) if r.status_code != 200: raise ServerError jsd = r.json() return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at'])
python
def refresh(self, refresh_token): r = requests.post(self.apiurl + "/token", params={"grant_type": "refresh_token", "client_id": self.cid, "client_secret": self.csecret, "refresh_token": refresh_token}) if r.status_code != 200: raise ServerError jsd = r.json() return jsd['access_token'], int(jsd['expires_in']) + int(jsd['created_at'])
[ "def", "refresh", "(", "self", ",", "refresh_token", ")", ":", "r", "=", "requests", ".", "post", "(", "self", ".", "apiurl", "+", "\"/token\"", ",", "params", "=", "{", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"client_id\"", ":", "self", ".", ...
Renew an oauth token given an appropriate refresh token. :param refresh_token: The Refresh Token :return: A tuple of (token, expiration time in unix time stamp)
[ "Renew", "an", "oauth", "token", "given", "an", "appropriate", "refresh", "token", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/auth.py#L50-L66
6,172
ccubed/PyMoe
Pymoe/Kitsu/auth.py
KitsuAuth.get
def get(self, username): """ If using the remember option and KitsuAuth is storing your tokens, this function will retrieve one. :param username: The username whose token we are retrieving :return: A token, NotFound or NotSaving error """ if not self.remember: raise NotSaving if username not in self.token_storage: raise UserNotFound if self.token_storage[username]['expiration'] < time.time(): new_token = self.refresh(self.token_storage[username]['refresh']) self.token_storage[username]['token'] = new_token[0] self.token_storage[username]['expiration'] = new_token[1] return new_token[0] else: return self.token_storage[username]['token']
python
def get(self, username): if not self.remember: raise NotSaving if username not in self.token_storage: raise UserNotFound if self.token_storage[username]['expiration'] < time.time(): new_token = self.refresh(self.token_storage[username]['refresh']) self.token_storage[username]['token'] = new_token[0] self.token_storage[username]['expiration'] = new_token[1] return new_token[0] else: return self.token_storage[username]['token']
[ "def", "get", "(", "self", ",", "username", ")", ":", "if", "not", "self", ".", "remember", ":", "raise", "NotSaving", "if", "username", "not", "in", "self", ".", "token_storage", ":", "raise", "UserNotFound", "if", "self", ".", "token_storage", "[", "us...
If using the remember option and KitsuAuth is storing your tokens, this function will retrieve one. :param username: The username whose token we are retrieving :return: A token, NotFound or NotSaving error
[ "If", "using", "the", "remember", "option", "and", "KitsuAuth", "is", "storing", "your", "tokens", "this", "function", "will", "retrieve", "one", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/auth.py#L69-L88
6,173
ccubed/PyMoe
Pymoe/Anidb/dump.py
save
def save(url, destination): """ This is just the thread target. It's actually responsible for downloading and saving. :param str url: which dump to download :param str destination: a file path to save to """ r = requests.get(url, stream=True) with open(destination, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk)
python
def save(url, destination): r = requests.get(url, stream=True) with open(destination, 'wb') as fd: for chunk in r.iter_content(chunk_size=128): fd.write(chunk)
[ "def", "save", "(", "url", ",", "destination", ")", ":", "r", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "with", "open", "(", "destination", ",", "'wb'", ")", "as", "fd", ":", "for", "chunk", "in", "r", ".", "iter_c...
This is just the thread target. It's actually responsible for downloading and saving. :param str url: which dump to download :param str destination: a file path to save to
[ "This", "is", "just", "the", "thread", "target", ".", "It", "s", "actually", "responsible", "for", "downloading", "and", "saving", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Anidb/dump.py#L40-L52
6,174
ccubed/PyMoe
Pymoe/Anidb/dump.py
Dump.download
def download(which, destination=None): """ I realize that the download for the dumps is going to take awhile. Given that, I've decided to approach this using threads. When you call this method, it will launch a thread to download the data. By default, the dump is dropped into the current working directory. If the directory given doesn't exist, we'll try to make it. Don't use '..' in the path as this confuses makedirs. :param int which: 0 for dat (txt), 1 for xml :param str destination: a file path to save to, defaults to cwd """ if destination: if not os.path.exists(destination): os.makedirs(destination) pthread = threading.Thread( target=save, args=( self.urls[which], os.path.join(destination, self.urls[which]) ) ) pthread.start() return pthread
python
def download(which, destination=None): if destination: if not os.path.exists(destination): os.makedirs(destination) pthread = threading.Thread( target=save, args=( self.urls[which], os.path.join(destination, self.urls[which]) ) ) pthread.start() return pthread
[ "def", "download", "(", "which", ",", "destination", "=", "None", ")", ":", "if", "destination", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "destination", ")", ":", "os", ".", "makedirs", "(", "destination", ")", "pthread", "=", "threadin...
I realize that the download for the dumps is going to take awhile. Given that, I've decided to approach this using threads. When you call this method, it will launch a thread to download the data. By default, the dump is dropped into the current working directory. If the directory given doesn't exist, we'll try to make it. Don't use '..' in the path as this confuses makedirs. :param int which: 0 for dat (txt), 1 for xml :param str destination: a file path to save to, defaults to cwd
[ "I", "realize", "that", "the", "download", "for", "the", "dumps", "is", "going", "to", "take", "awhile", ".", "Given", "that", "I", "ve", "decided", "to", "approach", "this", "using", "threads", ".", "When", "you", "call", "this", "method", "it", "will",...
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Anidb/dump.py#L13-L37
6,175
ccubed/PyMoe
Pymoe/Kitsu/manga.py
KitsuManga.get
def get(self, aid): """ Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError` """ r = requests.get(self.apiurl + "/manga/{}".format(aid), headers=self.header) if r.status_code != 200: if r.status_code == 404: return None else: raise ServerError return r.json()
python
def get(self, aid): r = requests.get(self.apiurl + "/manga/{}".format(aid), headers=self.header) if r.status_code != 200: if r.status_code == 404: return None else: raise ServerError return r.json()
[ "def", "get", "(", "self", ",", "aid", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"/manga/{}\"", ".", "format", "(", "aid", ")", ",", "headers", "=", "self", ".", "header", ")", "if", "r", ".", "status_code", "...
Get manga information by id. :param int aid: ID of the manga. :return: Dictionary or None (for not found) :rtype: Dictionary or None :raises: :class:`Pymoe.errors.ServerError`
[ "Get", "manga", "information", "by", "id", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/manga.py#L11-L28
6,176
ccubed/PyMoe
Pymoe/Bakatsuki/__init__.py
Bakatsuki.active
def active(self): """ Get a list of active projects. :return list: A list of tuples containing a title and pageid in that order. """ projects = [] r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmpageid': self.active_id, 'cmtype': 'page', 'cmlimit': '500', 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' in jsd: while True: r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmpageid': self.active_id, 'cmtype': 'page', 'cmlimit': '500', 'cmcontinue': jsd['query-continue']['categorymembers']['cmcontinue'], 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' not in jsd: break else: break return projects[0]
python
def active(self): projects = [] r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmpageid': self.active_id, 'cmtype': 'page', 'cmlimit': '500', 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' in jsd: while True: r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmpageid': self.active_id, 'cmtype': 'page', 'cmlimit': '500', 'cmcontinue': jsd['query-continue']['categorymembers']['cmcontinue'], 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' not in jsd: break else: break return projects[0]
[ "def", "active", "(", "self", ")", ":", "projects", "=", "[", "]", "r", "=", "requests", ".", "get", "(", "self", ".", "api", ",", "params", "=", "{", "'action'", ":", "'query'", ",", "'list'", ":", "'categorymembers'", ",", "'cmpageid'", ":", "self"...
Get a list of active projects. :return list: A list of tuples containing a title and pageid in that order.
[ "Get", "a", "list", "of", "active", "projects", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Bakatsuki/__init__.py#L26-L55
6,177
ccubed/PyMoe
Pymoe/Bakatsuki/__init__.py
Bakatsuki.light_novels
def light_novels(self, language="English"): """ Get a list of light novels under a certain language. :param str language: Defaults to English. Replace with whatever language you want to query. :return list: A list of tuples containing a title and pageid element in that order. """ projects = [] r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Light_novel_({})'.format(language.replace(" ", "_")), 'cmtype': 'page', 'cmlimit': '500', 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' in jsd: while True: r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Light_novel_({})'.format(language.replace(" ", "_")), 'cmtype': 'page', 'cmlimit': '500', 'cmcontinue': jsd['query-continue']['categorymembers']['cmcontinue'], 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' not in jsd: break else: break return projects[0]
python
def light_novels(self, language="English"): projects = [] r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Light_novel_({})'.format(language.replace(" ", "_")), 'cmtype': 'page', 'cmlimit': '500', 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' in jsd: while True: r = requests.get(self.api, params={'action': 'query', 'list': 'categorymembers', 'cmtitle': 'Category:Light_novel_({})'.format(language.replace(" ", "_")), 'cmtype': 'page', 'cmlimit': '500', 'cmcontinue': jsd['query-continue']['categorymembers']['cmcontinue'], 'format': 'json'}, headers=self.header) if r.status_code == 200: jsd = r.json() projects.append([(x['title'], x['pageid']) for x in jsd['query']['categorymembers']]) if 'query-continue' not in jsd: break else: break return projects[0]
[ "def", "light_novels", "(", "self", ",", "language", "=", "\"English\"", ")", ":", "projects", "=", "[", "]", "r", "=", "requests", ".", "get", "(", "self", ".", "api", ",", "params", "=", "{", "'action'", ":", "'query'", ",", "'list'", ":", "'catego...
Get a list of light novels under a certain language. :param str language: Defaults to English. Replace with whatever language you want to query. :return list: A list of tuples containing a title and pageid element in that order.
[ "Get", "a", "list", "of", "light", "novels", "under", "a", "certain", "language", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Bakatsuki/__init__.py#L57-L89
6,178
ccubed/PyMoe
Pymoe/Bakatsuki/__init__.py
Bakatsuki.chapters
def chapters(self, title): """ Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage. :param str title: The title of the novel you want chapters from :return OrderedDict: An OrderedDict which contains the chapters found for the visual novel supplied """ r = requests.get("https://www.baka-tsuki.org/project/index.php?title={}".format(title.replace(" ", "_")), headers=self.header) if r.status_code != 200: raise requests.HTTPError("Not Found") else: parsed = soup(r.text, 'html.parser') dd = parsed.find_all("a") volumes = [] for link in dd: if 'class' in link.attrs: if 'image' in link.get('class'): continue if 'href' in link.attrs: if re.search(self.chapter_regex, link.get('href')) is not None and not link.get('href').startswith('#'): volumes.append(link) seplist = OrderedDict() for item in volumes: if 'title' in item.attrs: result = re.search(self.separate_regex, item.get('title').lower()) else: result = re.search(self.separate_regex, item.text.lower()) if result and result.groups(): if result.group('chapter').lstrip('0') in seplist: seplist[result.group('chapter').lstrip('0')].append([item.get('href'), item.get('title') if 'title' in item.attrs else item.text]) else: seplist[result.group('chapter').lstrip('0')] = [[item.get('href'), item.get('title') if 'title' in item.attrs else item.text]] return seplist
python
def chapters(self, title): r = requests.get("https://www.baka-tsuki.org/project/index.php?title={}".format(title.replace(" ", "_")), headers=self.header) if r.status_code != 200: raise requests.HTTPError("Not Found") else: parsed = soup(r.text, 'html.parser') dd = parsed.find_all("a") volumes = [] for link in dd: if 'class' in link.attrs: if 'image' in link.get('class'): continue if 'href' in link.attrs: if re.search(self.chapter_regex, link.get('href')) is not None and not link.get('href').startswith('#'): volumes.append(link) seplist = OrderedDict() for item in volumes: if 'title' in item.attrs: result = re.search(self.separate_regex, item.get('title').lower()) else: result = re.search(self.separate_regex, item.text.lower()) if result and result.groups(): if result.group('chapter').lstrip('0') in seplist: seplist[result.group('chapter').lstrip('0')].append([item.get('href'), item.get('title') if 'title' in item.attrs else item.text]) else: seplist[result.group('chapter').lstrip('0')] = [[item.get('href'), item.get('title') if 'title' in item.attrs else item.text]] return seplist
[ "def", "chapters", "(", "self", ",", "title", ")", ":", "r", "=", "requests", ".", "get", "(", "\"https://www.baka-tsuki.org/project/index.php?title={}\"", ".", "format", "(", "title", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", ")", ",", "headers", "="...
Get a list of chapters for a visual novel. Keep in mind, this can be slow. I've certainly tried to make it as fast as possible, but it's still pulling text out of a webpage. :param str title: The title of the novel you want chapters from :return OrderedDict: An OrderedDict which contains the chapters found for the visual novel supplied
[ "Get", "a", "list", "of", "chapters", "for", "a", "visual", "novel", ".", "Keep", "in", "mind", "this", "can", "be", "slow", ".", "I", "ve", "certainly", "tried", "to", "make", "it", "as", "fast", "as", "possible", "but", "it", "s", "still", "pulling...
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Bakatsuki/__init__.py#L159-L195
6,179
ccubed/PyMoe
Pymoe/Bakatsuki/__init__.py
Bakatsuki.cover
def cover(self, pageid): """ Get a cover image given a page id. :param str pageid: The pageid for the light novel you want a cover image for :return str: the image url """ r = requests.get(self.api, params={'action': 'query', 'prop': 'pageimages', 'pageids': pageid, 'format': 'json'}, headers=self.header) jsd = r.json() image = "File:" + jsd['query']['pages'][str(pageid)]['pageimage'] r = requests.get(self.api, params={'action': 'query', 'prop': 'imageinfo', 'iiprop': 'url', 'titles': image, 'format': 'json'}, headers=self.header) jsd = r.json() return jsd['query']['pages'][list(jsd['query']['pages'].keys())[0]]['imageinfo'][0]['url']
python
def cover(self, pageid): r = requests.get(self.api, params={'action': 'query', 'prop': 'pageimages', 'pageids': pageid, 'format': 'json'}, headers=self.header) jsd = r.json() image = "File:" + jsd['query']['pages'][str(pageid)]['pageimage'] r = requests.get(self.api, params={'action': 'query', 'prop': 'imageinfo', 'iiprop': 'url', 'titles': image, 'format': 'json'}, headers=self.header) jsd = r.json() return jsd['query']['pages'][list(jsd['query']['pages'].keys())[0]]['imageinfo'][0]['url']
[ "def", "cover", "(", "self", ",", "pageid", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "api", ",", "params", "=", "{", "'action'", ":", "'query'", ",", "'prop'", ":", "'pageimages'", ",", "'pageids'", ":", "pageid", ",", "'format'"...
Get a cover image given a page id. :param str pageid: The pageid for the light novel you want a cover image for :return str: the image url
[ "Get", "a", "cover", "image", "given", "a", "page", "id", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Bakatsuki/__init__.py#L197-L214
6,180
ccubed/PyMoe
Pymoe/Bakatsuki/__init__.py
Bakatsuki.get_text
def get_text(self, title): """ This will grab the html content of the chapter given by url. Technically you can use this to get the content of other pages too. :param title: Title for the page you want the content of :return: a string containing the html content """ r = requests.get(self.api, params={'action': 'parse', 'page': title, 'format': 'json'}, headers=self.header) jsd = r.json() return jsd['parse']['text']['*']
python
def get_text(self, title): r = requests.get(self.api, params={'action': 'parse', 'page': title, 'format': 'json'}, headers=self.header) jsd = r.json() return jsd['parse']['text']['*']
[ "def", "get_text", "(", "self", ",", "title", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "api", ",", "params", "=", "{", "'action'", ":", "'parse'", ",", "'page'", ":", "title", ",", "'format'", ":", "'json'", "}", ",", "headers"...
This will grab the html content of the chapter given by url. Technically you can use this to get the content of other pages too. :param title: Title for the page you want the content of :return: a string containing the html content
[ "This", "will", "grab", "the", "html", "content", "of", "the", "chapter", "given", "by", "url", ".", "Technically", "you", "can", "use", "this", "to", "get", "the", "content", "of", "other", "pages", "too", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Bakatsuki/__init__.py#L216-L227
6,181
ccubed/PyMoe
Pymoe/Mal/__init__.py
Mal._verify_credentials
def _verify_credentials(self): """ An internal method that verifies the credentials given at instantiation. :raises: :class:`Pymoe.errors.UserLoginFailed` """ r = requests.get(self.apiurl + "account/verify_credentials.xml", auth=HTTPBasicAuth(self._username, self._password), headers=self.header) if r.status_code != 200: raise UserLoginFailed("Username or Password incorrect.")
python
def _verify_credentials(self): r = requests.get(self.apiurl + "account/verify_credentials.xml", auth=HTTPBasicAuth(self._username, self._password), headers=self.header) if r.status_code != 200: raise UserLoginFailed("Username or Password incorrect.")
[ "def", "_verify_credentials", "(", "self", ")", ":", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"account/verify_credentials.xml\"", ",", "auth", "=", "HTTPBasicAuth", "(", "self", ".", "_username", ",", "self", ".", "_password", ")"...
An internal method that verifies the credentials given at instantiation. :raises: :class:`Pymoe.errors.UserLoginFailed`
[ "An", "internal", "method", "that", "verifies", "the", "credentials", "given", "at", "instantiation", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Mal/__init__.py#L37-L47
6,182
ccubed/PyMoe
Pymoe/Mal/__init__.py
Mal._anime_add
def _anime_add(self, data): """ Adds an anime to a user's list. :param data: A :class:`Pymoe.Mal.Objects.Anime` object with the anime data :raises: SyntaxError on invalid data type :raises: ServerError on failure to add :rtype: Bool :return: True on success """ if isinstance(data, Anime): xmlstr = data.to_xml() r = requests.get(self.apiurl + "animelist/add/{}.xml".format(data.id), params={'data': xmlstr}, auth=HTTPBasicAuth(self._username, self._password), headers=self.header) if r.status_code != 201: raise ServerError(r.text, r.status_code) return True else: raise SyntaxError( "Invalid type: data should be a Pymoe.Mal.Objects.Anime object. Got a {}".format(type(data)))
python
def _anime_add(self, data): if isinstance(data, Anime): xmlstr = data.to_xml() r = requests.get(self.apiurl + "animelist/add/{}.xml".format(data.id), params={'data': xmlstr}, auth=HTTPBasicAuth(self._username, self._password), headers=self.header) if r.status_code != 201: raise ServerError(r.text, r.status_code) return True else: raise SyntaxError( "Invalid type: data should be a Pymoe.Mal.Objects.Anime object. Got a {}".format(type(data)))
[ "def", "_anime_add", "(", "self", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "Anime", ")", ":", "xmlstr", "=", "data", ".", "to_xml", "(", ")", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"animelist/add/{}.x...
Adds an anime to a user's list. :param data: A :class:`Pymoe.Mal.Objects.Anime` object with the anime data :raises: SyntaxError on invalid data type :raises: ServerError on failure to add :rtype: Bool :return: True on success
[ "Adds", "an", "anime", "to", "a", "user", "s", "list", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Mal/__init__.py#L136-L157
6,183
ccubed/PyMoe
Pymoe/Mal/__init__.py
Mal.user
def user(self, name): """ Get a user's anime list and details. This returns an encapsulated data type. :param str name: The username to query :rtype: :class:`Pymoe.Mal.Objects.User` :return: A :class:`Pymoe.Mal.Objects.User` Object """ anime_data = requests.get(self.apiusers, params={'u': name, 'status': 'all', 'type': 'anime'}, headers=self.header) if anime_data.status_code != 200: raise ConnectionError( "Anime Data Request failed. Please Open a bug on https://github.com/ccubed/Pymoe and include the following data.\nStatus Code: {}\n\nText:{}".format( anime_data.status_code, anime_data.text)) manga_data = requests.get(self.apiusers, params={'u': name, 'status': 'all', 'type': 'manga'}, headers=self.header) if manga_data.status_code != 200: raise ConnectionError( "Manga Data Request failed. Please Open a bug on https://github.com/ccubed/Pymoe and include the following data.\nStatus Code: {}\n\nText:{}".format( manga_data.status_code, manga_data.text)) root = ET.fromstring(anime_data.text) uid = root.find('myinfo').find('user_id').text uname = root.find('myinfo').find('user_name').text anime_object_list = self.parse_anime_data(anime_data.text) manga_object_list = self.parse_manga_data(manga_data.text) return User(uid=uid, name=uname, anime_list=NT_USER_ANIME( watching=[x for x in anime_object_list['data'] if x.status.user == "Currently Watching"], completed=[x for x in anime_object_list['data'] if x.status.user == "Completed"], held=[x for x in anime_object_list['data'] if x.status.user == "On Hold"], dropped=[x for x in anime_object_list['data'] if x.status.user == "Dropped"], planned=[x for x in anime_object_list['data'] if x.status.user == "Plan to Watch"] ), anime_days=anime_object_list['days'], manga_list=NT_USER_MANGA( reading=[x for x in manga_object_list['data'] if x.status.user == "Currently Reading"], completed=[x for x in manga_object_list['data'] if x.status.user == "Completed"], held=[x for x in manga_object_list['data'] if x.status.user == "On Hold"], dropped=[x for x in manga_object_list['data'] if x.status.user == "Dropped"], planned=[x for x in manga_object_list['data'] if x.status.user == "Plan to Read"] ), manga_days=manga_object_list['days'])
python
def user(self, name): anime_data = requests.get(self.apiusers, params={'u': name, 'status': 'all', 'type': 'anime'}, headers=self.header) if anime_data.status_code != 200: raise ConnectionError( "Anime Data Request failed. Please Open a bug on https://github.com/ccubed/Pymoe and include the following data.\nStatus Code: {}\n\nText:{}".format( anime_data.status_code, anime_data.text)) manga_data = requests.get(self.apiusers, params={'u': name, 'status': 'all', 'type': 'manga'}, headers=self.header) if manga_data.status_code != 200: raise ConnectionError( "Manga Data Request failed. Please Open a bug on https://github.com/ccubed/Pymoe and include the following data.\nStatus Code: {}\n\nText:{}".format( manga_data.status_code, manga_data.text)) root = ET.fromstring(anime_data.text) uid = root.find('myinfo').find('user_id').text uname = root.find('myinfo').find('user_name').text anime_object_list = self.parse_anime_data(anime_data.text) manga_object_list = self.parse_manga_data(manga_data.text) return User(uid=uid, name=uname, anime_list=NT_USER_ANIME( watching=[x for x in anime_object_list['data'] if x.status.user == "Currently Watching"], completed=[x for x in anime_object_list['data'] if x.status.user == "Completed"], held=[x for x in anime_object_list['data'] if x.status.user == "On Hold"], dropped=[x for x in anime_object_list['data'] if x.status.user == "Dropped"], planned=[x for x in anime_object_list['data'] if x.status.user == "Plan to Watch"] ), anime_days=anime_object_list['days'], manga_list=NT_USER_MANGA( reading=[x for x in manga_object_list['data'] if x.status.user == "Currently Reading"], completed=[x for x in manga_object_list['data'] if x.status.user == "Completed"], held=[x for x in manga_object_list['data'] if x.status.user == "On Hold"], dropped=[x for x in manga_object_list['data'] if x.status.user == "Dropped"], planned=[x for x in manga_object_list['data'] if x.status.user == "Plan to Read"] ), manga_days=manga_object_list['days'])
[ "def", "user", "(", "self", ",", "name", ")", ":", "anime_data", "=", "requests", ".", "get", "(", "self", ".", "apiusers", ",", "params", "=", "{", "'u'", ":", "name", ",", "'status'", ":", "'all'", ",", "'type'", ":", "'anime'", "}", ",", "header...
Get a user's anime list and details. This returns an encapsulated data type. :param str name: The username to query :rtype: :class:`Pymoe.Mal.Objects.User` :return: A :class:`Pymoe.Mal.Objects.User` Object
[ "Get", "a", "user", "s", "anime", "list", "and", "details", ".", "This", "returns", "an", "encapsulated", "data", "type", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Mal/__init__.py#L270-L316
6,184
ccubed/PyMoe
Pymoe/VNDB/connection.py
VNDBConnection.send_command
def send_command(self, command, args=None): """ Send a command to VNDB and then get the result. :param command: What command are we sending :param args: What are the json args for this command :return: Servers Response :rtype: Dictionary (See D11 docs on VNDB) """ if args: if isinstance(args, str): final_command = command + ' ' + args + '\x04' else: # We just let ujson propogate the error here if it can't parse the arguments final_command = command + ' ' + ujson.dumps(args) + '\x04' else: final_command = command + '\x04' self.sslwrap.sendall(final_command.encode('utf-8')) return self._recv_data()
python
def send_command(self, command, args=None): if args: if isinstance(args, str): final_command = command + ' ' + args + '\x04' else: # We just let ujson propogate the error here if it can't parse the arguments final_command = command + ' ' + ujson.dumps(args) + '\x04' else: final_command = command + '\x04' self.sslwrap.sendall(final_command.encode('utf-8')) return self._recv_data()
[ "def", "send_command", "(", "self", ",", "command", ",", "args", "=", "None", ")", ":", "if", "args", ":", "if", "isinstance", "(", "args", ",", "str", ")", ":", "final_command", "=", "command", "+", "' '", "+", "args", "+", "'\\x04'", "else", ":", ...
Send a command to VNDB and then get the result. :param command: What command are we sending :param args: What are the json args for this command :return: Servers Response :rtype: Dictionary (See D11 docs on VNDB)
[ "Send", "a", "command", "to", "VNDB", "and", "then", "get", "the", "result", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/VNDB/connection.py#L70-L88
6,185
ccubed/PyMoe
Pymoe/VNDB/connection.py
VNDBConnection._recv_data
def _recv_data(self): """ Receieves data until we reach the \x04 and then returns it. :return: The data received """ temp = "" while True: self.data_buffer = self.sslwrap.recv(1024) if '\x04' in self.data_buffer.decode('utf-8', 'ignore'): temp += self.data_buffer.decode('utf-8', 'ignore') break else: temp += self.data_buffer.decode('utf-8', 'ignore') self.data_buffer = bytes(1024) temp = temp.replace('\x04', '') if 'Ok' in temp: # Because login return temp else: return ujson.loads(temp.split(' ', 1)[1])
python
def _recv_data(self): temp = "" while True: self.data_buffer = self.sslwrap.recv(1024) if '\x04' in self.data_buffer.decode('utf-8', 'ignore'): temp += self.data_buffer.decode('utf-8', 'ignore') break else: temp += self.data_buffer.decode('utf-8', 'ignore') self.data_buffer = bytes(1024) temp = temp.replace('\x04', '') if 'Ok' in temp: # Because login return temp else: return ujson.loads(temp.split(' ', 1)[1])
[ "def", "_recv_data", "(", "self", ")", ":", "temp", "=", "\"\"", "while", "True", ":", "self", ".", "data_buffer", "=", "self", ".", "sslwrap", ".", "recv", "(", "1024", ")", "if", "'\\x04'", "in", "self", ".", "data_buffer", ".", "decode", "(", "'ut...
Receieves data until we reach the \x04 and then returns it. :return: The data received
[ "Receieves", "data", "until", "we", "reach", "the", "\\", "x04", "and", "then", "returns", "it", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/VNDB/connection.py#L90-L109
6,186
ccubed/PyMoe
Pymoe/Kitsu/library.py
KitsuLib.get
def get(self, uid, filters=None): """ Get a user's list of library entries. While individual entries on this list don't show what type of entry it is, you can use the filters provided by the Kitsu API to only select which ones you want :param uid: str: User ID to get library entries for :param filters: dict: Dictionary of filters for the library :return: Results or ServerError :rtype: SearchWrapper or Exception """ filters = self.__format_filters(filters) r = requests.get(self.apiurl + "/users/{}/library-entries".format(uid), headers=self.header, params=filters) if r.status_code != 200: raise ServerError jsd = r.json() if jsd['meta']['count']: return SearchWrapper(jsd['data'], jsd['links']['next'] if 'next' in jsd['links'] else None, self.header) else: return None
python
def get(self, uid, filters=None): filters = self.__format_filters(filters) r = requests.get(self.apiurl + "/users/{}/library-entries".format(uid), headers=self.header, params=filters) if r.status_code != 200: raise ServerError jsd = r.json() if jsd['meta']['count']: return SearchWrapper(jsd['data'], jsd['links']['next'] if 'next' in jsd['links'] else None, self.header) else: return None
[ "def", "get", "(", "self", ",", "uid", ",", "filters", "=", "None", ")", ":", "filters", "=", "self", ".", "__format_filters", "(", "filters", ")", "r", "=", "requests", ".", "get", "(", "self", ".", "apiurl", "+", "\"/users/{}/library-entries\"", ".", ...
Get a user's list of library entries. While individual entries on this list don't show what type of entry it is, you can use the filters provided by the Kitsu API to only select which ones you want :param uid: str: User ID to get library entries for :param filters: dict: Dictionary of filters for the library :return: Results or ServerError :rtype: SearchWrapper or Exception
[ "Get", "a", "user", "s", "list", "of", "library", "entries", ".", "While", "individual", "entries", "on", "this", "list", "don", "t", "show", "what", "type", "of", "entry", "it", "is", "you", "can", "use", "the", "filters", "provided", "by", "the", "Ki...
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/library.py#L10-L33
6,187
ccubed/PyMoe
Pymoe/Kitsu/library.py
KitsuLib.create
def create(self, user_id, media_id, item_type, token, data): """ Create a library entry for a user. data should be just the attributes. Data at least needs a status and progress. :param user_id str: User ID that this Library Entry is for :param media_id str: ID for the media this entry relates to :param item_type str: anime, drama or manga depending :param token str: OAuth token for user :param data dict: Dictionary of attributes for the entry :return: New Entry ID or ServerError :rtype: Str or Exception """ final_dict = { "data": { "type": "libraryEntries", "attributes": data, "relationships":{ "user":{ "data":{ "id": user_id, "type": "users" } }, "media":{ "data":{ "id": media_id, "type": item_type } } } } } final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.post(self.apiurl + "/library-entries", json=final_dict, headers=final_headers) if r.status_code != 201: raise ConnectionError(r.text) jsd = r.json() return jsd['data']['id']
python
def create(self, user_id, media_id, item_type, token, data): final_dict = { "data": { "type": "libraryEntries", "attributes": data, "relationships":{ "user":{ "data":{ "id": user_id, "type": "users" } }, "media":{ "data":{ "id": media_id, "type": item_type } } } } } final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.post(self.apiurl + "/library-entries", json=final_dict, headers=final_headers) if r.status_code != 201: raise ConnectionError(r.text) jsd = r.json() return jsd['data']['id']
[ "def", "create", "(", "self", ",", "user_id", ",", "media_id", ",", "item_type", ",", "token", ",", "data", ")", ":", "final_dict", "=", "{", "\"data\"", ":", "{", "\"type\"", ":", "\"libraryEntries\"", ",", "\"attributes\"", ":", "data", ",", "\"relations...
Create a library entry for a user. data should be just the attributes. Data at least needs a status and progress. :param user_id str: User ID that this Library Entry is for :param media_id str: ID for the media this entry relates to :param item_type str: anime, drama or manga depending :param token str: OAuth token for user :param data dict: Dictionary of attributes for the entry :return: New Entry ID or ServerError :rtype: Str or Exception
[ "Create", "a", "library", "entry", "for", "a", "user", ".", "data", "should", "be", "just", "the", "attributes", ".", "Data", "at", "least", "needs", "a", "status", "and", "progress", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/library.py#L35-L78
6,188
ccubed/PyMoe
Pymoe/Kitsu/library.py
KitsuLib.update
def update(self, eid, data, token): """ Update a given Library Entry. :param eid str: Entry ID :param data dict: Attributes :param token str: OAuth token :return: True or ServerError :rtype: Bool or Exception """ final_dict = {"data": {"id": eid, "type": "libraryEntries", "attributes": data}} final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.patch(self.apiurl + "/library-entries/{}".format(eid), json=final_dict, headers=final_headers) if r.status_code != 200: raise ConnectionError(r.text) return True
python
def update(self, eid, data, token): final_dict = {"data": {"id": eid, "type": "libraryEntries", "attributes": data}} final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.patch(self.apiurl + "/library-entries/{}".format(eid), json=final_dict, headers=final_headers) if r.status_code != 200: raise ConnectionError(r.text) return True
[ "def", "update", "(", "self", ",", "eid", ",", "data", ",", "token", ")", ":", "final_dict", "=", "{", "\"data\"", ":", "{", "\"id\"", ":", "eid", ",", "\"type\"", ":", "\"libraryEntries\"", ",", "\"attributes\"", ":", "data", "}", "}", "final_headers", ...
Update a given Library Entry. :param eid str: Entry ID :param data dict: Attributes :param token str: OAuth token :return: True or ServerError :rtype: Bool or Exception
[ "Update", "a", "given", "Library", "Entry", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/library.py#L80-L99
6,189
ccubed/PyMoe
Pymoe/Kitsu/library.py
KitsuLib.delete
def delete(self, eid, token): """ Delete a library entry. :param eid str: Entry ID :param token str: OAuth Token :return: True or ServerError :rtype: Bool or Exception """ final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.delete(self.apiurl + "/library-entries/{}".format(eid), headers=final_headers) if r.status_code != 204: print(r.status_code) raise ConnectionError(r.text) return True
python
def delete(self, eid, token): final_headers = self.header final_headers['Authorization'] = "Bearer {}".format(token) r = requests.delete(self.apiurl + "/library-entries/{}".format(eid), headers=final_headers) if r.status_code != 204: print(r.status_code) raise ConnectionError(r.text) return True
[ "def", "delete", "(", "self", ",", "eid", ",", "token", ")", ":", "final_headers", "=", "self", ".", "header", "final_headers", "[", "'Authorization'", "]", "=", "\"Bearer {}\"", ".", "format", "(", "token", ")", "r", "=", "requests", ".", "delete", "(",...
Delete a library entry. :param eid str: Entry ID :param token str: OAuth Token :return: True or ServerError :rtype: Bool or Exception
[ "Delete", "a", "library", "entry", "." ]
5b2a2591bb113bd80d838e65aaa06f3a97ff3670
https://github.com/ccubed/PyMoe/blob/5b2a2591bb113bd80d838e65aaa06f3a97ff3670/Pymoe/Kitsu/library.py#L101-L119
6,190
wecatch/app-turbo
turbo/mongo_model.py
convert_to_record
def convert_to_record(func): """Wrap mongodb record to a dict record with default value None """ @functools.wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if result is not None: if isinstance(result, dict): return _record(result) return (_record(i) for i in result) return result return wrapper
python
def convert_to_record(func): @functools.wraps(func) def wrapper(self, *args, **kwargs): result = func(self, *args, **kwargs) if result is not None: if isinstance(result, dict): return _record(result) return (_record(i) for i in result) return result return wrapper
[ "def", "convert_to_record", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "func", "(", "self", ",", "*", "args", ",", "*...
Wrap mongodb record to a dict record with default value None
[ "Wrap", "mongodb", "record", "to", "a", "dict", "record", "with", "default", "value", "None" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/mongo_model.py#L23-L36
6,191
wecatch/app-turbo
turbo/mongo_model.py
MixinModel.to_one_str
def to_one_str(cls, value, *args, **kwargs): """Convert single record's values to str """ if kwargs.get('wrapper'): return cls._wrapper_to_one_str(value) return _es.to_dict_str(value)
python
def to_one_str(cls, value, *args, **kwargs): if kwargs.get('wrapper'): return cls._wrapper_to_one_str(value) return _es.to_dict_str(value)
[ "def", "to_one_str", "(", "cls", ",", "value", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'wrapper'", ")", ":", "return", "cls", ".", "_wrapper_to_one_str", "(", "value", ")", "return", "_es", ".", "to_dict...
Convert single record's values to str
[ "Convert", "single", "record", "s", "values", "to", "str" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/mongo_model.py#L67-L73
6,192
wecatch/app-turbo
turbo/mongo_model.py
MixinModel.to_str
def to_str(cls, values, callback=None): """Convert many records's values to str """ if callback and callable(callback): if isinstance(values, dict): return callback(_es.to_str(values)) return [callback(_es.to_str(i)) for i in values] return _es.to_str(values)
python
def to_str(cls, values, callback=None): if callback and callable(callback): if isinstance(values, dict): return callback(_es.to_str(values)) return [callback(_es.to_str(i)) for i in values] return _es.to_str(values)
[ "def", "to_str", "(", "cls", ",", "values", ",", "callback", "=", "None", ")", ":", "if", "callback", "and", "callable", "(", "callback", ")", ":", "if", "isinstance", "(", "values", ",", "dict", ")", ":", "return", "callback", "(", "_es", ".", "to_s...
Convert many records's values to str
[ "Convert", "many", "records", "s", "values", "to", "str" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/mongo_model.py#L76-L84
6,193
wecatch/app-turbo
turbo/mongo_model.py
MixinModel.import_model
def import_model(cls, ins_name): """Import model class in models package """ try: package_space = getattr(cls, 'package_space') except AttributeError: raise ValueError('package_space not exist') else: return import_object(ins_name, package_space)
python
def import_model(cls, ins_name): try: package_space = getattr(cls, 'package_space') except AttributeError: raise ValueError('package_space not exist') else: return import_object(ins_name, package_space)
[ "def", "import_model", "(", "cls", ",", "ins_name", ")", ":", "try", ":", "package_space", "=", "getattr", "(", "cls", ",", "'package_space'", ")", "except", "AttributeError", ":", "raise", "ValueError", "(", "'package_space not exist'", ")", "else", ":", "ret...
Import model class in models package
[ "Import", "model", "class", "in", "models", "package" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/mongo_model.py#L132-L140
6,194
wecatch/app-turbo
turbo/register.py
register_app
def register_app(app_name, app_setting, web_application_setting, mainfile, package_space): """insert current project root path into sys path """ from turbo import log app_config.app_name = app_name app_config.app_setting = app_setting app_config.project_name = os.path.basename(get_base_dir(mainfile, 2)) app_config.web_application_setting.update(web_application_setting) if app_setting.get('session_config'): app_config.session_config.update(app_setting['session_config']) log.getLogger(**app_setting.log) _install_app(package_space)
python
def register_app(app_name, app_setting, web_application_setting, mainfile, package_space): from turbo import log app_config.app_name = app_name app_config.app_setting = app_setting app_config.project_name = os.path.basename(get_base_dir(mainfile, 2)) app_config.web_application_setting.update(web_application_setting) if app_setting.get('session_config'): app_config.session_config.update(app_setting['session_config']) log.getLogger(**app_setting.log) _install_app(package_space)
[ "def", "register_app", "(", "app_name", ",", "app_setting", ",", "web_application_setting", ",", "mainfile", ",", "package_space", ")", ":", "from", "turbo", "import", "log", "app_config", ".", "app_name", "=", "app_name", "app_config", ".", "app_setting", "=", ...
insert current project root path into sys path
[ "insert", "current", "project", "root", "path", "into", "sys", "path" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/register.py#L14-L25
6,195
wecatch/app-turbo
turbo/register.py
register_url
def register_url(url, handler, name=None, kwargs=None): """insert url into tornado application handlers group :arg str url: url :handler object handler: url mapping handler :name reverse url name :kwargs dict tornado handler initlize args """ if name is None and kwargs is None: app_config.urls.append((url, handler)) return if name is None: app_config.urls.append((url, handler, kwargs)) return app_config.urls.append((url, handler, kwargs, name))
python
def register_url(url, handler, name=None, kwargs=None): if name is None and kwargs is None: app_config.urls.append((url, handler)) return if name is None: app_config.urls.append((url, handler, kwargs)) return app_config.urls.append((url, handler, kwargs, name))
[ "def", "register_url", "(", "url", ",", "handler", ",", "name", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "name", "is", "None", "and", "kwargs", "is", "None", ":", "app_config", ".", "urls", ".", "append", "(", "(", "url", ",", "hand...
insert url into tornado application handlers group :arg str url: url :handler object handler: url mapping handler :name reverse url name :kwargs dict tornado handler initlize args
[ "insert", "url", "into", "tornado", "application", "handlers", "group" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/register.py#L28-L44
6,196
wecatch/app-turbo
turbo/app.py
BaseBaseHandler.parameter
def parameter(self): ''' according to request method config to filter all request paremter if value is invalid then set None ''' method = self.request.method.lower() arguments = self.request.arguments files = self.request.files rpd = {} # request parameter dict def filter_parameter(key, tp, default=None): if tp not in self._types: raise ValueError( '%s parameter expected types %s' % (key, self._types)) if not isinstance(tp, file_types): if key not in arguments: rpd[key] = default return if tp in [ObjectId, int, float, bool]: rpd[key] = getattr(self, 'to_%s' % getattr( tp, '__name__').lower())(self.get_argument(key)) return if tp == basestring_type or issubclass(tp, basestring_type): rpd[key] = self.get_argument(key, strip=False) return if tp == list: rpd[key] = self.get_arguments(key) return if tp == file: if key not in files: rpd[key] = [] return rpd[key] = self.request.files[key] required_params = getattr(self, '_required_params', None) if isinstance(required_params, list): for key, tp, default in required_params: filter_parameter(key, tp, default) # extract method required params method_required_params = getattr( self, '_%s_required_params' % method, None) if isinstance(method_required_params, list): for key, tp, default in method_required_params: filter_parameter(key, tp, default) params = getattr(self, '_%s_params' % method, None) if params is None: return rpd # need arguments try: for key, tp in params.get('need', []): if tp == list: filter_parameter(key, tp, []) else: filter_parameter(key, tp) except ValueError as e: app_log.error( '%s request need arguments parse error: %s' % (method, e)) raise ValueError(e) except Exception as e: app_log.error( '%s request need arguments parse error: %s' % (method, e)) raise e # option arguments for key, tp, default in params.get('option', []): filter_parameter(key, tp, default) return rpd
python
def parameter(self): ''' according to request method config to filter all request paremter if value is invalid then set None ''' method = self.request.method.lower() arguments = self.request.arguments files = self.request.files rpd = {} # request parameter dict def filter_parameter(key, tp, default=None): if tp not in self._types: raise ValueError( '%s parameter expected types %s' % (key, self._types)) if not isinstance(tp, file_types): if key not in arguments: rpd[key] = default return if tp in [ObjectId, int, float, bool]: rpd[key] = getattr(self, 'to_%s' % getattr( tp, '__name__').lower())(self.get_argument(key)) return if tp == basestring_type or issubclass(tp, basestring_type): rpd[key] = self.get_argument(key, strip=False) return if tp == list: rpd[key] = self.get_arguments(key) return if tp == file: if key not in files: rpd[key] = [] return rpd[key] = self.request.files[key] required_params = getattr(self, '_required_params', None) if isinstance(required_params, list): for key, tp, default in required_params: filter_parameter(key, tp, default) # extract method required params method_required_params = getattr( self, '_%s_required_params' % method, None) if isinstance(method_required_params, list): for key, tp, default in method_required_params: filter_parameter(key, tp, default) params = getattr(self, '_%s_params' % method, None) if params is None: return rpd # need arguments try: for key, tp in params.get('need', []): if tp == list: filter_parameter(key, tp, []) else: filter_parameter(key, tp) except ValueError as e: app_log.error( '%s request need arguments parse error: %s' % (method, e)) raise ValueError(e) except Exception as e: app_log.error( '%s request need arguments parse error: %s' % (method, e)) raise e # option arguments for key, tp, default in params.get('option', []): filter_parameter(key, tp, default) return rpd
[ "def", "parameter", "(", "self", ")", ":", "method", "=", "self", ".", "request", ".", "method", ".", "lower", "(", ")", "arguments", "=", "self", ".", "request", ".", "arguments", "files", "=", "self", ".", "request", ".", "files", "rpd", "=", "{", ...
according to request method config to filter all request paremter if value is invalid then set None
[ "according", "to", "request", "method", "config", "to", "filter", "all", "request", "paremter", "if", "value", "is", "invalid", "then", "set", "None" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/app.py#L173-L250
6,197
wecatch/app-turbo
turbo/app.py
BaseBaseHandler.wo_resp
def wo_resp(self, resp): """ can override for other style """ if self._data is not None: resp['res'] = self.to_str(self._data) return self.wo_json(resp)
python
def wo_resp(self, resp): if self._data is not None: resp['res'] = self.to_str(self._data) return self.wo_json(resp)
[ "def", "wo_resp", "(", "self", ",", "resp", ")", ":", "if", "self", ".", "_data", "is", "not", "None", ":", "resp", "[", "'res'", "]", "=", "self", ".", "to_str", "(", "self", ".", "_data", ")", "return", "self", ".", "wo_json", "(", "resp", ")" ...
can override for other style
[ "can", "override", "for", "other", "style" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/app.py#L307-L314
6,198
wecatch/app-turbo
turbo/model.py
BaseBaseModel.find
def find(self, *args, **kwargs): """collection find method """ wrapper = kwargs.pop('wrapper', False) if wrapper is True: return self._wrapper_find(*args, **kwargs) return self.__collect.find(*args, **kwargs)
python
def find(self, *args, **kwargs): wrapper = kwargs.pop('wrapper', False) if wrapper is True: return self._wrapper_find(*args, **kwargs) return self.__collect.find(*args, **kwargs)
[ "def", "find", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wrapper", "=", "kwargs", ".", "pop", "(", "'wrapper'", ",", "False", ")", "if", "wrapper", "is", "True", ":", "return", "self", ".", "_wrapper_find", "(", "*", "args"...
collection find method
[ "collection", "find", "method" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/model.py#L120-L128
6,199
wecatch/app-turbo
turbo/model.py
BaseBaseModel._wrapper_find_one
def _wrapper_find_one(self, filter_=None, *args, **kwargs): """Convert record to a dict that has no key error """ return self.__collect.find_one(filter_, *args, **kwargs)
python
def _wrapper_find_one(self, filter_=None, *args, **kwargs): return self.__collect.find_one(filter_, *args, **kwargs)
[ "def", "_wrapper_find_one", "(", "self", ",", "filter_", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__collect", ".", "find_one", "(", "filter_", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Convert record to a dict that has no key error
[ "Convert", "record", "to", "a", "dict", "that", "has", "no", "key", "error" ]
75faf97371a9a138c53f92168d0a486636cb8a9c
https://github.com/wecatch/app-turbo/blob/75faf97371a9a138c53f92168d0a486636cb8a9c/turbo/model.py#L131-L134