code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def add_config_path(path): """Select config parser by file extension and add path into parser. """ if not os.path.isfile(path): warnings.warn("Config file does not exist: {path}".format(path=path)) return False # select parser by file extension _base, ext = os.path.splitext(path) ...
Select config parser by file extension and add path into parser.
def generate_look_up_table(): """ Generate look up table. :return: List """ poly = 0xA001 table = [] for index in range(256): data = index << 1 crc = 0 for _ in range(8, 0, -1): data >>= 1 if (data ^ crc) & 0x0001: crc = (crc >> ...
Generate look up table. :return: List
def _get_envs_from_ref_paths(self, refs): ''' Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags. ''' def _check_ref(env_set, rname): ''' Add the appropriate saltenv(s) to the set ''' ...
Return the names of remote refs (stripped of the remote name) and tags which are map to the branches and tags.
def make_route_refresh_request(self, peer_ip, *route_families): """Request route-refresh for peer with `peer_ip` for given `route_families`. Will make route-refresh request for a given `route_family` only if such capability is supported and if peer is in ESTABLISHED state. Else, such ...
Request route-refresh for peer with `peer_ip` for given `route_families`. Will make route-refresh request for a given `route_family` only if such capability is supported and if peer is in ESTABLISHED state. Else, such requests are ignored. Raises appropriate error in other cases. If ...
def _parse_coords(coord_lines): """ Helper method to parse coordinates. """ paras = {} var_pattern = re.compile(r"^([A-Za-z]+\S*)[\s=,]+([\d\-\.]+)$") for l in coord_lines: m = var_pattern.match(l.strip()) if m: paras[m.group(1).str...
Helper method to parse coordinates.
def get_popular_aliases(self, *args, **kwargs): """ Return the aggregated results of :meth:`Timesheet.get_popular_aliases`. """ aliases_count_total = defaultdict(int) aliases_counts = self._timesheets_callback('get_popular_aliases')(*args, **kwargs) for aliases_count in ...
Return the aggregated results of :meth:`Timesheet.get_popular_aliases`.
def process(in_path, out_file, n_jobs, framesync): """Computes the features for the selected dataset or file.""" if os.path.isfile(in_path): # Single file mode # Get (if they exitst) or compute features file_struct = msaf.io.FileStruct(in_path) file_struct.features_file = out_fil...
Computes the features for the selected dataset or file.
def _update_project(self, request, data): """Update project info""" domain_id = identity.get_domain_id_for_operation(request) try: project_id = data['project_id'] # add extra information if keystone.VERSIONS.active >= 3: EXTRA_INFO = getattr(s...
Update project info
def readtxt(filepath): """ read file as is""" with open(filepath, 'rt') as f: lines = f.readlines() return ''.join(lines)
read file as is
def run_id(self): '''Run name without whitespace ''' s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', self.__class__.__name__) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Run name without whitespace
def dicom_to_nifti(dicom_input, output_file=None): """ This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: dir...
This is the main dicom to nifti conversion function for ge images. As input ge images are required. It will then determine the type of images and do the correct conversion :param output_file: filepath to the output nifti :param dicom_input: directory with dicom files for 1 scan
def calculate_mrcas(self, c1 : ClassId, c2 : ClassId) -> Set[ClassId]: """ Calculate the MRCA for a class pair """ G = self.G # reflexive ancestors ancs1 = self._ancestors(c1) | {c1} ancs2 = self._ancestors(c2) | {c2} common_ancestors = ancs1 & ancs2 ...
Calculate the MRCA for a class pair
def update_to_v24(self): """Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag. """ self.__update_...
Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag.
def add(self, *constraints: Tuple[Bool]) -> None: """Adds the constraints to this solver. :param constraints: constraints to add """ raw_constraints = [ c.raw for c in cast(Tuple[Bool], constraints) ] # type: List[z3.BoolRef] self.constraints.extend(raw_cons...
Adds the constraints to this solver. :param constraints: constraints to add
def _cast_inplace(terms, acceptable_dtypes, dtype): """Cast an expression inplace. Parameters ---------- terms : Op The expression that should cast. acceptable_dtypes : list of acceptable numpy.dtype Will not cast if term's dtype in this list. .. versionadded:: 0.19.0 ...
Cast an expression inplace. Parameters ---------- terms : Op The expression that should cast. acceptable_dtypes : list of acceptable numpy.dtype Will not cast if term's dtype in this list. .. versionadded:: 0.19.0 dtype : str or numpy.dtype The dtype to cast to.
def setup_stream_handlers(conf): """Setup logging stream handlers according to the options.""" class StdoutFilter(logging.Filter): def filter(self, record): return record.levelno in (logging.DEBUG, logging.INFO) log.handlers = [] stdout_handler = logging.StreamHandler(sys.stdout) ...
Setup logging stream handlers according to the options.
def create_network(name, router_ext=None, admin_state_up=True, network_type=None, physical_network=None, segmentation_id=None, shared=None, profile=None): ''' Creates a new network CLI Example: .. code-block:: bash salt '*' neutron.create_network network-name salt '*' neutron.create_n...
Creates a new network CLI Example: .. code-block:: bash salt '*' neutron.create_network network-name salt '*' neutron.create_network network-name profile=openstack1 :param name: Name of network to create :param admin_state_up: should the state of the network be up? defaul...
def transform(self, data): """ :param data: DataFrame with column to encode :return: encoded Series """ with timer('transform %s' % self.name, logging.DEBUG): transformed = super(Token, self).transform(self.tokenize(data)) return transformed.reshape((len(d...
:param data: DataFrame with column to encode :return: encoded Series
def p_review_comment_1(self, p): """review_comment : REVIEW_COMMENT TEXT""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.add_review_comment(self.document, value) except CardinalityError:...
review_comment : REVIEW_COMMENT TEXT
def sdk_version(self): '''sdk version of connected device.''' if self.__sdk == 0: try: self.__sdk = int(self.adb.cmd("shell", "getprop", "ro.build.version.sdk").communicate()[0].decode("utf-8").strip()) except: pass return self.__sdk
sdk version of connected device.
def appendOps(self, ops, append_to=None): """ Append op(s) to the transaction builder :param list ops: One or a list of operations """ if isinstance(ops, list): self.ops.extend(ops) else: self.ops.append(ops) parent = self.parent if pa...
Append op(s) to the transaction builder :param list ops: One or a list of operations
def create_sample_file(ip, op, num_lines): """ make a short version of an RDF file """ with open(ip, "rb") as f: with open(op, "wb") as fout: for _ in range(num_lines): fout.write(f.readline() )
make a short version of an RDF file
def child_folder(self, fragment): """ Returns a folder object by combining the fragment to this folder's path """ return Folder(os.path.join(self.path, Folder(fragment).path))
Returns a folder object by combining the fragment to this folder's path
def init_app(self, app): """Register the extension with the application. Args: app (flask.Flask): The application to register with. """ app.url_rule_class = partial(NavigationRule, copilot=self) app.context_processor(self.inject_context)
Register the extension with the application. Args: app (flask.Flask): The application to register with.
def push_json_file(json_file, url, dry_run=False, batch_size=100, anonymize_fields=[], remove_fields=[], rename_fields=[]): """ read the json file provided and POST in batches no bigger than the ...
read the json file provided and POST in batches no bigger than the batch_size specified to the specified url.
def get_phi_subvariables(self, var): """ Get sub-variables that phi variable `var` represents. :param SimVariable var: The variable instance. :return: A set of sub-variables, or an empty set if `var` is not a phi variable. :rtype: set """ ...
Get sub-variables that phi variable `var` represents. :param SimVariable var: The variable instance. :return: A set of sub-variables, or an empty set if `var` is not a phi variable. :rtype: set
def _rotate(coordinates, theta, around): """Rotate a set of coordinates around an arbitrary vector. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being rotated. theta : float The angle by which to rotate the coordinates, in radians. aro...
Rotate a set of coordinates around an arbitrary vector. Parameters ---------- coordinates : np.ndarray, shape=(n,3), dtype=float The coordinates being rotated. theta : float The angle by which to rotate the coordinates, in radians. around : np.ndarray, shape=(3,), dtype=float ...
def GetWindowsEventMessage(self, log_source, message_identifier): """Retrieves the message string for a specific Windows Event Log source. Args: log_source (str): Event Log source, such as "Application Error". message_identifier (int): message identifier. Returns: str: message string or ...
Retrieves the message string for a specific Windows Event Log source. Args: log_source (str): Event Log source, such as "Application Error". message_identifier (int): message identifier. Returns: str: message string or None if not available.
def run_vardict(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Run VarDict variant calling. """ items = shared.add_highdepth_genome_exclusion(items) if vcfutils.is_paired_analysis(align_bams, items): call_file = _run_vardict_paired(align_bams, items, re...
Run VarDict variant calling.
def process_request(self, request): """ Checks whether the page is already cached and returns the cached version if available. """ celery_task = getattr(request, '_cache_update_cache', False) if not request.method in ('GET', 'HEAD'): request._cache_update_cac...
Checks whether the page is already cached and returns the cached version if available.
def probable_languages( self, text: str, max_languages: int = 3) -> Tuple[str, ...]: """List of most probable programming languages, the list is ordered from the most probable to the least probable one. :param text: source code. :param max_languages: ...
List of most probable programming languages, the list is ordered from the most probable to the least probable one. :param text: source code. :param max_languages: maximum number of listed languages. :return: languages list
def get_running_time(self): """ Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds. """ if win32.PROCESS_ALL_ACCESS == win32.PROCESS_ALL_ACCESS_VISTA: dwAccess = win32.PROCESS_QUERY_LIMITED_INFORMATI...
Determines how long has this process been running. @rtype: long @return: Process running time in milliseconds.
def score(self, model): """ Computes a score to measure how well the given `BayesianModel` fits to the data set. (This method relies on the `local_score`-method that is implemented in each subclass.) Parameters ---------- model: `BayesianModel` instance The B...
Computes a score to measure how well the given `BayesianModel` fits to the data set. (This method relies on the `local_score`-method that is implemented in each subclass.) Parameters ---------- model: `BayesianModel` instance The Bayesian network that is to be scored. Nodes ...
def list_aliases(self): """List aliases linked to the index""" # check alias doesn't exist r = self.requests.get(self.index_url + "/_alias", headers=HEADER_JSON, verify=False) try: r.raise_for_status() except requests.exceptions.HTTPError as ex: logger.wa...
List aliases linked to the index
def onchain_exchange(self, withdraw_crypto, withdraw_address, value, unit='satoshi'): """ This method is like `add_output` but it sends to another """ self.onchain_rate = get_onchain_exchange_rates( self.crypto, withdraw_crypto, best=True, verbose=self.verbose ) ...
This method is like `add_output` but it sends to another
def _serve_dir(self, abspath, params): """Show a directory listing.""" relpath = os.path.relpath(abspath, self._root) breadcrumbs = self._create_breadcrumbs(relpath) entries = [{'link_path': os.path.join(relpath, e), 'name': e} for e in os.listdir(abspath)] args = self._default_template_args('dir.ht...
Show a directory listing.
def get_community_names(): ''' Get the current accepted SNMP community names and their permissions. If community names are being managed by Group Policy, those values will be returned instead like this: .. code-block:: bash TestCommunity: Managed by GPO Community names ma...
Get the current accepted SNMP community names and their permissions. If community names are being managed by Group Policy, those values will be returned instead like this: .. code-block:: bash TestCommunity: Managed by GPO Community names managed normally will denote the permissi...
def _urlopen_as_json(self, url, headers=None): """Shorcut for return contents as json""" req = Request(url, headers=headers) return json.loads(urlopen(req).read())
Shorcut for return contents as json
def log_parameters(self): """ Logs information about model parameters. """ arg_params, aux_params = self.module.get_params() total_parameters = 0 fixed_parameters = 0 learned_parameters = 0 info = [] # type: List[str] for name, array in sorted(arg...
Logs information about model parameters.
def open(self, data_source, *args, **kwargs): """ Open filename to get data for data_source. :param data_source: Data source for which the file contains data. :type data_source: str Positional and keyword arguments can contain either the data to use for the data source ...
Open filename to get data for data_source. :param data_source: Data source for which the file contains data. :type data_source: str Positional and keyword arguments can contain either the data to use for the data source or the full path of the file which contains data for the d...
def _minimum_coloring_qubo(x_vars, chi_lb, chi_ub, magnitude=1.): """We want to disincentivize unneeded colors. Generates the QUBO that does that. """ # if we already know the chromatic number, then we don't need to # disincentivize any colors. if chi_lb == chi_ub: return {} # we mi...
We want to disincentivize unneeded colors. Generates the QUBO that does that.
def generate(cls, strategy, **kwargs): """Generate a new instance. The instance will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. Returns: ...
Generate a new instance. The instance will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY). Args: strategy (str): the strategy to use for generating the instance. Returns: object: the generated instance
def _make_connection(self, addr, port): "make our proxy connection" sender = self._create_connection(addr, port) # XXX look out! we're depending on this "sender" implementing # certain Twisted APIs, and the state-machine shouldn't depend # on that. # XXX also, if sender ...
make our proxy connection
def delete_blobs(self, blobs, on_error=None, client=None): """Deletes a list of blobs from the current bucket. Uses :meth:`delete_blob` to delete each individual blob. If :attr:`user_project` is set, bills the API request to that project. :type blobs: list :param blobs: A list...
Deletes a list of blobs from the current bucket. Uses :meth:`delete_blob` to delete each individual blob. If :attr:`user_project` is set, bills the API request to that project. :type blobs: list :param blobs: A list of :class:`~google.cloud.storage.blob.Blob`-s or ...
def before(self, idx): """Return datetime of newest existing data record whose datetime is < idx. Might not even be in the same year! If no such record exists, return None.""" if not isinstance(idx, datetime): raise TypeError("'%s' is not %s" % (idx, datetime)) ...
Return datetime of newest existing data record whose datetime is < idx. Might not even be in the same year! If no such record exists, return None.
def update_status(self, *args, **kwargs): """ :reference: https://dev.twitter.com/rest/reference/post/statuses/update :allowed_param:'status', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'auto_populate_reply_metadata', 'lat', 'long', 'source', 'place_id', 'display_coordinates', 'media_ids'...
:reference: https://dev.twitter.com/rest/reference/post/statuses/update :allowed_param:'status', 'in_reply_to_status_id', 'in_reply_to_status_id_str', 'auto_populate_reply_metadata', 'lat', 'long', 'source', 'place_id', 'display_coordinates', 'media_ids'
def determine_paths(self, package_name=None, create_package_dir=False, dry_run=False): """Determine paths automatically and a little intelligently""" # Give preference to the environment variable here as it will not # derefrence sym links self.project_dir = Path(os.getenv('PWD'...
Determine paths automatically and a little intelligently
def match_list(lst, pattern, group_names=[]): """ Parameters ---------- lst: list of str regex: string group_names: list of strings See re.MatchObject group docstring Returns ------- list of strings Filtered list, with the strings that match the pattern """ ...
Parameters ---------- lst: list of str regex: string group_names: list of strings See re.MatchObject group docstring Returns ------- list of strings Filtered list, with the strings that match the pattern
def unindex_item(self, item): """ Un-index an item from our name_to_item dict. :param item: the item to un-index :type item: alignak.objects.item.Item :return: None """ name_property = getattr(self.__class__, "name_property", None) if name_property is None...
Un-index an item from our name_to_item dict. :param item: the item to un-index :type item: alignak.objects.item.Item :return: None
def x_fit(self, test_length): """ Test to see if the line can has enough space for the given length. """ if (self.x + test_length) >= self.xmax: return False else: return True
Test to see if the line can has enough space for the given length.
def guard_multi_verify(analysis): """Return whether the transition "multi_verify" can be performed or not The transition multi_verify will only take place if multi-verification of results is enabled. """ # Cannot multiverify if there is only one remaining verification remaining_verifications = a...
Return whether the transition "multi_verify" can be performed or not The transition multi_verify will only take place if multi-verification of results is enabled.
def check_image_is_3d(img): """Ensures the image loaded is 3d and nothing else.""" if len(img.shape) < 3: raise ValueError('Input volume must be atleast 3D!') elif len(img.shape) == 3: for dim_size in img.shape: if dim_size < 1: raise ValueError('Atleast one slic...
Ensures the image loaded is 3d and nothing else.
def compile_file(self, filename, encoding="utf-8", bare=False): '''compile a CoffeeScript script file to a JavaScript code. filename can be a list or tuple of filenames, then contents of files are concatenated with line feeds. if bare is True, then compile the JavaScript without the to...
compile a CoffeeScript script file to a JavaScript code. filename can be a list or tuple of filenames, then contents of files are concatenated with line feeds. if bare is True, then compile the JavaScript without the top-level function safety wrapper (like the coffee command).
def parseDateText(self, dateString, sourceTime=None): """ Parse long-form date strings:: 'May 31st, 2006' 'Jan 1st' 'July 2006' @type dateString: string @param dateString: text to convert to a datetime @type sourceTime: struct_time ...
Parse long-form date strings:: 'May 31st, 2006' 'Jan 1st' 'July 2006' @type dateString: string @param dateString: text to convert to a datetime @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base ...
def connect(self, uri, link_quality_callback, link_error_callback): """ Connect the link driver to a specified URI of the format: radio://<dongle nbr>/<radio channel>/[250K,1M,2M] The callback for linkQuality can be called at any moment from the driver to report back the link qu...
Connect the link driver to a specified URI of the format: radio://<dongle nbr>/<radio channel>/[250K,1M,2M] The callback for linkQuality can be called at any moment from the driver to report back the link quality in percentage. The callback from linkError will be called when a error occ...
def register(CommandSubClass): """A class decorator for Command classes to register in the default set.""" name = CommandSubClass.name() if name in Command._all_commands: raise ValueError("Command already exists: " + name) Command._all_commands[name] = CommandSubClass return CommandSubClass
A class decorator for Command classes to register in the default set.
def __get_dbms_version(self, make_connection=True): """ Returns the 'DBMS Version' string """ major, minor, _, _ = self.get_server_version(make_connection=make_connection) return '{}.{}'.format(major, minor)
Returns the 'DBMS Version' string
def merge(self, dataset): """ Merge the specified dataset on top of the existing data. This replaces all values in the existing dataset with the values from the given dataset. Args: dataset (TaskData): A reference to the TaskData object that should be merged ...
Merge the specified dataset on top of the existing data. This replaces all values in the existing dataset with the values from the given dataset. Args: dataset (TaskData): A reference to the TaskData object that should be merged on top of the existing object.
def set_dft_grid(self, radical_points=128, angular_points=302, grid_type="Lebedev"): """ Set the grid for DFT numerical integrations. Args: radical_points: Radical points. (Integer) angular_points: Angular points. (Integer) grid_type: The...
Set the grid for DFT numerical integrations. Args: radical_points: Radical points. (Integer) angular_points: Angular points. (Integer) grid_type: The type of of the grid. There are two standard grids: SG-1 and SG-0. The other two supported grids are "Lebedev"...
def _migration_required(connection): """ Returns True if ambry models do not match to db tables. Otherwise returns False. """ stored_version = get_stored_version(connection) actual_version = SCHEMA_VERSION assert isinstance(stored_version, int) assert isinstance(actual_version, int) assert store...
Returns True if ambry models do not match to db tables. Otherwise returns False.
def _discover_cover_image(zf, opf_xmldoc, opf_filepath): ''' Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension) ''' content = None filepath = None extension = None # Strategies to discover the cover-image path: # e.g.: <meta name="...
Find the cover image path in the OPF file. Returns a tuple: (image content in base64, file extension)
def Max(self, k): """Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf """ cdf = self.MakeCdf() cdf.ps = [p ** k for p in cdf.ps] return cdf
Computes the CDF of the maximum of k selections from this dist. k: int returns: new Cdf
def handle_document(self, item_session: ItemSession, filename: str) -> Actions: '''Process a successful document response. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) if action == Action...
Process a successful document response. Returns: A value from :class:`.hook.Actions`.
def bezier_real_minmax(p): """returns the minimum and maximum for any real cubic bezier""" local_extremizers = [0, 1] if len(p) == 4: # cubic case a = [p.real for p in p] denom = a[0] - 3*a[1] + 3*a[2] - a[3] if denom != 0: delta = a[1]**2 - (a[0] + a[1])*a[2] + a[2]**2 ...
returns the minimum and maximum for any real cubic bezier
def experience( self, agent_indices, observ, action, reward, unused_done, unused_nextob): """Process the transition tuple of the current step. When training, add the current transition tuple to the memory and update the streaming statistics for observations and rewards. A summary string is return...
Process the transition tuple of the current step. When training, add the current transition tuple to the memory and update the streaming statistics for observations and rewards. A summary string is returned if requested at this step. Args: agent_indices: Tensor containing current batch indices. ...
def add_comment(node, text, location='above'): """Add a comment to the given node. If the `SourceWithCommentGenerator` class is used these comments will be output as part of the source code. Note that a node can only contain one comment. Subsequent calls to `add_comment` will ovverride the existing comments...
Add a comment to the given node. If the `SourceWithCommentGenerator` class is used these comments will be output as part of the source code. Note that a node can only contain one comment. Subsequent calls to `add_comment` will ovverride the existing comments. Args: node: The AST node whose containing s...
def _get_all_objs( self, server_instance, regexes=None, include_only_marked=False, tags=None, use_guest_hostname=False ): """ Explore vCenter infrastructure to discover hosts, virtual machines, etc. and compute their associated tags. Start at the vCenter `rootFolder`, so as t...
Explore vCenter infrastructure to discover hosts, virtual machines, etc. and compute their associated tags. Start at the vCenter `rootFolder`, so as to collect every objet. Example topology: ``` rootFolder - datacenter1 - compute_resou...
def get_version(self, dependency): """Return the installed version parsing the output of 'pip show'.""" logger.debug("getting installed version for %s", dependency) stdout = helpers.logged_exec([self.pip_exe, "show", str(dependency)]) version = [line for line in stdout if line.startswith...
Return the installed version parsing the output of 'pip show'.
def p_expression_sla(self, p): 'expression : expression LSHIFTA expression' p[0] = Sll(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : expression LSHIFTA expression
def set(self, dic, val=None, force=False): """set can assign versatile options from `CMAOptions.versatile_options()` with a new value, use `init()` for the others. Arguments --------- `dic` either a dictionary or a key. In the latter c...
set can assign versatile options from `CMAOptions.versatile_options()` with a new value, use `init()` for the others. Arguments --------- `dic` either a dictionary or a key. In the latter case, `val` must be provided `val` ...
def write(self, data, sections=None): """ Write the data to the output socket. """ if self.error[0]: self.status = self.error[0] data = b(self.error[1]) if not self.headers_sent: self.send_headers(data, sections) if self.request_method != 'HEAD': ...
Write the data to the output socket.
def workflow_close(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /workflow-xxxx/close API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Data-Object-Lifecycle#API-method%3A-%2Fclass-xxxx%2Fclose """ return DXHTTPRequest('/%s/close' % objec...
Invokes the /workflow-xxxx/close API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Data-Object-Lifecycle#API-method%3A-%2Fclass-xxxx%2Fclose
def save_pid(name): """ When debugging and profiling, it is very annoying to poke through the process list to discover the currently running Ansible and MuxProcess IDs, especially when trying to catch an issue during early startup. So here, if a magic environment variable set, stash them in hidden f...
When debugging and profiling, it is very annoying to poke through the process list to discover the currently running Ansible and MuxProcess IDs, especially when trying to catch an issue during early startup. So here, if a magic environment variable set, stash them in hidden files in the CWD:: alias...
def expand_factor_conditions(s, env): """If env matches the expanded factor then return value else return ''. Example ------- >>> s = 'py{33,34}: docformatter' >>> expand_factor_conditions(s, Env(name="py34", ...)) "docformatter" >>> expand_factor_conditions(s, Env(name="py26", ...)) ""...
If env matches the expanded factor then return value else return ''. Example ------- >>> s = 'py{33,34}: docformatter' >>> expand_factor_conditions(s, Env(name="py34", ...)) "docformatter" >>> expand_factor_conditions(s, Env(name="py26", ...)) ""
def get_platforms_set(): '''Returns set of all possible platforms''' # arch and mageia are not in Py2 _supported_dists, so we add them manually # Ubuntu adds itself to the list on Ubuntu platforms = set([x.lower() for x in platform._supported_dists]) platforms |= set(['darwin', 'arch', 'mageia', 'ub...
Returns set of all possible platforms
def filter(self, *args, **kwargs): """ Apply filters to the existing nodes in the set. :param kwargs: filter parameters Filters mimic Django's syntax with the double '__' to separate field and operators. e.g `.filter(salary__gt=20000)` results in `salary > 20000`. ...
Apply filters to the existing nodes in the set. :param kwargs: filter parameters Filters mimic Django's syntax with the double '__' to separate field and operators. e.g `.filter(salary__gt=20000)` results in `salary > 20000`. The following operators are available: ...
def decode(self, msgbuf): '''decode a buffer as a MAVLink message''' # decode the header if msgbuf[0] != PROTOCOL_MARKER_V1: headerlen = 10 try: magic, mlen, incompat_flags, compat_flags, seq, srcSystem, srcC...
decode a buffer as a MAVLink message
def get_queryset(self, value, row, *args, **kwargs): """ Returns a queryset of all objects for this Model. Overwrite this method if you want to limit the pool of objects from which the related object is retrieved. :param value: The field's value in the datasource. :para...
Returns a queryset of all objects for this Model. Overwrite this method if you want to limit the pool of objects from which the related object is retrieved. :param value: The field's value in the datasource. :param row: The datasource's current row. As an example; if you'd lik...
def _init_client(self, from_archive=False): """Init client""" return BugzillaClient(self.url, user=self.user, password=self.password, max_bugs_csv=self.max_bugs_csv, archive=self.archive, from_archive=from_archive)
Init client
def _try_resolve_sam_resource_refs(self, input, supported_resource_refs): """ Try to resolve SAM resource references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input ...
Try to resolve SAM resource references on the given template. If the given object looks like one of the supported intrinsics, it calls the appropriate resolution on it. If not, this method returns the original input unmodified. :param dict input: Dictionary that may represent an intrinsic funct...
def _postprocess_for_cut(fac, bins, retbins, x_is_series, series_index, name, dtype): """ handles post processing for the cut method where we combine the index information if the originally passed datatype was a series """ if x_is_series: fac = Series(fac, index=...
handles post processing for the cut method where we combine the index information if the originally passed datatype was a series
def endpoint_catalog(catalog=None): # noqa: E501 """Retrieve the endpoint catalog Retrieve the endpoint catalog # noqa: E501 :param catalog: The data needed to get a catalog :type catalog: dict | bytes :rtype: Response """ if connexion.request.is_json: catalog = UserAuth.from_dic...
Retrieve the endpoint catalog Retrieve the endpoint catalog # noqa: E501 :param catalog: The data needed to get a catalog :type catalog: dict | bytes :rtype: Response
def compute_threat_list_diff( self, threat_type, constraints, version_token=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the most recent threat list diffs. ...
Gets the most recent threat list diffs. Example: >>> from google.cloud import webrisk_v1beta1 >>> from google.cloud.webrisk_v1beta1 import enums >>> >>> client = webrisk_v1beta1.WebRiskServiceV1Beta1Client() >>> >>> # TODO: Initialize `thr...
def CrearLiquidacion(self, tipo_cbte, pto_vta, nro_cbte, fecha, periodo, iibb_adquirente=None, domicilio_sede=None, inscripcion_registro_publico=None, datos_adicionales=None, alicuota_iva=None, **kwargs): "Inicializa internamente los da...
Inicializa internamente los datos de una liquidación para autorizar
def bishop88_i_from_v(voltage, photocurrent, saturation_current, resistance_series, resistance_shunt, nNsVth, method='newton'): """ Find current given any voltage. Parameters ---------- voltage : numeric voltage (V) in volts [V] photocurrent :...
Find current given any voltage. Parameters ---------- voltage : numeric voltage (V) in volts [V] photocurrent : numeric photogenerated current (Iph or IL) in amperes [A] saturation_current : numeric diode dark or saturation current (Io or Isat) in amperes [A] resistance_...
def _unpack_result(klass, result): '''Convert a D-BUS return variant into an appropriate return value''' result = result.unpack() # to be compatible with standard Python behaviour, unbox # single-element tuples and return None for empty result tuples if len(result) == 1: ...
Convert a D-BUS return variant into an appropriate return value
def find_all(self, *args, **kwargs): """ Like :meth:`find`, but selects all matches (not just the first one). Returns a :class:`Collection`. If no elements match, this returns a Collection with no items. """ op = operator.methodcaller('find_all', *args, **kwargs) ...
Like :meth:`find`, but selects all matches (not just the first one). Returns a :class:`Collection`. If no elements match, this returns a Collection with no items.
def get_lock_requests(self): """Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If...
Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty ...
def calls(self, call): """Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there' """ exp = self._get_current_call() exp.call_re...
Redefine a call. The fake method will execute your function. I.E.:: >>> f = Fake().provides('hello').calls(lambda: 'Why, hello there') >>> f.hello() 'Why, hello there'
def subscriptions_list(**kwargs): ''' .. versionadded:: 2019.2.0 List all subscriptions for a tenant. CLI Example: .. code-block:: bash salt-call azurearm_resource.subscriptions_list ''' result = {} subconn = __utils__['azurearm.get_client']('subscription', **kwargs) try...
.. versionadded:: 2019.2.0 List all subscriptions for a tenant. CLI Example: .. code-block:: bash salt-call azurearm_resource.subscriptions_list
def set_group(self, group): """Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group size of each group """ _check_call(_LIB.XGDMatrixSetGroup(self.handle, c_array(ctypes.c_uint...
Set group size of DMatrix (used for ranking). Parameters ---------- group : array like Group size of each group
def _group(self, rdd): """Group together the values with the same key.""" return rdd.reduceByKey(lambda x, y: x.append(y))
Group together the values with the same key.
def _advapi32_generate_pair(algorithm, bit_size=None): """ Generates a public/private key pair using CryptoAPI :param algorithm: The key algorithm - "rsa" or "dsa" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For ...
Generates a public/private key pair using CryptoAPI :param algorithm: The key algorithm - "rsa" or "dsa" :param bit_size: An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024, 2048, 3072 or 4096. For "dsa" the value may be 1024. :raises: ValueError - whe...
def normalize_partial_name(decl): """ Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name """ if decl.cache.normalized_partial_name is None: decl.cache.normalized_partial_name = normalize(decl.partial_name) ...
Cached variant of normalize Args: decl (declaration.declaration_t): the declaration Returns: str: normalized name
def f_translate_key(self, key): """Translates integer indices into the appropriate names""" if isinstance(key, int): if key == 0: key = self.v_name else: key = self.v_name + '_%d' % key return key
Translates integer indices into the appropriate names
def add_step(step_name, func): """ Add a step function to Orca. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argument name "iter_var" may be used to have the current iteration variable ...
Add a step function to Orca. The function's argument names and keyword argument values will be matched to registered variables when the function needs to be evaluated by Orca. The argument name "iter_var" may be used to have the current iteration variable injected. Parameters ---------- ...
def zoom(params, factor): """ Applies a zoom on the current parameters. Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates. :param params: Current application parameters. :param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom) "...
Applies a zoom on the current parameters. Computes the top-left plane-space coordinates from the Mandelbrot-space coordinates. :param params: Current application parameters. :param factor: Zoom factor by which the zoom ratio is divided (bigger factor, more zoom)
def read_until_done(self, command, timeout=None): """Yield messages read until we receive a 'DONE' command. Read messages of the given command until we receive a 'DONE' command. If a command different than the requested one is received, an AdbProtocolError is raised. Args: command: The comm...
Yield messages read until we receive a 'DONE' command. Read messages of the given command until we receive a 'DONE' command. If a command different than the requested one is received, an AdbProtocolError is raised. Args: command: The command to expect, like 'DENT' or 'DATA'. timeout: The ...
def clean_up(self):#, grid): """ de-select grid cols, refresh grid """ if self.selected_col: col_label_value = self.grid.GetColLabelValue(self.selected_col) col_label_value = col_label_value.strip('\nEDIT ALL') self.grid.SetColLabelValue(self.selected_...
de-select grid cols, refresh grid
def lint(fix_imports): """ Run flake8. """ from glob import glob from subprocess import call # FIXME: should support passing these in an option skip = [ 'ansible', 'db', 'flask_sessions', 'node_modules', 'requirements', ] root_files = glob('*....
Run flake8.