positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def _read_mulliken(self): """ Parses Mulliken charges. Also parses spins given an unrestricted SCF. """ if self.data.get('unrestricted', []): header_pattern = r"\-+\s+Ground-State Mulliken Net Atomic Charges\s+Atom\s+Charge \(a\.u\.\)\s+Spin\s\(a\.u\.\)\s+\-+" tab...
Parses Mulliken charges. Also parses spins given an unrestricted SCF.
def get_context_data(self, **kwargs): """Add context data to view""" context = super().get_context_data(**kwargs) context.update({ 'title': self.title, 'submit_value': self.submit_value, 'cancel_url': self.cancel_url }) return context
Add context data to view
def _checkFrom(self, pyobj): '''WS-Address From, XXX currently not checking the hostname, not forwarding messages. pyobj -- From server returned. ''' if pyobj is None: return value = pyobj._Address if value != self._addressTo: scheme,netloc,path,quer...
WS-Address From, XXX currently not checking the hostname, not forwarding messages. pyobj -- From server returned.
async def run(self, command, timeout=None): """Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance. """ action = clien...
Run command on this unit. :param str command: The command to run :param int timeout: Time, in seconds, to wait before command is considered failed :returns: A :class:`juju.action.Action` instance.
def update(cls, id, bandwidth, vm, background): """ Update this iface. """ if not background and not cls.intty(): background = True iface_params = {} iface_id = cls.usable_id(id) if bandwidth: iface_params['bandwidth'] = bandwidth if iface_param...
Update this iface.
def handle_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" type_, value, tb = exc_info # Python 3 is broken see http://bugs.python.org/issue17413 _value = value if not isinstan...
This function is called if an exception occurs, but only if we are to stop at or just below this level.
def _validate_schema(self, schema, field, value): """ {'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]} """ if schema is None: return if isinstance(value, Sequence) and not isinstance(value, _str_type):...
{'type': ['dict', 'string'], 'anyof': [{'validator': 'schema'}, {'validator': 'bulk_schema'}]}
def addthisbunch(bunchdt, data, commdct, thisbunch, theidf): """add a bunch to model. abunch usually comes from another idf file or it can be used to copy within the idf file""" key = thisbunch.key.upper() obj = copy.copy(thisbunch.obj) abunch = obj2bunch(data, commdct, obj) bunchdt[key].app...
add a bunch to model. abunch usually comes from another idf file or it can be used to copy within the idf file
def generate_make_string(out_f, max_step): """Generate the make_string template""" steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)] with Namespace( out_f, ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl'] ) as nsp: generate_take(out_f, steps, nsp.prefix(...
Generate the make_string template
def get_random_subgraph(graph, number_edges=None, number_seed_edges=None, seed=None, invert_degrees=None): """Generate a random subgraph based on weighted random walks from random seed edges. :type graph: pybel.BELGraph graph :param Optional[int] number_edges: Maximum number of edges. Defaults to :dat...
Generate a random subgraph based on weighted random walks from random seed edges. :type graph: pybel.BELGraph graph :param Optional[int] number_edges: Maximum number of edges. Defaults to :data:`pybel_tools.constants.SAMPLE_RANDOM_EDGE_COUNT` (250). :param Optional[int] number_seed_edges: Number of no...
def map_noreturn(targ, argslist): """ parallel_call_noreturn(targ, argslist) :Parameters: - targ : function - argslist : list of tuples Does [targ(*args) for args in argslist] using the threadpool. """ # Thanks to Anne Archibald's handythread.py for the exception handling # me...
parallel_call_noreturn(targ, argslist) :Parameters: - targ : function - argslist : list of tuples Does [targ(*args) for args in argslist] using the threadpool.
def get_console_size(): """Return console size as tuple = (width, height). Returns (None,None) in non-interactive session. """ from pandas import get_option display_width = get_option('display.width') # deprecated. display_height = get_option('display.max_rows') # Consider # inter...
Return console size as tuple = (width, height). Returns (None,None) in non-interactive session.
def pubkey(self): """If the :py:obj:`PGPKey` object is a private key, this method returns a corresponding public key object with all the trimmings. Otherwise, returns ``None`` """ if not self.is_public: if self._sibling is None or isinstance(self._sibling, weakref.ref): ...
If the :py:obj:`PGPKey` object is a private key, this method returns a corresponding public key object with all the trimmings. Otherwise, returns ``None``
def track_duration(self, key): """Context manager that sets a value with the duration of time that it takes to execute whatever it is wrapping. :param str key: The timing name """ if key not in self.durations: self.durations[key] = [] start_time = time.time(...
Context manager that sets a value with the duration of time that it takes to execute whatever it is wrapping. :param str key: The timing name
def fetch(dbconn, tablename, n=1, uuid=None, end=True): """ Returns `n` rows from the table's start or end :param dbconn: database connection :param tablename: name of the table :param n: number of rows to return from the end of the table :param uuid: Optional UUID to select from :return: If...
Returns `n` rows from the table's start or end :param dbconn: database connection :param tablename: name of the table :param n: number of rows to return from the end of the table :param uuid: Optional UUID to select from :return: If n > 1, a list of rows. If n=1, a single row
def _operator_count(self, individual): """Count the number of pipeline operators as a measure of pipeline complexity. Parameters ---------- individual: list A grown tree with leaves at possibly different depths dependending on the condition function. Ret...
Count the number of pipeline operators as a measure of pipeline complexity. Parameters ---------- individual: list A grown tree with leaves at possibly different depths dependending on the condition function. Returns ------- operator_count: int ...
def tf_compilation_index(self): """ Takes out index from the parameter's tensor name. E.g. parameter tensor name is GPR-0000/kern/lengthscales, the method for that parameter will return '0000' index. """ if self.parameter_tensor is None: return None name = se...
Takes out index from the parameter's tensor name. E.g. parameter tensor name is GPR-0000/kern/lengthscales, the method for that parameter will return '0000' index.
def from_range(cls, range_list, register_flag=True): """ core class method to create visible objects from a range (nested list) """ s = dict_from_range(range_list) obj = cls.from_serializable(s, register_flag) return obj
core class method to create visible objects from a range (nested list)
def list_names(cls): """Lists all known LXC names""" response = subwrap.run(['lxc-ls']) output = response.std_out return map(str.strip, output.splitlines())
Lists all known LXC names
def get_kpoint_degeneracy(self, kpoint, cartesian=False, tol=1e-2): """ Returns degeneracy of a given k-point based on structure symmetry Args: kpoint (1x3 array): coordinate of the k-point cartesian (bool): kpoint is in cartesian or fractional coordinates tol...
Returns degeneracy of a given k-point based on structure symmetry Args: kpoint (1x3 array): coordinate of the k-point cartesian (bool): kpoint is in cartesian or fractional coordinates tol (float): tolerance below which coordinates are considered equal Returns: ...
def cos(cls, x: 'TensorFluent') -> 'TensorFluent': '''Returns a TensorFluent for the cos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the cos function. ''' return cls._unary_op(x, tf.cos, tf.float32)
Returns a TensorFluent for the cos function. Args: x: The input fluent. Returns: A TensorFluent wrapping the cos function.
def ipv6_ipv6route_route_dest(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ipv6 = ET.SubElement(config, "ipv6", xmlns="urn:brocade.com:mgmt:brocade-common-def") ipv6route = ET.SubElement(ipv6, "ipv6route", xmlns="urn:brocade.com:mgmt:brocade-ip-forwar...
Auto Generated Code
def element(element, name, default=None): """ Returns the value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to retur...
Returns the value of an element, or a default if it's not defined :param element: The XML Element object :type element: etree._Element :param name: The name of the element to evaluate :type name: str :param default: The default value to return if the element is not defined
def get_user_api_key(self, username, create=True): """ Get the API key of a given user. API keys are generated on demand. :param username: :param create: Create the API key if none exists yet :return: the API key assigned to the user, or None if none exists and create is ...
Get the API key of a given user. API keys are generated on demand. :param username: :param create: Create the API key if none exists yet :return: the API key assigned to the user, or None if none exists and create is False.
def printStack(self,wrappedStack,include=None,filters=["*"]): """Prints the stack""" rawStack = wrappedStack['rawStack'] print "==== Stack {} ====".format(rawStack.name) print "Status: {} {}".format(rawStack.stack_status,defaultify(rawStack.stack_status_reason,'')) for resourceT...
Prints the stack
def wait_for_property(self, name, cond=lambda val: val, level_sensitive=True): """Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for properties such as ``idle_active`` indicating the player is done with regular playback and just idling around """...
Waits until ``cond`` evaluates to a truthy value on the named property. This can be used to wait for properties such as ``idle_active`` indicating the player is done with regular playback and just idling around
def finalize(self): """ Called at clean up. Is used to disconnect signals. """ self.spinBox.valueChanged.disconnect(self.commitChangedValue) super(IntCtiEditor, self).finalize()
Called at clean up. Is used to disconnect signals.
def copy(chain: MiningChain) -> MiningChain: """ Make a copy of the chain at the given state. Actions performed on the resulting chain will not affect the original chain. """ if not isinstance(chain, MiningChain): raise ValidationError("`at_block_number` may only be used with 'MiningChain")...
Make a copy of the chain at the given state. Actions performed on the resulting chain will not affect the original chain.
def disambiguate_fname(self, fname): """Generate a file name without ambiguation.""" files_path_list = [filename for filename in self.filenames if filename] return sourcecode.disambiguate_fname(files_path_list, fname)
Generate a file name without ambiguation.
def setup_ordered_indices_local_geometry(self, coordination): """ Sets up ordered indices for the local geometry, for testing purposes :param coordination: coordination of the local geometry """ self.icentral_site = 0 self.indices = list(range(1, coordination + 1))
Sets up ordered indices for the local geometry, for testing purposes :param coordination: coordination of the local geometry
def create_hosted_zone(domain_name, caller_ref=None, comment='', private_zone=False, vpc_id=None, vpc_name=None, vpc_region=None, region=None, key=None, keyid=None, profile=None): ''' Create a new Route53 Hosted Zone. Returns a Python data structure with information...
Create a new Route53 Hosted Zone. Returns a Python data structure with information about the newly created Hosted Zone. domain_name The name of the domain. This must be fully-qualified, terminating with a period. This is the name you have registered with your domain registrar. It is also the ...
def start_responder(host='127.0.0.1', port=8080, event_log=None, loop=None): """.""" loop = loop or asyncio.get_event_loop() event_log = event_log or structlog.get_logger() # Prepare a web application. app = web.Application(loop=loop, middlewares=[ inject_request_id, access_log_mid...
.
def sync(self, owner, id, **kwargs): """ Sync files Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to use webhooks or scr...
Sync files Update all files within a dataset that have originally been added via URL (e.g. via /datasets endpoints or on data.world). Check-out or tutorials for tips on how to add Google Sheets, GitHub and S3 files via URL and how to use webhooks or scripts to keep them always in sync. This method mak...
def to_unicode(self, omit_final_dot = False): """Convert name to Unicode text format. IDN ACE lables are converted to Unicode. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string ""...
Convert name to Unicode text format. IDN ACE lables are converted to Unicode. @param omit_final_dot: If True, don't emit the final dot (denoting the root label) for absolute names. The default is False. @rtype: string
def features_keep_within_radius(obj, center, radius, units): """ Filter all features in a collection by retaining only those that fall within the specified radius. """ features_keep = [] for feature in tqdm(obj['features']): if all([getattr(geopy.distance.vincenty((lat,lon), center), uni...
Filter all features in a collection by retaining only those that fall within the specified radius.
def solve_coupled_ecc_solution(F0, e0, gamma0, phase0, mc, q, t): """ Compute the solution to the coupled system of equations from from Peters (1964) and Barack & Cutler (2004) at a given time. :param F0: Initial orbital frequency [Hz] :param e0: Initial orbital eccentricity :param gam...
Compute the solution to the coupled system of equations from from Peters (1964) and Barack & Cutler (2004) at a given time. :param F0: Initial orbital frequency [Hz] :param e0: Initial orbital eccentricity :param gamma0: Initial angle of precession of periastron [rad] :param mc: Chirp mass...
def _delete_map_from_user_by_id(self, user, map_id): """ Delete a mapfile entry from database. """ map = self._get_map_from_user_by_id(user, map_id) if map is None: return None Session.delete(map) Session.commit() return map
Delete a mapfile entry from database.
def _project(reference_sources, C): """Project images using pre-computed filters C reference_sources are nsrc X nsampl X nchan C is nsrc X nchan X filters_len X nchan """ # shapes: ensure that input is 3d (comprising the source index) if len(reference_sources.shape) == 2: reference_sourc...
Project images using pre-computed filters C reference_sources are nsrc X nsampl X nchan C is nsrc X nchan X filters_len X nchan
def binary(self, length=(1 * 1024 * 1024)): """ Returns random binary blob. Default blob size is 1 Mb. """ blob = [self.generator.random.randrange(256) for _ in range(length)] return bytes(blob) if sys.version_info[0] >= 3 else bytearray(blob)
Returns random binary blob. Default blob size is 1 Mb.
def set_rollover(self, area, enabled): """Configure whether rollover is enabled for streaming or storage streams. Normally a SensorLog is used in ring-buffer mode which means that old readings are automatically overwritten as needed when new data is saved. However, you can configure it...
Configure whether rollover is enabled for streaming or storage streams. Normally a SensorLog is used in ring-buffer mode which means that old readings are automatically overwritten as needed when new data is saved. However, you can configure it into fill-stop mode by using: set_rollove...
def unload(self): '''unload module''' self.mpstate.console.close() self.mpstate.console = textconsole.SimpleConsole()
unload module
def add_document(self, question, answer): """Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: An answer to a question :type answer: :class:`str` """ question = question.strip() answer = ...
Add question answer set to DB. :param question: A question to an answer :type question: :class:`str` :param answer: An answer to a question :type answer: :class:`str`
def check_minion_cache(self, preserve_minions=None): ''' Check the minion cache to make sure that old minion data is cleared Optionally, pass in a list of minions which should have their caches preserved. To preserve all caches, set __opts__['preserve_minion_cache'] ''' ...
Check the minion cache to make sure that old minion data is cleared Optionally, pass in a list of minions which should have their caches preserved. To preserve all caches, set __opts__['preserve_minion_cache']
def invalidate_cache_after_error(f): """ catch any exception and invalidate internal cache with list of nodes """ @wraps(f) def wrapper(self, *args, **kwds): try: return f(self, *args, **kwds) except Exception: self.clear_cluster_nodes_cache() rais...
catch any exception and invalidate internal cache with list of nodes
def rmon_event_entry_log(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon") event_entry = ET.SubElement(rmon, "event-entry") event_index_key = ET.SubElement(event_entry,...
Auto Generated Code
def clean_ip(ip): """ Cleans the ip address up, useful for removing leading zeros, e.g.:: 1234:0:01:02:: -> 1234:0:1:2:: 1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a 1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1:: 0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:...
Cleans the ip address up, useful for removing leading zeros, e.g.:: 1234:0:01:02:: -> 1234:0:1:2:: 1234:0000:0000:0000:0000:0000:0000:000A -> 1234::a 1234:0000:0000:0000:0001:0000:0000:0000 -> 1234:0:0:0:1:: 0000:0000:0000:0000:0001:0000:0000:0000 -> ::1:0:0:0 :type ip: string ...
def add(self, child): """ Adds a typed child object to the conditional derived variable. @param child: Child object to be added. """ if isinstance(child, Case): self.add_case(child) else: raise ModelError('Unsupported child element')
Adds a typed child object to the conditional derived variable. @param child: Child object to be added.
def load(cls, path_to_file): """ Loads the image data from a file on disk and tries to guess the image MIME type :param path_to_file: path to the source file :type path_to_file: str :return: a `pyowm.image.Image` instance """ import mimetypes mimetypes.in...
Loads the image data from a file on disk and tries to guess the image MIME type :param path_to_file: path to the source file :type path_to_file: str :return: a `pyowm.image.Image` instance
def header(self): """Return the frame header (as an array of bytes).""" total_length = self.total_length() res = [0x06, 0x10, 0, 0, 0, 0] res[2] = (self.service_type_id >> 8) & 0xff res[3] = (self.service_type_id >> 0) & 0xff res[4] = (total_length >> 8) & 0xff re...
Return the frame header (as an array of bytes).
def _generic_action_parser(self): """Generic parser for Actions.""" actions = [] while True: action_code = unpack_ui8(self._src) if action_code == 0: break action_name = ACTION_NAMES[action_code] if action_code > 128: ...
Generic parser for Actions.
def sm_dict2lha(d): """Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.""" blocks = OrderedDict([ ('GAUGE', {'values': [[1, d['g'].real], [2, d['gp'].real], [3, d['gs'].real]]}), ('SCALAR', {'values': [[1, d['Lambda'].real], [2...
Convert a a dictionary of SM parameters into a dictionary that pylha can convert into a DSixTools SM output file.
def get(self, name, *df): """ Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set...
Get the value of a property by I{name}. @param name: The property name. @type name: str @param df: An optional value to be returned when the value is not set @type df: [1]. @return: The stored value, or I{df[0]} if not set. @rtype: any
def acp_users_delete(): """Delete or undelete an user account.""" if not current_user.is_admin: return error("Not authorized to edit users.", 401) if not db: return error('The ACP is not available in single-user mode.', 500) form = UserDeleteForm() if not form.validate(): re...
Delete or undelete an user account.
def are_debian_packages_installed(packages: List[str]) -> Dict[str, bool]: """ Check which of a list of Debian packages are installed, via ``dpkg-query``. Args: packages: list of Debian package names Returns: dict: mapping from package name to boolean ("present?") """ assert l...
Check which of a list of Debian packages are installed, via ``dpkg-query``. Args: packages: list of Debian package names Returns: dict: mapping from package name to boolean ("present?")
def conclude_deactivate_or_delete_enrollment(self, id, course_id, task=None): """ Conclude, deactivate, or delete an enrollment. Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment will be concluded. """ path = {} ...
Conclude, deactivate, or delete an enrollment. Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment will be concluded.
def _filter_kwargs(names, dict_): """Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the...
Filter out kwargs from a dictionary. Parameters ---------- names : set[str] The names to select from ``dict_``. dict_ : dict[str, any] The dictionary to select from. Returns ------- kwargs : dict[str, any] ``dict_`` where the keys intersect with ``names`` and the va...
def _version_less_than_or_equal_to(self, v1, v2): """ Returns true if v1 <= v2. """ # pylint: disable=no-name-in-module, import-error from distutils.version import LooseVersion return LooseVersion(v1) <= LooseVersion(v2)
Returns true if v1 <= v2.
def new( name, bucket, timeout, memory, description, subnet_ids, security_group_ids ): """ Create a new lambda project """ config = {} if timeout: config['timeout'] = timeout if memory: config['memory'] = memory if description: config['description'...
Create a new lambda project
async def handler(event): """#learn or #python: Tells the user to learn some Python first.""" await asyncio.wait([ event.delete(), event.respond( LEARN_PYTHON, reply_to=event.reply_to_msg_id, link_preview=False) ])
#learn or #python: Tells the user to learn some Python first.
def get_checkpoints_for_actor(actor_id): """Get the available checkpoints for the given actor ID, return a list sorted by checkpoint timestamp in descending order. """ checkpoint_info = ray.worker.global_state.actor_checkpoint_info(actor_id) if checkpoint_info is None: return [] checkpoi...
Get the available checkpoints for the given actor ID, return a list sorted by checkpoint timestamp in descending order.
def check_valid(self): """ check if input is valid """ for k,input in self.inputs.items(): if k in self.valid_opts: for param in self.valid_opts[k]: if param is None or input is None: return True elif type(param) is str and '+' in param: if re.search(r'^'+param,str(input)): retur...
check if input is valid
def encode(self, text, encoding, defaultchar='?'): """ Encode text under the given encoding :param text: Text to encode :param encoding: Encoding name to use (must be defined in capabilities) :param defaultchar: Fallback for non-encodable characters """ codepage_char_map...
Encode text under the given encoding :param text: Text to encode :param encoding: Encoding name to use (must be defined in capabilities) :param defaultchar: Fallback for non-encodable characters
def interpolate(values, color_map=None, dtype=np.uint8): """ Given a 1D list of values, return interpolated colors for the range. Parameters --------------- values : (n, ) float Values to be interpolated over color_map : None, or str Key to a colormap contained in: matplot...
Given a 1D list of values, return interpolated colors for the range. Parameters --------------- values : (n, ) float Values to be interpolated over color_map : None, or str Key to a colormap contained in: matplotlib.pyplot.colormaps() e.g: 'viridis' Returns --------...
def schedule(ident, cron=None, minute='*', hour='*', day_of_week='*', day_of_month='*', month_of_year='*'): '''Schedule an harvesting on a source given a crontab''' source = get_source(ident) if cron: minute, hour, day_of_month, month_of_year, day_of_week = cron.split() crontab = ...
Schedule an harvesting on a source given a crontab
def ensure_all_columns_are_used(num_vars_accounted_for, dataframe, data_title='long_data'): """ Ensure that all of the columns from dataframe are in the list of used_cols. Will raise a helpful UserWarning if otherwise. Parameters -----...
Ensure that all of the columns from dataframe are in the list of used_cols. Will raise a helpful UserWarning if otherwise. Parameters ---------- num_vars_accounted_for : int. Denotes the number of variables used in one's function. dataframe : pandas dataframe. Contains all of the da...
def get_children(self): """Return the children of this folder""" try: children = os.listdir(self.real_path) except OSError: return [] result = [] for name in children: try: child = self.get_child(name) except excepti...
Return the children of this folder
def on_service_arrival(self, svc_ref): """ Called when a service has been registered in the framework :param svc_ref: A service reference """ with self._lock: if self.reference is None: # Inject the service service = self._context.get_...
Called when a service has been registered in the framework :param svc_ref: A service reference
def set_metadata(self, container, metadata, clear=False, prefix=None): """ Accepts a dictionary of metadata key/value pairs and updates the specified container metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Othe...
Accepts a dictionary of metadata key/value pairs and updates the specified container metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Otherwise, the values passed here update the container's metadata. By default,...
def get_fw_rule(self, rule_id): """Return the firewall rule, given its ID. """ rule = None try: rule = self.neutronclient.show_firewall_rule(rule_id) except Exception as exc: LOG.error("Failed to get firewall rule for id %(id)s " "Exc %(exc)s...
Return the firewall rule, given its ID.
def content(self): """ Returns lazily content of the FileNode. If possible, would try to decode content from UTF-8. """ content = self._get_content() if bool(content and '\0' in content): return content return safe_unicode(content)
Returns lazily content of the FileNode. If possible, would try to decode content from UTF-8.
def try_rgb(s, default=None): """ Try parsing a string into an rgb value (int, int, int), where the ints are 0-255 inclusive. If None is passed, default is returned. On failure, InvalidArg is raised. """ if not s: return default try: r, g, b = (int(x.strip()) for ...
Try parsing a string into an rgb value (int, int, int), where the ints are 0-255 inclusive. If None is passed, default is returned. On failure, InvalidArg is raised.
def iqi(ql, qs, ns=None, rc=None, ot=None, coe=None, moc=DEFAULT_ITER_MAXOBJECTCOUNT,): # pylint: disable=line-too-long """ *New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMConnection.IterQueryInstances`. Execute a query in a...
*New in pywbem 0.10 as experimental and finalized in 0.12.* This function is a wrapper for :meth:`~pywbem.WBEMConnection.IterQueryInstances`. Execute a query in a namespace, using the corresponding pull operations if supported by the WBEM server or otherwise the corresponding traditional operation...
def _deg2num(self, lat_deg, lon_deg, zoom, leave_float=False): """ Taken from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Python """ lat_rad = mod_math.radians(lat_deg) n = 2.0 ** zoom xtile = (lon_deg + 180.0) / 360.0 * n ytile = (1.0 - mod_math.log(mod_math.tan(lat_...
Taken from http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Python
def get_primary_text(self, item_url, force_download=False): """ Retrieve the primary text for an item from the server :type item_url: String or Item :param item_url: URL of the item, or an Item object :type force_download: Boolean :param force_download: True to download from the...
Retrieve the primary text for an item from the server :type item_url: String or Item :param item_url: URL of the item, or an Item object :type force_download: Boolean :param force_download: True to download from the server regardless of the cache's contents :rtype: ...
def set_attrs(obj, attrs): """ Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict ...
Applies a collection of attributes C{attrs} to object C{obj} in the most generic way possible. @param obj: An instance implementing C{__setattr__}, or C{__setitem__} @param attrs: A collection implementing the C{iteritems} function @type attrs: Usually a dict
def send(self, message): """Send a handover request message to the remote server.""" log.debug("sending '{0}' message".format(message.type)) send_miu = self.socket.getsockopt(nfc.llcp.SO_SNDMIU) try: data = str(message) except nfc.llcp.EncodeError as e: lo...
Send a handover request message to the remote server.
def umi_histogram(fastq): ''' Counts the number of reads for each UMI Expects formatted fastq files. ''' annotations = detect_fastq_annotations(fastq) re_string = construct_transformed_regex(annotations) parser_re = re.compile(re_string) counter = collections.Counter() for read in read...
Counts the number of reads for each UMI Expects formatted fastq files.
def _start(self, tpart): """Start upload and accout for resource consumption.""" g = gevent.Greenlet(self.uploader, tpart) g.link(self._finish) # Account for concurrency_burden before starting the greenlet # to avoid racing against .join. self.concurrency_burden += 1 ...
Start upload and accout for resource consumption.
def getAll(self, event_name): """Gets all the events of a certain name that have been received so far. This is a non-blocking call. Args: callback_id: The id of the callback. event_name: string, the name of the event to get. Returns: A list of Snippe...
Gets all the events of a certain name that have been received so far. This is a non-blocking call. Args: callback_id: The id of the callback. event_name: string, the name of the event to get. Returns: A list of SnippetEvent, each representing an event from t...
def aaxn(mt, x, n, m=1): """ äxn : Return the actuarial present value of a (immediate) temporal (term certain) annuity: n-year temporary life annuity-anticipatory. Payable 'm' per year at the beginning of the period """ if m == 1: return (mt.Nx[x] - mt.Nx[x + n]) / mt.Dx[x] else: r...
äxn : Return the actuarial present value of a (immediate) temporal (term certain) annuity: n-year temporary life annuity-anticipatory. Payable 'm' per year at the beginning of the period
def zkronv(ttA, ttB): """ Do kronecker product between vectors ttA and ttB. Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product For details about operation refer: https://arxiv.org/abs/1802.02839 :param ttA: first TT-vector; :param ttB: second TT-vector; :return: operati...
Do kronecker product between vectors ttA and ttB. Look about kronecker at: https://en.wikipedia.org/wiki/Kronecker_product For details about operation refer: https://arxiv.org/abs/1802.02839 :param ttA: first TT-vector; :param ttB: second TT-vector; :return: operation result in z-order
def init_app(self, app, session): """ Will initialize the Flask app, supporting the app factory pattern. :param app: :param session: The SQLAlchemy session """ app.config.setdefault("APP_NAME", "F.A.B.") app.config.setdefault("APP_THEME", "") ...
Will initialize the Flask app, supporting the app factory pattern. :param app: :param session: The SQLAlchemy session
def extract_code(end_mark, current_str, str_array, line_num): '''Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list)...
Extract a multi-line string from a string array, up to a specified end marker. Args: end_mark (str): The end mark string to match for. current_str (str): The first line of the string array. str_array (list): An array of strings (lines). line_num (int): The curren...
def remove_container(self, container_id): """ Removes a container (with fire) """ self._docker.containers.get(container_id).remove(v=True, link=False, force=True)
Removes a container (with fire)
def run_worker(wname, data, engine_uuid_hex=None, **kwargs): """Run a workflow by name with list of data objects. The list of data can also contain WorkflowObjects. ``**kwargs`` can be used to pass custom arguments to the engine/object. :param wname: name of workflow to run. :type wname: str ...
Run a workflow by name with list of data objects. The list of data can also contain WorkflowObjects. ``**kwargs`` can be used to pass custom arguments to the engine/object. :param wname: name of workflow to run. :type wname: str :param data: objects to run through the workflow. :type data: l...
def dedupe_by(things, key=None): """ Given an iterator of things and an optional key generation function, return a new iterator of deduped things. Things are compared and de-duped by the key function, which is hash() by default. """ if not key: key = hash index = {key(thing): thing f...
Given an iterator of things and an optional key generation function, return a new iterator of deduped things. Things are compared and de-duped by the key function, which is hash() by default.
def info(self, exp_path=False, project_path=False, global_path=False, config_path=False, complete=False, no_fix=False, on_projects=False, on_globals=False, projectname=None, return_dict=False, insert_id=True, only_keys=False, archives=False, **kwargs): """ ...
Print information on the experiments Parameters ---------- exp_path: bool If True/set, print the filename of the experiment configuration project_path: bool If True/set, print the filename on the project configuration global_path: bool If True...
def fsencode(path, os_name=os.name, fs_encoding=FS_ENCODING, errors=None): ''' Encode given path. :param path: path will be encoded if not using bytes :type path: bytes or str :param os_name: operative system name, defaults to os.name :type os_name: str :param fs_encoding: current filesyste...
Encode given path. :param path: path will be encoded if not using bytes :type path: bytes or str :param os_name: operative system name, defaults to os.name :type os_name: str :param fs_encoding: current filesystem encoding, defaults to autodetected :type fs_encoding: str :return: encoded pa...
def ncr(n, r): """ Calculate n choose r. :param n: n :type n : int :param r: r :type r :int :return: n choose r as int """ r = min(r, n - r) numer = reduce(op.mul, range(n, n - r, -1), 1) denom = reduce(op.mul, range(1, r + 1), 1) return numer // denom
Calculate n choose r. :param n: n :type n : int :param r: r :type r :int :return: n choose r as int
def get_build_scanner_path(self, scanner): """Fetch the scanner path for this executor's targets and sources. """ env = self.get_build_env() try: cwd = self.batches[0].targets[0].cwd except (IndexError, AttributeError): cwd = None return scanner.pa...
Fetch the scanner path for this executor's targets and sources.
def hlp_source_under(folder): """ this function finds all the python packages under a folder and write the 'packages' and 'package_dir' entries for a python setup.py script """ # walk the folder and find the __init__.py entries for packages. packages = [] package_dir = dict() for roo...
this function finds all the python packages under a folder and write the 'packages' and 'package_dir' entries for a python setup.py script
def _activate(self, token): """Activate this node for the given token.""" info = token.to_info() activation = Activation( self.rule, frozenset(info.data), {k: v for k, v in info.context if isinstance(k, str)}) if token.is_valid(): if inf...
Activate this node for the given token.
def is_within_publication_dates(obj, timestamp=None): """ Return True if the given timestamp (or ``now()`` by default) is witin any publication start/end date constraints. """ if timestamp is None: timestamp = timezone.now() start_date_ok = not obj.publication...
Return True if the given timestamp (or ``now()`` by default) is witin any publication start/end date constraints.
def _get_result(self) -> float: """Return current measurement result in lx.""" try: data = self._bus.read_word_data(self._i2c_add, self._mode) self._ok = True except OSError as exc: self.log_error("Bad reading in bus: %s", exc) self._ok = False ...
Return current measurement result in lx.
def trainTopicGetTrainedTopic(self, uri, maxConcepts = 20, maxCategories = 10, ignoreConceptTypes=[], idfNormalization = True): """ retrieve topic for the topic for which you have already finished training @param uri: uri of the topic (obtained by calling trainTopicCreateTopic method...
retrieve topic for the topic for which you have already finished training @param uri: uri of the topic (obtained by calling trainTopicCreateTopic method) @param maxConcepts: number of top concepts to retrieve in the topic @param maxCategories: number of top categories to retrieve in the topic ...
def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines)
Rewrite a file adding a line to its beginning.
def update(self, data, append_value=None): """ This method takes data, and modifies the Wikidata item. This works together with the data already provided via the constructor or if the constructor is being instantiated with search_only=True. In the latter case, this allows for checking th...
This method takes data, and modifies the Wikidata item. This works together with the data already provided via the constructor or if the constructor is being instantiated with search_only=True. In the latter case, this allows for checking the item data before deciding which new data should be written to...
def get_attr(self, obj, name): """Get attribute of the target object with the configured attribute name in the :attr:`~brownant.pipeline.base.PipelineProperty.attr_names` of this instance. :param obj: the target object. :type obj: :class:`~brownant.dinergate.Dinergate` :...
Get attribute of the target object with the configured attribute name in the :attr:`~brownant.pipeline.base.PipelineProperty.attr_names` of this instance. :param obj: the target object. :type obj: :class:`~brownant.dinergate.Dinergate` :param name: the internal name used in the ...
def uniprot_reviewed_checker_batch(uniprot_ids): """Batch check if uniprot IDs are reviewed or not Args: uniprot_ids: UniProt ID or list of UniProt IDs Returns: A dictionary of {UniProtID: Boolean} """ uniprot_ids = ssbio.utils.force_list(uniprot_ids) invalid_ids = [i for i i...
Batch check if uniprot IDs are reviewed or not Args: uniprot_ids: UniProt ID or list of UniProt IDs Returns: A dictionary of {UniProtID: Boolean}
def _get_recommended_models(models, fld_name): """ Returns a list of models which have the minimum target field value for a given field name (AIC or BMDL). """ target_value = min([model.output[fld_name] for model in models]) return [model for model in models if model.outp...
Returns a list of models which have the minimum target field value for a given field name (AIC or BMDL).