Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
354,100
def fromfile(cls, fileobj, coltype=LIGOTimeGPS): c = [cls.entry_class(line, coltype=coltype) for line in fileobj] return cls(c)
Return a Cache object whose entries are read from an open file.
354,101
def discrete(self, vertices, scale=1.0, count=None): discrete = discretize_bezier(vertices[self.points], count=count, scale=scale) return self._orient(discrete)
Discretize the Bezier curve. Parameters ------------- vertices : (n, 2) or (n, 3) float Points in space scale : float Scale of overall drawings (for precision) count : int Number of segments to return Returns ------------- d...
354,102
def generate_method(method_name): def call(self, *args, **kwargs): if not self.threadloop.is_ready(): self.threadloop.start() return self.threadloop.submit( getattr(self.async_thrift, method_name), *args, **kwargs ) return call
Generate a method for a given Thrift service. Uses the provided TChannelSyncClient's threadloop in order to convert RPC calls to concurrent.futures :param method_name: Method being called. :return: A method that invokes the RPC using TChannelSyncClient
354,103
def transient_change_diff(self, transient_appeared, transient_gone, *class_build_args, **class_build_kwargs): to_add = set(regexes_match_sublist(self.transients_args, transient_appeared)) lost_matches = {n for n in self.transients if find_first_regex_match(n, self.transients_args) is None} ...
This should be called when we want to process a change in the status of the system (if we already have the diff) This function also applies changes due to regex_set updates if needed _transient_change_diff -> _update_transients
354,104
def does_coord_increase_w_index(arr): diff = np.diff(arr) if not np.all(np.abs(np.sign(diff))): raise ValueError("Array is not monotonic: {}".format(arr)) return bool(diff[0])
Determine if the array values increase with the index. Useful, e.g., for pressure, which sometimes is indexed surface to TOA and sometimes the opposite.
354,105
def log_no_newline(self, msg): self.print2file(self.logfile, False, False, msg)
print the message to the predefined log file without newline
354,106
def verify(self, assoc_handle, message): assoc = self.getAssociation(assoc_handle, dumb=True) if not assoc: logging.error("failed to get assoc with handle %r to verify " "message %r" % (assoc_handle, message)) return False ...
Verify that the signature for some data is valid. @param assoc_handle: The handle of the association used to sign the data. @type assoc_handle: str @param message: The signed message to verify @type message: openid.message.Message @returns: C{True} if the signature...
354,107
def extract(list_name, base_url, list_config=None, user=None, password=None): if not (base_url and list_name): raise RuntimeError( "base_url [{}] and list_name [{}] can not be NULL".format( base_url, list_name)) list_config = list_config or {} assert isinstance(list...
# FIXME DOCS
354,108
def clear_commentarea_cache(comment): parent = comment.content_object for instance in CommentsAreaItem.objects.parent(parent): instance.clear_cache()
Clean the plugin output cache of a rendered plugin.
354,109
def classify_regions(dataset, masks, method=, threshold=0.08, remove_overlap=True, regularization=, output=, studies=None, features=None, class_weight=, classifier=None, cross_val=, param_grid=None, scoring=): (X, y) = get_stu...
Perform classification on specified regions Given a set of masks, this function retrieves studies associated with each mask at the specified threshold, optionally removes overlap and filters by studies and features. Then it trains an algorithm to classify studies based on features and t...
354,110
def push_build_status(id): response = utils.checked_api_call(pnc_api.build_push, , build_record_id=id) if response: return utils.format_json(response)
Get status of Brew push.
354,111
def into_signalfx_point(self, metric): dims = { "collector": metric.getCollectorPath(), "prefix": metric.getPathPrefix(), } if metric.host is not None and metric.host != "": dims["host"] = metric.host return { "metric": metric.get...
Convert diamond metric into something signalfx can understand
354,112
def load_table(self, table): table = self._valid_table_name(table) schema, table = self.parse_table_name(table) if not schema: schema = self.schema tables = self.tables else: tables = self.tables_in_schema(schema) if table in tables: ...
Loads a table. Returns None if the table does not already exist in db
354,113
def call(self, path, query=None, get_all_pages=True, side_loading=False): zendesk = self.get_conn() first_request_successful = False while not first_request_successful: try: results = zendesk.call(path, query) first_request_successful = True ...
Call Zendesk API and return results :param path: The Zendesk API to call :param query: Query parameters :param get_all_pages: Accumulate results over all pages before returning. Due to strict rate limiting, this can often timeout. Waits for recommended period betwe...
354,114
def proximal_l1_l2(space, lam=1, g=None): r lam = float(lam) if g is not None and g not in space: raise TypeError(.format(g, space)) class ProximalL1L2(Operator): def __init__(self, sigma): super(ProximalL1L2, self).__init__( domain=s...
r"""Proximal operator factory of the group-L1-L2 norm/distance. Implements the proximal operator of the functional :: F(x) = lam || |x - g|_2 ||_1 with ``x`` and ``g`` elements in ``space``, and scaling factor ``lam``. Here, ``|.|_2`` is the pointwise Euclidean norm of a vector-valued functio...
354,115
def default_ccache_dir() -> str: if in os.environ: ccache_dir = os.path.realpath(os.environ[]) try: os.makedirs(ccache_dir, exist_ok=True) return ccache_dir except PermissionError: logging.info(, ccache_dir) import platform if platf...
:return: ccache directory for the current platform
354,116
def pos_tags(self): return [(Word(word, pos_tag=t), unicode(t)) for word, t in self.pos_tagger.tag(self.raw) ]
Returns an list of tuples of the form (word, POS tag). Example: :: [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'), ('Thursday', 'NNP'), ('morning', 'NN')] :rtype: list of tuples
354,117
def load(self, indexables): try: data = Persistence.read(self.path, create_file=True) except ValueError: data = {} return self.load_data(data, indexables)
Load the index file and reorder the banks based in order listed in index :param list[Indexable] indexables: Banks that will be reordered based in index file :return list[Bank]: Banks reordered
354,118
def pss(self): return (self.table[0, 0] * self.table[1, 1] - self.table[0, 1] * self.table[1, 0]) / \ ((self.table[0, 0] + self.table[1, 0]) * (self.table[0, 1] + self.table[1, 1]))
Peirce (Hansen-Kuipers, True) Skill Score (ad - bc)/((a+c)(b+d))
354,119
def qqplot(pv, distr = , alphaLevel = 0.05): shape_ok = (len(pv.shape)==1) or ((len(pv.shape)==2) and pv.shape[1]==1) assert shape_ok, tests = pv.shape[0] pnull = (0.5 + sp.arange(tests))/tests Ipv = sp.argsort(pv) if distr == : qnull = sp.stats.chi2.isf(pnull, 1) qemp = (sp.stats.chi2.isf(pv[Ipv...
This script makes a Quantile-Quantile plot of the observed negative log P-value distribution against the theoretical one under the null. Input: pv pvalues (numpy array) distr scale of the distribution (log10 or chi2) alphaLevel significance bounds
354,120
def LogHttpAdminUIAccess(self, request, response): event_id = self.GetNewEventId() api_method = response.headers.get("X-API-Method", "unknown") api_reason = response.headers.get("X-GRR-Reason", "none") log_msg = "%s API call [%s] by %s (reason: %s): %s [%d]" % ( event_id, api_met...
Log an http based api call. Args: request: A WSGI request object. response: A WSGI response object.
354,121
def ParseDom(self, dom, feed): shape_num = 0 for node in dom.getElementsByTagName(): p = self.ParsePlacemark(node) if p.IsPoint(): (lon, lat) = p.coordinates[0] m = self.stopNameRe.search(p.name) feed.AddStop(lat, lon, m.group(1)) elif p.IsLine(): self.Conv...
Parses the given kml dom tree and updates the Google transit feed object. Args: dom - kml dom tree feed - an instance of Schedule class to be updated
354,122
def toggle_actions(actions, enable): if actions is not None: for action in actions: if action is not None: action.setEnabled(enable)
Enable/disable actions
354,123
def get_base_fields(msg, prefix=, parse_header=True): slots = msg.__slots__ ret_val = [] msg_types = dict() for i in slots: slot_msg = getattr(msg, i) if not parse_header and i == : continue if hasattr(slot_msg, ): (subs, type_map) = get_base_fiel...
function to get the full names of every message field in the message
354,124
def get_both_blocks_sibling(self): if not self.is_both_blocks(): return None if self.block.block_letter and self.block.block_letter.upper() not in ["A", "B"]: return None other_instances = (EighthScheduledActivity.objects.filter(activity=self.activ...
If this is a both-blocks activity, get the other EighthScheduledActivity object that occurs on the other block. both_blocks means A and B block, NOT all of the blocks on that day. Returns: EighthScheduledActivity object if found None if the activity can...
354,125
def get(key, service=None, profile=None): client = _get_conn(profile) result = client.get(key) return result.value
Get a value from the etcd service
354,126
def _doc_object(obj, obj_type, nest=None, config=default_config): doc = inspect.getdoc(obj) if not doc and not nest: return None result = { : obj_type, : obj.__name__, : doc } if nest: result[] = nest return result
Return a dict with type, name, doc and nested doc (if any).
354,127
def add_proxy(self, proxy): protocol = proxy.protocol addr = proxy.addr if addr in self.proxies: self.proxies[protocol][addr].last_checked = proxy.last_checked else: self.proxies[protocol][addr] = proxy self.addr_list[protocol].append(addr)
Add a valid proxy into pool You must call `add_proxy` method to add a proxy into pool instead of directly operate the `proxies` variable.
354,128
def create_alert(name=None, api_key=None, reason=None, action_type="Create"): s requisites and other global state arguments could be found above. Required Parameters: api_key Itve copied while adding integration in OpsGenie. reason It will be used as alerts alias. If you want to u...
Create an alert in OpsGenie. Example usage with Salt's requisites and other global state arguments could be found above. Required Parameters: api_key It's the API Key you've copied while adding integration in OpsGenie. reason It will be used as alert's default message in OpsGenie. ...
354,129
def getsshkeys(self): request = requests.get( self.keys_url, headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 200: return request.json() else: return False
Gets all the ssh keys for the current user :return: a dictionary with the lists
354,130
def parse_env_zones(self): import csv reader = csv.reader([os.environ.get(,"")], skipinitialspace=True) zones = [r for r in reader] return [z for z in zones[0]]
returns a list of comma separated zones parsed from the GCE_ZONE environment variable. If provided, this will be used to filter the results of the grouped_instances call
354,131
def fcoe_get_login_output_fcoe_login_list_interface_type(self, **kwargs): config = ET.Element("config") fcoe_get_login = ET.Element("fcoe_get_login") config = fcoe_get_login output = ET.SubElement(fcoe_get_login, "output") fcoe_login_list = ET.SubElement(output, "fcoe-lo...
Auto Generated Code
354,132
def align_subplots(N,M,xlim=None, ylim=None): if xlim is None: xlim = [np.inf,-np.inf] for i in range(N*M): plt.subplot(N,M,i+1) xlim[0] = min(xlim[0],plt.xlim()[0]) xlim[1] = max(xlim[1],plt.xlim()[1]) if ylim is None: ylim = [np.inf,-np.inf...
make all of the subplots have the same limits, turn off unnecessary ticks
354,133
def pair_list(args): if args.entity_type and args.entity: if args.entity_type == : return [ args.entity.strip() ] elif args.entity_type == : entities = _entity_paginator(args.project, args.workspace, ,...
List pairs within a container.
354,134
def delete_collection_namespaced_stateful_set(self, namespace, **kwargs): kwargs[] = True if kwargs.get(): return self.delete_collection_namespaced_stateful_set_with_http_info(namespace, **kwargs) else: (data) = self.delete_collection_namespaced_stateful_set_...
delete_collection_namespaced_stateful_set # noqa: E501 delete collection of StatefulSet # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_namespaced_stateful_set(nam...
354,135
def _rt_update_docindices(self, element, docstart, docend): delta = element.docend - docend element.docstart = docstart element.docend = docend element.start += delta element.end += delta return delta
Updates the docstart, docend, start and end attributes for the specified element using the new limits for the docstring.
354,136
def get(self, slug): kb = api.get_kb_by_slug(slug) check_knowledge_access(kb) parser = reqparse.RequestParser() parser.add_argument( , type=str, help="Return only entries where key matches this.") parser.add_argument( , type...
Get KnwKB. Url parameters: - from: filter "mappings from" - to: filter "mappings to" - page - per_page - match_type: s=substring, e=exact, sw=startswith - sortby: 'from' or 'to'
354,137
def phi(self, mechanism, purview): return min(self.phi_cause_mip(mechanism, purview), self.phi_effect_mip(mechanism, purview))
Return the |small_phi| of a mechanism over a purview.
354,138
def load_file(cls, package_name, root_dir, relative_dirs): extension = "[!. file_matches = dbt.clients.system.find_matching( root_dir, relative_dirs, extension) for file_match in file_matches: file_contents = dbt.clients.system.load_file...
Load and parse documentation in a list of projects. Returns a list of ParsedNodes.
354,139
def with_validation(func): @wraps(func) def wrapper(*args, **kwargs): assert_valid_arguments(func, *args, **kwargs) return func(*args, **kwargs) return wrapper
Decorator that validates task arguments: - Checks the argspec for the input function - Validates that all arguments have been specified with non-None values - Aborts with helpful errors One caveat: this decorator *MUST* be the innermost decorator because other decorators will typically replac...
354,140
def publish( c, sdist=True, wheel=False, index=None, sign=False, dry_run=False, directory=None, dual_wheels=False, alt_python=None, check_desc=False, ): c.config.run.hide = False config = c.config.get("packaging", {}) index = config.get("index", index) ...
Publish code to PyPI or index of choice. All parameters save ``dry_run`` and ``directory`` honor config settings of the same name, under the ``packaging`` tree. E.g. say ``.configure({'packaging': {'wheel': True}})`` to force building wheel archives by default. :param bool sdist: Whether t...
354,141
def update_group_color(self, lights: list) -> None: for group in self.groups.values(): if not any({*lights} & {*group.lights}): continue light_ids = lights if len(light_ids) > 1: light_ids = grou...
Update group colors based on light states. deCONZ group updates don't contain any information about the current state of the lights in the group. This method updates the color properties of the group to the current color of the lights in the group. For groups where the lights h...
354,142
def _print_level(level, msg): for l in str(msg.rstrip()).split("\n"): print("{0:<9s}{1}".format(level, str(l)))
Print the information in Unicode safe manner.
354,143
def _is_cidr_in_ignore_routes(cidr): for ignore_cidr in CURRENT_STATE.ignore_routes: if is_cidr_in_cidr(cidr, ignore_cidr): return True return False
Checks the CIDR to see if it falls into any CIDRs specified via the ignore_routes parameter. This is used mostly to protect special routes to specific instances (for example proxies, etc.), so that the vpc-router does not clean those up. Only used to govern cleanup of routes, is not consulted when cre...
354,144
def _evaluate(self,x,return_indices = False): return self._evalOrDer(x,True,False)[0]
Returns the level of the interpolated function at each value in x. Only called internally by HARKinterpolator1D.__call__ (etc).
354,145
def encode_memo(priv, pub, nonce, message): shared_secret = get_shared_secret(priv, pub) aes = init_aes(shared_secret, nonce) " Checksum " raw = bytes(message, "utf8") checksum = hashlib.sha256(raw).digest() raw = checksum[0:4] + raw " Padding " raw = _pad(raw, 16) " Encryption ...
Encode a message with a shared secret between Alice and Bob :param PrivateKey priv: Private Key (of Alice) :param PublicKey pub: Public Key (of Bob) :param int nonce: Random nonce :param str message: Memo message :return: Encrypted message :rtype: hex
354,146
def _convert_1bit_array_to_byte_array(arr): while len(arr) < 8 or len(arr) % 8: arr.append(0) arr = _np.array(arr, dtype=) bit_arr = [] idx = 0 for arr_idx in range(int(len(arr) / 8)): bit_arr.append(((arr[idx] << 7) & (1 << 7)) | ((arr[idx+1] ...
Convert bit array to byte array. :param arr: list Bits as a list where each element is an integer of 0 or 1 Returns ------- numpy.array 1D numpy array of type uint8
354,147
def relevant_connections(n, _from, to): cm = np.zeros((n, n)) if not _from or not to: return cm cm[np.ix_(_from, to)] = 1 return cm
Construct a connectivity matrix. Args: n (int): The dimensions of the matrix _from (tuple[int]): Nodes with outgoing connections to ``to`` to (tuple[int]): Nodes with incoming connections from ``_from`` Returns: np.ndarray: An |n x n| connectivity matrix with the |i,jth| entry ...
354,148
def _construct_output_to_match(output_block): output_block.validate() selections = ( u % (output_block.fields[key].to_match(), key) for key in sorted(output_block.fields.keys()) ) return u % (u.join(selections),)
Transform a ConstructResult block into a MATCH query string.
354,149
def get_cell_node_coord(self, var, coords=None, axis=, nans=None): if coords is None: coords = self.ds.coords axis = axis.lower() get_coord = self.get_x if axis == else self.get_y coord = get_coord(var, coords=coords) if coord is not None: bounds...
Checks whether the bounds in the variable attribute are triangular Parameters ---------- var: xarray.Variable or xarray.DataArray The variable to check coords: dict Coordinates to use. If None, the coordinates of the dataset in the :attr:`ds` attribut...
354,150
def folder_source(path, folder): fnames, lbls, all_lbls = read_dirs(path, folder) lbl2idx = {lbl:idx for idx,lbl in enumerate(all_lbls)} idxs = [lbl2idx[lbl] for lbl in lbls] lbl_arr = np.array(idxs, dtype=int) return fnames, lbl_arr, all_lbls
Returns the filenames and labels for a folder within a path Returns: ------- fnames: a list of the filenames within `folder` all_lbls: a list of all of the labels in `folder`, where the # of labels is determined by the # of directories within `folder` lbl_arr: a numpy array of the label indices...
354,151
def solve(self): self.case.reset() b, l, g, _, _, _, _ = self._unpack_case(self.case) self.case.index_buses(b) refs, pq, pv, pvpq = self._index_buses(b) if len(refs) != 1: logger.error("Swing bus required for DCPF....
Runs a power flow @rtype: dict @return: Solution dictionary with the following keys: - C{V} - final complex voltages - C{converged} - boolean value indicating if the solver converged or not - C{iterations} - the number of ite...
354,152
def elements(self): offset = self.EXTRA_DIGITS if offset: return (self._id[:offset], self.company_prefix, self._reference, self.check_digit) else: return (self.company_prefix, self._reference, self.check_digit)
Return the identifier's elements as tuple.
354,153
def get(self, key, default=None): if key.count() == 0: return super(DotDict, self).get(key, default) value = default first, remainder = key.split(, 1) if first in self: value = super(DotDict, self).g...
Get a value from the `DotDict`. The `key` parameter can either be a regular string key, e.g. "foo", or it can be a string key with dot notation, e.g. "foo.bar.baz", to signify a nested lookup. The default value is returned if any level of the key's components are not found. ...
354,154
def list_worktrees(cwd, stale=False, user=None, password=None, output_encoding=None, **kwargs): s HEAD will be included in the return data. .. note:: By default, only worktrees for which the worktree director...
.. versionadded:: 2015.8.0 Returns information on worktrees .. versionchanged:: 2015.8.4 Version 2.7.0 added the ``list`` subcommand to `git-worktree(1)`_ which provides a lot of additional information. The return data has been changed to include this information, even for pre-2.7.0 ve...
354,155
def clear(self, train=False, split=0): logger.info(f"Clearing Features (split {split})") sub_query = ( self.session.query(Candidate.id).filter(Candidate.split == split).subquery() ) query = self.session.query(Feature).filter(Feature.candidate_id.in_(sub_que...
Delete Features of each class from the database. :param train: Whether or not to clear the FeatureKeys :type train: bool :param split: Which split of candidates to clear features from. :type split: int
354,156
def addParts(self, part_id, parent_id, part_relationship=None): if part_relationship is None: part_relationship = self.globaltt[] if parent_id is None: raise TypeError() elif part_id is None: raise TypeError() elif part_relationship i...
This will add a has_part (or subproperty) relationship between a parent_id and the supplied part. By default the relationship will be BFO:has_part, but any relationship could be given here. :param part_id: :param parent_id: :param part_relationship: :return:
354,157
def get_version(exe): assert isinstance(exe, list) return Popen(exe, stdout=PIPE, stderr=STDOUT).stdout.read()
:param exe: :type list required
354,158
def get_generated_cols(X_original, X_transformed, to_transform): original_cols = list(X_original.columns) if len(to_transform) > 0: [original_cols.remove(c) for c in to_transform] current_cols = list(X_transformed.columns) if len(original_cols) > 0: [current_cols.remove(c) for c i...
Returns a list of the generated/transformed columns. Arguments: X_original: df the original (input) DataFrame. X_transformed: df the transformed (current) DataFrame. to_transform: [str] a list of columns that were transformed (as in the original DataFrame...
354,159
def config(self, decimals_as_strings=True, ts_as_dates=False, sequencing=False, ts=False, **kwargs): flags = 0 if decimals_as_strings: flags += 8 if ts_as_dates: flags += 32 if ts: flags += 32768 if sequencing: ...
Send configuration to websocket server :param decimals_as_strings: bool, turn on/off decimals as strings :param ts_as_dates: bool, decide to request timestamps as dates instead :param sequencing: bool, turn on sequencing :param ts: bool, request the timestamp to be appended to every array ...
354,160
def startCompletion(self, force=False): tree = self.completerTree() if not force and tree.isVisible(): return tree.clear() obj, remain = self.objectAtCursor() if obj is None: tree.hide() ...
Starts a new completion popup for the current object. :return <bool> success
354,161
def get_reaction(self, reactants, products): return self._make_request("/reaction", payload={"reactants[]": reactants, "products[]": products}, mp_decode=False)
Gets a reaction from the Materials Project. Args: reactants ([str]): List of formulas products ([str]): List of formulas Returns: rxn
354,162
def get_tagged_version_numbers(series=): releases = [] if series == : tag_regex = re.compile() else: tag_regex = re.compile() tag_url = urllib.request.urlopen(GITHUB_TAGS) for ref in (i.get(, ) for i in json.loads(tag_url.read())): m = tag_regex.match(...
Retrieve git tags and find version numbers for a release series series - 'stable', 'oldstable', or 'testing
354,163
def discrete_clipping_params(ts, capacity=100, rate_limit=float()): raise NotImplementedError("Doesnt0t1integralthresholdt0t1thresholdintegralt0t1thresholdintegral': integral} return params
Start, end, and threshold that clips the value of a time series the most, given a limitted "capacity" and "rate" Assumes that the integrated maximum includes the peak (instantaneous maximum). Assumes that the threshold can only set to one of the values of the Series. Arguments: ts (TimeSeries): Time...
354,164
def _run_info_from_yaml(dirs, run_info_yaml, config, sample_names=None, is_cwl=False, integrations=None): validate_yaml(run_info_yaml, run_info_yaml) with open(run_info_yaml) as in_handle: loaded = yaml.safe_load(in_handle) fc_name, fc_date = None, None if dirs.get("...
Read run information from a passed YAML file.
354,165
def upload(self, source, destination, bucket, chunk_size = 2 * 1024 * 1024, metadata=None, keep_private=True): utf-8 env = keep_private = self._get_and_update_setting(env) or keep_private media = MediaFileUpload(s...
upload a file from a source to a destination. The client is expected to have a bucket (self._bucket) that is created when instantiated. This would be the method to do the same using the storage client, but not easily done for resumable blob = self._bucket.blob(destination) blob...
354,166
def __load_paths(self, base_path=None): if base_path is None: base_path = dirname(dirname(dirname(__file__))) if not base_path.endswith(sep): base_path += sep self.__paths = { : base_path, : base_path + + sep, : base_path + +...
Set the paths of the different folders
354,167
def _wrapper(self, func): def wrapped(*args, **kwargs): ret_val = func(*args, **kwargs) if isinstance(ret_val, pymongo.cursor.Cursor): ret_val = self.from_cursor(ret_val) return ret_val return wrapped
This function wraps all callable objects returned by self.__getattr__. If the result is a cursor, wrap it into a QueryResults object so that you can invoke postprocess functions in self._pproc
354,168
def router(self): if not self.has_root_router: self.middleware.add(HTTPMethod.ALL, MiddlewareChain.ROOT_PATTERN, Router()) return self.middleware.last().func
Property returning the router at the top of the middleware chain's stack (the last item in the list). If the list is empty OR the item is not an instance of growler.Router, one is created and added to the middleware chain, matching all requests.
354,169
def add(self, key, val, minutes): if hasattr(self._store, ): return self._store.add(key, val, self._get_minutes(minutes)) if not self.has(key): self.put(key, val, minutes) return True return False
Store an item in the cache if it does not exist. :param key: The cache key :type key: str :param val: The cache value :type val: mixed :param minutes: The lifetime in minutes of the cached value :type minutes: int|datetime :rtype: bool
354,170
def install_yum(self, fn=None, package_name=None, update=0, list_only=0): assert self.genv[ROLE] yum_req_fn = fn or self.find_template(self.genv.yum_requirments_fn) if not yum_req_fn: return [] assert os.path.isfile(yum_req_fn) update = int(update) if...
Installs system packages listed in yum-requirements.txt.
354,171
def call_missing_reference(cls, kb_app, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, node, contnode, ): for callback in EventAction.get_callbacks(kb_app, ...
On doctree-resolved, do callbacks
354,172
def execute_command(self, cmd, params=None, callback=None, raw=False): def execute_with_callbacks(cmd, params=None, callback=None, raw=False): code, params = self.send_command(cmd, params, raw) if callback: callback(code, params) return code, params ...
Execute a command and return a parsed response.
354,173
def _load_mirteFile(d, m): defs = d[] if in d else {} insts = d[] if in d else {} insts_to_skip = [] for k in insts: if k in m.insts: m.update_instance(k, dict(insts[k])) insts_to_skip.append(k) for k in insts_to_skip: del(insts[k]) it = s...
Loads the dictionary from the mirteFile into <m>
354,174
def manage_aldb_record(self, control_code, control_flags, group, address, data1, data2, data3): msg = ManageAllLinkRecord(control_code, control_flags, group, address, data1, data2, data3) self.send_msg(msg)
Update an IM All-Link record. Control Code values: - 0x00 Find First Starting at the top of the ALDB, search for the first ALL-Link Record matching the <ALL-Link Group> and <ID> in bytes 5 – 8. The search ignores byte 4, <ALL-Link Record Flags>. You will receive an ACK at the en...
354,175
def checkImages(images): images2 = [] for im in images: if PIL and isinstance(im, PIL.Image.Image): images2.append(im) elif np and isinstance(im, np.ndarray): if im.dtype == np.uint8: images2.append(im) e...
checkImages(images) Check numpy images and correct intensity range etc. The same for all movie formats.
354,176
def y(self, d): if "property" in d: javabridge.call(self.jobject, "setYProperty", "(Ljava/lang/String;)V", d["property"]) if "min" in d: javabridge.call(self.jobject, "setYMin", "(D)V", d["min"]) if "max" in d: javabridge.call(self.jobject, "setYMax",...
Allows to configure the Y of the grid with one method call. Keys for the dictionary: property, min, max, step, base, expression Types: property=str, min=float, max=float, step=float, base=float, expression=str :param d: the dictionary with the parameters :type d: dict
354,177
def getlineno(frame): lineno = frame.f_lineno code = frame.f_code if hasattr(code, ): table = code.co_lnotab lineno = code.co_firstlineno addr = 0 for i in range(0, len(table), 2): addr = addr + ord(table[i]) if addr > frame.f_lasti: break ...
Get the line number from a frame object, allowing for optimization.
354,178
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any: if isinstance(node.op, ast.UAdd): result = +self.visit(node=node.operand) elif isinstance(node.op, ast.USub): result = -self.visit(node=node.operand) elif isinstance(node.op, ast.Not): result = not se...
Visit the node operand and apply the operation on the result.
354,179
def message(self, value): try: import ast value = ast.literal_eval(value) except (SyntaxError, TypeError, ValueError): pass try: value = value.get(, value) msg_data = value.split() self._message = msg_data[0] ...
Attempt to deconstruct error message to retrieve further error data.
354,180
def readable_mem(mem): for suffix in ["", "K", "M", "G", "T"]: if mem < 10000: return "{}{}".format(int(mem), suffix) mem /= 1024 return "{}P".format(int(mem))
:param mem: An integer number of bytes to convert to human-readable form. :return: A human-readable string representation of the number.
354,181
def make_sentence(sentence, *args, **kwargs): return symbols.SENTENCE(*([sentence] + list(args)), **kwargs)
Wrapper: returns a Sentence node
354,182
def compile_dictionary(self, lang, wordlists, encoding, output): cmd = [ self.binary, , lang, , codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name, , , output ] wordlist = try: ...
Compile user dictionary.
354,183
def parse(): parser = argparse.ArgumentParser() parser.add_argument(, action=, version=.format(f90nml.__version__)) parser.add_argument(, , action=, help="specify namelist group to modify. " "When absent, the first group is used"...
Parse the command line input arguments.
354,184
def p_poke(p): i = 2 if isinstance(p[2], Symbol) or p[2] is None else 3 if p[i] is None or p[i + 2] is None: p[0] = None return p[0] = make_sentence(, make_typecast(TYPE.uinteger, p[i], p.lineno(i + 1)), make_typecast(TYPE.ubyte, p[i + 2...
statement : POKE expr COMMA expr | POKE LP expr COMMA expr RP
354,185
def global_symbols(self): declared_symbols = self.declared_symbols return set( s for s in self.referenced_symbols if s not in declared_symbols)
These are symbols that have been referenced, but not declared within this scope or any parent scopes.
354,186
def leastsq_NxN(x, y, fit_offset=False, perc=None): if perc is not None: if not fit_offset and isinstance(perc, (list, tuple)): perc = perc[1] weights = csr_matrix(get_weight(x, y, perc)).astype(bool) x, y = weights.multiply(x).tocsr(), weights.multiply(y).tocsr() else: weig...
Solution to least squares: gamma = cov(X,Y) / var(X)
354,187
def _normalize_server_url(self, server): server = server if server.startswith(("http://", "https://")) else "http://{}".format(server) return server
Check if the server URL starts with a HTTP or HTTPS scheme, fall back to http if not present
354,188
def time(self, t): _time = arrow.get(t).format() self._time = datetime.datetime.strptime(_time, )
Convert any timestamp into a datetime and save as _time
354,189
def pawns_at(self, x, y): for pawn in self.pawn.values(): if pawn.collide_point(x, y): yield pawn
Iterate over pawns that collide the given point.
354,190
def blocks(self, ignore_blank_lines=True): start, end = self.get_range(ignore_blank_lines=ignore_blank_lines) block = self._trigger.next() while block.blockNumber() <= end and block.isValid(): yield block block = block.next()
This generator generates the list of blocks directly under the fold region. This list does not contain blocks from child regions. :param ignore_blank_lines: True to ignore last blank lines.
354,191
def list_results(self, number, username): data = self.get_question_results(number, username) result = [] for number in data: result += [(number, data[number])] return result
[deprecated] 建議使用方法 `get_question_results()`
354,192
def getArgument(self, num): if not self.hasArgument(num): raise InterfaceException("Failed to retrieve argument " + str(num) + " -- not enough arguments provided") return self.args[num]
Get the num^th argument. :param num: Which argument to get; indexing here is from 0. :return: The num^th agument; arguments are always parsed as strings, so this will be a string. :raise InterfaceException: if there are fewer than num + 1 arguments.
354,193
def specs_to_ir(specs, version=, debug=False, route_whitelist_filter=None): parser_factory = ParserFactory(debug=debug) partial_asts = [] for path, text in specs: logger.info(, path) parser = parser_factory.get_parser() if debug: parser.test_lexing(text) p...
Converts a collection of Stone specifications into the intermediate representation used by Stone backends. The process is: Lexer -> Parser -> Semantic Analyzer -> IR Generator. The code is structured as: 1. Parser (Lexer embedded within) 2. IR Generator (Semantic Analyzer embedded within) ...
354,194
def policy_map_class_scheduler_strict_priority_priority_number(self, **kwargs): config = ET.Element("config") policy_map = ET.SubElement(config, "policy-map", xmlns="urn:brocade.com:mgmt:brocade-policer") po_name_key = ET.SubElement(policy_map, "po-name") po_name_key.text = kwar...
Auto Generated Code
354,195
def request(self, method, url, params=None, body=None, **kwargs): url = "{base_url}{version}{resource}".format(base_url=self.config.base_url, version=self.API_VERSION, resource=url) header...
Send an HTTP request. The :param:`params` will be properly encoded, as well as :param:`body` which will be wrapped with envelope the API expects and json encoded. When you get a reponse the method will try to json decode the response, if the media type represents json, unwrap the envel...
354,196
def _create_logger(name=, level=None): logger = logging.getLogger(name) handler = logging.StreamHandler() handler.setFormatter(Logging.ColoredFormatter()) logger.addHandler(handler) for level in Logging.LEVELS: setattr(logger, level, getattr...
Create fmf logger
354,197
def send(self, filenames=None): try: with self.ssh_client.connect() as ssh_conn: with self.sftp_client.connect(ssh_conn) as sftp_conn: for filename in filenames: sftp_conn.copy(filename=filename) self.archiv...
Sends the file to the remote host and archives the sent file locally.
354,198
def _compute(self): src_path = self.ctx.src_path if not src_path.exists: return NONE if src_path.is_null: return None try: if self.parse: value = self.parse(src_path) else: value = self._parse(src_pa...
Processes this fields `src` from `ctx.src`.
354,199
def _set_main_widget(self, widget, redraw): self.set_body(widget) self.reload_footer() if redraw: logger.debug("redraw main widget") self.refresh()
add provided widget to widget list and display it :param widget: :return: