code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
async def _async_request_soup(url): ''' Perform a GET web request and return a bs4 parser ''' from bs4 import BeautifulSoup import aiohttp _LOGGER.debug('GET %s', url) async with aiohttp.ClientSession() as session: resp = await session.get(url) text = await resp.text() ...
Perform a GET web request and return a bs4 parser
def add_data_point(self, x, y, number_format=None): """ Return an XyDataPoint object newly created with values *x* and *y*, and appended to this sequence. """ data_point = XyDataPoint(self, x, y, number_format) self.append(data_point) return data_point
Return an XyDataPoint object newly created with values *x* and *y*, and appended to this sequence.
def name(cls): """Return the preferred name as which this command will be known.""" name = cls.__name__.replace("_", "-").lower() name = name[4:] if name.startswith("cmd-") else name return name
Return the preferred name as which this command will be known.
def decode(self, packet): ''' Decode a UNSUBACK control packet. ''' self.encoded = packet lenLen = 1 while packet[lenLen] & 0x80: lenLen += 1 packet_remaining = packet[lenLen+1:] self.msgId = decode16Int(packet_remaining[0:2]) self.t...
Decode a UNSUBACK control packet.
def fromfile(fname): """Open SVG figure from file. Parameters ---------- fname : str name of the SVG file Returns ------- SVGFigure newly created :py:class:`SVGFigure` initialised with the file content """ fig = SVGFigure() with open(fname) as fid: svg_f...
Open SVG figure from file. Parameters ---------- fname : str name of the SVG file Returns ------- SVGFigure newly created :py:class:`SVGFigure` initialised with the file content
def iter_used_addresses( adapter, # type: BaseAdapter seed, # type: Seed start, # type: int security_level=None, # type: Optional[int] ): # type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, None] """ Scans the Tangle for used addresses. This is ba...
Scans the Tangle for used addresses. This is basically the opposite of invoking ``getNewAddresses`` with ``stop=None``.
def instantiate_labels(instructions): """ Takes an iterable of instructions which may contain label placeholders and assigns them all defined values. :return: list of instructions with all label placeholders assigned to real labels. """ label_i = 1 result = [] label_mapping = dict() ...
Takes an iterable of instructions which may contain label placeholders and assigns them all defined values. :return: list of instructions with all label placeholders assigned to real labels.
def captures(self, uuid, withTitles=False): """Return the captures for a given uuid optional value withTitles=yes""" picker = lambda x: x.get('capture', []) return self._get((uuid,), picker, withTitles='yes' if withTitles else 'no')
Return the captures for a given uuid optional value withTitles=yes
def get_version(filename, version='1.00'): ''' Read version as text to avoid machinations at import time. ''' with open(filename) as infile: for line in infile: if line.startswith('__version__'): try: version = line.split("'")[1] except Ind...
Read version as text to avoid machinations at import time.
def delete(self, config_file=None): """Deletes the credentials file specified in `config_file`. If no file is specified, it deletes the default user credential file. Args: config_file (str): Path to configuration file. Defaults to delete the user default location if ...
Deletes the credentials file specified in `config_file`. If no file is specified, it deletes the default user credential file. Args: config_file (str): Path to configuration file. Defaults to delete the user default location if `None`. .. Tip:: To see i...
def visit_starred(self, node, parent): """visit a Starred node and return a new instance of it""" context = self._get_context(node) newnode = nodes.Starred( ctx=context, lineno=node.lineno, col_offset=node.col_offset, parent=parent ) newnode.postinit(self.visit(node.v...
visit a Starred node and return a new instance of it
def get_features_from_equation_file(filename): """ returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature ...
returns list of feature names read from equation file given by ``filename``. format: one feature per line; comments start with ``#`` Example:: #this is a comment basefeature #empty lines are ignored myfeature anotherfeature :param filename: :return:
def assign_indent_numbers(lst, inum, dic=collections.defaultdict(int)): """ Associate keywords with their respective indentation numbers """ for i in lst: dic[i] = inum return dic
Associate keywords with their respective indentation numbers
def plain(self, markup): """ Strips Wikipedia markup from given text. This creates a "plain" version of the markup, stripping images and references and the like. Does some commonsense maintenance as well, like collapsing multiple spaces. If you specified...
Strips Wikipedia markup from given text. This creates a "plain" version of the markup, stripping images and references and the like. Does some commonsense maintenance as well, like collapsing multiple spaces. If you specified full_strip=False for WikipediaPage instance, ...
def get_std_xy_dataset_statistics(x_values, y_values, expect_negative_correlation = False, STDev_cutoff = 1.0): '''Calls parse_csv and returns the analysis in a format similar to get_xy_dataset_statistics in klab.stats.misc.''' assert(len(x_values) == len(y_values)) csv_lines = ['ID,X,Y'] + [','.join(map(st...
Calls parse_csv and returns the analysis in a format similar to get_xy_dataset_statistics in klab.stats.misc.
def __parse_entry(entry_line): """Parse the SOFT file entry name line that starts with '^', '!' or '#'. Args: entry_line (:obj:`str`): Line from SOFT to be parsed. Returns: :obj:`2-tuple`: Type of entry, value of entry. """ if entry_line.startswith("!"): entry_line = sub(...
Parse the SOFT file entry name line that starts with '^', '!' or '#'. Args: entry_line (:obj:`str`): Line from SOFT to be parsed. Returns: :obj:`2-tuple`: Type of entry, value of entry.
def create_application(self, description=None): """ Creats an application and sets the helpers current app_name to the created application """ out("Creating application " + str(self.app_name)) self.ebs.create_application(self.app_name, description=description)
Creats an application and sets the helpers current app_name to the created application
def getJSMinimumVolume(self, **kw): """Try convert the MinimumVolume to 'ml' or 'g' so that JS has an easier time working with it. If conversion fails, return raw value. """ default = self.Schema()['MinimumVolume'].get(self) try: mgdefault = default.split(' ', 1) ...
Try convert the MinimumVolume to 'ml' or 'g' so that JS has an easier time working with it. If conversion fails, return raw value.
def whitelist(ctx, whitelist_account, account): """ Add an account to a whitelist """ account = Account(account, blockchain_instance=ctx.blockchain) print_tx(account.whitelist(whitelist_account))
Add an account to a whitelist
def resume_job(job_id): """Resumes a job.""" try: current_app.apscheduler.resume_job(job_id) job = current_app.apscheduler.get_job(job_id) return jsonify(job) except JobLookupError: return jsonify(dict(error_message='Job %s not found' % job_id), status=404) except Except...
Resumes a job.
def watch(self, limit=None, timeout=None): """Block method to watch the clipboard changing.""" start_time = time.time() count = 0 while not timeout or time.time() - start_time < timeout: new = self.read() if new != self.temp: count += 1 ...
Block method to watch the clipboard changing.
def trySwitchStatement(self, block): """Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found. """ if not re.match(r'^\s*(default\s*|case\b.*):', block.text()): ...
Check for default and case keywords and assume we are in a switch statement. Try to find a previous default, case or switch and return its indentation or None if not found.
def dumpJSON(self): """ Encodes current parameters to JSON compatible dictionary """ numexp = self.number.get() expTime, _, _, _, _ = self.timing() if numexp == 0: numexp = -1 data = dict( numexp=self.number.value(), app=self.a...
Encodes current parameters to JSON compatible dictionary
def load_module_from_file_object(fp, filename='<unknown>', code_objects=None, fast_load=False, get_code=True): """load a module from a file object without importing it. See :func:load_module for a list of return values. """ if code_objects is None: code_objects = {} timest...
load a module from a file object without importing it. See :func:load_module for a list of return values.
def age(self): """ Get closer to your EOL """ # 0 means this composer will never decompose if self.rounds == 1: self.do_run = False elif self.rounds > 1: self.rounds -= 1
Get closer to your EOL
def proton_hydroxide_free_energy(temperature, pressure, pH): """Returns the Gibbs free energy of proton in bulk solution. Parameters ---------- pH : pH of bulk solution temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_...
Returns the Gibbs free energy of proton in bulk solution. Parameters ---------- pH : pH of bulk solution temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_OH : Gibbs free energy of proton and hydroxide.
def get_state_data(cls, entity): """ Returns the state data for the given entity. This also works for unmanaged entities. """ attrs = get_domain_class_attribute_iterator(type(entity)) return dict([(attr, get_nested_attribute(entity, attr.entity_attr...
Returns the state data for the given entity. This also works for unmanaged entities.
def parse(self, text, **kwargs): '''Parse the given text and return result from MeCab. :param text: the text to parse. :type text: str :param as_nodes: return generator of MeCabNodes if True; or string if False. :type as_nodes: bool, defaults to False :param ...
Parse the given text and return result from MeCab. :param text: the text to parse. :type text: str :param as_nodes: return generator of MeCabNodes if True; or string if False. :type as_nodes: bool, defaults to False :param boundary_constraints: regular expression for...
def stat( self, *args ): '''Check process completion and consume pending I/O data''' self.pipe.poll() if not self.pipe.returncode is None: '''cleanup handlers and timeouts''' if not self.expiration is None: self.ioloop.remove_timeout(self.expiration) ...
Check process completion and consume pending I/O data
def first(self, callback=None, default=None): """ Get the first item of the collection. :param default: The default value :type default: mixed """ if callback is not None: for val in self.items: if callback(val): return val...
Get the first item of the collection. :param default: The default value :type default: mixed
def unzip(zipped_file, output_directory=None, prefix="harvestingkit_unzip_", suffix=""): """Uncompress a zipped file from given filepath to an (optional) location. If no location is given, a temporary folder will be generated inside CFG_TMPDIR, prefixed with "apsharvest_unzip_". """ if no...
Uncompress a zipped file from given filepath to an (optional) location. If no location is given, a temporary folder will be generated inside CFG_TMPDIR, prefixed with "apsharvest_unzip_".
def pair(self): """ Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has ...
Returns a callable and an iterable respectively. Those can be used to both transmit a message and/or iterate over incoming messages, that were sent by a pair socket. Note that the iterable returns as many parts as sent by a pair. Also, the sender function has a ``print`` like signature, ...
def _adjust_router_list_for_global_router(self, routers): """ Pushes 'Global' routers to the end of the router list, so that deleting default route occurs before deletion of external nw subintf """ #ToDo(Hareesh): Simplify if possible for r in routers: if r[RO...
Pushes 'Global' routers to the end of the router list, so that deleting default route occurs before deletion of external nw subintf
def _run_eos_cmds(self, commands, switch): """Execute/sends a CAPI (Command API) command to EOS. This method is useful for running show commands that require no prefix or postfix commands. :param commands : List of commands to be executed on EOS. :param switch: Endpoint on the ...
Execute/sends a CAPI (Command API) command to EOS. This method is useful for running show commands that require no prefix or postfix commands. :param commands : List of commands to be executed on EOS. :param switch: Endpoint on the Arista switch to be configured
def save(self, **kwargs): """Overrides models.Model.save. - Delete formatted photos if format save and not now created (because of possible changes) """ if self.id: for f_photo in self.formatedphoto_set.all(): f_photo.delete() super(Format...
Overrides models.Model.save. - Delete formatted photos if format save and not now created (because of possible changes)
def _ParseFSMVariables(self, template): """Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the to...
Extracts Variables from start of template file. Values are expected as a contiguous block at the head of the file. These will be line separated from the State definitions that follow. Args: template: Valid template file, with Value definitions at the top. Raises: TextFSMTemplateError: If ...
def instruction_RTI(self, opcode): """ The saved machine state is recovered from the hardware stack and control is returned to the interrupted program. If the recovered E (entire) bit is clear, it indicates that only a subset of the machine state was saved (return address and con...
The saved machine state is recovered from the hardware stack and control is returned to the interrupted program. If the recovered E (entire) bit is clear, it indicates that only a subset of the machine state was saved (return address and condition codes) and only that subset is recovered. ...
def make_python_identifier(string, namespace=None, reserved_words=None, convert='drop', handle='force'): """ Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is alread...
Takes an arbitrary string and creates a valid Python identifier. If the input string is in the namespace, return its value. If the python identifier created is already in the namespace, but the input string is not (ie, two similar strings resolve to the same python identifier) or if the identifie...
def create_repository(self, repository_form=None): """Creates a new ``Repository``. :param repository_form: the form for this ``Repository`` :type repository_form: ``osid.repository.RepositoryForm`` :return: the new ``Repository`` :rtype: ``osid.repository.Repository`` :...
Creates a new ``Repository``. :param repository_form: the form for this ``Repository`` :type repository_form: ``osid.repository.RepositoryForm`` :return: the new ``Repository`` :rtype: ``osid.repository.Repository`` :raise: ``IllegalState`` -- ``repository_form`` already used in...
def print_file(self, f=sys.stdout, file_format="cif", tw=0): """Print :class:`~nmrstarlib.nmrstarlib.CIFFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `cif` or `json`. :param int tw: Tab width. :return: None ...
Print :class:`~nmrstarlib.nmrstarlib.CIFFile` into a file or stdout. :param io.StringIO f: writable file-like stream. :param str file_format: Format to use: `cif` or `json`. :param int tw: Tab width. :return: None :rtype: :py:obj:`None`
def intersperse(e, iterable, n=1): """Intersperse filler element *e* among the items in *iterable*, leaving *n* items between each filler element. >>> list(intersperse('!', [1, 2, 3, 4, 5])) [1, '!', 2, '!', 3, '!', 4, '!', 5] >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) [...
Intersperse filler element *e* among the items in *iterable*, leaving *n* items between each filler element. >>> list(intersperse('!', [1, 2, 3, 4, 5])) [1, '!', 2, '!', 3, '!', 4, '!', 5] >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) [1, 2, None, 3, 4, None, 5]
def can_use_cached_output(self, contentitem): """ Tell whether the code should try reading cached output """ plugin = contentitem.plugin return appsettings.FLUENT_CONTENTS_CACHE_OUTPUT and plugin.cache_output and contentitem.pk
Tell whether the code should try reading cached output
def unsafe(self): """True if the mapping is unsafe for an update. Applies only to local source. Returns True if the paths for source and destination are the same, or if one is a component of the other path. """ (scheme, netloc, path, params, query, frag) = urlparse(self.src_uri)...
True if the mapping is unsafe for an update. Applies only to local source. Returns True if the paths for source and destination are the same, or if one is a component of the other path.
def authenticate(self, request): """ Authenticate a client against all the backends configured in :attr:`authentication`. """ for backend in self.authentication: client = backend().authenticate(request) if client is not None: return client ...
Authenticate a client against all the backends configured in :attr:`authentication`.
def augment_initial_layout(self, base_response, initial_arguments=None): 'Add application state to initial values' if self.use_dash_layout() and not initial_arguments and False: return base_response.data, base_response.mimetype # Adjust the base layout response baseDataInByt...
Add application state to initial values
def parse_non_selinux(parts): """ Parse part of an ls output line that isn't selinux. Args: parts (list): A four element list of strings representing the initial parts of an ls line after the permission bits. The parts are link count, owner, group, and everything else. ...
Parse part of an ls output line that isn't selinux. Args: parts (list): A four element list of strings representing the initial parts of an ls line after the permission bits. The parts are link count, owner, group, and everything else. Returns: A dict containing links, ...
def _vis_calibrate(self, data): """Calibrate visible channels to reflectance.""" solar_irradiance = self['esun'] esd = self["earth_sun_distance_anomaly_in_AU"].astype(float) factor = np.pi * esd * esd / solar_irradiance res = data * factor res.attrs = data.attrs ...
Calibrate visible channels to reflectance.
def WriteEventBody(self, event): """Writes the body of an event object to the spreadsheet. Args: event (EventObject): event. """ for field_name in self._fields: if field_name == 'datetime': output_value = self._FormatDateTime(event) else: output_value = self._dynamic_f...
Writes the body of an event object to the spreadsheet. Args: event (EventObject): event.
def _handle_watch_message(self, message): """ Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes """ if self.log_protocol_level is not No...
Processes a binary message received from the watch and broadcasts the relevant events. :param message: A raw message from the watch, without any transport framing. :type message: bytes
def check_for_maintenance(self): ''' Returns True if the maintenance worker should be run now, and False otherwise. :return: ''' numrevs = self.conn.get_one("SELECT count(revnum) FROM csetLog")[0] if numrevs >= SIGNAL_MAINTENACE_CSETS: return True ...
Returns True if the maintenance worker should be run now, and False otherwise. :return:
def df_quantile(df, nb=100): """Returns the nb quantiles for datas in a dataframe """ quantiles = np.linspace(0, 1., nb) res = pd.DataFrame() for q in quantiles: res = res.append(df.quantile(q), ignore_index=True) return res
Returns the nb quantiles for datas in a dataframe
def _get_base_class_names(frame): """ Get baseclass names from the code object """ co, lasti = frame.f_code, frame.f_lasti code = co.co_code extends = [] for (op, oparg) in op_stream(code, lasti): if op in dis.hasconst: if type(co.co_consts[oparg]) == str: extend...
Get baseclass names from the code object
def palettize(self, colormap): """Palettize the current image using `colormap`. .. note:: Works only on "L" or "LA" images. """ if self.mode not in ("L", "LA"): raise ValueError("Image should be grayscale to colorize") l_data = self.data.sel(bands=['L...
Palettize the current image using `colormap`. .. note:: Works only on "L" or "LA" images.
def off_policy_train_batch(self, batch_info: BatchInfo): """ Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """ self.model.train() rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device) ba...
Perform an 'off-policy' training step of sampling the replay buffer and gradient descent
def POST(self, id): """ Delete based on ID """ id = int(id) model.del_todo(id) raise web.seeother('/')
Delete based on ID
def main(): """This is the CLI driver for ia-wrapper.""" args = docopt(__doc__, version=__version__, options_first=True) # Validate args. s = Schema({ six.text_type: bool, '--config-file': Or(None, str), '<args>': list, '<command>': Or(str, lambda _: 'help'), }) ...
This is the CLI driver for ia-wrapper.
def get_default_config(self): """ Returns the default collector settings """ config = super(ElasticSearchCollector, self).get_default_config() config.update({ 'host': '127.0.0.1', 'port': 9200, 'user': '', ...
Returns the default collector settings
def unmarshal( compoundSignature, data, offset = 0, lendian = True ): """ Unmarshals DBus encoded data. @type compoundSignature: C{string} @param compoundSignature: DBus signature specifying the encoded value types @type data: C{string} @param data: Binary data @type offset: C{int} @p...
Unmarshals DBus encoded data. @type compoundSignature: C{string} @param compoundSignature: DBus signature specifying the encoded value types @type data: C{string} @param data: Binary data @type offset: C{int} @param offset: Offset within data at which data for compoundSignature ...
def aq_esc_telemetry_encode(self, time_boot_ms, seq, num_motors, num_in_seq, escid, status_age, data_version, data0, data1): ''' Sends ESC32 telemetry data for up to 4 motors. Multiple messages may be sent in sequence when system has > 4 motors. Data is de...
Sends ESC32 telemetry data for up to 4 motors. Multiple messages may be sent in sequence when system has > 4 motors. Data is described as follows: // unsigned int state : 3; // unsigned int vin : 12; // x 100 // unsigned int amps...
def _parse_msg(client, command, actor, args): """Parse a PRIVMSG or NOTICE and dispatch the corresponding event.""" recipient, _, message = args.partition(' :') chantypes = client.server.features.get("CHANTYPES", "#") if recipient[0] in chantypes: recipient = client.server.get_channel(recipient)...
Parse a PRIVMSG or NOTICE and dispatch the corresponding event.
def subscribe(self, queue=None, *levels): """ Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes logs. Always use the returned queue name from this method, even if u specified the queue name to use Note: it is legal to subscribe to ...
Subscribe to the aggregated log stream. On subscribe a ledis queue will be fed with all running processes logs. Always use the returned queue name from this method, even if u specified the queue name to use Note: it is legal to subscribe to the same queue, but would be a bad logic if two processes are ...
def _add_observation(self, x_to_add, y_to_add): """Add observation to window, updating means/variance efficiently.""" self._add_observation_to_means(x_to_add, y_to_add) self._add_observation_to_variances(x_to_add, y_to_add) self.window_size += 1
Add observation to window, updating means/variance efficiently.
def lyricsmode(song): """ Returns the lyrics found in lyricsmode.com for the specified mp3 file or an empty string if not found. """ translate = { URLESCAPE: '', ' ': '_' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() ...
Returns the lyrics found in lyricsmode.com for the specified mp3 file or an empty string if not found.
def SendKeys(keys, pause=0.05, with_spaces=False, with_tabs=False, with_newlines=False, turn_off_numlock=True): "Parse the keys and type them" keys = parse_keys(keys, with_spaces, with_tabs, with_newlines) for k in keys: k.Run() ...
Parse the keys and type them
def _detach_dim_scale(self, name): """Detach the dimension scale corresponding to a dimension name.""" for var in self.variables.values(): for n, dim in enumerate(var.dimensions): if dim == name: var._h5ds.dims[n].detach_scale(self._all_h5groups[dim]) ...
Detach the dimension scale corresponding to a dimension name.
def options(self): """ Returns the options specified as argument to this command. """ if self._option_view is None: self._option_view = Option.View(self) return self._option_view
Returns the options specified as argument to this command.
def all_points_mutual_reachability(X, labels, cluster_id, metric='euclidean', d=None, **kwd_args): """ Compute the all-points-mutual-reachability distances for all the points of a cluster. If metric is 'precomputed' then assume X is a distance matrix for the full ...
Compute the all-points-mutual-reachability distances for all the points of a cluster. If metric is 'precomputed' then assume X is a distance matrix for the full dataset. Note that in this case you must pass in 'd' the dimension of the dataset. Parameters ---------- X : array (n_samples, n_...
def get_node(self, index): """ Returns the Node at given index. :param index: Index. :type index: QModelIndex :return: Node. :rtype: AbstractCompositeNode """ index = self.mapToSource(index) if not index.isValid(): return self.sourceM...
Returns the Node at given index. :param index: Index. :type index: QModelIndex :return: Node. :rtype: AbstractCompositeNode
def __calculate_radius(self, number_neighbors, radius): """! @brief Calculate new connectivity radius. @param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius. @param[in] radius (double): Current connectivity radius. ...
! @brief Calculate new connectivity radius. @param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius. @param[in] radius (double): Current connectivity radius. @return New connectivity radius.
def prepare_boxlist(self, boxes, scores, image_shape): """ Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object cla...
Returns BoxList from `boxes` and adds probability scores information as an extra field `boxes` has shape (#detections, 4 * #classes), where each row represents a list of predicted bounding boxes for each of the object classes in the dataset (including the background class). The detection...
async def load_cache_for_proof(self, archive: bool = False) -> int: """ Load schema, cred def, revocation caches; optionally archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdir...
Load schema, cred def, revocation caches; optionally archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :param archive: True to archive now or False...
def uri_query(self): """ Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string """ value = [] for option in self.options: if option.number == defines.OptionRegistry.URI_QUERY.number: ...
Get the Uri-Query of a request. :return: the Uri-Query :rtype : String :return: the Uri-Query string
def _post(self, path, **kwargs): """ return a dict. """ # clean kwargs (filter None and empty string) clean_kwargs = clean_dict(kwargs) data = bytes(json.dumps(clean_kwargs), encoding='UTF-8') # change content type on post self._headers['Content-Type'] = 'application/jso...
return a dict.
def __get_stpd_filename(self): ''' Choose the name for stepped data file ''' if self.use_caching: sep = "|" hasher = hashlib.md5() hashed_str = "cache version 6" + sep + \ ';'.join(self.load_profile.schedule) + sep + str(self.loop_limit) ha...
Choose the name for stepped data file
def prepare_project(project, project_dir, binaries, ips, urls): """ Generates blacklists / whitelists """ # Get Various Lists / Project Waivers lists = get_lists.GetLists() # Get file name black list and project waivers file_audit_list, file_audit_project_list = lists.file_audit_list(proje...
Generates blacklists / whitelists
def generate_acyclic_graph(self): """ Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object. """ # Maximum length of each table, respectively. # Hardcoded n = cm, where c = 3 # There might be a good way...
Generates an acyclic graph for the given words. Adds the graph, and a list of edge-word associations to the object.
def await_reservations(self, sc, status={}, timeout=600): """Block until all reservations are received.""" timespent = 0 while not self.reservations.done(): logging.info("waiting for {0} reservations".format(self.reservations.remaining())) # check status flags for any errors if 'error' in ...
Block until all reservations are received.
def priority_sort(list_, priority): r""" Args: list_ (list): priority (list): desired order of items Returns: list: reordered_list CommandLine: python -m utool.util_list --test-priority_argsort Example: >>> # ENABLE_DOCTEST >>> from utool.util_list ...
r""" Args: list_ (list): priority (list): desired order of items Returns: list: reordered_list CommandLine: python -m utool.util_list --test-priority_argsort Example: >>> # ENABLE_DOCTEST >>> from utool.util_list import * # NOQA >>> list_ = [2,...
def get_or_create(cls, subscriber, livemode=djstripe_settings.STRIPE_LIVE_MODE): """ Get or create a dj-stripe customer. :param subscriber: The subscriber model instance for which to get or create a customer. :type subscriber: User :param livemode: Whether to get the subscriber in live or test mode. :type...
Get or create a dj-stripe customer. :param subscriber: The subscriber model instance for which to get or create a customer. :type subscriber: User :param livemode: Whether to get the subscriber in live or test mode. :type livemode: bool
def _outlierDetection_threaded(inputs): ''' Detect the outlier ''' [samples_idx, samples_x, samples_y_aggregation] = inputs sys.stderr.write("[%s] DEBUG: Evaluating %dth of %d samples\n"\ % (os.path.basename(__file__), samples_idx + 1, len(samples_x))) outlier = None ...
Detect the outlier
def deploy_sandbox_shared_setup(log, verbose=True, app=None, exp_config=None): """Set up Git, push to Heroku, and launch the app.""" if verbose: out = None else: out = open(os.devnull, "w") config = get_config() if not config.ready: config.load() heroku.sanity_check(conf...
Set up Git, push to Heroku, and launch the app.
def mime_type(instance): """Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry. """ mime_pattern = re.compile(r'^(application|audio|font|image|message|model' '|multipart|text|video)/[a-zA-Z0-9.+_-]+') for key, ...
Ensure the 'mime_type' property of file objects comes from the Template column in the IANA media type registry.
def _norm(self, x): """Return the norm of ``x``. This method is intended to be private. Public callers should resort to `norm` which is type-checked. """ return float(np.sqrt(self.inner(x, x).real))
Return the norm of ``x``. This method is intended to be private. Public callers should resort to `norm` which is type-checked.
def create_required_directories(self): """Creates any directories required for Engineer to function if they don't already exist.""" required = (self.CACHE_DIR, self.LOG_DIR, self.OUTPUT_DIR, self.ENGINEER.JINJA_CACHE_DIR,) for folder i...
Creates any directories required for Engineer to function if they don't already exist.
def delete(self, params, args, data): # type: (str, dict, dict) -> None """ DELETE /resource/model_cls/[params]?[args] delete resource/s """ ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id is not None: retur...
DELETE /resource/model_cls/[params]?[args] delete resource/s
def searchPhotos(self, title, **kwargs): """ Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage. """ return self.search(libtype='photo', title=title, **kwargs)
Search for a photo. See :func:`~plexapi.library.LibrarySection.search()` for usage.
def destroy(self): """Finish up a session. """ if self.session_type == 'bash': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout() elif self.session_type == 'vagrant': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout()
Finish up a session.
def get_variables(scope=None, suffix=None): """Gets the list of variables, filtered by scope and/or suffix. Args: scope: an optional scope for filtering the variables to return. suffix: an optional suffix for filtering the variables to return. Returns: a copied list of variables with scope and suffi...
Gets the list of variables, filtered by scope and/or suffix. Args: scope: an optional scope for filtering the variables to return. suffix: an optional suffix for filtering the variables to return. Returns: a copied list of variables with scope and suffix.
def get_kafka_ssl_context(): """ Returns an SSL context based on the certificate information in the Kafka config vars. """ # NOTE: We assume that Kafka environment variables are present. If using # Apache Kafka on Heroku, they will be available in your app configuration. # # 1. Write the PEM...
Returns an SSL context based on the certificate information in the Kafka config vars.
def url(self): """Return the path subcomponent of the url to this object. For example: "/computers/id/451" """ if self.id: url = "%s%s%s" % (self._url, self.id_url, self.id) else: url = None return url
Return the path subcomponent of the url to this object. For example: "/computers/id/451"
def grab_focus(self): """grab window's focus. Keyboard and scroll events will be forwarded to the sprite who has the focus. Check the 'focused' property of sprite in the on-render event to decide how to render it (say, add an outline when focused=true)""" scene = self.get_scene()...
grab window's focus. Keyboard and scroll events will be forwarded to the sprite who has the focus. Check the 'focused' property of sprite in the on-render event to decide how to render it (say, add an outline when focused=true)
def write_template(data, results_dir, parent): """Write the html template :param dict data: the dict containing all data for output :param str results_dir: the ouput directory for results :param str parent: the parent directory """ print("Generating html report...") partial = time.time() ...
Write the html template :param dict data: the dict containing all data for output :param str results_dir: the ouput directory for results :param str parent: the parent directory
def expected(self, dynamizer): """ Get the expected values for the update """ if self._expect_kwargs: return encode_query_kwargs(dynamizer, self._expect_kwargs) if self._expected is not NO_ARG: ret = {} if is_null(self._expected): ret['Exists']...
Get the expected values for the update
def summary(args): """ %prog summary *.fasta Report real bases and N's in fastafiles in a tabular report """ from jcvi.utils.natsort import natsort_key p = OptionParser(summary.__doc__) p.add_option("--suffix", default="Mb", help="make the base pair counts human readable [defau...
%prog summary *.fasta Report real bases and N's in fastafiles in a tabular report
def _process_params(self, params): """ Converts Unicode/lists/booleans inside HTTP parameters """ processed_params = {} for key, value in params.items(): processed_params[key] = self._process_param_value(value) return processed_params
Converts Unicode/lists/booleans inside HTTP parameters
def percentiles(self, percentiles): """Given a list of percentiles (floats between 0 and 1), return a list of the values at those percentiles, interpolating if necessary.""" try: scores = [0.0]*len(percentiles) if self.count > 0: values = self.samples() values.sort() ...
Given a list of percentiles (floats between 0 and 1), return a list of the values at those percentiles, interpolating if necessary.
def pluck(self, key): """ Convenience version of a common use case of `map`: fetching a property. """ return self._wrap([x.get(key) for x in self.obj])
Convenience version of a common use case of `map`: fetching a property.
def console_script(): ''' The main entry point for the production administration script 'opensubmit-exec', installed by setuptools. ''' if len(sys.argv) == 1: print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]") r...
The main entry point for the production administration script 'opensubmit-exec', installed by setuptools.
def registerTzinfo(obj, tzinfo): """ Register tzinfo if it's not already registered, return its tzid. """ tzid = obj.pickTzid(tzinfo) if tzid and not getTzid(tzid, False): registerTzid(tzid, tzinfo) return tzid
Register tzinfo if it's not already registered, return its tzid.
def diff(s1, s2): """ Return a normalised Levenshtein distance between two strings. Distance is normalised by dividing the Levenshtein distance of the two strings by the max(len(s1), len(s2)). Examples: >>> text.diff("foo", "foo") 0 >>> text.diff("foo", "fooo") 1 ...
Return a normalised Levenshtein distance between two strings. Distance is normalised by dividing the Levenshtein distance of the two strings by the max(len(s1), len(s2)). Examples: >>> text.diff("foo", "foo") 0 >>> text.diff("foo", "fooo") 1 >>> text.diff("foo", ...