positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def update_labels(self, func): """ Map a function over baseline and adjustment values in place. Note that the baseline data values must be a LabelArray. """ if not isinstance(self.data, LabelArray): raise TypeError( 'update_labels only supported if data is of type LabelArray.' ) # Map the baseline values. self._data = self._data.map(func) # Map each of the adjustments. for _, row_adjustments in iteritems(self.adjustments): for adjustment in row_adjustments: adjustment.value = func(adjustment.value)
Map a function over baseline and adjustment values in place. Note that the baseline data values must be a LabelArray.
def dump(obj, fp, *args, **kwargs): """Serialize a object to a file object. Basic Usage: >>> import simplekit.objson >>> from cStringIO import StringIO >>> obj = {'name': 'wendy'} >>> io = StringIO() >>> simplekit.objson.dump(obj, io) >>> print io.getvalue() :param obj: a object which need to dump :param fp: a instance of file object :param args: Optional arguments that :func:`json.dump` takes. :param kwargs: Keys arguments that :func:`json.dump` takes. :return: None """ kwargs['default'] = object2dict json.dump(obj, fp, *args, **kwargs)
Serialize a object to a file object. Basic Usage: >>> import simplekit.objson >>> from cStringIO import StringIO >>> obj = {'name': 'wendy'} >>> io = StringIO() >>> simplekit.objson.dump(obj, io) >>> print io.getvalue() :param obj: a object which need to dump :param fp: a instance of file object :param args: Optional arguments that :func:`json.dump` takes. :param kwargs: Keys arguments that :func:`json.dump` takes. :return: None
def timestamp_to_datetime(cls, dt, dt_format=DATETIME_FORMAT): """Convert unix timestamp to human readable date/time string""" return cls.convert_datetime(cls.get_datetime(dt), dt_format=dt_format)
Convert unix timestamp to human readable date/time string
def perform_create(self, serializer): """ determine user when node is added """ if serializer.instance is None: serializer.save(user=self.request.user)
determine user when node is added
def get_config_path(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME): """ Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults to ``config.conf``. Returns: str: Fully qualified path (dir & filename) where we expect the config file. """ return os.path.join(appdirs.user_config_dir, file_name)
Return the path where the config file is stored. Args: app_name (text_type, optional): Name of the application, defaults to ``'projecthamster``. Allows you to use your own application specific namespace if you wish. file_name (text_type, optional): Name of the config file. Defaults to ``config.conf``. Returns: str: Fully qualified path (dir & filename) where we expect the config file.
def reporting(self): """ report on consumption info """ self.thread_debug("reporting") res = resource.getrusage(resource.RUSAGE_SELF) self.NOTIFY("", type='internal-usage', maxrss=round(res.ru_maxrss/1024, 2), ixrss=round(res.ru_ixrss/1024, 2), idrss=round(res.ru_idrss/1024, 2), isrss=round(res.ru_isrss/1024, 2), threads=threading.active_count(), proctot=len(self.monitors), procwin=self.stats.procwin)
report on consumption info
def _wiki_articles(shard_id, wikis_dir=None): """Generates WikipediaArticles from GCS that are part of shard shard_id.""" if not wikis_dir: wikis_dir = WIKI_CONTENT_DIR with tf.Graph().as_default(): dataset = tf.data.TFRecordDataset( cc_utils.readahead( os.path.join(wikis_dir, WIKI_CONTENT_FILE % shard_id)), buffer_size=16 * 1000 * 1000) def _parse_example(ex_ser): """Parse serialized Example containing Wikipedia article content.""" features = { "url": tf.VarLenFeature(tf.string), "title": tf.VarLenFeature(tf.string), "section_titles": tf.VarLenFeature(tf.string), "section_texts": tf.VarLenFeature(tf.string), } ex = tf.parse_single_example(ex_ser, features) for k in ex.keys(): ex[k] = ex[k].values ex["url"] = ex["url"][0] ex["title"] = ex["title"][0] return ex dataset = dataset.map(_parse_example, num_parallel_calls=32) dataset = dataset.prefetch(100) record_it = dataset.make_one_shot_iterator().get_next() with tf.Session() as sess: while True: try: ex = sess.run(record_it) except tf.errors.OutOfRangeError: break sections = [ WikipediaSection(title=text_encoder.to_unicode(title), text=text_encoder.to_unicode(text)) for title, text in zip(ex["section_titles"], ex["section_texts"]) ] yield WikipediaArticle( url=text_encoder.to_unicode(ex["url"]), title=text_encoder.to_unicode(ex["title"]), sections=sections)
Generates WikipediaArticles from GCS that are part of shard shard_id.
def author(self): """ | Comment: The id of the user who wrote the article (set to the user who made the request on create by default) """ if self.api and self.author_id: return self.api._get_user(self.author_id)
| Comment: The id of the user who wrote the article (set to the user who made the request on create by default)
def do_py(self, args: argparse.Namespace) -> bool: """Invoke Python command or shell""" from .pyscript_bridge import PyscriptBridge if self._in_py: err = "Recursively entering interactive Python consoles is not allowed." self.perror(err, traceback_war=False) return False try: self._in_py = True # Support the run command even if called prior to invoking an interactive interpreter def py_run(filename: str): """Run a Python script file in the interactive console. :param filename: filename of *.py script file to run """ expanded_filename = os.path.expanduser(filename) # cmd_echo defaults to False for scripts. The user can always toggle this value in their script. bridge.cmd_echo = False try: with open(expanded_filename) as f: interp.runcode(f.read()) except OSError as ex: error_msg = "Error opening script file '{}': {}".format(expanded_filename, ex) self.perror(error_msg, traceback_war=False) def py_quit(): """Function callable from the interactive Python console to exit that environment""" raise EmbeddedConsoleExit # Set up Python environment bridge = PyscriptBridge(self) self.pystate[self.pyscript_name] = bridge self.pystate['run'] = py_run self.pystate['quit'] = py_quit self.pystate['exit'] = py_quit if self.locals_in_py: self.pystate['self'] = self elif 'self' in self.pystate: del self.pystate['self'] localvars = self.pystate from code import InteractiveConsole interp = InteractiveConsole(locals=localvars) interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())') # Check if the user is running a Python statement on the command line if args.command: full_command = args.command if args.remainder: full_command += ' ' + ' '.join(args.remainder) # Set cmd_echo to True so PyscriptBridge statements like: py app('help') # run at the command line will print their output. bridge.cmd_echo = True # noinspection PyBroadException try: interp.runcode(full_command) except BaseException: # We don't care about any exception that happened in the interactive console pass # If there are no args, then we will open an interactive Python console else: # Set up readline for Python console if rl_type != RlType.NONE: # Save cmd2 history saved_cmd2_history = [] for i in range(1, readline.get_current_history_length() + 1): # noinspection PyArgumentList saved_cmd2_history.append(readline.get_history_item(i)) readline.clear_history() # Restore py's history for item in self.py_history: readline.add_history(item) if self.use_rawinput and self.completekey: # Set up tab completion for the Python console # rlcompleter relies on the default settings of the Python readline module if rl_type == RlType.GNU: saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value rl_basic_quote_characters.value = orig_rl_basic_quotes if 'gnureadline' in sys.modules: # rlcompleter imports readline by name, so it won't use gnureadline # Force rlcompleter to use gnureadline instead so it has our settings and history saved_readline = None if 'readline' in sys.modules: saved_readline = sys.modules['readline'] sys.modules['readline'] = sys.modules['gnureadline'] saved_delims = readline.get_completer_delims() readline.set_completer_delims(orig_rl_delims) # rlcompleter will not need cmd2's custom display function # This will be restored by cmd2 the next time complete() is called if rl_type == RlType.GNU: readline.set_completion_display_matches_hook(None) elif rl_type == RlType.PYREADLINE: # noinspection PyUnresolvedReferences readline.rl.mode._display_completions = self._display_matches_pyreadline # Save off the current completer and set a new one in the Python console # Make sure it tab completes from its locals() dictionary saved_completer = readline.get_completer() interp.runcode("from rlcompleter import Completer") interp.runcode("import readline") interp.runcode("readline.set_completer(Completer(locals()).complete)") # Set up sys module for the Python console self._reset_py_display() saved_sys_stdout = sys.stdout sys.stdout = self.stdout saved_sys_stdin = sys.stdin sys.stdin = self.stdin cprt = 'Type "help", "copyright", "credits" or "license" for more information.' instructions = ('End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, `exit()`.\n' 'Non-Python commands can be issued with: {}("your command")\n' 'Run Python code from external script files with: run("script.py")' .format(self.pyscript_name)) # noinspection PyBroadException try: interp.interact(banner="Python {} on {}\n{}\n\n{}\n". format(sys.version, sys.platform, cprt, instructions)) except BaseException: # We don't care about any exception that happened in the interactive console pass finally: sys.stdout = saved_sys_stdout sys.stdin = saved_sys_stdin # Set up readline for cmd2 if rl_type != RlType.NONE: # Save py's history self.py_history.clear() for i in range(1, readline.get_current_history_length() + 1): # noinspection PyArgumentList self.py_history.append(readline.get_history_item(i)) readline.clear_history() # Restore cmd2's history for item in saved_cmd2_history: readline.add_history(item) if self.use_rawinput and self.completekey: # Restore cmd2's tab completion settings readline.set_completer(saved_completer) readline.set_completer_delims(saved_delims) if rl_type == RlType.GNU: rl_basic_quote_characters.value = saved_basic_quotes if 'gnureadline' in sys.modules: # Restore what the readline module pointed to if saved_readline is None: del(sys.modules['readline']) else: sys.modules['readline'] = saved_readline except KeyboardInterrupt: pass finally: self._in_py = False return self._should_quit
Invoke Python command or shell
def get_parameters_as_dictionary(self, query_string): """ Returns query string parameters as a dictionary. """ pairs = (x.split('=', 1) for x in query_string.split('&')) return dict((k, unquote(v)) for k, v in pairs)
Returns query string parameters as a dictionary.
def load_molecule_in_rdkit_smiles(self, molSize,kekulize=True,bonds=[],bond_color=None,atom_color = {}, size= {} ): """ Loads mol file in rdkit without the hydrogens - they do not have to appear in the final figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to draw best - since we do not care about the actual coordinates of the original molecule, it is sufficient to have just 2D information. Some molecules can be problematic to import and steps such as stopping sanitize function can be taken. This is done automatically if problems are observed. However, better solutions can also be implemented and need more research. The molecule is then drawn from SMILES in 2D representation without hydrogens. The drawing is saved as an SVG file. """ mol_in_rdkit = self.topology_data.mol #need to reload without hydrogens try: mol_in_rdkit = Chem.RemoveHs(mol_in_rdkit) self.topology_data.smiles = Chem.MolFromSmiles(Chem.MolToSmiles(mol_in_rdkit)) except ValueError: mol_in_rdkit = Chem.RemoveHs(mol_in_rdkit, sanitize = False) self.topology_data.smiles = Chem.MolFromSmiles(Chem.MolToSmiles(mol_in_rdkit), sanitize=False) self.atom_identities = {} i=0 for atom in self.topology_data.smiles.GetAtoms(): self.atom_identities[mol_in_rdkit.GetProp('_smilesAtomOutputOrder')[1:].rsplit(",")[i]] = atom.GetIdx() i+=1 mc = Chem.Mol(self.topology_data.smiles.ToBinary()) if kekulize: try: Chem.Kekulize(mc) except: mc = Chem.Mol(self.topology_data.smiles.ToBinary()) if not mc.GetNumConformers(): rdDepictor.Compute2DCoords(mc) atoms=[] colors={} for i in range(mol_in_rdkit.GetNumAtoms()): atoms.append(i) if len(atom_color)==0: colors[i]=(1,1,1) else: colors = atom_color drawer = rdMolDraw2D.MolDraw2DSVG(int(molSize[0]),int(molSize[1])) drawer.DrawMolecule(mc,highlightAtoms=atoms,highlightBonds=bonds, highlightAtomColors=colors,highlightAtomRadii=size,highlightBondColors=bond_color) drawer.FinishDrawing() self.svg = drawer.GetDrawingText().replace('svg:','') filesvg = open("molecule.svg", "w+") filesvg.write(self.svg)
Loads mol file in rdkit without the hydrogens - they do not have to appear in the final figure. Once loaded, the molecule is converted to SMILES format which RDKit appears to draw best - since we do not care about the actual coordinates of the original molecule, it is sufficient to have just 2D information. Some molecules can be problematic to import and steps such as stopping sanitize function can be taken. This is done automatically if problems are observed. However, better solutions can also be implemented and need more research. The molecule is then drawn from SMILES in 2D representation without hydrogens. The drawing is saved as an SVG file.
def init(): """Initialize configuration and web application.""" global app if app: return app conf.init(), db.init(conf.DbPath, conf.DbStatements) bottle.TEMPLATE_PATH.insert(0, conf.TemplatePath) app = bottle.default_app() bottle.BaseTemplate.defaults.update(get_url=app.get_url) return app
Initialize configuration and web application.
def get_info(self): """Get the information about the channel groups. Returns ------- dict information about this channel group Notes ----- The items in selectedItems() are ordered based on the user's selection (which appears pretty random). It's more consistent to use the same order of the main channel list. That's why the additional for-loop is necessary. We don't care about the order of the reference channels. """ selectedItems = self.idx_l0.selectedItems() selected_chan = [x.text() for x in selectedItems] chan_to_plot = [] for chan in self.chan_name + ['_REF']: if chan in selected_chan: chan_to_plot.append(chan) selectedItems = self.idx_l1.selectedItems() ref_chan = [] for selected in selectedItems: ref_chan.append(selected.text()) hp = self.idx_hp.value() if hp == 0: low_cut = None else: low_cut = hp lp = self.idx_lp.value() if lp == 0: high_cut = None else: high_cut = lp scale = self.idx_scale.value() group_info = {'name': self.group_name, 'chan_to_plot': chan_to_plot, 'ref_chan': ref_chan, 'hp': low_cut, 'lp': high_cut, 'scale': float(scale), 'color': self.idx_color } return group_info
Get the information about the channel groups. Returns ------- dict information about this channel group Notes ----- The items in selectedItems() are ordered based on the user's selection (which appears pretty random). It's more consistent to use the same order of the main channel list. That's why the additional for-loop is necessary. We don't care about the order of the reference channels.
def strain_in_plane(self, **kwargs): ''' Returns the in-plane strain assuming no lattice relaxation, which is positive for tensile strain and negative for compressive strain. ''' if self._strain_out_of_plane is not None: return ((self._strain_out_of_plane / -2.) * (self.unstrained.c11(**kwargs) / self.unstrained.c12(**kwargs) ) ) else: return 1 - self.unstrained.a(**kwargs) / self.substrate.a(**kwargs)
Returns the in-plane strain assuming no lattice relaxation, which is positive for tensile strain and negative for compressive strain.
def value_and_grad(fun, x): """Returns a function that returns both value and gradient. Suitable for use in scipy.optimize""" vjp, ans = _make_vjp(fun, x) if not vspace(ans).size == 1: raise TypeError("value_and_grad only applies to real scalar-output " "functions. Try jacobian, elementwise_grad or " "holomorphic_grad.") return ans, vjp(vspace(ans).ones())
Returns a function that returns both value and gradient. Suitable for use in scipy.optimize
def create_product(self, product, version, build, name=None, description=None, attributes={}): ''' create_product(self, product, version, build, name=None, description=None, attributes={}) Create product :Parameters: * *product* (`string`) -- product * *version* (`string`) -- version * *build* (`string`) -- build * *name* (`string`) -- name * *description* (`string`) -- description * *attributes* (`object`) -- product attributes ''' request_data = {'product': product, 'version': version, 'build': build} if name: request_data['name']=name if description: request_data['description']=description if attributes: request_data['attributes']=attributes ret_data= self._call_rest_api('post', '/products', data=request_data, error='Failed to create a new product') pid = ret_data message = 'New product created [pid = %s] '%pid self.logger.info(message) return str(pid)
create_product(self, product, version, build, name=None, description=None, attributes={}) Create product :Parameters: * *product* (`string`) -- product * *version* (`string`) -- version * *build* (`string`) -- build * *name* (`string`) -- name * *description* (`string`) -- description * *attributes* (`object`) -- product attributes
def post(self, view_name): """ login handler """ sess_id = None input_data = {} # try: self._handle_headers() # handle input input_data = json_decode(self.request.body) if self.request.body else {} input_data['path'] = view_name # set or get session cookie if not self.get_cookie(COOKIE_NAME) or 'username' in input_data: sess_id = uuid4().hex self.set_cookie(COOKIE_NAME, sess_id) # , domain='127.0.0.1' else: sess_id = self.get_cookie(COOKIE_NAME) # h_sess_id = "HTTP_%s" % sess_id input_data = {'data': input_data, '_zops_remote_ip': self.request.remote_ip} log.info("New Request for %s: %s" % (sess_id, input_data)) self.application.pc.register_websocket(sess_id, self) self.application.pc.redirect_incoming_message(sess_id, json_encode(input_data), self.request)
login handler
def cycle_interface(self, increment=1): """Cycle through available interfaces in `increment` steps. Sign indicates direction.""" interfaces = [i for i in netifaces.interfaces() if i not in self.ignore_interfaces] if self.interface in interfaces: next_index = (interfaces.index(self.interface) + increment) % len(interfaces) self.interface = interfaces[next_index] elif len(interfaces) > 0: self.interface = interfaces[0] if self.network_traffic: self.network_traffic.clear_counters() self.kbs_arr = [0.0] * self.graph_width
Cycle through available interfaces in `increment` steps. Sign indicates direction.
def urlencode(resource): """ This implementation of urlencode supports all unicode characters :param: resource: Resource value to be url encoded. """ if isinstance(resource, str): return _urlencode(resource.encode('utf-8')) return _urlencode(resource)
This implementation of urlencode supports all unicode characters :param: resource: Resource value to be url encoded.
def is_location(v) -> (bool, str): """ Boolean function for checking if v is a location format Args: v: Returns: bool """ def convert2float(value): try: float_num = float(value) return float_num except ValueError: return False if not isinstance(v, str): return False, v split_lst = v.split(":") if len(split_lst) != 5: return False, v if convert2float(split_lst[3]): longitude = abs(convert2float(split_lst[3])) if longitude > 90: return False, v if convert2float(split_lst[4]): latitude = abs(convert2float(split_lst[3])) if latitude > 180: return False, v return True, v
Boolean function for checking if v is a location format Args: v: Returns: bool
def bytes_required(self): """ Returns ------- int Estimated number of bytes required by arrays registered on the cube, taking their extents into account. """ return np.sum([hcu.array_bytes(a) for a in self.arrays(reify=True).itervalues()])
Returns ------- int Estimated number of bytes required by arrays registered on the cube, taking their extents into account.
def add_particles_ascii(self, s): """ Adds particles from an ASCII string. Parameters ---------- s : string One particle per line. Each line should include particle's mass, radius, position and velocity. """ for l in s.split("\n"): r = l.split() if len(r): try: r = [float(x) for x in r] p = Particle(simulation=self, m=r[0], r=r[1], x=r[2], y=r[3], z=r[4], vx=r[5], vy=r[6], vz=r[7]) self.add(p) except: raise AttributeError("Each line requires 8 floats corresponding to mass, radius, position (x,y,z) and velocity (x,y,z).")
Adds particles from an ASCII string. Parameters ---------- s : string One particle per line. Each line should include particle's mass, radius, position and velocity.
def pieces(self): """ Number of pieces the content is split into or ``None`` if :attr:`piece_size` returns ``None`` """ if self.piece_size is None: return None else: return math.ceil(self.size / self.piece_size)
Number of pieces the content is split into or ``None`` if :attr:`piece_size` returns ``None``
def make_diffuse_comp_info(self, source_name, source_ver, diffuse_dict, components=None, comp_key=None): """ Make a dictionary mapping the merged component names to list of template files Parameters ---------- source_name : str Name of the source source_ver : str Key identifying the version of the source diffuse_dict : dict Information about this component comp_key : str Used when we need to keep track of sub-components, i.e., for moving and selection dependent sources. Returns `model_component.ModelComponentInfo` or `model_component.IsoComponentInfo` """ model_type = diffuse_dict['model_type'] sourcekey = '%s_%s' % (source_name, source_ver) if comp_key is None: template_name = self.make_template_name(model_type, sourcekey) srcmdl_name = self.make_xml_name(sourcekey) else: template_name = self.make_template_name( model_type, "%s_%s" % (sourcekey, comp_key)) srcmdl_name = self.make_xml_name("%s_%s" % (sourcekey, comp_key)) template_name = self._name_factory.fullpath(localpath=template_name) srcmdl_name = self._name_factory.fullpath(localpath=srcmdl_name) kwargs = dict(source_name=source_name, source_ver=source_ver, model_type=model_type, srcmdl_name=srcmdl_name, components=components, comp_key=comp_key) kwargs.update(diffuse_dict) if model_type == 'IsoSource': kwargs['Spectral_Filename'] = template_name return IsoComponentInfo(**kwargs) elif model_type == 'MapCubeSource': kwargs['Spatial_Filename'] = template_name return MapCubeComponentInfo(**kwargs) elif model_type == 'SpatialMap': kwargs['Spatial_Filename'] = template_name return SpatialMapComponentInfo(**kwargs) else: raise ValueError("Unexpected model type %s" % model_type)
Make a dictionary mapping the merged component names to list of template files Parameters ---------- source_name : str Name of the source source_ver : str Key identifying the version of the source diffuse_dict : dict Information about this component comp_key : str Used when we need to keep track of sub-components, i.e., for moving and selection dependent sources. Returns `model_component.ModelComponentInfo` or `model_component.IsoComponentInfo`
def venues(self): """Get a list of all venue objects. >>> venues = din.venues() """ response = self._request(V2_ENDPOINTS['VENUES']) # Normalize `dateHours` to array for venue in response["result_data"]["document"]["venue"]: if venue.get("id") in VENUE_NAMES: venue["name"] = VENUE_NAMES[venue.get("id")] if isinstance(venue.get("dateHours"), dict): venue["dateHours"] = [venue["dateHours"]] if "dateHours" in venue: for dh in venue["dateHours"]: if isinstance(dh.get("meal"), dict): dh["meal"] = [dh["meal"]] return response
Get a list of all venue objects. >>> venues = din.venues()
def prefetch(self, file_size=None): """ Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file's contents are incrementally buffered in a background thread. The prefetched data is stored in a buffer until read via the `.read` method. Once data has been read, it's removed from the buffer. The data may be read in a random order (using `.seek`); chunks of the buffer that haven't been read will continue to be buffered. :param int file_size: When this is ``None`` (the default), this method calls `stat` to determine the remote file size. In some situations, doing so can cause exceptions or hangs (see `#562 <https://github.com/paramiko/paramiko/pull/562>`_); as a workaround, one may call `stat` explicitly and pass its value in via this parameter. .. versionadded:: 1.5.1 .. versionchanged:: 1.16.0 The ``file_size`` parameter was added (with no default value). .. versionchanged:: 1.16.1 The ``file_size`` parameter was made optional for backwards compatibility. """ if file_size is None: file_size = self.stat().st_size # queue up async reads for the rest of the file chunks = [] n = self._realpos while n < file_size: chunk = min(self.MAX_REQUEST_SIZE, file_size - n) chunks.append((n, chunk)) n += chunk if len(chunks) > 0: self._start_prefetch(chunks)
Pre-fetch the remaining contents of this file in anticipation of future `.read` calls. If reading the entire file, pre-fetching can dramatically improve the download speed by avoiding roundtrip latency. The file's contents are incrementally buffered in a background thread. The prefetched data is stored in a buffer until read via the `.read` method. Once data has been read, it's removed from the buffer. The data may be read in a random order (using `.seek`); chunks of the buffer that haven't been read will continue to be buffered. :param int file_size: When this is ``None`` (the default), this method calls `stat` to determine the remote file size. In some situations, doing so can cause exceptions or hangs (see `#562 <https://github.com/paramiko/paramiko/pull/562>`_); as a workaround, one may call `stat` explicitly and pass its value in via this parameter. .. versionadded:: 1.5.1 .. versionchanged:: 1.16.0 The ``file_size`` parameter was added (with no default value). .. versionchanged:: 1.16.1 The ``file_size`` parameter was made optional for backwards compatibility.
def on_complete(cls, req): """ Callback called when the request to REST is done. Handles the errors and if there is none, :class:`.OutputPicker` is shown. """ # handle http errors if not (req.status == 200 or req.status == 0): ViewController.log_view.add(req.text) alert(req.text) # TODO: better handling return try: resp = json.loads(req.text) except ValueError: resp = None if not resp: alert("Chyba při konverzi!") # TODO: better ViewController.log_view.add( "Error while generating MARC: %s" % resp.text ) return OutputPicker.show(resp)
Callback called when the request to REST is done. Handles the errors and if there is none, :class:`.OutputPicker` is shown.
def _acronym_lic(self, license_statement): """Convert license acronym.""" pat = re.compile(r'\(([\w+\W?\s?]+)\)') if pat.search(license_statement): lic = pat.search(license_statement).group(1) if lic.startswith('CNRI'): acronym_licence = lic[:4] else: acronym_licence = lic.replace(' ', '') else: acronym_licence = ''.join( [w[0] for w in license_statement.split(self.prefix_lic)[1].split()]) return acronym_licence
Convert license acronym.
def get_right_geo_fhs(self, dsid, fhs): """Find the right geographical file handlers for given dataset ID *dsid*.""" ds_info = self.ids[dsid] req_geo, rem_geo = self._get_req_rem_geo(ds_info) desired, other = split_desired_other(fhs, req_geo, rem_geo) if desired: try: ds_info['dataset_groups'].remove(rem_geo) except ValueError: pass return desired else: return other
Find the right geographical file handlers for given dataset ID *dsid*.
def debracket(string): """ Eliminate the bracketed var names in doc, line strings """ result = re.sub(BRACKET_RE, ';', str(string)) result = result.lstrip(';') result = result.lstrip(' ') result = result.replace('; ;',';') return result
Eliminate the bracketed var names in doc, line strings
def linear(arr1, arr2): """ Create a linear blend of arr1 (fading out) and arr2 (fading in) """ n = N.shape(arr1)[0] try: channels = N.shape(arr1)[1] except: channels = 1 f_in = N.linspace(0, 1, num=n) f_out = N.linspace(1, 0, num=n) # f_in = N.arange(n) / float(n - 1) # f_out = N.arange(n - 1, -1, -1) / float(n) if channels > 1: f_in = N.tile(f_in, (channels, 1)).T f_out = N.tile(f_out, (channels, 1)).T vals = f_out * arr1 + f_in * arr2 return vals
Create a linear blend of arr1 (fading out) and arr2 (fading in)
def pltar(vrtces, plates): """ Compute the total area of a collection of triangular plates. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltar_c.html :param vrtces: Array of vertices. :type vrtces: Nx3-Element Array of floats :param plates: Array of plates. :type plates: Nx3-Element Array of ints :return: total area of the set of plates :rtype: float """ nv = ctypes.c_int(len(vrtces)) vrtces = stypes.toDoubleMatrix(vrtces) np = ctypes.c_int(len(plates)) plates = stypes.toIntMatrix(plates) return libspice.pltar_c(nv, vrtces, np, plates)
Compute the total area of a collection of triangular plates. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltar_c.html :param vrtces: Array of vertices. :type vrtces: Nx3-Element Array of floats :param plates: Array of plates. :type plates: Nx3-Element Array of ints :return: total area of the set of plates :rtype: float
def get_password(self, service, username): """Get password of the username for the service """ result = self._get_entry(self._keyring, service, username) if result: result = self._decrypt(result) return result
Get password of the username for the service
def array(arr, *args, **kwargs): ''' Wrapper around weldarray - first create np.array and then convert to weldarray. ''' return weldarray(np.array(arr, *args, **kwargs))
Wrapper around weldarray - first create np.array and then convert to weldarray.
def attach_template(self, _template, _key, **unbound_var_values): """Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: A new layer with operation applied. Raises: ValueError: If _key is specified twice or there is a problem computing the template. """ if _key in unbound_var_values: raise ValueError('%s specified twice.' % _key) unbound_var_values[_key] = self return _DeferredLayer(self.bookkeeper, _template.as_layer().construct, [], unbound_var_values, scope=self._scope, defaults=self._defaults, partial_context=self._partial_context)
Attaches the template to this with the _key is supplied with this layer. Note: names were chosen to avoid conflicts. Args: _template: The template to construct. _key: The key that this layer should replace. **unbound_var_values: The values for the unbound_vars. Returns: A new layer with operation applied. Raises: ValueError: If _key is specified twice or there is a problem computing the template.
def __skip_this(self, level): """ Check whether this comparison should be skipped because one of the objects to compare meets exclusion criteria. :rtype: bool """ skip = False if self.exclude_paths and level.path() in self.exclude_paths: skip = True elif self.exclude_regex_paths and any( [exclude_regex_path.search(level.path()) for exclude_regex_path in self.exclude_regex_paths]): skip = True else: if self.exclude_types_tuple and (isinstance(level.t1, self.exclude_types_tuple) or isinstance(level.t2, self.exclude_types_tuple)): skip = True return skip
Check whether this comparison should be skipped because one of the objects to compare meets exclusion criteria. :rtype: bool
def get_font(self, font): """Return the escpos index for `font`. Makes sure that the requested `font` is valid. """ font = {'a': 0, 'b': 1}.get(font, font) if not six.text_type(font) in self.fonts: raise NotSupported( '"{}" is not a valid font in the current profile'.format(font)) return font
Return the escpos index for `font`. Makes sure that the requested `font` is valid.
def save_formatted_data(self, data): """ This will save the formatted data as a repr object (see returns.py) :param data: dict of the return data :return: None """ self.data = data self._timestamps['process'] = time.time() self._stage = STAGE_DONE_DATA_FORMATTED
This will save the formatted data as a repr object (see returns.py) :param data: dict of the return data :return: None
def next_task(self): """ Returns the next task to be executed. This simply asks for the next Node to be evaluated, and then wraps it in the specific Task subclass with which we were initialized. """ node = self._find_next_ready_node() if node is None: return None executor = node.get_executor() if executor is None: return None tlist = executor.get_all_targets() task = self.tasker(self, tlist, node in self.original_top, node) try: task.make_ready() except Exception as e : # We had a problem just trying to get this task ready (like # a child couldn't be linked to a VariantDir when deciding # whether this node is current). Arrange to raise the # exception when the Task is "executed." self.ready_exc = sys.exc_info() if self.ready_exc: task.exception_set(self.ready_exc) self.ready_exc = None return task
Returns the next task to be executed. This simply asks for the next Node to be evaluated, and then wraps it in the specific Task subclass with which we were initialized.
def get_url(cls, data): """Return the URL for a get request based on data type. Args: data: Accepts multiple types. Int: Generate URL to object with data ID. None: Get basic object GET URL (list). String/Unicode: Search for <data> with default_search, usually "name". String/Unicode with "=": Other searches, for example Computers can be search by uuid with: "udid=E79E84CB-3227-5C69-A32C-6C45C2E77DF5" See the class "search_types" attribute for options. """ try: data = int(data) except (ValueError, TypeError): pass if isinstance(data, int): return "%s%s%s" % (cls._url, cls.id_url, data) elif data is None: return cls._url elif isinstance(data, basestring): if "=" in data: key, value = data.split("=") # pylint: disable=no-member if key in cls.search_types: return "%s%s%s" % (cls._url, cls.search_types[key], value) else: raise JSSUnsupportedSearchMethodError( "This object cannot be queried by %s." % key) else: return "%s%s%s" % (cls._url, cls.search_types[cls.default_search], data) else: raise ValueError
Return the URL for a get request based on data type. Args: data: Accepts multiple types. Int: Generate URL to object with data ID. None: Get basic object GET URL (list). String/Unicode: Search for <data> with default_search, usually "name". String/Unicode with "=": Other searches, for example Computers can be search by uuid with: "udid=E79E84CB-3227-5C69-A32C-6C45C2E77DF5" See the class "search_types" attribute for options.
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): work_id = ATTACK_WORK_ID_PATTERN.format(idx) self.work[work_id] = { 'claimed_worker_id': None, 'claimed_worker_start_time': None, 'is_completed': False, 'error': None, 'elapsed_time': None, 'submission_id': adv_batch_val['submission_id'], 'shard_id': None, 'output_adversarial_batch_id': adv_batch_id, }
Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data
def integrate_2d(uSin, angles, res, nm, lD=0, coords=None, count=None, max_count=None, verbose=0): r"""(slow) 2D reconstruction with the Fourier diffraction theorem Two-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,z)` by a dielectric object with refractive index :math:`n(x,z)`. This function implements the solution by summation in real space, which is extremely slow. Parameters ---------- uSin: (A,N) ndarray Two-dimensional sinogram of line recordings :math:`u_{\mathrm{B}, \phi_j}(x_\mathrm{D})` divided by the incident plane wave :math:`u_0(l_\mathrm{D})` measured at the detector. angles: (A,) ndarray Angular positions :math:`\phi_j` of `uSin` in radians. res: float Vacuum wavelength of the light :math:`\lambda` in pixels. nm: float Refractive index of the surrounding medium :math:`n_\mathrm{m}`. lD: float Distance from center of rotation to detector plane :math:`l_\mathrm{D}` in pixels. coords: None or (2,M) ndarray] Computes only the output image at these coordinates. This keyword is reserved for future versions and is not implemented yet. count, max_count: multiprocessing.Value or `None` Can be used to monitor the progress of the algorithm. Initially, the value of `max_count.value` is incremented by the total number of steps. At each step, the value of `count.value` is incremented. verbose: int Increment to increase verbosity. Returns ------- f: ndarray of shape (N,N), complex if `onlyreal` is `False` Reconstructed object function :math:`f(\mathbf{r})` as defined by the Helmholtz equation. :math:`f(x,z) = k_m^2 \left(\left(\frac{n(x,z)}{n_m}\right)^2 -1\right)` See Also -------- backpropagate_2d: implementation by backprojection fourier_map_2d: implementation by Fourier interpolation odt_to_ri: conversion of the object function :math:`f(\mathbf{r})` to refractive index :math:`n(\mathbf{r})` Notes ----- This method is not meant for production use. The computation time is very long and the reconstruction quality is bad. This function is included in the package, because of its educational value, exemplifying the backpropagation algorithm. Do not use the parameter `lD` in combination with the Rytov approximation - the propagation is not correctly described. Instead, numerically refocus the sinogram prior to converting it to Rytov data (using e.g. :func:`odtbrain.sinogram_as_rytov`) with a numerical focusing algorithm (available in the Python package :py:mod:`nrefocus`). """ if coords is None: lx = uSin.shape[1] x = np.linspace(-lx/2, lx/2, lx, endpoint=False) xv, yv = np.meshgrid(x, x) coords = np.zeros((2, lx**2)) coords[0, :] = xv.flat coords[1, :] = yv.flat if max_count is not None: max_count.value += coords.shape[1] + 1 # Cut-Off frequency km = (2 * np.pi * nm) / res # Fourier transform of all uB's # In the script we used the unitary angular frequency (uaf) Fourier # Transform. The discrete Fourier transform is equivalent to the # unitary ordinary frequency (uof) Fourier transform. # # uof: f₁(ξ) = int f(x) exp(-2πi xξ) # # uaf: f₃(ω) = (2π)^(-n/2) int f(x) exp(-i ωx) # # f₁(ω/(2π)) = (2π)^(n/2) f₃(ω) # ω = 2πξ # # We have a one-dimensional (n=1) Fourier transform and UB in the # script is equivalent to f₃(ω). Because we are working with the # uaf, we divide by sqrt(2π) after computing the fft with the uof. # # We calculate the fourier transform of uB further below. This is # necessary for memory control. # Corresponding sample frequencies fx = np.fft.fftfreq(uSin[0].shape[0]) # 1D array # kx is a 1D array. kx = 2 * np.pi * fx # Undersampling/oversampling? # Determine if the resolution of the image is too low by looking # at the maximum value for kx. This is no comparison between # Nyquist and Rayleigh frequency. if np.max(kx**2) <= 2 * km**2: # Detector is not set up properly. Higher resolution # can be achieved. if verbose: print("......Measurement data is undersampled.") else: if verbose: print("......Measurement data is oversampled.") raise NotImplementedError("Oversampled data not yet supported." + " Please rescale input data") # Differentials for integral dphi0 = 2 * np.pi / len(angles) dkx = kx[1] - kx[0] # We will later multiply with phi0. # Make sure we are using correct shapes kx = kx.reshape(1, kx.shape[0]) # Low-pass filter: # less-than-or-equal would give us zero division error. filter_klp = (kx**2 < km**2) # a0 will be multiplied with kx # a0 = np.atleast_1d(a0) # a0 = a0.reshape(1,-1) # Create the integrand # Integrals over ϕ₀ [0,2π]; kx [-kₘ,kₘ] # - double coverage factor 1/2 already included # - unitary angular frequency to unitary ordinary frequency # conversion performed in calculation of UB=FT(uB). # # f(r) = -i kₘ / ((2π)^(3/2) a₀) (prefactor) # * iint dϕ₀ dkx (prefactor) # * |kx| (prefactor) # * exp(-i kₘ M lD ) (prefactor) # * UBϕ₀(kx) (dependent on ϕ₀) # * exp( i (kx t⊥ + kₘ (M - 1) s₀) r ) (dependent on ϕ₀ and r) # # (r and s₀ are vectors. In the last term we perform the dot-product) # # kₘM = sqrt( kₘ² - kx² ) # t⊥ = ( cos(ϕ₀), sin(ϕ₀) ) # s₀ = ( -sin(ϕ₀), cos(ϕ₀) ) # # # everything that is not dependent on phi0: # # Filter M so there are no nans from the root M = 1. / km * np.sqrt((km**2 - kx**2) * filter_klp) prefactor = -1j * km / ((2 * np.pi)**(3. / 2)) prefactor *= dphi0 * dkx # Also filter the prefactor, so nothing outside the required # low-pass contributes to the sum. prefactor *= np.abs(kx) * filter_klp # new in version 0.1.4: # We multiply by the factor (M-1) instead of just (M) # to take into account that we have a scattered # wave that is normalized by u0. prefactor *= np.exp(-1j * km * (M-1) * lD) # Initiate function f f = np.zeros(len(coords[0]), dtype=np.complex128) lenf = len(f) lenu0 = len(uSin[0]) # lenu0 = len(kx[0]) # Initiate vector r that corresponds to calculating a value of f. r = np.zeros((2, 1, 1)) # Everything is normal. # Get the angles ϕ₀. phi0 = angles.reshape(-1, 1) # Compute the Fourier transform of uB. # This is true: np.fft.fft(UB)[0] == np.fft.fft(UB[0]) # because axis -1 is always used. # # # Furthermore, The notation in the our optical tomography script for # a wave propagating to the right is: # # u0(x) = exp(ikx) # # However, in physics usually usethe other sign convention: # # u0(x) = exp(-ikx) # # In order to be consisten with programs like Meep or our scattering # script for a dielectric cylinder, we want to use the latter sign # convention. # This is not a big problem. We only need to multiply the imaginary # part of the scattered wave by -1. UB = np.fft.fft(np.fft.ifftshift(uSin, axes=-1)) / np.sqrt(2 * np.pi) UBi = UB.reshape(len(angles), lenu0) if count is not None: count.value += 1 for j in range(lenf): # Get r (We compute f(r) in this for-loop) r[0][:] = coords[0, j] # x r[1][:] = coords[1, j] # y # Integrand changes with r, so we have to create a new # array: integrand = prefactor * UBi # We save memory by directly applying the following to # the integrand: # # Vector along which we measured # s0 = np.zeros((2, phi0.shape[0], kx.shape[0])) # s0[0] = -np.sin(phi0) # s0[1] = +np.cos(phi0) # Vector perpendicular to s0 # t_perp_kx = np.zeros((2, phi0.shape[0], kx.shape[1])) # # t_perp_kx[0] = kx*np.cos(phi0) # t_perp_kx[1] = kx*np.sin(phi0) # # term3 = np.exp(1j*np.sum(r*( t_perp_kx + (gamma-km)*s0 ), axis=0)) # integrand* = term3 # # Reminder: # f(r) = -i kₘ / ((2π)^(3/2) a₀) (prefactor) # * iint dϕ₀ dkx (prefactor) # * |kx| (prefactor) # * exp(-i kₘ M lD ) (prefactor) # * UB(kx) (dependent on ϕ₀) # * exp( i (kx t⊥ + kₘ(M - 1) s₀) r ) (dependent on ϕ₀ and r) # # (r and s₀ are vectors. In the last term we perform the dot-product) # # kₘM = sqrt( kₘ² - kx² ) # t⊥ = ( cos(ϕ₀), sin(ϕ₀) ) # s₀ = ( -sin(ϕ₀), cos(ϕ₀) ) integrand *= np.exp(1j * ( r[0] * (kx * np.cos(phi0) - km * (M - 1) * np.sin(phi0)) + r[1] * (kx * np.sin(phi0) + km * (M - 1) * np.cos(phi0)))) # Calculate the integral for the position r # integrand.sort() f[j] = np.sum(integrand) # free memory del integrand if count is not None: count.value += 1 return f.reshape(lx, lx)
r"""(slow) 2D reconstruction with the Fourier diffraction theorem Two-dimensional diffraction tomography reconstruction algorithm for scattering of a plane wave :math:`u_0(\mathbf{r}) = u_0(x,z)` by a dielectric object with refractive index :math:`n(x,z)`. This function implements the solution by summation in real space, which is extremely slow. Parameters ---------- uSin: (A,N) ndarray Two-dimensional sinogram of line recordings :math:`u_{\mathrm{B}, \phi_j}(x_\mathrm{D})` divided by the incident plane wave :math:`u_0(l_\mathrm{D})` measured at the detector. angles: (A,) ndarray Angular positions :math:`\phi_j` of `uSin` in radians. res: float Vacuum wavelength of the light :math:`\lambda` in pixels. nm: float Refractive index of the surrounding medium :math:`n_\mathrm{m}`. lD: float Distance from center of rotation to detector plane :math:`l_\mathrm{D}` in pixels. coords: None or (2,M) ndarray] Computes only the output image at these coordinates. This keyword is reserved for future versions and is not implemented yet. count, max_count: multiprocessing.Value or `None` Can be used to monitor the progress of the algorithm. Initially, the value of `max_count.value` is incremented by the total number of steps. At each step, the value of `count.value` is incremented. verbose: int Increment to increase verbosity. Returns ------- f: ndarray of shape (N,N), complex if `onlyreal` is `False` Reconstructed object function :math:`f(\mathbf{r})` as defined by the Helmholtz equation. :math:`f(x,z) = k_m^2 \left(\left(\frac{n(x,z)}{n_m}\right)^2 -1\right)` See Also -------- backpropagate_2d: implementation by backprojection fourier_map_2d: implementation by Fourier interpolation odt_to_ri: conversion of the object function :math:`f(\mathbf{r})` to refractive index :math:`n(\mathbf{r})` Notes ----- This method is not meant for production use. The computation time is very long and the reconstruction quality is bad. This function is included in the package, because of its educational value, exemplifying the backpropagation algorithm. Do not use the parameter `lD` in combination with the Rytov approximation - the propagation is not correctly described. Instead, numerically refocus the sinogram prior to converting it to Rytov data (using e.g. :func:`odtbrain.sinogram_as_rytov`) with a numerical focusing algorithm (available in the Python package :py:mod:`nrefocus`).
def iterative_plane_errors(axes,covariance_matrix, **kwargs): """ An iterative version of `pca.plane_errors`, which computes an error surface for a plane. """ sheet = kwargs.pop('sheet','upper') level = kwargs.pop('level',1) n = kwargs.pop('n',100) cov = N.sqrt(N.diagonal(covariance_matrix)) u = N.linspace(0, 2*N.pi, n) scales = dict(upper=1,lower=-1,nominal=0) c1 = scales[sheet] c1 *= -1 # We assume upper hemisphere if axes[2,2] < 0: c1 *= -1 def sdot(a,b): return sum([i*j for i,j in zip(a,b)]) def step_func(a): e = [ N.cos(a)*cov[0], N.sin(a)*cov[1], c1*cov[2]] d = [sdot(e,i) for i in axes.T] x,y,z = d[2],d[0],d[1] r = N.sqrt(x**2 + y**2 + z**2) lat = N.arcsin(z/r) lon = N.arctan2(y, x) return lon,lat # Get a bundle of vectors defining # a full rotation around the unit circle return N.array([step_func(i) for i in u])
An iterative version of `pca.plane_errors`, which computes an error surface for a plane.
def check_validity_for_dict(keys, dict): """ >>> dict = {'a': 0, 'b': 1, 'c': 2} >>> keys = ['a', 'd', 'e'] >>> check_validity_for_dict(keys, dict) == False True >>> keys = ['a', 'b', 'c'] >>> check_validity_for_dict(keys, dict) == False False """ for key in keys: if key not in dict or dict[key] is '' or dict[key] is None: return False return True
>>> dict = {'a': 0, 'b': 1, 'c': 2} >>> keys = ['a', 'd', 'e'] >>> check_validity_for_dict(keys, dict) == False True >>> keys = ['a', 'b', 'c'] >>> check_validity_for_dict(keys, dict) == False False
def cmd(send, *_): """Gets a random distro. Syntax: {command} """ url = get('http://distrowatch.com/random.php').url match = re.search('=(.*)', url) if match: send(match.group(1)) else: send("no distro found")
Gets a random distro. Syntax: {command}
def getSyntax(self, xmlFileName=None, mimeType=None, languageName=None, sourceFilePath=None, firstLine=None): """Get syntax by one of parameters: * xmlFileName * mimeType * languageName * sourceFilePath First parameter in the list has biggest priority """ syntax = None if syntax is None and xmlFileName is not None: try: syntax = self._getSyntaxByXmlFileName(xmlFileName) except KeyError: _logger.warning('No xml definition %s' % xmlFileName) if syntax is None and mimeType is not None: try: syntax = self._getSyntaxByMimeType(mimeType) except KeyError: _logger.warning('No syntax for mime type %s' % mimeType) if syntax is None and languageName is not None: try: syntax = self._getSyntaxByLanguageName(languageName) except KeyError: _logger.warning('No syntax for language %s' % languageName) if syntax is None and sourceFilePath is not None: baseName = os.path.basename(sourceFilePath) try: syntax = self._getSyntaxBySourceFileName(baseName) except KeyError: pass if syntax is None and firstLine is not None: try: syntax = self._getSyntaxByFirstLine(firstLine) except KeyError: pass return syntax
Get syntax by one of parameters: * xmlFileName * mimeType * languageName * sourceFilePath First parameter in the list has biggest priority
def delete_branch(self, project, repository, name, end_point): """ Delete branch from related repo :param self: :param project: :param repository: :param name: :param end_point: :return: """ url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branches'.format(project=project, repository=repository) data = {"name": str(name), "endPoint": str(end_point)} return self.delete(url, data=data)
Delete branch from related repo :param self: :param project: :param repository: :param name: :param end_point: :return:
def _aspirate_plunger_position(self, ul): """Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required """ millimeters = ul / self._ul_per_mm(ul, 'aspirate') destination_mm = self._get_plunger_position('bottom') + millimeters return round(destination_mm, 6)
Calculate axis position for a given liquid volume. Translates the passed liquid volume to absolute coordinates on the axis associated with this pipette. Calibration of the pipette motor's ul-to-mm conversion is required
def return_multiple_convert_numpy(self, start_id, end_id, converter, add_args=None): """ Converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- start_id : the id of the first object to be converted end_id : the id of the last object to be converted, if equal to -1, will convert all data points in range (start_id, <id of last element in database>) converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : 2-dimensional ndarray """ if end_id == -1: end_id = self.points_amt return return_multiple_convert_numpy_base(self.dbpath, self.path_to_set, self._set_object, start_id, end_id, converter, add_args)
Converts several objects, with ids in the range (start_id, end_id) into a 2d numpy array and returns the array, the conversion is done by the 'converter' function Parameters ---------- start_id : the id of the first object to be converted end_id : the id of the last object to be converted, if equal to -1, will convert all data points in range (start_id, <id of last element in database>) converter : function, which takes the path of a data point and *args as parameters and returns a numpy array add_args : optional arguments for the converter (list/dictionary/tuple/whatever). if None, the converter should take only one input argument - the file path. default value: None Returns ------- result : 2-dimensional ndarray
def teredo(self): """Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32) """ if (self._ip >> 96) != 0x20010000: return None return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), IPv4Address(~self._ip & 0xFFFFFFFF))
Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn't appear to be a teredo address (doesn't start with 2001::/32)
def remove_program_temp_directory(): """Remove the global temp directory and all its contents.""" if os.path.exists(program_temp_directory): max_retries = 3 curr_retries = 0 time_between_retries = 1 while True: try: shutil.rmtree(program_temp_directory) break except IOError: curr_retries += 1 if curr_retries > max_retries: raise # re-raise the exception time.sleep(time_between_retries) except: print("Cleaning up temp dir...", file=sys.stderr) raise
Remove the global temp directory and all its contents.
def _get_separated_values(self, secondary=False): """Separate values between odd and even series stacked""" series = self.secondary_series if secondary else self.series positive_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if index % 2 ] ) ) negative_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if not index % 2 ] ) ) return list(positive_vals), list(negative_vals)
Separate values between odd and even series stacked
def _construct(self, strings_collection): """ Generalized suffix tree construction algorithm based on the Ukkonen's algorithm for suffix tree construction, with linear [O(n_1 + ... + n_m)] worst-case time complexity, where m is the number of strings in collection. """ # 1. Add a unique character to each string in the collection strings_collection = utils.make_unique_endings(strings_collection) ############################################################ # 2. Build the GST using modified Ukkonnen's algorithm # ############################################################ root = ast.AnnotatedSuffixTree.Node() root.strings_collection = strings_collection # To preserve simplicity root.suffix_link = root root._arc = (0,-1,0) # For constant updating of all leafs, see [Gusfield {RUS}, p. 139] root._e = [0 for _ in xrange(len(strings_collection))] def _ukkonen_first_phases(string_ind): """ Looks for the part of the string which is already encoded. Returns a tuple of form ([length of already encoded string preffix], [tree node to start the first explicit phase with], [path to go down at the beginning of the first explicit phase]). """ already_in_tree = 0 suffix = strings_collection[string_ind] starting_path = (0, 0, 0) starting_node = root child_node = starting_node.chose_arc(suffix) while child_node: (str_ind, substr_start, substr_end) = child_node.arc() match = utils.match_strings( suffix, strings_collection[str_ind][substr_start:substr_end]) already_in_tree += match if match == substr_end-substr_start: # matched the arc, proceed with child node suffix = suffix[match:] starting_node = child_node child_node = starting_node.chose_arc(suffix) else: # otherwise we will have to proceed certain path at the beginning # of the first explicit phase starting_path = (str_ind, substr_start, substr_start+match) break # For constant updating of all leafs, see [Gusfield {RUS}, p. 139] root._e[string_ind] = already_in_tree return (already_in_tree, starting_node, starting_path) def _ukkonen_phase(string_ind, phase, starting_node, starting_path, starting_continuation): """ Ukkonen's algorithm single phase. Returns a tuple of form: ([tree node to start the next phase with], [path to go down at the beginning of the next phase], [starting continuation for the next phase]). """ current_suffix_end = starting_node suffix_link_source_node = None path_str_ind, path_substr_start, path_substr_end = starting_path # Continuations [starting_continuation..(i+1)] for continuation in xrange(starting_continuation, phase+1): # Go up to the first node with suffix link [no more than 1 pass] if continuation > starting_continuation: path_str_ind, path_substr_start, path_substr_end = 0, 0, 0 if not current_suffix_end.suffix_link: (path_str_ind, path_substr_start, path_substr_end) = current_suffix_end.arc() current_suffix_end = current_suffix_end.parent if current_suffix_end.is_root(): path_str_ind = string_ind path_substr_start = continuation path_substr_end = phase else: # Go through the suffix link current_suffix_end = current_suffix_end.suffix_link # Go down the path (str_ind, substr_start, substr_end) # NB: using Skip/Count trick, # see [Gusfield {RUS} p.134] for details g = path_substr_end - path_substr_start if g > 0: current_suffix_end = current_suffix_end.chose_arc(strings_collection [path_str_ind][path_substr_start]) (_, cs_ss_start, cs_ss_end) = current_suffix_end.arc() g_ = cs_ss_end - cs_ss_start while g >= g_: path_substr_start += g_ g -= g_ if g > 0: current_suffix_end = current_suffix_end.chose_arc(strings_collection [path_str_ind][path_substr_start]) (_, cs_ss_start, cs_ss_end) = current_suffix_end.arc() g_ = cs_ss_end - cs_ss_start # Perform continuation by one of three rules, # see [Gusfield {RUS} p. 129] for details if g == 0: # Rule 1 if current_suffix_end.is_leaf(): pass # Rule 2a elif not current_suffix_end.chose_arc(strings_collection[string_ind][phase]): if suffix_link_source_node: suffix_link_source_node.suffix_link = current_suffix_end new_leaf = current_suffix_end.add_new_child(string_ind, phase, -1) new_leaf.weight = 1 if continuation == starting_continuation: starting_node = new_leaf starting_path = (0, 0, 0) # Rule 3a else: if suffix_link_source_node: suffix_link_source_node.suffix_link = current_suffix_end starting_continuation = continuation starting_node = current_suffix_end starting_path = (string_ind, phase, phase+1) break suffix_link_source_node = None else: (si, ss, se) = current_suffix_end._arc # Rule 2b if strings_collection[si][ss + g] != strings_collection[string_ind][phase]: parent = current_suffix_end.parent parent.remove_child(current_suffix_end) current_suffix_end._arc = (si, ss+g, se) new_node = parent.add_new_child(si, ss, ss + g) new_leaf = new_node.add_new_child(string_ind, phase, -1) new_leaf.weight = 1 if continuation == starting_continuation: starting_node = new_leaf starting_path = (0, 0, 0) new_node.add_child(current_suffix_end) if suffix_link_source_node: # Define new suffix link suffix_link_source_node.suffix_link = new_node suffix_link_source_node = new_node current_suffix_end = new_node # Rule 3b else: suffix_link_source_node = None starting_continuation = continuation starting_node = current_suffix_end.parent starting_path = (si, ss, ss+g+1) break # Constant updating of all leafs, see [Gusfield {RUS}, p. 139] starting_node._e[string_ind] += 1 return starting_node, starting_path, starting_continuation for m in xrange(len(strings_collection)): # Check for phases 1..x that are already in tree starting_phase, starting_node, starting_path = _ukkonen_first_phases(m) starting_continuation = 0 # Perform phases (x+1)..n explicitly for phase in xrange(starting_phase, len(strings_collection[m])): starting_node, starting_path, starting_continuation = \ _ukkonen_phase(m, phase, starting_node, starting_path, starting_continuation) ############################################################ ############################################################ ############################################################ # 3. Delete degenerate first-level children for k in root.children.keys(): (ss, si, se) = root.children[k].arc() if (se - si == 1 and ord(strings_collection[ss][si]) >= consts.String.UNICODE_SPECIAL_SYMBOLS_START): del root.children[k] # 4. Make a depth-first bottom-up traversal and annotate # each node by the sum of its children; # each leaf is already annotated with '1'. def _annotate(node): weight = 0 for k in node.children: if node.children[k].weight > 0: weight += node.children[k].weight else: weight += _annotate(node.children[k]) node.weight = weight return weight _annotate(root) return root
Generalized suffix tree construction algorithm based on the Ukkonen's algorithm for suffix tree construction, with linear [O(n_1 + ... + n_m)] worst-case time complexity, where m is the number of strings in collection.
def _input_filter(self, keys, raw): """ handles keypresses. This function gets triggered directly by class:`urwid.MainLoop` upon user input and is supposed to pass on its `keys` parameter to let the root widget handle keys. We intercept the input here to trigger custom commands as defined in our keybindings. """ logging.debug("Got key (%s, %s)", keys, raw) # work around: escape triggers this twice, with keys = raw = [] # the first time.. if not keys: return # let widgets handle input if key is virtual window resize keypress # or we are in "passall" mode elif 'window resize' in keys or self._passall: return keys # end "lockdown" mode if the right key was pressed elif self._locked and keys[0] == self._unlock_key: self._locked = False self.mainloop.widget = self.root_widget if callable(self._unlock_callback): self._unlock_callback() # otherwise interpret keybinding else: def clear(*_): """Callback that resets the input queue.""" if self._alarm is not None: self.mainloop.remove_alarm(self._alarm) self.input_queue = [] async def _apply_fire(cmdline): try: await self.apply_commandline(cmdline) except CommandParseError as e: self.notify(str(e), priority='error') def fire(_, cmdline): clear() logging.debug("cmdline: '%s'", cmdline) if not self._locked: loop = asyncio.get_event_loop() loop.create_task(_apply_fire(cmdline)) # move keys are always passed elif cmdline in ['move up', 'move down', 'move page up', 'move page down']: return [cmdline[5:]] key = keys[0] if key and 'mouse' in key[0]: key = key[0] + ' %i' % key[1] self.input_queue.append(key) keyseq = ' '.join(self.input_queue) candidates = settings.get_mapped_input_keysequences(self.mode, prefix=keyseq) if keyseq in candidates: # case: current input queue is a mapped keysequence # get binding and interpret it if non-null cmdline = settings.get_keybinding(self.mode, keyseq) if cmdline: if len(candidates) > 1: timeout = float(settings.get('input_timeout')) if self._alarm is not None: self.mainloop.remove_alarm(self._alarm) self._alarm = self.mainloop.set_alarm_in( timeout, fire, cmdline) else: return fire(self.mainloop, cmdline) elif not candidates: # case: no sequence with prefix keyseq is mapped # just clear the input queue clear() else: # case: some sequences with proper prefix keyseq is mapped timeout = float(settings.get('input_timeout')) if self._alarm is not None: self.mainloop.remove_alarm(self._alarm) self._alarm = self.mainloop.set_alarm_in(timeout, clear) # update statusbar self.update()
handles keypresses. This function gets triggered directly by class:`urwid.MainLoop` upon user input and is supposed to pass on its `keys` parameter to let the root widget handle keys. We intercept the input here to trigger custom commands as defined in our keybindings.
def retrieve(self, id) : """ Retrieve a single source Returns a single source available to the user by the provided id If a source with the supplied unique identifier does not exist it returns an error :calls: ``get /deal_sources/{id}`` :param int id: Unique identifier of a DealSource. :return: Dictionary that support attriubte-style access and represent DealSource resource. :rtype: dict """ _, _, deal_source = self.http_client.get("/deal_sources/{id}".format(id=id)) return deal_source
Retrieve a single source Returns a single source available to the user by the provided id If a source with the supplied unique identifier does not exist it returns an error :calls: ``get /deal_sources/{id}`` :param int id: Unique identifier of a DealSource. :return: Dictionary that support attriubte-style access and represent DealSource resource. :rtype: dict
def delete_document( self, name, current_document=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> client.delete_document(name) Args: name (str): The resource name of the Document to delete. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_document" not in self._inner_api_calls: self._inner_api_calls[ "delete_document" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_document, default_retry=self._method_configs["DeleteDocument"].retry, default_timeout=self._method_configs["DeleteDocument"].timeout, client_info=self._client_info, ) request = firestore_pb2.DeleteDocumentRequest( name=name, current_document=current_document ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_document"]( request, retry=retry, timeout=timeout, metadata=metadata )
Deletes a document. Example: >>> from google.cloud import firestore_v1beta1 >>> >>> client = firestore_v1beta1.FirestoreClient() >>> >>> name = client.any_path_path('[PROJECT]', '[DATABASE]', '[DOCUMENT]', '[ANY_PATH]') >>> >>> client.delete_document(name) Args: name (str): The resource name of the Document to delete. In the format: ``projects/{project_id}/databases/{database_id}/documents/{document_path}``. current_document (Union[dict, ~google.cloud.firestore_v1beta1.types.Precondition]): An optional precondition on the document. The request will fail if this is set and not met by the target document. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.firestore_v1beta1.types.Precondition` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will not be retried. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid.
def _gst_available(): """Determine whether Gstreamer and the Python GObject bindings are installed. """ try: import gi except ImportError: return False try: gi.require_version('Gst', '1.0') except (ValueError, AttributeError): return False try: from gi.repository import Gst # noqa except ImportError: return False return True
Determine whether Gstreamer and the Python GObject bindings are installed.
def _calc_all_possible_moves(self, input_color): """ Returns list of all possible moves :type: input_color: Color :rtype: list """ for piece in self: # Tests if square on the board is not empty if piece is not None and piece.color == input_color: for move in piece.possible_moves(self): test = cp(self) test_move = Move(end_loc=move.end_loc, piece=test.piece_at_square(move.start_loc), status=move.status, start_loc=move.start_loc, promoted_to_piece=move.promoted_to_piece) test.update(test_move) if self.king_loc_dict is None: yield move continue my_king = test.piece_at_square(self.king_loc_dict[input_color]) if my_king is None or \ not isinstance(my_king, King) or \ my_king.color != input_color: self.king_loc_dict[input_color] = test.find_king(input_color) my_king = test.piece_at_square(self.king_loc_dict[input_color]) if not my_king.in_check(test): yield move
Returns list of all possible moves :type: input_color: Color :rtype: list
def neighbor_state_get(self, address=None, format='json'): """ This method returns the state of peer(s) in a json format. ``address`` specifies the address of a peer. If not given, the state of all the peers return. ``format`` specifies the format of the response. This parameter must be one of the following. - 'json' (default) - 'cli' """ show = { 'params': ['neighbor', 'summary'], 'format': format, } if address: show['params'].append(address) return call('operator.show', **show)
This method returns the state of peer(s) in a json format. ``address`` specifies the address of a peer. If not given, the state of all the peers return. ``format`` specifies the format of the response. This parameter must be one of the following. - 'json' (default) - 'cli'
def add_interim_values(module, input, output): """The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers """ try: del module.x except AttributeError: pass try: del module.y except AttributeError: pass module_type = module.__class__.__name__ if module_type in op_handler: func_name = op_handler[module_type].__name__ # First, check for cases where we don't need to save the x and y tensors if func_name == 'passthrough': pass else: # check only the 0th input varies for i in range(len(input)): if i != 0 and type(output) is tuple: assert input[i] == output[i], "Only the 0th input may vary!" # if a new method is added, it must be added here too. This ensures tensors # are only saved if necessary if func_name in ['maxpool', 'nonlinear_1d']: # only save tensors if necessary if type(input) is tuple: setattr(module, 'x', torch.nn.Parameter(input[0].detach())) else: setattr(module, 'x', torch.nn.Parameter(input.detach())) if type(output) is tuple: setattr(module, 'y', torch.nn.Parameter(output[0].detach())) else: setattr(module, 'y', torch.nn.Parameter(output.detach())) if module_type in failure_case_modules: input[0].register_hook(deeplift_tensor_grad)
The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers
def connect(self): "Connect to a host on a given (SSL) port." # # source_address é atributo incluído na versão 2.7 do Python # Verificando a existência para funcionar em versões anteriores à 2.7 # if hasattr(self, 'source_address'): sock = socket.create_connection((self.host, self.port), self.timeout, self.source_address) else: sock = socket.create_connection((self.host, self.port), self.timeout) if self._tunnel_host: self.sock = sock self._tunnel() if sys.version_info >= (2,7,13): self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLS, do_handshake_on_connect=False) else: self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_SSLv23, do_handshake_on_connect=False)
Connect to a host on a given (SSL) port.
def get_project() -> Optional[str]: """ Returns the current project name. """ project = SETTINGS.project if not project: require_test_mode_enabled() raise RunError('Missing project name; for test mode, please set PULUMI_NODEJS_PROJECT') return project
Returns the current project name.
def round_down(x, decimal_places): """ Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.23456, 2) 1.23 """ from math import floor d = int('1' + ('0' * decimal_places)) return floor(x * d) / d
Round a float down to decimal_places. Parameters ---------- x : float decimal_places : int Returns ------- rounded_float : float Examples -------- >>> round_down(1.23456, 3) 1.234 >>> round_down(1.23456, 2) 1.23
def pyxlines(self): """Cython code lines. Assumptions: * Function shall be a method * Method shall be inlined * Method returns nothing * Method arguments are of type `int` (except self) * Local variables are generally of type `int` but of type `double` when their name starts with `d_` """ lines = [' '+line for line in self.cleanlines] lines[0] = lines[0].replace('def ', 'cpdef inline void ') lines[0] = lines[0].replace('):', ') %s:' % _nogil) for name in self.untypedarguments: lines[0] = lines[0].replace(', %s ' % name, ', int %s ' % name) lines[0] = lines[0].replace(', %s)' % name, ', int %s)' % name) for name in self.untypedinternalvarnames: if name.startswith('d_'): lines.insert(1, ' cdef double ' + name) else: lines.insert(1, ' cdef int ' + name) return Lines(*lines)
Cython code lines. Assumptions: * Function shall be a method * Method shall be inlined * Method returns nothing * Method arguments are of type `int` (except self) * Local variables are generally of type `int` but of type `double` when their name starts with `d_`
def update(self, scriptid, params=None): ''' /v1/startupscript/update POST - account Update an existing startup script Link: https://www.vultr.com/api/#startupscript_update ''' params = update_params(params, {'SCRIPTID': scriptid}) return self.request('/v1/startupscript/update', params, 'POST')
/v1/startupscript/update POST - account Update an existing startup script Link: https://www.vultr.com/api/#startupscript_update
def _get_attrs(self): """An internal helper for the representation methods""" attrs = [] attrs.append(("N Blocks", self.n_blocks, "{}")) bds = self.bounds attrs.append(("X Bounds", (bds[0], bds[1]), "{:.3f}, {:.3f}")) attrs.append(("Y Bounds", (bds[2], bds[3]), "{:.3f}, {:.3f}")) attrs.append(("Z Bounds", (bds[4], bds[5]), "{:.3f}, {:.3f}")) return attrs
An internal helper for the representation methods
def get_rmq_cluster_status(self, sentry_unit): """Execute rabbitmq cluster status command on a unit and return the full output. :param unit: sentry unit :returns: String containing console output of cluster status command """ cmd = 'rabbitmqctl cluster_status' output, _ = self.run_cmd_unit(sentry_unit, cmd) self.log.debug('{} cluster_status:\n{}'.format( sentry_unit.info['unit_name'], output)) return str(output)
Execute rabbitmq cluster status command on a unit and return the full output. :param unit: sentry unit :returns: String containing console output of cluster status command
def find_sources_in_image(self, filename, hdu_index=0, outfile=None, rms=None, bkg=None, max_summits=None, innerclip=5, outerclip=4, cores=None, rmsin=None, bkgin=None, beam=None, doislandflux=False, nopositive=False, nonegative=False, mask=None, lat=None, imgpsf=None, blank=False, docov=True, cube_index=None): """ Run the Aegean source finder. Parameters ---------- filename : str or HDUList Image filename or HDUList. hdu_index : int The index of the FITS HDU (extension). outfile : str file for printing catalog (NOT a table, just a text file of my own design) rms : float Use this rms for the entire image (will also assume that background is 0) max_summits : int Fit up to this many components to each island (extras are included but not fit) innerclip, outerclip : float The seed (inner) and flood (outer) clipping level (sigmas). cores : int Number of CPU cores to use. None means all cores. rmsin, bkgin : str or HDUList Filename or HDUList for the noise and background images. If either are None, then it will be calculated internally. beam : (major, minor, pa) Floats representing the synthesised beam (degrees). Replaces whatever is given in the FITS header. If the FITS header has no BMAJ/BMIN then this is required. doislandflux : bool If True then each island will also be characterized. nopositive, nonegative : bool Whether to return positive or negative sources. Default nopositive=False, nonegative=True. mask : str The filename of a region file created by MIMAS. Islands outside of this region will be ignored. lat : float The latitude of the telescope (declination of zenith). imgpsf : str or HDUList Filename or HDUList for a psf image. blank : bool Cause the output image to be blanked where islands are found. docov : bool If True then include covariance matrix in the fitting process. (default=True) cube_index : int For image cubes, cube_index determines which slice is used. Returns ------- sources : list List of sources found. """ # Tell numpy to be quiet np.seterr(invalid='ignore') if cores is not None: if not (cores >= 1): raise AssertionError("cores must be one or more") self.load_globals(filename, hdu_index=hdu_index, bkgin=bkgin, rmsin=rmsin, beam=beam, rms=rms, bkg=bkg, cores=cores, verb=True, mask=mask, lat=lat, psf=imgpsf, blank=blank, docov=docov, cube_index=cube_index) global_data = self.global_data rmsimg = global_data.rmsimg data = global_data.data_pix self.log.info("beam = {0:5.2f}'' x {1:5.2f}'' at {2:5.2f}deg".format( global_data.beam.a * 3600, global_data.beam.b * 3600, global_data.beam.pa)) # stop people from doing silly things. if outerclip > innerclip: outerclip = innerclip self.log.info("seedclip={0}".format(innerclip)) self.log.info("floodclip={0}".format(outerclip)) isle_num = 0 if cores == 1: # single-threaded, no parallel processing queue = [] else: queue = pprocess.Queue(limit=cores, reuse=1) fit_parallel = queue.manage(pprocess.MakeReusable(self._fit_islands)) island_group = [] group_size = 20 for i, xmin, xmax, ymin, ymax in self._gen_flood_wrap(data, rmsimg, innerclip, outerclip, domask=True): # ignore empty islands # This should now be impossible to trigger if np.size(i) < 1: self.log.warn("Empty island detected, this should be imposisble.") continue isle_num += 1 scalars = (innerclip, outerclip, max_summits) offsets = (xmin, xmax, ymin, ymax) island_data = IslandFittingData(isle_num, i, scalars, offsets, doislandflux) # If cores==1 run fitting in main process. Otherwise build up groups of islands # and submit to queue for subprocesses. Passing a group of islands is more # efficient than passing single islands to the subprocesses. if cores == 1: res = self._fit_island(island_data) queue.append(res) else: island_group.append(island_data) # If the island group is full queue it for the subprocesses to fit if len(island_group) >= group_size: fit_parallel(island_group) island_group = [] # The last partially-filled island group also needs to be queued for fitting if len(island_group) > 0: fit_parallel(island_group) # Write the output to the output file if outfile: print(header.format("{0}-({1})".format(__version__, __date__), filename), file=outfile) print(OutputSource.header, file=outfile) sources = [] for srcs in queue: if srcs: # ignore empty lists for src in srcs: # ignore sources that we have been told to ignore if (src.peak_flux > 0 and nopositive) or (src.peak_flux < 0 and nonegative): continue sources.append(src) if outfile: print(str(src), file=outfile) self.sources.extend(sources) return sources
Run the Aegean source finder. Parameters ---------- filename : str or HDUList Image filename or HDUList. hdu_index : int The index of the FITS HDU (extension). outfile : str file for printing catalog (NOT a table, just a text file of my own design) rms : float Use this rms for the entire image (will also assume that background is 0) max_summits : int Fit up to this many components to each island (extras are included but not fit) innerclip, outerclip : float The seed (inner) and flood (outer) clipping level (sigmas). cores : int Number of CPU cores to use. None means all cores. rmsin, bkgin : str or HDUList Filename or HDUList for the noise and background images. If either are None, then it will be calculated internally. beam : (major, minor, pa) Floats representing the synthesised beam (degrees). Replaces whatever is given in the FITS header. If the FITS header has no BMAJ/BMIN then this is required. doislandflux : bool If True then each island will also be characterized. nopositive, nonegative : bool Whether to return positive or negative sources. Default nopositive=False, nonegative=True. mask : str The filename of a region file created by MIMAS. Islands outside of this region will be ignored. lat : float The latitude of the telescope (declination of zenith). imgpsf : str or HDUList Filename or HDUList for a psf image. blank : bool Cause the output image to be blanked where islands are found. docov : bool If True then include covariance matrix in the fitting process. (default=True) cube_index : int For image cubes, cube_index determines which slice is used. Returns ------- sources : list List of sources found.
def add_data_point(self, x, y, size, number_format=None): """ Append a new BubbleDataPoint object having the values *x*, *y*, and *size*. The optional *number_format* is used to format the Y value. If not provided, the number format is inherited from the series data. """ data_point = BubbleDataPoint(self, x, y, size, number_format) self.append(data_point) return data_point
Append a new BubbleDataPoint object having the values *x*, *y*, and *size*. The optional *number_format* is used to format the Y value. If not provided, the number format is inherited from the series data.
def collect_tokens(cls, parseresult, mode): """ Collect the tokens from a (potentially) nested parse result. """ inner = '(%s)' if mode=='parens' else '[%s]' if parseresult is None: return [] tokens = [] for token in parseresult.asList(): # If value is a tuple, the token will be a list if isinstance(token, list): token = cls.recurse_token(token, inner) tokens[-1] = tokens[-1] + token else: if token.strip() == ',': continue tokens.append(cls._strip_commas(token)) return tokens
Collect the tokens from a (potentially) nested parse result.
def dump(self, path): """Saves the pushdb as a properties file to the given path.""" with open(path, 'w') as props: Properties.dump(self._props, props)
Saves the pushdb as a properties file to the given path.
def remove_list_members(self, screen_name=None, user_id=None, slug=None, list_id=None, owner_id=None, owner_screen_name=None): """ Perform bulk remove of list members from user ID or screenname """ return self._remove_list_members(list_to_csv(screen_name), list_to_csv(user_id), slug, list_id, owner_id, owner_screen_name)
Perform bulk remove of list members from user ID or screenname
def get_tags(instance_id=None, keyid=None, key=None, profile=None, region=None): ''' Given an instance_id, return a list of tags associated with that instance. returns (list) - list of tags as key/value pairs CLI Example: .. code-block:: bash salt myminion boto_ec2.get_tags instance_id ''' tags = [] client = _get_conn(key=key, keyid=keyid, profile=profile, region=region) result = client.get_all_tags(filters={"resource-id": instance_id}) if result: for tag in result: tags.append({tag.name: tag.value}) else: log.info("No tags found for instance_id %s", instance_id) return tags
Given an instance_id, return a list of tags associated with that instance. returns (list) - list of tags as key/value pairs CLI Example: .. code-block:: bash salt myminion boto_ec2.get_tags instance_id
def ToJson(self): """ Convert object members to a dictionary that can be parsed as JSON. Returns: dict: """ obj = { 'usage': self.Usage, 'data': '' if not self.Data else self.Data.hex() } return obj
Convert object members to a dictionary that can be parsed as JSON. Returns: dict:
def predict_proba(self, X): """Predict probabilities on test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- proba : array, shape = [n_samples, n_classes] The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`. """ if not hasattr(self, '_program'): raise NotFittedError('SymbolicClassifier not fitted.') X = check_array(X) _, n_features = X.shape if self.n_features_ != n_features: raise ValueError('Number of features of the model must match the ' 'input. Model n_features is %s and input ' 'n_features is %s.' % (self.n_features_, n_features)) scores = self._program.execute(X) proba = self._transformer(scores) proba = np.vstack([1 - proba, proba]).T return proba
Predict probabilities on test vectors X. Parameters ---------- X : array-like, shape = [n_samples, n_features] Input vectors, where n_samples is the number of samples and n_features is the number of features. Returns ------- proba : array, shape = [n_samples, n_classes] The class probabilities of the input samples. The order of the classes corresponds to that in the attribute `classes_`.
def add_arguments(self, parser): """Unpack self.arguments for parser.add_arguments.""" parser.add_argument('app_label', nargs='*') for argument in self.arguments: parser.add_argument(*argument.split(' '), **self.arguments[argument])
Unpack self.arguments for parser.add_arguments.
def build_access_service(did, price, consume_endpoint, service_endpoint, timeout, template_id): """ Build the access service. :param did: DID, str :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: ServiceAgreement """ # TODO fill all the possible mappings param_map = { '_documentId': did_to_id(did), '_amount': price, '_rewardAddress': Keeper.get_instance().escrow_reward_condition.address, } sla_template_path = get_sla_template_path() sla_template = ServiceAgreementTemplate.from_json_file(sla_template_path) sla_template.template_id = template_id conditions = sla_template.conditions[:] for cond in conditions: for param in cond.parameters: param.value = param_map.get(param.name, '') if cond.timeout > 0: cond.timeout = timeout sla_template.set_conditions(conditions) sa = ServiceAgreement( 1, sla_template, consume_endpoint, service_endpoint, ServiceTypes.ASSET_ACCESS ) sa.set_did(did) return sa
Build the access service. :param did: DID, str :param price: Asset price, int :param consume_endpoint: url of the service provider, str :param service_endpoint: identifier of the service inside the asset DDO, str :param timeout: amount of time in seconds before the agreement expires, int :param template_id: id of the template use to create the service, str :return: ServiceAgreement
def dict(self): """ Returns current collection as a dictionary """ collection = super().dict() serialized_items = [] for item in collection['items']: serialized_items.append(self.serializer(item)) collection['items'] = serialized_items return collection
Returns current collection as a dictionary
def file_link(self, instance): ''' Renders the link to the student upload file. ''' sfile = instance.file_upload if not sfile: return mark_safe('No file submitted by student.') else: return mark_safe('<a href="%s">%s</a><br/>(<a href="%s" target="_new">Preview</a>)' % (sfile.get_absolute_url(), sfile.basename(), sfile.get_preview_url()))
Renders the link to the student upload file.
def getfiles(self, path, ext=None, start=None, stop=None, recursive=False): """ Get scheme, bucket, and keys for a set of files """ from .utils import connection_with_anon, connection_with_gs parse = BotoClient.parse_query(path) scheme = parse[0] bucket_name = parse[1] if scheme == 's3' or scheme == 's3n': conn = connection_with_anon(self.credentials) bucket = conn.get_bucket(parse[1]) elif scheme == 'gs': conn = connection_with_gs(bucket_name) bucket = conn.get_bucket() else: raise NotImplementedError("No file reader implementation for URL scheme " + scheme) keys = BotoClient.retrieve_keys( bucket, parse[2], prefix=parse[3], postfix=parse[4], recursive=recursive) keylist = [key.name for key in keys] if ext: if ext == 'tif' or ext == 'tiff': keylist = [keyname for keyname in keylist if keyname.endswith('tif')] keylist.append([keyname for keyname in keylist if keyname.endswith('tiff')]) else: keylist = [keyname for keyname in keylist if keyname.endswith(ext)] keylist.sort() keylist = select(keylist, start, stop) return scheme, bucket.name, keylist
Get scheme, bucket, and keys for a set of files
def _free_up_space(self, size, this_rel_path=None): '''If there are not size bytes of space left, delete files until there is Args: size: size of the current file this_rel_path: rel_pat to the current file, so we don't delete it. ''' # Amount of space we are over ( bytes ) for next put space = self.size + size - self.maxsize if space <= 0: return removes = [] for row in self.database.execute("SELECT path, size, time FROM files ORDER BY time ASC"): if space > 0: removes.append(row[0]) space -= row[1] else: break for rel_path in removes: if rel_path != this_rel_path: global_logger.debug("Deleting {}".format(rel_path)) self.remove(rel_path)
If there are not size bytes of space left, delete files until there is Args: size: size of the current file this_rel_path: rel_pat to the current file, so we don't delete it.
def close(self): """This method closes the database correctly.""" if self.filepath is not None: if path.isfile(self.filepath+'.lock'): remove(self.filepath+'.lock') self.filepath = None self.read_only = False self.lock() return True else: raise KPError('Can\'t close a not opened file')
This method closes the database correctly.
def datasets_list(self, project_id=None, max_results=0, page_token=None): """Issues a request to list the datasets in the project. Args: project_id: the project id to use to fetch the results; use None for the default project. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retrieval. Returns: A parsed result object. Raises: Exception if there is an error performing the operation. """ if project_id is None: project_id = self._project_id url = Api._ENDPOINT + (Api._DATASETS_PATH % (project_id, '')) args = {} if max_results != 0: args['maxResults'] = max_results if page_token is not None: args['pageToken'] = page_token return datalab.utils.Http.request(url, args=args, credentials=self._credentials)
Issues a request to list the datasets in the project. Args: project_id: the project id to use to fetch the results; use None for the default project. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retrieval. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def intersect(self, enumerable, key=lambda x: x): """ Returns enumerable that is the intersection between given enumerable and self :param enumerable: enumerable object :param key: key selector as lambda expression :return: new Enumerable object """ if not isinstance(enumerable, Enumerable3): raise TypeError( u"enumerable parameter must be an instance of Enumerable") return self.join(enumerable, key, key).select(lambda x: x[0])
Returns enumerable that is the intersection between given enumerable and self :param enumerable: enumerable object :param key: key selector as lambda expression :return: new Enumerable object
def launch(self, args, unknown): """Launch something according to the provided arguments :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: SystemExit """ pm = plugins.PluginManager.get() addon = pm.get_plugin(args.addon) isgui = isinstance(addon, plugins.JB_StandaloneGuiPlugin) if isgui: gui.main.init_gui() print "Launching %s..." % args.addon addon.run() if isgui: app = gui.main.get_qapp() sys.exit(app.exec_())
Launch something according to the provided arguments :param args: arguments from the launch parser :type args: Namespace :param unknown: list of unknown arguments :type unknown: list :returns: None :rtype: None :raises: SystemExit
def start(users, hosts, func, only_authenticate=False, **kwargs): """ Like run(), but automatically logs into the host before passing the host to the callback function. :type users: Account|list[Account] :param users: The account(s) to use for logging in. :type hosts: Host|list[Host] :param hosts: A list of Host objects. :type func: function :param func: The callback function. :type only_authenticate: bool :param only_authenticate: don't authorize, just authenticate? :type kwargs: dict :param kwargs: Passed to the Exscript.Queue constructor. """ if only_authenticate: run(users, hosts, autoauthenticate()(func), **kwargs) else: run(users, hosts, autologin()(func), **kwargs)
Like run(), but automatically logs into the host before passing the host to the callback function. :type users: Account|list[Account] :param users: The account(s) to use for logging in. :type hosts: Host|list[Host] :param hosts: A list of Host objects. :type func: function :param func: The callback function. :type only_authenticate: bool :param only_authenticate: don't authorize, just authenticate? :type kwargs: dict :param kwargs: Passed to the Exscript.Queue constructor.
def minmax_auto_scale(img, as_uint16): """ Utility function for rescaling all pixel values of input image to fit the range of uint8. Rescaling method is min-max, which is all pixel values are normalized to [0, 1] by using img.min() and img.max() and then are scaled up by 255 times. If the argument `as_uint16` is True, output image dtype is np.uint16 and the range of pixel values is [0, 65535] (scaled up by 65535 after normalized to [0, 1]). :param img (numpy.ndarray): input image. :param as_uint16: If True, output image dtype is uint16. :return: numpy.ndarray """ if as_uint16: output_high = 65535 output_type = np.uint16 else: output_high = 255 output_type = np.uint8 return rescale_pixel_intensity(img, input_low=img.min(), input_high=img.max(), output_low=0, output_high=output_high, output_type=output_type)
Utility function for rescaling all pixel values of input image to fit the range of uint8. Rescaling method is min-max, which is all pixel values are normalized to [0, 1] by using img.min() and img.max() and then are scaled up by 255 times. If the argument `as_uint16` is True, output image dtype is np.uint16 and the range of pixel values is [0, 65535] (scaled up by 65535 after normalized to [0, 1]). :param img (numpy.ndarray): input image. :param as_uint16: If True, output image dtype is uint16. :return: numpy.ndarray
def recent_all_projects(self, limit=30, offset=0): """Return information about recent builds across all projects. Args: limit (int), Number of builds to return, max=100, defaults=30. offset (int): Builds returned from this point, default=0. Returns: A list of dictionaries. """ method = 'GET' url = ('/recent-builds?circle-token={token}&limit={limit}&' 'offset={offset}'.format(token=self.client.api_token, limit=limit, offset=offset)) json_data = self.client.request(method, url) return json_data
Return information about recent builds across all projects. Args: limit (int), Number of builds to return, max=100, defaults=30. offset (int): Builds returned from this point, default=0. Returns: A list of dictionaries.
def convert_datetime_array(array): ''' Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array ''' if not isinstance(array, np.ndarray): return array try: dt2001 = np.datetime64('2001') legacy_datetime64 = (dt2001.astype('int64') == dt2001.astype('datetime64[ms]').astype('int64')) except AttributeError as e: if e.args == ("'module' object has no attribute 'datetime64'",): # for compatibility with PyPy that doesn't have datetime64 if 'PyPy' in sys.version: legacy_datetime64 = False pass else: raise e else: raise e # not quite correct, truncates to ms.. if array.dtype.kind == 'M': if legacy_datetime64: if array.dtype == np.dtype('datetime64[ns]'): array = array.astype('int64') / 10**6.0 else: array = array.astype('datetime64[us]').astype('int64') / 1000. elif array.dtype.kind == 'm': array = array.astype('timedelta64[us]').astype('int64') / 1000. return array
Convert NumPy datetime arrays to arrays to milliseconds since epoch. Args: array : (obj) A NumPy array of datetime to convert If the value passed in is not a NumPy array, it will be returned as-is. Returns: array
def download_file_with_progress_bar(url): """Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object """ request = requests.get(url, stream=True) if request.status_code == 404: msg = ('there was a 404 error trying to reach {} \nThis probably ' 'means the requested version does not exist.'.format(url)) logger.error(msg) sys.exit() total_size = int(request.headers["Content-Length"]) chunk_size = 1024 bars = int(total_size / chunk_size) bytes_io = io.BytesIO() pbar = tqdm(request.iter_content(chunk_size=chunk_size), total=bars, unit="kb", leave=False) for chunk in pbar: bytes_io.write(chunk) return bytes_io
Downloads a file from the given url, displays a progress bar. Returns a io.BytesIO object
def as_parameter(nullable=True, strict=True): """ Decorate a container class as a functional :class:`Parameter` class for a :class:`ParametricObject`. :param nullable: if set, parameter's value may be Null :type nullable: :class:`bool` .. doctest:: >>> from cqparts.params import as_parameter, ParametricObject >>> @as_parameter(nullable=True) ... class Stuff(object): ... def __init__(self, a=1, b=2, c=3): ... self.a = a ... self.b = b ... self.c = c ... @property ... def abc(self): ... return (self.a, self.b, self.c) >>> class Thing(ParametricObject): ... foo = Stuff({'a': 10, 'b': 100}, doc="controls stuff") >>> thing = Thing(foo={'a': 20}) >>> thing.foo.a 20 >>> thing.foo.abc (20, 2, 3) """ def decorator(cls): base_class = Parameter if nullable else NonNullParameter return type(cls.__name__, (base_class,), { # Preserve text for documentation '__name__': cls.__name__, '__doc__': cls.__doc__, '__module__': cls.__module__, # Sphinx doc type string '_doc_type': ":class:`{class_name} <{module}.{class_name}>`".format( class_name=cls.__name__, module=__name__ ), # 'type': lambda self, value: cls(**value) }) return decorator
Decorate a container class as a functional :class:`Parameter` class for a :class:`ParametricObject`. :param nullable: if set, parameter's value may be Null :type nullable: :class:`bool` .. doctest:: >>> from cqparts.params import as_parameter, ParametricObject >>> @as_parameter(nullable=True) ... class Stuff(object): ... def __init__(self, a=1, b=2, c=3): ... self.a = a ... self.b = b ... self.c = c ... @property ... def abc(self): ... return (self.a, self.b, self.c) >>> class Thing(ParametricObject): ... foo = Stuff({'a': 10, 'b': 100}, doc="controls stuff") >>> thing = Thing(foo={'a': 20}) >>> thing.foo.a 20 >>> thing.foo.abc (20, 2, 3)
def ekacld(handle, segno, column, dvals, entszs, nlflgs, rcptrs, wkindx): """ Add an entire double precision column to an EK segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html :param handle: EK file handle. :type handle: int :param segno: Number of segment to add column to. :type segno: int :param column: Column name. :type column: str :param dvals: Double precision values to add to column. :type dvals: Array of floats :param entszs: Array of sizes of column entries. :type entszs: Array of ints :param nlflgs: Array of null flags for column entries. :type nlflgs: Array of bools :param rcptrs: Record pointers for segment. :type rcptrs: Array of ints :param wkindx: Work space for column index. :type wkindx: Array of ints :return: Work space for column index. :rtype: Array of ints """ handle = ctypes.c_int(handle) segno = ctypes.c_int(segno) column = stypes.stringToCharP(column) dvals = stypes.toDoubleVector(dvals) entszs = stypes.toIntVector(entszs) nlflgs = stypes.toIntVector(nlflgs) rcptrs = stypes.toIntVector(rcptrs) wkindx = stypes.toIntVector(wkindx) libspice.ekacld_c(handle, segno, column, dvals, entszs, nlflgs, rcptrs, wkindx) return stypes.cVectorToPython(wkindx)
Add an entire double precision column to an EK segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekacld_c.html :param handle: EK file handle. :type handle: int :param segno: Number of segment to add column to. :type segno: int :param column: Column name. :type column: str :param dvals: Double precision values to add to column. :type dvals: Array of floats :param entszs: Array of sizes of column entries. :type entszs: Array of ints :param nlflgs: Array of null flags for column entries. :type nlflgs: Array of bools :param rcptrs: Record pointers for segment. :type rcptrs: Array of ints :param wkindx: Work space for column index. :type wkindx: Array of ints :return: Work space for column index. :rtype: Array of ints
def BGPNeighborPrefixExceeded_originator_switch_info_switchIpV6Address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") BGPNeighborPrefixExceeded = ET.SubElement(config, "BGPNeighborPrefixExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") originator_switch_info = ET.SubElement(BGPNeighborPrefixExceeded, "originator-switch-info") switchIpV6Address = ET.SubElement(originator_switch_info, "switchIpV6Address") switchIpV6Address.text = kwargs.pop('switchIpV6Address') callback = kwargs.pop('callback', self._callback) return callback(config)
Auto Generated Code
def getAutoServiceLevelEnabled(self): """Returns True if enabled, False if disabled""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) return not (flags & 0x0020)
Returns True if enabled, False if disabled
def get_diff(value1, value2, name1, name2): """Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff. """ lines1 = [line + "\n" for line in value1.splitlines()] lines2 = [line + "\n" for line in value2.splitlines()] diff_lines = difflib.context_diff( lines1, lines2, fromfile=name1, tofile=name2 ) return "".join(diff_lines)
Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff.
def use_sequestered_composition_view(self): """Pass through to provider CompositionLookupSession.use_sequestered_composition_view""" self._containable_views['composition'] = SEQUESTERED # self._get_provider_session('composition_lookup_session') # To make sure the session is tracked for session in self._get_provider_sessions(): try: session.use_sequestered_composition_view() except AttributeError: pass
Pass through to provider CompositionLookupSession.use_sequestered_composition_view
def setDictionary(self, data): """ Overwrites the entire dictionary """ # Create the directory containing the JSON file if it doesn't already exist jsonDir = os.path.dirname(self.jsonFile) if os.path.exists(jsonDir) == False: os.makedirs(jsonDir) # Store the dictionary Utility.writeFile(self.jsonFile, json.dumps(data))
Overwrites the entire dictionary
def scan_threads(self): """ Populates the snapshot with running threads. """ # Ignore special process IDs. # PID 0: System Idle Process. Also has a special meaning to the # toolhelp APIs (current process). # PID 4: System Integrity Group. See this forum post for more info: # http://tinyurl.com/ycza8jo # (points to social.technet.microsoft.com) # Only on XP and above # PID 8: System (?) only in Windows 2000 and below AFAIK. # It's probably the same as PID 4 in XP and above. dwProcessId = self.get_pid() if dwProcessId in (0, 4, 8): return ## dead_tids = set( self.get_thread_ids() ) # XXX triggers a scan dead_tids = self._get_thread_ids() dwProcessId = self.get_pid() hSnapshot = win32.CreateToolhelp32Snapshot(win32.TH32CS_SNAPTHREAD, dwProcessId) try: te = win32.Thread32First(hSnapshot) while te is not None: if te.th32OwnerProcessID == dwProcessId: dwThreadId = te.th32ThreadID if dwThreadId in dead_tids: dead_tids.remove(dwThreadId) ## if not self.has_thread(dwThreadId): # XXX triggers a scan if not self._has_thread_id(dwThreadId): aThread = Thread(dwThreadId, process = self) self._add_thread(aThread) te = win32.Thread32Next(hSnapshot) finally: win32.CloseHandle(hSnapshot) for tid in dead_tids: self._del_thread(tid)
Populates the snapshot with running threads.
def add_client(self, client_identifier): """Add a client.""" if client_identifier in self.clients: _LOGGER.error('%s already in group %s', client_identifier, self.identifier) return new_clients = self.clients new_clients.append(client_identifier) yield from self._server.group_clients(self.identifier, new_clients) _LOGGER.info('added %s to %s', client_identifier, self.identifier) self._server.client(client_identifier).callback() self.callback()
Add a client.
def get_report_raw(year, report_type): """Download and extract a CO-TRACER report. Generate a URL for the given report, download the corresponding archive, extract the CSV report, and interpret it using the standard CSV library. @param year: The year for which data should be downloaded. @type year: int @param report_type: The type of report that should be downloaded. Should be one of the strings in constants.REPORT_TYPES. @type report_type: str @return: A DictReader with the loaded data. Note that this data has not been interpreted so data fields like floating point values, dates, and boolean values are still strings. @rtype: csv.DictReader """ if not is_valid_report_type(report_type): msg = '%s is not a valid report type.' % report_type raise ValueError(msg) url = get_url(year, report_type) raw_contents = get_zipped_file(url) return csv.DictReader(cStringIO.StringIO(raw_contents))
Download and extract a CO-TRACER report. Generate a URL for the given report, download the corresponding archive, extract the CSV report, and interpret it using the standard CSV library. @param year: The year for which data should be downloaded. @type year: int @param report_type: The type of report that should be downloaded. Should be one of the strings in constants.REPORT_TYPES. @type report_type: str @return: A DictReader with the loaded data. Note that this data has not been interpreted so data fields like floating point values, dates, and boolean values are still strings. @rtype: csv.DictReader