code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def parse_numeric_code(self, force_hex=False): """ Parses and returns the numeric code as an integer. The numeric code can be either base 10 or base 16, depending on where the message came from. :param force_hex: force the numeric code to be processed as base 16. :type ...
Parses and returns the numeric code as an integer. The numeric code can be either base 10 or base 16, depending on where the message came from. :param force_hex: force the numeric code to be processed as base 16. :type force_hex: boolean :raises: ValueError
def readint2dnorm(filename): """Read corrected intensity and error matrices (Matlab mat or numpy npz format for Beamline B1 (HASYLAB/DORISIII)) Input ----- filename: string the name of the file Outputs ------- two ``np.ndarray``-s, the Intensity and the Error matrices File...
Read corrected intensity and error matrices (Matlab mat or numpy npz format for Beamline B1 (HASYLAB/DORISIII)) Input ----- filename: string the name of the file Outputs ------- two ``np.ndarray``-s, the Intensity and the Error matrices File formats supported: ------------...
def aggregate(self, pipeline, **kwargs): """Execute an aggregation pipeline on this collection. The aggregation can be run on a secondary if the client is connected to a replica set and its ``read_preference`` is not :attr:`PRIMARY`. :Parameters: - `pipeline`: a single comman...
Execute an aggregation pipeline on this collection. The aggregation can be run on a secondary if the client is connected to a replica set and its ``read_preference`` is not :attr:`PRIMARY`. :Parameters: - `pipeline`: a single command or list of aggregation commands - `sessi...
def p_objectlist_1(self, p): "objectlist : objectlist objectitem" if DEBUG: self.print_p(p) p[0] = p[1] + [p[2]]
objectlist : objectlist objectitem
def _analyse_mat_sections(sections): """ Cases: - ICRU flag present, LOADDEDX flag missing -> data loaded from some data hardcoded in SH12A binary, no need to load external files - ICRU flag present, LOADDEDX flag present -> data loaded from external files. ICRU number read from ...
Cases: - ICRU flag present, LOADDEDX flag missing -> data loaded from some data hardcoded in SH12A binary, no need to load external files - ICRU flag present, LOADDEDX flag present -> data loaded from external files. ICRU number read from ICRU flag, any number following LOADDEDX flag is ...
def update_namespace(namespace, path, name): """ A recursive function that takes a root element, list of namespaces, and the value being stored, and assigns namespaces to the root object via a chain of Namespace objects, connected through attributes Parameters ---------- namespace : Namespa...
A recursive function that takes a root element, list of namespaces, and the value being stored, and assigns namespaces to the root object via a chain of Namespace objects, connected through attributes Parameters ---------- namespace : Namespace The object onto which an attribute will be add...
def buildType(columns=[], extra=[]): """Build a table :param list columns: List of column names and types. eg [('colA', 'd')] :param list extra: A list of tuples describing additional non-standard fields :returns: A :py:class:`Type` """ return Type(id="epics:nt/NTTable:1...
Build a table :param list columns: List of column names and types. eg [('colA', 'd')] :param list extra: A list of tuples describing additional non-standard fields :returns: A :py:class:`Type`
def getInstIdFromIndices(self, *indices): """Return column instance identification from indices""" try: return self._idxToIdCache[indices] except TypeError: cacheable = False except KeyError: cacheable = True idx = 0 instId = () ...
Return column instance identification from indices
def _set_up_savefolder(self): """ Create catalogs for different file output to clean up savefolder. Non-public method Parameters ---------- None Returns ------- None """ if self.savefolder == None: return ...
Create catalogs for different file output to clean up savefolder. Non-public method Parameters ---------- None Returns ------- None
def get_register(self, motors, disable_sync_read=False): """ Gets the value from the specified register and sets it to the :class:`~pypot.dynamixel.motor.DxlMotor`. """ if not motors: return False ids = [m.id for m in motors] getter = getattr(self.io, 'get_{}'.format(self.re...
Gets the value from the specified register and sets it to the :class:`~pypot.dynamixel.motor.DxlMotor`.
def getRanking(self, profile, sampleFileName = None): """ Returns a list of lists that orders all candidates in tiers from best to worst when we use MCMC approximation to compute Bayesian utilities for an election profile. :ivar Profile profile: A Profile object that represents an elec...
Returns a list of lists that orders all candidates in tiers from best to worst when we use MCMC approximation to compute Bayesian utilities for an election profile. :ivar Profile profile: A Profile object that represents an election profile. :ivar str sampleFileName: An optional argument for t...
def task(self): """ Find the task for this build. Wraps the getTaskInfo RPC. :returns: deferred that when fired returns the Task object, or None if we could not determine the task for this build. """ # If we have no .task_id, this is a no-op to return ...
Find the task for this build. Wraps the getTaskInfo RPC. :returns: deferred that when fired returns the Task object, or None if we could not determine the task for this build.
def confd_state_daemon_status(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") daemon_status = ET.SubElement(confd_state, "daemon-status") daemon_s...
Auto Generated Code
def set_result(self, result): """Set future's result if needed (can be an exception). Else raise if needed.""" result = result.result()[0] if self.future is not None: if isinstance(result, Exception): self.future.set_exception(result) else: ...
Set future's result if needed (can be an exception). Else raise if needed.
def _iter_vals(key): """! Iterate over values of a key """ for i in range(winreg.QueryInfoKey(key)[1]): yield winreg.EnumValue(key, i)
! Iterate over values of a key
def calculate_subscription_lifecycle(subscription_id): """ Calculates the expected lifecycle position the subscription in subscription_ids, and creates a BehindSubscription entry for them. Args: subscription_id (str): ID of subscription to calculate lifecycle for """ subscription = Subs...
Calculates the expected lifecycle position the subscription in subscription_ids, and creates a BehindSubscription entry for them. Args: subscription_id (str): ID of subscription to calculate lifecycle for
def generate(node, environment, name, filename, stream=None, defer_init=False): """Generate the python source for a node tree.""" if not isinstance(node, nodes.Template): raise TypeError('Can\'t compile non template nodes') generator = CodeGenerator(environment, name, filename, stream, ...
Generate the python source for a node tree.
def _copy(self): """ Create a new L{TransitionTable} just like this one using a copy of the underlying transition table. @rtype: L{TransitionTable} """ table = {} for existingState, existingOutputs in self.table.items(): table[existingState] = {} ...
Create a new L{TransitionTable} just like this one using a copy of the underlying transition table. @rtype: L{TransitionTable}
def _process_raw_report(self, raw_report): "Default raw input report data handler" if not self.is_opened(): return if not self.__evt_handlers and not self.__raw_handler: return if not raw_report[0] and \ (raw_report[0] not in self.__input...
Default raw input report data handler
def attribute(self, name): """Expression for an input attribute. An input attribute is an attribute on the input port of the operator invocation. Args: name(str): Name of the attribute. Returns: Expression: Expression representing the input a...
Expression for an input attribute. An input attribute is an attribute on the input port of the operator invocation. Args: name(str): Name of the attribute. Returns: Expression: Expression representing the input attribute.
def plot_circular(widths, colors, curviness=0.2, mask=True, topo=None, topomaps=None, axes=None, order=None): """Circluar connectivity plot. Topos are arranged in a circle, with arrows indicating connectivity Parameters ---------- widths : float or array, shape (n_channels, n_channels) Wid...
Circluar connectivity plot. Topos are arranged in a circle, with arrows indicating connectivity Parameters ---------- widths : float or array, shape (n_channels, n_channels) Width of each arrow. Can be a scalar to assign the same width to all arrows. colors : array, shape (n_channels, n_ch...
def get_dict_hashid(dict_): r""" Args: dict_ (dict): Returns: int: id hash References: http://stackoverflow.com/questions/5884066/hashing-a-python-dictionary CommandLine: python -m utool.util_dict --test-get_dict_hashid python3 -m utool.util_dict --test-get...
r""" Args: dict_ (dict): Returns: int: id hash References: http://stackoverflow.com/questions/5884066/hashing-a-python-dictionary CommandLine: python -m utool.util_dict --test-get_dict_hashid python3 -m utool.util_dict --test-get_dict_hashid Example: ...
def format_datetime(time): """ Formats a date, converting the time to the user timezone if one is specified """ user_time_zone = timezone.get_current_timezone() if time.tzinfo is None: time = time.replace(tzinfo=pytz.utc) user_time_zone = pytz.timezone(getattr(settings, 'USER_TIME_ZO...
Formats a date, converting the time to the user timezone if one is specified
def _get_magnitude_vector_properties(catalogue, config): '''If an input minimum magnitude is given then consider catalogue only above the minimum magnitude - returns corresponding properties''' mmin = config.get('input_mmin', np.min(catalogue['magnitude'])) neq = np.float(np.sum(catalogue['magnitude'] ...
If an input minimum magnitude is given then consider catalogue only above the minimum magnitude - returns corresponding properties
def preproc(self, which='sin', **kwargs): """ Create preprocessing data Parameters ---------- which: str The name of the numpy function to apply ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main...
Create preprocessing data Parameters ---------- which: str The name of the numpy function to apply ``**kwargs`` Any other parameter for the :meth:`model_organization.ModelOrganizer.app_main` method
def discard(self, element): """ Return a new PSet with element removed. Returns itself if element is not present. """ if element in self._map: return self.evolver().remove(element).persistent() return self
Return a new PSet with element removed. Returns itself if element is not present.
def detect_version(basedir, compiler=None, **compiler_attrs): """Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compi...
Compile, link & execute a test program, in empty directory `basedir`. The C compiler will be updated with any keywords given via setattr. Parameters ---------- basedir : path The location where the test program will be compiled and run compiler : str The distutils compiler key (e....
def attribute_text_label(node, current_word): """ Tries to recover the label inside a string of the form '(3 hello)' where 3 is the label, and hello is the string. Label is not assigned if the string does not follow the expected format. Arguments: ---------- node : LabeledTree, ...
Tries to recover the label inside a string of the form '(3 hello)' where 3 is the label, and hello is the string. Label is not assigned if the string does not follow the expected format. Arguments: ---------- node : LabeledTree, current node that should possibly receive a la...
def convert_shape(params, w_name, scope_name, inputs, layers, weights, names): """ Convert shape operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary ...
Convert shape operation. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for k...
def _get_build_env(env): ''' Get build environment overrides dictionary to use in build process ''' env_override = '' if env is None: return env_override if not isinstance(env, dict): raise SaltInvocationError( '\'env\' must be a Python dictionary' ) for k...
Get build environment overrides dictionary to use in build process
def empty(shape, ctx=None, dtype=None, stype=None): """Returns a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the curren...
Returns a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current default context). dtype : str or numpy.dtype, optiona...
async def is_change_done(self, zone, change_id): """Check if a DNS change has completed. Args: zone (str): DNS zone of the change. change_id (str): Identifier of the change. Returns: Boolean """ zone_id = self.get_managed_zone(zone) ur...
Check if a DNS change has completed. Args: zone (str): DNS zone of the change. change_id (str): Identifier of the change. Returns: Boolean
def enable_nvm(): '''add to ~/.bashrc: Export of $NVM env variable and load nvm command.''' bash_snippet = '~/.bashrc_nvm' install_file_legacy(path=bash_snippet) prefix = flo('if [ -f {bash_snippet} ]; ') enabler = flo('if [ -f {bash_snippet} ]; then source {bash_snippet}; fi') if env.host == '...
add to ~/.bashrc: Export of $NVM env variable and load nvm command.
def get_tile_url(self, x, y, z, layer_id=None, feature_id=None, filter=None, extension="png"): """ Prepares a URL to get data (raster or vector) from a NamedMap or AnonymousMap :param x: The x tile :param y: The y tile :param z: The zoom level ...
Prepares a URL to get data (raster or vector) from a NamedMap or AnonymousMap :param x: The x tile :param y: The y tile :param z: The zoom level :param layer_id: Can be a number (referring to the # layer of your \ map), all layers of your map, or a list ...
def _init_mythril_dir() -> str: """ Initializes the mythril dir and config.ini file :return: The mythril dir's path """ try: mythril_dir = os.environ["MYTHRIL_DIR"] except KeyError: mythril_dir = os.path.join(os.path.expanduser("~"), ".mythril") ...
Initializes the mythril dir and config.ini file :return: The mythril dir's path
def fillna(data, other, join="left", dataset_join="left"): """Fill missing values in this object with data from the other object. Follows normal broadcasting and alignment rules. Parameters ---------- join : {'outer', 'inner', 'left', 'right'}, optional Method for joining the indexes of the...
Fill missing values in this object with data from the other object. Follows normal broadcasting and alignment rules. Parameters ---------- join : {'outer', 'inner', 'left', 'right'}, optional Method for joining the indexes of the passed objects along each dimension - 'outer': us...
def conditional_loss_ratio(loss_ratios, poes, probability): """ Return the loss ratio corresponding to the given PoE (Probability of Exceendance). We can have four cases: 1. If `probability` is in `poes` it takes the bigger corresponding loss_ratios. 2. If it is in `(poe1, poe2)` wher...
Return the loss ratio corresponding to the given PoE (Probability of Exceendance). We can have four cases: 1. If `probability` is in `poes` it takes the bigger corresponding loss_ratios. 2. If it is in `(poe1, poe2)` where both `poe1` and `poe2` are in `poes`, then we perform a linea...
def check_readable(self, timeout): """ Poll ``self.stdout`` and return True if it is readable. :param float timeout: seconds to wait I/O :return: True if readable, else False :rtype: boolean """ rlist, wlist, xlist = select.select([self._stdout], [], [], timeout)...
Poll ``self.stdout`` and return True if it is readable. :param float timeout: seconds to wait I/O :return: True if readable, else False :rtype: boolean
def update_plot_limits(ax, white_space): """Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d """ if ha...
Sets the limit options of a matplotlib plot. Args: ax: matplotlib axes white_space(float): whitespace added to surround the tight limit of the data Note: This relies on ax.dataLim (in 2d) and ax.[xy, zz]_dataLim being set in 3d
def adaptStandardLogging(loggerName, logCategory, targetModule): """ Make a logger from the standard library log through the Flumotion logging system. @param loggerName: The standard logger to adapt, e.g. 'library.module' @type loggerName: str @param logCategory: The Flumotion log category to u...
Make a logger from the standard library log through the Flumotion logging system. @param loggerName: The standard logger to adapt, e.g. 'library.module' @type loggerName: str @param logCategory: The Flumotion log category to use when reporting output from the standard logger, e....
def all(self): " execute query, get all list of lists" query,inputs = self._toedn() return self.db.q(query, inputs = inputs, limit = self._limit, offset = self._offset, history = self._history)
execute query, get all list of lists
def where_task(self, token_id, presented_pronunciation, confusion_probability): """Provide the prediction of the where task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param token_id: The token for which the prediction is being ...
Provide the prediction of the where task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param token_id: The token for which the prediction is being provided :param confusion_probability: The list or array of confusion probabilities...
def missing_output_files(self): """Make and return a dictionary of the missing output files. This returns a dictionary mapping filepath to list of links that produce the file as output. """ missing = self.check_output_files(return_found=False) ret_dict = {} for m...
Make and return a dictionary of the missing output files. This returns a dictionary mapping filepath to list of links that produce the file as output.
def _get_instance(self, iname, namespace, property_list, local_only, include_class_origin, include_qualifiers): """ Local method implements getinstance. This is generally used by other instance methods that need to get an instance from the repository. It at...
Local method implements getinstance. This is generally used by other instance methods that need to get an instance from the repository. It attempts to get the instance, copies it, and filters it for input parameters like localonly, includequalifiers, and propertylist. R...
def cumulative_value(self, slip_moment, mmax, mag_value, bbar, dbar): ''' Returns the rate of events with M > mag_value :param float slip_moment: Product of slip (cm/yr) * Area (cm ^ 2) * shear_modulus (dyne-cm) :param float mmax: Maximum magnitude :param...
Returns the rate of events with M > mag_value :param float slip_moment: Product of slip (cm/yr) * Area (cm ^ 2) * shear_modulus (dyne-cm) :param float mmax: Maximum magnitude :param float mag_value: Magnitude value :param float bbar: \bar{...
def num_samples(self): """ Return the total number of samples. """ with audioread.audio_open(self.path) as f: return int(f.duration * f.samplerate)
Return the total number of samples.
def make_seg_table(workflow, seg_files, seg_names, out_dir, tags=None, title_text=None, description=None): """ Creates a node in the workflow for writing the segment summary table. Returns a File instances for the output file. """ seg_files = list(seg_files) seg_names = list(seg_na...
Creates a node in the workflow for writing the segment summary table. Returns a File instances for the output file.
def save_file(self, data, filename, size=None, thumbnail_size=None): """ Saves an image File :param data: FileStorage from Flask form upload field :param filename: Filename with full path """ max_size = size or self.max_size thumbnail_size = thumbnai...
Saves an image File :param data: FileStorage from Flask form upload field :param filename: Filename with full path
def getElement(self, attri, fname, numtype='cycNum'): ''' In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete ...
In this method instead of getting a particular column of data, the program gets a particular row of data for a particular element name. attri : string The name of the attribute we are looking for. A complete list of them can be obtained by calling >>> get('e...
def _prepare_headers(self, request, filter=None, order_by=None, group_by=[], page=None, page_size=None): """ Prepare headers for the given request Args: request: the NURESTRequest to send filter: string order_by: string group_by: list ...
Prepare headers for the given request Args: request: the NURESTRequest to send filter: string order_by: string group_by: list of names page: int page_size: int
def get_form_kwargs(self): """ Pass template pack argument """ kwargs = super(FormContainersMixin, self).get_form_kwargs() kwargs.update({ 'pack': "foundation-{}".format(self.kwargs.get('foundation_version')) }) return kwargs
Pass template pack argument
def _get_observation(self): """ Returns an OrderedDict containing observations [(name_string, np.array), ...]. Important keys: robot-state: contains robot-centric information. object-state: requires @self.use_object_obs to be True. contains object...
Returns an OrderedDict containing observations [(name_string, np.array), ...]. Important keys: robot-state: contains robot-centric information. object-state: requires @self.use_object_obs to be True. contains object-centric information. image: require...
def bulk_copy(self, ids): """Bulk copy a set of devices. :param ids: Int list of device IDs. :return: :class:`devices.Device <devices.Device>` list """ schema = DeviceSchema() return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema)
Bulk copy a set of devices. :param ids: Int list of device IDs. :return: :class:`devices.Device <devices.Device>` list
def load_file(filename, out=sys.stdout): """ load a Python source file and compile it to byte-code _load_file(filename: string): code_object filename: name of file containing Python source code (normally a .py) code_object: code_object compiled from this source code This function...
load a Python source file and compile it to byte-code _load_file(filename: string): code_object filename: name of file containing Python source code (normally a .py) code_object: code_object compiled from this source code This function does NOT write any file!
def remove(self, name=None, prefix=None, pkgs=None, all_=False): """ Remove a package (from an environment) by name. Returns { success: bool, (this is always true), (other information) } """ logger.debug(str((prefix, pkgs))) cmd_list = ['...
Remove a package (from an environment) by name. Returns { success: bool, (this is always true), (other information) }
def modify_binding(site, binding, hostheader=None, ipaddress=None, port=None, sslflags=None): ''' Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the binding. .. versionadded:: 2017.7.0 Args: site (str): The IIS site name. binding (str): The bin...
Modify an IIS Web Binding. Use ``site`` and ``binding`` to target the binding. .. versionadded:: 2017.7.0 Args: site (str): The IIS site name. binding (str): The binding to edit. This is a combination of the IP address, port, and hostheader. It is in the following format: ...
def country_code_by_name(self, hostname): """ Returns 2-letter country code (e.g. US) from hostname. :arg hostname: Hostname (e.g. example.com) """ addr = self._gethostbyname(hostname) return self.country_code_by_addr(addr)
Returns 2-letter country code (e.g. US) from hostname. :arg hostname: Hostname (e.g. example.com)
async def close(self): """|coro| Closes the connection to discord. """ if self._closed: return await self.http.close() self._closed = True for voice in self.voice_clients: try: await voice.disconnect() except ...
|coro| Closes the connection to discord.
def log(self, obj): ''' Commit an arbitrary (picklable) object to the log ''' entries = self.get() entries.append(obj) # Only log the last |n| entries if set if self._size > 0: entries = entries[-self._size:] self._write_entries(entries)
Commit an arbitrary (picklable) object to the log
def get_success_url(self): """Reverses the ``redis_metric_aggregate_detail`` URL using ``self.metric_slugs`` as an argument.""" slugs = '+'.join(self.metric_slugs) url = reverse('redis_metric_aggregate_detail', args=[slugs]) # Django 1.6 quotes reversed URLs, which changes + into...
Reverses the ``redis_metric_aggregate_detail`` URL using ``self.metric_slugs`` as an argument.
def attachmethod(target): ''' Reference: https://blog.tonyseek.com/post/open-class-in-python/ class Spam(object): pass @attach_method(Spam) def egg1(self, name): print((self, name)) spam1 = Spam() # OpenClass 加入的方法 egg1 可用 spam1.egg1("Test1") # 输出Test1 ''' ...
Reference: https://blog.tonyseek.com/post/open-class-in-python/ class Spam(object): pass @attach_method(Spam) def egg1(self, name): print((self, name)) spam1 = Spam() # OpenClass 加入的方法 egg1 可用 spam1.egg1("Test1") # 输出Test1
def compile_geo(d): """ Compile top-level Geography dictionary. :param d: :return: """ logger_excel.info("enter compile_geo") d2 = OrderedDict() # get max number of sites, or number of coordinate points given. num_loc = _get_num_locations(d) # if there's one more than one locat...
Compile top-level Geography dictionary. :param d: :return:
def set_cookie(name, value): """Sets a cookie and redirects to cookie list. --- tags: - Cookies parameters: - in: path name: name type: string - in: path name: value type: string produces: - text/plain responses: 200: descript...
Sets a cookie and redirects to cookie list. --- tags: - Cookies parameters: - in: path name: name type: string - in: path name: value type: string produces: - text/plain responses: 200: description: Set cookies and redirects to co...
def _parse_prop(search, proplist): """Extract property value from record using the given urn search filter.""" props = [i for i in proplist if all(item in i['urn'].items() for item in search.items())] if len(props) > 0: return props[0]['value'][list(props[0]['value'].keys())[0]]
Extract property value from record using the given urn search filter.
def headers(params={}): """This decorator adds the headers passed in to the response http://flask.pocoo.org/snippets/100/ """ def decorator(f): if inspect.isclass(f): h = headers(params) apply_function_to_members(f, h) return f @functools.wraps(f) ...
This decorator adds the headers passed in to the response http://flask.pocoo.org/snippets/100/
def _set_font(self, family, size, bold, italic): """ Set the font properties of all the text in this text frame to *family*, *size*, *bold*, and *italic*. """ def iter_rPrs(txBody): for p in txBody.p_lst: for elm in p.content_children: ...
Set the font properties of all the text in this text frame to *family*, *size*, *bold*, and *italic*.
def get_wordpress(self, service_id, version_number, name): """Get information on a specific wordpress.""" content = self._fetch("/service/%s/version/%d/wordpress/%s" % (service_id, version_number, name)) return FastlyWordpress(self, content)
Get information on a specific wordpress.
def parse_command_only(self, rawinput: str) -> Statement: """Partially parse input into a Statement object. The command is identified, and shortcuts and aliases are expanded. Multiline commands are identified, but terminators and output redirection are not parsed. This method i...
Partially parse input into a Statement object. The command is identified, and shortcuts and aliases are expanded. Multiline commands are identified, but terminators and output redirection are not parsed. This method is used by tab completion code and therefore must not generate...
def set_style(style, mpl=False, **kwargs): """ If mpl is False accept either style name or a TStyle instance. If mpl is True accept either style name or a matplotlib.rcParams-like dictionary """ if mpl: import matplotlib as mpl style_dictionary = {} if isinstance(style, ...
If mpl is False accept either style name or a TStyle instance. If mpl is True accept either style name or a matplotlib.rcParams-like dictionary
def Open(self): """Connects to the database and creates the required tables. Raises: IOError: if the specified output file already exists. OSError: if the specified output file already exists. ValueError: if the filename is not set. """ if not self._filename: raise ValueError('M...
Connects to the database and creates the required tables. Raises: IOError: if the specified output file already exists. OSError: if the specified output file already exists. ValueError: if the filename is not set.
def _open_url(url): """Open a HTTP connection to the URL and return a file-like object.""" response = requests.get(url, stream=True) if response.status_code != 200: raise IOError("Unable to download {}, HTTP {}".format(url, response.status_code)) return response
Open a HTTP connection to the URL and return a file-like object.
def render_to_response(self, *args, **kwargs): '''Canonicalize the URL if the slug changed''' if self.request.path != self.object.get_absolute_url(): return HttpResponseRedirect(self.object.get_absolute_url()) return super(TalkView, self).render_to_response(*args, **kwargs)
Canonicalize the URL if the slug changed
def _evaluate_barycentric(nodes, degree, lambda1, lambda2, lambda3): r"""Compute a point on a surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)` for a B |eacute| zier surface / triangle defined by ``nodes``. .. note:: There is also a Fortran implementation of this functio...
r"""Compute a point on a surface. Evaluates :math:`B\left(\lambda_1, \lambda_2, \lambda_3\right)` for a B |eacute| zier surface / triangle defined by ``nodes``. .. note:: There is also a Fortran implementation of this function, which will be used if it can be built. Args: nodes...
def handle_button(self, event, event_type): """Convert the button information from quartz into evdev format.""" # 0 for left # 1 for right # 2 for middle/center # 3 for side mouse_button_number = self._get_mouse_button_number(event) # Identify buttons 3,4,5 ...
Convert the button information from quartz into evdev format.
def get_reply_states(self, string, dataset): """Get initial states from input string. Parameters ---------- string : `str` Input string. dataset : `str` Dataset key. Returns ------- `list` of `list` of `str` """ wo...
Get initial states from input string. Parameters ---------- string : `str` Input string. dataset : `str` Dataset key. Returns ------- `list` of `list` of `str`
def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): ''' Increment the value of a key CLI Example: .. code-block:: bash salt '*' memcached.increment <key> salt '*' memcached.increment <key> 2 ''' conn = _connect(host, port) _check_stats(conn) cur = get(ke...
Increment the value of a key CLI Example: .. code-block:: bash salt '*' memcached.increment <key> salt '*' memcached.increment <key> 2
def create_cell_renderer_combo(self, tree_view, title="title", assign=0, editable=False, model=None, function=None): """' Function creates a CellRendererCombo with title, model """ renderer_combo = Gtk.CellRendererCombo() renderer_combo.set_property('editable', editable) ...
Function creates a CellRendererCombo with title, model
def session_context(fn): """ Handles session setup and teardown """ @functools.wraps(fn) def wrap(*args, **kwargs): session = args[0].Session() # obtain from self result = fn(*args, session=session, **kwargs) session.close() return result return wrap
Handles session setup and teardown
def unescape_all(string): """Resolve all html entities to their corresponding unicode character""" def escape_single(matchobj): return _unicode_for_entity_with_name(matchobj.group(1)) return entities.sub(escape_single, string)
Resolve all html entities to their corresponding unicode character
def run_async(self, time_limit): ''' Run this module asynchronously and return a poller. ''' self.background = time_limit results = self.run() return results, poller.AsyncPoller(results, self)
Run this module asynchronously and return a poller.
def _maybe_validate_distributions(distributions, dtype_override, validate_args): """Checks that `distributions` satisfies all assumptions.""" assertions = [] if not _is_iterable(distributions) or not distributions: raise ValueError('`distributions` must be a list of one or more ' 'distri...
Checks that `distributions` satisfies all assumptions.
def remove_metadata_key(self, obj, key): """ Removes the specified key from the object's metadata. If the key does not exist in the metadata, nothing is done. """ meta_dict = {key: ""} return self.set_metadata(obj, meta_dict)
Removes the specified key from the object's metadata. If the key does not exist in the metadata, nothing is done.
def CheckInvalidIncrement(filename, clean_lines, linenum, error): """Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ ...
Checks for invalid increment *count++. For example following function: void increment_counter(int* count) { *count++; } is invalid, because it effectively does count++, moving pointer, and should be replaced with ++*count, (*count)++ or *count += 1. Args: filename: The name of the current file. ...
def access(i): """ Input: Can be dictionary or string (string will be converted to dictionary) { action module_uoa or CID -> converted to cid or (cid1) - if doesn't have = and doesn't start from -- or - or @ -> appended to...
Input: Can be dictionary or string (string will be converted to dictionary) { action module_uoa or CID -> converted to cid or (cid1) - if doesn't have = and doesn't start from -- or - or @ -> appended to cids[] (cid2...
def list(self, muted=values.unset, hold=values.unset, coaching=values.unset, limit=None, page_size=None): """ Lists ParticipantInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. ...
Lists ParticipantInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param bool muted: Whether to return only participants that are muted :param bool hold: Whether to return only participants that...
def run(self, command, **kwargs): """Run a command on the remote host. This is just a wrapper around ``RemoteTask(self.hostname, ...)`` """ return RemoteTask(self.hostname, command, identity_file=self._identity_file, **kwargs)
Run a command on the remote host. This is just a wrapper around ``RemoteTask(self.hostname, ...)``
def children(self): """ Returns the children in this group. :return [<QtGui.QListWidgetItem>, ..] """ new_refs = set() output = [] for ref in self._children: item = ref() if item is not None: output.a...
Returns the children in this group. :return [<QtGui.QListWidgetItem>, ..]
def euler(self): """TODO DEPRECATE THIS?""" e_xyz = transformations.euler_from_matrix(self.rotation, 'sxyz') return np.array([180.0 / np.pi * a for a in e_xyz])
TODO DEPRECATE THIS?
def login(self): """ 用户登陆 :return: true if login successfully """ self._cookies = self.__get_rndnum_cookies() # print self._cookies UserCode, UserPwd = self._userid, self._userpsw Validate = self._cookies['LogonNumber'] Submit = '%CC%E1+%BD%BB' ...
用户登陆 :return: true if login successfully
def update_insert_values(bel_resource: Mapping, mapping: Mapping[str, Tuple[str, str]], values: Dict[str, str]) -> None: """Update the value dictionary with a BEL resource dictionary.""" for database_column, (section, key) in mapping.items(): if section in bel_resource and key in bel_resource[section]: ...
Update the value dictionary with a BEL resource dictionary.
def last_day(self): """Return the last day of Yom Tov or Shabbat. This is useful for three-day holidays, for example: it will return the last in a string of Yom Tov + Shabbat. If this HDate is Shabbat followed by no Yom Tov, returns the Saturday. If this HDate is neither Yom Tov...
Return the last day of Yom Tov or Shabbat. This is useful for three-day holidays, for example: it will return the last in a string of Yom Tov + Shabbat. If this HDate is Shabbat followed by no Yom Tov, returns the Saturday. If this HDate is neither Yom Tov, nor Shabbat, this just return...
def XYZ_to_galcencyl(X,Y,Z,Xsun=1.,Zsun=0.,_extra_rot=True): """ NAME: XYZ_to_galcencyl PURPOSE: transform XYZ coordinates (wrt Sun) to cylindrical Galactocentric coordinates INPUT: X - X Y - Y Z - Z Xsun - cylindrical distance to the GC Z...
NAME: XYZ_to_galcencyl PURPOSE: transform XYZ coordinates (wrt Sun) to cylindrical Galactocentric coordinates INPUT: X - X Y - Y Z - Z Xsun - cylindrical distance to the GC Zsun - Sun's height above the midplane _extra_rot= (True) if True,...
async def load_variant(obj, elem, elem_type=None, params=None, field_archiver=None, wrapped=None): """ Loads variant from the obj representation :param obj: :param elem: :param elem_type: :param params: :param field_archiver: :param wrapped: :return: """ field_archiver = fiel...
Loads variant from the obj representation :param obj: :param elem: :param elem_type: :param params: :param field_archiver: :param wrapped: :return:
def about(): """ About box for aps. Gives version numbers for aps, NumPy, SciPy, Cython, and MatPlotLib. """ print("") print("aps: APS Journals API in Python for Humans") print("Copyright (c) 2017 and later.") print("Xiao Shang") print("") print("aps Version: %s" % aps.__v...
About box for aps. Gives version numbers for aps, NumPy, SciPy, Cython, and MatPlotLib.
def double(self, column, total=None, places=None): """ Create a new double column on the table. :param column: The column :type column: str :type total: int :type places: 2 :rtype: Fluent """ return self._add_column("double", column, total=tota...
Create a new double column on the table. :param column: The column :type column: str :type total: int :type places: 2 :rtype: Fluent
def append_num_column(self, text: str, index: int): """ Add value to the output row, width based on index """ width = self.columns[index]["width"] return f"{text:>{width}}"
Add value to the output row, width based on index
def search_tor_node(self, data_type, data): """Lookup an artifact to check if it is a known tor exit node. :param data_type: The artifact type. Must be one of 'ip', 'fqdn' or 'domain' :param data: The artifact to lookup :type data_type: str :type data: ...
Lookup an artifact to check if it is a known tor exit node. :param data_type: The artifact type. Must be one of 'ip', 'fqdn' or 'domain' :param data: The artifact to lookup :type data_type: str :type data: str :return: Data relative to the tor node. If ...
def coarsegrain(F, sets): r"""Coarse-grains the flux to the given sets. Parameters ---------- F : (n, n) ndarray or scipy.sparse matrix Matrix of flux values between pairs of states. sets : list of array-like of ints The sets of states onto which the flux is coarse-grained. Not...
r"""Coarse-grains the flux to the given sets. Parameters ---------- F : (n, n) ndarray or scipy.sparse matrix Matrix of flux values between pairs of states. sets : list of array-like of ints The sets of states onto which the flux is coarse-grained. Notes ----- The coarse gr...
def _read_data(self): """ Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled. """ while True: try: data = yield from self._socket.recv() except asyncio.CancelledError: ...
Reads data from the connection and adds it to _push_packet, until the connection is closed or the task in cancelled.
def spin_sz(self): """Returns the z-component of the spin of the secondary mass.""" return conversions.secondary_spin(self.mass1, self.mass2, self.spin1z, self.spin2z)
Returns the z-component of the spin of the secondary mass.