code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def data(self): """ Returns self.json loaded as a python object. """ try: data = self._data except AttributeError: data = self._data = json.loads(self.json) return data
Returns self.json loaded as a python object.
def dbmin10years(self, value=None): """ Corresponds to IDD Field `dbmin10years` 10-year return period values for minimum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmin10years` Unit: C if `value` is None it will not be ch...
Corresponds to IDD Field `dbmin10years` 10-year return period values for minimum extreme dry-bulb temperature Args: value (float): value for IDD Field `dbmin10years` Unit: C if `value` is None it will not be checked against the specification a...
def build_java_worker_command( java_worker_options, redis_address, plasma_store_name, raylet_name, redis_password, temp_dir, ): """This method assembles the command used to start a Java worker. Args: java_worker_options (str): The command options for Java...
This method assembles the command used to start a Java worker. Args: java_worker_options (str): The command options for Java worker. redis_address (str): Redis address of GCS. plasma_store_name (str): The name of the plasma store socket to connect to. raylet_name (str): T...
def clean_course(self): """ Verify course ID and retrieve course details. """ course_id = self.cleaned_data[self.Fields.COURSE].strip() if not course_id: return None try: client = EnrollmentApiClient() return client.get_course_details(c...
Verify course ID and retrieve course details.
def decrease_frequency(self, frequency=None): """ Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int """ if frequency is None: javabridge.call(self.jobject, "decreaseFrequency", "()V") else: ...
Decreases the frequency. :param frequency: the frequency to decrease by, 1 if None :type frequency: int
def _process_response_xml(self, response_xml): ''' Processa o xml de resposta e caso não existam erros retorna um dicionario com o codigo e data. :return: dictionary ''' result = {} xml = ElementTree.fromstring(response_xml) if xml.tag == 'errors': ...
Processa o xml de resposta e caso não existam erros retorna um dicionario com o codigo e data. :return: dictionary
def purge(self, queue, nowait=True, ticket=None, cb=None): ''' Purge all messages in a queue. ''' nowait = nowait and self.allow_nowait() and not cb args = Writer() args.write_short(ticket or self.default_ticket).\ write_shortstr(queue).\ write_bi...
Purge all messages in a queue.
def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102 num_processes=CPU_COUNT): """ Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for val...
Parallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. ...
def clone(self): """ Command Section: clone Clone a VM from a template """ self.config['hostname'] = self.config['hostname'].lower() self.config['mem'] = int(self.config['mem'] * 1024) # convert GB to MB print("Cloning %s to new host %s with %sMB RAM..." % ( ...
Command Section: clone Clone a VM from a template
def boxes_intersect(box1, box2): """Determines if two rectangles, each input as a tuple (xmin, xmax, ymin, ymax), intersect.""" xmin1, xmax1, ymin1, ymax1 = box1 xmin2, xmax2, ymin2, ymax2 = box2 if interval_intersection_width(xmin1, xmax1, xmin2, xmax2) and \ interval_intersection_w...
Determines if two rectangles, each input as a tuple (xmin, xmax, ymin, ymax), intersect.
def difference(self, other, sort=None): """ Compute set difference of two MultiIndex objects Parameters ---------- other : MultiIndex sort : False or None, default None Sort the resulting MultiIndex if possible .. versionadded:: 0.24.0 ...
Compute set difference of two MultiIndex objects Parameters ---------- other : MultiIndex sort : False or None, default None Sort the resulting MultiIndex if possible .. versionadded:: 0.24.0 .. versionchanged:: 0.24.1 Changed the de...
def enable_external_loaders(obj): """Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF` """ for name, loader in ct.EXTERNAL_LOADERS.items(): enabled = getattr( obj, "{}_ENABLED_FOR_DYNACONF".format(name.upper()), False ...
Enable external service loaders like `VAULT_` and `REDIS_` looks forenv variables like `REDIS_ENABLED_FOR_DYNACONF`
def fit(self): """Fit MCMC AgeDepthModel""" self._mcmcfit = self.mcmcsetup.run() self._mcmcfit.burnin(self.burnin) dmin = min(self._mcmcfit.depth_segments) dmax = max(self._mcmcfit.depth_segments) self._thick = (dmax - dmin) / len(self.mcmcfit.depth_segments) self...
Fit MCMC AgeDepthModel
def _netstat_route_sunos(): ''' Return netstat routing information for SunOS ''' ret = [] cmd = 'netstat -f inet -rn | tail +5' out = __salt__['cmd.run'](cmd, python_shell=True) for line in out.splitlines(): comps = line.split() ret.append({ 'addr_family': 'inet',...
Return netstat routing information for SunOS
def read_snapshots(path, comments="#", directed=False, delimiter=None, nodetype=None, timestamptype=None, encoding='utf-8', keys=False): """Read a DyNetx graph from snapshot graph list format. Parameters ---------- path : basestring The desired output filena...
Read a DyNetx graph from snapshot graph list format. Parameters ---------- path : basestring The desired output filename delimiter : character Column delimiter
def request(self, method, url, **kwargs): """ Overrides ``requests.Session.request`` to renew the cookie and then retry the original request (if required). """ resp = super(CookieSession, self).request(method, url, **kwargs) if not self._auto_renew: return re...
Overrides ``requests.Session.request`` to renew the cookie and then retry the original request (if required).
def _iter_restrict(self, zeros, ones): """Iterate through indices of all table entries that vary.""" inputs = list(self.inputs) unmapped = dict() for i, v in enumerate(self.inputs): if v in zeros: inputs[i] = 0 elif v in ones: input...
Iterate through indices of all table entries that vary.
def _setup_states(state_definitions, prev=()): """Create a StateList object from a 'states' Workflow attribute.""" states = list(prev) for state_def in state_definitions: if len(state_def) != 2: raise TypeError( "The 'state' attribute of a workflow should be " ...
Create a StateList object from a 'states' Workflow attribute.
def resolve(self, geoid, id_only=False): ''' Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_on...
Resolve a GeoZone given a GeoID. The start date is resolved from the given GeoID, ie. it find there is a zone valid a the geoid validity, resolve the `latest` alias or use `latest` when no validity is given. If `id_only` is True, the result will be the resolved GeoID ...
def handle_no_document(self, item_session: ItemSession) -> Actions: '''Callback for successful responses containing no useful document. Returns: A value from :class:`.hook.Actions`. ''' self._waiter.reset() action = self.handle_response(item_session) if act...
Callback for successful responses containing no useful document. Returns: A value from :class:`.hook.Actions`.
def _constrain_pan(self): """Constrain bounding box.""" if self.xmin is not None and self.xmax is not None: p0 = self.xmin + 1. / self._zoom[0] p1 = self.xmax - 1. / self._zoom[0] p0, p1 = min(p0, p1), max(p0, p1) self._pan[0] = np.clip(self._pan[0], p0, p...
Constrain bounding box.
def predict(self, t): """Predict the smoothed function value at time t Parameters ---------- t : array_like Times at which to predict the result Returns ------- y : ndarray Smoothed values at time t """ t = np.asarray(t) ...
Predict the smoothed function value at time t Parameters ---------- t : array_like Times at which to predict the result Returns ------- y : ndarray Smoothed values at time t
def send(self, value): """ Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chain...
Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chaining
def kth_to_last_dict(head, k): """ This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False """ if not (head and k > -1): return False d = dict()...
This is a brute force method where we keep a dict the size of the list Then we check it for the value we need. If the key is not in the dict, our and statement will short circuit and return False
def listunspent(self, address: str) -> list: '''Returns unspent transactions for given address.''' try: return cast(dict, self.ext_fetch('listunspent/' + address))['unspent_outputs'] except KeyError: raise InsufficientFunds('Insufficient funds.')
Returns unspent transactions for given address.
def get_next_event(event, now): """ Returns the next occurrence of a given event, relative to 'now'. The 'event' arg should be an iterable containing one element, namely the event we'd like to find the occurrence of. The reason for this is b/c the get_count() function of CountHandler, which this...
Returns the next occurrence of a given event, relative to 'now'. The 'event' arg should be an iterable containing one element, namely the event we'd like to find the occurrence of. The reason for this is b/c the get_count() function of CountHandler, which this func makes use of, expects an iterable. ...
def _set_active_policy(self, v, load=False): """ Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_policy is considered as a private method. Backends looki...
Setter method for active_policy, mapped from YANG variable /rbridge_id/secpolicy/active_policy (container) If this variable is read-only (config: false) in the source YANG file, then _set_active_policy is considered as a private method. Backends looking to populate this variable should do so via calling...
def ellipse(self, x,y,w,h,style=''): "Draw a ellipse" if(style=='F'): op='f' elif(style=='FD' or style=='DF'): op='B' else: op='S' cx = x + w/2.0 cy = y + h/2.0 rx = w/2.0 ry = h/2.0 lx = 4.0/3.0*(math.sqrt(2)-...
Draw a ellipse
def _construct_from_json(self, rec): """ Construct this Dagobah instance from a JSON document. """ self.delete() for required_key in ['dagobah_id', 'created_jobs']: setattr(self, required_key, rec[required_key]) for job_json in rec.get('jobs', []): self._add_jo...
Construct this Dagobah instance from a JSON document.
def _sync_string_to(bin_or_str, string): """ Python 3 compliance: ensure two strings are the same type (unicode or binary) """ if isinstance(string, type(bin_or_str)): return string elif isinstance(string, binary_type): return string.decode(DEFAULT_ENCODING) else: return string....
Python 3 compliance: ensure two strings are the same type (unicode or binary)
def get_grades(self): """Gets the grades in this system ranked from highest to lowest. return: (osid.grading.GradeList) - the list of grades raise: IllegalState - ``is_based_on_grades()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -...
Gets the grades in this system ranked from highest to lowest. return: (osid.grading.GradeList) - the list of grades raise: IllegalState - ``is_based_on_grades()`` is ``false`` raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented...
def _do_search(self): """ Perform the mlt call, then convert that raw format into a SearchResults instance and return it. """ if self._results_cache is None: response = self.raw() results = self.to_python(response.get('hits', {}).get('hits', [])) ...
Perform the mlt call, then convert that raw format into a SearchResults instance and return it.
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None): """ Add an entry to the system crontab. """ raise NotImplementedError
Add an entry to the system crontab.
def get_tc_api(self, host, headers=None, cert=None, logger=None): ''' Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods...
Gets HttpApi wrapped into a neat little package that raises TestStepFail if expected status code is not returned by the server. Default setting for expected status code is 200. Set expected to None when calling methods to ignore the expected status code parameter or set raiseException = ...
def torecarray(*args, **kwargs): """ Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``. """ import numpy as np return toarray(*args, **kwargs).view(np.recarray)
Convenient shorthand for ``toarray(*args, **kwargs).view(np.recarray)``.
def shader_substring(body, stack_frame=1): """ Call this method from a function that defines a literal shader string as the "body" argument. Dresses up a shader string in two ways: 1) Insert #line number declaration 2) un-indents The line number information can help debug glsl comp...
Call this method from a function that defines a literal shader string as the "body" argument. Dresses up a shader string in two ways: 1) Insert #line number declaration 2) un-indents The line number information can help debug glsl compile errors. The unindenting allows you to type the s...
def schedule_task(self, task_id): """Schedule a task. :param task_id: identifier of the task to schedule :raises NotFoundError: raised when the requested task is not found in the registry """ task = self.registry.get(task_id) job_args = self._build_job_argu...
Schedule a task. :param task_id: identifier of the task to schedule :raises NotFoundError: raised when the requested task is not found in the registry
def parse_row(self, row, row_index, cell_mode=CellMode.cooked): """Parse a row according to the given cell_mode.""" return [self.parse_cell(cell, (col_index, row_index), cell_mode) \ for col_index, cell in enumerate(row)]
Parse a row according to the given cell_mode.
def timeseries(X, **kwargs): """Plot X. See timeseries_subplot.""" pl.figure(figsize=(2*rcParams['figure.figsize'][0], rcParams['figure.figsize'][1]), subplotpars=sppars(left=0.12, right=0.98, bottom=0.13)) timeseries_subplot(X, **kwargs)
Plot X. See timeseries_subplot.
def parse_filename_meta(filename): """ taken from suvi code by vhsu Parse the metadata from a product filename, either L1b or l2. - file start - file end - platform - product :param filename: string filename of product :return: (start ...
taken from suvi code by vhsu Parse the metadata from a product filename, either L1b or l2. - file start - file end - platform - product :param filename: string filename of product :return: (start datetime, end datetime, platform)
def _pi_id(self): """Try to detect id of a Raspberry Pi.""" # Check for Pi boards: pi_rev_code = self._pi_rev_code() if pi_rev_code: for model, codes in _PI_REV_CODES.items(): if pi_rev_code in codes: return model return None
Try to detect id of a Raspberry Pi.
def format_seq(self, outstream=None, linewidth=70): """ Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence i...
Print a sequence in a readable format. :param outstream: if `None`, formatted sequence is returned as a string; otherwise, it is treated as a file-like object and the formatted sequence is printed to the outstream :param line...
def html_visit_inheritance_diagram(self, node): # type: (nodes.NodeVisitor, inheritance_diagram) -> None """ Output the graph for HTML. This will insert a PNG with clickable image map. """ graph = node['graph'] graph_hash = get_graph_hash(node) name = 'inheritance%s' % graph_hash ...
Output the graph for HTML. This will insert a PNG with clickable image map.
def remove_udp_port(self, port): """ Removes an associated UDP port number from this project. :param port: UDP port number """ if port in self._used_udp_ports: self._used_udp_ports.remove(port)
Removes an associated UDP port number from this project. :param port: UDP port number
def timeout_selecting(self): """Timeout of selecting on SELECTING state. Not specifiyed in [:rfc:`7844`]. See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`. """ logger.debug('C2.1: T In %s, timeout receiving response to select.', self.current_st...
Timeout of selecting on SELECTING state. Not specifiyed in [:rfc:`7844`]. See comments in :func:`dhcpcapfsm.DHCPCAPFSM.timeout_request`.
def delete(self, docids): """Delete documents from the current session.""" self.check_session() result = self.session.delete(docids) if self.autosession: self.commit() return result
Delete documents from the current session.
def _build_dictionary(self, results): """ Build model dictionary keyed by the relation's foreign key. :param results: The results :type results: Collection :rtype: dict """ foreign = self._foreign_key dictionary = {} for result in results: ...
Build model dictionary keyed by the relation's foreign key. :param results: The results :type results: Collection :rtype: dict
def normalize_surfs(in_file, transform_file, newpath=None): """ Re-center GIFTI coordinates to fit align to native T1 space For midthickness surfaces, add MidThickness metadata Coordinate update based on: https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceAp...
Re-center GIFTI coordinates to fit align to native T1 space For midthickness surfaces, add MidThickness metadata Coordinate update based on: https://github.com/Washington-University/workbench/blob/1b79e56/src/Algorithms/AlgorithmSurfaceApplyAffine.cxx#L73-L91 and https://github.com/Washington-Univ...
def calculate_average_scores_on_graph( graph: BELGraph, key: Optional[str] = None, tag: Optional[str] = None, default_score: Optional[float] = None, runs: Optional[int] = None, use_tqdm: bool = False, ): """Calculate the scores over all biological processes in the sub...
Calculate the scores over all biological processes in the sub-graph. As an implementation, it simply computes the sub-graphs then calls :func:`calculate_average_scores_on_subgraphs` as described in that function's documentation. :param graph: A BEL graph with heats already on the nodes :param key: The...
def add_suffix(fullname, suffix): """ Add suffix to a full file name""" name, ext = os.path.splitext(fullname) return name + '_' + suffix + ext
Add suffix to a full file name
def get_num_processes(): """Return the number of processes to use in parallel.""" cpu_count = multiprocessing.cpu_count() if config.NUMBER_OF_CORES == 0: raise ValueError( 'Invalid NUMBER_OF_CORES; value may not be 0.') if config.NUMBER_OF_CORES > cpu_count: log.info('Reque...
Return the number of processes to use in parallel.
def destination(self, point, bearing, distance=None): """ TODO docs. """ point = Point(point) lat1 = units.radians(degrees=point.latitude) lng1 = units.radians(degrees=point.longitude) bearing = units.radians(degrees=bearing) if distance is None: ...
TODO docs.
def eintr_retry(exc_type, f, *args, **kwargs): """Calls a function. If an error of the given exception type with interrupted system call (EINTR) occurs calls the function again. """ while True: try: return f(*args, **kwargs) except exc_type as exc: if exc.errno !...
Calls a function. If an error of the given exception type with interrupted system call (EINTR) occurs calls the function again.
def _get_bonds(self, mol): """ Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms. """ num_atoms = len(mo...
Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms.
def now(self, when=None): """Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager. """ if when is None: when = _TaskManager().get_time() tup = time.localtime(whe...
Set the current value to the correct tuple based on the seconds since the epoch. If 'when' is not provided, get the current time from the task manager.
def profile(request, status=200): """ Get the user's profile. If the user has no assigned profile, the HTTP 404 is returned. Make a POST request to modify the user's profile. GET parameters: html turn on the HTML version of the API username: username of user (onl...
Get the user's profile. If the user has no assigned profile, the HTTP 404 is returned. Make a POST request to modify the user's profile. GET parameters: html turn on the HTML version of the API username: username of user (only for users with public profile) stats...
def visit(self, node): """ Try to replace if node match the given pattern or keep going. """ for pattern, replace in know_pattern: check = Check(node, dict()) if check.visit(pattern): node = PlaceholderReplace(check.placeholders).visit(replace()) s...
Try to replace if node match the given pattern or keep going.
def tf_initialize(self, x_init, b): """ Initialization step preparing the arguments for the first iteration of the loop body: $x_0, 0, p_0, r_0, r_0^2$. Args: x_init: Initial solution guess $x_0$, zero vector if None. b: The right-hand side $b$ of the system of...
Initialization step preparing the arguments for the first iteration of the loop body: $x_0, 0, p_0, r_0, r_0^2$. Args: x_init: Initial solution guess $x_0$, zero vector if None. b: The right-hand side $b$ of the system of linear equations. Returns: Initial...
def gen_locale(locale, **kwargs): ''' Generate a locale. Options: .. versionadded:: 2014.7.0 :param locale: Any locale listed in /usr/share/i18n/locales or /usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions, which require the charmap to be specified as part of the loca...
Generate a locale. Options: .. versionadded:: 2014.7.0 :param locale: Any locale listed in /usr/share/i18n/locales or /usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions, which require the charmap to be specified as part of the locale when generating it. verbose ...
def _set_collector(self, v, load=False): """ Setter method for collector, mapped from YANG variable /telemetry/collector (list) If this variable is read-only (config: false) in the source YANG file, then _set_collector is considered as a private method. Backends looking to populate this variable sho...
Setter method for collector, mapped from YANG variable /telemetry/collector (list) If this variable is read-only (config: false) in the source YANG file, then _set_collector is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_collector() di...
def _get_dvs_infrastructure_traffic_resources(dvs_name, dvs_infra_traffic_ress): ''' Returns a list of dict representations of the DVS infrastructure traffic resource dvs_name The name of the DVS dvs_infra_traffic_ress The DVS infrastru...
Returns a list of dict representations of the DVS infrastructure traffic resource dvs_name The name of the DVS dvs_infra_traffic_ress The DVS infrastructure traffic resources
def get_user_groups(name, sid=False): ''' Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids ''' if nam...
Get the groups to which a user belongs Args: name (str): The user name to query sid (bool): True will return a list of SIDs, False will return a list of group names Returns: list: A list of group names or sids
def parse_text(document, container, element): "Parse text element." txt = None alternate = element.find(_name('{{{mc}}}AlternateContent')) if alternate is not None: parse_alternate(document, container, alternate) br = element.find(_name('{{{w}}}br')) if br is not None: if _n...
Parse text element.
def response(self, msgid, error, result): """Handle a results message given to the proxy by the protocol object.""" if error: self.requests[msgid].errback(Exception(str(error))) else: self.requests[msgid].callback(result) del self.requests[msgid]
Handle a results message given to the proxy by the protocol object.
def load(self, args): """ Load a simulation from the given arguments. """ self._queue.append(tc.CMD_LOAD) self._string += struct.pack("!BiB", 0, 1 + 4 + 1 + 1 + 4 + sum(map(len, args)) + 4 * len(args), tc.CMD_LOAD) self._packStringList(args) self._sendExact()
Load a simulation from the given arguments.
def reverseCommit(self): """ Re-insert the previously deleted line. """ # Loop over all lines in the rectangle to remove the # previously yanked strings. col = self.cursorPos[1] for ii, text in enumerate(self.insertedText): line = ii + self.cursorPos[...
Re-insert the previously deleted line.
def call_binop(self, context, operator, left, right): """For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6 """ ...
For intercepted binary operator calls (:meth:`intercepted_binops`) this function is executed instead of the builtin operator. This can be used to fine tune the behavior of certain operators. .. versionadded:: 2.6
def consume_message(self, header, message): """Consume a message""" logmessage = { "time": (time.time() % 1000) * 1000, "header": "", "message": message, } if header: logmessage["header"] = ( json.dumps(header, indent=2) + "...
Consume a message
def start_adc(self, channel, gain=1, data_rate=None): """Start continuous ADC conversions on the specified channel (0-3). Will return an initial conversion result, then call the get_last_result() function to read the most recent conversion result. Call stop_adc() to stop conversions. ...
Start continuous ADC conversions on the specified channel (0-3). Will return an initial conversion result, then call the get_last_result() function to read the most recent conversion result. Call stop_adc() to stop conversions.
def parse(self, fp, headersonly=False): """Create a message structure from the data in a binary file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The...
Create a message structure from the data in a binary file. Reads all the data from the file and returns the root of the message structure. Optional headersonly is a flag specifying whether to stop parsing after reading the headers or not. The default is False, meaning it parses the en...
def track_dependency(self, name:str, data:str, type:str=None, target:str=None, duration:int=None, success:bool=None, result_code:str=None, properties:Dict[str, object]=None, measurements:Dict[str, object]=None, dependency_id:str=None): """ Sends a single...
Sends a single dependency telemetry that was captured for the application. :param name: the name of the command initiated with this dependency call. Low cardinality value. Examples are stored procedure name and URL path template. :param data: the command initiated by this dependency call. Examples are S...
def _check_infinite_flows(self, steps, flows=None): """ Recursively loop through the flow_config and check if there are any cycles. :param steps: Set of step definitions to loop through :param flows: Flows already visited. :return: None """ if flows is None: ...
Recursively loop through the flow_config and check if there are any cycles. :param steps: Set of step definitions to loop through :param flows: Flows already visited. :return: None
def _OpenPathSpec(self, path_specification, ascii_codepage='cp1252'): """Opens the Windows Registry file specified by the path specification. Args: path_specification (dfvfs.PathSpec): path specification. ascii_codepage (Optional[str]): ASCII string codepage. Returns: WinRegistryFile: Wi...
Opens the Windows Registry file specified by the path specification. Args: path_specification (dfvfs.PathSpec): path specification. ascii_codepage (Optional[str]): ASCII string codepage. Returns: WinRegistryFile: Windows Registry file or None.
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = CheckBox(self.get_context(), None, d.style or "@attr/checkboxStyle")
Create the underlying widget.
def get_licenses(self): """ :calls: `GET /licenses <https://developer.github.com/v3/licenses/#list-all-licenses>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.License.License` """ url_parameters = dict() return github.PaginatedList.PaginatedLis...
:calls: `GET /licenses <https://developer.github.com/v3/licenses/#list-all-licenses>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.License.License`
def get_object(self, item): """ Returns a StorageObject matching the specified item. If no such object exists, a NotFound exception is raised. If 'item' is not a string, that item is returned unchanged. """ if isinstance(item, six.string_types): item = self.ob...
Returns a StorageObject matching the specified item. If no such object exists, a NotFound exception is raised. If 'item' is not a string, that item is returned unchanged.
def _readconfig(): """Configures environment variables""" config = ConfigParser.SafeConfigParser() try: found = config.read(littlechef.CONFIGFILE) except ConfigParser.ParsingError as e: abort(str(e)) if not len(found): try: found = config.read(['config.cfg', 'auth...
Configures environment variables
def servicegroup_server_exists(sg_name, s_name, s_port=None, **connection_args): ''' Check if a server:port combination is a member of a servicegroup CLI Example: .. code-block:: bash salt '*' netscaler.servicegroup_server_exists 'serviceGroupName' 'serverName' 'serverPort' ''' return...
Check if a server:port combination is a member of a servicegroup CLI Example: .. code-block:: bash salt '*' netscaler.servicegroup_server_exists 'serviceGroupName' 'serverName' 'serverPort'
def compute_effsize(x, y, paired=False, eftype='cohen'): """Calculate effect size between two set of observations. Parameters ---------- x : np.array or list First set of observations. y : np.array or list Second set of observations. paired : boolean If True, uses Cohen ...
Calculate effect size between two set of observations. Parameters ---------- x : np.array or list First set of observations. y : np.array or list Second set of observations. paired : boolean If True, uses Cohen d-avg formula to correct for repeated measurements (Cumm...
def members_entries(self, all_are_optional: bool=False) -> List[Tuple[str, str]]: """ Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return: """ rval = [] if self._mem...
Return an ordered list of elements for the _members section :param all_are_optional: True means we're in a choice situation so everything is optional :return:
def p_expression_And(self, p): 'expression : expression AND expression' p[0] = And(p[1], p[3], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
expression : expression AND expression
def func_call_as_str(name, *args, **kwds): """ Return arguments and keyword arguments as formatted string >>> func_call_as_str('f', 1, 2, a=1) 'f(1, 2, a=1)' """ return '{0}({1})'.format( name, ', '.join(itertools.chain( map('{0!r}'.format, args), map('{...
Return arguments and keyword arguments as formatted string >>> func_call_as_str('f', 1, 2, a=1) 'f(1, 2, a=1)'
def copy(self, src, dst, other_system=None): """ Copy object of the same storage. Args: src (str): Path or URL. dst (str): Path or URL. other_system (pycosio._core.io_system.SystemBase subclass): Unused. """ copy_source = self.get_client_kwarg...
Copy object of the same storage. Args: src (str): Path or URL. dst (str): Path or URL. other_system (pycosio._core.io_system.SystemBase subclass): Unused.
def to_int(self, number, default=0): """Returns an integer """ try: return int(number) except (KeyError, ValueError): return self.to_int(default, 0)
Returns an integer
def elect(self, candidate_aggregates, candidate_id): """ Elect a candidate, updating internal state to track this. Calculate the paper count to be transferred on to other candidates, and if required schedule a distribution fo papers. """ # somewhat paranoid cross-check, ...
Elect a candidate, updating internal state to track this. Calculate the paper count to be transferred on to other candidates, and if required schedule a distribution fo papers.
def LoadExclusions(self, snps): """ Load locus exclusions. :param snps: Can either be a list of rsids or a file containing rsids. :return: None If snps is a file, the file must only contain RSIDs separated by whitespace (tabs, spaces and return characters). """ ...
Load locus exclusions. :param snps: Can either be a list of rsids or a file containing rsids. :return: None If snps is a file, the file must only contain RSIDs separated by whitespace (tabs, spaces and return characters).
def _prepare_calls(result_file, out_dir, data): """Write summary file of results of HLA typing by allele. """ sample = dd.get_sample_name(data) out_file = os.path.join(out_dir, "%s-optitype.csv" % (sample)) if not utils.file_uptodate(out_file, result_file): hla_truth = bwakit.get_hla_truthse...
Write summary file of results of HLA typing by allele.
def from_dict(cls, operation, client, **caller_metadata): """Factory: construct an instance from a dictionary. :type operation: dict :param operation: Operation as a JSON object. :type client: :class:`~google.cloud.client.Client` :param client: The client used to poll for the s...
Factory: construct an instance from a dictionary. :type operation: dict :param operation: Operation as a JSON object. :type client: :class:`~google.cloud.client.Client` :param client: The client used to poll for the status of the operation. :type caller_metadata: dict ...
def _query_entities(self, table_name, filter=None, select=None, max_results=None, marker=None, accept=TablePayloadFormat.JSON_MINIMAL_METADATA, property_resolver=None, timeout=None, _context=None): ''' Returns a list of entities under the specified table. ...
Returns a list of entities under the specified table. Makes a single list request to the service. Used internally by the query_entities method. :param str table_name: The name of the table to query. :param str filter: Returns only entities that satisfy the specified fil...
def pretty_str(self, indent=0): """Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation. """ indent = ' ' * indent if self.value is not None: return '{}{} {}'.format(indent, self.na...
Return a human-readable string representation of this object. Kwargs: indent (int): The amount of spaces to use as indentation.
def cmd_host(verbose): """Collect information about the host where habu is running. Example: \b $ habu.host { "kernel": [ "Linux", "demo123", "5.0.6-200.fc29.x86_64", "#1 SMP Wed Apr 3 15:09:51 UTC 2019", "x86_64", "x8...
Collect information about the host where habu is running. Example: \b $ habu.host { "kernel": [ "Linux", "demo123", "5.0.6-200.fc29.x86_64", "#1 SMP Wed Apr 3 15:09:51 UTC 2019", "x86_64", "x86_64" ], "dist...
def current_rev_reg_id(base_dir: str, cd_id: str) -> str: """ Return the current revocation registry identifier for input credential definition identifier, in input directory. Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined. :par...
Return the current revocation registry identifier for input credential definition identifier, in input directory. Raise AbsentTails if no corresponding tails file, signifying no such revocation registry defined. :param base_dir: base directory for tails files, thereafter split by cred def id ...
def merge_configs(config: Dict[str, Any], default_config: Dict[str, Any]) -> Dict[str, Any]: """ Merges a `default` config with DAG config. Used to set default values for a group of DAGs. :param config: config to merge in default values :type config: Dict[str, Any] :param default_config: confi...
Merges a `default` config with DAG config. Used to set default values for a group of DAGs. :param config: config to merge in default values :type config: Dict[str, Any] :param default_config: config to merge default values from :type default_config: Dict[str, Any] :returns: dict with merged co...
def userpass(self, dir="ppcoin"): """Reads config file for username/password""" source = os.path.expanduser("~/.{0}/{0}.conf").format(dir) dest = open(source, "r") with dest as conf: for line in conf: if line.startswith("rpcuser"): usernam...
Reads config file for username/password
def get(self, mail): """ Get one document store into LinShare.""" users = (v for v in self.list() if v.get('mail') == mail) for i in users: self.log.debug(i) return i return None
Get one document store into LinShare.
def t_NATIVEPHP(t): r'<\?php((?!<\?php)[\s\S])*\?>[ \t]*(?=\n)' lineNoInc(t) t.value = t.value[6:].lstrip() pos2 = t.value.rfind('?>') t.value = t.value[0:pos2].rstrip() # print t.value return t
r'<\?php((?!<\?php)[\s\S])*\?>[ \t]*(?=\n)
def cos_zen(utc_time, lon, lat): """Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*. utc_time: datetime.datetime instance of the UTC time lon and lat in degrees. """ lon = np.deg2rad(lon) lat = np.deg2rad(lat) r_a, dec = sun_ra_dec(utc_time) h__ = _local_hour_angle(utc_tim...
Cosine of the sun-zenith angle for *lon*, *lat* at *utc_time*. utc_time: datetime.datetime instance of the UTC time lon and lat in degrees.
def __collect_interfaces_return(interfaces): """Collect new style (44.1+) return values to old-style kv-list""" acc = [] for (interfaceName, interfaceData) in interfaces.items(): signalValues = interfaceData.get("signals", {}) for (signalName, signalValue) in signalValues...
Collect new style (44.1+) return values to old-style kv-list
def find_satisfied_condition(conditions, ps): """Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.""" assert is_iterable_typed(conditions, property_set.PropertySet) assert isinstance(ps, property_set.PropertySet) for conditio...
Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.
def update_model_cache(table_name): """ Updates model cache by generating a new key for the model """ model_cache_info = ModelCacheInfo(table_name, uuid.uuid4().hex) model_cache_backend.share_model_cache_info(model_cache_info)
Updates model cache by generating a new key for the model