code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def set_mode_cb(self, mode, tf): """Called when one of the Move/Draw/Edit radio buttons is selected.""" if tf: self.canvas.set_draw_mode(mode) if mode == 'edit': self.edit_select_marks() return True
Called when one of the Move/Draw/Edit radio buttons is selected.
def supports_suggested_actions(channel_id: str, button_cnt: int = 100) -> bool: """Determine if a number of Suggested Actions are supported by a Channel. Args: channel_id (str): The Channel to check the if Suggested Actions are supported in. button_cnt (int, optional): Defaults ...
Determine if a number of Suggested Actions are supported by a Channel. Args: channel_id (str): The Channel to check the if Suggested Actions are supported in. button_cnt (int, optional): Defaults to 100. The number of Suggested Actions to check for the Channel. Returns: ...
def is_annual(self): """Check if an analysis period is annual.""" if (self.st_month, self.st_day, self.st_hour, self.end_month, self.end_day, self.end_hour) == (1, 1, 0, 12, 31, 23): return True else: return False
Check if an analysis period is annual.
def validate(data, schema=None): """Validate the given dictionary against the given schema. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors...
Validate the given dictionary against the given schema. Args: data (dict): record to validate. schema (Union[dict, str]): schema to validate against. If it is a string, it is intepreted as the name of the schema to load (e.g. ``authors`` or ``jobs``). If it is ``None``, the ...
def insert_from_xmldoc(connection, source_xmldoc, preserve_ids = False, verbose = False): """ Insert the tables from an in-ram XML document into the database at the given connection. If preserve_ids is False (default), then row IDs are modified during the insert process to prevent collisions with IDs already in t...
Insert the tables from an in-ram XML document into the database at the given connection. If preserve_ids is False (default), then row IDs are modified during the insert process to prevent collisions with IDs already in the database. If preserve_ids is True then IDs are not modified; this will result in database ...
def get_success_url(self): """ Returns redirect URL for valid form submittal. :rtype: str. """ if self.success_url: url = force_text(self.success_url) else: url = reverse('{0}:index'.format(self.url_namespace)) return url
Returns redirect URL for valid form submittal. :rtype: str.
def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sa...
Run selected module generator.
async def self_check(cls): """ Check that the configuration is correct - Presence of "token" in the settings - Presence of "BERNARD_BASE_URL" in the global configuration """ # noinspection PyTypeChecker async for check in super(Telegram, cls).self_check(): ...
Check that the configuration is correct - Presence of "token" in the settings - Presence of "BERNARD_BASE_URL" in the global configuration
def repeater(call, args=None, kwargs=None, retries=4): """ repeat call x-times: docker API is just awesome :param call: function :param args: tuple, args for function :param kwargs: dict, kwargs for function :param retries: int, how many times we try? :return: response of the call """ ...
repeat call x-times: docker API is just awesome :param call: function :param args: tuple, args for function :param kwargs: dict, kwargs for function :param retries: int, how many times we try? :return: response of the call
def run_the_target(G, target, settings): """ Wrapper function that sends to commands in a target's 'formula' to run_commands() Args: The graph we are going to build The target to run The settings dictionary """ sprint = settings["sprint"] sprint("Running target {}".f...
Wrapper function that sends to commands in a target's 'formula' to run_commands() Args: The graph we are going to build The target to run The settings dictionary
def get_parameter_value(self, parameter, from_cache=True, timeout=10): """ Retrieve the current value of the specified parameter. :param str parameter: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :param bool from_cache: ...
Retrieve the current value of the specified parameter. :param str parameter: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :param bool from_cache: If ``False`` this call will block until a fresh value is re...
def update(self, *iterables): """Update the set, adding elements from all *iterables*.""" _set = self._set values = set(chain(*iterables)) if (4 * len(values)) > len(_set): _list = self._list _set.update(values) _list.clear() _list.update(_...
Update the set, adding elements from all *iterables*.
def _applyInter(finter0, finter1, conflict="ignore"): """ Return the restriction of first interval by the second. Args: - inter0, inter1 (tuple of Feature): intervals Return(tuple of Feature): the resulting interval - conflict(str): if a property hasn't compatible valu...
Return the restriction of first interval by the second. Args: - inter0, inter1 (tuple of Feature): intervals Return(tuple of Feature): the resulting interval - conflict(str): if a property hasn't compatible values/constrains, do: - ``"error"``: raise exception. -...
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'key') and self.key is not None: _dict['key'] = self.key if hasattr(self, 'matching_results') and self.matching_results is not None: _dict['m...
Return a json dictionary representing this model.
def del_password(name): ''' Deletes the account password :param str name: The user name of the account :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash sal...
Deletes the account password :param str name: The user name of the account :return: True if successful, otherwise False :rtype: bool :raises: CommandExecutionError on user not found or any other unknown error CLI Example: .. code-block:: bash salt '*' shadow.del_password username
def searchIndex(self, printData=True): """Search the index with all the repo's specified parameters""" backupValue = copy.deepcopy(self.output.printData) self.output.printData = printData self.data = self.index.search(self.searchString, self.category, self.math, self.game, self.searchFiles, self.extension) se...
Search the index with all the repo's specified parameters
def format(self, dt, fmt, locale=None): """ Formats a DateTime instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.DateTime :param fmt: The format to use :type fmt: str :param locale: The locale to use :type loc...
Formats a DateTime instance with a given format and locale. :param dt: The instance to format :type dt: pendulum.DateTime :param fmt: The format to use :type fmt: str :param locale: The locale to use :type locale: str or Locale or None :rtype: str
def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey) if compressed: pubkey = pubkey.compressed() else: pubkey = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA256(...
Derive address using ``RIPEMD160(SHA256(x))``
def generate_data_type(self, data_type): """Output a data type definition (a struct or union).""" if isinstance(data_type, Struct): # Output a struct definition. self.emit('') self.emit('struct %s' % data_type.name) with self.indent(): if d...
Output a data type definition (a struct or union).
def print_bytes(data): """ Function to visualize byte streams. Split into bytes, print to console. :param bs: BYTE STRING """ bs = bytearray(data) symbols_in_one_line = 8 n = len(bs) // symbols_in_one_line i = 0 for i in range(n): print(str(i*symbols_in_one_line)+" | "+" ".jo...
Function to visualize byte streams. Split into bytes, print to console. :param bs: BYTE STRING
def __store_clustering_results(self, amount_clusters, leaf_blocks): """! @brief Stores clustering results in a convenient way. @param[in] amount_clusters (uint): Amount of cluster that was allocated during processing. @param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest ce...
! @brief Stores clustering results in a convenient way. @param[in] amount_clusters (uint): Amount of cluster that was allocated during processing. @param[in] leaf_blocks (list): Leaf BANG-blocks (the smallest cells).
def _validate( # pylint: disable=too-many-arguments cls, sign, integer_part, non_repeating_part, repeating_part, base ): """ Check if radix is valid. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the part on the left...
Check if radix is valid. :param int sign: -1, 0, or 1 as appropriate :param integer_part: the part on the left side of the radix :type integer_part: list of int :param non_repeating_part: non repeating part on left side :type non_repeating_part: list of int :param repeat...
def _heappop_max(heap): """Maxheap version of a heappop.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup_max(heap, 0) return returnitem return lastelt
Maxheap version of a heappop.
def texts(self: object, fileids: str, plaintext: bool = True): """ Returns the text content of a .tess file, i.e. removing the bracketed citation info (e.g. "<Ach. Tat. 1.1.0>") """ for doc in self.docs(fileids): if plaintext==True: doc = re.sub(r'<....
Returns the text content of a .tess file, i.e. removing the bracketed citation info (e.g. "<Ach. Tat. 1.1.0>")
def collect_iptable(self, tablename): """ When running the iptables command, it unfortunately auto-loads the modules before trying to get output. Some people explicitly don't want this, so check if the modules are loaded before running the command. If they aren't loaded, there can't po...
When running the iptables command, it unfortunately auto-loads the modules before trying to get output. Some people explicitly don't want this, so check if the modules are loaded before running the command. If they aren't loaded, there can't possibly be any relevant rules in that table
def average(sequence, key): """Averages a sequence based on a key.""" return sum(map(key, sequence)) / float(len(sequence))
Averages a sequence based on a key.
def put_file(self, in_path, out_path): ''' transfer a file from local to remote ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) data = file(in_path)...
transfer a file from local to remote
def lsa_twitter(cased_tokens): """ Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens """ # Only 5 of these tokens are saved for a no_below=2 filter: # PyCons NLPS #PyCon2016 #NaturalLanguageProcessing #naturallanguageprocessing if cased_tokens is N...
Latent Sentiment Analyis on random sampling of twitter search results for words listed in cased_tokens
def validate(self, data): """Validate data. Raise NotValid error for invalid data.""" validated = self._validated(data) errors = [] for validator in self.additional_validators: if not validator(validated): errors.append( "%s invalidated by ...
Validate data. Raise NotValid error for invalid data.
def select_many( self, collection_selector=identity, result_selector=identity): '''Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a ...
Projects each element of a sequence to an intermediate new sequence, flattens the resulting sequences into one sequence and optionally transforms the flattened sequence using a selector function. Note: This method uses deferred execution. Args: collection_selector: A unary ...
def masses(self): """ :returns: peak masses :rtype: list of floats """ buf = ffi.new("double[]", self.size) ims.spectrum_masses(self.ptr, buf) return list(buf)
:returns: peak masses :rtype: list of floats
def remove_entry_listener(self, registration_id): """ Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise. ...
Removes the specified entry listener. Returns silently if there is no such listener added before. :param registration_id: (str), id of registered listener. :return: (bool), ``true`` if registration is removed, ``false`` otherwise.
def _find_utmp(): ''' Figure out which utmp file to use when determining runlevel. Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness. ''' result = {} # These are the likely locations for the file on Ubuntu for utmp in '/var/run/utmp', '/run/utmp': try: r...
Figure out which utmp file to use when determining runlevel. Sometimes /var/run/utmp doesn't exist, /run/utmp is the new hotness.
def registerDisplay(func): """ Registers a function to the display hook queue to be called on hook. Look at the sys.displayhook documentation for more information. :param func | <callable> """ setup() ref = weakref.ref(func) if ref not in _displayhooks: _displayhooks.ap...
Registers a function to the display hook queue to be called on hook. Look at the sys.displayhook documentation for more information. :param func | <callable>
def upgrade(): """Upgrade database.""" op.create_table( 'records_metadata', sa.Column('created', sa.DateTime(), nullable=False), sa.Column('updated', sa.DateTime(), nullable=False), sa.Column( 'id', sqlalchemy_utils.types.uuid.UUIDType(), nullable=False), sa.C...
Upgrade database.
def pdf_link(self, inv_link_f, y, Y_metadata=None): """ Likelihood function given inverse link of f. .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}} :param inv_link_f: latent variables inverse link of f. :type inv_link_f: Nx1 array ...
Likelihood function given inverse link of f. .. math:: p(y_{i}|\\lambda(f_{i})) = \\lambda(f_{i})^{y_{i}}(1-f_{i})^{1-y_{i}} :param inv_link_f: latent variables inverse link of f. :type inv_link_f: Nx1 array :param y: data :type y: Nx1 array :param Y_metadat...
def scheme_host_port_prefix(self, scheme='http', host='host', port=None, prefix=None): """Return URI composed of scheme, server, port, and prefix.""" uri = scheme + '://' + host if (port and not ((scheme == 'http' and port == 80) or (sche...
Return URI composed of scheme, server, port, and prefix.
def yyparse(self, lexfile): """ Args: lexfile (str): Flex file to be parsed Returns: DFA: A dfa automaton """ temp = tempfile.gettempdir() self.outfile = temp+'/'+''.join( random.choice( string.ascii_uppercase + string.d...
Args: lexfile (str): Flex file to be parsed Returns: DFA: A dfa automaton
def get_new_pid(institute): """ Return a new Project ID Keyword arguments: institute_id -- Institute id """ number = '0001' prefix = 'p%s' % institute.name.replace(' ', '')[:4] found = True while found: try: Project.objects.get(pid=prefix + number) number...
Return a new Project ID Keyword arguments: institute_id -- Institute id
def response_add(self, request, obj, post_url_continue=POST_URL_CONTINUE): """If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup """ if '_a...
If we're adding, save must be "save and continue editing" Two exceptions to that workflow: * The user has pressed the 'Save and add another' button * We are adding a user in a popup
def concatenate_variables(scope, variables, container): ''' This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation. ''' # Check if it's possible to concatenate those inputs. ...
This function allocate operators to from a float tensor by concatenating all input variables. Notice that if all integer inputs would be converted to floats before concatenation.
def formatter(self): """ Creates and returns a Formatter capable of nicely formatting Lambda function logs Returns ------- LogsFormatter """ formatter_chain = [ LambdaLogMsgFormatters.colorize_errors, # Format JSON "before" highlighting t...
Creates and returns a Formatter capable of nicely formatting Lambda function logs Returns ------- LogsFormatter
def _set_logging( logger_name="colin", level=logging.INFO, handler_class=logging.StreamHandler, handler_kwargs=None, format='%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s', date_format='%H:%M:%S'): """ Set personal logger for this library. ...
Set personal logger for this library. :param logger_name: str, name of the logger :param level: int, see logging.{DEBUG,INFO,ERROR,...}: level of logger and handler :param handler_class: logging.Handler instance, default is StreamHandler (/dev/stderr) :param handler_kwargs: dict, keyword arguments to h...
def _add_instruction(self, instruction, value): """ :param instruction: instruction name to be added :param value: instruction value """ if (instruction == 'LABEL' or instruction == 'ENV') and len(value) == 2: new_line = instruction + ' ' + '='.join(map(quote, value))...
:param instruction: instruction name to be added :param value: instruction value
def json(self) -> dict: """Returns json compatible state of the Button instance. Returns: control_json: Json representation of Button state. """ content = {} content['name'] = self.name content['callback'] = self.callback self.control_json['content'] ...
Returns json compatible state of the Button instance. Returns: control_json: Json representation of Button state.
def filter_data(self, field, filter_value, filter_operator, field_converter=None): """Filter the data given the provided. Args: field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for compar...
Filter the data given the provided. Args: field (string): The field to filter on. filter_value (string | list): The value to match. filter_operator (string): The operator for comparison. field_converter (method): A method used to convert the field before comparis...
def _reload(self, force=False): """Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally. """ self._config_map = dict() self._r...
Reloads the configuration from the file and environment variables. Useful if using `os.environ` instead of this class' `set_env` method, or if the underlying configuration file is changed externally.
def parse_port_from_tensorboard_output(tensorboard_output: str) -> int: """ Parse tensorboard port from its outputted message. :param tensorboard_output: Output message of Tensorboard in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869 :return: Returns the port TensorBoard is listening on...
Parse tensorboard port from its outputted message. :param tensorboard_output: Output message of Tensorboard in format TensorBoard 1.8.0 at http://martin-VirtualBox:36869 :return: Returns the port TensorBoard is listening on. :raise UnexpectedOutputError
def validate(self): """ Cleans and validates the field values """ for name, field in self._fields.items(): v = getattr(self, name) if v is None and not self._values[name].explicit and field.has_default: v = field.get_default() val = fie...
Cleans and validates the field values
def get_alexa_rankings(self, domains): """Retrieves the most recent VT info for a set of domains. Args: domains: list of string domains. Returns: A dict with the domain as key and the VT report as value. """ api_name = 'alexa_rankings' (all_respo...
Retrieves the most recent VT info for a set of domains. Args: domains: list of string domains. Returns: A dict with the domain as key and the VT report as value.
def ll(self,*args,**kwargs): """ NAME: ll PURPOSE: return Galactic longitude INPUT: t - (optional) time at which to get ll obs=[X,Y,Z] - (optional) position of observer (in kpc) (default=Object-wide default) ...
NAME: ll PURPOSE: return Galactic longitude INPUT: t - (optional) time at which to get ll obs=[X,Y,Z] - (optional) position of observer (in kpc) (default=Object-wide default) OR Orbit object that corresponds t...
def erase_screen(self): """ Erase output screen. """ self.vt100_output.erase_screen() self.vt100_output.cursor_goto(0, 0) self.vt100_output.flush()
Erase output screen.
def _join(lst, key, sep=";"): """Auxiliary function to join same elements of a list of dictionaries if the elements are not None. """ return sep.join([d[key] for d in lst if d[key]])
Auxiliary function to join same elements of a list of dictionaries if the elements are not None.
def _read_audio_data(self, file_path): """ Read audio data from file. :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception """ try: self.log(u"Reading audio data...") # if we know the TTS outputs to PCM16 mono WAVE ...
Read audio data from file. :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
def _makeTags(tagStr, xml, suppress_LT=Suppress("<"), suppress_GT=Suppress(">")): """Internal helper to construct opening and closing tag expressions, given a tag name""" if isinstance(tagStr,basestring): resname = tagStr tagStr = Keyword(tagStr, caseless=not xml) ...
Internal helper to construct opening and closing tag expressions, given a tag name
def visit_Num(self, node: ast.Num) -> Union[int, float]: """Recompute the value as the number at the node.""" result = node.n self.recomputed_values[node] = result return result
Recompute the value as the number at the node.
def get_log_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the log lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogLookupSession) - a ``LogLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationF...
Gets the ``OsidSession`` associated with the log lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.logging.LogLookupSession) - a ``LogLookupSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to complete request raise: U...
async def fetch_emoji(self, emoji_id): """|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :clas...
|coro| Retrieves a custom :class:`Emoji` from the guild. .. note:: This method is an API call. For general usage, consider iterating over :attr:`emojis` instead. Parameters ------------- emoji_id: :class:`int` The emoji's ID. Raise...
def add_tweets(self, url, last_modified, tweets): """Adds new tweets to the cache.""" try: self.cache[url] = {"last_modified": last_modified, "tweets": tweets} self.mark_updated() return True except TypeError: return False
Adds new tweets to the cache.
def enableEditing(self, editable=True): """ Sets the DataFrameModel and columnDtypeModel's editable properties. :param editable: bool defaults to True, False disables most editing methods. :return: None """ self.editable = edita...
Sets the DataFrameModel and columnDtypeModel's editable properties. :param editable: bool defaults to True, False disables most editing methods. :return: None
def minimum_image(self): """Align the system according to the minimum image convention""" if self.box_vectors is None: raise ValueError('No periodic vectors defined') else: self.r_array = minimum_image(self.r_array, self.box_vectors.diagonal()) return sel...
Align the system according to the minimum image convention
def add_property(self, property_): """ Add a property to this thing. property_ -- property to add """ property_.set_href_prefix(self.href_prefix) self.properties[property_.name] = property_
Add a property to this thing. property_ -- property to add
def M200(self, Rs, rho0, c): """ M(R_200) calculation for NFW profile :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param c: concentration :type c: float [4,40] :return: M(R_...
M(R_200) calculation for NFW profile :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :param c: concentration :type c: float [4,40] :return: M(R_200) density
def python_like_mod_finder(import_line, alt_path=None, stop_token=None): """ Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module st...
Locate a module path based on an import line in an python-like file import_line is the line of source code containing the import alt_path specifies an alternate base path for the module stop_token specifies the desired name to stop on This is used to a find the path to python-like modules (...
def add_perf_task(task, auth, url): """ function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks ...
function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into JSON and issues a RESTFUL call to create the performance task. device. :param task: dictionary containing all required fields for performance tasks :param auth: requests auth object #usually ...
def get_subtree(self, name): # noqa: D302 r""" Get all node names in a sub-tree. :param name: Sub-tree root node name :type name: :ref:`NodeName` :rtype: list of :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeErro...
r""" Get all node names in a sub-tree. :param name: Sub-tree root node name :type name: :ref:`NodeName` :rtype: list of :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* not in tree) Using the sa...
def _unique(list_of_dicts): ''' Returns an unique list of dictionaries given a list that may contain duplicates. ''' unique_list = [] for ele in list_of_dicts: if ele not in unique_list: unique_list.append(ele) return unique_list
Returns an unique list of dictionaries given a list that may contain duplicates.
def generate_np(self, x_val, **kwargs): """ Generate adversarial examples and return them as a NumPy array. Sub-classes *should not* implement this method unless they must perform special handling of arguments. :param x_val: A NumPy array with the original inputs. :param **kwargs: optional para...
Generate adversarial examples and return them as a NumPy array. Sub-classes *should not* implement this method unless they must perform special handling of arguments. :param x_val: A NumPy array with the original inputs. :param **kwargs: optional parameters used by child classes. :return: A NumPy a...
def init_threads(tf_session): """ Starts threads running """ coord = tf.train.Coordinator() threads = list() for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS): threads.extend(qr.create_threads(tf_session, coord=coord, daemon=True, start=True)) return threads, co...
Starts threads running
def connect(self): """ Connect to a host on a given (SSL) port using PyOpenSSL. """ sock = socket.create_connection((self.host, self.port), self.timeout) if not USE_STDLIB_SSL: ssl_ctx = configure_pyopenssl_context(self.credentials) # attempt to upgrade t...
Connect to a host on a given (SSL) port using PyOpenSSL.
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) return self.tokenizer.decode([self.itos[index]...
Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``.
def execute(self, action): """Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be ex...
Execute the indicated action within the environment and return the resulting immediate reward dictated by the reward program. Usage: immediate_reward = scenario.execute(selected_action) Arguments: action: The action to be executed within the current situation. ...
def _save_upload_state_to_file(self): """if create and create_file has execute, save upload state to file for next resume upload if current upload process is interrupted. """ if os.access(self.file_dir, os.W_OK | os.R_OK | os.X_OK): save_file = self.file + '.upload' ...
if create and create_file has execute, save upload state to file for next resume upload if current upload process is interrupted.
def append_dict_key_value( in_dict, keys, value, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `k...
Ensures that in_dict contains the series of recursive keys defined in keys. Also appends `value` to the list that is at the end of `in_dict` traversed with `keys`. :param dict in_dict: The dictionary to work with :param str keys: The delimited string with one or more keys. :param any value: The val...
def norm(self, x): """Return the weighted norm of ``x``. Parameters ---------- x1 : `NumpyTensor` Tensor whose norm is calculated. Returns ------- norm : float The norm of the tensor. """ if self.exponent == 2.0: ...
Return the weighted norm of ``x``. Parameters ---------- x1 : `NumpyTensor` Tensor whose norm is calculated. Returns ------- norm : float The norm of the tensor.
def remove_phenotype(self, ind_obj, phenotypes=None): """Remove multiple phenotypes from an individual.""" if phenotypes is None: logger.info("delete all phenotypes related to %s", ind_obj.ind_id) self.query(PhenotypeTerm).filter_by(ind_id=ind_obj.id).delete() else: ...
Remove multiple phenotypes from an individual.
def _import_plugin(module_name, plugin_path, modnames, modlist): """Import the plugin `module_name` from `plugin_path`, add it to `modlist` and adds its name to `modnames`. """ if module_name in modnames: return try: # First add a mock module with the LOCALEPATH attribute so t...
Import the plugin `module_name` from `plugin_path`, add it to `modlist` and adds its name to `modnames`.
def generate_seeds(num, root_seed, secret): """ Deterministically generate list of seeds from a root seed. :param num: Numbers of seeds to generate as int :param root_seed: Seed to start off with. :return: seed values as a list of length num """ # Generate a starting see...
Deterministically generate list of seeds from a root seed. :param num: Numbers of seeds to generate as int :param root_seed: Seed to start off with. :return: seed values as a list of length num
def assert_operations(self, *args): """Assets if the requested operations are allowed in this context.""" if not set(args).issubset(self.allowed_operations): raise http.exceptions.Forbidden()
Assets if the requested operations are allowed in this context.
def start(self): """Start IOLoop in daemonized thread.""" assert self._thread is None, 'thread already started' # configure thread self._thread = Thread(target=self._start_io_loop) self._thread.daemon = True # begin thread and block until ready self._thread.star...
Start IOLoop in daemonized thread.
def _create_header(info, format, encoding, errors): """Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. """ parts = [ stn(info.get("name", ""), 100, encoding, errors), itn(info.get("mode", 0) & 0o7...
Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants.
def _render(self, request, template=None, status=200, context={}, headers={}, prefix_template_path=True): """ Render a HTTP response. :param request: A django.http.HttpRequest instance. :param template: A string describing the path to a template. :param status: An integer descri...
Render a HTTP response. :param request: A django.http.HttpRequest instance. :param template: A string describing the path to a template. :param status: An integer describing the HTTP status code to respond with. :param context: A dictionary describing variables to populate the template ...
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :clas...
Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `new_n...
def get_idx_by_name(self, name): # type: (str) -> Optional[int] """ get_idx_by_name returns the index of a matching registered header This implementation will prefer returning a static entry index whenever possible. If multiple matching header name are found in the static table,...
get_idx_by_name returns the index of a matching registered header This implementation will prefer returning a static entry index whenever possible. If multiple matching header name are found in the static table, there is insurance that the first entry (lowest index number) will be retur...
def get_hub(): """Return the instance of the hub.""" try: hub = _local.hub except AttributeError: # The Hub can only be instantiated from the root fiber. No other fibers # can run until the Hub is there, so the root will always be the first # one to call get_hub(). as...
Return the instance of the hub.
def check_title_match(expected_title, pa11y_results, logger): """ Check if Scrapy reports any issue with the HTML <title> element. If so, compare that <title> element to the title that we got in the A11yItem. If they don't match, something is screwy, and pa11y isn't parsing the page that we expect. ...
Check if Scrapy reports any issue with the HTML <title> element. If so, compare that <title> element to the title that we got in the A11yItem. If they don't match, something is screwy, and pa11y isn't parsing the page that we expect.
def get_pids_in_revision_chain(client, did): """Args: client: d1_client.cnclient.CoordinatingNodeClient or d1_client.mnclient.MemberNodeClient. did : str SID or a PID of any object in a revision chain. Returns: list of str: All PIDs in the chain. The returned list is in the sam...
Args: client: d1_client.cnclient.CoordinatingNodeClient or d1_client.mnclient.MemberNodeClient. did : str SID or a PID of any object in a revision chain. Returns: list of str: All PIDs in the chain. The returned list is in the same order as the chain. The initial PID is typ...
def GetEntries(self, parser_mediator, top_level=None, **unused_kwargs): """Extracts relevant install history entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. top_level (dict[str, object]): plist top-lev...
Extracts relevant install history entries. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. top_level (dict[str, object]): plist top-level key.
def get_wake_on_modem(): ''' Displays whether 'wake on modem' is on or off if supported :return: A string value representing the "wake on modem" settings :rtype: str CLI Example: .. code-block:: bash salt '*' power.get_wake_on_modem ''' ret = salt.utils.mac_utils.execute_retu...
Displays whether 'wake on modem' is on or off if supported :return: A string value representing the "wake on modem" settings :rtype: str CLI Example: .. code-block:: bash salt '*' power.get_wake_on_modem
def show_csrs(): ''' Show certificate requests for this API key CLI Example: .. code-block:: bash salt-run digicert.show_csrs ''' data = salt.utils.http.query( '{0}/certificaterequests'.format(_base_url()), status=True, decode=True, decode_type='json', ...
Show certificate requests for this API key CLI Example: .. code-block:: bash salt-run digicert.show_csrs
def check_instance(function): """ Wrapper that tests the type of _session. Purpose: This decorator function is used by all functions within | the Jaide class that interact with a device to ensure the | proper session type is in use. If it is not, it will | atte...
Wrapper that tests the type of _session. Purpose: This decorator function is used by all functions within | the Jaide class that interact with a device to ensure the | proper session type is in use. If it is not, it will | attempt to migrate _session to that type befor...
def _append_callback_id(ids, obj, callback_id): ''' Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _r...
Helper function adding a callback ID to the IDs dict. The callback ids dict maps an object to event callback ids. :param ids: dict of callback IDs to update :param obj: one of the keys of REGISTER_FUNCTIONS :param callback_id: the result of _register_callback
def requires_submit(func): """ Decorator to ensure that a submit has been performed before calling the method. Args: func (callable): test function to be decorated. Returns: callable: the decorated function. """ @functools.wraps(func) def _wrapper(self, *args, **kwargs)...
Decorator to ensure that a submit has been performed before calling the method. Args: func (callable): test function to be decorated. Returns: callable: the decorated function.
def make_polynomial(degree=3, n_samples=100, bias=0.0, noise=0.0, return_coefs=False, random_state=None): """ Generate a noisy polynomial for a regression problem Examples -------- >>> X, y, coefs = make_polynomial(degree=3, n_samples=200, noise=.5, ... ...
Generate a noisy polynomial for a regression problem Examples -------- >>> X, y, coefs = make_polynomial(degree=3, n_samples=200, noise=.5, ... return_coefs=True, random_state=1)
def add_method_model(self, func, # type: Callable name=None, # type: Optional[str] description=None, # type: Optional[str] owner=None, # type: object ): # type: (...) -> MethodModel ...
Register a function to be added to the block
def _filter_vcf(out_file): """Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference. """ in_file = out_file.replace(".vcf", "-ori.vcf") FILTER_line = ('##FILTER=<ID=SBIAS,Description="Due to bias">\n' '##FILTER=<ID=5BP,Description="Due to 5BP">\n' ...
Fix sample names, FILTER and FORMAT fields. Remove lines with ambiguous reference.
def check_parameter_similarity(files_dict): """ Checks if the parameter names of all files are similar. Takes the dictionary from get_parameter_from_files output as input. """ try: parameter_names = files_dict.itervalues().next().keys() # get the parameter names of the first file, to check if ...
Checks if the parameter names of all files are similar. Takes the dictionary from get_parameter_from_files output as input.
def get_sitetree(self, alias): """Gets site tree items from the given site tree. Caches result to dictionary. Returns (tree alias, tree items) tuple. :param str|unicode alias: :rtype: tuple """ cache_ = self.cache get_cache_entry = cache_.get_entry ...
Gets site tree items from the given site tree. Caches result to dictionary. Returns (tree alias, tree items) tuple. :param str|unicode alias: :rtype: tuple
def isExpandKeyEvent(self, keyEvent): """Check if key event should expand rectangular selection""" return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, ...
Check if key event should expand rectangular selection
def imshow(x, y, z, ax, **kwargs): """ Image plot of 2d DataArray using matplotlib.pyplot Wraps :func:`matplotlib:matplotlib.pyplot.imshow` While other plot methods require the DataArray to be strictly two-dimensional, ``imshow`` also accepts a 3D array where some dimension can be interpreted ...
Image plot of 2d DataArray using matplotlib.pyplot Wraps :func:`matplotlib:matplotlib.pyplot.imshow` While other plot methods require the DataArray to be strictly two-dimensional, ``imshow`` also accepts a 3D array where some dimension can be interpreted as RGB or RGBA color channels and allows th...