code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def recursive_dictionary_get(keys, dictionary): """ Gets contents of requirement key recursively so users can search for specific keys inside nested requirement dicts. :param keys: key or dot separated string of keys to look for. :param dictionary: Dictionary to search from :return: results of ...
Gets contents of requirement key recursively so users can search for specific keys inside nested requirement dicts. :param keys: key or dot separated string of keys to look for. :param dictionary: Dictionary to search from :return: results of search or None
def html_temp_launch(html): """given text, make it a temporary HTML file and launch it.""" fname = tempfile.gettempdir()+"/swhlab/temp.html" with open(fname,'w') as f: f.write(html) webbrowser.open(fname)
given text, make it a temporary HTML file and launch it.
def init_app(self, app): """ Register this extension with the flask app. :param app: A flask application """ # Save this so we can use it later in the extension if not hasattr(app, 'extensions'): # pragma: no cover app.extensions = {} app.extensions[...
Register this extension with the flask app. :param app: A flask application
def _simple_command(self, command, arg=None, **kwargs): """Send a simple command.""" self._protocol.send_command(command, arg) return self._protocol.handle_simple_responses(**kwargs)
Send a simple command.
def open(self, vendor_id: int = 0x16c0, product_id: int = 0x5dc, bus: int = None, address: int = None) -> bool: """ Open the first device that matches the search criteria. Th default parameters are set up for the likely most common case of a single uDMX interface. However, for the case o...
Open the first device that matches the search criteria. Th default parameters are set up for the likely most common case of a single uDMX interface. However, for the case of multiple uDMX interfaces, you can use the bus and address paramters to further specifiy the uDMX interface to be o...
def remove(self, item): """ Removes the specified element's first occurrence from the list if it exists in this list. :param item: (object), the specified element. :return: (bool), ``true`` if the specified element is present in this list. """ check_not_none(item, "Value...
Removes the specified element's first occurrence from the list if it exists in this list. :param item: (object), the specified element. :return: (bool), ``true`` if the specified element is present in this list.
def close(self): """Should be closed[explicit] while using external session or connector, instead of close by self.__del__.""" try: if not self.session.closed: if self.session._connector_owner: self.session._connector.close() self.s...
Should be closed[explicit] while using external session or connector, instead of close by self.__del__.
def _xml_element_value(el: Element, int_tags: list): """ Gets XML Element value. :param el: Element :param int_tags: List of tags that should be treated as ints :return: value of the element (int/str) """ # None if el.text is None: return None # int try: if el.tag...
Gets XML Element value. :param el: Element :param int_tags: List of tags that should be treated as ints :return: value of the element (int/str)
def find_bindmounts(self): """Finds all bind mountpoints that are inside mounts that match the :attr:`re_pattern`""" for mountpoint, (orig, fs, opts) in self.mountpoints.items(): if 'bind' in opts and re.match(self.re_pattern, mountpoint): yield mountpoint
Finds all bind mountpoints that are inside mounts that match the :attr:`re_pattern`
def is_data_dependent(fmto, data): """Check whether a formatoption is data dependent Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to check data: xarray.DataArray The data array to use if the :attr:`~Formatoption.data_dependent` attribute is a c...
Check whether a formatoption is data dependent Parameters ---------- fmto: Formatoption The :class:`Formatoption` instance to check data: xarray.DataArray The data array to use if the :attr:`~Formatoption.data_dependent` attribute is a callable Returns ------- bool ...
def add_tcp_flag(self, tcp_flag): """Add a single TCP flag - will be OR'd into the existing bitmask""" if tcp_flag not in [1, 2, 4, 8, 16, 32, 64, 128]: raise ValueError("Invalid TCP flag. Valid: [1, 2, 4, 8, 16,32, 64, 128]") prev_size = 0 if self._json_dict.get('tcp_flag...
Add a single TCP flag - will be OR'd into the existing bitmask
def load_command_table(self, args): #pylint: disable=too-many-statements """Load all Service Fabric commands""" # Need an empty client for the select and upload operations with CommandSuperGroup(__name__, self, 'rcctl.custom_cluster#{}') as super_group: ...
Load all Service Fabric commands
def handle_stranded_tasks(self, engine): """Deal with jobs resident in an engine that died.""" lost = self.pending[engine] for msg_id in lost.keys(): if msg_id not in self.pending[engine]: # prevent double-handling of messages continue raw...
Deal with jobs resident in an engine that died.
def syncFlags(self): """ Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute. """ self.flags = set(self.skype.conn("GET", SkypeConnection.API_FLAGS, auth=SkypeConnection.Auth.SkypeToken).json())
Update the cached list of all enabled flags, and store it in the :attr:`flags` attribute.
def live_profile(script, argv, profiler_factory, interval, spawn, signum, pickle_protocol, mono): """Profile a Python script continuously.""" filename, code, globals_ = script sys.argv[:] = [filename] + list(argv) parent_sock, child_sock = socket.socketpair() stderr_r_fd, stderr_w_f...
Profile a Python script continuously.
def convert_sum( params, w_name, scope_name, inputs, layers, weights, names ): """ Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with ker...
Convert sum. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
def bounded_uniform(cls, lowest, highest, weight_interval=None): """ Initialize with a uniform distribution between two values. If no ``weight_interval`` is passed, this weight distribution will just consist of ``[(lowest, 1), (highest, 1)]``. If specified, weights (still with u...
Initialize with a uniform distribution between two values. If no ``weight_interval`` is passed, this weight distribution will just consist of ``[(lowest, 1), (highest, 1)]``. If specified, weights (still with uniform weight distribution) will be added every ``weight_interval``. Use this...
def add_auth_to_method(self, path, method_name, auth, api): """ Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string...
Adds auth settings for this path/method. Auth settings currently consist solely of Authorizers but this method will eventually include setting other auth settings such as API Key, Resource Policy, etc. :param string path: Path name :param string method_name: Method name :param d...
def get_providers(self, security_filter, name_filter='%', only_providers_flag='Y', internal_external='I', ordering_authority='', real_provider='N'): """ invokes TouchWorksMagicConstants.ACTION_G...
invokes TouchWorksMagicConstants.ACTION_GET_ENCOUNTER_LIST_FOR_PATIENT action :param security_filter - This is the EntryCode of the Security_Code_DE dictionary for the providers being sought. A list of valid security codes can be obtained from GetDictionary on the Security_Code_DE dictio...
def _toplevel(cls): """Find the top level of the chain we're in. For example, if we have: C inheriting from B inheriting from A inheriting from ClosureModel C._toplevel() will return A. """ superclasses = ( list(set(ClosureModel.__subclasses__()) ...
Find the top level of the chain we're in. For example, if we have: C inheriting from B inheriting from A inheriting from ClosureModel C._toplevel() will return A.
def register(self, renewable, timeout=300): """Register a renewable entity for automatic lock renewal. :param renewable: A locked entity that needs to be renewed. :type renewable: ~azure.servicebus.aio.async_message.Message or ~azure.servicebus.aio.async_receive_handler.SessionReceiver...
Register a renewable entity for automatic lock renewal. :param renewable: A locked entity that needs to be renewed. :type renewable: ~azure.servicebus.aio.async_message.Message or ~azure.servicebus.aio.async_receive_handler.SessionReceiver :param timeout: A time in seconds that the loc...
def _get_dependency_specification(dep_spec: typing.List[tuple]) -> str: """Get string representation of dependency specification as provided by PythonDependencyParser.""" return ",".join(dep_range[0] + dep_range[1] for dep_range in dep_spec)
Get string representation of dependency specification as provided by PythonDependencyParser.
def Zuo_Stenby(T, Tc, Pc, omega): r'''Calculates air-water surface tension using the reference fluids methods of [1]_. .. math:: \sigma^{(1)} = 40.520(1-T_r)^{1.287} \sigma^{(2)} = 52.095(1-T_r)^{1.21548} \sigma_r = \sigma_r^{(1)}+ \frac{\omega - \omega^{(1)}} {\omega^{(2)}-...
r'''Calculates air-water surface tension using the reference fluids methods of [1]_. .. math:: \sigma^{(1)} = 40.520(1-T_r)^{1.287} \sigma^{(2)} = 52.095(1-T_r)^{1.21548} \sigma_r = \sigma_r^{(1)}+ \frac{\omega - \omega^{(1)}} {\omega^{(2)}-\omega^{(1)}} (\sigma_r^{(2)}-\sigma_r...
def create_tag(self, name): """ .. versionadded:: 0.2.0 Add a new tag resource to the account :param str name: the name of the new tag :rtype: Tag :raises DOAPIError: if the API endpoint replies with an error """ return self._tag(self.request('/v2/tags',...
.. versionadded:: 0.2.0 Add a new tag resource to the account :param str name: the name of the new tag :rtype: Tag :raises DOAPIError: if the API endpoint replies with an error
def find_weights(self, scorer, test_size=0.2, method='SLSQP'): """Finds optimal weights for weighted average of models. Parameters ---------- scorer : function Scikit-learn like metric. test_size : float, default 0.2 method : str Type of solver. ...
Finds optimal weights for weighted average of models. Parameters ---------- scorer : function Scikit-learn like metric. test_size : float, default 0.2 method : str Type of solver. Should be one of: - 'Nelder-Mead' - 'Powell' ...
def _modelmat(self, X, term=-1): """ Builds a model matrix, B, out of the spline basis for each feature B = [B_0, B_1, ..., B_p] Parameters --------- X : array-like of shape (n_samples, m_features) containing the input dataset term : int, optional ...
Builds a model matrix, B, out of the spline basis for each feature B = [B_0, B_1, ..., B_p] Parameters --------- X : array-like of shape (n_samples, m_features) containing the input dataset term : int, optional term index for which to compute the model m...
def upload_file_content(self, file_id, etag=None, source=None, content=None): '''Upload a file content. The file entity must already exist. If an ETag is provided the file stored on the server is verified against it. If it does not match, StorageException is raised. This means the clien...
Upload a file content. The file entity must already exist. If an ETag is provided the file stored on the server is verified against it. If it does not match, StorageException is raised. This means the client needs to update its knowledge of the resource before attempting to update again...
def into(self, val: str) -> Union['ApiNode', 'ApiEndpoint']: """Get another leaf node with name `val` if possible""" if val in self.paths: return self.paths[val] if self.param: return self.param raise IndexError(_("Value {} is missing from api").format(val))
Get another leaf node with name `val` if possible
def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True...
Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True, print a "full" checking of each parameter :type verbose: bool :param step: The size of the step around wh...
def updateResults(self, newResults, **kwArgs): """ Update the results related to this request excluding the 'response' and 'logEntries' values. We specifically update (if present): overallRC, rc, rs, errno. Input: Dictionary containing the results to be upd...
Update the results related to this request excluding the 'response' and 'logEntries' values. We specifically update (if present): overallRC, rc, rs, errno. Input: Dictionary containing the results to be updated or an empty dictionary the reset keyword was spe...
def metadata(self): """ Retrieve the metadata info for this prefix Returns: dict: metadata info """ if self._metadata is None: try: with open(self.paths.metadata()) as metadata_fd: self._metadata = json.load(metadata_fd...
Retrieve the metadata info for this prefix Returns: dict: metadata info
def _assemble_with_columns(self, sql_str, columns, *args, **kwargs): """ Format a select statement with specific columns :sql_str: An SQL string template :columns: The columns to be selected and put into {0} :*args: Arguments to use as query parameters. :return...
Format a select statement with specific columns :sql_str: An SQL string template :columns: The columns to be selected and put into {0} :*args: Arguments to use as query parameters. :returns: Psycopg2 compiled query
def daemon_start(main, pidfile, daemon=True, workspace=None): """Start application in background mode if required and available. If not then in front mode. """ logger.debug("start daemon application pidfile={pidfile} daemon={daemon} workspace={workspace}.".format(pidfile=pidfile, daemon=daemon, workspace=wo...
Start application in background mode if required and available. If not then in front mode.
def create_entity2user(enti_uid, user_id): ''' create entity2user record in the database. ''' record = TabEntity2User.select().where( (TabEntity2User.entity_id == enti_uid) & (TabEntity2User.user_id == user_id) ) if record.count() > 0: record = re...
create entity2user record in the database.
def _yield_exercises(self): """A helper function to reduce the number of nested loops. Yields ------- (dynamic_ex) or (static_ex) Yields the exercises in the program. """ for day in self.days: for dynamic_ex in day.dynamic_exercises: ...
A helper function to reduce the number of nested loops. Yields ------- (dynamic_ex) or (static_ex) Yields the exercises in the program.
def link_with_parents(self, parent, c_selectors, c_rules): """ Link with a parent for the current child rule. If parents found, returns a list of parent rules to the child """ parent_found = None for p_selectors, p_rules in self.parts.items(): _p_selectors, _,...
Link with a parent for the current child rule. If parents found, returns a list of parent rules to the child
def match_member_id(self, member_conf, current_member_confs): """ Attempts to find an id for member_conf where fom current members confs there exists a element. Returns the id of an element of current confs WHERE member_conf.host and element.host are EQUAL or map to same host ...
Attempts to find an id for member_conf where fom current members confs there exists a element. Returns the id of an element of current confs WHERE member_conf.host and element.host are EQUAL or map to same host
def _load_tsv_variables(layout, suffix, dataset=None, columns=None, prepend_type=False, scope='all', **selectors): ''' Reads variables from scans.tsv, sessions.tsv, and participants.tsv. Args: layout (BIDSLayout): The BIDSLayout to use. suffix (str): The suffix of file t...
Reads variables from scans.tsv, sessions.tsv, and participants.tsv. Args: layout (BIDSLayout): The BIDSLayout to use. suffix (str): The suffix of file to read from. Must be one of 'scans', 'sessions', or 'participants'. dataset (NodeIndex): A BIDS NodeIndex container. If None, a...
def get_field(name, data, default="object", document_object_field=None, is_document=False): """ Return a valid Field by given data """ if isinstance(data, AbstractField): return data data = keys_to_string(data) _type = data.get('type', default) if _type == "string": return St...
Return a valid Field by given data
def execute(self, task): """ Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id...
Given a task instance, this runs it. This includes handling retries & re-raising exceptions. Ex:: task = Task(async=False, retries=5) task.to_call(add, 101, 35) finished_task = gator.execute(task) :param task_id: The identifier of the task to process ...
def auth_required(self): """ If any ancestor required an authentication, this node needs it too. """ if self._auth: return self._auth, self return self.__parent__.auth_required()
If any ancestor required an authentication, this node needs it too.
def DeleteInstance(r, instance, dry_run=False): """ Deletes an instance. @type instance: str @param instance: the instance to delete @rtype: int @return: job id """ return r.request("delete", "/2/instances/%s" % instance, query={"dry-run": dry_run})
Deletes an instance. @type instance: str @param instance: the instance to delete @rtype: int @return: job id
def check_email_syntax (self, mail): """Check email syntax. The relevant RFCs: - How to check names (memo): http://tools.ietf.org/html/rfc3696 - Email address syntax http://tools.ietf.org/html/rfc2822 - SMTP protocol http://tools.ietf.org/html/rfc5321#sectio...
Check email syntax. The relevant RFCs: - How to check names (memo): http://tools.ietf.org/html/rfc3696 - Email address syntax http://tools.ietf.org/html/rfc2822 - SMTP protocol http://tools.ietf.org/html/rfc5321#section-4.1.3 - IPv6 http://tools.ie...
def insort_right(a, x, lo=0, hi=None): """Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched. """ if lo < 0: raise V...
Insert item x in list a, and keep it sorted assuming a is sorted. If x is already in a, insert it to the right of the rightmost x. Optional args lo (default 0) and hi (default len(a)) bound the slice of a to be searched.
def forms(self): """ Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is retuned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`. """ forms = Fo...
Form values parsed from an `url-encoded` or `multipart/form-data` encoded POST or PUT request body. The result is retuned as a :class:`FormsDict`. All keys and values are strings. File uploads are stored separately in :attr:`files`.
def axis_bounds(self) -> Dict[str, Tuple[float, float]]: """ The (minimum, maximum) bounds for each axis. """ return {ax: (0, pos+0.5) for ax, pos in _HOME_POSITION.items() if ax not in 'BC'}
The (minimum, maximum) bounds for each axis.
def fmt_duration(secs): """Format a duration in seconds.""" return ' '.join(fmt.human_duration(secs, 0, precision=2, short=True).strip().split())
Format a duration in seconds.
def login_required(request): "Lookup decorator to require the user to be authenticated." user = getattr(request, 'user', None) if user is None or not user.is_authenticated: return HttpResponse(status=401)
Lookup decorator to require the user to be authenticated.
def loadResults(resultsFile): """returns a dict of active folders with days as keys.""" with open(resultsFile) as f: raw=f.read().split("\n") foldersByDay={} for line in raw: folder=line.split('"')[1]+"\\" line=[]+line.split('"')[2].split(", ") for day in line[1:]...
returns a dict of active folders with days as keys.
def _build(self, input_batch, is_training, test_local_stats=False): """Connects the BatchNormV2 module into the graph. Args: input_batch: A Tensor of the same dimension as `len(data_format)`. is_training: A boolean to indicate if the module should be connected...
Connects the BatchNormV2 module into the graph. Args: input_batch: A Tensor of the same dimension as `len(data_format)`. is_training: A boolean to indicate if the module should be connected in training mode, meaning the moving averages are updated. Can be a Tensor. test_local_stats: A boo...
def get_proxy_parts(proxy): """ Take a proxy url and break it up to its parts """ proxy_parts = {'schema': None, 'user': None, 'password': None, 'host': None, 'port': None, } # Find parts results = re....
Take a proxy url and break it up to its parts
def find_usage(self): """ Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`. """ logger.debug("Checking usage for service %s", self.service_name) self.connect() for lim i...
Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
def peukerdouglas(np, fel, streamSkeleton, workingdir=None, mpiexedir=None, exedir=None, log_file=None, runtime_file=None, hostfile=None): """Run peuker-douglas function""" fname = TauDEM.func_name('peukerdouglas') return TauDEM.run(FileClass.get_executable_fullpath(fname, ...
Run peuker-douglas function
def process_needlist(app, doctree, fromdocname): """ Replace all needlist nodes with a list of the collected needs. Augment each need with a backlink to the original location. """ env = app.builder.env for node in doctree.traverse(Needlist): if not app.config.needs_include_needs: ...
Replace all needlist nodes with a list of the collected needs. Augment each need with a backlink to the original location.
def generate_exercises_from_importstudioid(self, args, options): """ Create rows in Exercises.csv and ExerciseQuestions.csv from a Studio channel, specified based on a studio_id (e.g. studio_id of main_tree for some channel)' """ print('Generating Exercises.csv and ExerciseQuesti...
Create rows in Exercises.csv and ExerciseQuestions.csv from a Studio channel, specified based on a studio_id (e.g. studio_id of main_tree for some channel)'
def query_sequence_length(self): """ does not include hard clipped""" if self.entries.seq: return len(self.entries.seq) if not self.entries.cigar: raise ValueError('Cannot give a query length if no cigar and no query sequence are present') return sum([x[0] for x in self.cigar_array if re.match('[...
does not include hard clipped
def _iparam_objectname(objectname, arg_name): """ Convert an object name (= class or instance name) specified in an operation method into a CIM object that can be passed to imethodcall(). """ if isinstance(objectname, (CIMClassName, CIMInstanceName)): objectn...
Convert an object name (= class or instance name) specified in an operation method into a CIM object that can be passed to imethodcall().
def loess_inline(h,x,cut,nan=True): """ #This is a raw, inline version of the loess filtering function. Runs much more slowlier. """ n=np.size(h) #Start filtering if there are more than 1 point if n == 1 : lf = h[0] else : pass #Get the half-width of filter window ...
#This is a raw, inline version of the loess filtering function. Runs much more slowlier.
def example4(): """ Example 4: Transforming coordinates using affine matrix. """ transform_matrix = create_transformation_matrix() result = tl.prepro.affine_transform_cv2(image, transform_matrix) # 76 times faster # Transform keypoint coordinates coords = [[(50, 100), (100, 100), (100, 50), (200, 2...
Example 4: Transforming coordinates using affine matrix.
def assertDateTimesLagEqual(self, sequence, lag, msg=None): '''Fail unless max element in ``sequence`` is separated from the present by ``lag`` as determined by the '==' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date,...
Fail unless max element in ``sequence`` is separated from the present by ``lag`` as determined by the '==' operator. If the max element is a datetime, "present" is defined as ``datetime.now()``; if the max element is a date, "present" is defined as ``date.today()``. This is equ...
def main(argv=None): """Run Preprocessing as a Dataflow.""" args = parse_arguments(sys.argv if argv is None else argv) temp_dir = os.path.join(args.output, 'tmp') if args.cloud: pipeline_name = 'DataflowRunner' else: pipeline_name = 'DirectRunner' # Suppress TF warnings. os.environ['TF_CPP_MI...
Run Preprocessing as a Dataflow.
def load(self, path): """Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str` """ fieldnames = ['work', 'label'] with open(path, 'r', encoding='utf-8', newline='') as fh: reader = csv.DictReader(fh, delimiter='...
Loads the data from `path` into the catalogue. :param path: path to catalogue file :type path: `str`
def pluginSetting(name, namespace=None, typ=None): ''' Returns the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. No...
Returns the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param namespace: The namespace. If not passed or None, the namespace will be inferred from the caller method. Normally, this should not be passed, since it suffices to let thi...
def watch_statuses(self, observer, batch_ids): """Allows a component to register to be notified when a set of batches is no longer PENDING. Expects to be able to call the "notify_batches_finished" method on the registered component, sending the statuses of the batches. Args: ...
Allows a component to register to be notified when a set of batches is no longer PENDING. Expects to be able to call the "notify_batches_finished" method on the registered component, sending the statuses of the batches. Args: observer (object): Must implement "notify_batches...
def _band_calculations(self, rsr, flux, scale, **options): """Derive the inband solar flux or inband solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU. rsr: Relative Spectral Response (one detector only) Dictionary with ...
Derive the inband solar flux or inband solar irradiance for a given instrument relative spectral response valid for an earth-sun distance of one AU. rsr: Relative Spectral Response (one detector only) Dictionary with two members 'wavelength' and 'response' options: detec...
def render(request, template_name, context=None, content_type=None, status=None, using=None, logs=None): """ Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed. """ if logs: obj_logger = ObjectLogger() if not i...
Wrapper around Django render method. Can take one or a list of logs and logs the response. No overhead if no logs are passed.
def _parse_led(self, keypad, component_xml): """Parses an LED device that part of a keypad.""" component_num = int(component_xml.get('ComponentNumber')) led_num = component_num - 80 led = Led(self._lutron, keypad, name=('LED %d' % led_num), led_num=led_num, comp...
Parses an LED device that part of a keypad.
def do_wait(coro: Callable) -> Any: """ Perform aynchronous operation; await then return the result. :param coro: coroutine to await :return: coroutine result """ event_loop = None try: event_loop = asyncio.get_event_loop() except RuntimeError: event_loop = asyncio.new_...
Perform aynchronous operation; await then return the result. :param coro: coroutine to await :return: coroutine result
def make_all_uppercase( lst: Union[list, tuple, str, set] ) -> Union[list, tuple, str, set]: """Make all characters uppercase. It supports characters in a (mix of) list, tuple, set or string. The return value is of the same type of the input value. """ if not is...
Make all characters uppercase. It supports characters in a (mix of) list, tuple, set or string. The return value is of the same type of the input value.
def namedTempFileReader(self) -> NamedTempFileReader: """ Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a...
Named Temporary File Reader This provides an object compatible with NamedTemporaryFile, used for reading this files contents. This will still delete after the object falls out of scope. This solves the problem on windows where a NamedTemporaryFile can not be read while it's being writt...
def check_data_complete(data, parameter_columns): """ For any parameters specified with edges, make sure edges don't overlap and don't have any gaps. Assumes that edges are specified with ends and starts overlapping (but one exclusive and the other inclusive) so can check that end of previous == start ...
For any parameters specified with edges, make sure edges don't overlap and don't have any gaps. Assumes that edges are specified with ends and starts overlapping (but one exclusive and the other inclusive) so can check that end of previous == start of current. If multiple parameters, make sure all ...
def merge(d1, d2): """This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] } """ d1, d2 = deepcopy(d1),...
This method does cool stuff like append and replace for dicts d1 = { "steve": 10, "gary": 4 } d2 = { "&steve": 11, "-gary": null } result = { "steve": [10, 11] }
def dump_by_server(self, hosts): """Returns the output of dump for each server. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of ((server_ip, port), ClientInfo). """ dump_by_endpoint = {} for endpoint in self._to_endpoints(ho...
Returns the output of dump for each server. :param hosts: comma separated lists of members of the ZK ensemble. :returns: A dictionary of ((server_ip, port), ClientInfo).
def translate_aliases(kwargs, aliases): """Given a dict of keyword arguments and a dict mapping aliases to their canonical values, canonicalize the keys in the kwargs dict. :return: A dict continaing all the values in kwargs referenced by their canonical key. :raises: `AliasException`, if a can...
Given a dict of keyword arguments and a dict mapping aliases to their canonical values, canonicalize the keys in the kwargs dict. :return: A dict continaing all the values in kwargs referenced by their canonical key. :raises: `AliasException`, if a canonical key is defined more than once.
def get_clean_factor(factor, forward_returns, groupby=None, binning_by_group=False, quantiles=5, bins=None, groupby_labels=None, max_loss=0.35, zero_awa...
Formats the factor data, forward return data, and group mappings into a DataFrame that contains aligned MultiIndex indices of timestamp and asset. The returned data will be formatted to be suitable for Alphalens functions. It is safe to skip a call to this function and still make use of Alphalens funct...
def cvtToBlocks(rh, diskSize): """ Convert a disk storage value to a number of blocks. Input: Request Handle Size of disk in bytes Output: Results structure: overallRC - Overall return code for the function: 0 - Everything went ok ...
Convert a disk storage value to a number of blocks. Input: Request Handle Size of disk in bytes Output: Results structure: overallRC - Overall return code for the function: 0 - Everything went ok 4 - Input validation error ...
def post(self, request, pzone_pk): """Add a new operation to the given pzone, return json of the new operation.""" # attempt to get given content list pzone = None try: pzone = PZone.objects.get(pk=pzone_pk) except PZone.DoesNotExist: raise Http404("Canno...
Add a new operation to the given pzone, return json of the new operation.
def _create(self, format, args): """Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remaind...
Create a GVariant object from given format and argument list. This method recursively calls itself for complex structures (arrays, dictionaries, boxed). Return a tuple (variant, rest_format, rest_args) with the generated GVariant, the remainder of the format string, and the remainder o...
def add_curie(self, name, href): """Adds a CURIE definition. A CURIE link with the given ``name`` and ``href`` is added to the document. This method returns self, allowing it to be chained with additional method calls. """ self.draft.set_curie(self, name, href) ...
Adds a CURIE definition. A CURIE link with the given ``name`` and ``href`` is added to the document. This method returns self, allowing it to be chained with additional method calls.
def update_metric(self, eval_metric, labels, pre_sliced=False): """Evaluates and accumulates evaluation metric on outputs of the last forward computation. Subclass should override this method if needed. Parameters ---------- eval_metric : EvalMetric labels : list of NDAr...
Evaluates and accumulates evaluation metric on outputs of the last forward computation. Subclass should override this method if needed. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``.
def search_agents(self, start=0, limit=100, filter={}, **kwargs): ''' search_agents(self, start=0, limit=100, filter={}, **kwargs) Search agents :Parameters: * *start* (`int`) -- start index to retrieve from. Default is 0 * *limit* (`int`) -- maximum number of entities ...
search_agents(self, start=0, limit=100, filter={}, **kwargs) Search agents :Parameters: * *start* (`int`) -- start index to retrieve from. Default is 0 * *limit* (`int`) -- maximum number of entities to retrieve. Default is 100 * *filter* (`object`) -- free text search pattern ...
def from_binary(self, d): """Given a binary payload d, update the appropriate payload fields of the message. """ p = MsgEphemerisGPSDepF._parser.parse(d) for n in self.__class__.__slots__: setattr(self, n, getattr(p, n))
Given a binary payload d, update the appropriate payload fields of the message.
def build_fptree(self, transactions, root_value, root_count, frequent, headers): """ Build the FP tree and return the root node. """ root = FPNode(root_value, root_count, None) for transaction in transactions: sorted_items = [x for x in transacti...
Build the FP tree and return the root node.
async def set_heater_temp(self, device_id, set_temp): """Set heater temp.""" payload = {"homeType": 0, "timeZoneNum": "+02:00", "deviceId": device_id, "value": int(set_temp), "key": "holidayTemp"} await self.request("cha...
Set heater temp.
def _fill_function(*args): """Fills in the rest of function data into the skeleton function object The skeleton itself is create by _make_skel_func(). """ if len(args) == 2: func = args[0] state = args[1] elif len(args) == 5: # Backwards compat for cloudpickle v0.4.0, after ...
Fills in the rest of function data into the skeleton function object The skeleton itself is create by _make_skel_func().
def absent(name=None, start_addr=None, end_addr=None, data=None, **api_opts): ''' Ensure the range is removed Supplying the end of the range is optional. State example: .. code-block:: yaml infoblox_range.absent: - name: 'vlan10' infoblox_range.absent: - ...
Ensure the range is removed Supplying the end of the range is optional. State example: .. code-block:: yaml infoblox_range.absent: - name: 'vlan10' infoblox_range.absent: - name: - start_addr: 127.0.1.20
def advisory_lock(dax, key, lock_mode=LockMode.wait, xact=False): """A context manager for obtaining a lock, executing code, and then releasing the lock. A boolean value is passed to the block indicating whether or not the lock was obtained. :dax: a DataAccess instance :key: either a big int or a 2-tuple ...
A context manager for obtaining a lock, executing code, and then releasing the lock. A boolean value is passed to the block indicating whether or not the lock was obtained. :dax: a DataAccess instance :key: either a big int or a 2-tuple of integers :lock_mode: a member of the LockMode enum. Determines how...
def _get_samples(n, sim, inc_warmup=True): # NOTE: this is in stanfit-class.R in RStan (rather than misc.R) """Get chains for `n`th parameter. Parameters ---------- n : int sim : dict A dictionary tied to a StanFit4Model instance. Returns ------- chains : list of array ...
Get chains for `n`th parameter. Parameters ---------- n : int sim : dict A dictionary tied to a StanFit4Model instance. Returns ------- chains : list of array Each chain is an element in the list.
def presign_v4(method, url, access_key, secret_key, session_token=None, region=None, headers=None, expires=None, response_headers=None, request_date=None): """ Calculates signature version '4' for regular presigned URLs. :param method: Method to be presigned examples 'PUT', 'G...
Calculates signature version '4' for regular presigned URLs. :param method: Method to be presigned examples 'PUT', 'GET'. :param url: URL to be presigned. :param access_key: Access key id for your AWS s3 account. :param secret_key: Secret access key for your AWS s3 account. :param session_token: Se...
def is_cgi(self): """Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that ...
Test whether self.path corresponds to a CGI script. Returns True and updates the cgi_info attribute to the tuple (dir, rest) if self.path requires running a CGI script. Returns False otherwise. If any exception is raised, the caller should assume that self.path was rejected as ...
def peek(self, eof_token=False): """Same as :meth:`next`, except the token is not dequeued.""" if len(self.queue) == 0: self._refill(eof_token) return self.queue[-1]
Same as :meth:`next`, except the token is not dequeued.
def get_payments_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1): """ Get payments of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return...
Get payments of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return: list
def _von_mises_cdf_normal(x, concentration, dtype): """Computes the von Mises CDF and its derivative via Normal approximation.""" def cdf_func(concentration): """A helper function that is passed to value_and_gradient.""" # z is an "almost Normally distributed" random variable. z = ((np.sqrt(2. / np.pi)...
Computes the von Mises CDF and its derivative via Normal approximation.
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True, clean_trailing_whitespaces=True, safe_save=True, restore_cursor_position=True, preferred_eol=0, autodetect_eol=True, show_whitespaces=False, **kwargs): """ Opens a ...
Opens a document. :param path: Path of the document to open :param encoding: The encoding to use to open the file. Default is locale.getpreferredencoding(). :param replace_tabs_by_spaces: Enable/Disable replace tabs by spaces. Default is true. :param clean_traili...
def ParseFileObject(self, parser_mediator, file_object): """Parses an Amcache.hve file for events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. """ regf_...
Parses an Amcache.hve file for events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
def glob (dirs, patterns): """ Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can...
Returns the list of files matching the given pattern in the specified directory. Both directories and patterns are supplied as portable paths. Each pattern should be non-absolute path, and can't contain "." or ".." elements. Each slash separated element of pattern can contain the following special char...
def set_data(self, data): """Sets this parameter's value on all contexts.""" self.shape = data.shape if self._data is None: assert self._deferred_init, \ "Parameter '%s' has not been initialized"%self.name self._deferred_init = self._deferred_init[:3] + (...
Sets this parameter's value on all contexts.
async def is_owner(self, user): """Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. Parameters ----------- u...
Checks if a :class:`~discord.User` or :class:`~discord.Member` is the owner of this bot. If an :attr:`owner_id` is not set, it is fetched automatically through the use of :meth:`~.Bot.application_info`. Parameters ----------- user: :class:`.abc.User` The use...
def get_free_gpus(max_procs=0): """ Checks the number of processes running on your GPUs. Parameters ---------- max_procs : int Maximum number of procs allowed to run on a gpu for it to be considered 'available' Returns ------- availabilities : list(bool) List of...
Checks the number of processes running on your GPUs. Parameters ---------- max_procs : int Maximum number of procs allowed to run on a gpu for it to be considered 'available' Returns ------- availabilities : list(bool) List of length N for an N-gpu system. The nth value...
def get_dataset_files(in_path): """Gets the files of the given dataset.""" # Get audio files audio_files = [] for ext in ds_config.audio_exts: audio_files += glob.glob( os.path.join(in_path, ds_config.audio_dir, "*" + ext)) # Make sure directories exist utils.ensure_dir(os.p...
Gets the files of the given dataset.