positive
stringlengths
100
30.3k
anchor
stringlengths
1
15k
def group_members_remove(self, device_group_id, body, **kwargs): # noqa: E501 """Remove a device from a group # noqa: E501 Remove one device from a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchrono...
Remove a device from a group # noqa: E501 Remove one device from a group # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> thread = api.group_members_remove(device_group_id, body, asynchronous=...
def fill_array(self, array, weights=None): """ Fill this histogram with a NumPy array """ try: try: from root_numpy import fill_hist as fill_func except ImportError: from root_numpy import fill_array as fill_func except Impo...
Fill this histogram with a NumPy array
def report(self): """Creates sistr reports""" # Initialise strings to store report data header = '\t'.join(self.headers) + '\n' data = '' for sample in self.metadata: if sample.general.bestassemblyfile != 'NA': # Each strain is a fresh row ...
Creates sistr reports
def get_list(sld, tld): ''' Gets a list of DNS servers associated with the requested domain. returns a dictionary of information about requested domain sld SLD of the domain name tld TLD of the domain name CLI Example: .. code-block:: bash salt 'my-minion' namec...
Gets a list of DNS servers associated with the requested domain. returns a dictionary of information about requested domain sld SLD of the domain name tld TLD of the domain name CLI Example: .. code-block:: bash salt 'my-minion' namecheap_domains_dns.get_list sld tld
def prune(self): """ Remove anything which shouldn't be displayed. """ def to_include(obj): inc = obj.permission in self.display if self.settings['hide_undoc'].lower() == 'true' and not obj.doc: inc = False return inc if self.o...
Remove anything which shouldn't be displayed.
def _concrete_instance(self, instance_doc): """Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance` """ ...
Concretize an instance document. :param dict instance_doc: A document describing an instance. Should come from the API. :returns: A subclass of :py:class:`bases.BaseInstance`, or None. :rtype: :py:class:`bases.BaseInstance`
def _emit(self, **kwargs): ''' Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy. ''' oc_dict = {} for mapping, result_key in kwargs['mapping']['variables'].items(): result = kwargs[result_key]...
Emit an OpenConfig object given a certain combination of fields mappeed in the config to the corresponding hierarchy.
def parameter_list(data): """Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Parameter list. :rtype: dict """ items = [] for item in data: param = Parameter(item[...
Create a list of parameter objects from a dict. :param data: Dictionary to convert to parameter list. :type data: dict :return: Parameter list. :rtype: dict
def stats(request, date_offset=0, fields=None, title_prefix=None, model='WikiItem'): """ In addition to chart data in data['chart'], send statistics data to view in data['stats'] """ data = {} modified_chart_data = data['chart']['chartdata'] if 'y2' in data['chart']['chartdata']: matrix...
In addition to chart data in data['chart'], send statistics data to view in data['stats']
def set_environment_variable(self, name, value): """ Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this...
Set the value of an environment variable. .. warning:: The server may reject this request depending on its ``AcceptEnv`` setting; such rejections will fail silently (which is common client practice for this particular request type). Make sure you understand your ...
def _getPhrase( self, i, sentence, NPlabels ): ''' Fetches the full length phrase from the position i based on the existing NP phrase annotations (from NPlabels); Returns list of sentence tokens in the phrase, and indices of the phrase; ''' ...
Fetches the full length phrase from the position i based on the existing NP phrase annotations (from NPlabels); Returns list of sentence tokens in the phrase, and indices of the phrase;
def as_xml_part(self, basename="/tmp/sitemap.xml", part_number=0): """Return a string of component sitemap number part_number. Used in the case of a large list that is split into component sitemaps. basename is used to create "index" links to the sitemapindex Q - what timestam...
Return a string of component sitemap number part_number. Used in the case of a large list that is split into component sitemaps. basename is used to create "index" links to the sitemapindex Q - what timestamp should be used?
def job_priority_index(job_priorities): '''This structure helps with finding data from the job priorities table''' jp_index = {} # Creating this data structure which reduces how many times we iterate through the DB rows for jp in job_priorities: key = jp.unique_identifier() # This is gu...
This structure helps with finding data from the job priorities table
def _pdb_frame(self): """Return current Pdb frame if there is any""" if self._pdb_obj is not None and self._pdb_obj.curframe is not None: return self._pdb_obj.curframe
Return current Pdb frame if there is any
def add_code_challenge(request_args, service, **kwargs): """ PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :para...
PKCE RFC 7636 support To be added as a post_construct method to an :py:class:`oidcservice.oidc.service.Authorization` instance :param service: The service that uses this function :param request_args: Set of request arguments :param kwargs: Extra set of keyword arguments :return: Updated set of ...
def ProcessHttpRequest(self, http_request): """Hook for pre-processing of http requests.""" http_request.headers.update(self.additional_http_headers) if self.log_request: logging.info('Making http %s to %s', http_request.http_method, http_request.url) ...
Hook for pre-processing of http requests.
def _iris_cell_methods_to_str(cell_methods_obj): """ Converts a Iris cell methods into a string """ cell_methods = [] for cell_method in cell_methods_obj: names = ''.join(['{}: '.format(n) for n in cell_method.coord_names]) intervals = ' '.join(['interval: {}'.format(interval) ...
Converts a Iris cell methods into a string
def iter_distribution_names(self): """Yield all packages, modules, and extension names in distribution""" for pkg in self.packages or (): yield pkg for module in self.py_modules or (): yield module for ext in self.ext_modules or (): if isinstance(ex...
Yield all packages, modules, and extension names in distribution
def domain_create(self, domain, master=True, **kwargs): """ Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Lin...
Registers a new Domain on the acting user's account. Make sure to point your registrar to Linode's nameservers so that Linode's DNS manager will correctly serve your domain. :param domain: The domain to register to Linode's DNS manager. :type domain: str :param master: Whether ...
def get_prices(self) -> List[PriceModel]: """ Returns all available prices for security """ # return self.security.prices.order_by(Price.date) from pricedb.dal import Price pricedb = PriceDbApplication() repo = pricedb.get_price_repository() query = (repo.query(Price) ...
Returns all available prices for security
def _parse_oratab(sid): ''' Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions ''' if __grains__.get('kernel') in ('Linux', 'AIX', 'FreeBSD', 'OpenBSD', 'NetBSD'): ORATAB = '/etc/oratab' elif __grains__.get('kernel') in 'SunOS': ORATAB = '...
Return ORACLE_HOME for a given SID found in oratab Note: only works with Unix-like minions
def drawPoints(self, pointPen, filterRedundantPoints=False): """draw self using pointPen""" if filterRedundantPoints: pointPen = FilterRedundantPointPen(pointPen) for contour in self.contours: pointPen.beginPath(identifier=contour["identifier"]) for segmentTyp...
draw self using pointPen
def get_field(self, offset, length, format): """Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: ...
Returns unpacked Python struct array. Args: offset (int): offset to byte array within structure length (int): how many bytes to unpack format (str): Python struct format string for unpacking See Also: https://docs.python.org/2/library/struct.html#format-...
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
Incrementally updates the tree with the given sample record.
def truncatechars(value, arg): """ Truncates a string after a certain number of chars. Argument: Number of chars to truncate after. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. if len(value) > length: return...
Truncates a string after a certain number of chars. Argument: Number of chars to truncate after.
def refresh_token(self, **kwargs): """Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetch_token``. """ if 'client_secret' not in kwargs: kwargs.update(client_secret=se...
Refresh the authentication token. :param str refresh_token: The refresh token to use. May be empty if retrieved with ``fetch_token``.
def install(self, plugin): ''' Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API. ''' if hasattr(plugin, 'setup'): plugin.setup(s...
Add a plugin to the list of plugins and prepare it for beeing applied to all routes of this application. A plugin may be a simple decorator or an object that implements the :class:`Plugin` API.
def is_snp(reference_bases, alternate_bases): """ Return whether or not the variant is a SNP """ if len(reference_bases) > 1: return False for alt in alternate_bases: if alt is None: return False if alt not in ['A', 'C', 'G', 'T', 'N', '*']: return False r...
Return whether or not the variant is a SNP
def _list_gids(): ''' Return a list of gids in use ''' output = __salt__['cmd.run']( ['dscacheutil', '-q', 'group'], output_loglevel='quiet', python_shell=False ) ret = set() for line in salt.utils.itertools.split(output, '\n'): if line.startswith('gid:'): ...
Return a list of gids in use
def granted(self, lock): '''Return True if a previously requested lock has been granted''' unit = hookenv.local_unit() ts = self.requests[unit].get(lock) if ts and self.grants.get(unit, {}).get(lock) == ts: return True return False
Return True if a previously requested lock has been granted
def load_probe_file(recording, probe_file, channel_map=None, channel_groups=None): '''Loads channel information into recording extractor. If a .prb file is given, then 'location' and 'group' information for each channel is stored. If a .csv file is given, then it will only store 'location' Parameters ...
Loads channel information into recording extractor. If a .prb file is given, then 'location' and 'group' information for each channel is stored. If a .csv file is given, then it will only store 'location' Parameters ---------- recording: RecordingExtractor The recording extractor to channel...
def get_nbt(self, x, z): """ Return a NBTFile of the specified chunk. Raise InconceivedChunk if the chunk is not included in the file. """ # TODO: cache results? data = self.get_blockdata(x, z) # This may raise a RegionFileFormatError. data = BytesIO(data) ...
Return a NBTFile of the specified chunk. Raise InconceivedChunk if the chunk is not included in the file.
def _dispose(self): """Dispose of the pool for this instance, closing all connections.""" self.close() # _DBProxy.dispose doesn't actually call dispose on the pool conn_params = self.get_connection_params() key = db_pool._serialize(**conn_params) try: pool = d...
Dispose of the pool for this instance, closing all connections.
def plotJacobi(self,*args,**kwargs): """ NAME: plotE PURPOSE: plot Jacobi(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS) """ ...
NAME: plotE PURPOSE: plot Jacobi(.) along the orbit INPUT: bovy_plot.bovy_plot inputs OUTPUT: figure to output device HISTORY: 2014-06-16 - Written - Bovy (IAS)
def find_element_by_xpath(self, xpath): """ Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_ """ ...
Finds an element by xpath. :param xpath: The xpath locator of the element to find. :return: See html5lib xpath expressions `here <https://docs.python.org/2/library/xml.etree.elementtree.html#supported-xpath-syntax>`_
def dump_json_file(json_data, pwd_dir_path, dump_file_name): """ dump json data to file """ class PythonObjectEncoder(json.JSONEncoder): def default(self, obj): try: return super().default(self, obj) except TypeError: return str(obj) logs_...
dump json data to file
def Flemmer_Banks(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \frac{24}{Re}10^E E = 0.383Re^{0.356}-0.207Re^{0.396} - \frac{0.143}{1+(\log_{10} Re)^2} Parameters ---------- Re : float Reynolds n...
r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \frac{24}{Re}10^E E = 0.383Re^{0.356}-0.207Re^{0.396} - \frac{0.143}{1+(\log_{10} Re)^2} Parameters ---------- Re : float Reynolds number of the sphere, [-] ...
async def handle_action(self, action: str, request_id: str, **kwargs): """ run the action. """ try: await self.check_permissions(action, **kwargs) if action not in self.actions: raise MethodNotAllowed(method=action) content, status = ...
run the action.
def service_password_encryption(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") service = ET.SubElement(config, "service", xmlns="urn:brocade.com:mgmt:brocade-aaa") password_encryption = ET.SubElement(service, "password-encryption") callback = k...
Auto Generated Code
def update_session(self, alias, headers=None, cookies=None): """Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session """ session = self._cache.switch(alias) ses...
Update Session Headers: update a HTTP Session Headers ``alias`` Robot Framework alias to identify the session ``headers`` Dictionary of headers merge into session
def derive(self): '''Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1))''' #res = [0] * (len(self)-1) # pre-allocate the list, it will be one item shorter because the constant coefficient (x^0) will be removed #for i in _range(2, len(self)+1): # start at 2 to skip the first...
Compute the formal derivative of the polynomial: sum(i*coeff[i] x^(i-1))
def contribute_to_class(self, cls, name): """ Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``. """ super(KeywordsField, self).contribute_to_class(cls, name) string_field_name = list(self.fields.keys())[0] % \ ...
Swap out any reference to ``KeywordsField`` with the ``KEYWORDS_FIELD_string`` field in ``search_fields``.
def _parse_header(self, data): """Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list """ return_list = [] headers = data.split(':') for header in headers: he...
Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list
def burst_run(self): """ Run CPU as fast as Python can... """ # https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots... get_and_call_next_op = self.get_and_call_next_op for __ in range(self.outer_burst_op_count): for __ in range(self.inner_burst_op_count): ...
Run CPU as fast as Python can...
def graph_dot(self): """ Export a graph of the data in dot format. """ default_graphviz_template = """ digraph role_dependencies { size="%size" dpi=%dpi ratio="fill" landscape=false rankdir="BT"; node [shape = "box", style = ...
Export a graph of the data in dot format.
def set_parallel_multiple(self, value): """ Setter for 'parallel_multiple' field. :param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value. """ if value is None or not isinstance(value, bool): raise TypeError("Paralle...
Setter for 'parallel_multiple' field. :param value - a new value of 'parallel_multiple' field. Must be a boolean type. Does not accept None value.
def binaryEntropyVectorized(x): """ Calculate entropy for a list of binary random variables :param x: (numpy array) the probability of the variable to be 1. :return: entropy: (numpy array) entropy """ entropy = - x*np.log2(x) - (1-x)*np.log2(1-x) entropy[x*(1 - x) == 0] = 0 return entropy
Calculate entropy for a list of binary random variables :param x: (numpy array) the probability of the variable to be 1. :return: entropy: (numpy array) entropy
def _setup_logging(): """Setup logging to log to nowhere by default. For details, see: http://docs.python.org/3/howto/logging.html#library-config Internal function. """ import logging logger = logging.getLogger('spotify-connect') handler = logging.NullHandler() logger.addHandler(h...
Setup logging to log to nowhere by default. For details, see: http://docs.python.org/3/howto/logging.html#library-config Internal function.
def pdf_new(self, x, mu, sigma, skw): """ function with different parameterisation :param x: :param mu: mean :param sigma: sigma :param skw: skewness :return: """ if skw > 1 or skw < -1: print("skewness %s out of range" % skw) ...
function with different parameterisation :param x: :param mu: mean :param sigma: sigma :param skw: skewness :return:
def show_support_save_status_output_show_support_save_status_message(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_support_save_status = ET.Element("show_support_save_status") config = show_support_save_status output = ET.SubElement(show_s...
Auto Generated Code
def set_uppercase(self, uppercase): """Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise. """ for row in self.rows: for key in row.keys: if type(key) == VKey: if uppercase: key.value ...
Sets layout uppercase state. :param uppercase: True if uppercase, False otherwise.
def potential_purviews(self, direction, mechanism, purviews=False): """Return all purviews that could belong to the |MIC|/|MIE|. Filters out trivially-reducible purviews. Args: direction (str): Either |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism of interes...
Return all purviews that could belong to the |MIC|/|MIE|. Filters out trivially-reducible purviews. Args: direction (str): Either |CAUSE| or |EFFECT|. mechanism (tuple[int]): The mechanism of interest. Keyword Args: purviews (tuple[int]): Optional subset of...
def get_none_policy_text(none_policy, # type: int verbose=False # type: bool ): """ Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return: """ if none_policy is N...
Returns a user-friendly description of a NonePolicy taking into account NoneArgPolicy :param none_policy: :param verbose: :return:
def findall_operations_between(self, start_frontier: Dict[ops.Qid, int], end_frontier: Dict[ops.Qid, int], omit_crossing_operations: bool = False ) -> List[Tuple[int, ops.Operation...
Finds operations between the two given frontiers. If a qubit is in `start_frontier` but not `end_frontier`, its end index defaults to the end of the circuit. If a qubit is in `end_frontier` but not `start_frontier`, its start index defaults to the start of the circuit. Operations on qub...
def wrapinstance(ptr, base=None): """convert a pointer to a Qt class instance (PySide/PyQt compatible)""" if ptr is None: return None ptr = long(ptr) # Ensure type from wishlib.qt import active, QtCore, QtGui if active == "PySide": import shiboken if base is None: ...
convert a pointer to a Qt class instance (PySide/PyQt compatible)
def image_top(body_output, targets, model_hparams, vocab_size): """Top transformation for images.""" del targets # unused arg # TODO(lukaszkaiser): is this a universal enough way to get channels? num_channels = model_hparams.problem.num_channels with tf.variable_scope("rgb_softmax"): body_output_shape = ...
Top transformation for images.
def createContactItem(self, person, label, number): """ Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} ...
Create a L{PhoneNumber} item for C{number}, associated with C{person}. @type person: L{Person} @param label: The value to use for the I{label} attribute of the new L{PhoneNumber} item. @type label: C{unicode} @param number: The value to use for the I{number} attribute of the n...
def execute_pending_service_agreements(storage_path, account, actor_type, did_resolver_fn): """ Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, ...
Iterates over pending service agreements recorded in the local storage, fetches their service definitions, and subscribes to service agreement events. :param storage_path: storage path for the internal db, str :param account: :param actor_type: :param did_resolver_fn: :return:
def clean(ctx): """Clean previously built package artifacts. """ ctx.run(f"python setup.py clean") dist = ROOT.joinpath("dist") build = ROOT.joinpath("build") print(f"[clean] Removing {dist} and {build}") if dist.exists(): shutil.rmtree(str(dist)) if build.exists(): shuti...
Clean previously built package artifacts.
def set_current(self, channel, value, unit='A'): '''Setting current of current source ''' dac_offset = self._ch_cal[channel]['DAC']['offset'] dac_gain = self._ch_cal[channel]['DAC']['gain'] if unit == 'raw': value = value elif unit == 'A': value = ...
Setting current of current source
def right_censor_lifetimes(lifetimes, max_, min_=0): """ Right censor the deaths, uniformly lifetimes: (n,) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur Returns The actual observations including uniform right ...
Right censor the deaths, uniformly lifetimes: (n,) array of positive random variables max_: the max time a censorship can occur min_: the min time a censorship can occur Returns The actual observations including uniform right censoring, and D_i (observed death or did not) I think...
def is_array(type_): """returns True, if type represents C++ array type, False otherwise""" nake_type = remove_alias(type_) nake_type = remove_reference(nake_type) nake_type = remove_cv(nake_type) return isinstance(nake_type, cpptypes.array_t)
returns True, if type represents C++ array type, False otherwise
def stop_listener_thread(self): """ Stop listener thread running in the background """ if self.sync_thread: self.should_listen = False self.sync_thread.join() self.sync_thread = None
Stop listener thread running in the background
def plot_world_with_plotly(world, species_list=None, max_count=1000): """ Plot a World on IPython Notebook """ if isinstance(world, str): from .simulation import load_world world = load_world(world) if species_list is None: species_list = [sp.serial() for sp in world.list_sp...
Plot a World on IPython Notebook
def get_key_policy(key_id, policy_name, region=None, key=None, keyid=None, profile=None): ''' Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy ''' conn = _get_conn(region=region, key=key, keyid=keyid, profil...
Get the policy for the specified key. CLI example:: salt myminion boto_kms.get_key_policy 'alias/mykey' mypolicy
def duration_to_text(self, duration): """ Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a num...
Return the textual representation of the given `duration`. The duration can either be a tuple of :class:`datetime.time` objects, or a simple number. The returned text will be either a hhmm-hhmm string (if the given `duration` is a tuple) or a number.
def _run(self, url_path, headers=None, **kwargs): """ Requests API """ url = self._construct_url(url_path) payload = kwargs payload.update({'api_token': self.api_token}) return self._make_request(url, payload, headers)
Requests API
def disable_ipython(self): """ Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook. """ from IPython.core.getipython import get_ipython self.ipython_enabled = F...
Disable plotting in the iPython notebook. After disabling, lightning plots will be produced in your lightning server, but will not appear in the notebook.
def _get_cache(self): """ Return the cache to use for thundering herd protection, etc. """ if not self._cache: self._cache = get_cache(self.app) return self._cache
Return the cache to use for thundering herd protection, etc.
def probabilities(self, choosers, alternatives): """ Returns alternative probabilties for each chooser segment as a dictionary keyed by segment name. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households...
Returns alternative probabilties for each chooser segment as a dictionary keyed by segment name. Parameters ---------- choosers : pandas.DataFrame Table describing the agents making choices, e.g. households. Must have a column matching the .segmentation_col attri...
def reset_new_request(self): """Remove the non-sense args from the self.ignore, return self.new_request""" raw_url = self.new_request['url'] parsed_url = urlparse(raw_url) qsl = parse_qsl(parsed_url.query) new_url = self._join_url( parsed_url, [i for i in qsl if i not...
Remove the non-sense args from the self.ignore, return self.new_request
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Picker(self.get_context(), None, d.style or '@attr/numberPickerStyle')
Create the underlying widget.
def setLocked(self, state, force=False): """ Sets the locked state for this panel to the inputed state. :param state | <bool> """ if not force and state == self._locked: return self._locked = state tabbar = self.tabBar() ...
Sets the locked state for this panel to the inputed state. :param state | <bool>
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'credential_id') and self.credential_id is not None: _dict['credential_id'] = self.credential_id if hasattr(self, 'source_type') and self.source_type is not None: ...
Return a json dictionary representing this model.
def _add_auth_headers(self, base): """Attach the acces_token to a request.""" if 'access_token' in self.creds: return _extend(base, { 'authorization': 'Bearer ' + self.creds['access_token'] }) return base
Attach the acces_token to a request.
def estimateHeritabilities(self, K, verbose=False): """ estimate variance components and fixed effects from a single trait model having only two terms """ # Fit single trait model varg = SP.zeros(self.P) varn = SP.zeros(self.P) fixed = SP.zeros(...
estimate variance components and fixed effects from a single trait model having only two terms
def get_action_arguments(self, service_name, action_name): """ Returns a list of tuples with all known arguments for the given service- and action-name combination. The tuples contain the argument-name, direction and data_type. """ return self.services[service_name].actio...
Returns a list of tuples with all known arguments for the given service- and action-name combination. The tuples contain the argument-name, direction and data_type.
def _normalize_stack(graphobjs): """Convert runs of qQ's in the stack into single graphobjs""" for operands, operator in graphobjs: operator = str(operator) if re.match(r'Q*q+$', operator): # Zero or more Q, one or more q for char in operator: # Split into individual ...
Convert runs of qQ's in the stack into single graphobjs
def sigmascale (nsigma): """Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the n-sigma confidence interval? Negative or zero values result in Na...
Say we take a Gaussian bivariate and convert the parameters of the distribution to an ellipse (major, minor, PA). By what factor should we scale those axes to make the area of the ellipse correspond to the n-sigma confidence interval? Negative or zero values result in NaN.
def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a charact...
r""" Replace occurrences of pattern/regex in the Series/Index with some other string. Equivalent to :meth:`str.replace` or :func:`re.sub`. Parameters ---------- pat : str or compiled regex String can be a character sequence or regular expression. .. versionadded:: 0.20.0 ...
def Start(self): """Starts the profiler.""" filename = '{0:s}-{1:s}.csv.gz'.format( self._FILENAME_PREFIX, self._identifier) if self._path: filename = os.path.join(self._path, filename) self._sample_file = gzip.open(filename, 'wb') self._WritesString(self._FILE_HEADER) self._star...
Starts the profiler.
def write(self, inputdata): """Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Pytho...
Write to a port on dummy_serial. Args: inputdata (string/bytes): data for sending to the port on dummy_serial. Will affect the response for subsequent read operations. Note that for Python2, the inputdata should be a **string**. For Python3 it should be of type **bytes**.
def export_event_params(filename, params, count=None, density=None): """Write event analysis data to CSV.""" heading_row_1 = ['Segment index', 'Start time', 'End time', 'Stitches', 'Stage', 'Cycle', ...
Write event analysis data to CSV.
def _make_request(session, url, argument=None, params=None, raw=False): """Make a request to API endpoint.""" if not params: params = {} params['key'] = session.auth.key try: if argument: request_url = '{}{}{}{}'.format(session.auth.base_url, VOOBLY_API_URL, url, argument) ...
Make a request to API endpoint.
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type i...
Draw this time scale to PNG. :param image: the image to draw onto :param int h_zoom: the horizontal zoom :param int v_zoom: the vertical zoom :param int current_y: the current y offset, in modules :type image: :class:`PIL.Image`
def set_options(self, options): """ Sets instance variables based on an options dict """ # COMMAND LINE OPTIONS self.wipe = options.get("wipe") self.test_run = options.get("test_run") self.quiet = options.get("test_run") self.container_name = options.get("...
Sets instance variables based on an options dict
def density(args): """ %prog density test.clm Estimate link density of contigs. """ p = OptionParser(density.__doc__) p.add_option("--save", default=False, action="store_true", help="Write log densitites of contigs to file") p.set_cpus() opts, args = p.parse_args(args) ...
%prog density test.clm Estimate link density of contigs.
def _from_dict(cls, _dict): """Initialize a Context object from a json dictionary.""" args = {} xtra = _dict.copy() if 'conversation_id' in _dict: args['conversation_id'] = _dict.get('conversation_id') del xtra['conversation_id'] if 'system' in _dict: ...
Initialize a Context object from a json dictionary.
def register_cli_argument(self, scope, dest, argtype, **kwargs): """ Add an argument to the argument registry :param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand') :type scope: str :param dest: The parameter/destination that this argument is for ...
Add an argument to the argument registry :param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand') :type scope: str :param dest: The parameter/destination that this argument is for :type dest: str :param argtype: The argument type for this com...
def set_prekeys_as_sent(self, prekeyIds): """ :param prekeyIds: :type prekeyIds: list :return: :rtype: """ logger.debug("set_prekeys_as_sent(prekeyIds=[%d prekeyIds])" % len(prekeyIds)) self._store.preKeyStore.setAsSent([prekey.getId() for prekey in prekey...
:param prekeyIds: :type prekeyIds: list :return: :rtype:
def _add_datetime_arraylike(self, other): """ Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray. """ if isinstance(other, np.ndarray): # At this point we have already checked that dtype is datetime64 from pandas.core.arrays import DatetimeArray ...
Add DatetimeArray/Index or ndarray[datetime64] to TimedeltaArray.
def command(self): """Returns a string representing the command you have to type to obtain the same packet""" f = [] for fn,fv in self.fields.items(): fld = self.get_field(fn) if isinstance(fv, Packet): fv = fv.command() elif fld.islist and fld...
Returns a string representing the command you have to type to obtain the same packet
def _generateFeatures(self): """ Generates a pool of features to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column. """ size = self.sensorInputSize bits = self.numInputBits self.features = []...
Generates a pool of features to be used for the experiments. For each index, numColumns SDR's are created, as locations for the same feature should be different for each column.
def get_maxsing(self,eigthresh=1.0e-5): """ Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns -----...
Get the number of singular components with a singular value ratio greater than or equal to eigthresh Parameters ---------- eigthresh : float the ratio of the largest to smallest singular value Returns ------- int : int number of singular ...
def get(self, key, side): """ Returns an edge given a particular key Parmeters ---------- key : tuple (te, be, le, re) tuple that identifies a tile side : str top, bottom, left, or right, which edge to return """ return getattr(self...
Returns an edge given a particular key Parmeters ---------- key : tuple (te, be, le, re) tuple that identifies a tile side : str top, bottom, left, or right, which edge to return
def post(self) -> Vpn: """ Creates the vpn with the given data. """ vpn = Vpn() session.add(vpn) self.update(vpn) session.flush() session.commit() return vpn, 201, { 'Location': url_for('vpn', vpn_id=vpn.id) }
Creates the vpn with the given data.
def RIBVRFRouteLimitExceeded_originator_switch_info_switchVcsId(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream") origin...
Auto Generated Code
def to_mask(self, method='exact', subpixels=5): """ Return a list of `~photutils.ApertureMask` objects, one for each aperture position. Parameters ---------- method : {'exact', 'center', 'subpixel'}, optional The method used to determine the overlap of the ap...
Return a list of `~photutils.ApertureMask` objects, one for each aperture position. Parameters ---------- method : {'exact', 'center', 'subpixel'}, optional The method used to determine the overlap of the aperture on the pixel grid. Not all options are available...
def delete(self, *args, **kwargs): """ custom delete method to update counts """ super(UpdateCountsMixin, self).delete(*args, **kwargs) self.update_count()
custom delete method to update counts
def replace_entities(self, html): """ Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced """ def fixup(text): """replace the htmlentities in some text""" ...
Replace htmlentities with unicode characters @Params html - html source to replace entities in @Returns String html with entities replaced