code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def verify_branch(branch_name): # type: (str) -> bool """ Verify if the given branch exists. Args: branch_name (str): The name of the branch to check. Returns: bool: **True** if a branch with name *branch_name* exits, **False** otherwise. """ try: sh...
Verify if the given branch exists. Args: branch_name (str): The name of the branch to check. Returns: bool: **True** if a branch with name *branch_name* exits, **False** otherwise.
def Rt_display(stock_no): """ For real time stock display 即時盤用,顯示目前查詢各股的股價資訊。 """ a = twsk(stock_no).real if a: re = "{%(time)s} %(stock_no)s %(c)s %(range)+.2f(%(pp)+.2f%%) %(value)s" % { 'stock_no': stock_no, 'time': a['time'], 'c': a['c'], 'range': covstr(a['range'])...
For real time stock display 即時盤用,顯示目前查詢各股的股價資訊。
def uncompress(pub): ''' Input must be hex string, and a valid compressed public key. Check if it's a valid key first, using the validatepubkey() function below, and then verify that the str len is 66. ''' yp = int(pub[:2],16) - 2 x = int(pub[2:],16) a = (pow_mod(x,3,P) + 7) % P y =...
Input must be hex string, and a valid compressed public key. Check if it's a valid key first, using the validatepubkey() function below, and then verify that the str len is 66.
def findpeak_multi(x, y, dy, N, Ntolerance, Nfit=None, curve='Lorentz', return_xfit=False, return_stat=False): """Find multiple peaks in the dataset given by vectors x and y. Points are searched for in the dataset where the N points before and after have strictly lower values than them. To get rid of false...
Find multiple peaks in the dataset given by vectors x and y. Points are searched for in the dataset where the N points before and after have strictly lower values than them. To get rid of false negatives caused by fluctuations, Ntolerance is introduced. It is the number of outlier points to be tolerate...
def convert_args_to_sets(f): """ Converts all args to 'set' type via self.setify function. """ @wraps(f) def wrapper(*args, **kwargs): args = (setify(x) for x in args) return f(*args, **kwargs) return wrapper
Converts all args to 'set' type via self.setify function.
def replicate_filter(sources, model, cache=None): '''Replicates the list of objects to other class and returns their reflections''' targets = [replicate_no_merge(source, model, cache=cache) for source in sources] # Some objects may not be available in target DB (not published), so we ...
Replicates the list of objects to other class and returns their reflections
def get_item(track_url, client_id=CLIENT_ID): """ Fetches metadata for a track or playlist """ try: item_url = url['resolve'].format(track_url) r = requests.get(item_url, params={'client_id': client_id}) logger.debug(r.url) if r.status_code == 403: return get...
Fetches metadata for a track or playlist
def translate_symbol(self, in_symbol: str) -> str: """ translate the incoming symbol into locally-used """ # read all mappings from the db if not self.symbol_maps: self.__load_symbol_maps() # translate the incoming symbol result = self.symbol_maps[in_symbol] if in_sym...
translate the incoming symbol into locally-used
def show_delvol_on_destroy(name, kwargs=None, call=None): ''' Do not delete all/specified EBS volumes upon instance termination CLI Example: .. code-block:: bash salt-cloud -a show_delvol_on_destroy mymachine ''' if call != 'action': raise SaltCloudSystemExit( 'Th...
Do not delete all/specified EBS volumes upon instance termination CLI Example: .. code-block:: bash salt-cloud -a show_delvol_on_destroy mymachine
async def page_view(self, url: str, title: str, user_id: str, user_lang: str='') -> None: """ Track the view of a page """ raise NotImplementedError
Track the view of a page
def new_registry_ont_id_transaction(self, ont_id: str, pub_key: str or bytes, b58_payer_address: str, gas_limit: int, gas_price: int) -> Transaction: """ This interface is used to generate a Transaction object which is used to register ONT ID. :param ont_...
This interface is used to generate a Transaction object which is used to register ONT ID. :param ont_id: OntId. :param pub_key: the hexadecimal public key in the form of string. :param b58_payer_address: a base58 encode address which indicate who will pay for the transaction. :param gas...
def _extra_stats(self): """Adds ``loglr``, ``optimal_snrsq`` and matched filter snrsq in each detector to the default stats.""" return ['loglr'] + \ ['{}_optimal_snrsq'.format(det) for det in self._data] + \ ['{}_matchedfilter_snrsq'.format(det) for det in self._dat...
Adds ``loglr``, ``optimal_snrsq`` and matched filter snrsq in each detector to the default stats.
def do_alias(self, args: argparse.Namespace) -> None: """Manage aliases""" func = getattr(args, 'func', None) if func is not None: # Call whatever sub-command function was selected func(self, args) else: # No sub-command was provided, so call help ...
Manage aliases
def task_denotate(self, task, annotation): """ Removes an annotation from a task. """ self._execute( task['uuid'], 'denotate', '--', annotation ) id, denotated_task = self.get_task(uuid=task[six.u('uuid')]) return denotated_task
Removes an annotation from a task.
def upload_progress(request): """ Used by Ajax calls Return the upload progress and total length values """ if 'X-Progress-ID' in request.GET: progress_id = request.GET['X-Progress-ID'] elif 'X-Progress-ID' in request.META: progress_id = request.META['X-Progress-ID'] if prog...
Used by Ajax calls Return the upload progress and total length values
def iterate_forever(func, *args, **kwargs): """Iterate over a finite iterator forever When the iterator is exhausted will call the function again to generate a new iterator and keep iterating. """ output = func(*args, **kwargs) while True: try: playlist_item = next(output) ...
Iterate over a finite iterator forever When the iterator is exhausted will call the function again to generate a new iterator and keep iterating.
def get_parser(func, parent): """ Imposta il parser. """ parser = parent.add_parser(func.__cmd_name__, help=func.__doc__) for args, kwargs in func.__arguments__: parser.add_argument(*args, **kwargs) return parser
Imposta il parser.
def from_dade_matrix(filename, header=False): """ Loads a numpy array from a Dade matrix instance, e.g.: A matrix containing the following (or equivalent in numpy) [['RST','chr1~0','chr1~10','chr2~0','chr2~30'], ['chr1~0','5', '10', '11', '2'], ['chr1~10', '8', '3', '5'], ['chr2~0', '...
Loads a numpy array from a Dade matrix instance, e.g.: A matrix containing the following (or equivalent in numpy) [['RST','chr1~0','chr1~10','chr2~0','chr2~30'], ['chr1~0','5', '10', '11', '2'], ['chr1~10', '8', '3', '5'], ['chr2~0', '3', '5'], ['chr2~30', '5']] [['5'...
def download_url(job, url, work_dir='.', name=None, s3_key_path=None, cghub_key_path=None): """ Downloads URL, can pass in file://, http://, s3://, or ftp://, gnos://cghub/analysisID, or gnos:///analysisID If downloading S3 URLs, the S3AM binary must be on the PATH :param toil.job.Job job: Toil job tha...
Downloads URL, can pass in file://, http://, s3://, or ftp://, gnos://cghub/analysisID, or gnos:///analysisID If downloading S3 URLs, the S3AM binary must be on the PATH :param toil.job.Job job: Toil job that is calling this function :param str url: URL to download from :param str work_dir: Directory t...
def genExampleStar(binaryLetter='', heirarchy=True): """ generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up """ starPar = StarParameters() starPar.addParam('age', '7.6') starPar.addParam('magB', '9.8')...
generates example star, if binaryLetter is true creates a parent binary object, if heirarchy is true will create a system and link everything up
def timestamp_to_local_time(timestamp, timezone_name): """Convert epoch timestamp to a localized Delorean datetime object. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. Returns -------...
Convert epoch timestamp to a localized Delorean datetime object. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. Returns ------- delorean.Delorean A localized Delorean datetime o...
def update(self, name, rssi): """Update the device name and/or RSSI. During an ongoing scan, multiple records from the same device can be received during the scan. Each time that happens this method is called to update the :attr:`name` and/or :attr:`rssi` attributes. """ ...
Update the device name and/or RSSI. During an ongoing scan, multiple records from the same device can be received during the scan. Each time that happens this method is called to update the :attr:`name` and/or :attr:`rssi` attributes.
def get_ml_job(): """get_ml_job Get an ``MLJob`` by database id. """ parser = argparse.ArgumentParser( description=("Python client get AI Job by ID")) parser.add_argument( "-u", help="username", required=False, dest="user") parser.add_argument( ...
get_ml_job Get an ``MLJob`` by database id.
def _data_dict_to_bokeh_chart_data(self, data): """ Take a dictionary of data, as returned by the :py:class:`~.ProjectStats` per_*_data properties, return a 2-tuple of data dict and x labels list usable by bokeh.charts. :param data: data dict from :py:class:`~.ProjectStats` prop...
Take a dictionary of data, as returned by the :py:class:`~.ProjectStats` per_*_data properties, return a 2-tuple of data dict and x labels list usable by bokeh.charts. :param data: data dict from :py:class:`~.ProjectStats` property :type data: dict :return: 2-tuple of data dict,...
def read(self, len): """Refresh the content of the input buffer, the old data are considered consumed This routine handle the I18N transcoding to internal UTF-8 """ ret = libxml2mod.xmlParserInputBufferRead(self._o, len) return ret
Refresh the content of the input buffer, the old data are considered consumed This routine handle the I18N transcoding to internal UTF-8
def inject_long_nonspeech_fragments(self, pairs, replacement_string): """ Inject nonspeech fragments corresponding to the given intervals in this fragment list. It is assumed that ``pairs`` are consistent, e.g. they are produced by ``fragments_ending_inside_nonspeech_intervals``...
Inject nonspeech fragments corresponding to the given intervals in this fragment list. It is assumed that ``pairs`` are consistent, e.g. they are produced by ``fragments_ending_inside_nonspeech_intervals``. :param list pairs: list of ``(TimeInterval, int)`` pairs, ...
def get_filename(self, instance): """Get the filename """ filename = self.field.getFilename(instance) if filename: return filename fieldname = self.get_field_name() content_type = self.get_content_type(instance) extension = mimetypes.guess_extension(c...
Get the filename
def get_position(self, rst_tree, node_id=None): """Get the linear position of an element of this DGParentedTree in an RSTTree. If ``node_id`` is given, this will return the position of the subtree with that node ID. Otherwise, the position of the root of this DGParentedTree in the given...
Get the linear position of an element of this DGParentedTree in an RSTTree. If ``node_id`` is given, this will return the position of the subtree with that node ID. Otherwise, the position of the root of this DGParentedTree in the given RSTTree is returned.
def readNullModelFile(nfile): """" reading file with null model info nfile File containing null model info """ params0_file = nfile+'.p0' nll0_file = nfile+'.nll0' assert os.path.exists(params0_file), '%s is missing.'%params0_file assert os.path.exists(nll0_file), '%s is missing.'%nl...
reading file with null model info nfile File containing null model info
def _check_set_values(instance, dic): """ This function checks if the dict values are correct. :instance: the object instance. Used for querying :dic: is a dictionary with the following format: {'actions': [{'act_row_idx': 0, 'action': 'repeat', 'an_result_id': ...
This function checks if the dict values are correct. :instance: the object instance. Used for querying :dic: is a dictionary with the following format: {'actions': [{'act_row_idx': 0, 'action': 'repeat', 'an_result_id': 'rep-1', 'analyst': '', ...
def to_postdata(self): """Serialize as post data for a POST request.""" items = [] for k, v in sorted(self.items()): # predictable for testing items.append((k.encode('utf-8'), to_utf8_optional_iterator(v))) # tell urlencode to deal with sequence values and map them correctl...
Serialize as post data for a POST request.
def rcfile(appname, args={}, strip_dashes=True, module_name=None): """ Read environment variables and config files and return them merged with predefined list of arguments. Arguments: appname - application name, used for config files and environemnt variable names. args - ar...
Read environment variables and config files and return them merged with predefined list of arguments. Arguments: appname - application name, used for config files and environemnt variable names. args - arguments from command line (optparse, docopt, etc). strip_dashes - strip...
def coordination_geometry_symmetry_measures_standard(self, coordination_geometry, algo, points_perfect=None, ...
Returns the symmetry measures for a set of permutations (whose setup depends on the coordination geometry) for the coordination geometry "coordination_geometry". Standard implementation looking for the symmetry measures of each permutation :param coordination_geometry: The coordination geometry...
def root_chip(self): """The coordinates (x, y) of the chip used to boot the machine.""" # If not known, query the machine if self._root_chip is None: self._root_chip = self.get_software_version(255, 255, 0).position return self._root_chip
The coordinates (x, y) of the chip used to boot the machine.
def command(self, cmd_name, callback, *args): """Run an asynchronous command. Args: cmd_name (int): The unique code for the command to execute. callback (callable): The optional callback to run when the command finishes. The signature should be callback(cmd_name,...
Run an asynchronous command. Args: cmd_name (int): The unique code for the command to execute. callback (callable): The optional callback to run when the command finishes. The signature should be callback(cmd_name, result, exception) *args: Any arguments that...
def to_json(self): """ Writes the complete Morse complex merge hierarchy to a string object. @ Out, a string object storing the entire merge hierarchy of all maxima. """ capsule = {} capsule["Hierarchy"] = [] for ( dying, ...
Writes the complete Morse complex merge hierarchy to a string object. @ Out, a string object storing the entire merge hierarchy of all maxima.
def maybe_convert_platform_interval(values): """ Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype ...
Try to do platform conversion, with special casing for IntervalArray. Wrapper around maybe_convert_platform that alters the default return dtype in certain cases to be compatible with IntervalArray. For example, empty lists return with integer dtype instead of object dtype, which is prohibited for Inte...
def list_merge(list_a, list_b): """ Merge two lists without duplicating items Args: list_a: list list_b: list Returns: New list with deduplicated items from list_a and list_b """ #return list(collections.OrderedDict.fromkeys(list_a + list_b)) #result = list(list_b) res...
Merge two lists without duplicating items Args: list_a: list list_b: list Returns: New list with deduplicated items from list_a and list_b
def compositions(self): """ :rtype: twilio.rest.video.v1.composition.CompositionList """ if self._compositions is None: self._compositions = CompositionList(self) return self._compositions
:rtype: twilio.rest.video.v1.composition.CompositionList
def physical_conversion(quantity,pop=False): """Decorator to convert to physical coordinates: quantity = [position,velocity,time]""" def wrapper(method): @wraps(method) def wrapped(*args,**kwargs): use_physical= kwargs.get('use_physical',True) and \ not kwargs.ge...
Decorator to convert to physical coordinates: quantity = [position,velocity,time]
def delete_event_public_discount(self, id, discount_id, **data): """ DELETE /events/:id/public_discounts/:discount_id/ Deletes a public discount. """ return self.delete("/events/{0}/public_discounts/{0}/".format(id,discount_id), data=data)
DELETE /events/:id/public_discounts/:discount_id/ Deletes a public discount.
def connect_euca(host=None, aws_access_key_id=None, aws_secret_access_key=None, port=8773, path='/services/Eucalyptus', is_secure=False, **kwargs): """ Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server...
Connect to a Eucalyptus service. :type host: string :param host: the host name or ip address of the Eucalyptus server :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key ...
def generateSummary(self, extraLapse = TYPICAL_LAPSE): '''Generates a summary of the status of the expected scripts broken based on the log. This summary (a list of strings) is returned as well as a list with the dates (which can be used to index the log)of the most recent attempts at the failed jobs. ''' ...
Generates a summary of the status of the expected scripts broken based on the log. This summary (a list of strings) is returned as well as a list with the dates (which can be used to index the log)of the most recent attempts at the failed jobs.
def grid_to_eccentric_radii(self, grid): """Convert a grid of (y,x) coordinates to an eccentric radius, which is (1.0/axis_ratio) * elliptical radius \ and used to define light profile half-light radii using circular radii. If the coordinates have not been transformed to the profile's geometry,...
Convert a grid of (y,x) coordinates to an eccentric radius, which is (1.0/axis_ratio) * elliptical radius \ and used to define light profile half-light radii using circular radii. If the coordinates have not been transformed to the profile's geometry, this is performed automatically. Parameter...
def matches(self, sexp): ''' Body of a non-terminal is always a :class:`Sequence`. For an s-expr to match, it must be of the form:: ['name'] + [sexpr-0, ..., sexpr-n] where the first list contains a name of the non-terminal, and the second one matches its body seque...
Body of a non-terminal is always a :class:`Sequence`. For an s-expr to match, it must be of the form:: ['name'] + [sexpr-0, ..., sexpr-n] where the first list contains a name of the non-terminal, and the second one matches its body sequence.
def setProfile(self, name): """ Assign a PROFILE to this unnamed component. Used by vCard, not by vCalendar. """ if self.name or self.useBegin: if self.name == name: return raise VObjectError("This component already has a PROFILE or " ...
Assign a PROFILE to this unnamed component. Used by vCard, not by vCalendar.
def mex_hat(x, sigma): r"""Mexican hat This method implements a Mexican hat (or Ricker) wavelet. Parameters ---------- x : float Input data point sigma : float Standard deviation (filter scale) Returns ------- float Mexican hat filtered data point Examples ...
r"""Mexican hat This method implements a Mexican hat (or Ricker) wavelet. Parameters ---------- x : float Input data point sigma : float Standard deviation (filter scale) Returns ------- float Mexican hat filtered data point Examples -------- >>> from modo...
def encode(self): ''' Encode and store a SUBACK control packet. ''' header = bytearray(1) payload = bytearray() varHeader = encode16Int(self.msgId) header[0] = 0x90 for code in self.granted: payload.append(code[0] | (0x80 if code[1] == Tru...
Encode and store a SUBACK control packet.
def _property_create_dict(header, data): ''' Create a property dict ''' prop = dict(zip(header, _merge_last(data, len(header)))) prop['name'] = _property_normalize_name(prop['property']) prop['type'] = _property_detect_type(prop['name'], prop['values']) prop['edit'] = from_bool(prop['edit'])...
Create a property dict
def getStatus(self): """ RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet STDY - Steady Bit. This bit is updated w...
RDY - Ready Bit. This bit provides the status of the RDY flag from the part. The status and function of this bit is the same as the RDY output pin. A number of events set the RDY bit high as indicated in Table XVIII in datasheet STDY - Steady Bit. This bit is updated when the filter writes a result to the Data...
def exponential_terms(order, variables, data): """ Compute exponential expansions. Parameters ---------- order: range or list(int) A list of exponential terms to include. For instance, [1, 2] indicates that the first and second exponential terms should be added. To retain th...
Compute exponential expansions. Parameters ---------- order: range or list(int) A list of exponential terms to include. For instance, [1, 2] indicates that the first and second exponential terms should be added. To retain the original terms, 1 *must* be included in the list. var...
def _GetLink(self): """Retrieves the link. Returns: str: full path of the linked file entry. """ if self._link is None: self._link = '' if self.entry_type != definitions.FILE_ENTRY_TYPE_LINK: return self._link cpio_archive_file = self._file_system.GetCPIOArchiveFile() ...
Retrieves the link. Returns: str: full path of the linked file entry.
def set_code(self, code): """Sets widget from code string Parameters ---------- code: String \tCode representation of widget value """ for i, (_, style_code) in enumerate(self.styles): if code == style_code: self.SetSelection(i)
Sets widget from code string Parameters ---------- code: String \tCode representation of widget value
def terminate(self): """ Terminate a running cluster. (Due to a signal.) :return none """ for node in self.client_nodes: node.terminate() for node in self.nodes: node.terminate()
Terminate a running cluster. (Due to a signal.) :return none
def add_directive(self, key: Optional[str], value: str, lineno: Optional[int] = None, comment: str = '') -> None: '''Assignments are items with ':' type ''' if key is None: # continuation of multi-line di...
Assignments are items with ':' type
def _post(self, *args, **kwargs): """ A wrapper for posting things. It will also json encode your 'data' parameter :returns: The response of your post :rtype: dict :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServe...
A wrapper for posting things. It will also json encode your 'data' parameter :returns: The response of your post :rtype: dict :raises: This will raise a :class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerException>` if there is an error from New...
def find(self, id, columns=None): """ Execute a query for a single record by id :param id: The id of the record to retrieve :type id: mixed :param columns: The columns of the record to retrive :type columns: list :return: mixed :rtype: mixed """...
Execute a query for a single record by id :param id: The id of the record to retrieve :type id: mixed :param columns: The columns of the record to retrive :type columns: list :return: mixed :rtype: mixed
def inverse(self): """Inverse of this operator. The inverse of ``scalar * op`` is given by ``op.inverse * 1/scalar`` if ``scalar != 0``. If ``scalar == 0``, the inverse is not defined. ``OperatorLeftScalarMult(op, s).inverse == OperatorRightScalarMult(op.inverse...
Inverse of this operator. The inverse of ``scalar * op`` is given by ``op.inverse * 1/scalar`` if ``scalar != 0``. If ``scalar == 0``, the inverse is not defined. ``OperatorLeftScalarMult(op, s).inverse == OperatorRightScalarMult(op.inverse, 1/s)`` Examples ...
async def start(self, remoteParameters): """ Initiate connectivity checks. :param: remoteParameters: The :class:`RTCIceParameters` associated with the remote :class:`RTCIceTransport`. """ if self.state == 'closed': raise InvalidState...
Initiate connectivity checks. :param: remoteParameters: The :class:`RTCIceParameters` associated with the remote :class:`RTCIceTransport`.
def _get_all_templates(network_id, template_id): """ Get all the templates for the nodes, links and groups of a network. Return these templates as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link. """ base_qry = db.DBSession.query( ...
Get all the templates for the nodes, links and groups of a network. Return these templates as a dictionary, keyed on type (NODE, LINK, GROUP) then by ID of the node or link.
def populate_iteration(self, iteration): """Parse genotypes from the file and iteration with relevant marker \ details. :param iteration: ParseLocus object which is returned per iteration :return: True indicates current locus is valid. StopIteration is thrown if the marker ...
Parse genotypes from the file and iteration with relevant marker \ details. :param iteration: ParseLocus object which is returned per iteration :return: True indicates current locus is valid. StopIteration is thrown if the marker reaches the end of the file or the valid gen...
def strict_deps_for_target(self, target, predicate=None): """Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'. If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will only be able to see their immediate dependencies declared in the...
Get the dependencies of `target` filtered by `predicate`, accounting for 'strict_deps'. If 'strict_deps' is on, instead of using the transitive closure of dependencies, targets will only be able to see their immediate dependencies declared in the BUILD file. The 'strict_deps' setting is obtained from the r...
def ckw02(handle, begtim, endtim, inst, ref, segid, nrec, start, stop, quats, avvs, rates): """ Write a type 2 segment to a C-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw02_c.html :param handle: Handle of an open CK file. :type handle: int :param begtim: The be...
Write a type 2 segment to a C-kernel. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckw02_c.html :param handle: Handle of an open CK file. :type handle: int :param begtim: The beginning encoded SCLK of the segment. :type begtim: float :param endtim: The ending encoded SCLK of the seg...
def branches(self): """ Returns a data frame of all branches in origin. The DataFrame will have the columns: * repository * local * branch :returns: DataFrame """ df = pd.DataFrame(columns=['repository', 'local', 'branch']) if _has_joblib: ...
Returns a data frame of all branches in origin. The DataFrame will have the columns: * repository * local * branch :returns: DataFrame
def flatten_container(self, container): """ Accepts a kubernetes container and pulls out the nested values into the top level """ for names in ARG_MAP.values(): if names[TransformationTypes.KUBERNETES.value]['name'] and \ '.' in names[Transformatio...
Accepts a kubernetes container and pulls out the nested values into the top level
def register(view): # Type[BananasAPI] """ Register the API view class in the bananas router. :param BananasAPI view: """ meta = view.get_admin_meta() prefix = meta.basename.replace(".", "/") router.register(prefix, view, meta.basename)
Register the API view class in the bananas router. :param BananasAPI view:
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(PackageManagerRuntime, self).init_argparser(argparser) # Ideally, we could use more ...
Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand.
def _writen(fd, data): """Write all the data to a descriptor.""" while data: n = os.write(fd, data) data = data[n:]
Write all the data to a descriptor.
def view(allowed_methods, exceptions={}): """ Decorates a Django function based view and wraps it's return in the :py:func:`jason.response` function. The view should return a list or tuple which is unpacked using the ``*``-operator into :py:func:`jason.response`. The view can raise a :py:class:`jas...
Decorates a Django function based view and wraps it's return in the :py:func:`jason.response` function. The view should return a list or tuple which is unpacked using the ``*``-operator into :py:func:`jason.response`. The view can raise a :py:class:`jason.Bail` Exception. ``allowed_methods`` lists whi...
def rmon_event_entry_event_owner(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(even...
Auto Generated Code
def parse_auth(rule): ''' Parses the auth/authconfig line ''' parser = argparse.ArgumentParser() rules = shlex.split(rule) rules.pop(0) noargs = ('back', 'test', 'nostart', 'kickstart', 'probe', 'enablecache', 'disablecache', 'disablenis', 'enableshadow', 'disableshadow', ...
Parses the auth/authconfig line
def sms(self, client_id, phone_number): """Start flow sending a SMS message. """ return self.post( 'https://{}/passwordless/start'.format(self.domain), data={ 'client_id': client_id, 'connection': 'sms', 'phone_number': pho...
Start flow sending a SMS message.
def setFieldStats(self, fieldName, fieldStats): """ TODO: document """ #If the stats are not fully formed, ignore. if fieldStats[fieldName]['min'] == None or \ fieldStats[fieldName]['max'] == None: return self.minval = fieldStats[fieldName]['min'] self.maxval = fieldStats[field...
TODO: document
def spkacs(targ, et, ref, abcorr, obs): """ Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time and stellar aberration, expressed relative to an inertial reference frame. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/s...
Return the state (position and velocity) of a target body relative to an observer, optionally corrected for light time and stellar aberration, expressed relative to an inertial reference frame. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkacs_c.html :param targ: Target body. :typ...
def parseTargetNameAndSpec(target_name_and_spec): ''' Parse targetname[@versionspec] and return a tuple (target_name_string, version_spec_string). targetname[,versionspec] is also supported (this is how target names and specifications are stored internally, and was the documented way of ...
Parse targetname[@versionspec] and return a tuple (target_name_string, version_spec_string). targetname[,versionspec] is also supported (this is how target names and specifications are stored internally, and was the documented way of setting the spec on the commandline) Also ac...
def get_feed_permissions(self, feed_id, include_ids=None, exclude_inherited_permissions=None, identity_descriptor=None): """GetFeedPermissions. [Preview API] Get the permissions for a feed. :param str feed_id: Name or Id of the feed. :param bool include_ids: True to include user Ids in t...
GetFeedPermissions. [Preview API] Get the permissions for a feed. :param str feed_id: Name or Id of the feed. :param bool include_ids: True to include user Ids in the response. Default is false. :param bool exclude_inherited_permissions: True to only return explicitly set permissions on...
def _compile(self, expression): """ Transform a class exp into an actual regex """ x = self.RE_PYTHON_VAR.sub('(?:\\1,)', expression) x = self.RE_SPACES.sub('', x) return re.compile(x)
Transform a class exp into an actual regex
def download_file_insecure_to_io(url, target_file=None, headers={}): """ Use Python to download the file, even though it cannot authenticate the connection. """ src = None try: req = Request( url, data=None, headers=headers ) src = ur...
Use Python to download the file, even though it cannot authenticate the connection.
def add_genelist(self, list_id, gene_ids, case_obj=None): """Create a new gene list and optionally link to cases.""" new_genelist = GeneList(list_id=list_id) new_genelist.gene_ids = gene_ids if case_obj: new_genelist.cases.append(case_obj) self.session.add(new_geneli...
Create a new gene list and optionally link to cases.
def q(line, cell=None, _ns=None): """Run q code. Options: -l (dir|script) - pre-load database or script -h host:port - execute on the given host -o var - send output to a variable named var. -i var1,..,varN - input variables -1/-2 - redirect stdout/stderr """ if cell ...
Run q code. Options: -l (dir|script) - pre-load database or script -h host:port - execute on the given host -o var - send output to a variable named var. -i var1,..,varN - input variables -1/-2 - redirect stdout/stderr
def sanitize_color_palette(colorpalette): """ Sanitze the given color palette so it can be safely used by Colorful. It will convert colors specified in hex RGB to a RGB channel triplet. """ new_palette = {} def __make_valid_color_name(name): """ Convert the given name i...
Sanitze the given color palette so it can be safely used by Colorful. It will convert colors specified in hex RGB to a RGB channel triplet.
def to_JSON(self): """Dumps object fields into a JSON formatted string :returns: the JSON string """ return json.dumps({'name': self._name, 'coordinates': {'lon': self._lon, 'lat': self._lat ...
Dumps object fields into a JSON formatted string :returns: the JSON string
def get_command(self, ctx, name): """Get command for click.""" env = ctx.ensure_object(environment.Environment) env.load() # Do alias lookup (only available for root commands) if len(self.path) == 0: name = env.resolve_alias(name) new_path = list(self.path) ...
Get command for click.
def reind_proc(self, inputstring, **kwargs): """Add back indentation.""" out = [] level = 0 for line in inputstring.splitlines(): line, comment = split_comment(line.strip()) indent, line = split_leading_indent(line) level += ind_change(indent) ...
Add back indentation.
def new_child(self): """Get a new child :class:`Environment`. The child's scopes will be mine, with an additional empty innermost one. Returns: Environment: The child. """ child = Environment(self.globals, self.max_things) child.scopes = self.scopes....
Get a new child :class:`Environment`. The child's scopes will be mine, with an additional empty innermost one. Returns: Environment: The child.
def _wiki_urls_for_shard(shard_id, urls_dir=None): """Urls for chunk: dict<str wiki_url, list<str> ref_urls>.""" urls_dir = urls_dir or WIKI_URLS_DIR urls_filepath = os.path.join(urls_dir, WIKI_URLS_FILE % shard_id) with tf.gfile.GFile(urls_filepath) as f: return json.loads(f.read())
Urls for chunk: dict<str wiki_url, list<str> ref_urls>.
def wrap(self, data, many): """Wrap response in envelope.""" if not many: return data else: data = {'parts': data} multipart = self.context.get('multipart') if multipart: data.update(MultipartObjectSchema(context={ ...
Wrap response in envelope.
def _legendre_dtr(x, y, y_err, legendredeg=10): '''This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Arra...
This calculates the residual and chi-sq values for a Legendre function fit. Parameters ---------- x : np.array Array of the independent variable. y : np.array Array of the dependent variable. y_err : np.array Array of errors associated with each `y` value. Used to cal...
def get(self, call_sid): """ Constructs a ParticipantContext :param call_sid: The Call SID of the resource to fetch :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext ...
Constructs a ParticipantContext :param call_sid: The Call SID of the resource to fetch :returns: twilio.rest.api.v2010.account.conference.participant.ParticipantContext :rtype: twilio.rest.api.v2010.account.conference.participant.ParticipantContext
def send_build_close(params,response_url): '''send build close sends a final response (post) to the server to bring down the instance. The following must be included in params: repo_url, logfile, repo_id, secret, log_file, token ''' # Finally, package everything to send back to shub response = ...
send build close sends a final response (post) to the server to bring down the instance. The following must be included in params: repo_url, logfile, repo_id, secret, log_file, token
def get_node_meta_type(manager, handle_id): """ Returns the meta type of the supplied node as a string. :param manager: Neo4jDBSessionManager :param handle_id: Unique id :return: string """ node = get_node(manager=manager, handle_id=handle_id, legacy=False) for label in node.labels: ...
Returns the meta type of the supplied node as a string. :param manager: Neo4jDBSessionManager :param handle_id: Unique id :return: string
def get_limit_log(self, stat_name, default_action=False): """Return the log tag for the alert.""" # Get the log tag for stat + header # Exemple: network_wlan0_rx_log try: log_tag = self._limits[stat_name + '_log'] except KeyError: # Try fallback to plugin ...
Return the log tag for the alert.
def to_float(self): """ Converts to 32-bit data. Returns ------- :obj:`DepthImage` depth image with 32 bit float data """ return DepthImage(self.data.astype(np.float32), frame=self.frame)
Converts to 32-bit data. Returns ------- :obj:`DepthImage` depth image with 32 bit float data
def add_new_enriched_bins_matrixes(region_files, dfs, bin_size): """Add enriched bins based on bed files. There is no way to find the correspondence between region file and matrix file, but it does not matter.""" dfs = _remove_epic_enriched(dfs) names = ["Enriched_" + os.path.basename(r) for r i...
Add enriched bins based on bed files. There is no way to find the correspondence between region file and matrix file, but it does not matter.
def _completed_families(self, reference_name, rightmost_boundary): '''returns one or more families whose end < rightmost boundary''' in_progress = self._right_coords_in_progress[reference_name] while len(in_progress): right_coord = in_progress[0] if right_coord < rightmos...
returns one or more families whose end < rightmost boundary
def equal_to(self, key, value): """ 增加查询条件,查询字段的值必须为指定值。 :param key: 查询条件的字段名 :param value: 查询条件的值 :rtype: Query """ self._where[key] = utils.encode(value) return self
增加查询条件,查询字段的值必须为指定值。 :param key: 查询条件的字段名 :param value: 查询条件的值 :rtype: Query
def eval_hessian(self, *args, **kwargs): """ :return: Hessian evaluated at the specified point. """ # Evaluate the hessian model and use the resulting Ans namedtuple as a # dict. From this, take the relevant components. eval_hess_dict = self.hessian_model(*args, **kwargs)...
:return: Hessian evaluated at the specified point.
def device_text_string_request(self): """Get FX Username. Only required for devices that support FX Commands. FX Addressee responds with an ED 0x0301 FX Username Response message. """ msg = StandardSend(self._address, COMMAND_FX_USERNAME_0X03_0X01) self._send_msg(msg)
Get FX Username. Only required for devices that support FX Commands. FX Addressee responds with an ED 0x0301 FX Username Response message.
def connect(self, ssl=None, timeout=None): """ Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object. Often times there is more than one address specified for a server or client. This function will prioritize local connections before remote and HTTPS before HTTP...
Returns a new :class:`~server.PlexServer` or :class:`~client.PlexClient` object. Often times there is more than one address specified for a server or client. This function will prioritize local connections before remote and HTTPS before HTTP. After trying to connect to all available ...
def get_enough_colours(num_unique_values): """ Generates and returns an array of `num_unique_values` HEX colours. :param num_unique_values: int, number of colours to be generated. :return: array of str, containing colours in HEX format. """ if num_unique_values in NUM2COLOURS: return NUM...
Generates and returns an array of `num_unique_values` HEX colours. :param num_unique_values: int, number of colours to be generated. :return: array of str, containing colours in HEX format.