code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def register_job_from_link(self, link, key, **kwargs): """Register a job in the `JobArchive` from a `Link` object """ job_config = kwargs.get('job_config', None) if job_config is None: job_config = link.args status = kwargs.get('status', JobStatus.unknown) job_details...
Register a job in the `JobArchive` from a `Link` object
def peek_64(library, session, address): """Read an 64-bit value from the specified address. Corresponds to viPeek64 function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param address: Source address to read the v...
Read an 64-bit value from the specified address. Corresponds to viPeek64 function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param address: Source address to read the value. :return: Data read from bus, return v...
def add_input_opt(self, opt, inp): """ Add an option that determines an input """ self.add_opt(opt, inp._dax_repr()) self._add_input(inp)
Add an option that determines an input
def parse_options(self, arg): """ Parse options with the argv :param arg: one arg from argv """ if not arg.startswith('-'): return False value = None if '=' in arg: arg, value = arg.split('=') for option in self._option_list: ...
Parse options with the argv :param arg: one arg from argv
def last(self): """Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.""" if len(self._range) == 0: raise IndexError("range is empty") if self._idx == -1: return self._range[0] return...
Returns the last element accessed via next() or prev(). Returns the first element of range() if neither of these was called.
def _clear_entity_type_registry(entity, **kwargs): """Clear the given database/collection object's type registry.""" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs)
Clear the given database/collection object's type registry.
def get_any_node(self, addr): """ Get any VFG node corresponding to the basic block at @addr. Note that depending on the context sensitivity level, there might be multiple nodes corresponding to different contexts. This function will return the first one it encounters, which migh...
Get any VFG node corresponding to the basic block at @addr. Note that depending on the context sensitivity level, there might be multiple nodes corresponding to different contexts. This function will return the first one it encounters, which might not be what you want.
def remove_release(self, username, package_name, version): ''' remove a release and all files under it :param username: the login of the package owner :param package_name: the name of the package :param version: the name of the package ''' url = '%s/release/%s/%s...
remove a release and all files under it :param username: the login of the package owner :param package_name: the name of the package :param version: the name of the package
def get(self, list_id, merge_id): """ Get information about a specific merge field in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param merge_id: The id for the merge field. :type merge_id: :py:class:`str` """ self....
Get information about a specific merge field in a list. :param list_id: The unique id for the list. :type list_id: :py:class:`str` :param merge_id: The id for the merge field. :type merge_id: :py:class:`str`
def list(self, log_level=values.unset, start_date=values.unset, end_date=values.unset, limit=None, page_size=None): """ Lists AlertInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. ...
Lists AlertInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param unicode log_level: Only show alerts for this log-level. :param date start_date: Only show Alerts on or after this date. ...
def _check_reset_and_type_change(self, name, orig_ctr): """Check if name is in orig_ctr or in one of the other type containers.""" # Resetting a hyperparameter if name in orig_ctr: tf.logging.warning("Overwriting hparam %s", name) ctr_names = [ (self._categorical_params, "categorical"), ...
Check if name is in orig_ctr or in one of the other type containers.
def _parametersToDefaults(self, parameters): """ Extract the defaults from C{parameters}, constructing a dictionary mapping parameter names to default values, suitable for passing to L{ListChangeParameter}. @type parameters: C{list} of L{liveform.Parameter} or L{liveform...
Extract the defaults from C{parameters}, constructing a dictionary mapping parameter names to default values, suitable for passing to L{ListChangeParameter}. @type parameters: C{list} of L{liveform.Parameter} or L{liveform.ChoiceParameter}. @rtype: C{dict}
def _parse_permission(self, obj): """ 从 obj 中取出权限 :param obj: :return: [A.QUERY, A.WRITE, ...] """ if isinstance(obj, str): if obj == '*': return A.ALL elif obj in A.ALL: return obj, else: ...
从 obj 中取出权限 :param obj: :return: [A.QUERY, A.WRITE, ...]
def clear_from(self, timestamp): """Clear all data from `timestamp` onwards. Note that the timestamp is rounded down to the nearest block boundary""" block_size = self.config.block_size offset, remainder = timestamp // block_size, timestamp % block_size if remainder: ...
Clear all data from `timestamp` onwards. Note that the timestamp is rounded down to the nearest block boundary
def _init_default_values(self): """Set default initial values The default values are hard-coded for backwards compatibility and for several functionalities in dclab. """ # Do not filter out invalid event values self["filtering"]["remove invalid events"] = False #...
Set default initial values The default values are hard-coded for backwards compatibility and for several functionalities in dclab.
def fs_cleansed_attachments(self): """ returns a list of absolute paths to the cleansed attachements""" if exists(self.fs_cleansed_attachment_container): return [join(self.fs_cleansed_attachment_container, attachment) for attachment in listdir(self.fs_cleansed_attachment_...
returns a list of absolute paths to the cleansed attachements
def average_last_builds(connection, package, limit=5): """ Find the average duration time for the last couple of builds. :param connection: txkoji.Connection :param package: package name :returns: deferred that when fired returns a datetime.timedelta object, or None if there were no p...
Find the average duration time for the last couple of builds. :param connection: txkoji.Connection :param package: package name :returns: deferred that when fired returns a datetime.timedelta object, or None if there were no previous builds for this package.
def _PrintTasksStatus(self, processing_status): """Prints the status of the tasks. Args: processing_status (ProcessingStatus): processing status. """ if processing_status and processing_status.tasks_status: tasks_status = processing_status.tasks_status table_view = views.CLITabularTa...
Prints the status of the tasks. Args: processing_status (ProcessingStatus): processing status.
def saveVizGithub(contents, ontouri): """ DEPRECATED on 2016-11-16 Was working but had a dependecies on package 'uritemplate.py' which caused problems at installation time """ title = "Ontospy: ontology export" readme = """This ontology documentation was automatically generated with Ontospy (htt...
DEPRECATED on 2016-11-16 Was working but had a dependecies on package 'uritemplate.py' which caused problems at installation time
def update(self, other): """Adds all the tag-entry pairs from _other_ to the `Grant`. If there is a conflict _other_ takes precedence. # Parameters _other_ : `Grant` > Another `Grant` of the same type as _self_ """ if type(self) != type(other): return NotIm...
Adds all the tag-entry pairs from _other_ to the `Grant`. If there is a conflict _other_ takes precedence. # Parameters _other_ : `Grant` > Another `Grant` of the same type as _self_
def load_ply(fileobj): """Same as load_ply, but takes a file-like object""" def nextline(): """Read next line, skip comments""" while True: line = fileobj.readline() assert line != '' # eof if not line.startswith('comment'): return line.strip(...
Same as load_ply, but takes a file-like object
def _create_results_summary(self): """ Create the dataframe that displays the estimation results, and store it on the model instance. Returns ------- None. """ # Make sure we have all attributes needed to create the results summary needed_attribut...
Create the dataframe that displays the estimation results, and store it on the model instance. Returns ------- None.
def call_handlers(self, msg): """ Reimplemented to emit signals instead of making callbacks. """ # Emit the generic signal. self.message_received.emit(msg) # Emit signals for specialized message types. msg_type = msg['header']['msg_type'] if msg_type == 'input_re...
Reimplemented to emit signals instead of making callbacks.
def decode(self, binSequence): """decodes a binary sequence to return a string""" try: binSeq = iter(binSequence[0]) except TypeError, te: binSeq = binSequence ret = '' for b in binSeq : ch = '' for c in self.charToBin : if b & self.forma[self.charToBin[c]] > 0 : ch += c +'/' if c...
decodes a binary sequence to return a string
def not_empty(value, allow_empty = False, **kwargs): """Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueErro...
Validate that ``value`` is not empty. :param value: The value to validate. :param allow_empty: If ``True``, returns :obj:`None <python:None>` if ``value`` is empty. If ``False``, raises a :class:`EmptyValueError <validator_collection.errors.EmptyValueError>` if ``value`` is empty. Defaults t...
def get_media_detail_input_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_media_detail = ET.Element("get_media_detail") config = get_media_detail input = ET.SubElement(get_media_detail, "input") interface_name = ET.Sub...
Auto Generated Code
def _on_message(self, socket, message): """ Called aways when a message arrives. """ data = json.loads(message) message_type = None identifier = None subscription = None if 'type' in data: message_type = data['type'] if 'identifier' i...
Called aways when a message arrives.
def count(self): """ :returns: The total number of elements in the reference list. :rtype: int """ references = self.conn.client.get(self.refcount_key) if references is None: return 0 return int(references)
:returns: The total number of elements in the reference list. :rtype: int
def update_job_by_id(user, job_id): """Update a job """ # get If-Match header if_match_etag = utils.check_and_get_etag(flask.request.headers) # get the diverse parameters values = schemas.job.put(flask.request.json) job = v1_utils.verify_existence_and_get(job_id, _TABLE) job = dict(job...
Update a job
def DeleteGRRUser(self, username): """Deletes the user and all related metadata with the given username.""" try: del self.approvals_by_username[username] except KeyError: pass # No approvals to delete for this user. for approvals in itervalues(self.approvals_by_username): for approva...
Deletes the user and all related metadata with the given username.
def sanitize_filename(filename): """preserve the file ending, but replace the name with a random token """ # TODO: fix broken splitext (it reveals everything of the filename after the first `.` - doh!) token = generate_drop_id() name, extension = splitext(filename) if extension: return '%s%s...
preserve the file ending, but replace the name with a random token
def get_sizestr(img): """ Extract and reformat voxel size, matrix size, field of view, and number of slices into pretty strings. Parameters ---------- img : :obj:`nibabel.Nifti1Image` Image from scan from which to derive parameters. Returns ------- n_slices : :obj:`int` ...
Extract and reformat voxel size, matrix size, field of view, and number of slices into pretty strings. Parameters ---------- img : :obj:`nibabel.Nifti1Image` Image from scan from which to derive parameters. Returns ------- n_slices : :obj:`int` Number of slices. voxel_s...
def decode(packet): """Decode a navdata packet.""" offset = 0 _ = struct.unpack_from('IIII', packet, offset) s = _[1] state = dict() state['fly'] = s & 1 # FLY MASK : (0) ardrone is landed, (1) ardrone is flying state['video'] = s >> 1 & 1 # VIDEO MASK :...
Decode a navdata packet.
def value_dp_matrix(self): """ :return: DataProperty for table data. :rtype: list """ if self.__value_dp_matrix is None: self.__value_dp_matrix = self.__dp_extractor.to_dp_matrix( to_value_matrix(self.headers, self.rows) ) return ...
:return: DataProperty for table data. :rtype: list
def get_rules(license): """Gets can, cannot and must rules from github license API""" can = [] cannot = [] must = [] req = requests.get("{base_url}/licenses/{license}".format( base_url=BASE_URL, license=license), headers=_HEADERS) if req.status_code == requests.codes.ok: data = re...
Gets can, cannot and must rules from github license API
def flush_incoming(self): """ Flush all incoming queues to the respective processing methods. The handlers are called as usual, thus it may require at least one iteration through the asyncio event loop before effects can be seen. The incoming queues are empty after a call to thi...
Flush all incoming queues to the respective processing methods. The handlers are called as usual, thus it may require at least one iteration through the asyncio event loop before effects can be seen. The incoming queues are empty after a call to this method. It is legal (but pretty use...
def _ensure_allow_rp(rp_pyxb): """Ensure that RP allows replication.""" if not rp_pyxb.replicationAllowed: rp_pyxb.replicationAllowed = True if not rp_pyxb.numberReplicas: rp_pyxb.numberReplicas = 3
Ensure that RP allows replication.
def XORPS(cpu, dest, src): """ Performs a bitwise logical OR operation on the source operand (second operand) and the destination operand (first operand) and stores the result in the destination operand. The source operand can be an MMX technology register or a 64-bit memory location or ...
Performs a bitwise logical OR operation on the source operand (second operand) and the destination operand (first operand) and stores the result in the destination operand. The source operand can be an MMX technology register or a 64-bit memory location or it can be an XMM register or a 128-bit memory l...
def _validate_max_staleness(max_staleness): """Validate max_staleness.""" if max_staleness == -1: return -1 if not isinstance(max_staleness, integer_types): raise TypeError(_invalid_max_staleness_msg(max_staleness)) if max_staleness <= 0: raise ValueError(_invalid_max_staleness...
Validate max_staleness.
def appname(path=None): """ Return a useful application name based on the program argument. A special case maps 'mod_wsgi' to a more appropriate name so web applications show up as our own. """ if path is None: path = sys.argv[0] name = os.path.basename(os.path.splitext(path)[0]) if name == 'mod...
Return a useful application name based on the program argument. A special case maps 'mod_wsgi' to a more appropriate name so web applications show up as our own.
def spatialimg_to_hdfgroup(h5group, spatial_img): """Saves a Nifti1Image into an HDF5 group. Parameters ---------- h5group: h5py Group Output HDF5 file path spatial_img: nibabel SpatialImage Image to be saved h5path: str HDF5 group path where the image data will be sav...
Saves a Nifti1Image into an HDF5 group. Parameters ---------- h5group: h5py Group Output HDF5 file path spatial_img: nibabel SpatialImage Image to be saved h5path: str HDF5 group path where the image data will be saved. Datasets will be created inside the given gro...
def run(input_path=None, output_path=None, verbose=True, plot=True, hist_sheet=False): """ Run the MS Excel User Interface. This function performs the following: 1. If `input_path` is not specified, show a dialog to choose an input Excel file. 2. Extract d...
Run the MS Excel User Interface. This function performs the following: 1. If `input_path` is not specified, show a dialog to choose an input Excel file. 2. Extract data from the Instruments, Beads, and Samples tables. 3. Process all the bead samples specified in the Beads table. 4. Gen...
def register_sigma_task(self, *args, **kwargs): """Register a sigma task.""" kwargs["task_class"] = SigmaTask return self.register_task(*args, **kwargs)
Register a sigma task.
def authorization_documents(self): """ :rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList """ if self._authorization_documents is None: self._authorization_documents = AuthorizationDocumentList(self) return self._authorization_...
:rtype: twilio.rest.preview.hosted_numbers.authorization_document.AuthorizationDocumentList
def get_readonly_fields(self, request, obj=None): """ Makes `created_by`, `create_date` & `update_date` readonly when editing. Author: Himanshu Shankar (https://himanshus.com) """ # Get read only fields from super fields = list(super(CreateUpdateAdmin, self).get...
Makes `created_by`, `create_date` & `update_date` readonly when editing. Author: Himanshu Shankar (https://himanshus.com)
def property_present(properties, admin_username='root', admin_password='calvin', host=None, **kwargs): ''' properties = {} ''' ret = {'name': host, 'context': {'Host': host}, 'result': True, 'changes': {}, 'comment': ''} if host is None: output =...
properties = {}
def recv(self, tab_key, message_id=None, timeout=30): ''' Recieve a message, optionally filtering for a specified message id. If `message_id` is none, the first command in the receive queue is returned. If `message_id` is not none, the command waits untill a message is received with the specified id, or it t...
Recieve a message, optionally filtering for a specified message id. If `message_id` is none, the first command in the receive queue is returned. If `message_id` is not none, the command waits untill a message is received with the specified id, or it times out. Timeout is the number of seconds to wait for a re...
def col_frequencies(col, weights=None, gap_chars='-.'): """Frequencies of each residue type (totaling 1.0) in a single column.""" counts = col_counts(col, weights, gap_chars) # Reduce to frequencies scale = 1.0 / sum(counts.values()) return dict((aa, cnt * scale) for aa, cnt in counts.iteritems())
Frequencies of each residue type (totaling 1.0) in a single column.
def interval_to_milliseconds(interval): """Convert a Binance interval string to milliseconds :param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: None if unit not one of m, h, d or w None if string not in corr...
Convert a Binance interval string to milliseconds :param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w :type interval: str :return: None if unit not one of m, h, d or w None if string not in correct format int value of interval in mi...
def gather_job_info(self, jid, tgt, tgt_type, listen=True, **kwargs): ''' Return the information about a given job ''' log.debug('Checking whether jid %s is still running', jid) timeout = int(kwargs.get('gather_job_timeout', self.opts['gather_job_timeout'])) pub_data = s...
Return the information about a given job
def save_bed(cls, query, filename=sys.stdout): """ write a bed12 file of the query. Parameters ---------- query : query a table or query to save to file filename : file string or filehandle to write output """ out = _open(filename...
write a bed12 file of the query. Parameters ---------- query : query a table or query to save to file filename : file string or filehandle to write output
def _get_name(self): """ There are three cases, because apipie definitions can have multiple signatures but python does not For example, the api endpoint: /api/myres/:myres_id/subres/:subres_id/subres2 for method *index* will be translated to the api method name: ...
There are three cases, because apipie definitions can have multiple signatures but python does not For example, the api endpoint: /api/myres/:myres_id/subres/:subres_id/subres2 for method *index* will be translated to the api method name: subres_index_subres2 So ...
def _initialize_counter(self): """Initialize our counter pointer. If we're the top-level factory, instantiate a new counter Otherwise, point to the top-level factory's counter. """ if self._counter is not None: return if self.counter_reference is self: ...
Initialize our counter pointer. If we're the top-level factory, instantiate a new counter Otherwise, point to the top-level factory's counter.
def version(self, value): """Version setter.""" self.bytearray[self._get_slicers(1)] = bytearray(c_uint8(value or 0))
Version setter.
def has_default_privileges(name, object_name, object_type, defprivileges=None, grant_option=None, prepend='public', maintenance_db=None, user=None, host=None, port=None, password=None, runas=None): ''' .. versionadded:: 2019...
.. versionadded:: 2019.0.0 Check if a role has the specified privileges on an object CLI Example: .. code-block:: bash salt '*' postgres.has_default_privileges user_name table_name table \\ SELECT,INSERT maintenance_db=db_name name Name of the role whose privileges should be ...
def create_zone(server, token, domain, identifier, dtype, master=None): """Create zone records. Arguments: server: TonicDNS API server token: TonicDNS API authentication token domain: Specify domain name identifier: Template ID dtype: MASTER|SLAVE|NATI...
Create zone records. Arguments: server: TonicDNS API server token: TonicDNS API authentication token domain: Specify domain name identifier: Template ID dtype: MASTER|SLAVE|NATIVE (default: MASTER) master: master server ip address when dtype is...
def get_flops(): """ # DOESNT WORK """ from sys import stdout from re import compile filename = "linpack.out" fpnum = r'\d+\.\d+E[+-]\d\d' fpnum_1 = fpnum + r' +' pattern = compile(r'^ *' + fpnum_1 + fpnum_1 + fpnum_1 + r'(' + fpnum + r') +' + fpnum_1 + fpnum + r' *\n$') speeds = [0.0, ...
# DOESNT WORK
def make_masks(self, template): """This method generates all seven masks so that the best mask can be determined. The template parameter is a code matrix that will server as the base for all the generated masks. """ from copy import deepcopy nmasks = len(tables.mask_patt...
This method generates all seven masks so that the best mask can be determined. The template parameter is a code matrix that will server as the base for all the generated masks.
def intervention_strategies(df, filepath=None): """ Plots all intervention strategies Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns starting with `TR:` filepath: str Absolute path to a folder where to write the plot Returns ------- plot ...
Plots all intervention strategies Parameters ---------- df: `pandas.DataFrame`_ DataFrame with columns starting with `TR:` filepath: str Absolute path to a folder where to write the plot Returns ------- plot Generated plot .. _pandas.DataFrame: http://pandas...
def _submit_task_with_template(self, task_ids): '''Submit tasks by interpolating a shell script defined in job_template''' runtime = self.config runtime.update({ 'workdir': os.getcwd(), 'cur_dir': os.getcwd(), # for backward compatibility 'verbosity': env.ver...
Submit tasks by interpolating a shell script defined in job_template
def create_mask(self): """Create boolean mask from drawing. All areas enclosed by all the shapes drawn will be set to 1 (True) in the mask. Otherwise, the values will be set to 0 (False). The mask will be inserted as a new image buffer, like ``Mosaic``. """ ntags = len(...
Create boolean mask from drawing. All areas enclosed by all the shapes drawn will be set to 1 (True) in the mask. Otherwise, the values will be set to 0 (False). The mask will be inserted as a new image buffer, like ``Mosaic``.
def clean(self, py_value): """ Cleans the value before storing it. :param: py_value : <str> :return: <str> """ try: import bleach return bleach.clean(py_value, **self.__bleachOptions) except ImportError: warnings.warn('...
Cleans the value before storing it. :param: py_value : <str> :return: <str>
def TNRS(self, names, context_name=None, id_list=None, fuzzy_matching=False, include_deprecated=False, include_dubious=False, do_approximate_matching=None, wrap_response=None): """Takes a name and optional co...
Takes a name and optional contextName returns a list of matches. `wrap_response` can be True to return a TNRSResponse object, None to return the "raw" response dict, or a function/class that takes (response, query_data=dict) as its arguments. Each match is a dict with: ...
def item_fields(self): """ Get all available item fields """ # Check for a valid cached version if self.templates.get("item_fields") and not self._updated( "/itemFields", self.templates["item_fields"], "item_fields" ): return self.templates["item_fields"][...
Get all available item fields
def load(self, filename): '''load settings from a file. Return True/False on success/failure''' try: f = open(filename, mode='r') except Exception: return False while True: line = f.readline() if not line: break ...
load settings from a file. Return True/False on success/failure
def add(self, element): """Add an element to this set.""" key = self._transform(element) if key not in self._elements: self._elements[key] = element
Add an element to this set.
def process_upload(upload_file, instance, form, event, request): """ Helper function that actually processes and saves the upload(s). Segregated out for readability. """ caption = form.cleaned_data.get('caption') upload_name = upload_file.name.lower() if upload_name.endswith('.jpg') or uploa...
Helper function that actually processes and saves the upload(s). Segregated out for readability.
def _read_local_kwalitee_configuration(directory="."): """Check if the repo has a ``.kwalitee.yaml`` file.""" filepath = os.path.abspath(os.path.join(directory, '.kwalitee.yml')) data = {} if os.path.exists(filepath): with open(filepath, 'r') as file_read: data = yaml.load(file_read....
Check if the repo has a ``.kwalitee.yaml`` file.
def set_op_version(version): ''' .. versionadded:: 2019.2.0 Set the glusterfs volume op-version version Version to set the glusterfs volume op-version CLI Example: .. code-block:: bash salt '*' glusterfs.set_op_version <volume> ''' cmd = 'volume set all cluster.op-v...
.. versionadded:: 2019.2.0 Set the glusterfs volume op-version version Version to set the glusterfs volume op-version CLI Example: .. code-block:: bash salt '*' glusterfs.set_op_version <volume>
def verify(self, h, sig, sig_fmt=SER_BINARY): """ Verifies that `sig' is a signature for a message with SHA-512 hash `h'. """ s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
Verifies that `sig' is a signature for a message with SHA-512 hash `h'.
def _dev_api(cls): """Get a developer instance for GitHub API access.""" gh = github3.GitHub() gh.set_client_id(cls.remote.consumer_key, cls.remote.consumer_secret) return gh
Get a developer instance for GitHub API access.
def set_debug(self, set_to=True): """ Sets the capture to debug mode (or turns it off if specified). """ if set_to: StreamHandler(sys.stdout).push_application() self._log.level = logbook.DEBUG self.debug = set_to
Sets the capture to debug mode (or turns it off if specified).
async def patch_entries(self, entry, **kwargs): """ PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags ...
PATCH /api/entries/{entry}.{_format} Change several properties of an entry :param entry: the entry to 'patch' / update :param kwargs: can contain one of the following title: string tags: a list of tags tag1,tag2,tag3 archive: '0' or '1', default '0' archive...
def _get_device_by_label(devices, label): ''' Returns the device with the given label, raises error if the device is not found. devices list of vim.vm.device.VirtualDevice objects key Unique key of device ''' device_labels = [d for d in devices if d.deviceInfo.label == labe...
Returns the device with the given label, raises error if the device is not found. devices list of vim.vm.device.VirtualDevice objects key Unique key of device
def get_urlpatterns(self): """ Returns the URL patterns managed by the considered factory / application. """ return [ path( '', search_view_factory(view_class=self.search_view, form_class=self.search_form), name='search', ), ...
Returns the URL patterns managed by the considered factory / application.
def authGenders(self, countsOnly = False, fractionsMode = False, _countsTuple = False): """Creates a dict mapping `'Male'`, `'Female'` and `'Unknown'` to lists of the names of all the authors. # Parameters _countsOnly_ : `optional bool` > Default `False`, if `True` the counts (lengths...
Creates a dict mapping `'Male'`, `'Female'` and `'Unknown'` to lists of the names of all the authors. # Parameters _countsOnly_ : `optional bool` > Default `False`, if `True` the counts (lengths of the lists) will be given instead of the lists of names _fractionsMode_ : `optional boo...
def _notify(self, topic, **kwargs): """ Invokes callbacks for an event topic. @param topic: String event name @type topic: str @param kwargs: Values associated with the event @type kwargs: dict """ for cb in self._connects.get(topic, []): try:...
Invokes callbacks for an event topic. @param topic: String event name @type topic: str @param kwargs: Values associated with the event @type kwargs: dict
def image_import(self, image_name, url, image_meta, remote_host=None): """Import the image specified in url to SDK image repository, and create a record in image db, the imported images are located in image_repository/prov_method/os_version/image_name/, for example, /opt/sdk/images/netbo...
Import the image specified in url to SDK image repository, and create a record in image db, the imported images are located in image_repository/prov_method/os_version/image_name/, for example, /opt/sdk/images/netboot/rhel7.2/90685d2b-167bimage/0100
def gzip_if_smaller(content_related, data): """Calls bytes(request), and based on a certain threshold, optionally gzips the resulting data. If the gzipped data is smaller than the original byte array, this is returned instead. Note that this only applies to content related requ...
Calls bytes(request), and based on a certain threshold, optionally gzips the resulting data. If the gzipped data is smaller than the original byte array, this is returned instead. Note that this only applies to content related requests.
def popError(text, title="Lackey Error"): """ Creates an error dialog with the specified text. """ root = tk.Tk() root.withdraw() tkMessageBox.showerror(title, text)
Creates an error dialog with the specified text.
def Pad(self, n): """Pad places zeros at the current offset.""" for i in range_func(n): self.Place(0, N.Uint8Flags)
Pad places zeros at the current offset.
def is_nested(values): '''Check if values is composed only by iterable elements.''' return (all(isinstance(item, Iterable) for item in values) if isinstance(values, Iterable) else False)
Check if values is composed only by iterable elements.
def add_to_submenu(self, submenu_path, item): ''' add an item to a submenu using a menu path array ''' for m in self.items: if m.name == submenu_path[0]: m.add_to_submenu(submenu_path[1:], item) return raise(ValueError("No submenu (%s) ...
add an item to a submenu using a menu path array
def _get(self, text): """ Analyze the text to get the right function Parameters ---------- text : str The text that could call a function """ if self.strict: match = self.prog.match(text) if match: cmd = mat...
Analyze the text to get the right function Parameters ---------- text : str The text that could call a function
def pathFromHere_explore(self, astr_startPath = '/'): """ Return a list of paths from "here" in the stree, using the child explore access. :param astr_startPath: path from which to start :return: a list of paths from "here" """ self.l...
Return a list of paths from "here" in the stree, using the child explore access. :param astr_startPath: path from which to start :return: a list of paths from "here"
def post(self, request, *args, **kwargs): """ Run some custom POST logic for Enterprise workflows before routing the user through existing views. """ # pylint: disable=unused-variable enterprise_customer_uuid, course_run_id, course_key, program_uuid = RouterView.get_path_variable...
Run some custom POST logic for Enterprise workflows before routing the user through existing views.
def log(duration, message=None, use_last_commit_message=False): """ Log time against the current active issue """ branch = git.branch issue = jira.get_issue(branch) # Create the comment comment = "Working on issue %s" % branch if message: comment = message elif use_last_commi...
Log time against the current active issue
def check_lat_extents(self, ds): ''' Check that the values of geospatial_lat_min/geospatial_lat_max approximately match the data. :param netCDF4.Dataset ds: An open netCDF dataset ''' if not (hasattr(ds, 'geospatial_lat_min') or hasattr(ds, 'geospatial_lat_max')): ...
Check that the values of geospatial_lat_min/geospatial_lat_max approximately match the data. :param netCDF4.Dataset ds: An open netCDF dataset
def human_file_size(size): """ Returns a human-friendly string representing a file size that is 2-4 characters long. For example, depending on the number of bytes given, can be one of:: 256b 64k 1.1G Parameters ---------- size : int The size of the file...
Returns a human-friendly string representing a file size that is 2-4 characters long. For example, depending on the number of bytes given, can be one of:: 256b 64k 1.1G Parameters ---------- size : int The size of the file (in bytes) Returns ------- ...
def update_from_env(yaml_dict, prefix=None): ''' Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL. ''' ...
Override YAML settings with values from the environment variables. - The letter '_' is delimit the hierarchy of the YAML settings such that the value of 'config.databases.local' will be overridden by CONFIG_DATABASES_LOCAL.
def suppress_output(reverse=False): """ Suppress output """ if reverse: sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ else: sys.stdout = os.devnull sys.stderr = os.devnull
Suppress output
def unflag_field(self, move_x, move_y): """Unflag or unquestion a grid by given position.""" field_status = self.info_map[move_y, move_x] if field_status == 9 or field_status == 10: self.info_map[move_y, move_x] = 11
Unflag or unquestion a grid by given position.
def set_routput(self, routput): """ Add routput to be used in next api call :param routput: key :return: True/False, message """ if type(routput) != str: return False, "Routput must be string" self.r_outputs.append(routput) return True, "Ok"
Add routput to be used in next api call :param routput: key :return: True/False, message
def base(number, input_base=10, output_base=10, max_depth=10, string=False, recurring=True): """ Converts a number from any base to any another. Args: number(tuple|str|int): The number to convert. input_base(int): The base to convert from (defualt 10). output_base(i...
Converts a number from any base to any another. Args: number(tuple|str|int): The number to convert. input_base(int): The base to convert from (defualt 10). output_base(int): The base to convert to (default 10). max_depth(int): The maximum number of fractional digits (defult 10...
def to_description_dict(self): """ You might need keys below in some situation - caCertificateId - previousOwnedBy """ return { 'certificateArn': self.arn, 'certificateId': self.certificate_id, 'status': self.status, 'ce...
You might need keys below in some situation - caCertificateId - previousOwnedBy
def normalize_object_slot(self, value=_nothing, prop=None, obj=None): """This hook wraps ``normalize_slot``, and performs clean-ups which require access to the object the slot is in as well as the value. """ if value is not _nothing and hasattr(prop, "compare_as"): method, na...
This hook wraps ``normalize_slot``, and performs clean-ups which require access to the object the slot is in as well as the value.
def _supply_data(data_sink, context): """ Supply data to the data sink """ try: data_sink.sink(context) except Exception as e: ex = ValueError("An exception occurred while " "supplying data to data sink '{ds}'\n\n" "{e}\n\n" "{help}".format(ds=context.name...
Supply data to the data sink
def __from_xml(self,value): """Initialize a `VCardAdr` object from and XML element. :Parameters: - `value`: field value as an XML node :Types: - `value`: `libxml2.xmlNode`""" n=value.children vns=get_node_ns(value) while n: if n.type!=...
Initialize a `VCardAdr` object from and XML element. :Parameters: - `value`: field value as an XML node :Types: - `value`: `libxml2.xmlNode`
def load_key(self, key, key_type, key_encoding): """Load a key from bytes. :param bytes key: Key bytes :param EncryptionKeyType key_type: Type of key :param KeyEncodingType key_encoding: Encoding used to serialize key :returns: Loaded key """ if key_type not in (...
Load a key from bytes. :param bytes key: Key bytes :param EncryptionKeyType key_type: Type of key :param KeyEncodingType key_encoding: Encoding used to serialize key :returns: Loaded key
def get_s3_bucket_keys(api_client, bucket_name, bucket, check_encryption, check_acls): """ Get key-specific information (server-side encryption, acls, etc...) :param api_client: :param bucket_name: :param bucket: :param check_encryption: :param check_acls: :return: """ bucket['k...
Get key-specific information (server-side encryption, acls, etc...) :param api_client: :param bucket_name: :param bucket: :param check_encryption: :param check_acls: :return: