repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_documentation_string
stringlengths
1
47.2k
func_code_url
stringlengths
85
339
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 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
Yield instructions to process a str or bytes constant.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/transformers/interpolated_strings.py#L109-L117
llllllllll/codetransformer
codetransformer/instructions.py
_mk_call_init
def _mk_call_init(class_): """Create an __init__ function for a call type instruction. Parameters ---------- class_ : type The type to bind the function to. Returns ------- __init__ : callable The __init__ method for the class. """ def __init__(self, packed=no_default, *, positional=0, keyword=0): if packed is no_default: arg = int.from_bytes(bytes((positional, keyword)), 'little') elif not positional and not keyword: arg = packed else: raise TypeError('cannot specify packed and unpacked arguments') self.positional, self.keyword = arg.to_bytes(2, 'little') super(class_, self).__init__(arg) return __init__
python
def _mk_call_init(class_): """Create an __init__ function for a call type instruction. Parameters ---------- class_ : type The type to bind the function to. Returns ------- __init__ : callable The __init__ method for the class. """ def __init__(self, packed=no_default, *, positional=0, keyword=0): if packed is no_default: arg = int.from_bytes(bytes((positional, keyword)), 'little') elif not positional and not keyword: arg = packed else: raise TypeError('cannot specify packed and unpacked arguments') self.positional, self.keyword = arg.to_bytes(2, 'little') super(class_, self).__init__(arg) return __init__
Create an __init__ function for a call type instruction. Parameters ---------- class_ : type The type to bind the function to. Returns ------- __init__ : callable The __init__ method for the class.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L270-L293
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): """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
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.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L161-L186
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): """ 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)
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``.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L189-L205
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): """ 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 ()) )
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).
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L208-L236
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): """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
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.
https://github.com/llllllllll/codetransformer/blob/c5f551e915df45adc7da7e0b1b635f0cc6a1bb27/codetransformer/instructions.py#L238-L259
jedie/DragonPy
boot_dragonpy.py
create_environment
def create_environment(home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, download=False, no_setuptools=False, no_pip=False, no_wheel=False, symlink=True): """ Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared. """ home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) py_executable = os.path.abspath(install_python( home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear, symlink=symlink)) install_distutils(home_dir) to_install = [] if not no_setuptools: to_install.append('setuptools') if not no_pip: to_install.append('pip') if not no_wheel: to_install.append('wheel') if to_install: install_wheel( to_install, py_executable, search_dirs, download=download, ) install_activate(home_dir, bin_dir, prompt) install_python_config(home_dir, bin_dir, prompt)
python
def create_environment(home_dir, site_packages=False, clear=False, unzip_setuptools=False, prompt=None, search_dirs=None, download=False, no_setuptools=False, no_pip=False, no_wheel=False, symlink=True): """ Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared. """ home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) py_executable = os.path.abspath(install_python( home_dir, lib_dir, inc_dir, bin_dir, site_packages=site_packages, clear=clear, symlink=symlink)) install_distutils(home_dir) to_install = [] if not no_setuptools: to_install.append('setuptools') if not no_pip: to_install.append('pip') if not no_wheel: to_install.append('wheel') if to_install: install_wheel( to_install, py_executable, search_dirs, download=download, ) install_activate(home_dir, bin_dir, prompt) install_python_config(home_dir, bin_dir, prompt)
Creates a new environment in ``home_dir``. If ``site_packages`` is true, then the global ``site-packages/`` directory will be on the path. If ``clear`` is true (default False) then the environment will first be cleared.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L913-L956
jedie/DragonPy
boot_dragonpy.py
path_locations
def path_locations(home_dir): """Return the path locations for the environment (where libraries are, where scripts go, etc)""" home_dir = os.path.abspath(home_dir) # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its # prefix arg is broken: http://bugs.python.org/issue3386 if is_win: # Windows has lots of problems with executables with spaces in # the name; this function will remove them (using the ~1 # format): mkdir(home_dir) if ' ' in home_dir: import ctypes GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW size = max(len(home_dir)+1, 256) buf = ctypes.create_unicode_buffer(size) try: u = unicode except NameError: u = str ret = GetShortPathName(u(home_dir), buf, size) if not ret: print('Error: the path "%s" has a space in it' % home_dir) print('We could not determine the short pathname for it.') print('Exiting.') sys.exit(3) home_dir = str(buf.value) lib_dir = join(home_dir, 'Lib') inc_dir = join(home_dir, 'Include') bin_dir = join(home_dir, 'Scripts') if is_jython: lib_dir = join(home_dir, 'Lib') inc_dir = join(home_dir, 'Include') bin_dir = join(home_dir, 'bin') elif is_pypy: lib_dir = home_dir inc_dir = join(home_dir, 'include') bin_dir = join(home_dir, 'bin') elif not is_win: lib_dir = join(home_dir, 'lib', py_version) inc_dir = join(home_dir, 'include', py_version + abiflags) bin_dir = join(home_dir, 'bin') return home_dir, lib_dir, inc_dir, bin_dir
python
def path_locations(home_dir): """Return the path locations for the environment (where libraries are, where scripts go, etc)""" home_dir = os.path.abspath(home_dir) # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its # prefix arg is broken: http://bugs.python.org/issue3386 if is_win: # Windows has lots of problems with executables with spaces in # the name; this function will remove them (using the ~1 # format): mkdir(home_dir) if ' ' in home_dir: import ctypes GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW size = max(len(home_dir)+1, 256) buf = ctypes.create_unicode_buffer(size) try: u = unicode except NameError: u = str ret = GetShortPathName(u(home_dir), buf, size) if not ret: print('Error: the path "%s" has a space in it' % home_dir) print('We could not determine the short pathname for it.') print('Exiting.') sys.exit(3) home_dir = str(buf.value) lib_dir = join(home_dir, 'Lib') inc_dir = join(home_dir, 'Include') bin_dir = join(home_dir, 'Scripts') if is_jython: lib_dir = join(home_dir, 'Lib') inc_dir = join(home_dir, 'Include') bin_dir = join(home_dir, 'bin') elif is_pypy: lib_dir = home_dir inc_dir = join(home_dir, 'include') bin_dir = join(home_dir, 'bin') elif not is_win: lib_dir = join(home_dir, 'lib', py_version) inc_dir = join(home_dir, 'include', py_version + abiflags) bin_dir = join(home_dir, 'bin') return home_dir, lib_dir, inc_dir, bin_dir
Return the path locations for the environment (where libraries are, where scripts go, etc)
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L961-L1003
jedie/DragonPy
boot_dragonpy.py
copy_tcltk
def copy_tcltk(src, dest, symlink): """ copy tcl/tk libraries on Windows (issue #93) """ if majver == 2: libver = '8.5' else: libver = '8.6' for name in ['tcl', 'tk']: srcdir = src + '/tcl/' + name + libver dstdir = dest + '/tcl/' + name + libver copyfileordir(srcdir, dstdir, symlink)
python
def copy_tcltk(src, dest, symlink): """ copy tcl/tk libraries on Windows (issue #93) """ if majver == 2: libver = '8.5' else: libver = '8.6' for name in ['tcl', 'tk']: srcdir = src + '/tcl/' + name + libver dstdir = dest + '/tcl/' + name + libver copyfileordir(srcdir, dstdir, symlink)
copy tcl/tk libraries on Windows (issue #93)
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1075-L1084
jedie/DragonPy
boot_dragonpy.py
install_python
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True): """Install just the base environment, no distutils patches etc""" if sys.executable.startswith(bin_dir): print('Please use the *system* python to run this script') return if clear: rmtree(lib_dir) ## FIXME: why not delete it? ## Maybe it should delete everything with #!/path/to/venv/python in it logger.notify('Not deleting %s', bin_dir) if hasattr(sys, 'real_prefix'): logger.notify('Using real prefix %r' % sys.real_prefix) prefix = sys.real_prefix elif hasattr(sys, 'base_prefix'): logger.notify('Using base prefix %r' % sys.base_prefix) prefix = sys.base_prefix else: prefix = sys.prefix mkdir(lib_dir) fix_lib64(lib_dir, symlink) stdlib_dirs = [os.path.dirname(os.__file__)] if is_win: stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs')) elif is_darwin: stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages')) if hasattr(os, 'symlink'): logger.info('Symlinking Python bootstrap modules') else: logger.info('Copying Python bootstrap modules') logger.indent += 2 try: # copy required files... for stdlib_dir in stdlib_dirs: if not os.path.isdir(stdlib_dir): continue for fn in os.listdir(stdlib_dir): bn = os.path.splitext(fn)[0] if fn != 'site-packages' and bn in REQUIRED_FILES: copyfile(join(stdlib_dir, fn), join(lib_dir, fn), symlink) # ...and modules copy_required_modules(home_dir, symlink) finally: logger.indent -= 2 # ...copy tcl/tk if is_win: copy_tcltk(prefix, home_dir, symlink) mkdir(join(lib_dir, 'site-packages')) import site site_filename = site.__file__ if site_filename.endswith('.pyc') or site_filename.endswith('.pyo'): site_filename = site_filename[:-1] elif site_filename.endswith('$py.class'): site_filename = site_filename.replace('$py.class', '.py') site_filename_dst = change_prefix(site_filename, home_dir) site_dir = os.path.dirname(site_filename_dst) writefile(site_filename_dst, SITE_PY) writefile(join(site_dir, 'orig-prefix.txt'), prefix) site_packages_filename = join(site_dir, 'no-global-site-packages.txt') if not site_packages: writefile(site_packages_filename, '') if is_pypy or is_win: stdinc_dir = join(prefix, 'include') else: stdinc_dir = join(prefix, 'include', py_version + abiflags) if os.path.exists(stdinc_dir): copyfile(stdinc_dir, inc_dir, symlink) else: logger.debug('No include dir %s' % stdinc_dir) platinc_dir = distutils.sysconfig.get_python_inc(plat_specific=1) if platinc_dir != stdinc_dir: platinc_dest = distutils.sysconfig.get_python_inc( plat_specific=1, prefix=home_dir) if platinc_dir == platinc_dest: # Do platinc_dest manually due to a CPython bug; # not http://bugs.python.org/issue3386 but a close cousin platinc_dest = subst_path(platinc_dir, prefix, home_dir) if platinc_dest: # PyPy's stdinc_dir and prefix are relative to the original binary # (traversing virtualenvs), whereas the platinc_dir is relative to # the inner virtualenv and ignores the prefix argument. # This seems more evolved than designed. copyfile(platinc_dir, platinc_dest, symlink) # pypy never uses exec_prefix, just ignore it if sys.exec_prefix != prefix and not is_pypy: if is_win: exec_dir = join(sys.exec_prefix, 'lib') elif is_jython: exec_dir = join(sys.exec_prefix, 'Lib') else: exec_dir = join(sys.exec_prefix, 'lib', py_version) for fn in os.listdir(exec_dir): copyfile(join(exec_dir, fn), join(lib_dir, fn), symlink) if is_jython: # Jython has either jython-dev.jar and javalib/ dir, or just # jython.jar for name in 'jython-dev.jar', 'javalib', 'jython.jar': src = join(prefix, name) if os.path.exists(src): copyfile(src, join(home_dir, name), symlink) # XXX: registry should always exist after Jython 2.5rc1 src = join(prefix, 'registry') if os.path.exists(src): copyfile(src, join(home_dir, 'registry'), symlink=False) copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'), symlink=False) mkdir(bin_dir) py_executable = join(bin_dir, os.path.basename(sys.executable)) if 'Python.framework' in prefix: # OS X framework builds cause validation to break # https://github.com/pypa/virtualenv/issues/322 if os.environ.get('__PYVENV_LAUNCHER__'): del os.environ["__PYVENV_LAUNCHER__"] if re.search(r'/Python(?:-32|-64)*$', py_executable): # The name of the python executable is not quite what # we want, rename it. py_executable = os.path.join( os.path.dirname(py_executable), 'python') logger.notify('New %s executable in %s', expected_exe, py_executable) pcbuild_dir = os.path.dirname(sys.executable) pyd_pth = os.path.join(lib_dir, 'site-packages', 'virtualenv_builddir_pyd.pth') if is_win and os.path.exists(os.path.join(pcbuild_dir, 'build.bat')): logger.notify('Detected python running from build directory %s', pcbuild_dir) logger.notify('Writing .pth file linking to build directory for *.pyd files') writefile(pyd_pth, pcbuild_dir) else: pcbuild_dir = None if os.path.exists(pyd_pth): logger.info('Deleting %s (not Windows env or not build directory python)' % pyd_pth) os.unlink(pyd_pth) if sys.executable != py_executable: ## FIXME: could I just hard link? executable = sys.executable shutil.copyfile(executable, py_executable) make_exe(py_executable) if is_win or is_cygwin: pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe') if os.path.exists(pythonw): logger.info('Also created pythonw.exe') shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe')) python_d = os.path.join(os.path.dirname(sys.executable), 'python_d.exe') python_d_dest = os.path.join(os.path.dirname(py_executable), 'python_d.exe') if os.path.exists(python_d): logger.info('Also created python_d.exe') shutil.copyfile(python_d, python_d_dest) elif os.path.exists(python_d_dest): logger.info('Removed python_d.exe as it is no longer at the source') os.unlink(python_d_dest) # we need to copy the DLL to enforce that windows will load the correct one. # may not exist if we are cygwin. py_executable_dll = 'python%s%s.dll' % ( sys.version_info[0], sys.version_info[1]) py_executable_dll_d = 'python%s%s_d.dll' % ( sys.version_info[0], sys.version_info[1]) pythondll = os.path.join(os.path.dirname(sys.executable), py_executable_dll) pythondll_d = os.path.join(os.path.dirname(sys.executable), py_executable_dll_d) pythondll_d_dest = os.path.join(os.path.dirname(py_executable), py_executable_dll_d) if os.path.exists(pythondll): logger.info('Also created %s' % py_executable_dll) shutil.copyfile(pythondll, os.path.join(os.path.dirname(py_executable), py_executable_dll)) if os.path.exists(pythondll_d): logger.info('Also created %s' % py_executable_dll_d) shutil.copyfile(pythondll_d, pythondll_d_dest) elif os.path.exists(pythondll_d_dest): logger.info('Removed %s as the source does not exist' % pythondll_d_dest) os.unlink(pythondll_d_dest) if is_pypy: # make a symlink python --> pypy-c python_executable = os.path.join(os.path.dirname(py_executable), 'python') if sys.platform in ('win32', 'cygwin'): python_executable += '.exe' logger.info('Also created executable %s' % python_executable) copyfile(py_executable, python_executable, symlink) if is_win: for name in ['libexpat.dll', 'libpypy.dll', 'libpypy-c.dll', 'libeay32.dll', 'ssleay32.dll', 'sqlite3.dll', 'tcl85.dll', 'tk85.dll']: src = join(prefix, name) if os.path.exists(src): copyfile(src, join(bin_dir, name), symlink) for d in sys.path: if d.endswith('lib_pypy'): break else: logger.fatal('Could not find lib_pypy in sys.path') raise SystemExit(3) logger.info('Copying lib_pypy') copyfile(d, os.path.join(home_dir, 'lib_pypy'), symlink) if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe: secondary_exe = os.path.join(os.path.dirname(py_executable), expected_exe) py_executable_ext = os.path.splitext(py_executable)[1] if py_executable_ext.lower() == '.exe': # python2.4 gives an extension of '.4' :P secondary_exe += py_executable_ext if os.path.exists(secondary_exe): logger.warn('Not overwriting existing %s script %s (you must use %s)' % (expected_exe, secondary_exe, py_executable)) else: logger.notify('Also creating executable in %s' % secondary_exe) shutil.copyfile(sys.executable, secondary_exe) make_exe(secondary_exe) if '.framework' in prefix: if 'Python.framework' in prefix: logger.debug('MacOSX Python framework detected') # Make sure we use the embedded interpreter inside # the framework, even if sys.executable points to # the stub executable in ${sys.prefix}/bin # See http://groups.google.com/group/python-virtualenv/ # browse_thread/thread/17cab2f85da75951 original_python = os.path.join( prefix, 'Resources/Python.app/Contents/MacOS/Python') if 'EPD' in prefix: logger.debug('EPD framework detected') original_python = os.path.join(prefix, 'bin/python') shutil.copy(original_python, py_executable) # Copy the framework's dylib into the virtual # environment virtual_lib = os.path.join(home_dir, '.Python') if os.path.exists(virtual_lib): os.unlink(virtual_lib) copyfile( os.path.join(prefix, 'Python'), virtual_lib, symlink) # And then change the install_name of the copied python executable try: mach_o_change(py_executable, os.path.join(prefix, 'Python'), '@executable_path/../.Python') except: e = sys.exc_info()[1] logger.warn("Could not call mach_o_change: %s. " "Trying to call install_name_tool instead." % e) try: call_subprocess( ["install_name_tool", "-change", os.path.join(prefix, 'Python'), '@executable_path/../.Python', py_executable]) except: logger.fatal("Could not call install_name_tool -- you must " "have Apple's development tools installed") raise if not is_win: # Ensure that 'python', 'pythonX' and 'pythonX.Y' all exist py_exe_version_major = 'python%s' % sys.version_info[0] py_exe_version_major_minor = 'python%s.%s' % ( sys.version_info[0], sys.version_info[1]) py_exe_no_version = 'python' required_symlinks = [ py_exe_no_version, py_exe_version_major, py_exe_version_major_minor ] py_executable_base = os.path.basename(py_executable) if py_executable_base in required_symlinks: # Don't try to symlink to yourself. required_symlinks.remove(py_executable_base) for pth in required_symlinks: full_pth = join(bin_dir, pth) if os.path.exists(full_pth): os.unlink(full_pth) if symlink: os.symlink(py_executable_base, full_pth) else: copyfile(py_executable, full_pth, symlink) if is_win and ' ' in py_executable: # There's a bug with subprocess on Windows when using a first # argument that has a space in it. Instead we have to quote # the value: py_executable = '"%s"' % py_executable # NOTE: keep this check as one line, cmd.exe doesn't cope with line breaks cmd = [py_executable, '-c', 'import sys;out=sys.stdout;' 'getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))'] logger.info('Testing executable with %s %s "%s"' % tuple(cmd)) try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) proc_stdout, proc_stderr = proc.communicate() except OSError: e = sys.exc_info()[1] if e.errno == errno.EACCES: logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e)) sys.exit(100) else: raise e proc_stdout = proc_stdout.strip().decode("utf-8") proc_stdout = os.path.normcase(os.path.abspath(proc_stdout)) norm_home_dir = os.path.normcase(os.path.abspath(home_dir)) if hasattr(norm_home_dir, 'decode'): norm_home_dir = norm_home_dir.decode(sys.getfilesystemencoding()) if proc_stdout != norm_home_dir: logger.fatal( 'ERROR: The executable %s is not functioning' % py_executable) logger.fatal( 'ERROR: It thinks sys.prefix is %r (should be %r)' % (proc_stdout, norm_home_dir)) logger.fatal( 'ERROR: virtualenv is not compatible with this system or executable') if is_win: logger.fatal( 'Note: some Windows users have reported this error when they ' 'installed Python for "Only this user" or have multiple ' 'versions of Python installed. Copying the appropriate ' 'PythonXX.dll to the virtualenv Scripts/ directory may fix ' 'this problem.') sys.exit(100) else: logger.info('Got sys.prefix result: %r' % proc_stdout) pydistutils = os.path.expanduser('~/.pydistutils.cfg') if os.path.exists(pydistutils): logger.notify('Please make sure you remove any previous custom paths from ' 'your %s file.' % pydistutils) ## FIXME: really this should be calculated earlier fix_local_scheme(home_dir, symlink) if site_packages: if os.path.exists(site_packages_filename): logger.info('Deleting %s' % site_packages_filename) os.unlink(site_packages_filename) return py_executable
python
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True): """Install just the base environment, no distutils patches etc""" if sys.executable.startswith(bin_dir): print('Please use the *system* python to run this script') return if clear: rmtree(lib_dir) ## FIXME: why not delete it? ## Maybe it should delete everything with #!/path/to/venv/python in it logger.notify('Not deleting %s', bin_dir) if hasattr(sys, 'real_prefix'): logger.notify('Using real prefix %r' % sys.real_prefix) prefix = sys.real_prefix elif hasattr(sys, 'base_prefix'): logger.notify('Using base prefix %r' % sys.base_prefix) prefix = sys.base_prefix else: prefix = sys.prefix mkdir(lib_dir) fix_lib64(lib_dir, symlink) stdlib_dirs = [os.path.dirname(os.__file__)] if is_win: stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs')) elif is_darwin: stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages')) if hasattr(os, 'symlink'): logger.info('Symlinking Python bootstrap modules') else: logger.info('Copying Python bootstrap modules') logger.indent += 2 try: # copy required files... for stdlib_dir in stdlib_dirs: if not os.path.isdir(stdlib_dir): continue for fn in os.listdir(stdlib_dir): bn = os.path.splitext(fn)[0] if fn != 'site-packages' and bn in REQUIRED_FILES: copyfile(join(stdlib_dir, fn), join(lib_dir, fn), symlink) # ...and modules copy_required_modules(home_dir, symlink) finally: logger.indent -= 2 # ...copy tcl/tk if is_win: copy_tcltk(prefix, home_dir, symlink) mkdir(join(lib_dir, 'site-packages')) import site site_filename = site.__file__ if site_filename.endswith('.pyc') or site_filename.endswith('.pyo'): site_filename = site_filename[:-1] elif site_filename.endswith('$py.class'): site_filename = site_filename.replace('$py.class', '.py') site_filename_dst = change_prefix(site_filename, home_dir) site_dir = os.path.dirname(site_filename_dst) writefile(site_filename_dst, SITE_PY) writefile(join(site_dir, 'orig-prefix.txt'), prefix) site_packages_filename = join(site_dir, 'no-global-site-packages.txt') if not site_packages: writefile(site_packages_filename, '') if is_pypy or is_win: stdinc_dir = join(prefix, 'include') else: stdinc_dir = join(prefix, 'include', py_version + abiflags) if os.path.exists(stdinc_dir): copyfile(stdinc_dir, inc_dir, symlink) else: logger.debug('No include dir %s' % stdinc_dir) platinc_dir = distutils.sysconfig.get_python_inc(plat_specific=1) if platinc_dir != stdinc_dir: platinc_dest = distutils.sysconfig.get_python_inc( plat_specific=1, prefix=home_dir) if platinc_dir == platinc_dest: # Do platinc_dest manually due to a CPython bug; # not http://bugs.python.org/issue3386 but a close cousin platinc_dest = subst_path(platinc_dir, prefix, home_dir) if platinc_dest: # PyPy's stdinc_dir and prefix are relative to the original binary # (traversing virtualenvs), whereas the platinc_dir is relative to # the inner virtualenv and ignores the prefix argument. # This seems more evolved than designed. copyfile(platinc_dir, platinc_dest, symlink) # pypy never uses exec_prefix, just ignore it if sys.exec_prefix != prefix and not is_pypy: if is_win: exec_dir = join(sys.exec_prefix, 'lib') elif is_jython: exec_dir = join(sys.exec_prefix, 'Lib') else: exec_dir = join(sys.exec_prefix, 'lib', py_version) for fn in os.listdir(exec_dir): copyfile(join(exec_dir, fn), join(lib_dir, fn), symlink) if is_jython: # Jython has either jython-dev.jar and javalib/ dir, or just # jython.jar for name in 'jython-dev.jar', 'javalib', 'jython.jar': src = join(prefix, name) if os.path.exists(src): copyfile(src, join(home_dir, name), symlink) # XXX: registry should always exist after Jython 2.5rc1 src = join(prefix, 'registry') if os.path.exists(src): copyfile(src, join(home_dir, 'registry'), symlink=False) copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'), symlink=False) mkdir(bin_dir) py_executable = join(bin_dir, os.path.basename(sys.executable)) if 'Python.framework' in prefix: # OS X framework builds cause validation to break # https://github.com/pypa/virtualenv/issues/322 if os.environ.get('__PYVENV_LAUNCHER__'): del os.environ["__PYVENV_LAUNCHER__"] if re.search(r'/Python(?:-32|-64)*$', py_executable): # The name of the python executable is not quite what # we want, rename it. py_executable = os.path.join( os.path.dirname(py_executable), 'python') logger.notify('New %s executable in %s', expected_exe, py_executable) pcbuild_dir = os.path.dirname(sys.executable) pyd_pth = os.path.join(lib_dir, 'site-packages', 'virtualenv_builddir_pyd.pth') if is_win and os.path.exists(os.path.join(pcbuild_dir, 'build.bat')): logger.notify('Detected python running from build directory %s', pcbuild_dir) logger.notify('Writing .pth file linking to build directory for *.pyd files') writefile(pyd_pth, pcbuild_dir) else: pcbuild_dir = None if os.path.exists(pyd_pth): logger.info('Deleting %s (not Windows env or not build directory python)' % pyd_pth) os.unlink(pyd_pth) if sys.executable != py_executable: ## FIXME: could I just hard link? executable = sys.executable shutil.copyfile(executable, py_executable) make_exe(py_executable) if is_win or is_cygwin: pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe') if os.path.exists(pythonw): logger.info('Also created pythonw.exe') shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe')) python_d = os.path.join(os.path.dirname(sys.executable), 'python_d.exe') python_d_dest = os.path.join(os.path.dirname(py_executable), 'python_d.exe') if os.path.exists(python_d): logger.info('Also created python_d.exe') shutil.copyfile(python_d, python_d_dest) elif os.path.exists(python_d_dest): logger.info('Removed python_d.exe as it is no longer at the source') os.unlink(python_d_dest) # we need to copy the DLL to enforce that windows will load the correct one. # may not exist if we are cygwin. py_executable_dll = 'python%s%s.dll' % ( sys.version_info[0], sys.version_info[1]) py_executable_dll_d = 'python%s%s_d.dll' % ( sys.version_info[0], sys.version_info[1]) pythondll = os.path.join(os.path.dirname(sys.executable), py_executable_dll) pythondll_d = os.path.join(os.path.dirname(sys.executable), py_executable_dll_d) pythondll_d_dest = os.path.join(os.path.dirname(py_executable), py_executable_dll_d) if os.path.exists(pythondll): logger.info('Also created %s' % py_executable_dll) shutil.copyfile(pythondll, os.path.join(os.path.dirname(py_executable), py_executable_dll)) if os.path.exists(pythondll_d): logger.info('Also created %s' % py_executable_dll_d) shutil.copyfile(pythondll_d, pythondll_d_dest) elif os.path.exists(pythondll_d_dest): logger.info('Removed %s as the source does not exist' % pythondll_d_dest) os.unlink(pythondll_d_dest) if is_pypy: # make a symlink python --> pypy-c python_executable = os.path.join(os.path.dirname(py_executable), 'python') if sys.platform in ('win32', 'cygwin'): python_executable += '.exe' logger.info('Also created executable %s' % python_executable) copyfile(py_executable, python_executable, symlink) if is_win: for name in ['libexpat.dll', 'libpypy.dll', 'libpypy-c.dll', 'libeay32.dll', 'ssleay32.dll', 'sqlite3.dll', 'tcl85.dll', 'tk85.dll']: src = join(prefix, name) if os.path.exists(src): copyfile(src, join(bin_dir, name), symlink) for d in sys.path: if d.endswith('lib_pypy'): break else: logger.fatal('Could not find lib_pypy in sys.path') raise SystemExit(3) logger.info('Copying lib_pypy') copyfile(d, os.path.join(home_dir, 'lib_pypy'), symlink) if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe: secondary_exe = os.path.join(os.path.dirname(py_executable), expected_exe) py_executable_ext = os.path.splitext(py_executable)[1] if py_executable_ext.lower() == '.exe': # python2.4 gives an extension of '.4' :P secondary_exe += py_executable_ext if os.path.exists(secondary_exe): logger.warn('Not overwriting existing %s script %s (you must use %s)' % (expected_exe, secondary_exe, py_executable)) else: logger.notify('Also creating executable in %s' % secondary_exe) shutil.copyfile(sys.executable, secondary_exe) make_exe(secondary_exe) if '.framework' in prefix: if 'Python.framework' in prefix: logger.debug('MacOSX Python framework detected') # Make sure we use the embedded interpreter inside # the framework, even if sys.executable points to # the stub executable in ${sys.prefix}/bin # See http://groups.google.com/group/python-virtualenv/ # browse_thread/thread/17cab2f85da75951 original_python = os.path.join( prefix, 'Resources/Python.app/Contents/MacOS/Python') if 'EPD' in prefix: logger.debug('EPD framework detected') original_python = os.path.join(prefix, 'bin/python') shutil.copy(original_python, py_executable) # Copy the framework's dylib into the virtual # environment virtual_lib = os.path.join(home_dir, '.Python') if os.path.exists(virtual_lib): os.unlink(virtual_lib) copyfile( os.path.join(prefix, 'Python'), virtual_lib, symlink) # And then change the install_name of the copied python executable try: mach_o_change(py_executable, os.path.join(prefix, 'Python'), '@executable_path/../.Python') except: e = sys.exc_info()[1] logger.warn("Could not call mach_o_change: %s. " "Trying to call install_name_tool instead." % e) try: call_subprocess( ["install_name_tool", "-change", os.path.join(prefix, 'Python'), '@executable_path/../.Python', py_executable]) except: logger.fatal("Could not call install_name_tool -- you must " "have Apple's development tools installed") raise if not is_win: # Ensure that 'python', 'pythonX' and 'pythonX.Y' all exist py_exe_version_major = 'python%s' % sys.version_info[0] py_exe_version_major_minor = 'python%s.%s' % ( sys.version_info[0], sys.version_info[1]) py_exe_no_version = 'python' required_symlinks = [ py_exe_no_version, py_exe_version_major, py_exe_version_major_minor ] py_executable_base = os.path.basename(py_executable) if py_executable_base in required_symlinks: # Don't try to symlink to yourself. required_symlinks.remove(py_executable_base) for pth in required_symlinks: full_pth = join(bin_dir, pth) if os.path.exists(full_pth): os.unlink(full_pth) if symlink: os.symlink(py_executable_base, full_pth) else: copyfile(py_executable, full_pth, symlink) if is_win and ' ' in py_executable: # There's a bug with subprocess on Windows when using a first # argument that has a space in it. Instead we have to quote # the value: py_executable = '"%s"' % py_executable # NOTE: keep this check as one line, cmd.exe doesn't cope with line breaks cmd = [py_executable, '-c', 'import sys;out=sys.stdout;' 'getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))'] logger.info('Testing executable with %s %s "%s"' % tuple(cmd)) try: proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) proc_stdout, proc_stderr = proc.communicate() except OSError: e = sys.exc_info()[1] if e.errno == errno.EACCES: logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e)) sys.exit(100) else: raise e proc_stdout = proc_stdout.strip().decode("utf-8") proc_stdout = os.path.normcase(os.path.abspath(proc_stdout)) norm_home_dir = os.path.normcase(os.path.abspath(home_dir)) if hasattr(norm_home_dir, 'decode'): norm_home_dir = norm_home_dir.decode(sys.getfilesystemencoding()) if proc_stdout != norm_home_dir: logger.fatal( 'ERROR: The executable %s is not functioning' % py_executable) logger.fatal( 'ERROR: It thinks sys.prefix is %r (should be %r)' % (proc_stdout, norm_home_dir)) logger.fatal( 'ERROR: virtualenv is not compatible with this system or executable') if is_win: logger.fatal( 'Note: some Windows users have reported this error when they ' 'installed Python for "Only this user" or have multiple ' 'versions of Python installed. Copying the appropriate ' 'PythonXX.dll to the virtualenv Scripts/ directory may fix ' 'this problem.') sys.exit(100) else: logger.info('Got sys.prefix result: %r' % proc_stdout) pydistutils = os.path.expanduser('~/.pydistutils.cfg') if os.path.exists(pydistutils): logger.notify('Please make sure you remove any previous custom paths from ' 'your %s file.' % pydistutils) ## FIXME: really this should be calculated earlier fix_local_scheme(home_dir, symlink) if site_packages: if os.path.exists(site_packages_filename): logger.info('Deleting %s' % site_packages_filename) os.unlink(site_packages_filename) return py_executable
Install just the base environment, no distutils patches etc
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1096-L1438
jedie/DragonPy
boot_dragonpy.py
fix_lib64
def fix_lib64(lib_dir, symlink=True): """ Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y instead of lib/pythonX.Y. If this is such a platform we'll just create a symlink so lib64 points to lib """ # PyPy's library path scheme is not affected by this. # Return early or we will die on the following assert. if is_pypy: logger.debug('PyPy detected, skipping lib64 symlinking') return # Check we have a lib64 library path if not [p for p in distutils.sysconfig.get_config_vars().values() if isinstance(p, basestring) and 'lib64' in p]: return logger.debug('This system uses lib64; symlinking lib64 to lib') assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], ( "Unexpected python lib dir: %r" % lib_dir) lib_parent = os.path.dirname(lib_dir) top_level = os.path.dirname(lib_parent) lib_dir = os.path.join(top_level, 'lib') lib64_link = os.path.join(top_level, 'lib64') assert os.path.basename(lib_parent) == 'lib', ( "Unexpected parent dir: %r" % lib_parent) if os.path.lexists(lib64_link): return if symlink: os.symlink('lib', lib64_link) else: copyfile('lib', lib64_link)
python
def fix_lib64(lib_dir, symlink=True): """ Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y instead of lib/pythonX.Y. If this is such a platform we'll just create a symlink so lib64 points to lib """ # PyPy's library path scheme is not affected by this. # Return early or we will die on the following assert. if is_pypy: logger.debug('PyPy detected, skipping lib64 symlinking') return # Check we have a lib64 library path if not [p for p in distutils.sysconfig.get_config_vars().values() if isinstance(p, basestring) and 'lib64' in p]: return logger.debug('This system uses lib64; symlinking lib64 to lib') assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], ( "Unexpected python lib dir: %r" % lib_dir) lib_parent = os.path.dirname(lib_dir) top_level = os.path.dirname(lib_parent) lib_dir = os.path.join(top_level, 'lib') lib64_link = os.path.join(top_level, 'lib64') assert os.path.basename(lib_parent) == 'lib', ( "Unexpected parent dir: %r" % lib_parent) if os.path.lexists(lib64_link): return if symlink: os.symlink('lib', lib64_link) else: copyfile('lib', lib64_link)
Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y instead of lib/pythonX.Y. If this is such a platform we'll just create a symlink so lib64 points to lib
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1524-L1555
jedie/DragonPy
boot_dragonpy.py
mach_o_change
def mach_o_change(path, what, value): """ Replace a given name (what) in any LC_LOAD_DYLIB command found in the given binary with a new name (value), provided it's shorter. """ def do_macho(file, bits, endian): # Read Mach-O header (the magic number is assumed read by the caller) cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = read_data(file, endian, 6) # 64-bits header has one more field. if bits == 64: read_data(file, endian) # The header is followed by ncmds commands for n in range(ncmds): where = file.tell() # Read command header cmd, cmdsize = read_data(file, endian, 2) if cmd == LC_LOAD_DYLIB: # The first data field in LC_LOAD_DYLIB commands is the # offset of the name, starting from the beginning of the # command. name_offset = read_data(file, endian) file.seek(where + name_offset, os.SEEK_SET) # Read the NUL terminated string load = file.read(cmdsize - name_offset).decode() load = load[:load.index('\0')] # If the string is what is being replaced, overwrite it. if load == what: file.seek(where + name_offset, os.SEEK_SET) file.write(value.encode() + '\0'.encode()) # Seek to the next command file.seek(where + cmdsize, os.SEEK_SET) def do_file(file, offset=0, size=maxint): file = fileview(file, offset, size) # Read magic number magic = read_data(file, BIG_ENDIAN) if magic == FAT_MAGIC: # Fat binaries contain nfat_arch Mach-O binaries nfat_arch = read_data(file, BIG_ENDIAN) for n in range(nfat_arch): # Read arch header cputype, cpusubtype, offset, size, align = read_data(file, BIG_ENDIAN, 5) do_file(file, offset, size) elif magic == MH_MAGIC: do_macho(file, 32, BIG_ENDIAN) elif magic == MH_CIGAM: do_macho(file, 32, LITTLE_ENDIAN) elif magic == MH_MAGIC_64: do_macho(file, 64, BIG_ENDIAN) elif magic == MH_CIGAM_64: do_macho(file, 64, LITTLE_ENDIAN) assert(len(what) >= len(value)) with open(path, 'r+b') as f: do_file(f)
python
def mach_o_change(path, what, value): """ Replace a given name (what) in any LC_LOAD_DYLIB command found in the given binary with a new name (value), provided it's shorter. """ def do_macho(file, bits, endian): # Read Mach-O header (the magic number is assumed read by the caller) cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = read_data(file, endian, 6) # 64-bits header has one more field. if bits == 64: read_data(file, endian) # The header is followed by ncmds commands for n in range(ncmds): where = file.tell() # Read command header cmd, cmdsize = read_data(file, endian, 2) if cmd == LC_LOAD_DYLIB: # The first data field in LC_LOAD_DYLIB commands is the # offset of the name, starting from the beginning of the # command. name_offset = read_data(file, endian) file.seek(where + name_offset, os.SEEK_SET) # Read the NUL terminated string load = file.read(cmdsize - name_offset).decode() load = load[:load.index('\0')] # If the string is what is being replaced, overwrite it. if load == what: file.seek(where + name_offset, os.SEEK_SET) file.write(value.encode() + '\0'.encode()) # Seek to the next command file.seek(where + cmdsize, os.SEEK_SET) def do_file(file, offset=0, size=maxint): file = fileview(file, offset, size) # Read magic number magic = read_data(file, BIG_ENDIAN) if magic == FAT_MAGIC: # Fat binaries contain nfat_arch Mach-O binaries nfat_arch = read_data(file, BIG_ENDIAN) for n in range(nfat_arch): # Read arch header cputype, cpusubtype, offset, size, align = read_data(file, BIG_ENDIAN, 5) do_file(file, offset, size) elif magic == MH_MAGIC: do_macho(file, 32, BIG_ENDIAN) elif magic == MH_CIGAM: do_macho(file, 32, LITTLE_ENDIAN) elif magic == MH_MAGIC_64: do_macho(file, 64, BIG_ENDIAN) elif magic == MH_CIGAM_64: do_macho(file, 64, LITTLE_ENDIAN) assert(len(what) >= len(value)) with open(path, 'r+b') as f: do_file(f)
Replace a given name (what) in any LC_LOAD_DYLIB command found in the given binary with a new name (value), provided it's shorter.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L21664-L21720
jedie/DragonPy
boot_dragonpy.py
EnvSubprocess._get_bin_dir
def _get_bin_dir(self): """ Normaly we have a ...env/bin/ dir. But under Windows we have ...env/Scripts/ But not PyPy2 under Windows, see: https://bitbucket.org/pypy/pypy/issues/2125/tcl-doesnt-work-inside-a-virtualenv-on#comment-21247266 So just try to test via os.path.isdir() """ for subdir in ("bin", "Scripts"): bin_dir = os.path.join(self.abs_home_dir, subdir) if os.path.isdir(bin_dir): print("bin dir: %r" % bin_dir) return bin_dir raise RuntimeError("Can't find 'bin/Scripts' dir in: %r" % self.abs_home_dir)
python
def _get_bin_dir(self): """ Normaly we have a ...env/bin/ dir. But under Windows we have ...env/Scripts/ But not PyPy2 under Windows, see: https://bitbucket.org/pypy/pypy/issues/2125/tcl-doesnt-work-inside-a-virtualenv-on#comment-21247266 So just try to test via os.path.isdir() """ for subdir in ("bin", "Scripts"): bin_dir = os.path.join(self.abs_home_dir, subdir) if os.path.isdir(bin_dir): print("bin dir: %r" % bin_dir) return bin_dir raise RuntimeError("Can't find 'bin/Scripts' dir in: %r" % self.abs_home_dir)
Normaly we have a ...env/bin/ dir. But under Windows we have ...env/Scripts/ But not PyPy2 under Windows, see: https://bitbucket.org/pypy/pypy/issues/2125/tcl-doesnt-work-inside-a-virtualenv-on#comment-21247266 So just try to test via os.path.isdir()
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1885-L1899
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): """ 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)
return the python executable in the virtualenv. Try first sys.executable but use fallbacks.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/boot_dragonpy.py#L1901-L1912
jedie/DragonPy
dragonpy/utils/humanize.py
hex_repr
def hex_repr(d): """ >>> hex_repr({"A":0x1,"B":0xabc}) 'A=$01 B=$0abc' """ txt = [] for k, v in sorted(d.items()): if isinstance(v, int): txt.append("%s=%s" % (k, nice_hex(v))) else: txt.append("%s=%s" % (k, v)) return " ".join(txt)
python
def hex_repr(d): """ >>> hex_repr({"A":0x1,"B":0xabc}) 'A=$01 B=$0abc' """ txt = [] for k, v in sorted(d.items()): if isinstance(v, int): txt.append("%s=%s" % (k, nice_hex(v))) else: txt.append("%s=%s" % (k, v)) return " ".join(txt)
>>> hex_repr({"A":0x1,"B":0xabc}) 'A=$01 B=$0abc'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/humanize.py#L56-L67
jedie/DragonPy
dragonpy/core/gui_starter.py
StarterGUI._run_dragonpy_cli
def _run_dragonpy_cli(self, *args): """ Run DragonPy cli with given args. Add "--verbosity" from GUI. """ verbosity = self.frame_settings.var_verbosity.get() verbosity_no = VERBOSITY_DICT2[verbosity] log.debug("Verbosity: %i (%s)" % (verbosity_no, verbosity)) args = ( "--verbosity", "%s" % verbosity_no # "--log_list", # "--log", # "dragonpy.components.cpu6809,40", # "dragonpy.Dragon32.MC6821_PIA,50", ) + args click.echo("\n") run_dragonpy(*args, verbose=True)
python
def _run_dragonpy_cli(self, *args): """ Run DragonPy cli with given args. Add "--verbosity" from GUI. """ verbosity = self.frame_settings.var_verbosity.get() verbosity_no = VERBOSITY_DICT2[verbosity] log.debug("Verbosity: %i (%s)" % (verbosity_no, verbosity)) args = ( "--verbosity", "%s" % verbosity_no # "--log_list", # "--log", # "dragonpy.components.cpu6809,40", # "dragonpy.Dragon32.MC6821_PIA,50", ) + args click.echo("\n") run_dragonpy(*args, verbose=True)
Run DragonPy cli with given args. Add "--verbosity" from GUI.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui_starter.py#L221-L238
jedie/DragonPy
dragonpy/core/gui_starter.py
StarterGUI._run_command
def _run_command(self, command): """ Run DragonPy cli with given command like "run" or "editor" Add "--machine" from GUI. "--verbosity" will also be set, later. """ machine_name = self.frame_run_buttons.var_machine.get() self._run_dragonpy_cli("--machine", machine_name, command)
python
def _run_command(self, command): """ Run DragonPy cli with given command like "run" or "editor" Add "--machine" from GUI. "--verbosity" will also be set, later. """ machine_name = self.frame_run_buttons.var_machine.get() self._run_dragonpy_cli("--machine", machine_name, command)
Run DragonPy cli with given command like "run" or "editor" Add "--machine" from GUI. "--verbosity" will also be set, later.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui_starter.py#L240-L247
jedie/DragonPy
dragonpy/utils/srecord_utils.py
int_to_padded_hex_byte
def int_to_padded_hex_byte(integer): """ Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C") """ to_hex = hex(integer) xpos = to_hex.find('x') hex_byte = to_hex[xpos+1 : len(to_hex)].upper() if len(hex_byte) == 1: hex_byte = ''.join(['0', hex_byte]) return hex_byte
python
def int_to_padded_hex_byte(integer): """ Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C") """ to_hex = hex(integer) xpos = to_hex.find('x') hex_byte = to_hex[xpos+1 : len(to_hex)].upper() if len(hex_byte) == 1: hex_byte = ''.join(['0', hex_byte]) return hex_byte
Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C")
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L36-L49
jedie/DragonPy
dragonpy/utils/srecord_utils.py
compute_srec_checksum
def compute_srec_checksum(srec): """ Compute the checksum byte of a given S-Record Returns: The checksum as a string hex byte (ex: "0C") """ # Get the summable data from srec # start at 2 to remove the S* record entry data = srec[2:len(srec)] sum = 0 # For each byte, convert to int and add. # (step each two character to form a byte) for position in range(0, len(data), 2): current_byte = data[position : position+2] int_value = int(current_byte, 16) sum += int_value # Extract the Least significant byte from the hex form hex_sum = hex(sum) least_significant_byte = hex_sum[len(hex_sum)-2:] least_significant_byte = least_significant_byte.replace('x', '0') # turn back to int and find the 8-bit one's complement int_lsb = int(least_significant_byte, 16) computed_checksum = (~int_lsb) & 0xff return computed_checksum
python
def compute_srec_checksum(srec): """ Compute the checksum byte of a given S-Record Returns: The checksum as a string hex byte (ex: "0C") """ # Get the summable data from srec # start at 2 to remove the S* record entry data = srec[2:len(srec)] sum = 0 # For each byte, convert to int and add. # (step each two character to form a byte) for position in range(0, len(data), 2): current_byte = data[position : position+2] int_value = int(current_byte, 16) sum += int_value # Extract the Least significant byte from the hex form hex_sum = hex(sum) least_significant_byte = hex_sum[len(hex_sum)-2:] least_significant_byte = least_significant_byte.replace('x', '0') # turn back to int and find the 8-bit one's complement int_lsb = int(least_significant_byte, 16) computed_checksum = (~int_lsb) & 0xff return computed_checksum
Compute the checksum byte of a given S-Record Returns: The checksum as a string hex byte (ex: "0C")
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L52-L78
jedie/DragonPy
dragonpy/utils/srecord_utils.py
validate_srec_checksum
def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not """ checksum = srec[len(srec)-2:] # Strip the original checksum and compare with the computed one if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16): return True else: return False
python
def validate_srec_checksum(srec): """ Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not """ checksum = srec[len(srec)-2:] # Strip the original checksum and compare with the computed one if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16): return True else: return False
Validate if the checksum of the supplied s-record is valid Returns: True if valid, False if not
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L81-L92
jedie/DragonPy
dragonpy/utils/srecord_utils.py
get_readable_string
def get_readable_string(integer): r""" Convert an integer to a readable 2-character representation. This is useful for reversing examples: 41 == ".A", 13 == "\n", 20 (space) == "__" Returns a readable 2-char representation of an int. """ if integer == 9: #\t readable_string = "\\t" elif integer == 10: #\r readable_string = "\\r" elif integer == 13: #\n readable_string = "\\n" elif integer == 32: # space readable_string = '__' elif integer >= 33 and integer <= 126: # Readable ascii readable_string = ''.join([chr(integer), '.']) else: # rest readable_string = int_to_padded_hex_byte(integer) return readable_string
python
def get_readable_string(integer): r""" Convert an integer to a readable 2-character representation. This is useful for reversing examples: 41 == ".A", 13 == "\n", 20 (space) == "__" Returns a readable 2-char representation of an int. """ if integer == 9: #\t readable_string = "\\t" elif integer == 10: #\r readable_string = "\\r" elif integer == 13: #\n readable_string = "\\n" elif integer == 32: # space readable_string = '__' elif integer >= 33 and integer <= 126: # Readable ascii readable_string = ''.join([chr(integer), '.']) else: # rest readable_string = int_to_padded_hex_byte(integer) return readable_string
r""" Convert an integer to a readable 2-character representation. This is useful for reversing examples: 41 == ".A", 13 == "\n", 20 (space) == "__" Returns a readable 2-char representation of an int.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L95-L114
jedie/DragonPy
dragonpy/utils/srecord_utils.py
offset_byte_in_data
def offset_byte_in_data(target_data, offset, target_byte_pos, readable = False, wraparound = False): """ Offset a given byte in the provided data payload (kind of rot(x)) readable will return a human-readable representation of the byte+offset wraparound will wrap around 255 to 0 (ex: 257 = 2) Returns: the offseted byte """ byte_pos = target_byte_pos * 2 prefix = target_data[:byte_pos] suffix = target_data[byte_pos+2:] target_byte = target_data[byte_pos:byte_pos+2] int_value = int(target_byte, 16) int_value += offset # Wraparound if int_value > 255 and wraparound: int_value -= 256 # Extract readable char for analysis if readable: if int_value < 256 and int_value > 0: offset_byte = get_readable_string(int_value) else: offset_byte = int_to_padded_hex_byte(int_value) else: offset_byte = int_to_padded_hex_byte(int_value) return ''.join([prefix, offset_byte, suffix])
python
def offset_byte_in_data(target_data, offset, target_byte_pos, readable = False, wraparound = False): """ Offset a given byte in the provided data payload (kind of rot(x)) readable will return a human-readable representation of the byte+offset wraparound will wrap around 255 to 0 (ex: 257 = 2) Returns: the offseted byte """ byte_pos = target_byte_pos * 2 prefix = target_data[:byte_pos] suffix = target_data[byte_pos+2:] target_byte = target_data[byte_pos:byte_pos+2] int_value = int(target_byte, 16) int_value += offset # Wraparound if int_value > 255 and wraparound: int_value -= 256 # Extract readable char for analysis if readable: if int_value < 256 and int_value > 0: offset_byte = get_readable_string(int_value) else: offset_byte = int_to_padded_hex_byte(int_value) else: offset_byte = int_to_padded_hex_byte(int_value) return ''.join([prefix, offset_byte, suffix])
Offset a given byte in the provided data payload (kind of rot(x)) readable will return a human-readable representation of the byte+offset wraparound will wrap around 255 to 0 (ex: 257 = 2) Returns: the offseted byte
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L117-L144
jedie/DragonPy
dragonpy/utils/srecord_utils.py
offset_data
def offset_data(data_section, offset, readable = False, wraparound = False): """ Offset the whole data section. see offset_byte_in_data for more information Returns: the entire data section + offset on each byte """ for pos in range(0, len(data_section)/2): data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound) return data_section
python
def offset_data(data_section, offset, readable = False, wraparound = False): """ Offset the whole data section. see offset_byte_in_data for more information Returns: the entire data section + offset on each byte """ for pos in range(0, len(data_section)/2): data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound) return data_section
Offset the whole data section. see offset_byte_in_data for more information Returns: the entire data section + offset on each byte
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L149-L158
jedie/DragonPy
dragonpy/utils/srecord_utils.py
parse_srec
def parse_srec(srec): """ Extract the data portion of a given S-Record (without checksum) Returns: the record type, the lenght of the data section, the write address, the data itself and the checksum """ record_type = srec[0:2] data_len = srec[2:4] addr_len = __ADDR_LEN.get(record_type) * 2 addr = srec[4:4 + addr_len] data = srec[4 + addr_len:len(srec)-2] checksum = srec[len(srec) - 2:] return record_type, data_len, addr, data, checksum
python
def parse_srec(srec): """ Extract the data portion of a given S-Record (without checksum) Returns: the record type, the lenght of the data section, the write address, the data itself and the checksum """ record_type = srec[0:2] data_len = srec[2:4] addr_len = __ADDR_LEN.get(record_type) * 2 addr = srec[4:4 + addr_len] data = srec[4 + addr_len:len(srec)-2] checksum = srec[len(srec) - 2:] return record_type, data_len, addr, data, checksum
Extract the data portion of a given S-Record (without checksum) Returns: the record type, the lenght of the data section, the write address, the data itself and the checksum
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/srecord_utils.py#L161-L172
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): """ 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
convert in every way.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/__init__.py#L29-L70
jedie/DragonPy
dragonpy/Dragon64/config.py
Dragon64Cfg.get_initial_RAM
def get_initial_RAM(self): """ init the Dragon RAM See: http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=5&t=4444 """ mem_FF = [0xff for _ in xrange(4)] mem_00 = [0x00 for _ in xrange(4)] mem = [] for _ in xrange(self.RAM_SIZE // 8): mem += mem_FF mem += mem_00 return mem
python
def get_initial_RAM(self): """ init the Dragon RAM See: http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=5&t=4444 """ mem_FF = [0xff for _ in xrange(4)] mem_00 = [0x00 for _ in xrange(4)] mem = [] for _ in xrange(self.RAM_SIZE // 8): mem += mem_FF mem += mem_00 return mem
init the Dragon RAM See: http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=5&t=4444
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon64/config.py#L65-L78
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 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()
save cursor and scroll position
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/scrolled_text.py#L92-L99
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 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)
restore cursor and scroll position
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/scrolled_text.py#L101-L108
jedie/DragonPy
basic_editor/highlighting.py
TkTextHighlighting.__update_interval
def __update_interval(self): """ highlight the current line """ self.update() self.after_id = self.text.after(250, self.__update_interval)
python
def __update_interval(self): """ highlight the current line """ self.update() self.after_id = self.text.after(250, self.__update_interval)
highlight the current line
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/highlighting.py#L63-L66
jedie/DragonPy
basic_editor/highlighting.py
TkTextHighlightCurrentLine.update
def update(self, event=None, force=False): """ highlight the current line """ line_no = self.text.index(tkinter.INSERT).split(".")[0] # if not force: # if line_no == self.current_line: # log.critical("no highlight line needed.") # return # log.critical("highlight line: %s" % line_no) # self.current_line = line_no self.text.tag_remove(self.tag_current_line.id, "1.0", "end") self.text.tag_add(self.tag_current_line.id, "%s.0" % line_no, "%s.0+1lines" % line_no)
python
def update(self, event=None, force=False): """ highlight the current line """ line_no = self.text.index(tkinter.INSERT).split(".")[0] # if not force: # if line_no == self.current_line: # log.critical("no highlight line needed.") # return # log.critical("highlight line: %s" % line_no) # self.current_line = line_no self.text.tag_remove(self.tag_current_line.id, "1.0", "end") self.text.tag_add(self.tag_current_line.id, "%s.0" % line_no, "%s.0+1lines" % line_no)
highlight the current line
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/highlighting.py#L179-L192
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): """ 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)
Request url and return his content The Requested content will be cached into the default temp directory.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/rom.py#L139-L159
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): """ 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")
Send the clipboard content as user input to the CPU.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui.py#L219-L227
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): """ called via memory write_byte_middleware """ self.display.write_byte(cpu_cycles, op_address, address, value) return value
called via memory write_byte_middleware
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui.py#L346-L349
jedie/DragonPy
dragonpy/core/gui.py
ScrolledTextGUI.event_key_pressed
def event_key_pressed(self, event): """ So a "invert shift" for user inputs: Convert all lowercase letters to uppercase and vice versa. """ char = event.char if not char: return if char in string.ascii_letters: char = invert_shift(char) self.user_input_queue.put(char) # Don't insert the char in text widget, because it will be echoed # back from the machine! return "break"
python
def event_key_pressed(self, event): """ So a "invert shift" for user inputs: Convert all lowercase letters to uppercase and vice versa. """ char = event.char if not char: return if char in string.ascii_letters: char = invert_shift(char) self.user_input_queue.put(char) # Don't insert the char in text widget, because it will be echoed # back from the machine! return "break"
So a "invert shift" for user inputs: Convert all lowercase letters to uppercase and vice versa.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/gui.py#L439-L455
jedie/DragonPy
dragonpy/__init__.py
fix_virtualenv_tkinter
def fix_virtualenv_tkinter(): """ work-a-round for tkinter under windows in a virtualenv: "TclError: Can't find a usable init.tcl..." Known bug, see: https://github.com/pypa/virtualenv/issues/93 There are "fix tk" file here: C:\Python27\Lib\lib-tk\FixTk.py C:\Python34\Lib\tkinter\_fix.py These modules will be automatic imported by tkinter import. The fix set theses environment variables: TCL_LIBRARY C:\Python27\tcl\tcl8.5 TIX_LIBRARY C:\Python27\tcl\tix8.4.3 TK_LIBRARY C:\Python27\tcl\tk8.5 TCL_LIBRARY C:\Python34\tcl\tcl8.6 TIX_LIBRARY C:\Python34\tcl\tix8.4.3 TK_LIBRARY C:\Python34\tcl\tk8.6 but only if: os.path.exists(os.path.join(sys.prefix,"tcl")) And the virtualenv activate script will change the sys.prefix to the current env. So we temporary change it back to sys.real_prefix and import the fix module. If the fix module was imported before, then we reload it. """ if "TCL_LIBRARY" in os.environ: # Fix not needed (e.g. virtualenv issues #93 fixed?) return if not hasattr(sys, "real_prefix"): # we are not in a activated virtualenv return if sys.version_info[0] == 2: # Python v2 virtualprefix = sys.prefix sys.prefix = sys.real_prefix import FixTk if "TCL_LIBRARY" not in os.environ: reload(FixTk) sys.prefix = virtualprefix else: # Python v3 virtualprefix = sys.base_prefix sys.base_prefix = sys.real_prefix from tkinter import _fix if "TCL_LIBRARY" not in os.environ: from imp import reload reload(_fix) sys.base_prefix = virtualprefix
python
def fix_virtualenv_tkinter(): """ work-a-round for tkinter under windows in a virtualenv: "TclError: Can't find a usable init.tcl..." Known bug, see: https://github.com/pypa/virtualenv/issues/93 There are "fix tk" file here: C:\Python27\Lib\lib-tk\FixTk.py C:\Python34\Lib\tkinter\_fix.py These modules will be automatic imported by tkinter import. The fix set theses environment variables: TCL_LIBRARY C:\Python27\tcl\tcl8.5 TIX_LIBRARY C:\Python27\tcl\tix8.4.3 TK_LIBRARY C:\Python27\tcl\tk8.5 TCL_LIBRARY C:\Python34\tcl\tcl8.6 TIX_LIBRARY C:\Python34\tcl\tix8.4.3 TK_LIBRARY C:\Python34\tcl\tk8.6 but only if: os.path.exists(os.path.join(sys.prefix,"tcl")) And the virtualenv activate script will change the sys.prefix to the current env. So we temporary change it back to sys.real_prefix and import the fix module. If the fix module was imported before, then we reload it. """ if "TCL_LIBRARY" in os.environ: # Fix not needed (e.g. virtualenv issues #93 fixed?) return if not hasattr(sys, "real_prefix"): # we are not in a activated virtualenv return if sys.version_info[0] == 2: # Python v2 virtualprefix = sys.prefix sys.prefix = sys.real_prefix import FixTk if "TCL_LIBRARY" not in os.environ: reload(FixTk) sys.prefix = virtualprefix else: # Python v3 virtualprefix = sys.base_prefix sys.base_prefix = sys.real_prefix from tkinter import _fix if "TCL_LIBRARY" not in os.environ: from imp import reload reload(_fix) sys.base_prefix = virtualprefix
work-a-round for tkinter under windows in a virtualenv: "TclError: Can't find a usable init.tcl..." Known bug, see: https://github.com/pypa/virtualenv/issues/93 There are "fix tk" file here: C:\Python27\Lib\lib-tk\FixTk.py C:\Python34\Lib\tkinter\_fix.py These modules will be automatic imported by tkinter import. The fix set theses environment variables: TCL_LIBRARY C:\Python27\tcl\tcl8.5 TIX_LIBRARY C:\Python27\tcl\tix8.4.3 TK_LIBRARY C:\Python27\tcl\tk8.5 TCL_LIBRARY C:\Python34\tcl\tcl8.6 TIX_LIBRARY C:\Python34\tcl\tix8.4.3 TK_LIBRARY C:\Python34\tcl\tk8.6 but only if: os.path.exists(os.path.join(sys.prefix,"tcl")) And the virtualenv activate script will change the sys.prefix to the current env. So we temporary change it back to sys.real_prefix and import the fix module. If the fix module was imported before, then we reload it.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/__init__.py#L14-L76
jedie/DragonPy
dragonpy/Dragon32/MC6821_PIA.py
PIA.internal_reset
def internal_reset(self): """ internal state reset. used e.g. in unittests """ log.critical("PIA internal_reset()") self.empty_key_toggle = True self.current_input_char = None self.input_repead = 0
python
def internal_reset(self): """ internal state reset. used e.g. in unittests """ log.critical("PIA internal_reset()") self.empty_key_toggle = True self.current_input_char = None self.input_repead = 0
internal state reset. used e.g. in unittests
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L152-L160
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): """ 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
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L218-L299
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): """ 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)
write to 0xff00 -> PIA 0 A side Data reg.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L301-L307
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): """ 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
read from 0xff01 -> PIA 0 A side control register
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L309-L319
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): """ 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()
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L321-L344
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): """ 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
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L346-L367
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): """ 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
read from 0xff03 -> PIA 0 B side Control reg.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L379-L389
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): """ 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)
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/MC6821_PIA.py#L391-L433
jedie/DragonPy
dragonpy/CoCo/config.py
CoCo2bCfg.basic_addresses_write
def basic_addresses_write(self, cycles, last_op_address, address, word): """ 0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM 0114 001B VARTAB RMB 2 *PV START OF VARIABLES 0115 001D ARYTAB RMB 2 *PV START OF ARRAYS 0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1) 0117 0021 FRETOP RMB 2 *PV START OF STRING STORAGE (TOP OF FREE RAM) 0118 0023 STRTAB RMB 2 *PV START OF STRING VARIABLES 0119 0025 FRESPC RMB 2 UTILITY STRING POINTER 0120 0027 MEMSIZ RMB 2 *PV TOP OF STRING SPACE """ log.critical("%04x| write $%04x to $%04x", last_op_address, word, address) return word
python
def basic_addresses_write(self, cycles, last_op_address, address, word): """ 0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM 0114 001B VARTAB RMB 2 *PV START OF VARIABLES 0115 001D ARYTAB RMB 2 *PV START OF ARRAYS 0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1) 0117 0021 FRETOP RMB 2 *PV START OF STRING STORAGE (TOP OF FREE RAM) 0118 0023 STRTAB RMB 2 *PV START OF STRING VARIABLES 0119 0025 FRESPC RMB 2 UTILITY STRING POINTER 0120 0027 MEMSIZ RMB 2 *PV TOP OF STRING SPACE """ log.critical("%04x| write $%04x to $%04x", last_op_address, word, address) return word
0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM 0114 001B VARTAB RMB 2 *PV START OF VARIABLES 0115 001D ARYTAB RMB 2 *PV START OF ARRAYS 0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1) 0117 0021 FRETOP RMB 2 *PV START OF STRING STORAGE (TOP OF FREE RAM) 0118 0023 STRTAB RMB 2 *PV START OF STRING VARIABLES 0119 0025 FRESPC RMB 2 UTILITY STRING POINTER 0120 0027 MEMSIZ RMB 2 *PV TOP OF STRING SPACE
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/CoCo/config.py#L95-L107
jedie/DragonPy
basic_editor/editor.py
EditorWindow.event_text_key
def event_text_key(self, event): """ So a "invert shift" for user inputs: Convert all lowercase letters to uppercase and vice versa. """ char = event.char if not char or char not in string.ascii_letters: # ignore all non letter inputs return converted_char = invert_shift(char) log.debug("convert keycode %s - char %s to %s", event.keycode, repr(char), converted_char) # self.text.delete(Tkinter.INSERT + "-1c") # Delete last input char self.text.insert(tkinter.INSERT, converted_char) # Insert converted char return "break"
python
def event_text_key(self, event): """ So a "invert shift" for user inputs: Convert all lowercase letters to uppercase and vice versa. """ char = event.char if not char or char not in string.ascii_letters: # ignore all non letter inputs return converted_char = invert_shift(char) log.debug("convert keycode %s - char %s to %s", event.keycode, repr(char), converted_char) # self.text.delete(Tkinter.INSERT + "-1c") # Delete last input char self.text.insert(tkinter.INSERT, converted_char) # Insert converted char return "break"
So a "invert shift" for user inputs: Convert all lowercase letters to uppercase and vice versa.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/basic_editor/editor.py#L156-L170
jedie/DragonPy
PyDC/PyDC/bitstream_handler.py
pop_bytes_from_bit_list
def pop_bytes_from_bit_list(bit_list, count): """ >>> bit_str = ( ... "00110011" ... "00001111" ... "01010101" ... "11001100") >>> bit_list = [int(i) for i in bit_str] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 1) >>> bytes [[0, 0, 1, 1, 0, 0, 1, 1]] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 2) >>> bytes [[0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 1) >>> bytes [[1, 1, 0, 0, 1, 1, 0, 0]] """ data_bit_count = count * 8 data_bit_list = bit_list[:data_bit_count] data = list(iter_steps(data_bit_list, steps=8)) bit_list = bit_list[data_bit_count:] return bit_list, data
python
def pop_bytes_from_bit_list(bit_list, count): """ >>> bit_str = ( ... "00110011" ... "00001111" ... "01010101" ... "11001100") >>> bit_list = [int(i) for i in bit_str] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 1) >>> bytes [[0, 0, 1, 1, 0, 0, 1, 1]] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 2) >>> bytes [[0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 1) >>> bytes [[1, 1, 0, 0, 1, 1, 0, 0]] """ data_bit_count = count * 8 data_bit_list = bit_list[:data_bit_count] data = list(iter_steps(data_bit_list, steps=8)) bit_list = bit_list[data_bit_count:] return bit_list, data
>>> bit_str = ( ... "00110011" ... "00001111" ... "01010101" ... "11001100") >>> bit_list = [int(i) for i in bit_str] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 1) >>> bytes [[0, 0, 1, 1, 0, 0, 1, 1]] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 2) >>> bytes [[0, 0, 0, 0, 1, 1, 1, 1], [0, 1, 0, 1, 0, 1, 0, 1]] >>> bit_list, bytes = pop_bytes_from_bit_list(bit_list, 1) >>> bytes [[1, 1, 0, 0, 1, 1, 0, 0]]
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/bitstream_handler.py#L40-L64
jedie/DragonPy
PyDC/PyDC/bitstream_handler.py
print_bit_list_stats
def print_bit_list_stats(bit_list): """ >>> print_bit_list_stats([1,1,1,1,0,0,0,0]) 8 Bits: 4 positive bits and 4 negative bits """ print "%i Bits:" % len(bit_list), positive_count = 0 negative_count = 0 for bit in bit_list: if bit == 1: positive_count += 1 elif bit == 0: negative_count += 1 else: raise TypeError("Not a bit: %s" % repr(bit)) print "%i positive bits and %i negative bits" % (positive_count, negative_count)
python
def print_bit_list_stats(bit_list): """ >>> print_bit_list_stats([1,1,1,1,0,0,0,0]) 8 Bits: 4 positive bits and 4 negative bits """ print "%i Bits:" % len(bit_list), positive_count = 0 negative_count = 0 for bit in bit_list: if bit == 1: positive_count += 1 elif bit == 0: negative_count += 1 else: raise TypeError("Not a bit: %s" % repr(bit)) print "%i positive bits and %i negative bits" % (positive_count, negative_count)
>>> print_bit_list_stats([1,1,1,1,0,0,0,0]) 8 Bits: 4 positive bits and 4 negative bits
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/bitstream_handler.py#L321-L336
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): """ 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.")
save the given ASCII BASIC program listing into the emulator RAM.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/machine.py#L95-L111
jedie/DragonPy
dragonpy/Dragon32/dragon_charmap.py
get_rgb_color
def get_rgb_color(color): """ >>> get_rgb_color(BLUE) ((0, 0, 0), (33, 16, 181)) >>> get_rgb_color(NORMAL) ((0, 65, 0), (0, 255, 0)) """ if color == INVERTED: foreground = (0, 255, 0) background = (0, 65, 0) elif color == NORMAL: foreground = (0, 65, 0) background = (0, 255, 0) else: foreground = (0, 0, 0) background = COLOR_INFO[color] return (foreground, background)
python
def get_rgb_color(color): """ >>> get_rgb_color(BLUE) ((0, 0, 0), (33, 16, 181)) >>> get_rgb_color(NORMAL) ((0, 65, 0), (0, 255, 0)) """ if color == INVERTED: foreground = (0, 255, 0) background = (0, 65, 0) elif color == NORMAL: foreground = (0, 65, 0) background = (0, 255, 0) else: foreground = (0, 0, 0) background = COLOR_INFO[color] return (foreground, background)
>>> get_rgb_color(BLUE) ((0, 0, 0), (33, 16, 181)) >>> get_rgb_color(NORMAL) ((0, 65, 0), (0, 255, 0))
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/dragon_charmap.py#L57-L74
jedie/DragonPy
dragonpy/Dragon32/dragon_charmap.py
create_wiki_page
def create_wiki_page(): """ for http://archive.worldofdragon.org/index.php?title=CharMap """ print ( '{| class="wikitable"' ' style="font-family: monospace;' ' background-color:#ffffcc;"' ' cellpadding="10"' ) print("|-") print("! POKE") print("value") print("! ") print("! unicode") print("codepoint") print("! type") print("|-") for no, data in enumerate(DRAGON_CHARS_MAP): item, item_type = data codepoint = ord(item) print("|%i" % no) foreground, background = get_rgb_color(item_type) foreground = "#%02x%02x%02x" % foreground background = "#%02x%02x%02x" % background style = "color: #%s;" print('| style="color:%s; background-color:%s;" | &#x%x;' % ( foreground, background, codepoint )) print("|%i" % codepoint) print("|%s" % item_type) print("|-") print("|}")
python
def create_wiki_page(): """ for http://archive.worldofdragon.org/index.php?title=CharMap """ print ( '{| class="wikitable"' ' style="font-family: monospace;' ' background-color:#ffffcc;"' ' cellpadding="10"' ) print("|-") print("! POKE") print("value") print("! ") print("! unicode") print("codepoint") print("! type") print("|-") for no, data in enumerate(DRAGON_CHARS_MAP): item, item_type = data codepoint = ord(item) print("|%i" % no) foreground, background = get_rgb_color(item_type) foreground = "#%02x%02x%02x" % foreground background = "#%02x%02x%02x" % background style = "color: #%s;" print('| style="color:%s; background-color:%s;" | &#x%x;' % ( foreground, background, codepoint )) print("|%i" % codepoint) print("|%s" % item_type) print("|-") print("|}")
for http://archive.worldofdragon.org/index.php?title=CharMap
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/dragon_charmap.py#L218-L253
jedie/DragonPy
PyDC/PyDC/basic_tokens.py
bytes2codeline
def bytes2codeline(raw_bytes): """ >>> data = (0x87,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22) >>> bytes2codeline(data) 'PRINT "HELLO WORLD!"' """ code_line = "" func_token = False for byte_no in raw_bytes: if byte_no == 0xff: # Next byte is a function token func_token = True continue elif func_token == True: func_token = False try: character = FUNCTION_TOKEN[byte_no] except KeyError, err: print "Error: BASIC function torken for '%s' not found!" % hex(byte_no) character = chr(byte_no) elif byte_no in BASIC_TOKENS: try: character = BASIC_TOKENS[byte_no] except KeyError, err: print "Error: BASIC torken for '%s' not found!" % hex(byte_no) character = chr(byte_no) else: character = chr(byte_no) # print byte_no, repr(character) code_line += character return code_line
python
def bytes2codeline(raw_bytes): """ >>> data = (0x87,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22) >>> bytes2codeline(data) 'PRINT "HELLO WORLD!"' """ code_line = "" func_token = False for byte_no in raw_bytes: if byte_no == 0xff: # Next byte is a function token func_token = True continue elif func_token == True: func_token = False try: character = FUNCTION_TOKEN[byte_no] except KeyError, err: print "Error: BASIC function torken for '%s' not found!" % hex(byte_no) character = chr(byte_no) elif byte_no in BASIC_TOKENS: try: character = BASIC_TOKENS[byte_no] except KeyError, err: print "Error: BASIC torken for '%s' not found!" % hex(byte_no) character = chr(byte_no) else: character = chr(byte_no) # print byte_no, repr(character) code_line += character return code_line
>>> data = (0x87,0x20,0x22,0x48,0x45,0x4c,0x4c,0x4f,0x20,0x57,0x4f,0x52,0x4c,0x44,0x21,0x22) >>> bytes2codeline(data) 'PRINT "HELLO WORLD!"'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/basic_tokens.py#L130-L159
jedie/DragonPy
PyDC/PyDC/wave2bitstream.py
Wave2Bitstream.analyze
def analyze(self): """ Example output: 394Hz ( 28 Samples) exist: 1 613Hz ( 18 Samples) exist: 1 788Hz ( 14 Samples) exist: 1 919Hz ( 12 Samples) exist: 329 ********* 1002Hz ( 11 Samples) exist: 1704 ********************************************** 1103Hz ( 10 Samples) exist: 1256 ********************************** 1225Hz ( 9 Samples) exist: 1743 *********************************************** 1378Hz ( 8 Samples) exist: 1 1575Hz ( 7 Samples) exist: 322 ********* 1838Hz ( 6 Samples) exist: 1851 ************************************************** 2205Hz ( 5 Samples) exist: 1397 ************************************** 2756Hz ( 4 Samples) exist: 913 ************************* """ log.debug("enable half sinus scan") self.half_sinus = True statistics = self._get_statistics() width = 50 max_count = max(statistics.values()) print print "Found this zeror crossing timings in the wave file:" print for duration, count in sorted(statistics.items(), reverse=True): hz = duration2hz(duration, self.framerate / 2) w = int(round(float(width) / max_count * count)) stars = "*"*w print "%5sHz (%5s Samples) exist: %4s %s" % (hz, duration, count, stars) print print "Notes:" print " - Hz values are converted to full sinus cycle duration." print " - Sample cound is from half sinus cycle."
python
def analyze(self): """ Example output: 394Hz ( 28 Samples) exist: 1 613Hz ( 18 Samples) exist: 1 788Hz ( 14 Samples) exist: 1 919Hz ( 12 Samples) exist: 329 ********* 1002Hz ( 11 Samples) exist: 1704 ********************************************** 1103Hz ( 10 Samples) exist: 1256 ********************************** 1225Hz ( 9 Samples) exist: 1743 *********************************************** 1378Hz ( 8 Samples) exist: 1 1575Hz ( 7 Samples) exist: 322 ********* 1838Hz ( 6 Samples) exist: 1851 ************************************************** 2205Hz ( 5 Samples) exist: 1397 ************************************** 2756Hz ( 4 Samples) exist: 913 ************************* """ log.debug("enable half sinus scan") self.half_sinus = True statistics = self._get_statistics() width = 50 max_count = max(statistics.values()) print print "Found this zeror crossing timings in the wave file:" print for duration, count in sorted(statistics.items(), reverse=True): hz = duration2hz(duration, self.framerate / 2) w = int(round(float(width) / max_count * count)) stars = "*"*w print "%5sHz (%5s Samples) exist: %4s %s" % (hz, duration, count, stars) print print "Notes:" print " - Hz values are converted to full sinus cycle duration." print " - Sample cound is from half sinus cycle."
Example output: 394Hz ( 28 Samples) exist: 1 613Hz ( 18 Samples) exist: 1 788Hz ( 14 Samples) exist: 1 919Hz ( 12 Samples) exist: 329 ********* 1002Hz ( 11 Samples) exist: 1704 ********************************************** 1103Hz ( 10 Samples) exist: 1256 ********************************** 1225Hz ( 9 Samples) exist: 1743 *********************************************** 1378Hz ( 8 Samples) exist: 1 1575Hz ( 7 Samples) exist: 322 ********* 1838Hz ( 6 Samples) exist: 1851 ************************************************** 2205Hz ( 5 Samples) exist: 1397 ************************************** 2756Hz ( 4 Samples) exist: 913 *************************
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L167-L204
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): """ 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")
synchronized weave sync trigger
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L206-L242
jedie/DragonPy
PyDC/PyDC/wave2bitstream.py
Wave2Bitstream.iter_bitstream
def iter_bitstream(self, iter_duration_generator): """ iterate over self.iter_trigger() and yield the bits """ assert self.half_sinus == False # Allways trigger full sinus cycle # build min/max Hz values bit_nul_min_hz = self.cfg.BIT_NUL_HZ - self.cfg.HZ_VARIATION bit_nul_max_hz = self.cfg.BIT_NUL_HZ + self.cfg.HZ_VARIATION bit_one_min_hz = self.cfg.BIT_ONE_HZ - self.cfg.HZ_VARIATION bit_one_max_hz = self.cfg.BIT_ONE_HZ + self.cfg.HZ_VARIATION bit_nul_max_duration = self._hz2duration(bit_nul_min_hz) bit_nul_min_duration = self._hz2duration(bit_nul_max_hz) bit_one_max_duration = self._hz2duration(bit_one_min_hz) bit_one_min_duration = self._hz2duration(bit_one_max_hz) log.info("bit-0 in %sHz - %sHz (duration: %s-%s) | bit-1 in %sHz - %sHz (duration: %s-%s)" % ( bit_nul_min_hz, bit_nul_max_hz, bit_nul_min_duration, bit_nul_max_duration, bit_one_min_hz, bit_one_max_hz, bit_one_min_duration, bit_one_max_duration, )) assert bit_nul_max_hz < bit_one_min_hz, "HZ_VARIATION value is %sHz too high!" % ( ((bit_nul_max_hz - bit_one_min_hz) / 2) + 1 ) assert bit_one_max_duration < bit_nul_min_duration, "HZ_VARIATION value is too high!" # for end statistics bit_one_count = 0 one_hz_min = sys.maxint one_hz_avg = None one_hz_max = 0 bit_nul_count = 0 nul_hz_min = sys.maxint nul_hz_avg = None nul_hz_max = 0 for duration in iter_duration_generator: if bit_one_min_duration < duration < bit_one_max_duration: hz = self._duration2hz(duration) log.log(5, "bit 1 at %s in %sSamples = %sHz" % ( self.pformat_pos(), duration, hz ) ) yield 1 bit_one_count += 1 if hz < one_hz_min: one_hz_min = hz if hz > one_hz_max: one_hz_max = hz one_hz_avg = average(one_hz_avg, hz, bit_one_count) elif bit_nul_min_duration < duration < bit_nul_max_duration: hz = self._duration2hz(duration) log.log(5, "bit 0 at %s in %sSamples = %sHz" % ( self.pformat_pos(), duration, hz ) ) yield 0 bit_nul_count += 1 if hz < nul_hz_min: nul_hz_min = hz if hz > nul_hz_max: nul_hz_max = hz nul_hz_avg = average(nul_hz_avg, hz, bit_nul_count) else: hz = self._duration2hz(duration) log.log(7, "Skip signal at %s with %sHz (%sSamples) out of frequency range." % ( self.pformat_pos(), hz, duration ) ) continue bit_count = bit_one_count + bit_nul_count if bit_count == 0: print "ERROR: No information from wave to generate the bits" print "trigger volume to high?" sys.exit(-1) log.info("\n%i Bits: %i positive bits and %i negative bits" % ( bit_count, bit_one_count, bit_nul_count )) if bit_one_count > 0: log.info("Bit 1: %sHz - %sHz avg: %.1fHz variation: %sHz" % ( one_hz_min, one_hz_max, one_hz_avg, one_hz_max - one_hz_min )) if bit_nul_count > 0: log.info("Bit 0: %sHz - %sHz avg: %.1fHz variation: %sHz" % ( nul_hz_min, nul_hz_max, nul_hz_avg, nul_hz_max - nul_hz_min ))
python
def iter_bitstream(self, iter_duration_generator): """ iterate over self.iter_trigger() and yield the bits """ assert self.half_sinus == False # Allways trigger full sinus cycle # build min/max Hz values bit_nul_min_hz = self.cfg.BIT_NUL_HZ - self.cfg.HZ_VARIATION bit_nul_max_hz = self.cfg.BIT_NUL_HZ + self.cfg.HZ_VARIATION bit_one_min_hz = self.cfg.BIT_ONE_HZ - self.cfg.HZ_VARIATION bit_one_max_hz = self.cfg.BIT_ONE_HZ + self.cfg.HZ_VARIATION bit_nul_max_duration = self._hz2duration(bit_nul_min_hz) bit_nul_min_duration = self._hz2duration(bit_nul_max_hz) bit_one_max_duration = self._hz2duration(bit_one_min_hz) bit_one_min_duration = self._hz2duration(bit_one_max_hz) log.info("bit-0 in %sHz - %sHz (duration: %s-%s) | bit-1 in %sHz - %sHz (duration: %s-%s)" % ( bit_nul_min_hz, bit_nul_max_hz, bit_nul_min_duration, bit_nul_max_duration, bit_one_min_hz, bit_one_max_hz, bit_one_min_duration, bit_one_max_duration, )) assert bit_nul_max_hz < bit_one_min_hz, "HZ_VARIATION value is %sHz too high!" % ( ((bit_nul_max_hz - bit_one_min_hz) / 2) + 1 ) assert bit_one_max_duration < bit_nul_min_duration, "HZ_VARIATION value is too high!" # for end statistics bit_one_count = 0 one_hz_min = sys.maxint one_hz_avg = None one_hz_max = 0 bit_nul_count = 0 nul_hz_min = sys.maxint nul_hz_avg = None nul_hz_max = 0 for duration in iter_duration_generator: if bit_one_min_duration < duration < bit_one_max_duration: hz = self._duration2hz(duration) log.log(5, "bit 1 at %s in %sSamples = %sHz" % ( self.pformat_pos(), duration, hz ) ) yield 1 bit_one_count += 1 if hz < one_hz_min: one_hz_min = hz if hz > one_hz_max: one_hz_max = hz one_hz_avg = average(one_hz_avg, hz, bit_one_count) elif bit_nul_min_duration < duration < bit_nul_max_duration: hz = self._duration2hz(duration) log.log(5, "bit 0 at %s in %sSamples = %sHz" % ( self.pformat_pos(), duration, hz ) ) yield 0 bit_nul_count += 1 if hz < nul_hz_min: nul_hz_min = hz if hz > nul_hz_max: nul_hz_max = hz nul_hz_avg = average(nul_hz_avg, hz, bit_nul_count) else: hz = self._duration2hz(duration) log.log(7, "Skip signal at %s with %sHz (%sSamples) out of frequency range." % ( self.pformat_pos(), hz, duration ) ) continue bit_count = bit_one_count + bit_nul_count if bit_count == 0: print "ERROR: No information from wave to generate the bits" print "trigger volume to high?" sys.exit(-1) log.info("\n%i Bits: %i positive bits and %i negative bits" % ( bit_count, bit_one_count, bit_nul_count )) if bit_one_count > 0: log.info("Bit 1: %sHz - %sHz avg: %.1fHz variation: %sHz" % ( one_hz_min, one_hz_max, one_hz_avg, one_hz_max - one_hz_min )) if bit_nul_count > 0: log.info("Bit 0: %sHz - %sHz avg: %.1fHz variation: %sHz" % ( nul_hz_min, nul_hz_max, nul_hz_avg, nul_hz_max - nul_hz_min ))
iterate over self.iter_trigger() and yield the bits
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L250-L345
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): """ 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
yield the duration of two frames in a row.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L347-L368
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): """ 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
trigger middle crossing of the wave sinus curve
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L370-L417
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): """ 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())
yield frame numer + volume value from the WAVE file
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/wave2bitstream.py#L441-L510
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): """ 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)
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]
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/hex2bin.py#L18-L46
jedie/DragonPy
dragonpy/components/memory.py
Memory.get
def get(self, start, end): """ used in unittests """ return [self.read_byte(addr) for addr in xrange(start, end)]
python
def get(self, start, end): """ used in unittests """ return [self.read_byte(addr) for addr in xrange(start, end)]
used in unittests
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/memory.py#L308-L312
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): """ 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)
insert in text field
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/periphery.py#L209-L214
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): """ 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()
work-a-round for blocking input
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/components/periphery.py#L249-L263
jedie/DragonPy
dragonpy/Dragon32/gui_config.py
BaseTkinterGUIConfig.command_cycles_per_sec
def command_cycles_per_sec(self, event=None): """ TODO: refactor: move code to CPU! """ try: cycles_per_sec = self.cycles_per_sec_var.get() except ValueError: self.cycles_per_sec_var.set(self.runtime_cfg.cycles_per_sec) return self.cycles_per_sec_label_var.set( "cycles/sec / 1000000 = %f MHz CPU frequency * 16 = %f Mhz crystal" % ( cycles_per_sec / 1000000, cycles_per_sec / 1000000 * 16, ) ) self.runtime_cfg.cycles_per_sec = cycles_per_sec
python
def command_cycles_per_sec(self, event=None): """ TODO: refactor: move code to CPU! """ try: cycles_per_sec = self.cycles_per_sec_var.get() except ValueError: self.cycles_per_sec_var.set(self.runtime_cfg.cycles_per_sec) return self.cycles_per_sec_label_var.set( "cycles/sec / 1000000 = %f MHz CPU frequency * 16 = %f Mhz crystal" % ( cycles_per_sec / 1000000, cycles_per_sec / 1000000 * 16, ) ) self.runtime_cfg.cycles_per_sec = cycles_per_sec
TODO: refactor: move code to CPU!
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L209-L226
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): """ 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)
CPU burst max running time - self.runtime_cfg.max_delay
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L228-L242
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): """ 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)
CPU burst max running time - self.runtime_cfg.inner_burst_op_count
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L244-L255
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): """ 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)
max CPU burst op count - self.runtime_cfg.max_burst_count
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L257-L268
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): """ 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)
CPU burst max running time - self.runtime_cfg.max_run_time
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/Dragon32/gui_config.py#L270-L278
jedie/DragonPy
dragonpy/core/cli.py
cli
def cli(ctx, **kwargs): """ DragonPy is a Open source (GPL v3 or later) emulator for the 30 years old homecomputer Dragon 32 and Tandy TRS-80 Color Computer (CoCo)... Homepage: https://github.com/jedie/DragonPy """ log.critical("cli kwargs: %s", repr(kwargs)) ctx.obj = CliConfig(**kwargs)
python
def cli(ctx, **kwargs): """ DragonPy is a Open source (GPL v3 or later) emulator for the 30 years old homecomputer Dragon 32 and Tandy TRS-80 Color Computer (CoCo)... Homepage: https://github.com/jedie/DragonPy """ log.critical("cli kwargs: %s", repr(kwargs)) ctx.obj = CliConfig(**kwargs)
DragonPy is a Open source (GPL v3 or later) emulator for the 30 years old homecomputer Dragon 32 and Tandy TRS-80 Color Computer (CoCo)... Homepage: https://github.com/jedie/DragonPy
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/core/cli.py#L147-L156
jedie/DragonPy
dragonpy/utils/pager.py
_windows_get_window_size
def _windows_get_window_size(): """Return (width, height) of available window area on Windows. (0, 0) if no console is allocated. """ sbi = CONSOLE_SCREEN_BUFFER_INFO() ret = windll.kernel32.GetConsoleScreenBufferInfo(console_handle, byref(sbi)) if ret == 0: return (0, 0) return (sbi.srWindow.Right - sbi.srWindow.Left + 1, sbi.srWindow.Bottom - sbi.srWindow.Top + 1)
python
def _windows_get_window_size(): """Return (width, height) of available window area on Windows. (0, 0) if no console is allocated. """ sbi = CONSOLE_SCREEN_BUFFER_INFO() ret = windll.kernel32.GetConsoleScreenBufferInfo(console_handle, byref(sbi)) if ret == 0: return (0, 0) return (sbi.srWindow.Right - sbi.srWindow.Left + 1, sbi.srWindow.Bottom - sbi.srWindow.Top + 1)
Return (width, height) of available window area on Windows. (0, 0) if no console is allocated.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L64-L73
jedie/DragonPy
dragonpy/utils/pager.py
_posix_get_window_size
def _posix_get_window_size(): """Return (width, height) of console terminal on POSIX system. (0, 0) on IOError, i.e. when no console is allocated. """ # see README.txt for reference information # http://www.kernel.org/doc/man-pages/online/pages/man4/tty_ioctl.4.html from fcntl import ioctl from termios import TIOCGWINSZ from array import array """ struct winsize { unsigned short ws_row; unsigned short ws_col; unsigned short ws_xpixel; /* unused */ unsigned short ws_ypixel; /* unused */ }; """ winsize = array("H", [0] * 4) try: ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize) except IOError: # for example IOError: [Errno 25] Inappropriate ioctl for device # when output is redirected # [ ] TODO: check fd with os.isatty pass return (winsize[1], winsize[0])
python
def _posix_get_window_size(): """Return (width, height) of console terminal on POSIX system. (0, 0) on IOError, i.e. when no console is allocated. """ # see README.txt for reference information # http://www.kernel.org/doc/man-pages/online/pages/man4/tty_ioctl.4.html from fcntl import ioctl from termios import TIOCGWINSZ from array import array """ struct winsize { unsigned short ws_row; unsigned short ws_col; unsigned short ws_xpixel; /* unused */ unsigned short ws_ypixel; /* unused */ }; """ winsize = array("H", [0] * 4) try: ioctl(sys.stdout.fileno(), TIOCGWINSZ, winsize) except IOError: # for example IOError: [Errno 25] Inappropriate ioctl for device # when output is redirected # [ ] TODO: check fd with os.isatty pass return (winsize[1], winsize[0])
Return (width, height) of console terminal on POSIX system. (0, 0) on IOError, i.e. when no console is allocated.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L75-L102
jedie/DragonPy
dragonpy/utils/pager.py
dumpkey
def dumpkey(key): """ Helper to convert result of `getch` (string) or `getchars` (list) to hex string. """ def hex3fy(key): """Helper to convert string into hex string (Python 3 compatible)""" from binascii import hexlify # Python 3 strings are no longer binary, encode them for hexlify() if PY3K: key = key.encode('utf-8') keyhex = hexlify(key).upper() if PY3K: keyhex = keyhex.decode('utf-8') return keyhex if type(key) == str: return hex3fy(key) else: return ' '.join( [hex3fy(s) for s in key] )
python
def dumpkey(key): """ Helper to convert result of `getch` (string) or `getchars` (list) to hex string. """ def hex3fy(key): """Helper to convert string into hex string (Python 3 compatible)""" from binascii import hexlify # Python 3 strings are no longer binary, encode them for hexlify() if PY3K: key = key.encode('utf-8') keyhex = hexlify(key).upper() if PY3K: keyhex = keyhex.decode('utf-8') return keyhex if type(key) == str: return hex3fy(key) else: return ' '.join( [hex3fy(s) for s in key] )
Helper to convert result of `getch` (string) or `getchars` (list) to hex string.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L170-L188
jedie/DragonPy
dragonpy/utils/pager.py
_getch_unix
def _getch_unix(_getall=False): """ # --- current algorithm --- # 1. switch to char-by-char input mode # 2. turn off echo # 3. wait for at least one char to appear # 4. read the rest of the character buffer (_getall=True) # 5. return list of characters (_getall on) # or a single char (_getall off) """ import sys, termios fd = sys.stdin.fileno() # save old terminal settings old_settings = termios.tcgetattr(fd) chars = [] try: # change terminal settings - turn off canonical mode and echo. # in canonical mode read from stdin returns one line at a time # and we need one char at a time (see DESIGN.rst for more info) newattr = list(old_settings) newattr[3] &= ~termios.ICANON newattr[3] &= ~termios.ECHO newattr[6][termios.VMIN] = 1 # block until one char received newattr[6][termios.VTIME] = 0 # TCSANOW below means apply settings immediately termios.tcsetattr(fd, termios.TCSANOW, newattr) # [ ] this fails when stdin is redirected, like # ls -la | pager.py # [ ] also check on Windows ch = sys.stdin.read(1) chars = [ch] if _getall: # move rest of chars (if any) from input buffer # change terminal settings - enable non-blocking read newattr = termios.tcgetattr(fd) newattr[6][termios.VMIN] = 0 # CC structure newattr[6][termios.VTIME] = 0 termios.tcsetattr(fd, termios.TCSANOW, newattr) while True: ch = sys.stdin.read(1) if ch != '': chars.append(ch) else: break finally: # restore terminal settings. Do this when all output is # finished - TCSADRAIN flag termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) if _getall: return chars else: return chars[0]
python
def _getch_unix(_getall=False): """ # --- current algorithm --- # 1. switch to char-by-char input mode # 2. turn off echo # 3. wait for at least one char to appear # 4. read the rest of the character buffer (_getall=True) # 5. return list of characters (_getall on) # or a single char (_getall off) """ import sys, termios fd = sys.stdin.fileno() # save old terminal settings old_settings = termios.tcgetattr(fd) chars = [] try: # change terminal settings - turn off canonical mode and echo. # in canonical mode read from stdin returns one line at a time # and we need one char at a time (see DESIGN.rst for more info) newattr = list(old_settings) newattr[3] &= ~termios.ICANON newattr[3] &= ~termios.ECHO newattr[6][termios.VMIN] = 1 # block until one char received newattr[6][termios.VTIME] = 0 # TCSANOW below means apply settings immediately termios.tcsetattr(fd, termios.TCSANOW, newattr) # [ ] this fails when stdin is redirected, like # ls -la | pager.py # [ ] also check on Windows ch = sys.stdin.read(1) chars = [ch] if _getall: # move rest of chars (if any) from input buffer # change terminal settings - enable non-blocking read newattr = termios.tcgetattr(fd) newattr[6][termios.VMIN] = 0 # CC structure newattr[6][termios.VTIME] = 0 termios.tcsetattr(fd, termios.TCSANOW, newattr) while True: ch = sys.stdin.read(1) if ch != '': chars.append(ch) else: break finally: # restore terminal settings. Do this when all output is # finished - TCSADRAIN flag termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) if _getall: return chars else: return chars[0]
# --- current algorithm --- # 1. switch to char-by-char input mode # 2. turn off echo # 3. wait for at least one char to appear # 4. read the rest of the character buffer (_getall=True) # 5. return list of characters (_getall on) # or a single char (_getall off)
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L208-L265
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): """ 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')
Show default prompt to continue and process keypress. It assumes terminal/console understands carriage return \r character.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L311-L321
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): """ 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
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.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/pager.py#L323-L377
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): """ 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
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/sbc09/create_trace.py#L88-L157
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): """ 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}
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'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L29-L76
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): """ 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)
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L111-L124
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): """ 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)
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]
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L158-L182
jedie/DragonPy
PyDC/PyDC/utils.py
count_continuous_pattern
def count_continuous_pattern(bitstream, pattern): """ >>> pattern = list(bytes2bit_strings("A")) >>> bitstream = bytes2bit_strings("AAAXXX") >>> count_continuous_pattern(bitstream, pattern) 3 >>> pattern = list(bytes2bit_strings("X")) >>> bitstream = bytes2bit_strings("AAAXXX") >>> count_continuous_pattern(bitstream, pattern) 0 """ assert isinstance(bitstream, (collections.Iterable, types.GeneratorType)) assert isinstance(pattern, (list, tuple)) window_size = len(pattern) count = -1 for count, data in enumerate(iter_steps(bitstream, window_size), 1): # print count, data, pattern if data != pattern: count -= 1 break return count
python
def count_continuous_pattern(bitstream, pattern): """ >>> pattern = list(bytes2bit_strings("A")) >>> bitstream = bytes2bit_strings("AAAXXX") >>> count_continuous_pattern(bitstream, pattern) 3 >>> pattern = list(bytes2bit_strings("X")) >>> bitstream = bytes2bit_strings("AAAXXX") >>> count_continuous_pattern(bitstream, pattern) 0 """ assert isinstance(bitstream, (collections.Iterable, types.GeneratorType)) assert isinstance(pattern, (list, tuple)) window_size = len(pattern) count = -1 for count, data in enumerate(iter_steps(bitstream, window_size), 1): # print count, data, pattern if data != pattern: count -= 1 break return count
>>> pattern = list(bytes2bit_strings("A")) >>> bitstream = bytes2bit_strings("AAAXXX") >>> count_continuous_pattern(bitstream, pattern) 3 >>> pattern = list(bytes2bit_strings("X")) >>> bitstream = bytes2bit_strings("AAAXXX") >>> count_continuous_pattern(bitstream, pattern) 0
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L185-L208
jedie/DragonPy
PyDC/PyDC/utils.py
find_iter_window
def find_iter_window(bitstream, pattern, max_pos=None): """ >>> pattern = list(bytes2bit_strings("B")) >>> bitstream = bytes2bit_strings("AAABCCC") >>> find_iter_window(bitstream, pattern) 24 >>> "".join(list(bitstream2string(bitstream))) 'CCC' >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("LO"))) 24 >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("LO")), max_pos=16) Traceback (most recent call last): ... MaxPosArraived: 17 >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("X"))) Traceback (most recent call last): ... PatternNotFound: 40 """ assert isinstance(bitstream, (collections.Iterable, types.GeneratorType)) assert isinstance(pattern, (list, tuple)) window_size = len(pattern) pos = -1 for pos, data in enumerate(iter_window(bitstream, window_size)): # print pos, data, pattern if data == pattern: return pos if max_pos is not None and pos > max_pos: raise MaxPosArraived(pos) raise PatternNotFound(pos)
python
def find_iter_window(bitstream, pattern, max_pos=None): """ >>> pattern = list(bytes2bit_strings("B")) >>> bitstream = bytes2bit_strings("AAABCCC") >>> find_iter_window(bitstream, pattern) 24 >>> "".join(list(bitstream2string(bitstream))) 'CCC' >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("LO"))) 24 >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("LO")), max_pos=16) Traceback (most recent call last): ... MaxPosArraived: 17 >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("X"))) Traceback (most recent call last): ... PatternNotFound: 40 """ assert isinstance(bitstream, (collections.Iterable, types.GeneratorType)) assert isinstance(pattern, (list, tuple)) window_size = len(pattern) pos = -1 for pos, data in enumerate(iter_window(bitstream, window_size)): # print pos, data, pattern if data == pattern: return pos if max_pos is not None and pos > max_pos: raise MaxPosArraived(pos) raise PatternNotFound(pos)
>>> pattern = list(bytes2bit_strings("B")) >>> bitstream = bytes2bit_strings("AAABCCC") >>> find_iter_window(bitstream, pattern) 24 >>> "".join(list(bitstream2string(bitstream))) 'CCC' >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("LO"))) 24 >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("LO")), max_pos=16) Traceback (most recent call last): ... MaxPosArraived: 17 >>> find_iter_window(bytes2bit_strings("HELLO!"), list(bytes2bit_strings("X"))) Traceback (most recent call last): ... PatternNotFound: 40
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L217-L250
jedie/DragonPy
PyDC/PyDC/utils.py
count_the_same
def count_the_same(iterable, sentinel): """ >>> count_the_same([0x55,0x55,0x55,0x55,0x3C,"foo","bar"],0x55) (4, 60) >>> 0x3C == 60 True """ count = 0 x = None for count, x in enumerate(iterable): if x != sentinel: break return count, x
python
def count_the_same(iterable, sentinel): """ >>> count_the_same([0x55,0x55,0x55,0x55,0x3C,"foo","bar"],0x55) (4, 60) >>> 0x3C == 60 True """ count = 0 x = None for count, x in enumerate(iterable): if x != sentinel: break return count, x
>>> count_the_same([0x55,0x55,0x55,0x55,0x3C,"foo","bar"],0x55) (4, 60) >>> 0x3C == 60 True
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L253-L265
jedie/DragonPy
PyDC/PyDC/utils.py
diff_info
def diff_info(data): """ >>> diff_info([5,5,10,10,5,5,10,10]) (0, 15) >>> diff_info([5,10,10,5,5,10,10,5]) (15, 0) """ def get_diff(l): diff = 0 for no1, no2 in iter_steps(l, steps=2): diff += abs(no1 - no2) return diff data1 = data[2:] diff1 = get_diff(data1) data2 = data[1:-1] diff2 = get_diff(data2) return diff1, diff2
python
def diff_info(data): """ >>> diff_info([5,5,10,10,5,5,10,10]) (0, 15) >>> diff_info([5,10,10,5,5,10,10,5]) (15, 0) """ def get_diff(l): diff = 0 for no1, no2 in iter_steps(l, steps=2): diff += abs(no1 - no2) return diff data1 = data[2:] diff1 = get_diff(data1) data2 = data[1:-1] diff2 = get_diff(data2) return diff1, diff2
>>> diff_info([5,5,10,10,5,5,10,10]) (0, 15) >>> diff_info([5,10,10,5,5,10,10,5]) (15, 0)
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L268-L287
jedie/DragonPy
PyDC/PyDC/utils.py
count_sign
def count_sign(values, min_value): """ >>> count_sign([3,-1,-2], 0) (1, 2) >>> count_sign([3,-1,-2], 2) (1, 0) >>> count_sign([0,-1],0) (0, 1) """ positive_count = 0 negative_count = 0 for value in values: if value > min_value: positive_count += 1 elif value < -min_value: negative_count += 1 return positive_count, negative_count
python
def count_sign(values, min_value): """ >>> count_sign([3,-1,-2], 0) (1, 2) >>> count_sign([3,-1,-2], 2) (1, 0) >>> count_sign([0,-1],0) (0, 1) """ positive_count = 0 negative_count = 0 for value in values: if value > min_value: positive_count += 1 elif value < -min_value: negative_count += 1 return positive_count, negative_count
>>> count_sign([3,-1,-2], 0) (1, 2) >>> count_sign([3,-1,-2], 2) (1, 0) >>> count_sign([0,-1],0) (0, 1)
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L363-L379
jedie/DragonPy
PyDC/PyDC/utils.py
bits2codepoint
def bits2codepoint(bits): """ >>> c = bits2codepoint([0, 0, 0, 1, 0, 0, 1, 0]) >>> c 72 >>> chr(c) 'H' >>> bits2codepoint("00010010") 72 >>> bits2codepoint([0, 0, 1, 1, 0, 0, 1, 0]) 76 """ bit_string = "".join([str(c) for c in reversed(bits)]) return int(bit_string, 2)
python
def bits2codepoint(bits): """ >>> c = bits2codepoint([0, 0, 0, 1, 0, 0, 1, 0]) >>> c 72 >>> chr(c) 'H' >>> bits2codepoint("00010010") 72 >>> bits2codepoint([0, 0, 1, 1, 0, 0, 1, 0]) 76 """ bit_string = "".join([str(c) for c in reversed(bits)]) return int(bit_string, 2)
>>> c = bits2codepoint([0, 0, 0, 1, 0, 0, 1, 0]) >>> c 72 >>> chr(c) 'H' >>> bits2codepoint("00010010") 72 >>> bits2codepoint([0, 0, 1, 1, 0, 0, 1, 0]) 76
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L397-L412
jedie/DragonPy
PyDC/PyDC/utils.py
byte2bit_string
def byte2bit_string(data): """ >>> byte2bit_string("H") '00010010' >>> byte2bit_string(0x55) '10101010' """ if isinstance(data, basestring): assert len(data) == 1 data = ord(data) bits = '{0:08b}'.format(data) bits = bits[::-1] return bits
python
def byte2bit_string(data): """ >>> byte2bit_string("H") '00010010' >>> byte2bit_string(0x55) '10101010' """ if isinstance(data, basestring): assert len(data) == 1 data = ord(data) bits = '{0:08b}'.format(data) bits = bits[::-1] return bits
>>> byte2bit_string("H") '00010010' >>> byte2bit_string(0x55) '10101010'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L450-L464
jedie/DragonPy
PyDC/PyDC/utils.py
codepoints2bitstream
def codepoints2bitstream(codepoints): """ >>> list(codepoints2bitstream([0x48,0x45])) [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0] >>> list(codepoints2bitstream(0x48)) [0, 0, 0, 1, 0, 0, 1, 0] """ if isinstance(codepoints, int): codepoints = [codepoints] for codepoint in codepoints: bit_string = byte2bit_string(codepoint) for bit in bit_string: yield int(bit)
python
def codepoints2bitstream(codepoints): """ >>> list(codepoints2bitstream([0x48,0x45])) [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0] >>> list(codepoints2bitstream(0x48)) [0, 0, 0, 1, 0, 0, 1, 0] """ if isinstance(codepoints, int): codepoints = [codepoints] for codepoint in codepoints: bit_string = byte2bit_string(codepoint) for bit in bit_string: yield int(bit)
>>> list(codepoints2bitstream([0x48,0x45])) [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0] >>> list(codepoints2bitstream(0x48)) [0, 0, 0, 1, 0, 0, 1, 0]
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L466-L478
jedie/DragonPy
PyDC/PyDC/utils.py
print_codepoint_stream
def print_codepoint_stream(codepoint_stream, display_block_count=8, no_repr=False): """ >>> def g(txt): ... for c in txt: yield ord(c) >>> codepoint_stream = g("HELLO!") >>> print_codepoint_stream(codepoint_stream) ... # doctest: +NORMALIZE_WHITESPACE 6 | 0x48 'H' | 0x45 'E' | 0x4c 'L' | 0x4c 'L' | 0x4f 'O' | 0x21 '!' | """ in_line_count = 0 line = [] for no, codepoint in enumerate(codepoint_stream, 1): r = repr(chr(codepoint)) if "\\x" in r: # FIXME txt = "%s %i" % (hex(codepoint), codepoint) else: txt = "%s %s" % (hex(codepoint), r) line.append(txt.center(8)) in_line_count += 1 if in_line_count >= display_block_count: in_line_count = 0 print "%4s | %s |" % (no, " | ".join(line)) line = [] if line: print "%4s | %s |" % (no, " | ".join(line)) if in_line_count > 0: print
python
def print_codepoint_stream(codepoint_stream, display_block_count=8, no_repr=False): """ >>> def g(txt): ... for c in txt: yield ord(c) >>> codepoint_stream = g("HELLO!") >>> print_codepoint_stream(codepoint_stream) ... # doctest: +NORMALIZE_WHITESPACE 6 | 0x48 'H' | 0x45 'E' | 0x4c 'L' | 0x4c 'L' | 0x4f 'O' | 0x21 '!' | """ in_line_count = 0 line = [] for no, codepoint in enumerate(codepoint_stream, 1): r = repr(chr(codepoint)) if "\\x" in r: # FIXME txt = "%s %i" % (hex(codepoint), codepoint) else: txt = "%s %s" % (hex(codepoint), r) line.append(txt.center(8)) in_line_count += 1 if in_line_count >= display_block_count: in_line_count = 0 print "%4s | %s |" % (no, " | ".join(line)) line = [] if line: print "%4s | %s |" % (no, " | ".join(line)) if in_line_count > 0: print
>>> def g(txt): ... for c in txt: yield ord(c) >>> codepoint_stream = g("HELLO!") >>> print_codepoint_stream(codepoint_stream) ... # doctest: +NORMALIZE_WHITESPACE 6 | 0x48 'H' | 0x45 'E' | 0x4c 'L' | 0x4c 'L' | 0x4f 'O' | 0x21 '!' |
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L523-L553
jedie/DragonPy
PyDC/PyDC/utils.py
pformat_codepoints
def pformat_codepoints(codepoints): """ >>> l = pformat_codepoints([13, 70, 111, 111, 32, 66, 97, 114, 32, 33, 13]) >>> repr(l) "['\\\\r', 'Foo Bar !', '\\\\r']" """ printable = string.printable.replace("\n", "").replace("\r", "") line = [] strings = "" for codepoint in codepoints: char = chr(codepoint) if char in printable: strings += char else: if strings != "": line.append(strings) strings = "" line.append(char) return line
python
def pformat_codepoints(codepoints): """ >>> l = pformat_codepoints([13, 70, 111, 111, 32, 66, 97, 114, 32, 33, 13]) >>> repr(l) "['\\\\r', 'Foo Bar !', '\\\\r']" """ printable = string.printable.replace("\n", "").replace("\r", "") line = [] strings = "" for codepoint in codepoints: char = chr(codepoint) if char in printable: strings += char else: if strings != "": line.append(strings) strings = "" line.append(char) return line
>>> l = pformat_codepoints([13, 70, 111, 111, 32, 66, 97, 114, 32, 33, 13]) >>> repr(l) "['\\\\r', 'Foo Bar !', '\\\\r']"
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L563-L581
jedie/DragonPy
PyDC/PyDC/utils.py
print_block_bit_list
def print_block_bit_list(block_bit_list, display_block_count=8, no_repr=False): """ >>> bit_list = ( ... [0,0,1,1,0,0,1,0], # L ... [1,0,0,1,0,0,1,0], # I ... ) >>> print_block_bit_list(bit_list) ... # doctest: +NORMALIZE_WHITESPACE 2 - 00110010 10010010 0x4c 'L' 0x49 'I' """ def print_line(no, line, line_info): print "%4s - %s" % (no, line) if no_repr: return line = [] for codepoint in line_info: r = repr(chr(codepoint)) if "\\x" in r: # FIXME txt = "%s" % hex(codepoint) else: txt = "%s %s" % (hex(codepoint), r) txt = txt.center(8) line.append(txt) print " %s" % " ".join(line) in_line_count = 0 line = "" line_info = [] for no, bits in enumerate(block_bit_list, 1): line += "%s " % "".join([str(c) for c in bits]) codepoint = bits2codepoint(bits) line_info.append(codepoint) in_line_count += 1 if in_line_count >= display_block_count: in_line_count = 0 print_line(no, line, line_info) line_info = [] line = "" if line: print_line(no, line, line_info) if in_line_count > 0: print
python
def print_block_bit_list(block_bit_list, display_block_count=8, no_repr=False): """ >>> bit_list = ( ... [0,0,1,1,0,0,1,0], # L ... [1,0,0,1,0,0,1,0], # I ... ) >>> print_block_bit_list(bit_list) ... # doctest: +NORMALIZE_WHITESPACE 2 - 00110010 10010010 0x4c 'L' 0x49 'I' """ def print_line(no, line, line_info): print "%4s - %s" % (no, line) if no_repr: return line = [] for codepoint in line_info: r = repr(chr(codepoint)) if "\\x" in r: # FIXME txt = "%s" % hex(codepoint) else: txt = "%s %s" % (hex(codepoint), r) txt = txt.center(8) line.append(txt) print " %s" % " ".join(line) in_line_count = 0 line = "" line_info = [] for no, bits in enumerate(block_bit_list, 1): line += "%s " % "".join([str(c) for c in bits]) codepoint = bits2codepoint(bits) line_info.append(codepoint) in_line_count += 1 if in_line_count >= display_block_count: in_line_count = 0 print_line(no, line, line_info) line_info = [] line = "" if line: print_line(no, line, line_info) if in_line_count > 0: print
>>> bit_list = ( ... [0,0,1,1,0,0,1,0], # L ... [1,0,0,1,0,0,1,0], # I ... ) >>> print_block_bit_list(bit_list) ... # doctest: +NORMALIZE_WHITESPACE 2 - 00110010 10010010 0x4c 'L' 0x49 'I'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L583-L632
jedie/DragonPy
PyDC/PyDC/utils.py
print_bitlist
def print_bitlist(bitstream, no_repr=False): """ >>> bitstream = bytes2bitstream("Hallo World!") >>> print_bitlist(bitstream) ... # doctest: +NORMALIZE_WHITESPACE 8 - 00010010 10000110 00110110 00110110 11110110 00000100 11101010 11110110 0x48 'H' 0x61 'a' 0x6c 'l' 0x6c 'l' 0x6f 'o' 0x20 ' ' 0x57 'W' 0x6f 'o' 12 - 01001110 00110110 00100110 10000100 0x72 'r' 0x6c 'l' 0x64 'd' 0x21 '!' >>> bitstream = bytes2bitstream("Hallo World!") >>> print_bitlist(bitstream, no_repr=True) ... # doctest: +NORMALIZE_WHITESPACE 8 - 00010010 10000110 00110110 00110110 11110110 00000100 11101010 11110110 12 - 01001110 00110110 00100110 10000100 """ block_bit_list = iter_steps(bitstream, steps=8) print_block_bit_list(block_bit_list, no_repr=no_repr)
python
def print_bitlist(bitstream, no_repr=False): """ >>> bitstream = bytes2bitstream("Hallo World!") >>> print_bitlist(bitstream) ... # doctest: +NORMALIZE_WHITESPACE 8 - 00010010 10000110 00110110 00110110 11110110 00000100 11101010 11110110 0x48 'H' 0x61 'a' 0x6c 'l' 0x6c 'l' 0x6f 'o' 0x20 ' ' 0x57 'W' 0x6f 'o' 12 - 01001110 00110110 00100110 10000100 0x72 'r' 0x6c 'l' 0x64 'd' 0x21 '!' >>> bitstream = bytes2bitstream("Hallo World!") >>> print_bitlist(bitstream, no_repr=True) ... # doctest: +NORMALIZE_WHITESPACE 8 - 00010010 10000110 00110110 00110110 11110110 00000100 11101010 11110110 12 - 01001110 00110110 00100110 10000100 """ block_bit_list = iter_steps(bitstream, steps=8) print_block_bit_list(block_bit_list, no_repr=no_repr)
>>> bitstream = bytes2bitstream("Hallo World!") >>> print_bitlist(bitstream) ... # doctest: +NORMALIZE_WHITESPACE 8 - 00010010 10000110 00110110 00110110 11110110 00000100 11101010 11110110 0x48 'H' 0x61 'a' 0x6c 'l' 0x6c 'l' 0x6f 'o' 0x20 ' ' 0x57 'W' 0x6f 'o' 12 - 01001110 00110110 00100110 10000100 0x72 'r' 0x6c 'l' 0x64 'd' 0x21 '!' >>> bitstream = bytes2bitstream("Hallo World!") >>> print_bitlist(bitstream, no_repr=True) ... # doctest: +NORMALIZE_WHITESPACE 8 - 00010010 10000110 00110110 00110110 11110110 00000100 11101010 11110110 12 - 01001110 00110110 00100110 10000100
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L634-L651
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): """ 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
return a uint16 value >>> g=iter([0x1e, 0x12]) >>> v=get_word(g) >>> v 7698 >>> hex(v) '0x1e12'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L654-L670
jedie/DragonPy
PyDC/PyDC/utils.py
sinus_values
def sinus_values(count, max_value): """ >>> values = list(sinus_values(10, 32768)) >>> len(values) 10 >>> values [0, 21063, 32270, 28378, 11207, -11207, -28378, -32270, -21063, 0] >>> tl = TextLevelMeter(32768, width=40) >>> for v in values: ... tl.feed(v) '| * |' '| | * |' '| | *|' '| | * |' '| | * |' '| * | |' '| * | |' '|* | |' '| * | |' '| * |' """ count -= 1 for index in xrange(0, count + 1): angle = 360.0 / count * index y = math.sin(math.radians(angle)) * max_value y = int(round(y)) yield y
python
def sinus_values(count, max_value): """ >>> values = list(sinus_values(10, 32768)) >>> len(values) 10 >>> values [0, 21063, 32270, 28378, 11207, -11207, -28378, -32270, -21063, 0] >>> tl = TextLevelMeter(32768, width=40) >>> for v in values: ... tl.feed(v) '| * |' '| | * |' '| | *|' '| | * |' '| | * |' '| * | |' '| * | |' '|* | |' '| * | |' '| * |' """ count -= 1 for index in xrange(0, count + 1): angle = 360.0 / count * index y = math.sin(math.radians(angle)) * max_value y = int(round(y)) yield y
>>> values = list(sinus_values(10, 32768)) >>> len(values) 10 >>> values [0, 21063, 32270, 28378, 11207, -11207, -28378, -32270, -21063, 0] >>> tl = TextLevelMeter(32768, width=40) >>> for v in values: ... tl.feed(v) '| * |' '| | * |' '| | *|' '| | * |' '| | * |' '| * | |' '| * | |' '|* | |' '| * | |' '| * |'
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L684-L711
jedie/DragonPy
PyDC/PyDC/utils.py
sinus_values_by_hz
def sinus_values_by_hz(framerate, hz, max_value): """ Create sinus values with the given framerate and Hz. Note: We skip the first zero-crossing, so the values can be used directy in a loop. >>> values = sinus_values_by_hz(22050, 1200, 255) >>> len(values) # 22050 / 1200Hz = 18,375 18 >>> values (87, 164, 221, 251, 251, 221, 164, 87, 0, -87, -164, -221, -251, -251, -221, -164, -87, 0) >>> tl = TextLevelMeter(255, width=40) >>> for v in values: ... tl.feed(v) '| | * |' '| | * |' '| | * |' '| | *|' '| | *|' '| | * |' '| | * |' '| | * |' '| * |' '| * | |' '| * | |' '| * | |' '|* | |' '|* | |' '| * | |' '| * | |' '| * | |' '| * |' >>> values = sinus_values_by_hz(44100, 1200, 255) >>> len(values) # 44100 / 1200Hz = 36,75 37 """ count = int(round(float(framerate) / float(hz))) count += 1 values = tuple(sinus_values(count, max_value)) values = values[1:] return values
python
def sinus_values_by_hz(framerate, hz, max_value): """ Create sinus values with the given framerate and Hz. Note: We skip the first zero-crossing, so the values can be used directy in a loop. >>> values = sinus_values_by_hz(22050, 1200, 255) >>> len(values) # 22050 / 1200Hz = 18,375 18 >>> values (87, 164, 221, 251, 251, 221, 164, 87, 0, -87, -164, -221, -251, -251, -221, -164, -87, 0) >>> tl = TextLevelMeter(255, width=40) >>> for v in values: ... tl.feed(v) '| | * |' '| | * |' '| | * |' '| | *|' '| | *|' '| | * |' '| | * |' '| | * |' '| * |' '| * | |' '| * | |' '| * | |' '|* | |' '|* | |' '| * | |' '| * | |' '| * | |' '| * |' >>> values = sinus_values_by_hz(44100, 1200, 255) >>> len(values) # 44100 / 1200Hz = 36,75 37 """ count = int(round(float(framerate) / float(hz))) count += 1 values = tuple(sinus_values(count, max_value)) values = values[1:] return values
Create sinus values with the given framerate and Hz. Note: We skip the first zero-crossing, so the values can be used directy in a loop. >>> values = sinus_values_by_hz(22050, 1200, 255) >>> len(values) # 22050 / 1200Hz = 18,375 18 >>> values (87, 164, 221, 251, 251, 221, 164, 87, 0, -87, -164, -221, -251, -251, -221, -164, -87, 0) >>> tl = TextLevelMeter(255, width=40) >>> for v in values: ... tl.feed(v) '| | * |' '| | * |' '| | * |' '| | *|' '| | *|' '| | * |' '| | * |' '| | * |' '| * |' '| * | |' '| * | |' '| * | |' '|* | |' '|* | |' '| * | |' '| * | |' '| * | |' '| * |' >>> values = sinus_values_by_hz(44100, 1200, 255) >>> len(values) # 44100 / 1200Hz = 36,75 37
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/utils.py#L713-L755
jedie/DragonPy
dragonpy/utils/starter.py
get_module_name
def get_module_name(package): """ package must have these attributes: e.g.: package.DISTRIBUTION_NAME = "DragonPyEmulator" package.DIST_GROUP = "console_scripts" package.ENTRY_POINT = "DragonPy" :return: a string like: "dragonpy.core.cli" """ distribution = get_distribution(package.DISTRIBUTION_NAME) entry_info = distribution.get_entry_info(package.DIST_GROUP, package.ENTRY_POINT) if not entry_info: raise RuntimeError( "Can't find entry info for distribution: %r (group: %r, entry point: %r)" % ( package.DISTRIBUTION_NAME, package.DIST_GROUP, package.ENTRY_POINT ) ) return entry_info.module_name
python
def get_module_name(package): """ package must have these attributes: e.g.: package.DISTRIBUTION_NAME = "DragonPyEmulator" package.DIST_GROUP = "console_scripts" package.ENTRY_POINT = "DragonPy" :return: a string like: "dragonpy.core.cli" """ distribution = get_distribution(package.DISTRIBUTION_NAME) entry_info = distribution.get_entry_info(package.DIST_GROUP, package.ENTRY_POINT) if not entry_info: raise RuntimeError( "Can't find entry info for distribution: %r (group: %r, entry point: %r)" % ( package.DISTRIBUTION_NAME, package.DIST_GROUP, package.ENTRY_POINT ) ) return entry_info.module_name
package must have these attributes: e.g.: package.DISTRIBUTION_NAME = "DragonPyEmulator" package.DIST_GROUP = "console_scripts" package.ENTRY_POINT = "DragonPy" :return: a string like: "dragonpy.core.cli"
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/starter.py#L26-L44
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): """ 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)
Run current executable via subprocess and given args
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/starter.py#L53-L67
jedie/DragonPy
bootstrap/source_after_install.py
after_install
def after_install(options, home_dir): # --- CUT here --- """ called after virtualenv was created and pip/setuptools installed. Now we installed requirement libs/packages. """ if options.install_type==INST_PYPI: requirements=NORMAL_INSTALLATION elif options.install_type==INST_GIT: requirements=GIT_READONLY_INSTALLATION elif options.install_type==INST_DEV: requirements=DEVELOPER_INSTALLATION else: # Should never happen raise RuntimeError("Install type %r unknown?!?" % options.install_type) env_subprocess = EnvSubprocess(home_dir) # from bootstrap_env.bootstrap_install_pip logfile = os.path.join(env_subprocess.abs_home_dir, "install.log") for requirement in requirements: sys.stdout.write("\n\nInstall %r:\n" % requirement) env_subprocess.call_env_pip(["install", "--log=%s" % logfile, requirement]) sys.stdout.write("\n")
python
def after_install(options, home_dir): # --- CUT here --- """ called after virtualenv was created and pip/setuptools installed. Now we installed requirement libs/packages. """ if options.install_type==INST_PYPI: requirements=NORMAL_INSTALLATION elif options.install_type==INST_GIT: requirements=GIT_READONLY_INSTALLATION elif options.install_type==INST_DEV: requirements=DEVELOPER_INSTALLATION else: # Should never happen raise RuntimeError("Install type %r unknown?!?" % options.install_type) env_subprocess = EnvSubprocess(home_dir) # from bootstrap_env.bootstrap_install_pip logfile = os.path.join(env_subprocess.abs_home_dir, "install.log") for requirement in requirements: sys.stdout.write("\n\nInstall %r:\n" % requirement) env_subprocess.call_env_pip(["install", "--log=%s" % logfile, requirement]) sys.stdout.write("\n")
called after virtualenv was created and pip/setuptools installed. Now we installed requirement libs/packages.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/bootstrap/source_after_install.py#L14-L37
jedie/DragonPy
dragonpy/utils/simple_debugger.py
print_exc_plus
def print_exc_plus(): """ Print the usual traceback information, followed by a listing of all the local variables in each frame. """ sys.stderr.flush() # for eclipse sys.stdout.flush() # for eclipse tb = sys.exc_info()[2] while True: if not tb.tb_next: break tb = tb.tb_next stack = [] f = tb.tb_frame while f: stack.append(f) f = f.f_back txt = traceback.format_exc() txt_lines = txt.splitlines() first_line = txt_lines.pop(0) last_line = txt_lines.pop(-1) click.secho(first_line, fg="red") for line in txt_lines: if line.strip().startswith("File"): click.echo(line) else: click.secho(line, fg="white", bold=True) click.secho(last_line, fg="red") click.echo() click.secho( "Locals by frame, most recent call first:", fg="blue", bold=True ) for frame in stack: msg = 'File "%s", line %i, in %s' % ( frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name, ) msg = click.style(msg, fg="white", bold=True, underline=True) click.echo("\n *** %s" % msg) for key, value in list(frame.f_locals.items()): click.echo("%30s = " % click.style(key, bold=True), nl=False) # We have to be careful not to cause a new error in our error # printer! Calling str() on an unknown object could cause an # error we don't want. if isinstance(value, int): value = "$%x (decimal: %i)" % (value, value) else: value = repr(value) if len(value) > MAX_CHARS: value = "%s..." % value[:MAX_CHARS] try: click.echo(value) except: click.echo("<ERROR WHILE PRINTING VALUE>")
python
def print_exc_plus(): """ Print the usual traceback information, followed by a listing of all the local variables in each frame. """ sys.stderr.flush() # for eclipse sys.stdout.flush() # for eclipse tb = sys.exc_info()[2] while True: if not tb.tb_next: break tb = tb.tb_next stack = [] f = tb.tb_frame while f: stack.append(f) f = f.f_back txt = traceback.format_exc() txt_lines = txt.splitlines() first_line = txt_lines.pop(0) last_line = txt_lines.pop(-1) click.secho(first_line, fg="red") for line in txt_lines: if line.strip().startswith("File"): click.echo(line) else: click.secho(line, fg="white", bold=True) click.secho(last_line, fg="red") click.echo() click.secho( "Locals by frame, most recent call first:", fg="blue", bold=True ) for frame in stack: msg = 'File "%s", line %i, in %s' % ( frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name, ) msg = click.style(msg, fg="white", bold=True, underline=True) click.echo("\n *** %s" % msg) for key, value in list(frame.f_locals.items()): click.echo("%30s = " % click.style(key, bold=True), nl=False) # We have to be careful not to cause a new error in our error # printer! Calling str() on an unknown object could cause an # error we don't want. if isinstance(value, int): value = "$%x (decimal: %i)" % (value, value) else: value = repr(value) if len(value) > MAX_CHARS: value = "%s..." % value[:MAX_CHARS] try: click.echo(value) except: click.echo("<ERROR WHILE PRINTING VALUE>")
Print the usual traceback information, followed by a listing of all the local variables in each frame.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/dragonpy/utils/simple_debugger.py#L27-L88
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): """ 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
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
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/CassetteObjects.py#L81-L212
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): """ 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 )
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!"
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/CassetteObjects.py#L214-L268
jedie/DragonPy
PyDC/PyDC/CassetteObjects.py
CassetteFile.get_filename_block_as_codepoints
def get_filename_block_as_codepoints(self): """ TODO: Support tokenized BASIC. Now we only create ASCII BASIC. """ codepoints = [] codepoints += list(string2codepoint(self.filename.ljust(8, " "))) codepoints.append(self.cfg.FTYPE_BASIC) # one byte file type codepoints.append(self.cfg.BASIC_ASCII) # one byte ASCII flag # one byte gap flag (0x00=no gaps, 0xFF=gaps) # http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4231&p=9110#p9110 codepoints.append(self.gap_flag) # machine code starting/loading address if self.file_type != self.cfg.FTYPE_BASIC: # BASIC programm (0x00) codepoints = iter(codepoints) self.start_address = get_word(codepoints) log.info("machine code starting address: %s" % hex(self.start_address)) self.load_address = get_word(codepoints) log.info("machine code loading address: %s" % hex(self.load_address)) else: # not needed in BASIC files # http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4341&p=9109#p9109 pass log.debug("filename block: %s" % pformat_codepoints(codepoints)) return codepoints
python
def get_filename_block_as_codepoints(self): """ TODO: Support tokenized BASIC. Now we only create ASCII BASIC. """ codepoints = [] codepoints += list(string2codepoint(self.filename.ljust(8, " "))) codepoints.append(self.cfg.FTYPE_BASIC) # one byte file type codepoints.append(self.cfg.BASIC_ASCII) # one byte ASCII flag # one byte gap flag (0x00=no gaps, 0xFF=gaps) # http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4231&p=9110#p9110 codepoints.append(self.gap_flag) # machine code starting/loading address if self.file_type != self.cfg.FTYPE_BASIC: # BASIC programm (0x00) codepoints = iter(codepoints) self.start_address = get_word(codepoints) log.info("machine code starting address: %s" % hex(self.start_address)) self.load_address = get_word(codepoints) log.info("machine code loading address: %s" % hex(self.load_address)) else: # not needed in BASIC files # http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=8&t=4341&p=9109#p9109 pass log.debug("filename block: %s" % pformat_codepoints(codepoints)) return codepoints
TODO: Support tokenized BASIC. Now we only create ASCII BASIC.
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/CassetteObjects.py#L389-L417
jedie/DragonPy
PyDC/PyDC/CassetteObjects.py
Cassette.buffer2file
def buffer2file(self): """ add the code buffer content to CassetteFile() instance """ if self.current_file is not None and self.buffer: self.current_file.add_block_data(self.buffered_block_length, self.buffer) self.buffer = [] self.buffered_block_length = 0
python
def buffer2file(self): """ add the code buffer content to CassetteFile() instance """ if self.current_file is not None and self.buffer: self.current_file.add_block_data(self.buffered_block_length, self.buffer) self.buffer = [] self.buffered_block_length = 0
add the code buffer content to CassetteFile() instance
https://github.com/jedie/DragonPy/blob/6659e5b5133aab26979a498ee7453495773a4f6c/PyDC/PyDC/CassetteObjects.py#L509-L516