code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
def register_pretty(type=None, predicate=None): if type is None and predicate is None: raise ValueError( "You must provide either the or argument." ) if type is not None and predicate is not None: raise ValueError( "You must provide either the or argume...
Returns a decorator that registers the decorated function as the pretty printer for instances of ``type``. :param type: the type to register the pretty printer for, or a ``str`` to indicate the module and name, e.g.: ``'collections.Counter'``. :param predicate: a predicate function that ta...
def update_ipsec_site_connection(self, ipsecsite_conn, body=None): return self.put( self.ipsec_site_connection_path % (ipsecsite_conn), body=body )
Updates an IPsecSiteConnection.
def dictlist_convert_to_float(dict_list: Iterable[Dict], key: str) -> None: for d in dict_list: try: d[key] = float(d[key]) except ValueError: d[key] = None
Process an iterable of dictionaries. For each dictionary ``d``, convert (in place) ``d[key]`` to a float. If that fails, convert it to ``None``.
def PlayWaveFile(filePath: str = r, isAsync: bool = False, isLoop: bool = False) -> bool: if filePath: SND_ASYNC = 0x0001 SND_NODEFAULT = 0x0002 SND_LOOP = 0x0008 SND_FILENAME = 0x20000 flags = SND_NODEFAULT | SND_FILENAME if isAsync: flags |= SND_ASY...
Call PlaySound from Win32. filePath: str, if emtpy, stop playing the current sound. isAsync: bool, if True, the sound is played asynchronously and returns immediately. isLoop: bool, if True, the sound plays repeatedly until PlayWaveFile(None) is called again, must also set isAsync to True. Return bool, ...
def get_config(self): path = res = self._make_ocs_request( , , path ) if res.status_code == 200: tree = ET.fromstring(res.content) self._check_ocs_status(tree) values = [] element = tree.find()...
Returns ownCloud config information :returns: array of tuples (key, value) for each information e.g. [('version', '1.7'), ('website', 'ownCloud'), ('host', 'cloud.example.com'), ('contact', ''), ('ssl', 'false')] :raises: HTTPResponseError in case an HTTP error status was returne...
def _geom_type(self, source): if isinstance(source, AbstractLayer): query = source.orig_query else: query = .format(table=source) resp = self.sql_client.send( utils.minify_sql(( , , ST_Point\ST_MultiPoin...
gets geometry type(s) of specified layer
def _check_1st_line(line, **kwargs): components = kwargs.get("components", ()) max_first_line = kwargs.get("max_first_line", 50) errors = [] lineno = 1 if len(line) > max_first_line: errors.append(("M190", lineno, max_first_line, len(line))) if line.endswith("."): errors.a...
First line check. Check that the first line has a known component name followed by a colon and then a short description of the commit. :param line: first line :type line: str :param components: list of known component names :type line: list :param max_first_line: maximum length of the firs...
def describe(path): if os.path.islink(path): return elif os.path.isdir(path): if path == : return elif path == : return else: if os.path.basename(path) == : return " directory" elif os.path.basename(path) == ...
Return a textual description of the file pointed by this path. Options: - "symbolic link" - "directory" - "'.' directory" - "'..' directory" - "regular file" - "regular empty file" - "non existent" - "entry"
def get_pp_name(self): ppnames = [] natomtypes = int(self._get_line(, self.outputf).split()[5]) with open(self.outputf) as fp: for line in fp: if "PseudoPot. ppnames.append(Scalar(value=next(fp).split()[-1].rstrip())) ...
Determine the pseudopotential names from the output
def _ParseCmdItem(self, cmd_input, template_file=None): fsm = textfsm.TextFSM(template_file) if not self._keys: self._keys = set(fsm.GetValuesByAttrib()) table = texttable.TextTable() table.header = fsm.header for record in fsm.ParseText(cmd_input): table.Append(rec...
Creates Texttable with output of command. Args: cmd_input: String, Device response. template_file: File object, template to parse with. Returns: TextTable containing command output. Raises: CliTableError: A template was not found for the given command.
def tag(value): rdict = load_feedback() tests = rdict.setdefault("tests", {}) tests["*auto-tag-" + str(hash(str(value)))] = str(value) save_feedback(rdict)
Add a tag with generated id. :param value: everything working with the str() function
def check_state(self, pair, state): self.__log_info(, pair, pair.state, state) pair.state = state
Updates the state of a check.
def get_existing_thumbnail(self, thumbnail_options, high_resolution=False): thumbnail_options = self.get_options(thumbnail_options) names = [ self.get_thumbnail_name( thumbnail_options, transparent=False, high_resolution=high_resolution)] tran...
Return a ``ThumbnailFile`` containing an existing thumbnail for a set of thumbnail options, or ``None`` if not found.
def launch_background_job(self, job, on_error=None, on_success=None): if not self.main.mode_online: self.sortie_erreur_GUI( "Local mode activated. Can't run background task !") self.reset() return on_error = on_error or self.sortie_erreur_GUI...
Launch the callable job in background thread. Succes or failure are controlled by on_error and on_success
def clear_trace_filter_cache(): global should_trace_hook try: old_hook = should_trace_hook should_trace_hook = None linecache.clearcache() _filename_to_ignored_lines.clear() finally: should_trace_hook = old_hook
Clear the trace filter cache. Call this after reloading.
def remove_all(self, key): check_not_none(key, "key can't be none") return self._encode_invoke(transactional_multi_map_remove_codec, key=self._to_data(key))
Transactional implementation of :func:`MultiMap.remove_all(key) <hazelcast.proxy.multi_map.MultiMap.remove_all>` :param key: (object), the key of the entries to remove. :return: (list), the collection of the values associated with the key.
def pretty_print_counters(counters): totals = collections.defaultdict(int) for (name, val) in counters: prefixes = [name[:i] for i in xrange(len(name)) if name[i] == "/"] + [name] for p in prefixes: totals[p] += val parts = [] for name, val in sorted(six.iteritems(totals)): parts.append(" "...
print counters hierarchically. Each counter is a pair of a string and a number. The string can have slashes, meaning that the number also counts towards each prefix. e.g. "parameters/trainable" counts towards both "parameters" and "parameters/trainable". Args: counters: a list of (string, number) pair...
def fetch_reference_restriction(self, ): inter = self.get_refobjinter() restricted = self.status() is not None return restricted or inter.fetch_action_restriction(self, )
Fetch whether referencing is restricted :returns: True, if referencing is restricted :rtype: :class:`bool` :raises: None
def whoami(self, note=None, loglevel=logging.DEBUG): shutit = self.shutit shutit.handle_note(note) res = self.send_and_get_output(, echo=False, loglevel=loglevel).strip() if res == : res = self.send_and_get_output(, ...
Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string
def _filesystems(config=, leading_key=True): name/dirdev/dev/hd8name/dirname/dirdev/dev/hd8 ret = OrderedDict() lines = [] parsing_block = False if not os.path.isfile(config) or not in __grains__[]: return ret with salt.utils.files.fopen(config) as ifile: for line in ifile...
Return the contents of the filesystems in an OrderedDict config File containing filesystem infomation leading_key True return dictionary keyed by 'name' and value as dictionary with other keys, values (name excluded) OrderedDict({ '/dir' : OrderedDict({'dev': '/dev/hd8', ......
async def callproc(self, procname, args=()): conn = self._get_db() if self._echo: logger.info("CALL %s", procname) logger.info("%r", args) for index, arg in enumerate(args): q = "SET @_%s_%d=%s" % (procname, index, conn.escape(arg)) await...
Execute stored procedure procname with args Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are only available by storing them in a server variable and then retrieved by a query. Since stored procedures...
def indent(self, levels, first_line=None): self._indentation_levels.append(levels) self._indent_first_line.append(first_line)
Increase indentation by ``levels`` levels.
def update(self, level): sl = level + 1 stack = inspect.stack() try: self._get_vars(stack[:sl], scopes=[]) finally: del stack[:], stack
Update the current scope by going back `level` levels. Parameters ---------- level : int or None, optional, default None
def enable_qt4(self, app=None): from IPython.lib.inputhookqt4 import create_inputhook_qt4 app, inputhook_qt4 = create_inputhook_qt4(self, app) self.set_inputhook(inputhook_qt4) self._current_gui = GUI_QT4 app._in_event_loop = True self._apps[GUI_QT4] = app ...
Enable event loop integration with PyQt4. Parameters ---------- app : Qt Application, optional. Running application to use. If not given, we probe Qt for an existing application object, and create a new one if none is found. Notes ----- ...
def links_to(self, other, tpe): if self.check_type(tpe): self.links.append([other, tpe]) else: raise Exception()
adds a link from this thing to other thing using type (is_a, has_a, uses, contains, part_of)
def catch_gzip_errors(f): def new_f(self, *args, **kwargs): try: return f(self, *args, **kwargs) except requests.exceptions.ContentDecodingError as e: log.warning("caught gzip error: %s", e) self.connect() return f(self, *args, **kwargs) retur...
A decorator to handle gzip encoding errors which have been known to happen during hydration.
def yVal_xml(self): return self._yVal_tmpl.format(**{ : , : self.numRef_xml( self._series.y_values_ref, self._series.number_format, self._series.y_values ), })
Return the ``<c:yVal>`` element for this series as unicode text. This element contains the Y values for this series.
def get_user_matches(session, user_id, from_timestamp=None, limit=None): return get_recent_matches(session, .format( session.auth.base_url, PROFILE_URL, user_id, user_id), from_timestamp, limit)
Get recent matches by user.
def throw_to(self, target, *a): self.ready.append((getcurrent(), ())) return target.throw(*a)
if len(a) == 1 and isinstance(a[0], preserve_exception): return target.throw(a[0].typ, a[0].val, a[0].tb)
def bat_to_sh(file_path): sh_file = file_path[:-4] + with open(file_path, ) as inf, open(sh_file, ) as outf: outf.write() for line in inf: if line.strip(): continue else: break for line in inf: if lin...
Convert honeybee .bat file to .sh file. WARNING: This is a very simple function and doesn't handle any edge cases.
def operations(nsteps): return {: 1 + nsteps, : 2 + nsteps, : 2 + nsteps, : 1 + nsteps, : 2 + nsteps + nsteps*(nsteps+1)/2, : 4 + 2*nsteps + nsteps*(nsteps+1)/2 }
Returns the number of operations needed for nsteps of GMRES
def _run_select_solution(ploidy_outdirs, work_dir, data): out_file = os.path.join(work_dir, "optimalClusters.txt") if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: ploidy_inputs = " ".join(["--ploidyRun%s=%s" % (p, d) for p, d in ploidy_outdirs])...
Select optimal
def getFileAndName(self, *args, **kwargs): pgctnt, hName, mime = self.getFileNameMime(*args, **kwargs) return pgctnt, hName
Give a requested page (note: the arguments for this call are forwarded to getpage()), return the content at the target URL and the filename for the target content as a 2-tuple (pgctnt, hName) for the content at the target URL. The filename specified in the content-disposition header is used, if present. Otherwis...
def open_recruitment(self, n=1): logger.info("Multi recruitment running for {} participants".format(n)) recruitments = [] messages = {} remaining = n for recruiter, count in self.recruiters(n): if not count: break if recruiter.nick...
Return initial experiment URL list.
def muc(clusters, mention_to_gold): true_p, all_p = 0, 0 for cluster in clusters: all_p += len(cluster) - 1 true_p += len(cluster) linked = set() for mention in cluster: if mention in mention_to_gold: linked.add...
Counts the mentions in each predicted cluster which need to be re-allocated in order for each predicted cluster to be contained by the respective gold cluster. <http://aclweb.org/anthology/M/M95/M95-1005.pdf>
def select_window(pymux, variables): window_id = variables[] def invalid_window(): raise CommandException( % window_id) if window_id.startswith(): try: number = int(window_id[1:]) except ValueError: invalid_window() else: w = pymux.a...
Select a window. E.g: select-window -t :3
def rolling(self, *args, **kwargs): from pandas.core.window import RollingGroupby return RollingGroupby(self, *args, **kwargs)
Return a rolling grouper, providing rolling functionality per group.
def get_search_results(portal_type=None, uid=None, **kw): if uid is not None: logger.info("UID found, returning the object immediately" % uid) return u.to_list(get_object_by_uid(uid)) include_portal = False if u.to_string(portal_type) == "Plone Site": include_portal...
Search the catalog and return the results :returns: Catalog search results :rtype: iterable
def record_results(self, results): repository = Repo(self.__repository_directory, search_parent_directories=True) for tag in repository.tags: if tag.name == self.__tag_name: tag_object = tag break else: raise Exception("Experiment ...
Record the results of this experiment, by updating the tag. :param results: A dictionary containing the results of the experiment. :type results: dict
def get_datatype_str(self, element, length): spaces = *(self.get_width(element) - length) type_info = element.get() ret = if type_info == or type_info == : ret = spaces + .format(type_info) elif element.get() is not None: ret = spaces + element...
get_datatype_str High-level api: Produce a string that indicates the data type of a node. Parameters ---------- element : `Element` A node in model tree. length : `int` String length that has been consumed. Returns ------- str...
def EnableNetworkInterfaces( self, interfaces, logger, dhclient_script=None): interfaces_to_up = [i for i in interfaces if i != ] if interfaces_to_up: logger.info(, interfaces_to_up) self._WriteIfcfg(interfaces_to_up, logger) self._Ifup(interfaces_to_up, logger)
Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient.
def fileopenbox(msg=None, title=None, default=, filetypes=None, multiple=False): localRoot = Tk() localRoot.withdraw() initialbase, initialfile, initialdir, filetypes = fileboxSetup( default, filetypes) if (initialfile.find("*") < 0) and (initialfile.find("?") < 0...
A dialog to get a file name. **About the "default" argument** The "default" argument specifies a filepath that (normally) contains one or more wildcards. fileopenbox will display only files that match the default filepath. If omitted, defaults to "\*" (all files in the current directory). WIN...
def setCovariance(self, cov): assert cov.shape[0]==self.dim, S, U = la.eigh(cov) U = U[:,::-1] S = S[::-1] _X = U[:, :self.rank] * sp.sqrt(S[:self.rank]) self.X = _X
makes lowrank approximation of cov
def channel(layer, n_channel, batch=None): if batch is None: return lambda T: tf.reduce_mean(T(layer)[..., n_channel]) else: return lambda T: tf.reduce_mean(T(layer)[batch, ..., n_channel])
Visualize a single channel
def adjust_for_length(self, key, r, kwargs): length = len(str(kwargs)) if length > settings.defaults["max_detail_length"]: self._log_length_error(key, length) r["max_detail_length_error"] = length return r return kwargs
Converts the response to a string and compares its length to a max length specified in settings. If the response is too long, an error is logged, and an abbreviated response is returned instead.
def _convertPointsToSegments(points, willBeReversed=False): previousOnCurve = None for point in reversed(points): if point.segmentType is not None: previousOnCurve = point.coordinates break assert previousOnCurve is not None offCurves = [] segments = []...
Compile points into InputSegment objects.
def OnApprove(self, event): if not self.main_window.safe_mode: return msg = _(u"You are going to approve and trust a file that\n" u"you have not created yourself.\n" u"After proceeding, the file is executed.\n \n" u"It may harm your ...
File approve event handler
def merge_overlaps(self, data_reducer=None, data_initializer=None, strict=True): if not self: return sorted_intervals = sorted(self.all_intervals) merged = [] current_reduced = [None] higher = None def new_series(): if data_...
Finds all intervals with overlapping ranges and merges them into a single interval. If provided, uses data_reducer and data_initializer with similar semantics to Python's built-in reduce(reducer_func[, initializer]), as follows: If data_reducer is set to a function, combines the data ...
def regex_lexer(regex_pat): if isinstance(regex_pat, str): regex_pat = re.compile(regex_pat) def f(inp_str, pos): m = regex_pat.match(inp_str, pos) return m.group() if m else None elif hasattr(regex_pat, ): def f(inp_str, pos): m = regex_pat.mat...
generate token names' cache
def entity_list(args): r = fapi.get_entities_with_type(args.project, args.workspace) fapi._check_response_code(r, 200) return [ .format(e[], e[]) for e in r.json() ]
List entities in a workspace.
def listdir(search_base, followlinks=False, filter=, relpath=False, bestprefix=False, system=NIST): for root, dirs, files in os.walk(search_base, followlinks=followlinks): for name in fnmatch.filter(files, filter): _path = os.path.join(root, name) if relpath: ...
This is a generator which recurses the directory tree `search_base`, yielding 2-tuples of: * The absolute/relative path to a discovered file * A bitmath instance representing the "apparent size" of the file. - `search_base` - The directory to begin walking down. - `followlinks` - Whether or not to follow symb...
def size(self): size = {} if self._w3c: size = self._execute(Command.GET_ELEMENT_RECT)[] else: size = self._execute(Command.GET_ELEMENT_SIZE)[] new_size = {"height": size["height"], "width": size["width"]} return new_size
The size of the element.
def combine_first(self, other): if isinstance(other, SparseSeries): other = other.to_dense() dense_combined = self.to_dense().combine_first(other) return dense_combined.to_sparse(fill_value=self.fill_value)
Combine Series values, choosing the calling Series's values first. Result index will be the union of the two indexes Parameters ---------- other : Series Returns ------- y : Series
def decrypt(self, text, appid): try: cryptor = AES.new(self.key, self.mode, self.key[:16]) plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception as e: raise DecryptAESError(e) try: if six.PY2: ...
对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文
def _rpartition(entity, sep): idx = entity.rfind(sep) if idx == -1: return , , entity return entity[:idx], sep, entity[idx + 1:]
Python2.4 doesn't have an rpartition method so we provide our own that mimics str.rpartition from later releases. Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is no...
def get_int(errmsg, arg, default=1, cmdname=None): if arg: try: default = int(eval(arg)) except (SyntaxError, NameError, ValueError): if cmdname: errmsg("Command expects an integer; got: %s." % (cmdname, s...
If arg is an int, use that otherwise take default.
def parse_date(dt, ignoretz=True, as_tz=None): dttm = parse_datetime(dt, ignoretz=ignoretz) return None if dttm is None else dttm.date()
:param dt: string datetime to convert into datetime object. :return: date object if the string can be parsed into a date. Otherwise, return None. :see: http://labix.org/python-dateutil Examples: >>> parse_date('2011-12-30') datetime.date(2011, 12, 30) >>> parse_date('12/30/2011') ...
def delete_user_avatar(self, username, avatar): params = {: username} url = self._get_url( + avatar) return self._session.delete(url, params=params)
Delete a user's avatar. :param username: the user to delete the avatar from :param avatar: ID of the avatar to remove
def dbus_readBytesFD(self, fd, byte_count): f = os.fdopen(fd, ) result = f.read(byte_count) f.close() return bytearray(result)
Reads byte_count bytes from fd and returns them.
def peek(self, n=None, constructor=list): return self.copy().take(n=n, constructor=constructor)
Sees/peeks the next few items in the Stream, without removing them. Besides that this functions keeps the Stream items, it's the same to the ``Stream.take()`` method. See Also -------- Stream.take : Returns the n first elements from the Stream, removing them. Note ---- When appl...
def solve(self, graph, timeout, debug=False, anim=None): savings_list = self.compute_savings_list(graph) solution = SavingsSolution(graph) start = time.time() for i, j in savings_list[:]: if solution.is_complete(): break if solution.c...
Solves the CVRP problem using Clarke and Wright Savings methods Parameters ---------- graph: :networkx:`NetworkX Graph Obj< >` A NetworkX graaph is used. timeout: int max processing time in seconds debug: bool, defaults to False If True, infor...
def replaceWith(self, *nodes: Union[AbstractNode, str]) -> None: if self.parentNode: node = _to_node_list(nodes) self.parentNode.replaceChild(node, self)
Replace this node with nodes. If nodes contains ``str``, it will be converted to Text node.
def _set_alignment(self, group_size, bit_offset=0, auto_align=False): field_offset = int(bit_offset) if auto_align: field_size, bit_offset = divmod(field_offset, 8) if bit_offset is not 0: field_size += 1 field_...
Sets the alignment of the ``Decimal`` field. :param int group_size: size of the aligned `Field` group in bytes, can be between ``1`` and ``8``. :param int bit_offset: bit offset of the `Decimal` field within the aligned `Field` group, can be between ``0`` and ``63``. :pa...
def _inferSchema(self, rdd, samplingRatio=None, names=None): first = rdd.first() if not first: raise ValueError("The first row in RDD is empty, " "can not infer schema") if type(first) is dict: warnings.warn("Using RDD of dict to infe...
Infer schema from an RDD of Row or tuple. :param rdd: an RDD of Row or tuple :param samplingRatio: sampling ratio, or no sampling (default) :return: :class:`pyspark.sql.types.StructType`
def analyse_cache_dir(self, jobhandler=None, batchsize=1, **kwargs): if jobhandler is None: jobhandler = SequentialJobHandler() files = glob.glob(os.path.join(self.cache_dir, )) records = [] outfiles = [] dna = self.collection[0].is_dna() fo...
Scan the cache directory and launch analysis for all unscored alignments using associated task handler. KWargs are passed to the tree calculating task managed by the TaskInterface in self.task_interface. Example kwargs: TreeCollectionTaskInterface: scale=1, guide_tree=None, ...
def loads(data, validate=False, **kwargs): d = json.loads(data, **kwargs) content_spec = d["content-spec"] Payload = CONTENT_SPECS[content_spec] payload = Payload.load(d) if validate: errors = payload.problems() if errors: raise ValidationError(errors) return pay...
Load a PPMP message from the JSON-formatted string in `data`. When `validate` is set, raise `ValidationError`. Additional keyword arguments are the same that are accepted by `json.loads`, e.g. `indent` to get a pretty output.
def confirm(self, question, default=False, true_answer_regex="(?i)^y"): return self._io.confirm(question, default, true_answer_regex)
Confirm a question with the user.
def set_euid(): current = os.geteuid() logger.debug("Current EUID is %s" % current) if settings.DROPLET_USER is None: logger.info("Not changing EUID, DROPLET_USER is None") return uid = int(pwd.getpwnam(settings.DROPLET_USER).pw_uid) if current != uid: try: ...
Set settings.DROPLET_USER effective UID for the current process This adds some security, but nothing magic, an attacker can still gain root access, but at least we only elevate privileges when needed See root context manager
def _instance_callable(obj): if not isinstance(obj, ClassTypes): return getattr(obj, , None) is not None klass = obj if klass.__dict__.get() is not None: return True for base in klass.__bases__: if _instance_callable(base): return True return ...
Given an object, return True if the object is callable. For classes, return True if instances would be callable.
def read_version(version_file): "Read the `(version-string, version-info)` from `version_file`." vars = {} with open(version_file) as f: exec(f.read(), {}, vars) return (vars[], vars[])
Read the `(version-string, version-info)` from `version_file`.
def set_state_data(cls, entity, data): attr_names = get_domain_class_attribute_names(type(entity)) nested_items = [] for attr, new_attr_value in iteritems_(data): if not attr.entity_attr in attr_names: raise ValueError( % (at...
Sets the state data for the given entity to the given data. This also works for unmanaged entities.
def check_classes(self, scope=-1): for entry in self[scope].values(): if entry.class_ is None: syntax_error(entry.lineno, "Unknown identifier " % entry.name)
Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked.
async def get_participant(self, p_id: int, force_update=False) -> Participant: found_p = self._find_participant(p_id) if force_update or found_p is None: await self.get_participants() found_p = self._find_participant(p_id) return found_p
get a participant by its id |methcoro| Args: p_id: participant id force_update (dfault=False): True to force an update to the Challonge API Returns: Participant: None if not found Raises: APIException
def import_object(object_name): package, name = object_name.rsplit(, 1) return getattr(importlib.import_module(package), name)
Import an object from its Fully Qualified Name.
def capture_reset_password_requests(reset_password_sent_at=None): reset_requests = [] def _on(app, **data): reset_requests.append(data) reset_password_instructions_sent.connect(_on) try: yield reset_requests finally: reset_password_instructions_sent.disconnect(_on)
Testing utility for capturing password reset requests. :param reset_password_sent_at: An optional datetime object to set the user's `reset_password_sent_at` to
def _send_start_ok(self, frame_in): mechanisms = try_utf8_decode(frame_in.mechanisms) if in mechanisms: mechanism = credentials = elif in mechanisms: mechanism = credentials = self._plain_credentials() else: except...
Send Start OK frame. :param specification.Connection.Start frame_in: Amqp frame. :return:
def valid_return_codes(self, *codes): previous_codes = self._valid_return_codes self._valid_return_codes = codes yield self._valid_return_codes = previous_codes
Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log')
def matches(self, tokenJson): s analysis of a single word token; ' if self.otherRules != None: otherMatches = [] for field in self.otherRules: match = field in tokenJson and ((self.otherRules[field]).match(tokenJson[field]) != None) ...
Determines whether given token (tokenJson) satisfies all the rules listed in the WordTemplate. If the rules describe tokenJson[ANALYSIS], it is required that at least one item in the list tokenJson[ANALYSIS] satisfies all the rules (but it is not required that all the items should...
def is_conditional(self, include_loop=True): if self.contains_if(include_loop) or self.contains_require_or_assert(): return True if self.irs: last_ir = self.irs[-1] if last_ir: if isinstance(last_ir, Return): for r in last_...
Check if the node is a conditional node A conditional node is either a IF or a require/assert or a RETURN bool Returns: bool: True if the node is a conditional node
def search(self, query, category=None, orientation=None, page=1, per_page=10): if orientation and orientation not in self.orientation_values: raise Exception() params = { "query": query, "category": category, "orientation": orientation, ...
Get a single page from a photo search. Optionally limit your search to a set of categories by supplying the category ID’s. Note: If supplying multiple category ID’s, the resulting photos will be those that match all of the given categories, not ones that match any category. :pa...
def set(self, key, val, timeout=None, using=None): if timeout is None: timeout = self.timeout if self.is_managed(using=using) and self._patched_var: self.local[key] = val else: self.cache_backend.set(key, val, timeout)
Set will be using the generational key, so if another thread bumps this key, the localstore version will still be invalid. If the key is bumped during a transaction it will be new to the global cache on commit, so it will still be a bump.
def user_saw_task(self, username, courseid, taskid): self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid}, {"$setOnInsert": {"username": username, "courseid": courseid, "taskid": taskid, ...
Set in the database that the user has viewed this task
def client_list_entries_multi_project( client, to_delete ): PROJECT_IDS = ["one-project", "another-project"] for entry in client.list_entries(project_ids=PROJECT_IDS): do_something_with(entry)
List entries via client across multiple projects.
def is_oriented(self): if util.is_shape(self.primitive.transform, (4, 4)): return not np.allclose(self.primitive.transform[ 0:3, 0:3], np.eye(3)) else: return False
Returns whether or not the current box is rotated at all.
def import_(self, data): return self.__import(json.loads(data, **self.kwargs))
Read JSON from `data`.
def expand(self, local_search=False): new_nodes = [] for action in self.problem.actions(self.state): new_state = self.problem.result(self.state, action) cost = self.problem.cost(self.state, action, ...
Create successors.
def dump(self): scan_lines = bytearray() for y in range(self.height): scan_lines.append(0) scan_lines.extend( self.canvas[(y * self.width * 4):((y + 1) * self.width * 4)] ) return SIGNATURE + \ self.pack_chunk(b,...
Dump the image data
def list_descriptors(self): paths = self._props.Get(_CHARACTERISTIC_INTERFACE, ) return map(BluezGattDescriptor, get_provider()._get_objects_by_path(paths))
Return list of GATT descriptors that have been discovered for this characteristic.
def get_apps_api(): global apps_api if apps_api is None: config.load_kube_config() if API_KEY is not None: configuration = client.Configuration() configuration.api_key[] = API_KEY configuration.api_key_prefix[] = apps_api = clie...
Create instance of Apps V1 API of kubernetes: https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/AppsV1Api.md :return: instance of client
def interpolate_sysenv(line, defaults={}): map = ChainMap(os.environ, defaults) return line.format(**map)
Format line system environment variables + defaults
def container_query(self, query, quiet=False): results = self._list_containers() matches = [] for result in results: for key,val in result.metadata.items(): if query in val and result not in matches: matches.append(result) if not quiet: bot.info("[gs://...
search for a specific container. This function would likely be similar to the above, but have different filter criteria from the user (based on the query)
def notify_created(room, event, user): tpl = get_plugin_template_module(, chatroom=room, event=event, user=user) _send(event, tpl)
Notifies about the creation of a chatroom. :param room: the chatroom :param event: the event :param user: the user performing the action
def chains(xs, labels=None, truths=None, truth_color=u" alpha=0.5, fig=None): n_walkers, n_steps, K = xs.shape if labels is not None: assert len(labels) == K if truths is not None: assert len(truths) == K factor = 2.0 lbdim = 0.5 * factor trdim = 0.2 * factor whs...
Create a plot showing the walker values for each parameter at every step. :param xs: The samples. This should be a 3D :class:`numpy.ndarray` of size (``n_walkers``, ``n_steps``, ``n_parameters``). :type xs: :class:`numpy.ndarray` :param labels: [optional] Labels for all t...
def read_code(self, address, size=1): assert address < len(self.bytecode) value = self.bytecode[address:address + size] if len(value) < size: value += * (size - len(value)) return value
Read size byte from bytecode. If less than size bytes are available result will be pad with \x00
def pad(text, bits=32): return text + (bits - len(text) % bits) * chr(bits - len(text) % bits)
Pads the inputted text to ensure it fits the proper block length for encryption. :param text | <str> bits | <int> :return <str>
def tree(string, token=[WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA]): return Text(string, token)
Transforms the output of parse() into a Text object. The token parameter lists the order of tags in each token in the input string.
def url_to_tile(url): info = url.strip().split() name = .join(info[-7: -4]) date = .join(info[-4: -1]) return name, date, int(info[-1])
Extracts tile name, date and AWS index from tile url on AWS. :param url: class input parameter 'metafiles' :type url: str :return: Name of tile, date and AWS index which uniquely identifies tile on AWS :rtype: (str, str, int)
def split_unescaped(char, string, include_empty_strings=False): \\ words = [] pos = len(string) lastpos = pos while pos >= 0: pos = get_last_pos_of_char(char, string[:lastpos]) if pos >= 0: if pos + 1 != lastpos or include_empty_strings: words.append(strin...
:param char: The character on which to split the string :type char: string :param string: The string to split :type string: string :returns: List of substrings of *string* :rtype: list of strings Splits *string* whenever *char* appears without an odd number of backslashes ('\\') preceding i...
def fast_sync_sign_snapshot( snapshot_path, private_key, first=False ): if not os.path.exists(snapshot_path): log.error("No such file or directory: {}".format(snapshot_path)) return False file_size = 0 payload_size = 0 write_offset = 0 try: sb = os.stat(snapshot_pat...
Append a signature to the end of a snapshot path with the given private key. If first is True, then don't expect the signature trailer. Return True on success Return False on error
def skips(self, user): return self._get(self._build_url(self.endpoint.skips(id=user)))
Skips for user. Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/ticket_skips>`__.