bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def write_env(bld, cwd, cname): # write out env.csh for people who haven't yet learned bash env_name = os.path.join(cwd, 'env.csh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "setenv LD_LIBRARY_PATH " + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "setenv PYTHONPATH " + os.environ['PYTHONPATH'] except: pass print >> f, "setenv PATH %s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "setenv MEMOSA_CONFNAME %s" % cname f.close() # write out env.sh env_name = os.path.join(cwd, 'env.sh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "export LD_LIBRARY_PATH=" + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "export PYTHONPATH=" + os.environ['PYTHONPATH'] except: pass print >> f, "export PATH=%s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "export MEMOSA_CONFNAME=%s" % cname f.close() return env_name
def write_env(bld, cwd, cname): # write out env.csh for people who haven't yet learned bash env_name = os.path.join(cwd, 'env.csh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "setenv LD_LIBRARY_PATH " + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "setenv PYTHONPATH " + os.environ['PYTHONPATH'] except: pass print >> f, "setenv PATH %s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "setenv MEMOSA_CONFNAME %s" % cname f.close() # write out env.sh env_name = os.path.join(cwd, 'env.sh') f = open(env_name, 'w') for cmd in config('ALL', 'before'): f.write('%s\n' % cmd) print >> f, "export LD_LIBRARY_PATH=" + bld.libdir + ":$LD_LIBRARY_PATH" try: if os.environ['PYTHONPATH']: print >> f, "export PYTHONPATH=" + os.environ['PYTHONPATH'] except: pass print >> f, "export PATH=%s:$PATH" % bld.bindir print >> f, "\n# Need this to recompile MPM in its directory." print >> f, "export MEMOSA_CONFNAME=%s" % cname f.close() return env_name
477,000
def acceptMPM( self, istep): if ( istep%self.couplingStep == 0 ): #gettin nlocalfaces from MPM ( len(nlocalfaces) = remote_comm_world.size() )
def acceptMPM( self, istep): if ( istep%self.couplingStep == 0 ): #gettin nlocalfaces from MPM ( len(nlocalfaces) = remote_comm_world.size() )
477,001
def acceptMPM( self, istep): if ( istep%self.couplingStep == 0 ): #gettin nlocalfaces from MPM ( len(nlocalfaces) = remote_comm_world.size() )
def acceptMPM( self, istep): if ( istep%self.couplingStep == 0 ): #gettin nlocalfaces from MPM ( len(nlocalfaces) = remote_comm_world.size() )
477,002
def setBaseVars(env,cla): for o in optionsList: env[o[0]] = o[1] for k,v in cla.iteritems(): if v in ['True','true']: v = True elif v in ['False', 'false']: v = False env[k] = v env['DEBUG'] = env['VERSION'] == 'debug' env['ARCH'] = Arch.getArch() sconstructDir = os.path.abspath(str(env.fs.SConstruct_dir)) #print sconstructDir env['TOPDIR'] = sconstructDir env['SRCDIR'] = '$TOPDIR/src' if env['BUILDDIR'] is None: env['BUILDDIR'] = '$TOPDIR/build' if isinstance(env['ATYPES'],types.StringType): env['ATYPES'] = [atype.lower() for atype in env['ATYPES'].split(',')] # Third-party packages directory variables if env['PACKAGESDIR'] is None: env['PACKAGESDIR'] = '$TOPDIR/packages/$ARCH' env['PACKAGESLIBDIR'] = '$PACKAGESDIR/lib' # Propagate the following env variables for var in ['TMP', 'TEMP', 'LD_LIBRARY_PATH', 'PATH']: if var in os.environ: env['ENV'][var] = os.environ[var] # Redefine command string variables for compact output. if env['COMPACTOUTPUT']: for var in ['SHCXXCOMSTR', 'CXXCOMSTR', 'CCCOMSTR', 'SHCCCOMSTR']: env[var] = 'Compiling $SOURCE' for var in ['SHLINKCOMSTR', 'LINKCOMSTR', 'LDMODULECOMSTR']: env[var] = 'Linking $TARGET' env['SWIGCOMSTR'] = 'Building swig module for $SOURCE'
def setBaseVars(env,cla): for o in optionsList: env[o[0]] = o[1] for k,v in cla.iteritems(): if v in ['True','true']: v = True elif v in ['False', 'false']: v = False env[k] = v env['DEBUG'] = env['VERSION'] == 'debug' env['ARCH'] = Arch.getArch() sconstructDir = os.path.abspath(str(env.fs.SConstruct_dir)) #print sconstructDir env['TOPDIR'] = sconstructDir env['SRCDIR'] = '$TOPDIR/src' if env['BUILDDIR'] is None: env['BUILDDIR'] = '$TOPDIR/build' if isinstance(env['ATYPES'],types.StringType): env['ATYPES'] = [atype.lower() for atype in env['ATYPES'].split(',')] # Third-party packages directory variables if env['PACKAGESDIR'] is None: env['PACKAGESDIR'] = '$TOPDIR/packages/$ARCH' env['PACKAGESLIBDIR'] = '$PACKAGESDIR/lib' # Propagate the following env variables for var in ['TMP', 'TEMP', 'LD_LIBRARY_PATH', 'PATH']: if var in os.environ: env['ENV'][var] = os.environ[var] # Redefine command string variables for compact output. if env['COMPACTOUTPUT']: for var in ['SHCXXCOMSTR', 'CXXCOMSTR', 'CCCOMSTR', 'SHCCCOMSTR']: env[var] = 'Compiling $SOURCE' for var in ['SHLINKCOMSTR', 'LINKCOMSTR', 'LDMODULECOMSTR']: env[var] = 'Linking $TARGET' env['SWIGCOMSTR'] = 'Building swig module for $SOURCE'
477,003
def setBaseVars(env,cla): for o in optionsList: env[o[0]] = o[1] for k,v in cla.iteritems(): if v in ['True','true']: v = True elif v in ['False', 'false']: v = False env[k] = v env['DEBUG'] = env['VERSION'] == 'debug' env['ARCH'] = Arch.getArch() sconstructDir = os.path.abspath(str(env.fs.SConstruct_dir)) #print sconstructDir env['TOPDIR'] = sconstructDir env['SRCDIR'] = '$TOPDIR/src' if env['BUILDDIR'] is None: env['BUILDDIR'] = '$TOPDIR/build' if isinstance(env['ATYPES'],types.StringType): env['ATYPES'] = [atype.lower() for atype in env['ATYPES'].split(',')] # Third-party packages directory variables if env['PACKAGESDIR'] is None: env['PACKAGESDIR'] = '$TOPDIR/packages/$ARCH' env['PACKAGESLIBDIR'] = '$PACKAGESDIR/lib' # Propagate the following env variables for var in ['TMP', 'TEMP', 'LD_LIBRARY_PATH', 'PATH']: if var in os.environ: env['ENV'][var] = os.environ[var] # Redefine command string variables for compact output. if env['COMPACTOUTPUT']: for var in ['SHCXXCOMSTR', 'CXXCOMSTR', 'CCCOMSTR', 'SHCCCOMSTR']: env[var] = 'Compiling $SOURCE' for var in ['SHLINKCOMSTR', 'LINKCOMSTR', 'LDMODULECOMSTR']: env[var] = 'Linking $TARGET' env['SWIGCOMSTR'] = 'Building swig module for $SOURCE'
def setBaseVars(env,cla): for o in optionsList: env[o[0]] = o[1] for k,v in cla.iteritems(): if v in ['True','true']: v = True elif v in ['False', 'false']: v = False env[k] = v env['DEBUG'] = env['VERSION'] == 'debug' env['ARCH'] = Arch.getArch() sconstructDir = os.path.abspath(str(env.fs.SConstruct_dir)) #print sconstructDir env['TOPDIR'] = sconstructDir env['SRCDIR'] = '$TOPDIR/src' if env['BUILDDIR'] is None: env['BUILDDIR'] = '$TOPDIR/build' if isinstance(env['ATYPES'],types.StringType): env['ATYPES'] = [atype.lower() for atype in env['ATYPES'].split(',')] # Third-party packages directory variables if env['PACKAGESDIR'] is None: env['PACKAGESDIR'] = '$TOPDIR/packages/$ARCH' env['PACKAGESLIBDIR'] = '$PACKAGESDIR/lib' # Propagate the following env variables for var in ['TMP', 'TEMP', 'LD_LIBRARY_PATH', 'PATH']: if var in os.environ: env['ENV'][var] = os.environ[var] # Redefine command string variables for compact output. if env['COMPACTOUTPUT']: for var in ['SHCXXCOMSTR', 'CXXCOMSTR', 'CCCOMSTR', 'SHCCCOMSTR']: env[var] = 'Compiling $SOURCE' for var in ['SHLINKCOMSTR', 'LINKCOMSTR', 'LDMODULECOMSTR']: env[var] = 'Linking $TARGET' env['SWIGCOMSTR'] = 'Building swig module for $SOURCE'
477,004
def setBaseVars(env,cla): for o in optionsList: env[o[0]] = o[1] for k,v in cla.iteritems(): if v in ['True','true']: v = True elif v in ['False', 'false']: v = False env[k] = v env['DEBUG'] = env['VERSION'] == 'debug' env['ARCH'] = Arch.getArch() sconstructDir = os.path.abspath(str(env.fs.SConstruct_dir)) #print sconstructDir env['TOPDIR'] = sconstructDir env['SRCDIR'] = '$TOPDIR/src' if env['BUILDDIR'] is None: env['BUILDDIR'] = '$TOPDIR/build' if isinstance(env['ATYPES'],types.StringType): env['ATYPES'] = [atype.lower() for atype in env['ATYPES'].split(',')] # Third-party packages directory variables if env['PACKAGESDIR'] is None: env['PACKAGESDIR'] = '$TOPDIR/packages/$ARCH' env['PACKAGESLIBDIR'] = '$PACKAGESDIR/lib' # Propagate the following env variables for var in ['TMP', 'TEMP', 'LD_LIBRARY_PATH', 'PATH']: if var in os.environ: env['ENV'][var] = os.environ[var] # Redefine command string variables for compact output. if env['COMPACTOUTPUT']: for var in ['SHCXXCOMSTR', 'CXXCOMSTR', 'CCCOMSTR', 'SHCCCOMSTR']: env[var] = 'Compiling $SOURCE' for var in ['SHLINKCOMSTR', 'LINKCOMSTR', 'LDMODULECOMSTR']: env[var] = 'Linking $TARGET' env['SWIGCOMSTR'] = 'Building swig module for $SOURCE'
def setBaseVars(env,cla): for o in optionsList: env[o[0]] = o[1] for k,v in cla.iteritems(): if v in ['True','true']: v = True elif v in ['False', 'false']: v = False env[k] = v env['DEBUG'] = env['VERSION'] == 'debug' env['ARCH'] = Arch.getArch() sconstructDir = os.path.abspath(str(env.fs.SConstruct_dir)) #print sconstructDir env['TOPDIR'] = sconstructDir env['SRCDIR'] = '$TOPDIR/src' if env['BUILDDIR'] is None: env['BUILDDIR'] = '$TOPDIR/build' if isinstance(env['ATYPES'],types.StringType): env['ATYPES'] = [atype.lower() for atype in env['ATYPES'].split(',')] # Third-party packages directory variables if env['PACKAGESDIR'] is None: env['PACKAGESDIR'] = '$TOPDIR/packages/$ARCH' env['PACKAGESLIBDIR'] = '$PACKAGESDIR/lib' # Propagate the following env variables for var in ['TMP', 'TEMP', 'LD_LIBRARY_PATH', 'PATH']: if var in os.environ: env['ENV'][var] = os.environ[var] # Redefine command string variables for compact output. if env['COMPACTOUTPUT']: for var in ['SHCXXCOMSTR', 'CXXCOMSTR', 'CCCOMSTR', 'SHCCCOMSTR']: env[var] = 'Compiling $SOURCE' for var in ['SHLINKCOMSTR', 'LINKCOMSTR', 'LDMODULECOMSTR']: env[var] = 'Linking $TARGET' env['SWIGCOMSTR'] = 'Building swig module for $SOURCE'
477,005
def setVersionPaths(env): env['BUILDVERSION'] = '$COMPILER/$VERSION' env['BUILDVERSIONDIR'] = '$BUILDDIR/$ARCH/$BUILDVERSION' env['AUTOGENDIR'] = '$BUILDVERSIONDIR/autogen' buildvdir = os.path.join(env['TOPDIR'], env.GetBuildPath('$BUILDVERSIONDIR')) if not os.access(buildvdir,os.F_OK): os.makedirs(buildvdir)
def setVersionPaths(env): env['BUILDVERSION'] = '$COMPILER/$VERSION' env['BUILDVERSIONDIR'] = '$BUILDDIR/$ARCH/$BUILDVERSION' env['AUTOGENDIR'] = '$BUILDVERSIONDIR/autogen' buildvdir = os.path.join(env['TOPDIR'], env.GetBuildPath('$BUILDVERSIONDIR')) if not os.access(buildvdir,os.F_OK): os.makedirs(buildvdir)
477,006
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
477,007
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
477,008
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
477,009
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
def __init__(self, platform=None, **kwargs): SConsEnvironment.__init__(self, platform=platform, tools=[])
477,010
def constructComponents(self): for component, dir in self._compDirMap.iteritems(): env = self.myClone(newTargets=True)
def constructComponents(self): for component, dir in self._compDirMap.iteritems(): env = self.myClone(newTargets=True)
477,011
def createATypedSharedLibrary(self, target, sources=[], deplibs=[], skip=[],**kwargs): env = self.myClone()
def createATypedSharedLibrary(self, target, sources=[], deplibs=[], skip=[],**kwargs): env = self.myClone()
477,012
def createSwigModule(self, target, sources=[], deplibs=[], atype=None,**kwargs):
def createSwigModule(self, target, sources=[], deplibs=[], atype=None,**kwargs):
477,013
def createSwigModule(self, target, sources=[], deplibs=[], atype=None,**kwargs):
def createSwigModule(self, target, sources=[], deplibs=[], atype=None,**kwargs):
477,014
def createATypedSwigModule(self, target, sources=[], deplibs=[], skip=[],**kwargs): env = self.myClone() env.loadTools(['swig'])
def createATypedSwigModule(self, target, sources=[], deplibs=[], skip=[],**kwargs): env = self.myClone() env.loadTools(['swig'])
477,015
def createATypedSwigModule(self, target, sources=[], deplibs=[], skip=[],**kwargs): env = self.myClone() env.loadTools(['swig'])
def createATypedSwigModule(self, target, sources=[], deplibs=[], skip=[],**kwargs): env = self.myClone() env.loadTools(['swig'])
477,016
def _addTarget(self, nodes): self._targets.extend(nodes)
def _addTarget(self, nodes): self._targets.extend(nodes)
477,017
def do_file(self, subcmd, opts, action, path): """${cmd_name}: operations on files: ls/rm/add
def do_file(self, subcmd, opts, action, path): """${cmd_name}: operations on files: ls/rm/add
477,018
def __str__(self): return self.basename
def __str__(self): return self.basename
477,019
def dir_show_mirrors(conn, path, missing=False): """Show mirrors on which a certain directory path was found. The path could actually also be a file, it doesn't matter, but directory is what we are looking for in the context that this function was written for. """ if missing: query = """select distinct(mirrors) from filearr where path not like '%s%%'""" % path else: query = """select distinct(mirrors) from filearr where path like '%s%%'""" % path result = conn.Server._connection.queryAll(query) mirror_ids = [] for i in result: i = i[0] for mirror_id in i: mirror_id = str(mirror_id) if mirror_id not in mirror_ids: mirror_ids.append(mirror_id) if not mirror_ids: return [] query = """select identifier from server where id in (%s)""" % ','.join(mirror_ids) result = conn.Server._connection.queryAll(query) return result
def dir_show_mirrors(conn, path, missing=False): """Show mirrors on which a certain directory path was found. The path could actually also be a file, it doesn't matter, but directory is what we are looking for in the context that this function was written for. """ query = """select distinct(mirrors) from filearr where path like '%s%%'""" % path result = conn.Server._connection.queryAll(query) mirror_ids = [] for i in result: i = i[0] for mirror_id in i: mirror_id = str(mirror_id) if mirror_id not in mirror_ids: mirror_ids.append(mirror_id) if not mirror_ids: return [] query = """select identifier from server where id in (%s)""" % ','.join(mirror_ids) result = conn.Server._connection.queryAll(query) return result
477,020
def dir_show_mirrors(conn, path, missing=False): """Show mirrors on which a certain directory path was found. The path could actually also be a file, it doesn't matter, but directory is what we are looking for in the context that this function was written for. """ if missing: query = """select distinct(mirrors) from filearr where path not like '%s%%'""" % path else: query = """select distinct(mirrors) from filearr where path like '%s%%'""" % path result = conn.Server._connection.queryAll(query) mirror_ids = [] for i in result: i = i[0] for mirror_id in i: mirror_id = str(mirror_id) if mirror_id not in mirror_ids: mirror_ids.append(mirror_id) if not mirror_ids: return [] query = """select identifier from server where id in (%s)""" % ','.join(mirror_ids) result = conn.Server._connection.queryAll(query) return result
def dir_show_mirrors(conn, path, missing=False): """Show mirrors on which a certain directory path was found. The path could actually also be a file, it doesn't matter, but directory is what we are looking for in the context that this function was written for. """ if missing: query = """select distinct(mirrors) from filearr where path not like '%s%%'""" % path else: query = """select distinct(mirrors) from filearr where path like '%s%%'""" % path result = conn.Server._connection.queryAll(query) mirror_ids = [] for i in result: i = i[0] for mirror_id in i: mirror_id = str(mirror_id) if mirror_id not in mirror_ids: mirror_ids.append(mirror_id) if not mirror_ids: return [] if not missing: query = """select identifier from server where id in (%s)""" % ','.join(mirror_ids) else: query = """select identifier from server where id not in (%s)""" % ','.join(mirror_ids) result = conn.Server._connection.queryAll(query) return result
477,021
def do_edit(self, subcmd, opts, identifier): """${cmd_name}: edit a new mirror entry in $EDITOR
def do_edit(self, subcmd, opts, identifier): """${cmd_name}: edit a new mirror entry in $EDITOR
477,022
def do_edit(self, subcmd, opts, identifier): """${cmd_name}: edit a new mirror entry in $EDITOR
def do_edit(self, subcmd, opts, identifier): """${cmd_name}: edit a new mirror entry in $EDITOR
477,023
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
477,024
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
477,025
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
477,026
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
477,027
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: print mirror.identifier, mirror.baseurl raise # not reached, if the timeout goes off mirror.timed_out = False
def probe_http(mirror): """Try to reach host at baseurl. Set status_baseurl_new.""" logging.debug("%s probing %s" % (threading.currentThread().getName(), mirror.identifier)) #req = urllib2.Request('http://old-cherry.suse.de') # never works #req = urllib2.Request('http://doozer.poeml.de/') # always works req = urllib2.Request(mirror.baseurl) req.add_header('User-Agent', USER_AGENT) #req.get_method = lambda: "HEAD" mirror.status_baseurl_new = False mirror.timed_out = True mirror.response_code = None mirror.response = None if mirror.baseurl == '': return None try: response = urllib2.urlopen(req) try: mirror.response_code = response.code # if the web server redirects to an ftp:// URL, our response won't have a code attribute # (except we are going via a proxy) except AttributeError: if response.url.startswith('ftp://'): # count as success mirror.response_code = 200 logging.debug('mirror %s redirects to ftp:// URL' % mirror.identifier) logging.debug('%s got response for %s: %s' % (threading.currentThread().getName(), mirror.identifier, getattr(response, 'code', None))) mirror.response = response.read() mirror.status_baseurl_new = True except ValueError, e: if str(e).startswith('invalid literal for int()'): mirror.response = 'response not read due to http://bugs.python.org/issue1205' logging.info('mirror %s sends broken chunked reply, see http://bugs.python.org/issue1205' % mirror.identifier) except socket.timeout, e: mirror.response = 'socket timeout in reading response: %s' % e except socket.error, e: #errno, errstr = sys.exc_info()[:2] mirror.response = "socket error: %s" % e except httplib.BadStatusLine: mirror.response_code = None mirror.response = None except urllib2.HTTPError, e: mirror.response_code = e.code mirror.response = e.read() except urllib2.URLError, e: mirror.response_code = 0 mirror.response = "%s" % e.reason except IOError, e: # IOError: [Errno ftp error] (111, 'Connection refused') if e.errno == 'ftp error': mirror.response_code = 0 mirror.response = "%s: %s" % (e.errno, e.strerror) else: print mirror.identifier, mirror.baseurl, 'errno:', e.errno raise except: mirror.response_code = None mirror.response = 'unknown error' # not reached, if the timeout goes off mirror.timed_out = False
477,028
def do_test(self, subcmd, opts, identifier): """${cmd_name}: test if a mirror is working
def do_test(self, subcmd, opts, identifier): """${cmd_name}: test if a mirror is working
477,029
def check_db(self, conn, verbose=False, dry_run=False, force=False): """check if the hashes that are stored in the database are up to date for performance, this function talks very low level to the database""" # get a database cursor, but make it persistent which is faster try: conn.mycursor except AttributeError: conn.mycursor = conn.Hash._connection.getConnection().cursor() c = conn.mycursor
def check_db(self, conn, verbose=False, dry_run=False, force=False): """check if the hashes that are stored in the database are up to date for performance, this function talks very low level to the database""" # get a database cursor, but make it persistent which is faster try: conn.mycursor except AttributeError: conn.mycursor = conn.Hash._connection.getConnection().cursor() c = conn.mycursor
477,030
def check_db(self, conn, verbose=False, dry_run=False, force=False): """check if the hashes that are stored in the database are up to date for performance, this function talks very low level to the database""" # get a database cursor, but make it persistent which is faster try: conn.mycursor except AttributeError: conn.mycursor = conn.Hash._connection.getConnection().cursor() c = conn.mycursor
def check_db(self, conn, verbose=False, dry_run=False, force=False): """check if the hashes that are stored in the database are up to date for performance, this function talks very low level to the database""" # get a database cursor, but make it persistent which is faster try: conn.mycursor except AttributeError: conn.mycursor = conn.Hash._connection.getConnection().cursor() c = conn.mycursor
477,031
def check_db(self, conn, verbose=False, dry_run=False, force=False): """check if the hashes that are stored in the database are up to date for performance, this function talks very low level to the database""" # get a database cursor, but make it persistent which is faster try: conn.mycursor except AttributeError: conn.mycursor = conn.Hash._connection.getConnection().cursor() c = conn.mycursor
def check_db(self, conn, verbose=False, dry_run=False, force=False): """check if the hashes that are stored in the database are up to date for performance, this function talks very low level to the database""" # get a database cursor, but make it persistent which is faster try: conn.mycursor except AttributeError: conn.mycursor = conn.Hash._connection.getConnection().cursor() c = conn.mycursor
477,032
def fill(self, verbose=False): verbose = True # XXX if verbose: sys.stdout.write('Hashing %r... ' % self.src) sys.stdout.flush()
def fill(self, verbose=False): verbose = True # XXX if verbose: sys.stdout.write('Hashing %r... ' % self.src) sys.stdout.flush()
477,033
def iplookup(conn, s): from mb.util import IpAddress import mb.mberr if s[0].isdigit(): a = IpAddress(s) else: import sys, socket # note the difference between socket.gethostbyname # and socket.gethostbyname_ex try: host, aliases, ips = socket.gethostbyname_ex(s) except socket.error, e: if e[0] == socket.EAI_NONAME: raise mb.mberr.NameOrServiceNotKnown(s) else: print 'socket error msg:', str(e) return None #print host, aliases, ips if len(ips) != 1: print >>sys.stderr, \ '>>> warning: %r resolves to a multiple IP addresses: %s' \ % (s, ', '.join(ips)) print >>sys.stderr, '>>> see http://mirrorbrain.org/archive/mirrorbrain/0042.html why this could' \ ' could be a problem, and what to do about it.\n' a = IpAddress(ips[0]) query = """SELECT pfx, asn \ FROM pfx2asn \ WHERE pfx >>= ip4r('%s') \ ORDER BY ip4r_size(pfx) \ LIMIT 1""" % a.ip try: res = conn.Pfx2asn._connection.queryAll(query) except AttributeError: # we get this error if mod_asn isn't installed as well return a if len(res) != 1: return a (a.prefix, a.asn) = res[0] return a
def iplookup(conn, s): from mb.util import IpAddress import mb.mberr if s[0].isdigit(): a = IpAddress(s) else: import sys, socket # note the difference between socket.gethostbyname # and socket.gethostbyname_ex try: host, aliases, ips = socket.gethostbyname_ex(s) except socket.error, e: if e[0] == socket.EAI_NONAME: raise mb.mberr.NameOrServiceNotKnown(s) else: print 'socket error msg:', str(e) return None #print host, aliases, ips if len(ips) != 1: print >>sys.stderr, \ '>>> warning: %r resolves to multiple IP addresses: %s' \ % (s, ', '.join(ips)) print >>sys.stderr, '>>> see http://mirrorbrain.org/archive/mirrorbrain/0042.html why this could' \ ' could be a problem, and what to do about it.\n' a = IpAddress(ips[0]) query = """SELECT pfx, asn \ FROM pfx2asn \ WHERE pfx >>= ip4r('%s') \ ORDER BY ip4r_size(pfx) \ LIMIT 1""" % a.ip try: res = conn.Pfx2asn._connection.queryAll(query) except AttributeError: # we get this error if mod_asn isn't installed as well return a if len(res) != 1: return a (a.prefix, a.asn) = res[0] return a
477,034
def do_export(self, subcmd, opts, *args): """${cmd_name}: export the mirror list as text file
def do_export(self, subcmd, opts, *args): """${cmd_name}: export the mirror list as text file
477,035
def do_size(self, subcmd, opts, host): """${cmd_name}: find out the size of an rsync module
def do_size(self, subcmd, opts, host): """${cmd_name}: find out the size of an rsync module
477,036
def render(self, name, value, attrs=None): html = super(RestructuredTextareaWidget, self).render(name, value, attrs)
def render(self, name, value, attrs=None): html = super(RestructuredTextareaWidget, self).render(name, value, attrs)
477,037
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', ] if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', ] if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
477,038
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
477,039
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" alt="%s" />' % (src, src) output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
477,040
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
477,041
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
def render(self, name, value, attrs=None, choices=()): import logging logging.debug("Adding media %s" % RichCheckboxSelectMultiple.Media.js) if value is None: value = [] has_id = attrs and 'id' in attrs checkbox_class = 'richtable-checkbox' if attrs and 'class' in attrs: attrs['class'] = attrs['class'] + ' ' + checkbox_class else: attrs['class'] = checkbox_class final_attrs = self.build_attrs(attrs, name=name) output = [u'<table class="datatable richcheckboxselectmultiple%s">' % (attrs and 'class' in attrs and ' ' + attrs['class']), u'<thead class="datatable-thead">', u'<tr class="datatable-thead-subheader">' u'<th>%s</th>' % _("State"), u'<th>%s</th>' % _("Name"), u'<th>%s</th>' % _("On/Off"), u'</tr>', u'</thead>', u'<tbody class="datatable-tbody">', ] # Normalize to strings str_values = set([force_unicode(v) for v in value]) for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = u' for="%s"' % final_attrs['id'] else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_unicode(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_unicode(option_label)) # Adding img next to the field itself if option_value in str_values: src = richicon_src("icon-yes.gif") else: src = richicon_src("icon-no.gif") tr_class = i % 2 and "even" or "odd" img_tag = u'<img src="%s" />' % src output.append(u'<tr class="%s">' u'<td class="centered">%s</td>' u'<td><label%s>%s</label></td>' u'<td>%s</td>' u'</tr></tbody>' % (tr_class, img_tag, label_for, option_label, rendered_cb)) if self.extra: output.append( u'<tfoot>' u'<tr><td colspan="3">' u'<a class="richbutton select-all">Select all</a>' u'<a class="richbutton deselect-all">Deselect all</a>' u'<a class="richbutton change-all">Reverse all</a>' u'</td></tr>' u'</tfoot>')
477,042
def handle_label(self, app=None, **options): if app is None: raise CommandError("Specify at least one app") if app not in settings.INSTALLED_APPS: raise CommandError("%s not found at INSTALLED_APPS" % app) MEDIA_ROOT = os.path.abspath(options['media_root'])
def handle_label(self, app=None, **options): if app is None: raise CommandError("Specify at least one app") if app not in settings.INSTALLED_APPS: raise CommandError("%s not found at INSTALLED_APPS" % app) MEDIA_ROOT = os.path.abspath(options['media_root'])
477,043
def register_rst_directives(directives_items): """ Registers restructuredText directives given as dictionary with keys being names and paths to directive function. """ for name, directive_path in directives_items: try: splitted = directive_path.split('.') mod_path, method_name = '.'.join(splitted[:-1]), splitted[-1] mod = __import__(mod_path, (), (), [method_name], -1) directive = getattr(mod, method_name) directives.register_directive(name, directive) msg = "Registered restructuredText directive: %s" % method_name logging.debug(msg) except ImportError, err: msg = "Couldn't register restructuredText directive. Original "\ "exception was: %s" % err logging.warn(msg)
def register_rst_directives(directives_items): """ Registers restructuredText directives given as dictionary with keys being names and paths to directive function. """ for name, directive_path in directives_items: try: splitted = directive_path.split('.') mod_path, method_name = '.'.join(splitted[:-1]), splitted[-1] mod = __import__(mod_path, (), (), [method_name], -1) directive = getattr(mod, method_name) directives.register_directive(name, directive) msg = "Registered restructuredText directive: %s" % method_name logger.debug(msg) except ImportError, err: msg = "Couldn't register restructuredText directive. Original "\ "exception was: %s" % err logging.warn(msg)
477,044
def register_rst_directives(directives_items): """ Registers restructuredText directives given as dictionary with keys being names and paths to directive function. """ for name, directive_path in directives_items: try: splitted = directive_path.split('.') mod_path, method_name = '.'.join(splitted[:-1]), splitted[-1] mod = __import__(mod_path, (), (), [method_name], -1) directive = getattr(mod, method_name) directives.register_directive(name, directive) msg = "Registered restructuredText directive: %s" % method_name logging.debug(msg) except ImportError, err: msg = "Couldn't register restructuredText directive. Original "\ "exception was: %s" % err logging.warn(msg)
def register_rst_directives(directives_items): """ Registers restructuredText directives given as dictionary with keys being names and paths to directive function. """ for name, directive_path in directives_items: try: splitted = directive_path.split('.') mod_path, method_name = '.'.join(splitted[:-1]), splitted[-1] mod = __import__(mod_path, (), (), [method_name], -1) directive = getattr(mod, method_name) directives.register_directive(name, directive) msg = "Registered restructuredText directive: %s" % method_name logging.debug(msg) except ImportError, err: msg = "Couldn't register restructuredText directive. Original "\ "exception was: %s" % err logger.warn(msg)
477,045
def rho(r): R = 0.354 Delta = 0.153 R1 = R - Delta / 2 R2 = R + Delta / 2 return rho0 * (theta(R2-r) - theta(r-R1))
def rho(r): R = 0.354 * nm Delta = 0.153 * nm R1 = R - Delta / 2 R2 = R + Delta / 2 return rho0 * (theta(R2-r) - theta(r-R1))
477,046
def rho(r): R = 0.354 Delta = 0.153 R1 = R - Delta / 2 R2 = R + Delta / 2 return rho0 * (theta(R2-r) - theta(r-R1))
def rho(r): R = 0.354 Delta = 0.153 R1 = R - Delta / 2 R2 = R + Delta / 2 return rho0 * (theta(R2-r) - theta(r-R1))
477,047
def close(self): # free parsed data if not self.is_opened(): return self.__open_status = False
def close(self): # free parsed data if not self.is_opened(): return self.__open_status = False
477,048
def close(self): # free parsed data if not self.is_opened(): return self.__open_status = False
def close(self): # free parsed data if not self.is_opened(): return self.__open_status = False
477,049
def run(self): hid_object = self.hid_object while hid_object.is_opened() and not self.__abort: raw_report = hid_object._input_report_queue.get() if not raw_report: continue hid_object._process_raw_report(raw_report) # reuse the report (avoid allocating new memory) hid_object._input_report_queue.reuse(raw_report)
def run(self): hid_object = self.hid_object while hid_object.is_opened() and not self.__abort: raw_report = hid_object._input_report_queue.get() if not raw_report or self.__abort: break hid_object._process_raw_report(raw_report) # reuse the report (avoid allocating new memory) hid_object._input_report_queue.reuse(raw_report)
477,050
def run(self): hid_object = self.hid_object while hid_object.is_opened() and not self.__abort: raw_report = hid_object._input_report_queue.get() if not raw_report: continue hid_object._process_raw_report(raw_report) # reuse the report (avoid allocating new memory) hid_object._input_report_queue.reuse(raw_report)
def run(self): hid_object = self.hid_object while hid_object.is_opened() and not self.__abort: raw_report = hid_object._input_report_queue.get() if not raw_report: continue hid_object._process_raw_report(raw_report) # reuse the report (avoid allocating new memory) if hid_object._input_report_queue: hid_object._input_report_queue.reuse(raw_report)
477,051
def abort(self): if not self.__abort: self.__abort = True if self.is_alive() and self.__overlapped_read_obj: # force overlapped events completition SetEvent(self.__overlapped_read_obj.h_event)
def abort(self): if not self.__active: return self.__abort = True if self.is_alive() and self.__overlapped_read_obj: # force overlapped events completition SetEvent(self.__overlapped_read_obj.h_event)
477,052
def run(self): if not self.raw_report_size: # don't raise any error as the hid object can still be used # for writing reports raise HIDError("Attempting to read input reports on non "\ "capable HID device") over_read = OVERLAPPED() over_read.h_event = CreateEvent(None, 0, 0, None) if over_read.h_event: self.__overlapped_read_obj = over_read else: raise HIDError("Error when create hid event resource")
def self.__active = False self.__abort = True run(self): self.__active = False self.__abort = True if self.__active = False self.__abort = True not self.__active = False self.__abort = True self.raw_report_size: self.__active = False self.__abort = True # self.__active = False self.__abort = True don't self.__active = False self.__abort = True raise self.__active = False self.__abort = True any self.__active = False self.__abort = True error self.__active = False self.__abort = True as self.__active = False self.__abort = True the self.__active = False self.__abort = True hid self.__active = False self.__abort = True object self.__active = False self.__abort = True can self.__active = False self.__abort = True still self.__active = False self.__abort = True be self.__active = False self.__abort = True used self.__active = False self.__abort = True # self.__active = False self.__abort = True for self.__active = False self.__abort = True writing self.__active = False self.__abort = True reports self.__active = False self.__abort = True raise self.__active = False self.__abort = True HIDError("Attempting self.__active = False self.__abort = True to self.__active = False self.__abort = True read self.__active = False self.__abort = True input self.__active = False self.__abort = True reports self.__active = False self.__abort = True on self.__active = False self.__abort = True non self.__active = False self.__abort = True "\ self.__active = False self.__abort = True "capable self.__active = False self.__abort = True HID self.__active = False self.__abort = True device") self.__active = False self.__abort = True self.__active = False self.__abort = True over_read self.__active = False self.__abort = True = self.__active = False self.__abort = True OVERLAPPED() self.__active = False self.__abort = True over_read.h_event self.__active = False self.__abort = True = self.__active = False self.__abort = True CreateEvent(None, self.__active = False self.__abort = True 0, self.__active = False self.__abort = True 0, self.__active = False self.__abort = True None) self.__active = False self.__abort = True if self.__active = False self.__abort = True over_read.h_event: self.__active = False self.__abort = True self.__overlapped_read_obj self.__active = False self.__abort = True = self.__active = False self.__abort = True over_read self.__active = False self.__abort = True else: self.__active = False self.__abort = True raise self.__active = False self.__abort = True HIDError("Error self.__active = False self.__abort = True when self.__active = False self.__abort = True create self.__active = False self.__abort = True hid self.__active = False self.__abort = True event self.__active = False self.__abort = True resource")
477,053
def send_output_report(self, data): """Send input/output/feature report ID = report_id, data should be a c_ubyte object with included the required report data """ assert( self.is_opened() )
defsend_output_report(self,data):"""Sendinput/output/featurereportID=report_id,datashouldbeac_ubyteobjectwithincludedtherequiredreportdata"""assert(self.is_opened())
477,054
def __setitem__(self, index, value): "Allow to access value array by index" if not self.__is_value_array: raise ValueError("Report item is not value usage array") if index < self.__report_count: byte_index = (index * self.__bit_size) / 8 byte_index = (index * self.__bit_size) % 8 bit_value = (value & ((1 << self.__bit_size) - 1)) << byte_index self.__value[byte_index] &= bit_value self.__value[byte_index] |= bit_value else: raise IndexError
def __setitem__(self, index, value): "Allow to access value array by index" if not self.__is_value_array: raise ValueError("Report item is not value usage array") if index < self.__report_count: byte_index = (index * self.__bit_size) / 8 bit_index = (index * self.__bit_size) % 8 bit_mask = ((1 << self.__bit_size) - 1) self.__value[byte_index] &= ~(bit_mask << bit_index) self.__value[byte_index] |= (value & bit_mask) << bit_index else: raise IndexError
477,055
def __getitem__(self, index): "Allow to access value array by index" if not self.__is_value_array: raise ValueError("Report item is not value usage array") if index < self.__report_count: byte_index = (index * self.__bit_size) / 8 byte_index = (index * self.__bit_size) % 8 return ((self.__value[byte_index] >> byte_index) & self.__bit_size ) else: raise IndexError
def __getitem__(self, index): "Allow to access value array by index" if not self.__is_value_array: raise ValueError("Report item is not value usage array") if index < self.__report_count: byte_index = (index * self.__bit_size) / 8 bit_index = (index * self.__bit_size) % 8 return ((self.__value[byte_index] >> bit_index) & ((1 << self.__bit_size) - 1) ) else: raise IndexError
477,056
def get(self): if self.__locked_down: return None #wait for data self.posted_event.wait() self.fresh_lock.acquire() if self.__locked_down: self.fresh_lock.release() return None
def get(self): if self.__locked_down: return None #wait for data self.posted_event.wait() self.fresh_lock.acquire() if self.__locked_down: self.fresh_lock.release() return None
477,057
def post(self, raw_report): if self.__locked_down: self.posted_event.set() return self.fresh_lock.acquire() self.fresh_queue.append( raw_report ) self.fresh_lock.release() self.posted_event.set()
def post(self, raw_report): if self.__locked_down: return self.fresh_lock.acquire() self.fresh_queue.append( raw_report ) self.fresh_lock.release() self.posted_event.set()
477,058
def run(self): time.sleep(0.050) # this fixes an strange python threading bug if not self.raw_report_size: # don't raise any error as the hid object can still be used # for writing reports raise HIDError("Attempting to read input reports on non "\ "capable HID device")
def run(self): time.sleep(0.050) # this fixes an strange python threading bug if not self.raw_report_size: # don't raise any error as the hid object can still be used # for writing reports raise HIDError("Attempting to read input reports on non "\ "capable HID device")
477,059
def __repr__(self): res = [] if self.string_index: res.append( self.get_usage_string() ) res.append( "page_id=%s"%hex(self.page_id) ) res.append( "usage_id=%s"%hex(self.usage_id) ) if self.__value != None: res.append( "value=%s)"%hex(self.__value) ) else: res.append( "value=[None])" ) usage_type = "" if self.is_button(): usage_type = "Button" elif self.is_value(): usage_type = "Value" return usage_type + "Usage item, %s (" % hex(get_full_usage_id ( \ self.page_id, self.usage_id)) + ', '.join(res) + ')'
def __repr__(self): res = [] if self.string_index: res.append( self.get_usage_string() ) res.append( "page_id=%s"%hex(self.page_id) ) res.append( "usage_id=%s"%hex(self.usage_id) ) if self.__value != None: res.append( "value=%s" % str(self.get_value())) else: res.append( "value=[None])" ) usage_type = "" if self.is_button(): usage_type = "Button" elif self.is_value(): usage_type = "Value" return usage_type + "Usage item, %s (" % hex(get_full_usage_id ( \ self.page_id, self.usage_id)) + ', '.join(res) + ')'
477,060
def set_raw_data(self, raw_data): """Set usage values based on given raw data, item[0] is report_id, lenght should match 'raw_data_length' value, best performance if raw_data is c_ubyte ctypes array object type """ #pre-parsed data should exist if not self.__hid_object.ptr_preparsed_data: raise HIDError("HID object close or unable to request preparsed "\ "report data") #valid lenght if len(raw_data) != self.__raw_report_size: raise HIDError( "Report size has to be %d elements (bytes)" \ % self.__raw_report_size ) # copy to internal storage self.__alloc_raw_data(raw_data) if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) data_list_type = HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA bufer data_list = self.__usage_data_list data_len = c_ulong(len(data_list))
def set_raw_data(self, raw_data): """Set usage values based on given raw data, item[0] is report_id, lenght should match 'raw_data_length' value, best performance if raw_data is c_ubyte ctypes array object type """ #pre-parsed data should exist if not self.__hid_object.ptr_preparsed_data: raise HIDError("HID object close or unable to request preparsed "\ "report data") #valid lenght if len(raw_data) != self.__raw_report_size: raise HIDError( "Report size has to be %d elements (bytes)" \ % self.__raw_report_size ) # copy to internal storage self.__alloc_raw_data(raw_data) if not self.__usage_data_list: # create HIDP_DATA buffer max_items = hid_dll.HidP_MaxDataListLength(self.__report_kind, self.__hid_object.ptr_preparsed_data) data_list_type = HIDP_DATA * max_items self.__usage_data_list = data_list_type() #reference HIDP_DATA bufer data_list = self.__usage_data_list data_len = c_ulong(len(data_list))
477,061
def __getitem__(self, key): if '.' not in key: return self.parent[key] else: all_keys = key.split('.') curr_var = self.parent[all_keys[0]] for item in all_keys[1:]: new_var = getattr(curr_var, item) curr_var = new_var return new_var
def __getitem__(self, key): if '.' not in key: return self.parent[key] else: all_keys = key.split('.') curr_var = self.parent[all_keys[0]] for item in all_keys[1:]: new_var = getattr(curr_var, item) curr_var = new_var return new_var
477,062
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,063
def SaveFileSequence(arr,basename=None,format='gif',tiffBits=16): if basename==None: basename=wx.SaveFileSelector('Array as Sequence of Gifs -- numbers automatically added to','.'+format) if format in _gif_names: pass elif format in _tif_names: if tiffBits not in [8,16,32]: print 'Unsupported tiff format! Choose 8 or 16 bit.' return else: print 'Unsupported Format! Choose Gif or Tiff format' return if dtype==np.uint8 and arr.max()>255: arr=np.array(arr*255./arr.max(),np.uint8) if len(arr.shape)==2: SaveSingle(arr,os.path.splitext(basename)[0]+'_0_000'+'.'+format,format=format,tiffBits=tiffBits) elif len(arr.shape)==3: for i in range(arr.shape[0]): SaveSingle(arr[i],os.path.splitext(basename)[0]+'_0_'+str('%03d' % i)+'.'+format,format=format,tiffBits=tiffBits) elif len(arr.shape)==4: for i in range(arr.shape[0]): for j in range(arr.shape[1]): SaveSingle(arr[i,j],os.path.splitext(basename)[0]+'_'+str(i)+'_'+str('%03d' % j)+'.'+format,format=format,tiffBits=tiffBits) else: print 'This function does not support saving arrays with more than 4 dimensions!'
def SaveFileSequence(arr,basename=None,format='gif',tiffBits=16): if basename==None: basename=wx.SaveFileSelector('Array as Sequence of Gifs -- numbers automatically added to','.'+format) if format in _gif_names: pass elif format in _tif_names: if tiffBits not in [8,16,32]: print 'Unsupported tiff format! Choose 8 or 16 bit.' return else: print 'Unsupported Format! Choose Gif or Tiff format' return if arr.dtype==np.uint8 and arr.max()>255: arr=np.array(arr*255./arr.max(),np.uint8) if len(arr.shape)==2: SaveSingle(arr,os.path.splitext(basename)[0]+'_0_000'+'.'+format,format=format,tiffBits=tiffBits) elif len(arr.shape)==3: for i in range(arr.shape[0]): SaveSingle(arr[i],os.path.splitext(basename)[0]+'_0_'+str('%03d' % i)+'.'+format,format=format,tiffBits=tiffBits) elif len(arr.shape)==4: for i in range(arr.shape[0]): for j in range(arr.shape[1]): SaveSingle(arr[i,j],os.path.splitext(basename)[0]+'_'+str(i)+'_'+str('%03d' % j)+'.'+format,format=format,tiffBits=tiffBits) else: print 'This function does not support saving arrays with more than 4 dimensions!'
477,064
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,065
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,066
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,067
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadSingle(filename=None): if filename==None: filename=wx.FileSelector() im=Image.open(filename) # TODO: Need to add more smarts to this based on the mode 'I;16' vs. RGB, etc... #'1','P','RGB','RGBA','L','F','CMYK','YCbCr','I', # Can I simplify this by simply fixing the PIL -> numpy conversion #if im.format in _tif_names: datatype=np.uint16 #elif im.format in _gif_names: datatype=np.uint8 t=np.array(im) if t.dtype in [np.uint8,np.uint16,np.float32]: pass elif t.dtype==np.int16: t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) else: print 'What kind of image fomrat is this anyway???' print 'Should be a 16 or 32 bit tiff or 8 bit unsigned gif or tiff' return t.resize(im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format in _tif_names: fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,068
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) datatype = GetDatatype(im) l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,069
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,070
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadMonolithic(filename=None): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 l=[] numFrames=0 while 1: l.append(np.asarray(im.getdata(),dtype=datatype)) numFrames+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence t=np.array(l,dtype=datatype) # Oops--was t=np.array(im)!! #No need for this any more... # if t.dtype in [np.uint8,np.uint16]: # pass # elif t.dtype==np.int16: # t=np.uint16(t) # Convert from int16 to uint16 (same as what ImageJ does [I think]) # else: # print 'What kind of image fomrat is this anyway???' # print 'Should be a 16bit tiff or 8bit unsigned gif or tiff.' # return t.resize(numFrames,im.size[1],im.size[0]) # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,071
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) datatype = GetDatatype(im) t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,072
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
def LoadFrameFromMonolithic(filename=None,frameNum=0): #f='C:/Documents and Settings/Owner/Desktop/Stack_Zproject_GBR_DC.gif' if filename==None: filename=wx.FileSelector() im=Image.open(filename) if im.format in _tif_names: datatype=np.uint16 elif im.format in _gif_names: datatype=np.uint8 t=None i=0 while 1: if i==frameNum: t = np.asarray(im.getdata(),dtype=datatype) t.resize(numFrames,im.size[1],im.size[0]) break i+=1 try: im.seek(im.tell()+1) except EOFError: break # end of sequence if t==None: print 'Frame not able to be loaded' return t else: # Patch around PIL's Tiff stupidity... if im.format=='TIFF': fid=open(filename,'rb') endianness=fid.read(2) fid.close() if endianness=='MM': # I assume no one will use earlier than 1.1.4 # 1.1.4 to 1.1.6 had a bug; fixed in 1.1.7 and later if Image.VERSION in ['1.1.4','1.1.5','1.1.6']: t.byteswap(True) elif endianness=='II': pass else: print "Just so you know... that ain't no tiff!" return t
477,073
def LoadMonolithicOrSequenceSpecial(filename=None): if filename==None: filename=wx.FileSelector() numFrames,w,h,isSequence = GetShapeMonolithicOrSequence(filename) if isSequence: files = getSortedListOfNumericalEquivalentFiles( filename,os.path.split(filename)[0] ) if len(files)==0: print 'Empty Directory!' return t0=LoadSingle(files[0]) t=np.zeros([len(files),t0.shape[0],t0.shape[1]],t0.dtype) for i in range(len(files)): t[i]=LoadSingle(files[i]) return t else: return LoadMonolithic(filename)
def LoadMonolithicOrSequenceSpecial(filename=None): if filename==None: filename=wx.FileSelector() numFrames,w,h,isSequence = GetShapeMonolithicOrSequence(filename) if isSequence: files = getSortedListOfNumericalEquivalentFiles( filename,os.path.split(filename)[0]) if len(files)==0: print 'Empty Directory!' return t0=LoadSingle(files[0]) t=np.zeros([len(files),t0.shape[0],t0.shape[1]],t0.dtype) for i in range(len(files)): t[i]=LoadSingle(files[i]) return t else: return LoadMonolithic(filename)
477,074
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: import bluesock try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
477,075
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
477,076
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
def find_bricks(host=None, name=None): """Used by find_one_brick to look for bricks ***ADVANCED USERS ONLY***""" try: import usbsock usb_available = True socks = usbsock.find_bricks(host, name) for s in socks: yield s except ImportError: usb_available = False import sys print >>sys.stderr, "USB module unavailable, not searching there" try: from bluetooth import BluetoothError try: import bluesock socks = bluesock.find_bricks(host, name) for s in socks: yield s except (bluesock.bluetooth.BluetoothError, IOError): #for cases such as no adapter, bluetooth throws IOError, not BluetoothError pass except ImportError: import sys print >>sys.stderr, "Bluetooth module unavailable, not searching there" if not usb_available: raise NoBackendError("Neither USB nor Bluetooth could be used! Did you install PyUSB or PyBluez?")
477,077
def _ls_read(self): for n in range(3): try: return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
def _ls_get_status(self, n_bytes): for n in range(3): try: return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
477,078
def _ls_read(self): for n in range(3): try: return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
def _ls_read(self): for n in range(3): try: return self.brick.ls_read(self.port) except I2CError: pass raise I2CError, 'ls_read timeout'
477,079
def _i2c_query(self, address, format): """Reads an i2c value from given address, and returns a value unpacked according to the given format. Format is the same as in the struct module. """ n_bytes = struct.calcsize(format) msg = chr(self.I2C_DEV) + chr(address) if not self.lastpoll: self.lastpoll = time() if self.lastpoll+0.02 > time(): diff = time() - self.lastpoll sleep(0.02 - diff) self.brick.ls_write(self.port, msg, n_bytes) data = self._ls_read() self.lastpoll = time() if len(data) < n_bytes: raise I2CError, 'Read failure' return struct.unpack(format, data[-n_bytes:]) # TODO: why could there be more than n_bytes?
def _i2c_query(self, address, format): """Reads an i2c value from given address, and returns a value unpacked according to the given format. Format is the same as in the struct module. """ n_bytes = struct.calcsize(format) msg = chr(self.I2C_DEV) + chr(address) if not self.lastpoll: self.lastpoll = time() if self.lastpoll+0.02 > time(): diff = time() - self.lastpoll sleep(0.02 - diff) self.brick.ls_write(self.port, msg, n_bytes) self._ls_get_status(n_bytes) data = self.brick.ls_read(self.port) self.lastpoll = time() if len(data) < n_bytes: raise I2CError, 'Read failure' return struct.unpack(format, data[-n_bytes:]) # TODO: why could there be more than n_bytes?
477,080
def __init__(self, red, green, blue, white): self.red, self.green, self.blue, self.white = red, green, blue, white
def __init__(self, red, green, blue, white): self.red, self.green, self.blue, self.white = red, green, blue, white
477,081
def __init__(self, red, green, blue, white): self.red, self.green, self.blue, self.white = red, green, blue, white
def __init__(self, red, green, blue, white): self.red, self.green, self.blue, self.white = red, green, blue, white
477,082
def get_passive_color(self): """"Returns color values when in passive or raw mode. """ red = self.read_value('rawred') green = self.read_value('rawgreen') blue = self.read_value('rawblue') white = self.read_value('rawwhite') return PassiveColor(red, green, blue, white)
def get_passive_color(self): """"Returns color values when in passive or raw mode. """ red, green, blue, white = self.read_value('all_raw_data') return PassiveColor(red, green, blue, white)
477,083
def paintEvent(self, event) : if len(self.highlight_positions_list) > 0 : painter = Qt.QPainter(self)
def paintEvent(self, event) : if len(self.highlight_positions_list) > 0 : painter = Qt.QPainter(self)
477,084
def data(index = -1) : if index < 0 : index = self.index() return self.actions_list[index].data()
def data(self, index = -1) : if index < 0 : index = self.index() return self.actions_list[index].data()
477,085
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
477,086
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
477,087
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
477,088
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
def compress(base, directory): filelist = os.listdir(directory) filelist.sort() for file in filelist: if file in ('checksum.files', 'checksum.global', 'var', 'files.html'): continue if base: filename = base + '/' + file else: filename = file absfilename = os.path.join(directory, file) if os.path.isfile(absfilename): print 'BZIP2', os.path.normcase(absfilename) os.system('updater\\bzip2.exe %s' % os.path.normcase(absfilename)) elif os.path.isdir(absfilename): compress(filename, os.path.join(directory, file)) else: raise 'Unknow file type %s' % file
477,089
def index_product(product): """Indexes passed product. """ if product.is_variant(): try: product = product.parent.get_default_variant() except AttributeError: return _index_products([product])
def index_product(product): """Indexes passed product. """ if product.is_variant(): try: product = product.parent.get_default_variant() except AttributeError: return if product.active: _index_products([product])
477,090
def delete_product(product): """Deletes passed product from index. """ conn = Solr(SOLR_ADDRESS) conn.delete(id=product.id)
def delete_product(product): """Deletes passed product from index. """ conn = Solr(SOLR_ADDRESS) conn.delete(id=product.id)
477,091
def _changesetFromRevision(self, branch, revision_id): """ Generate changeset for the given Bzr revision """ from datetime import datetime from vcpx.tzinfo import FixedOffset, UTC
def _changesetFromRevision(self, branch, revision_id): """ Generate changeset for the given Bzr revision """ from datetime import datetime from vcpx.tzinfo import FixedOffset, UTC
477,092
def setLog(self, log): """Strip away the "Ignore-this:" noise from the changelog."""
def setLog(self, log): """Strip away the "Ignore-this:" noise from the changelog."""
477,093
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
477,094
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
def debug (*what): print >> sys.stderr, '[DEBUG]: ', ' '.join (map (unicode, what))
477,095
def process_phrase (okey, phrase, freq): global phrase_counter, phrases, freq_total, i_map phrase_counter += 1 k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq freq_total += freq ikeys = g ([[]], okey.split (), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join (i) if ikey in ip_map: ip_map[ikey].add (k) else: ip_map[ikey] = set ([k])
def process_phrase (okey, phrase, freq): global phrase_counter, phrases, freq_total, i_map phrase_counter += 1 k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g ([[]], okey.split (), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join (i) if ikey in ip_map: ip_map[ikey].add (k) else: ip_map[ikey] = set ([k]) for okey in okeys: for phrase in okeys[okey]: process_phrase(okey, phrase, 0) if options.verbose and phrase_counter % 1000 == 0: print >> sys.stderr, '%dk phrases imported from %s.' % (phrase_counter / 1000, keyword_file) del okeys
477,096
def __register_dict(self, dict_prefix, max_key_length, schema_info): if dict_prefix not in self.__dict: s = self.__dict[dict_prefix] = [max_key_length, [], None, dict(), -1] else: s = self.__dict[dict_prefix][1] s.append(schema_info)
def __register_dict(self, dict_prefix, max_key_length, schema_info): if dict_prefix not in self.__dict: s = self.__dict[dict_prefix] = [max_key_length, [], None, dict(), -1] else: s = self.__dict[dict_prefix][1] s.append(schema_info)
477,097
def process_phrase(okey, phrase, freq): global phrase_counter, phrases, freq_total, ip_map phrase_counter += 1 freq_total += freq k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g([[]], okey.split(), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join(i) if ikey in ip_map: ip_map[ikey].add(k) else: ip_map[ikey] = set([k])
def process_phrase(okey, phrase, freq): global phrase_counter, phrases, freq_total, ip_map phrase_counter += 1 freq_total += freq k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g([[]], okey.split(), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join(i) if ikey in ip_map: ip_map[ikey].add(k) else: ip_map[ikey] = set([k])
477,098
def process_phrase(okey, phrase, freq): global phrase_counter, phrases, freq_total, ip_map phrase_counter += 1 freq_total += freq k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g([[]], okey.split(), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join(i) if ikey in ip_map: ip_map[ikey].add(k) else: ip_map[ikey] = set([k])
def process_phrase(okey, phrase, freq): global phrase_counter, phrases, freq_total, ip_map phrase_counter += 1 freq_total += freq k = (okey, phrase) if k in phrases: phrases[k] += freq else: phrases[k] = freq ikeys = g([[]], okey.split(), 0) if not ikeys and options.verbose: print >> sys.stderr, 'failed index generation for phrase [%s] %s.' % (okey, phrase) for i in ikeys: ikey = u' '.join(i) if ikey in ip_map: ip_map[ikey].add(k) else: ip_map[ikey] = set([k])
477,099