code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def apply_chromatic_adaptation_on_color(color, targ_illum, adaptation='bradford'): """ Convenience function to apply an adaptation directly to a Color object. """ xyz_x = color.xyz_x xyz_y = color.xyz_y xyz_z = color.xyz_z orig_illum = color.illuminant targ_illum = targ_illum.lower() ...
Convenience function to apply an adaptation directly to a Color object.
def generate_apsara_log_config(json_value): """Generate apsara logtail config from loaded json value :param json_value: :return: """ input_detail = json_value['inputDetail'] output_detail = json_value['outputDetail'] config_name = json_value['configName'] ...
Generate apsara logtail config from loaded json value :param json_value: :return:
def xmlrpc_task_done(self, result): """ Take the results of a computation and put it into the results list. """ (task_id, task_results) = result del self.scheduled_tasks[task_id] self.task_store.update_results(task_id, task_results) self.results += 1 retur...
Take the results of a computation and put it into the results list.
def _set_digraph_b(self, char): ''' Sets the second part of a digraph. ''' self.has_digraph_b = True # Change the active vowel to the one provided by the second part # of the digraph. self.active_vowel_ro = di_b_lt[char][0] self.active_dgr_b_info = di_b_lt...
Sets the second part of a digraph.
def aspirate(self, volume: float = None, location: Union[types.Location, Well] = None, rate: float = 1.0) -> 'InstrumentContext': """ Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location If only...
Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location If only a volume is passed, the pipette will aspirate from its current position. If only a location is passed, :py:meth:`aspirate` will default to its :py:attr:`max_volume`. :param vo...
def update(self, y=None, inplace=False, **kwargs): """ Add data or change classification parameters. Parameters ---------- y : array (n,1) array of data to classify inplace : bool whether to conduct the up...
Add data or change classification parameters. Parameters ---------- y : array (n,1) array of data to classify inplace : bool whether to conduct the update in place or to return a copy estimated fro...
def toto(arch_name, comment='', clear=False, read_comment=False, list_members=False, time_show=False): """ Small utility for changing comment in a zip file without changing the file modification datetime. """ if comment and clear: clingon.RunnerError("You cannot specify --comment and --clear...
Small utility for changing comment in a zip file without changing the file modification datetime.
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if self.has_option([u"--list-parameters"]): return self.print_parameters() if len(self.actual_arguments) < 2: return self.print_help() c...
Perform command and return the appropriate exit code. :rtype: int
def add_node(self,node): """ Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being ...
Add a CondorDAGNode to this DAG. The CondorJob that the node uses is also added to the list of Condor jobs in the DAG so that a list of the submit files needed by the DAG can be maintained. Each unique CondorJob will be added once to prevent duplicate submit files being written. @param node: CondorDAGNo...
def _api_item_history(self, plugin, item, nb=0): """Glances API RESTful implementation. Return the JSON representation of the couple plugin/history of item HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error """ return self._api_itemvalue(plu...
Glances API RESTful implementation. Return the JSON representation of the couple plugin/history of item HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error
def withdraw(self, amount): """ Withdraws specified neopoints from the user's account, returns result Parameters: amount (int) -- Amount of neopoints to withdraw Returns bool - True if successful, False otherwise Raises ...
Withdraws specified neopoints from the user's account, returns result Parameters: amount (int) -- Amount of neopoints to withdraw Returns bool - True if successful, False otherwise Raises notEnoughBalance
def query(self, sql, parameters=None): """A generator to issue a query on the server, mogrifying the parameters against the sql statement. Results are returned as a :py:class:`queries.Results` object which can act as an iterator and has multiple ways to access the result data. :...
A generator to issue a query on the server, mogrifying the parameters against the sql statement. Results are returned as a :py:class:`queries.Results` object which can act as an iterator and has multiple ways to access the result data. :param str sql: The SQL statement :param di...
def push(self, value: Union[int, bytes]) -> None: """ Push an item onto the stack. """ if len(self.values) > 1023: raise FullStack('Stack limit reached') validate_stack_item(value) self.values.append(value)
Push an item onto the stack.
def _remove_from_world(self): """ Clear all the internal data the token needed while it was part of the world. Note that this method doesn't actually remove the token from the world. That's what World._remove_token() does. This method is just responsible for setting...
Clear all the internal data the token needed while it was part of the world. Note that this method doesn't actually remove the token from the world. That's what World._remove_token() does. This method is just responsible for setting the internal state of the token being removed.
def _setAttributes(self, attributes): '''parameters attributes -- a flat list of all attributes, from this list all items in attribute_typecode_dict will be generated into attrComponents. returns a list of strings representing the attribute_typecode_dict. ''' ...
parameters attributes -- a flat list of all attributes, from this list all items in attribute_typecode_dict will be generated into attrComponents. returns a list of strings representing the attribute_typecode_dict.
def dst_to_src(self, dst_file): """Map destination path to source URI.""" for map in self.mappings: src_uri = map.dst_to_src(dst_file) if (src_uri is not None): return(src_uri) # Must have failed if loop exited raise MapperError( "Unabl...
Map destination path to source URI.
def get_img_tag(self, title='', alt_text='', **kwargs): """ Build a <img> tag for the image with the specified options. Returns: an HTML fragment. """ try: style = [] for key in ('img_style', 'style'): if key in kwargs: if isinstance...
Build a <img> tag for the image with the specified options. Returns: an HTML fragment.
def ContainsKey(self, public_key): """ Test if the wallet contains the supplied public key. Args: public_key (edcsa.Curve.point): a public key to test for its existance. e.g. KeyPair.PublicKey Returns: bool: True if exists, False otherwise. """ r...
Test if the wallet contains the supplied public key. Args: public_key (edcsa.Curve.point): a public key to test for its existance. e.g. KeyPair.PublicKey Returns: bool: True if exists, False otherwise.
def isSelectionPositionValid(self, selPos: tuple): """ Return **True** if the start- and end position denote valid positions within the document. |Args| * ``selPos`` (**tuple**): tuple with four integers. |Returns| **bool**: **True** if the positions are valid...
Return **True** if the start- and end position denote valid positions within the document. |Args| * ``selPos`` (**tuple**): tuple with four integers. |Returns| **bool**: **True** if the positions are valid; **False** otherwise. |Raises| * **None**
def get_health_events(self, recipient): """ Starts a healthcheck task for `recipient` and returns a HealthEvents with locks to react on its current state. """ if recipient not in self.addresses_events: self.start_health_check(recipient) return self.addresses_events[r...
Starts a healthcheck task for `recipient` and returns a HealthEvents with locks to react on its current state.
def cached_download(url, name): """Download the data at a URL, and cache it under the given name. The file is stored under `pyav/test` with the given name in the directory :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of: - the current virtualenv - ``/usr/local/share`` - ``/usr/...
Download the data at a URL, and cache it under the given name. The file is stored under `pyav/test` with the given name in the directory :envvar:`PYAV_TESTDATA_DIR`, or the first that is writeable of: - the current virtualenv - ``/usr/local/share`` - ``/usr/local/lib`` - ``/usr/share`` - `...
def _write_error_batch_wait(future, batch, database, measurement, measurements): """Invoked by the IOLoop, this method checks if the HTTP request future created by :meth:`_write_error_batch` is done. If it's done it will evaluate the result, logging any error and moving on to the...
Invoked by the IOLoop, this method checks if the HTTP request future created by :meth:`_write_error_batch` is done. If it's done it will evaluate the result, logging any error and moving on to the next measurement. If there are no measurements left in the `measurements` argument, it will consider the ba...
def _activity_import_doc(self, time_doc, activities): ''' Import activities for a single document into timeline. ''' batch_updates = [time_doc] # We want to consider only activities that happend before time_doc # do not move this, because time_doc._start changes #...
Import activities for a single document into timeline.
def byteorder_isnative(byteorder): """Return if byteorder matches the system's byteorder. >>> byteorder_isnative('=') True """ if byteorder in ('=', sys.byteorder): return True keys = {'big': '>', 'little': '<'} return keys.get(byteorder, byteorder) == keys[sys.byteorder]
Return if byteorder matches the system's byteorder. >>> byteorder_isnative('=') True
def calculate_leaf_paths(self): """Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves. """ reverse_xref = {} leaves = set() for v in self.value.values(): if v.leaf: leaves.add(v) for xref in v.value_xref:...
Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
def update_text(self): """ Write the current text, and check for any new text changes. This also updates the elapsed time. """ self.write() try: newtext = self.text_queue.get_nowait() self._text = newtext except Empty: pass
Write the current text, and check for any new text changes. This also updates the elapsed time.
def gcm_send_message(registration_id, data, encoding='utf-8', **kwargs): """ Standalone method to send a single gcm notification """ messenger = GCMMessenger(registration_id, data, encoding=encoding, **kwargs) return messenger.send_plain()
Standalone method to send a single gcm notification
def consume(self, data): """Takes input that must be parsed Note: Attach all your listeners before calling this method Args: data (str): input json string """ if not self._started: self.fire(JSONStreamer.DOC_START_EVENT) self._sta...
Takes input that must be parsed Note: Attach all your listeners before calling this method Args: data (str): input json string
def run_filter_radia(job, bams, radia_file, univ_options, radia_options, chrom): """ This module will run filterradia on the RNA and DNA bams. ARGUMENTS 1. bams: REFER ARGUMENTS of run_radia() 2. univ_options: REFER ARGUMENTS of run_radia() 3. radia_file: <JSid of vcf generated by run_radia()> ...
This module will run filterradia on the RNA and DNA bams. ARGUMENTS 1. bams: REFER ARGUMENTS of run_radia() 2. univ_options: REFER ARGUMENTS of run_radia() 3. radia_file: <JSid of vcf generated by run_radia()> 3. radia_options: REFER ARGUMENTS of run_radia() 4. chrom: REFER ARGUMENTS of run_rad...
def find_all(self, predicate): """Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool. """ for _nid, entry in self._registry.items(): if predicate(...
Returns a generator that produces a sequence of Entry objects for which the predicate returned True. Args: predicate: A callable that returns a value coercible to bool.
def master_event(type, master=None): ''' Centralized master event function which will return event type based on event_map ''' event_map = {'connected': '__master_connected', 'disconnected': '__master_disconnected', 'failback': '__master_failback', 'ali...
Centralized master event function which will return event type based on event_map
def remove_optional(annotation: type): """ Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away. """ origin = getattr(annotation, '__origin__', None) args = getattr(annotation, '__args__', (...
Optional[X] annotations are actually represented as Union[X, NoneType]. For our purposes, the "Optional" part is not interesting, so here we throw it away.
def node_to_text(self, node, prev_node_hint=None): """ Return the textual representation of the given `node`. If `prev_node_hint` is specified, then the current node is formatted suitably as following the node given in `prev_node_hint`. This might affect how much space we keep/...
Return the textual representation of the given `node`. If `prev_node_hint` is specified, then the current node is formatted suitably as following the node given in `prev_node_hint`. This might affect how much space we keep/discard, etc.
def show_quickref(self): """Show IPython Cheat Sheet""" from IPython.core.usage import quick_reference self.main.help.show_plain_text(quick_reference)
Show IPython Cheat Sheet
def run_opt(self, popsize, numgen, processors, plot=False, log=False, **kwargs): """ Runs the optimizer. :param popsize: :param numgen: :param processors: :param plot: :param log: :param kwargs: :return: """ self._pa...
Runs the optimizer. :param popsize: :param numgen: :param processors: :param plot: :param log: :param kwargs: :return:
def parse_csv(self, infile, delimiter=",", decimal_sep="."): "Parse template format csv file and create elements dict" keys = ('name','type','x1','y1','x2','y2','font','size', 'bold','italic','underline','foreground','background', 'align','text','priority', 'multiline') s...
Parse template format csv file and create elements dict
def merge(revision, branch_label, message, list_revisions=''): """ Merge two revision together, create new revision file """ alembic_command.merge( config=get_config(), revisions=list_revisions, message=message, branch_label=branch_label, rev_id=revision )
Merge two revision together, create new revision file
def get_containers(self): """ :return: a dict of available containers in the form { "name": { #for example, "default" "id": "container img id", # "sha256:715c5cb5575cdb2641956e42af4a53e69edf763ce701006b2c6e0f4f39b68dd3" ...
:return: a dict of available containers in the form { "name": { #for example, "default" "id": "container img id", # "sha256:715c5cb5575cdb2641956e42af4a53e69edf763ce701006b2c6e0f4f39b68dd3" "created": 12345678 # cre...
def _verify_docker_image_size(self, image_name): """Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is within the limits, False otherwise. """ shell_call(['docker', 'pull', image_name]) try: image_size = subprocess.check_...
Verifies size of Docker image. Args: image_name: name of the Docker image. Returns: True if image size is within the limits, False otherwise.
def default(self, statement: Statement) -> Optional[bool]: """Executed when the command given isn't a recognized command implemented by a do_* method. :param statement: Statement object with parsed input """ if self.default_to_shell: if 'shell' not in self.exclude_from_histo...
Executed when the command given isn't a recognized command implemented by a do_* method. :param statement: Statement object with parsed input
def get_pr_review_status(pr: PullRequestDetails) -> Any: """ References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request """ url = ("https://api.github.com/repos/{}/{}/pulls/{}/reviews" "?access_token={}".format(pr.repo.organization, ...
References: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request
def submit_combine(basename, readers, job_ids=None, project_name=None): """Submit a batch job to combine the outputs of a reading job. This function is provided for backwards compatibility. You should use the PmidSubmitter and submit_combine methods. """ sub = PmidSubmitter(basename, readers, proje...
Submit a batch job to combine the outputs of a reading job. This function is provided for backwards compatibility. You should use the PmidSubmitter and submit_combine methods.
def patch( target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs ): """ `patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new...
`patch` acts as a function decorator, class decorator or a context manager. Inside the body of the function or with statement, the `target` is patched with a `new` object. When the function/with statement exits the patch is undone. If `new` is omitted, then the target is replaced with a `MagicMock`...
def invert_affine_mat44(mat): """Assumes there is only rotate, translate, and uniform scale componenets to the matrix. """ inverted = Matrix44() # Transpose the 3x3 rotation component for i in range(3): for j in range(3): inverted.data[i][j] = mat.data[j][i] # Set tran...
Assumes there is only rotate, translate, and uniform scale componenets to the matrix.
def getReadLengths(reads, gapChars): """ Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values. """ gapChars = set(gapChars) ...
Get all read lengths, excluding gap characters. @param reads: A C{Reads} instance. @param gapChars: A C{str} of sequence characters considered to be gaps. @return: A C{dict} keyed by read id, with C{int} length values.
def codegen(lang, # type: str i, # type: List[Dict[Text, Any]] schema_metadata, # type: Dict[Text, Any] loader # type: Loader ): # type: (...) -> None """Generate classes with loaders for the given Schema Salad description.""" ...
Generate classes with loaders for the given Schema Salad description.
def _split_generators(self, dl_manager): """Returns SplitGenerators.""" url = _DL_URLS[self.builder_config.name] data_dirs = dl_manager.download_and_extract(url) path_to_dataset = os.path.join(data_dirs, tf.io.gfile.listdir(data_dirs)[0]) train_a_path = os.path.join(path_to_dataset, "trainA") ...
Returns SplitGenerators.
def process_bool_arg(arg): """ Determine True/False from argument """ if isinstance(arg, bool): return arg elif isinstance(arg, basestring): if arg.lower() in ["true", "1"]: return True elif arg.lower() in ["false", "0"]: return False
Determine True/False from argument
def get_var_dict_from_ctx(ctx: commands.Context, prefix: str = '_'): """ Returns the dict to be used in REPL for a given Context. """ raw_var_dict = { 'author': ctx.author, 'bot': ctx.bot, 'channel': ctx.channel, 'ctx': ctx, 'find': discord.utils.find, 'g...
Returns the dict to be used in REPL for a given Context.
def exportPreflibFile(self, fileName): """ Exports a preflib format file that contains all the information of the current Profile. :ivar str fileName: The name of the output file to be exported. """ elecType = self.getElecType() if elecType != "soc" and elecType != "to...
Exports a preflib format file that contains all the information of the current Profile. :ivar str fileName: The name of the output file to be exported.
def get_spot_value(self, assets, field, dt, data_frequency): """ Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. ...
Public API method that returns a scalar value representing the value of the desired asset's field at either the given dt. Parameters ---------- assets : Asset, ContinuousFuture, or iterable of same. The asset or assets whose data is desired. field : {'open', 'high', ...
def new_table_graphicFrame(cls, id_, name, rows, cols, x, y, cx, cy): """ Return a ``<p:graphicFrame>`` element tree populated with a table element. """ graphicFrame = cls.new_graphicFrame(id_, name, x, y, cx, cy) graphicFrame.graphic.graphicData.uri = GRAPHIC_DATA_URI_TA...
Return a ``<p:graphicFrame>`` element tree populated with a table element.
def reply_topic(self, topic_id, content): """小组回帖 :return: 帖子 id 或 ``None`` """ data = { 'body': content, 'csrfmiddlewaretoken': self._request.cookies.get('csrftoken') } url = 'http://www.shanbay.com/api/v1/forum/thread/%s/post/' % topic_id ...
小组回帖 :return: 帖子 id 或 ``None``
def get_host_health_temperature_sensors(self, data=None): """Get the health Temp Sensor report. :param: the data to retrieve from the server, defaults to None. :returns: the dictionary containing the temperature sensors information. :raises: IloConnectionError if failed conn...
Get the health Temp Sensor report. :param: the data to retrieve from the server, defaults to None. :returns: the dictionary containing the temperature sensors information. :raises: IloConnectionError if failed connecting to the iLO. :raises: IloError, on an error from iLO.
def register_actions(self, shortcut_manager): """Register callback methods for triggered actions in all child controllers. :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions. """ assert ...
Register callback methods for triggered actions in all child controllers. :param rafcon.gui.shortcut_manager.ShortcutManager shortcut_manager: Shortcut Manager Object holding mappings between shortcuts and actions.
def nmap_discover(): """ This function retrieves ranges from jackal Uses two functions of nmap to find hosts: ping: icmp / arp pinging of targets lookup: reverse dns lookup """ rs = RangeSearch() rs_parser = rs.argparser arg = argparse.ArgumentParser(parents...
This function retrieves ranges from jackal Uses two functions of nmap to find hosts: ping: icmp / arp pinging of targets lookup: reverse dns lookup
def _get_labels_right(self, validate=None): """Get all labels of the right dataframe.""" labels = [] for compare_func in self.features: labels = labels + listify(compare_func.labels_right) # check requested labels (for better error messages) if not is_label_datafra...
Get all labels of the right dataframe.
def post(method, hmc, uri, uri_parms, body, logon_required, wait_for_completion): """Operation: Add Candidate Adapter Ports to an FCP Storage Group.""" assert wait_for_completion is True # async not supported yet # The URI is a POST operation, so we need to construct the SG URI ...
Operation: Add Candidate Adapter Ports to an FCP Storage Group.
def visit_exec(self, node, parent): """visit an Exec node by returning a fresh instance of it""" newnode = nodes.Exec(node.lineno, node.col_offset, parent) newnode.postinit( self.visit(node.body, newnode), _visit_or_none(node, "globals", self, newnode), _visit...
visit an Exec node by returning a fresh instance of it
def is_confusable(string, greedy=False, preferred_aliases=[]): """Checks if ``string`` contains characters which might be confusable with characters from ``preferred_aliases``. If ``greedy=False``, it will only return the first confusable character found without looking at the rest of the string, ``gre...
Checks if ``string`` contains characters which might be confusable with characters from ``preferred_aliases``. If ``greedy=False``, it will only return the first confusable character found without looking at the rest of the string, ``greedy=True`` returns all of them. ``preferred_aliases=[]`` can ...
def step(self, **args): """ SRN.step() Extends network step method by automatically copying hidden layer activations to the context layer. """ if self.sequenceType == None: raise AttributeError("""sequenceType not set! Use SRN.setSequenceType() """) # ...
SRN.step() Extends network step method by automatically copying hidden layer activations to the context layer.
def find(entity, **kwargs): """Return all TypedFields found on the input `Entity` that were initialized with the input **kwargs. Example: >>> find(myentity, multiple=True, type_=Foo) Note: TypedFields.__init__() can accept a string or a class as a type_ argument, but this metho...
Return all TypedFields found on the input `Entity` that were initialized with the input **kwargs. Example: >>> find(myentity, multiple=True, type_=Foo) Note: TypedFields.__init__() can accept a string or a class as a type_ argument, but this method expects a class. Args: ...
def arraymax(X,Y): """ Fast "vectorized" max function for element-wise comparison of two numpy arrays. For two numpy arrays `X` and `Y` of equal length, return numpy array `Z` such that:: Z[i] = max(X[i],Y[i]) **Parameters** **X** : numpy array Numpy...
Fast "vectorized" max function for element-wise comparison of two numpy arrays. For two numpy arrays `X` and `Y` of equal length, return numpy array `Z` such that:: Z[i] = max(X[i],Y[i]) **Parameters** **X** : numpy array Numpy array; `len(X) = len(Y)`. ...
def server_extensions_handshake(requested, supported): # type: (List[str], List[Extension]) -> Optional[bytes] """Agree on the extensions to use returning an appropriate header value. This returns None if there are no agreed extensions """ accepts = {} for offer in requested: name = off...
Agree on the extensions to use returning an appropriate header value. This returns None if there are no agreed extensions
def rpc(ctx, call, arguments, api): """ Construct RPC call directly \b You can specify which API to send the call to: uptick rpc --api assets You can also specify lists using uptick rpc get_objects "['2.0.0', '2.1.0']" """ try: data = list(eval(d) ...
Construct RPC call directly \b You can specify which API to send the call to: uptick rpc --api assets You can also specify lists using uptick rpc get_objects "['2.0.0', '2.1.0']"
def shell_context_processor(self, func: Callable) -> Callable: """Add a shell context processor. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.shell_context_processor def additional_context(): return context ...
Add a shell context processor. This is designed to be used as a decorator. An example usage, .. code-block:: python @app.shell_context_processor def additional_context(): return context
def exception(self, message, *args, **kwargs): """Handle exception """ self.logger.exception(message, *args, **kwargs)
Handle exception
def analysis_download(self, webid, type, run=None, file=None): """ Download a resource for an analysis. E.g. the full report, binaries, screenshots. The full list of resources can be found in our API documentation. When `file` is given, the return value is the filename specified by the ...
Download a resource for an analysis. E.g. the full report, binaries, screenshots. The full list of resources can be found in our API documentation. When `file` is given, the return value is the filename specified by the server, otherwise it's a tuple of (filename, bytes). Parameters: ...
def limit(self, limit): """ Sets the limit of this ListEmployeeWagesRequest. Maximum number of Employee Wages to return per page. Can range between 1 and 200. The default is the maximum at 200. :param limit: The limit of this ListEmployeeWagesRequest. :type: int """ ...
Sets the limit of this ListEmployeeWagesRequest. Maximum number of Employee Wages to return per page. Can range between 1 and 200. The default is the maximum at 200. :param limit: The limit of this ListEmployeeWagesRequest. :type: int
def _go_to_line(editor, line): """ Move cursor to this line in the current buffer. """ b = editor.application.current_buffer b.cursor_position = b.document.translate_row_col_to_index(max(0, int(line) - 1), 0)
Move cursor to this line in the current buffer.
def get_json(self, path: str, params: Dict[str, Any], host: str = 'www.instagram.com', session: Optional[requests.Session] = None, _attempt=1) -> Dict[str, Any]: """JSON request to Instagram. :param path: URL, relative to the given domain which defaults to www.instagram.com/ :p...
JSON request to Instagram. :param path: URL, relative to the given domain which defaults to www.instagram.com/ :param params: GET parameters :param host: Domain part of the URL from where to download the requested JSON; defaults to www.instagram.com :param session: Session to use, or No...
def match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function r...
Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 and RFC 6125 rules are followed, but IP addresses are not accepted for *hostname*. CertificateError is raised on failure. On success, the function returns nothing.
def update_metric_by_name(self, metric_name, metric_type, description=None, custom_properties=None, tags=None, **kwargs): """ Create or update a metric object Args: metric_name (string): name of metric type (string): metric type, must be one...
Create or update a metric object Args: metric_name (string): name of metric type (string): metric type, must be one of 'gauge', 'counter', 'cumulative_counter' description (optional[string]): a description custom_properties (optional[d...
def write_state_file(self): """Save information that must persist to a file. We do not want to create a new VPC and new identical security groups, so we save information about them in a file between runs. """ fh = open('awsproviderstate.json', 'w') state = {} sta...
Save information that must persist to a file. We do not want to create a new VPC and new identical security groups, so we save information about them in a file between runs.
def add_node(self, node, weight=1): """ Adds node to circle and rebuild it. """ self._nodes.add(node) self._weights[node] = weight self._hashring = dict() self._sorted_keys = [] self._build_circle()
Adds node to circle and rebuild it.
def _append_instruction(self, obj, qargs=None): """Update the current Operator by apply an instruction.""" if isinstance(obj, Instruction): chan = None if obj.name == 'reset': # For superoperator evolution we can simulate a reset as # a non-unitary...
Update the current Operator by apply an instruction.
def respond_to_SIGHUP(signal_number, frame, logger=None): """raise the KeyboardInterrupt which will cause the app to effectively shutdown, closing all it resources. Then, because it sets 'restart' to True, the app will reread all the configuration information, rebuild all of its structures and resource...
raise the KeyboardInterrupt which will cause the app to effectively shutdown, closing all it resources. Then, because it sets 'restart' to True, the app will reread all the configuration information, rebuild all of its structures and resources and start running again
def calc_asymptotic_covariance(hessian, fisher_info_matrix): """ Parameters ---------- hessian : 2D ndarray. It should have shape `(num_vars, num_vars)`. It is the matrix of second derivatives of the total loss across the dataset, with respect to each pair of coefficients being e...
Parameters ---------- hessian : 2D ndarray. It should have shape `(num_vars, num_vars)`. It is the matrix of second derivatives of the total loss across the dataset, with respect to each pair of coefficients being estimated. fisher_info_matrix : 2D ndarray. It should have a s...
def _comparison_functions(cls, partial=False): """Retrieve comparison methods to apply on version components. This is a private API. Args: partial (bool): whether to provide 'partial' or 'strict' matching. Returns: 5-tuple of cmp-like functions. """ ...
Retrieve comparison methods to apply on version components. This is a private API. Args: partial (bool): whether to provide 'partial' or 'strict' matching. Returns: 5-tuple of cmp-like functions.
def follow(user, obj): """ Make a user follow an object """ follow, created = Follow.objects.get_or_create(user, obj) return follow
Make a user follow an object
def has_plugin(self, name=None, plugin_type=None): """ Check if the manager has a plugin / plugin(s), either by its name, type, or simply checking if the manager has any plugins registered in it. Utilizing the name argument will check if a plugin with that name exists in the manager. ...
Check if the manager has a plugin / plugin(s), either by its name, type, or simply checking if the manager has any plugins registered in it. Utilizing the name argument will check if a plugin with that name exists in the manager. Using both the name and plugin_type arguments will check if a plu...
def predict(self, X): """Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters -------...
Predict the closest cluster each sample in X belongs to. In the vector quantization literature, `cluster_centers_` is called the code book and each value returned by `predict` is the index of the closest code in the code book. Parameters ---------- X : ArrayRDD containi...
def initialize(self): """Sets up initial ensime-vim editor settings.""" # TODO: This seems wrong, the user setting value is never used anywhere. if 'EnErrorStyle' not in self._vim.vars: self._vim.vars['EnErrorStyle'] = 'EnError' self._vim.command('highlight EnErrorStyle cterm...
Sets up initial ensime-vim editor settings.
def _get_cache(self): """ Return the cache to use for thundering herd protection, etc. """ if not self._cache: self._cache = get_cache(self.app) return self._cache
Return the cache to use for thundering herd protection, etc.
def resize(self, size=None): """ Resize the container's PTY. If `size` is not None, it must be a tuple of (height,width), otherwise it will be determined by the size of the current TTY. """ if not self.operation.israw(): return size = size or tty.si...
Resize the container's PTY. If `size` is not None, it must be a tuple of (height,width), otherwise it will be determined by the size of the current TTY.
def _db_upgrade(self, db_name): """ Upgrade nipap database schema """ current_db_version = self._get_db_version() self._execute(db_schema.functions) for i in range(current_db_version, nipap.__db_version__): self._logger.info("Upgrading DB schema:", i, "to", i+1) ...
Upgrade nipap database schema
def transformFromNative(obj): """ Replace the Name in obj.value with a string. """ obj.isNative = False obj.value = serializeFields(obj.value, NAME_ORDER) return obj
Replace the Name in obj.value with a string.
def pivot_pandas_to_excel(soup, show_intermediate_breakdown=False, show_total_breakdown=False): '''pandas style pivot to excel style pivot formatting for outlook/html This function is meant to be provided to the email functionality as a postprocessor. It expects a jupyter or pandas exported html table of a...
pandas style pivot to excel style pivot formatting for outlook/html This function is meant to be provided to the email functionality as a postprocessor. It expects a jupyter or pandas exported html table of a dataframe with the following index: example: # a single pivot pt1 = pd.pivot_table(data, ...
def load_plugins(self, plugin_path): """ Loads plugins from modules in plugin_path. Looks for the config_name property in each object that's found. If so, adds that to the dictionary with the config_name as the key. config_name should be unique between different plugins. :param ...
Loads plugins from modules in plugin_path. Looks for the config_name property in each object that's found. If so, adds that to the dictionary with the config_name as the key. config_name should be unique between different plugins. :param plugin_path: Path to load plugins from :return: d...
def execute_code_block(elem, doc): """Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of the command. """ command = select_executor(elem, doc).split(' ') code = elem.text if 'plt' in elem.attrib...
Executes a code block by passing it to the executor. Args: elem The AST element. doc The document. Returns: The output of the command.
async def subscribe( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, subscribe_field_resolver: GraphQLFieldResolver = None, )...
Create a GraphQL subscription. Implements the "Subscribe" algorithm described in the GraphQL spec. Returns a coroutine object which yields either an AsyncIterator (if successful) or an ExecutionResult (client error). The coroutine will raise an exception if a server error occurs. If the client-pr...
def set_password(username, password, encrypted=False, role=None, crypt_salt=None, algorithm='sha256', **kwargs): ''' Set users password on switch. username Username to configure password ...
Set users password on switch. username Username to configure password Password to configure for username encrypted Whether or not to encrypt the password Default: False role Configure role for the username Default: None crypt_salt Configur...
def sort_projects( self, workflowTags): """*order the projects within this taskpaper object via a list of tags* The order of the tags in the list dictates the order of the sort - first comes first* **Key Arguments:** - ``workflowTags`` -- a string of space/...
*order the projects within this taskpaper object via a list of tags* The order of the tags in the list dictates the order of the sort - first comes first* **Key Arguments:** - ``workflowTags`` -- a string of space/comma seperated tags. **Return:** - ``None`` ...
def iter_subclasses(class_): """Iterate over all the subclasses (and subclasses thereof, etc.) of given class. :param class_: Class to yield the subclasses of :return: Iterable of subclasses, sub-subclasses, etc. of ``class_`` """ ensure_class(class_) classes = set() def descend(class...
Iterate over all the subclasses (and subclasses thereof, etc.) of given class. :param class_: Class to yield the subclasses of :return: Iterable of subclasses, sub-subclasses, etc. of ``class_``
def get_update_status_brok(self): """ Create an update item brok :return: Brok object :rtype: alignak.Brok """ data = {'uuid': self.uuid} self.fill_data_brok_from(data, 'full_status') return Brok({'type': 'update_' + self.my_type + '_status', 'data': data...
Create an update item brok :return: Brok object :rtype: alignak.Brok
def knx_to_date(knxdata): """Convert a 3 byte KNX data object to a date""" if len(knxdata) != 3: raise KNXException("Can only convert a 3 Byte object to date") year = knxdata[2] if year >= 90: year += 1900 else: year += 2000 return date(year, knxdata[1], knxdata[0])
Convert a 3 byte KNX data object to a date
def bowtie_alignment_plot (self): """ Make the HighCharts HTML to plot the alignment rates """ # Specify the order of the different possible categories keys = OrderedDict() keys['reads_aligned'] = { 'color': '#8bbc21', 'name': 'Aligned' } keys['multimapped'] = { 'color': '#2f7...
Make the HighCharts HTML to plot the alignment rates
def _get_path(self, file): """Creates the cache directory if it doesn't already exist. Returns the full path to the specified file inside the cache directory.""" dir = self._cache_directory() if not os.path.exists(dir): os.makedirs(dir) return os.path.join(dir, file)
Creates the cache directory if it doesn't already exist. Returns the full path to the specified file inside the cache directory.
def decompressBWT(inputDir, outputDir, numProcs, logger): ''' This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do, it's included in this package for completion purposes. @param inputDir - the directory of the compressed BWT we plan on decompressing ...
This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do, it's included in this package for completion purposes. @param inputDir - the directory of the compressed BWT we plan on decompressing @param outputFN - the directory for the output decompressed BWT, it...
def set_scan_option(self, scan_id, name, value): """ Sets a scan's option to a provided value. """ return self.scan_collection.set_option(scan_id, name, value)
Sets a scan's option to a provided value.