Unnamed: 0
int64
0
389k
code
stringlengths
26
79.6k
docstring
stringlengths
1
46.9k
374,900
def includeme(config): log.info() for key, val in config.registry.settings.items(): if key.startswith(): log.debug( % (key, val)) htmlmin_opts[key[8:]] = asbool(val) if key.startswith(): log.debug( % (key, val)) opts[key[16:]] = asbool(val) ...
Add pyramid_htmlmin n your pyramid include list.
374,901
def delete_cache_security_group(name, region=None, key=None, keyid=None, profile=None, **args): return _delete_resource(name, name_param=, desc=, res_type=, region=region, key=key, keyid=keyid, profile=profile, **args)
Delete a cache security group. Example: .. code-block:: bash salt myminion boto3_elasticache.delete_cache_security_group myelasticachesg
374,902
def Right(self, n = 1, dl = 0): self.Delay(dl) self.keyboard.tap_key(self.keyboard.right_key, n)
右方向键n次
374,903
def flush(self): chunks = [] chunks.append(self._compress(b, lib.BROTLI_OPERATION_FLUSH)) while lib.BrotliEncoderHasMoreOutput(self._encoder) == lib.BROTLI_TRUE: chunks.append(self._compress(b, lib.BROTLI_OPERATION_FLUSH)) return b.join(chunks)
Flush the compressor. This will emit the remaining output data, but will not destroy the compressor. It can be used, for example, to ensure that given chunks of content will decompress immediately.
374,904
def sphlat(r, colat, lons): r = ctypes.c_double(r) colat = ctypes.c_double(colat) lons = ctypes.c_double(lons) radius = ctypes.c_double() lon = ctypes.c_double() lat = ctypes.c_double() libspice.sphcyl_c(r, colat, lons, ctypes.byref(radius), ctypes.byref(lon), ctyp...
Convert from spherical coordinates to latitudinal coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphlat_c.html :param r: Distance of the point from the origin. :type r: float :param colat: Angle of the point from positive z axis (radians). :type colat: float :param lons: ...
374,905
def _create_storage(storage_service, trajectory=None, **kwargs): kwargs_copy = kwargs.copy() kwargs_copy[] = trajectory matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy) storage_service = storage_service(**matching_kwargs) unused_kwargs = set(kwargs.keys()) - set(matching_kwar...
Creates a service from a constructor and checks which kwargs are not used
374,906
def lmean (inlist): sum = 0 for item in inlist: sum = sum + item return sum/float(len(inlist))
Returns the arithematic mean of the values in the passed list. Assumes a '1D' list, but will function on the 1st dim of an array(!). Usage: lmean(inlist)
374,907
def node_link_graph(data, directed=False, attrs=_attrs): directed = data.get(, directed) graph = dn.DynGraph() if directed: graph = graph.to_directed() id_ = attrs[] mapping = [] graph.graph = data.get(, {}) c = count() for d in data[]: node = d.get(id_, next(c)) ...
Return graph from node-link data format. Parameters ---------- data : dict node-link formatted graph data directed : bool If True, and direction not specified in data, return a directed graph. attrs : dict A dictionary that contains three keys 'id', 'source', 'target'. ...
374,908
def add_missing_row( df: pd.DataFrame, id_cols: List[str], reference_col: str, complete_index: Union[Dict[str, str], List[str]] = None, method: str = None, cols_to_keep: List[str] = None ) -> pd.DataFrame: if cols_to_keep is None: cols_for_index = [reference_col] else: ...
Add missing row to a df base on a reference column --- ### Parameters *mandatory :* - `id_cols` (*list of str*): names of the columns used to create each group - `reference_col` (*str*): name of the column used to identify missing rows *optional :* - `complete_index` (*list* or *dict*): ...
374,909
def watch(self, *keys): if self.explicit_transaction: raise RedisError("Cannot issue a WATCH after a MULTI") self.watching = True for key in keys: self._watched_keys[key] = deepcopy(self.mock_redis.redis.get(self.mock_redis._encode(key)))
Put the pipeline into immediate execution mode. Does not actually watch any keys.
374,910
def _parse_options(self, argv, location): observed = [] while argv: if argv[0].startswith(): name = argv.pop(0)[2:] if not name: break if name not in self.options: raise InvalidO...
Parse the options part of an argument list. IN: lsArgs <list str>: List of arguments. Will be altered. location <str>: A user friendly string describing where this data came from.
374,911
def expand_effect_repertoire(self, new_purview=None): return self.subsystem.expand_effect_repertoire( self.effect.repertoire, new_purview)
See |Subsystem.expand_repertoire()|.
374,912
def eval_model(model, test, add_eval_metrics={}): logger.info("Evaluate...") model_metrics_values = model.evaluate(test[0], test[1], verbose=0, batch_size=test[1].shape[0]) model_metrics = dict(zip(_listify(model.metrics_names), ...
Evaluate model's performance on the test-set. # Arguments model: Keras model test: test-dataset. Tuple of inputs `x` and target `y` - `(x, y)`. add_eval_metrics: Additional evaluation metrics to use. Can be a dictionary or a list of functions accepting arguments: `y_true`, `y_predicted`...
374,913
def _gaussian(x, amp, loc, std): return amp * np.exp(-((x - loc)*(x - loc))/(2.0*std*std))
This is a simple gaussian. Parameters ---------- x : np.array The items at which the Gaussian is evaluated. amp : float The amplitude of the Gaussian. loc : float The central value of the Gaussian. std : float The standard deviation of the Gaussian. Retu...
374,914
def remove_stream_handlers(logger=None): if not isinstance(logger, logging.Logger): logger = logging.getLogger(logger) new_handlers = [] for handler in logger.handlers: if (isinstance(handler, logging.FileHandler) or isinstance(handler, logging.NullHandler...
Remove only stream handlers from the specified logger :param logger: logging name or object to modify, defaults to root logger
374,915
def aggregate_detail(slug_list, with_data_table=False): r = get_r() metrics_data = [] granularities = r._granularities() keys = [, , , , , , ] key_mapping = {gran: key for gran, key in zip(GRANULARITIES, keys)} keys = [key_mapping[gran] for gran in granularities] ...
Template Tag to display multiple metrics. * ``slug_list`` -- A list of slugs to display * ``with_data_table`` -- if True, prints the raw data in a table.
374,916
def find_last_true(sorted_list, true_criterion): if not true_criterion(sorted_list[0]): raise ValueError if true_criterion(sorted_list[-1]): return sorted_list[-1] lower, upper = 0, len(sorted_list) - 1 index = int((lower + upper) / 2.0) while 1: if true_cr...
Suppose we have a list of item [item1, item2, ..., itemN]. :type array: list :param array: an iterable object that support inex :param x: a comparable value If we do a mapping:: >>> def true_criterion(item): ... return item <= 6 >>> [true_criterion(item) for item in sorte...
374,917
def goto(reference_beats, estimated_beats, goto_threshold=0.35, goto_mu=0.2, goto_sigma=0.2): validate(reference_beats, estimated_beats) if estimated_beats.size == 0 or reference_beats.size == 0: return 0. beat_error = np.ones(reference_beats.shape[...
Calculate Goto's score, a binary 1 or 0 depending on some specific heuristic criteria Examples -------- >>> reference_beats = mir_eval.io.load_events('reference.txt') >>> reference_beats = mir_eval.beat.trim_beats(reference_beats) >>> estimated_beats = mir_eval.io.load_events('estimated.txt') ...
374,918
def h2i(self, pkt, seconds): if seconds is None: seconds = 0 tmp_short = (seconds >> 32) & 0xFFFF tmp_int = seconds & 0xFFFFFFFF return struct.pack("!HI", tmp_short, tmp_int)
Convert the number of seconds since 1-Jan-70 UTC to the packed representation.
374,919
def minimize(self, time, variables, **kwargs): deltas = self.step(time=time, variables=variables, **kwargs) with tf.control_dependencies(control_inputs=deltas): return tf.no_...
Performs an optimization step. Args: time: Time tensor. variables: List of variables to optimize. **kwargs: Additional optimizer-specific arguments. The following arguments are used by some optimizers: - arguments: Dict of arguments for callables,...
374,920
def backup(self, backup_name, folder_key=None, folder_name=None): folder = self._find_or_create_folder(folder_key, folder_name) drive_service = self.drive_service try: source_rsrc = drive_service.files().get(fileId=self.document_key).execute() except Exceptio...
Copies the google spreadsheet to the backup_name and folder specified. Args: backup_name (str): The name of the backup document to create. folder_key (Optional) (str): The key of a folder that the new copy will be moved to. folder_name (Opti...
374,921
def _database_create(self, engine, database): logger.info(, database, engine) database_operation(engine, , database) url = copy(engine.url) url.database = database return str(url)
Create a new database and return a new url representing a connection to the new database
374,922
def get_job(self, job_id): try: return RawMantaClient.get_job(self, job_id) except errors.MantaAPIError as ex: if ex.res.status != 404: raise mpath = "/%s/jobs/%s/job.json" % (self.account, job_id) content = self.get_o...
GetJob https://apidocs.joyent.com/manta/api.html#GetJob with the added sugar that it will retrieve the archived job if it has been archived, per: https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
374,923
def get_device_by_name(self, device_name): found_device = None for device in self.get_devices(): if device.name == device_name: found_device = device break if found_device is None: logger.debug(.format(device_...
Search the list of connected devices by name. device_name param is the string name of the device
374,924
def add_stock(self, product_id, sku_info, quantity): return self._post( , data={ "product_id": product_id, "sku_info": sku_info, "quantity": quantity } )
增加库存 :param product_id: 商品ID :param sku_info: sku信息,格式"id1:vid1;id2:vid2",如商品为统一规格,则此处赋值为空字符串即可 :param quantity: 增加的库存数量 :return: 返回的 JSON 数据包
374,925
def calc_tc_v1(self): con = self.parameters.control.fastaccess inp = self.sequences.inputs.fastaccess flu = self.sequences.fluxes.fastaccess for k in range(con.nmbzones): flu.tc[k] = inp.t-con.tcalt[k]*(con.zonez[k]-con.zrelt)
Adjust the measured air temperature to the altitude of the individual zones. Required control parameters: |NmbZones| |TCAlt| |ZoneZ| |ZRelT| Required input sequence: |hland_inputs.T| Calculated flux sequences: |TC| Basic equation: :math:`TC = T - TCAlt \...
374,926
def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn): original_ordering = [(p.topic, p.partition) for p in payloads] broker = self._get_coordinator_for_group(group) responses = {} request_id = self._next_id() ...
Send a list of requests to the consumer coordinator for the group specified using the supplied encode/decode functions. As the payloads that use consumer-aware requests do not contain the group (e.g. OffsetFetchRequest), all payloads must be for a single group. Arguments: group...
374,927
def _process_execute_error(self, msg): content = msg[] if content[]==: keepkernel = content[]== or content[]== self._keep_kernel_on_exit = keepkernel self.exit_requested.emit(self) else: traceback = .join(content...
Process a reply for an execution request that resulted in an error.
374,928
def _fit_stage(self, i, X, y, y_pred, sample_weight, sample_mask, random_state, scale, X_idx_sorted, X_csc=None, X_csr=None): assert sample_mask.dtype == numpy.bool loss = self.loss_ do_dropout = self.dropout_rate > 0. and 0 < i < len(scale) - 1 fo...
Fit another stage of ``n_classes_`` trees to the boosting model.
374,929
def server(self): conn = self.connection_class(self) with self.mutex: self.connections.append(conn) return conn
Creates and returns a ServerConnection object.
374,930
def _goto(self, pose, duration, wait, accurate): kwargs = {} if not accurate: kwargs[] = 3 q0 = self.convert_to_ik_angles(self.joints_position) q = self.inverse_kinematics(pose, initial_position=q0, **kwargs) joints = self.convert_from_ik_angles(q) ...
Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computatio...
374,931
def obfn_g0var(self): return self.var_y0() if self.opt[] else \ self.cnst_A0(None, self.Xf) - self.cnst_c0()
Variable to be evaluated in computing :meth:`.ADMMTwoBlockCnstrnt.obfn_g0`, depending on the ``AuxVarObj`` option value.
374,932
def post_cleanup(self): targetNode = self.article.top_node node = self.add_siblings(targetNode) for e in self.parser.getChildren(node): e_tag = self.parser.getTag(e) if e_tag != : if self.is_highlink_density(e) \ or self.is_tab...
\ remove any divs that looks like non-content, clusters of links, or paras with no gusto
374,933
def _truncate_to_field(model, field_name, value): field = model._meta.get_field(field_name) if len(value) > field.max_length: midpoint = field.max_length // 2 len_after_midpoint = field.max_length - midpoint first = value[:midpoint] sep = last = value[len(value) -...
Shorten data to fit in the specified model field. If the data were too big for the field, it would cause a failure to insert, so we shorten it, truncating in the middle (because valuable information often shows up at the end.
374,934
def list(self, service_rec=None, host_rec=None, hostfilter=None): return self.send.service_list(service_rec, host_rec, hostfilter)
List a specific service or all services :param service_rec: t_services.id :param host_rec: t_hosts.id :param hostfilter: Valid hostfilter or None :return: [(svc.t_services.id, svc.t_services.f_hosts_id, svc.t_hosts.f_ipaddr, svc.t_hosts.f_hostname, svc.t_services.f_proto, ...
374,935
def _get_headers(self): user_agent = __api_lib_name__ + + __version__ + + \ PYTHON_VERSION headers = {: user_agent, : } if self.key: headers[] = + self.key return headers
Get all the headers we're going to need: 1. Authorization 2. Content-Type 3. User-agent Note that the User-agent string contains the library name, the libary version, and the python version. This will help us track what people are using, and where we should concentrate ...
374,936
def _set_mldVlan(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=mldVlan.mldVlan, is_container=, presence=False, yang_name="mldVlan", rest_name="mld", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extens...
Setter method for mldVlan, mapped from YANG variable /interface_vlan/interface/vlan/ipv6/mldVlan (container) If this variable is read-only (config: false) in the source YANG file, then _set_mldVlan is considered as a private method. Backends looking to populate this variable should do so via calling thi...
374,937
def collection(data, bins=10, *args, **kwargs): from physt.histogram_collection import HistogramCollection if hasattr(data, "columns"): data = {column: data[column] for column in data.columns} return HistogramCollection.multi_h1(data, bins, **kwargs)
Create histogram collection with shared binnning.
374,938
def exec_func_src3(func, globals_, sentinal=None, verbose=False, start=None, stop=None): import utool as ut sourcecode = ut.get_func_sourcecode(func, stripdef=True, stripret=True) if sentinal is not None: sourcecode = ut.replace_between_tags(sourcecode, , sentinal) if sta...
execs a func and returns requested local vars. Does not modify globals unless update=True (or in IPython) SeeAlso: ut.execstr_funckw
374,939
def next_conkey(self, conkey): if conkey in self.conditions: return conkey conkeys = self.sorted_conkeys(prefix=conkey) if not conkeys: return conkey for candidate in conkeys: if self.conditions[candidate] ...
Return the next <conkey><n> based on conkey as a string. Example, if 'startcond3' and 'startcond5' exist, this will return 'startcond6' if 'startcond5' value is not None, else startcond5 is returned. It is assumed conkey is a valid condition key. .. warning:: Under c...
374,940
def make_measurement(name, channels, lumi=1.0, lumi_rel_error=0.1, output_prefix=, POI=None, const_params=None, verbose=False): if verbose: llog = log[] llog.info("creat...
Create a Measurement from a list of Channels
374,941
def set_value(self, control, value=None): func = getattr(_xinput, + control) if in control: target_type = c_short if self.percent: target_value = int(32767 * value) else: target_value = value elif in control: ...
Set a value on the controller If percent is True all controls will accept a value between -1.0 and 1.0 If not then: Triggers are 0 to 255 Axis are -32768 to 32767 Control List: AxisLx , Left Stick X-Axis AxisLy , Left Stick Y-Axis AxisRx ,...
374,942
def geom_find_group(g, atwts, pr_ax, mom, tt, \ nmax=_DEF.SYMM_MATCH_NMAX, \ tol=_DEF.SYMM_MATCH_TOL, \ dig=_DEF.SYMM_ATWT_ROUND_DIGITS, avmax=_DEF.SYMM_AVG_MAX): g = make_nd_vec(g, nd=None, t=np.float64, norm=False) atwts = make_nd_vec(atwts, nd=None, t...
[Find all(?) proper rotation axes (n > 1) and reflection planes.] .. todo:: Complete geom_find_axes docstring INCLUDING NEW HEADER LINE DEPENDS on principal axes and moments being sorted such that: I_A <= I_B <= I_C Logic flow developed using: 1) http://symmetry.otterbein.edu/common/image...
374,943
def fragment_fromstring(html, create_parent=False, base_url=None, parser=None, **kw): if parser is None: parser = html_parser accept_leading_text = bool(create_parent) elements = fragments_fromstring( html, parser=parser, no_leading_text=not accept_leading_text...
Parses a single HTML element; it is an error if there is more than one element, or if anything but whitespace precedes or follows the element. If ``create_parent`` is true (or is a tag name) then a parent node will be created to encapsulate the HTML in a single element. In this case, leading or tr...
374,944
def finalize(self): super(StatisticsConsumer, self).finalize() self.result = zip(self.grid, map(self.statistics, self.result))
finalize for StatisticsConsumer
374,945
def _reverse_rounding_method(method): if method is RoundingMethods.ROUND_UP: return RoundingMethods.ROUND_DOWN if method is RoundingMethods.ROUND_DOWN: return RoundingMethods.ROUND_UP if method is RoundingMethods.ROUND_HALF_UP: return RoundingMethods....
Reverse meaning of ``method`` between positive and negative.
374,946
def preserve_shape(func): @wraps(func) def wrapped_function(img, *args, **kwargs): shape = img.shape result = func(img, *args, **kwargs) result = result.reshape(shape) return result return wrapped_function
Preserve shape of the image.
374,947
def _function_add_node(self, cfg_node, function_addr): snippet = self._to_snippet(cfg_node=cfg_node) self.kb.functions._add_node(function_addr, snippet)
Adds node to function manager, converting address to CodeNode if possible :param CFGNode cfg_node: A CFGNode instance. :param int function_addr: Address of the current function. :return: None
374,948
def move(self, key, folder): path, host, flags = self._exists(key) self._invalidate_cache() newpath = joinpath( folder.base, folder.get_name(), "cur", basename(path) ) self.filesystem....
Move the specified key to folder. folder must be an MdFolder instance. MdFolders can be obtained through the 'folders' method call.
374,949
def root_mean_square(X): segment_width = X.shape[1] return np.sqrt(np.sum(X * X, axis=1) / segment_width)
root mean square for each variable in the segmented time series
374,950
def add_url_rule( self, path: str, endpoint: Optional[str]=None, view_func: Optional[Callable]=None, methods: Optional[Iterable[str]]=None, defaults: Optional[dict]=None, host: Optional[str]=None, subdomain: Optional[str]=No...
Add a route/url rule to the application. This is designed to be used on the application directly. An example usage, .. code-block:: python def route(): ... app.add_url_rule('/', route) Arguments: path: The path to route on, should ...
374,951
def send_text(self, text): return self.client.api.send_message(self.room_id, text)
Send a plain text message to the room.
374,952
def uniform_discr_frompartition(partition, dtype=None, impl=, **kwargs): if not isinstance(partition, RectPartition): raise TypeError( .format(partition)) if not partition.is_uniform: raise ValueError() if dtype is not None: dtype = np.dtype(dtype) ...
Return a uniformly discretized L^p function space. Parameters ---------- partition : `RectPartition` Uniform partition to be used for discretization. It defines the domain and the functions and the grid for discretization. dtype : optional Data type for the discretized s...
374,953
def _determine_rotated_logfile(self): rotated_filename = self._check_rotated_filename_candidates() if rotated_filename and exists(rotated_filename): if stat(rotated_filename).st_ino == self._offset_file_inode: return rotated_filename ...
We suspect the logfile has been rotated, so try to guess what the rotated filename is, and return it.
374,954
def fieldAlphaHistogram( self, name, q=, fq=None, nbins=10, includequeries=True ): oldpersist = self.persistent self.persistent = True bins = [] qbin = [] fvals = [] try: fva...
Generates a histogram of values from a string field. Output is: [[low, high, count, query], ... ] Bin edges is determined by equal division of the fields
374,955
def get_managed_policy_document(policy_arn, policy_metadata=None, client=None, **kwargs): if not policy_metadata: policy_metadata = client.get_policy(PolicyArn=policy_arn) policy_document = client.get_policy_version(PolicyArn=policy_arn, VersionId=po...
Retrieve the currently active (i.e. 'default') policy version document for a policy. :param policy_arn: :param policy_metadata: This is a previously fetch managed policy response from boto/cloudaux. This is used to prevent unnecessary API calls to get the initial policy default vers...
374,956
def unit_overlap(evaluated_model, reference_model): if not (isinstance(evaluated_model, TfModel) and isinstance(reference_model, TfModel)): raise ValueError( "Arguments has to be instances of ") terms1 = frozenset(evaluated_model.terms) terms2 = frozenset(reference_model.terms) ...
Computes unit overlap of two text documents. Documents has to be represented as TF models of non-empty document. :returns float: 0 <= overlap <= 1, where 0 means no match and 1 means exactly the same.
374,957
def register_model(cls, model): rest_name = model.rest_name resource_name = model.resource_name if rest_name not in cls._model_rest_name_registry: cls._model_rest_name_registry[rest_name] = [model] cls._model_resource_name_registry[resource_name] = [model] ...
Register a model class according to its remote name Args: model: the model to register
374,958
def write_dltime (self, url_data): self.writeln(u"<tr><td>"+self.part("dltime")+u"</td><td>"+ (_("%.3f seconds") % url_data.dltime)+ u"</td></tr>")
Write url_data.dltime.
374,959
def knob_end(self): side_chain_atoms = self.knob_residue.side_chain if not side_chain_atoms: return self.knob_residue[] distances = [distance(self.knob_residue[], x) for x in side_chain_atoms] max_d = max(distances) knob_end_atoms = [atom for atom, d in zip(s...
Coordinates of the end of the knob residue (atom in side-chain furthest from CB atom. Returns CA coordinates for GLY.
374,960
def directional_hamming_distance(reference_intervals, estimated_intervals): util.validate_intervals(estimated_intervals) util.validate_intervals(reference_intervals) if len(reference_intervals) > 1 and (reference_intervals[:-1, 1] > reference_intervals[1:,...
Compute the directional hamming distance between reference and estimated intervals as defined by [#harte2010towards]_ and used for MIREX 'OverSeg', 'UnderSeg' and 'MeanSeg' measures. Examples -------- >>> (ref_intervals, ... ref_labels) = mir_eval.io.load_labeled_intervals('ref.lab') >>> (...
374,961
def _fix_repo_url(repo_url): parsed = urlparse.urlparse(repo_url) if parsed.scheme not in (, ): return repo_url username = parsed.username or "" password = parsed.password or "" port = ":" + parsed.port if parsed.port else "" netloc = "".join((username, ":", password,...
Add empty credentials to a repo URL if not set, but only for HTTP/HTTPS. This is to make git not hang while trying to read the username and password from standard input.
374,962
def get_rendition_size(self, spec, output_scale, crop): if crop: _, _, width, height = crop else: width = self._record.width height = self._record.height mode = spec.get(, ) if mode == : return self.get_...
Wrapper to determine the overall rendition size and cropping box Returns tuple of (size,box)
374,963
def _check_operators(self): if not isinstance(self._operators, (list, tuple, np.ndarray)): raise TypeError(( ).format(type(self._operators))) for op in self._operators: if not hasattr(op, ): raise ValueError() op...
Check Operators This method checks if the input operators have a "cost" method Raises ------ ValueError For invalid operators type ValueError For operators without "cost" method
374,964
def decode(data): if riemann.network.CASHADDR_PREFIX is None: raise ValueError( .format(riemann.get_current_network_name())) if data.find(riemann.network.CASHADDR_PREFIX) != 0: raise ValueError( .format(riemann.netowrk.CASHADDR_PREFIX)) ...
str -> bytes
374,965
def _make_fake_message(self, user_id, page_id, payload): event = { : { : user_id, }, : { : page_id, }, : { : ujson.dumps(payload), }, } return FacebookMessage(event,...
Creates a fake message for the given user_id. It contains a postback with the given payload.
374,966
def _main(self): probes = self.config.get(, None) if not probes: raise ValueError() for probe_config in self.config[]: probe = plugin.get_probe(probe_config, self.plugin_context) if not in probe_config: raise ValueError(...
process
374,967
def validate_rc(): transactions = rc.read() if not transactions: print() return False transactions = sort(unique(transactions)) return validate_setup(transactions)
Before we execute any actions, let's validate our .vacationrc.
374,968
def parse(data): sections = re.compile("^ headings = re.findall("^ sections.pop(0) parsed = [] def func(h, s): p = parse_heading(h) p["content"] = s parsed.append(p) list(map(func, headings, sections)) return parsed
Parse the given ChangeLog data into a list of Hashes. @param [String] data File data from the ChangeLog.md @return [Array<Hash>] Parsed data, e.g. [{ 'version' => ..., 'url' => ..., 'date' => ..., 'content' => ...}, ...]
374,969
def get_file_str(path, saltenv=): * fn_ = cache_file(path, saltenv) if isinstance(fn_, six.string_types): try: with salt.utils.files.fopen(fn_, ) as fp_: return fp_.read() except IOError: return False return fn_
Download a file from a URL to the Minion cache directory and return the contents of that file Returns ``False`` if Salt was unable to cache a file from a URL. CLI Example: .. code-block:: bash salt '*' cp.get_file_str salt://my/file
374,970
def to_wire(self, file, compress=None, origin=None, **kw): return super(RRset, self).to_wire(self.name, file, compress, origin, self.deleting, **kw)
Convert the RRset to wire format.
374,971
def set_lacp_fallback(self, name, mode=None): if mode not in [, , ]: return False disable = True if mode == else False commands = [ % name] commands.append(self.command_builder(, value=mode, disable=disable)) retu...
Configures the Port-Channel lacp_fallback Args: name(str): The Port-Channel interface name mode(str): The Port-Channel LACP fallback setting Valid values are 'disabled', 'static', 'individual': * static - Fallback to static LAG mode * i...
374,972
def vote_choice_address(self) -> List[str]: if self.vote_id is None: raise Exception("vote_id is required") addresses = [] vote_init_txid = unhexlify(self.vote_id) for choice in self.choices: vote_cast_privkey = sha256(vote_init_txid + bytes( ...
calculate the addresses on which the vote is casted.
374,973
def _get_elements(complex_type, root): found_elements = [] element = findall(root, % XS_NAMESPACE, attribute_name=, attribute_value=complex_type)[0] found_elements = findall(element, % XS_NAMESPACE) return found_elements
Get attribute elements
374,974
def on_menu_exit(self, event): try: self.help_window.Destroy() except: pass if in sys.argv: self.Destroy() try: sys.exit() except Exception as ex: if isinstance(ex, TypeError): pass ...
Exit the GUI
374,975
def convert_op(self, op): if op == : return elif op == or op == : return elif op == : return elif op == : return elif op == : return elif op == : return elif op == : ...
Converts NeuroML arithmetic/logical operators to python equivalents. @param op: NeuroML operator @type op: string @return: Python operator @rtype: string
374,976
def get_rendered_fields(self, ctx=None): if ctx is None: ctx = RenderContext() ctx.push(self) current = self._fields[self._field_idx] res = current.get_rendered_fields(ctx) ctx.pop() return res
:param ctx: rendering context in which the method was called :return: ordered list of the fields that will be rendered
374,977
def _get_shaperecords(self, num_fill_bits, num_line_bits, shape_number): shape_records = [] bc = BitConsumer(self._src) while True: type_flag = bc.u_get(1) if type_flag: straight_flag = bc.u_get(1) ...
Return an array of SHAPERECORDS.
374,978
def get_scale_fac(fig, fiducial_width=8, fiducial_height=7): width, height = fig.get_size_inches() return (width*height/(fiducial_width*fiducial_height))**0.5
Gets a factor to scale fonts by for the given figure. The scale factor is relative to a figure with dimensions (`fiducial_width`, `fiducial_height`).
374,979
def fetch(version=): doi = { : , : } try: doi = doi[version] except KeyError as err: raise ValueError(.format( version, .join([.format(k) for k in doi.keys()]) )) requirements = { : {: }, : {: } }[versi...
Downloads the specified version of the Bayestar dust map. Args: version (Optional[:obj:`str`]): The map version to download. Valid versions are :obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and :obj:`'bayestar2015'` (Green, Schlafly, Finkbeiner et al. 2015). Defaul...
374,980
def timeinfo(self): if self.istep not in self.sdat.tseries.index: return None return self.sdat.tseries.loc[self.istep]
Time series data of the time step. Set to None if no time series data is available for this time step.
374,981
def latitude(self, latitude): if not (-90 <= latitude <= 90): raise ValueError( .format(latitude)) self._latitude = latitude
Setter for latiutde.
374,982
def resource_to_url(resource, request=None, quote=False): if request is None: request = get_current_request() reg = get_current_registry() cnv = reg.getAdapter(request, IResourceUrlConverter) return cnv.resource_to_url(resource, quote=quote)
Converts the given resource to a URL. :param request: Request object (required for the host name part of the URL). If this is not given, the current request is used. :param bool quote: If set, the URL returned will be quoted.
374,983
def spades(args): from jcvi.formats.fastq import readlen p = OptionParser(spades.__doc__) opts, args = p.parse_args(args) if len(args) == 0: sys.exit(not p.print_help()) folder, = args for p, pf in iter_project(folder): rl = readlen([p[0], "--silent"]) k...
%prog spades folder Run automated SPADES.
374,984
def _fetch(self, params, required, defaults): defaults.update(params) pp_params = self._check_and_update_params(required, defaults) pp_string = self.signature + urlencode(pp_params) response = self._request(pp_string) response_params = self._parse_response(response) ...
Make the NVP request and store the response.
374,985
def _check_response(response, expected): response_code = response.status_code if expected == response_code: return if response_code < 400: raise ex.UnexpectedResponseCodeException(response.text) elif response_code == 401: raise ex.Unauthori...
Checks if the expected response code matches the actual response code. If they're not equal, raises the appropriate exception Args: response: (int) Actual status code expected: (int) Expected status code
374,986
def class_in_progress(stack=None): if stack is None: stack = inspect.stack() for frame in stack: statement_list = frame[4] if statement_list is None: continue if statement_list[0].strip().startswith(): return True return False
True if currently inside a class definition, else False.
374,987
async def delete(self, request, resource=None, **kwargs): if resource is None: raise RESTNotFound(reason=) self.collection.remove(resource)
Delete a resource.
374,988
def data_files(self): tf_record_pattern = os.path.join(FLAGS.data_dir, % self.subset) data_files = tf.gfile.Glob(tf_record_pattern) if not data_files: print( % (self.name, self.subset, ...
Returns a python list of all (sharded) data subset files. Returns: python list of all (sharded) data set files. Raises: ValueError: if there are not data_files matching the subset.
374,989
def populate(self): if self.exists: raise CacheAlreadyExistsException( % self.cache_uri) self._populate_setup() with closing(self.graph): with self._download_metadata_archive() as metadata_archive: for fact in self._iter_metadata_triples(metadat...
Populates a new cache.
374,990
def time_col_turbulent(EnergyDis, ConcAl, ConcClay, coag, material, DiamTarget, DIM_FRACTAL): return((1/6) * (6/np.pi)**(1/9) * EnergyDis**(-1/3) * DiamTarget**(2/3) * frac_vol_floc_initial(ConcAl, ConcClay, coag, material)**(-8/9) * (DiamTarget / material.Diameter)...
Calculate single collision time for turbulent flow mediated collisions. Calculated as a function of floc size.
374,991
def registerFilter(self, column, patterns, is_regex=False, ignore_case=False): if isinstance(patterns, basestring): patt_list = (patterns,) elif isinstance(patterns, (tuple, list)): patt_list = list(patterns) else: raise ValueE...
Register filter on a column of table. @param column: The column name. @param patterns: A single pattern or a list of patterns used for matching column values. @param is_regex: The patterns will be treated as regex if True, the ...
374,992
def derenzo_sources(space, min_pt=None, max_pt=None): if space.ndim == 2: return ellipsoid_phantom(space, _derenzo_sources_2d(), min_pt, max_pt) if space.ndim == 3: return ellipsoid_phantom( space, cylinders_from_ellipses(_derenzo_sources_2d()), min_pt, max_pt) e...
Create the PET/SPECT Derenzo sources phantom. The Derenzo phantom contains a series of circles of decreasing size. In 3d the phantom is simply the 2d phantom extended in the z direction as cylinders. Parameters ---------- space : `DiscreteLp` Space in which the phantom should be creat...
374,993
def add_ones(a): arr = N.ones((a.shape[0],a.shape[1]+1)) arr[:,:-1] = a return arr
Adds a column of 1s at the end of the array
374,994
def call_pre_hook(awsclient, cloudformation): if not hasattr(cloudformation, ): return hook_func = getattr(cloudformation, ) if not hook_func.func_code.co_argcount: hook_func() else: log.error( + )
Invoke the pre_hook BEFORE the config is read. :param awsclient: :param cloudformation:
374,995
def get_daemon_stats(self, details=False): logger.debug("Get daemon statistics for %s, %s %s", self.name, self.alive, self.reachable) return self.con.get( % ( if details else ))
Send a HTTP request to the satellite (GET /get_daemon_stats) :return: Daemon statistics :rtype: dict
374,996
def list_items(path_to_directory, pattern, wanted): if not path_to_directory: return set() needed = make_needed(pattern, path_to_directory, wanted) return [os.path.join(path_to_directory, name) for name in _names_in_directory(path_to_directory) if needed(name)]
All items in the given path which match the given glob and are wanted
374,997
def get_sidecar(fname, allowedfileformats=): if allowedfileformats == : allowedfileformats = [, ] for f in allowedfileformats: fname = fname.split(f)[0] fname += if os.path.exists(fname): with open(fname) as fs: sidecar = json.load(fs) else: sidecar ...
Loads sidecar or creates one
374,998
def increase(self, infile): gf = infile[31:] index = gf.index(random.choice(gf)) index_len = len(gf[index]) large_size_index = random.choice([gf.index(g) for g in gf if len(g) > index_len]) gf[index], gf[large_size_index] = gf[large_size_index], gf[index] return ...
Increase: 任意の箇所のバイト列と それより大きなサイズの任意のバイト列と入れ換える
374,999
def getReferenceSetByName(self, name): if name not in self._referenceSetNameMap: raise exceptions.ReferenceSetNameNotFoundException(name) return self._referenceSetNameMap[name]
Returns the reference set with the specified name.