language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def _lower_expressions_to_between(base_expression): """Return a new expression, with any eligible comparisons lowered to `between` clauses.""" expression_list = list(_extract_conjuction_elements_from_expression(base_expression)) if len(expression_list) == 0: raise AssertionError(u'Received empty exp...
python
def add_to_groups(self, groups=None, all_groups=False, group_type=None): """ Add user to some (typically PLC) groups. Note that, if you add to no groups, the effect is simply to do an "add to organization Everybody group", so we let that be done. :param groups: list of group names the u...
python
def write_notebook_rst(txt, res, fnm, pth): """ Write the converted notebook text `txt` and resources `res` to filename `fnm` in directory `pth`. """ # Extended filename used for output images extfnm = fnm + '_files' # Directory into which output images are written extpth = os.path.join...
python
def aperture_photometry(data, apertures, error=None, mask=None, method='exact', subpixels=5, unit=None, wcs=None): """ Perform aperture photometry on the input data by summing the flux within the given aperture(s). Parameters ---------- data : array_like, `~astropy.units...
python
def gen_dynamic_completions(self, text): """ generates the dynamic values, like the names of resource groups """ try: # pylint: disable=too-many-nested-blocks param = self.leftover_args[-1] # command table specific name arg_name = self.get_arg_name(param) ...
java
private void onFullMiss(Node node) { // Upon accessing an HIR non-resident block X. This is a miss. We remove the HIR resident block // at the bottom of stack Q (it then becomes a non-resident block) and evict it from the cache. // Then, we load the requested block X into the freed buffer and place it at th...
python
def init_progress_bar(self): """Initialize and return a progress bar.""" # Forked worker processes can't show progress bars. disable = MapReduce._forked or not config.PROGRESS_BARS # Don't materialize iterable unless we have to: huge iterables # (e.g. of `KCuts`) eat memory. ...
python
def read_file(filename, binary_mode=False): """Read and return the contents of a file in a single file.read(). :param string filename: The filename of the file to read. :param bool binary_mode: Read from file as bytes or unicode. :returns: The contents of the file. :rtype: string """ mode = 'rb' if binar...
python
def PC_varExplained(Y,standardized=True): """ Run PCA and calculate the cumulative fraction of variance Args: Y: phenotype values standardize: if True, phenotypes are standardized Returns: var: cumulative distribution of variance explained """ # figuring out the number of...
python
def restore_type(self, dtype, sample=None): """Restore type from Pandas """ # Pandas types if pdc.is_bool_dtype(dtype): return 'boolean' elif pdc.is_datetime64_any_dtype(dtype): return 'datetime' elif pdc.is_integer_dtype(dtype): retur...
python
def find_collection_ids( self, search_pattern="", identifier="", page=None, page_size=30 ): """ Fetches a list of all resource IDs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. Th...
java
public ServiceFuture<ConnectionMonitorResultInner> createOrUpdateAsync(String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, final ServiceCallback<ConnectionMonitorResultInner> serviceCallback) { return ServiceFuture.fromResponse(createOrUpdateWith...
python
def getCard(self, name): """ Retrieve card object for given card name. Args: name (str): Name of card to be retrieved. Returns: :class:`.ProjectCard` or None: Project card object. Will return None if the card is not available. """ cards = self.pr...
java
public com.google.protobuf.ByteString getMemberBytes() { java.lang.Object ref = member_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); member_ = b; return b; } e...
python
def partitioned_repertoire(self, direction, partition): """Compute the repertoire of a partitioned mechanism and purview.""" repertoires = [ self.repertoire(direction, part.mechanism, part.purview) for part in partition ] return functools.reduce(np.multiply, reper...
java
@Invalidate public void stop() { for (ServiceRegistration<Template> reg : registrations.values()) { try { reg.unregister(); } catch (Exception e) { //NOSONAR // Ignore it. } } registrations.clear(); }
java
public BitapMatcher substitutionOnlyMatcherFirst(int substitutions, final Sequence sequence, int from, int to) { if (sequence.getAlphabet().size() != patternMask.length) throw new IllegalArgumentException(); return new BitapMatcherImpl(substitutions + 1, from, to) { @Override ...
python
def _process_args_as_rows_or_columns(self, arg, unpack=False): """ We must be able to interpret the args as as either a column name or row number, or sequences thereof. Numpy arrays and slices are also fine. Examples: 'field' 35 [35,55,86] ...
java
public String getAsString() { if (stringName == null) { StringBuilder str = new StringBuilder(); for (int i = 0; i < getLength(); i++) { str.append(names[i].getAsString(true)); } stringName = str.toString(); } return stringName; }
java
static public String capitalize(String string0) { if (string0 == null) { return null; } int length = string0.length(); // if empty string, just return it if (length == 0) { return string0; } else if (length == 1) { return string0.toUppe...
java
@SuppressWarnings("static-method") protected String getGeneratedMemberAccessor(MemberDescription description) { return "get" //$NON-NLS-1$ + Strings.toFirstUpper(description.getElementDescription().getElementType().getSimpleName()) + "()"; //$NON-NLS-1$ }
python
def untar(fname, verbose=True): """ Uunzip and untar a tar.gz file into a subdir of the BIGDATA_PATH directory """ if fname.lower().endswith(".tar.gz"): dirpath = os.path.join(BIGDATA_PATH, os.path.basename(fname)[:-7]) if os.path.isdir(dirpath): return dirpath with tarfile.o...
java
protected JavascriptVarBuilder encodeRow(final FacesContext context, final String rowKey, final JavascriptVarBuilder jsData, final JavascriptVarBuilder jsRowStyle, final JavascriptVarBuilder jsStyle, final JavascriptVarBuilder jsReadOnly, final Sheet sheet, final int rowI...
java
public String getStringAttribute(boolean runtime, String attributeName, Address address) throws Exception { return getAttribute(runtime, attributeName, address).asString(); }
python
def parse(self): """Parse an asset from Earth Engine to STAC item Raises: ValueError -- If asset is not of type Image or ImageCollection Returns: Item -- STAC feature of the Google Earth Engine Asset Collection -- STAC collection of the Google Earth Engine A...
python
def inHouseJoy(self): """ Returns if the object is in its house of joy. """ house = self.house() return props.object.houseJoy[self.obj.id] == house.id
java
private <O extends Featurable> O createFeaturable(Class<O> type, Setup setup) throws NoSuchMethodException { final O featurable = UtilReflection.createReduce(type, services, setup); addFeatures(featurable, services, setup); for (final Feature feature : featurable.getFeatures()) ...
python
def unlist(list_thing, complain=True): """transforms [Something] -> Something. By default, raises a ValueError for any other list values.""" if complain and len(list_thing) > 1: raise ValueError("More than one element in {}".format(list_thing)) elif len(list_thing) == 1: return list_thin...
python
def _GetMemberForOffset(self, offset): """Finds the member whose data includes the provided offset. Args: offset (int): offset in the uncompressed data to find the containing member for. Returns: gzipfile.GzipMember: gzip file member or None if not available. Raises: Value...
java
@Override public CPOption findByC_ERC(long companyId, String externalReferenceCode) throws NoSuchCPOptionException { CPOption cpOption = fetchByC_ERC(companyId, externalReferenceCode); if (cpOption == null) { StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("...
python
def delete(self, changelist=0): """Marks the file for delete :param changelist: Changelist to add the move to :type changelist: :class:`.Changelist` """ cmd = ['delete'] if changelist: cmd += ['-c', str(changelist)] cmd.append(self.depotFile) ...
java
@Override public DeploymentPlanBuilder andDeploy() { String addedKey = getAddedContentKey(); DeploymentActionImpl deployMod = DeploymentActionImpl.getDeployAction(addedKey); return new DeploymentPlanBuilderImpl(this, deployMod); }
java
private static long shallowSizeOfArray(Object array) { long size = NUM_BYTES_ARRAY_HEADER; final int len = Array.getLength(array); if (len > 0) { Class<?> arrayElementClazz = array.getClass().getComponentType(); if (arrayElementClazz.isPrimitive()) { size += (long) len * primitiveS...
java
public boolean isRoundingAvailable(CurrencyUnit currencyUnit, String... providers) { return isRoundingAvailable(RoundingQueryBuilder.of().setProviderNames(providers).setCurrency(currencyUnit).build()); }
python
def _get_ann_labels_data(self, order_ann, bins_ann): """Generate ColumnDataSource dictionary for annular labels. """ if self.yticks is None: return dict(x=[], y=[], text=[], angle=[]) mapping = self._compute_tick_mapping("radius", order_ann, bins_ann) values = [(la...
python
def load_csv(self, url, **kwargs): """Loads csv data in the main dataframe :param url: url of the csv file to load: can be absolute if it starts with ``/`` or relative if it starts with ``./`` :type url: str :param kwargs: ...
python
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
java
static public boolean metaFileExists(FSDatasetInterface dataset, int namespaceId, Block b) throws IOException { return getMetaFile(dataset, namespaceId, b).exists(); }
python
def new_dxrecord(details=None, **kwargs): ''' :rtype: :class:`DXRecord` :param details: The contents of the record to be created. :type details: dict Additional optional parameters not listed: all those under :func:`dxpy.bindings.DXDataObject.new`, except `details`. Creates a new remote r...
python
def sample_t(self,n): """ NAME: sample_t PURPOSE: generate a stripping time (time since stripping); simple implementation could be replaced by more complicated distributions in sub-classes of streamdf INPUT: n - number of points to return OUTPUT:...
java
public void compute() { if (!computable) { throw new RuntimeException("can't re-'compute' experiment results after a 'restore'"); } expt = new MatchExpt[blockers.size()][learners.size()][datasets.size()]; for (int i=0; i<blockers.size(); i++) { Blocker blocker = (Blocker)blockers.get(i); for (int j=0...
python
def guess_winner(self, i): """Guess if a player won. Find what team the player was on. If anyone on their team resigned, assume the player lost. """ for team in self.get_teams(): if i not in team: continue for p in team: if...
python
def _get_certificate_obj(cert): ''' Returns a certificate object based on PEM text. ''' if isinstance(cert, M2Crypto.X509.X509): return cert text = _text_or_file(cert) text = get_pem_entry(text, pem_type='CERTIFICATE') return M2Crypto.X509.load_cert_string(text)
python
def get_dispatcher_event(self, name): """Retrieves an Event object by name Args: name (str): The name of the :class:`Event` or :class:`~pydispatch.properties.Property` object to retrieve Returns: The :class:`Event` instance for the event or property defi...
python
def _websocket_mask_python(mask: bytes, data: bytes) -> bytes: """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This ...
java
@RequestMapping(method = RequestMethod.GET) public ApplicationRegistry getMetrics(@RequestParam Map<String, String> filters) throws IOException { boolean all = filters.get("all") != null; String filterMeterNameRegex = filters.getOrDefault("meterNameRegex", ""); String filterTagNameRegex = filters.getO...
python
def serialized(func): """Write a serializer by yielding each line of output""" @wraps(func) def wrapper(*args, **kwargs): return '\n'.join( ' '.join(parts) if isinstance(parts, tuple) else parts for parts in func(*args, **kwargs) ) return wrapper
java
public void initSchema() { List<Resource> scripts = getScripts("spring.datasource.data", this.properties.getData(), "data"); if (!scripts.isEmpty()) { if (!isEnabled()) { logger.debug("Initialization disabled (not running data scripts)"); return; } String username = this.properties.getDataUsern...
python
def is_numeric(value, minimum = None, maximum = None, **kwargs): """Indicate whether ``value`` is a numeric value. :param value: The value to evaluate. :param minimum: If supplied, will make sure that ``value`` is greater than or equal to this value. ...
python
def locus_features(self, locus): """ Returns all features associated with a locus :param locus: string containing HLA locus. :type locus: ``str`` :rtype: ``dict`` """ features = self.api.list_features(locus=locus) feat_dict = {":".join([a.locus, str(a.ran...
python
def get_last_config_update_time_for_xpaths_output_last_config_update_time_for_xpaths_last_config_update_time(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_last_config_update_time_for_xpaths = ET.Element("get_last_config_update_time_for_xpaths") con...
python
def sum_of_entropies(image, mask, binary_image): """Bin the foreground and background pixels and compute the entropy of the distribution of points among the bins """ mask=mask.copy() mask[np.isnan(image)] = False if not np.any(mask): return 0 # # Clamp the dynamic range of the f...
java
public void taskletFailed(final int taskletId, final Exception e) { final boolean aggregateOnCount; synchronized (stateLock) { failedTasklets.add(new ImmutablePair<>(taskletId, e)); removePendingTaskletReferenceCount(taskletId); aggregateOnCount = aggregateOnCount(); } if (aggregateOn...
python
def auto_filters(cls): """ Adds a dynamic filterclass to a viewset with all auto filters available for the field type that are declared in a tuple auto_filter_fields @auto_filters def class(...): ... auto_filters_fields('id', 'location', 'category') """ msg = 'Viewset mu...
java
public void copyToLocalFile(boolean delSrc, Path src, Path dst) throws IOException { fs.copyToLocalFile(delSrc, src, dst); }
java
protected final String getForCopy(final Class<?> pClass) { if (this.seEntities.contains(pClass) || pClass == Deliv.class || pClass == PayMd.class) { return null; } if (pClass == ServiceSpecifics.class || pClass == GoodsSpecifics.class) { return PrcItemSpecificsRetrieve.class.getSimpleName(...
java
@SuppressWarnings("unchecked") public static Span parse(String text, Options options) { // store now for later =) //_now = options.getNow(); // put the text into a normal format to ease scanning String normalizedText = Chronic.preNormalize(text); // get base tokens for each word List<Token> ...
java
public static String generateTableCopy( String inputTblName, String outputTblName, String inputDbName, String outputDbName, Optional<Map<String, String>> optionalPartitionDMLInfo) { Preconditions.checkArgument(StringUtils.isNotBlank(inputTblName)); Preconditions.checkArgument(Strin...
python
def backprop(self, input_data, df_output, cache=None): """ Backpropagate through the hidden layer **Parameters:** input_data : ``GPUArray`` Input data to compute activations for. df_output : ``GPUArray`` Gradients with respect to the activations of this layer ...
python
def _probe_characteristics(self, conn, services, timeout=5.0): """Probe gatt services for all associated characteristics in a BLE device Args: conn (int): the connection handle to probe services (dict): a dictionary of services produced by probe_services() timeout (f...
java
Stream<DynatraceCustomMetric> writeMeter(Meter meter) { final long wallTime = clock.wallTime(); return StreamSupport.stream(meter.measure().spliterator(), false) .map(Measurement::getValue) .filter(Double::isFinite) .map(value -> createCustomMetric(meter.g...
python
def exec_command(command, **kwargs): """ Executes the given command and send the output to the console :param str|list command: :kwargs: * `shell` (``bool`` = False) -- * `stdin` (``*`` = None) -- * `stdout` (``*`` = None) -- * `stderr` (``*`` = None) -- ...
python
def trailing_range_window(preceding, order_by, group_by=None): """Create a trailing time window for use with aggregate window functions. Parameters ---------- preceding : float or expression of intervals, i.e. ibis.interval(days=1) + ibis.interval(hours=5) order_by : expressions, default No...
python
def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): ''' Check to see if policy exists. CLI Example: .. code-block:: bash salt myminion boto_iam.instance_profile_exists myiprofile ''' conn = _get_conn(region=region, key=key, keyid=keyid, p...
java
@Override public Promise ping(long timeoutMillis, String nodeID) { // Local node? if (this.nodeID.equals(nodeID)) { Tree rsp = new Tree(); long time = System.currentTimeMillis(); rsp.put("time", time); rsp.put("arrived", time); return Promise.resolve(rsp); } // Do we have a transporter? if (...
python
def find_file_format(file_name): """ Returns a tuple with the file path and format found, or (None, None) """ for file_format in Format.ALLOWED: file_path = '.'.join((file_name, file_format)) if os.path.exists(file_path): return file_path, file_for...
java
@SafeVarargs public static <T> T randomFrom(Iterable<T> iterable, T... excludes) { return randomFrom(iterable, Arrays.asList(excludes)); }
java
protected static String getMethodSignature(String methodName, Class<?>[] parameterTypes, Class<?> returnType) { StringBuilder buffer = new StringBuilder(methodName); buffer.append("("); if (parameterTypes != null) { int index = 0; for (Class<?> parameterType : parameterTypes) { buff...
java
public static FailedRequest getFailedRequest(int httpStatus, String contentType, InputStream content) { FailedRequest failure = null; // by default XML is supported if ( contentType != null ) { MediaType mediaType = MediaType.parse(contentType); if ( "xml".equals(mediaType.subtype()) ) { ...
python
def create_cluster(self, node_list, cluster_attrs={}, node_attrs={}): ''' API: create_cluster(self, node_list, cluster_attrs, node_attrs) Description: Creates a cluster from the node given in the node list. Input: node_list: List of nodes in the cluste...
python
def rgb2cmy(self, img, whitebg=False): """transforms image from RGB to CMY""" tmp = img*1.0 if whitebg: tmp = (1.0 - (img - img.min())/(img.max() - img.min())) out = tmp*0.0 out[:,:,0] = (tmp[:,:,1] + tmp[:,:,2])/2.0 out[:,:,1] = (tmp[:,:,0] + tmp[:,:,2])/2.0 ...
java
@Override public ValueComparator compare(Value o) { if (o == null) { return ValueComparator.NOT_EQUAL_TO; } switch (o.getType()) { case ORDINALVALUE: OrdinalValue other = (OrdinalValue) o; if (val == null || other.val == null) { ...
python
def Repository(self, *dirs): """Specify Repository directories to search.""" for d in dirs: if not isinstance(d, SCons.Node.Node): d = self.Dir(d) self.Top.addRepository(d)
java
public static InputStream getResourceAsStream(String resourcePath, Object source) throws FileNotFoundException { // Try the current classloader InputStream is = source.getClass().getResourceAsStream(resourcePath); // Weblogic 10 likes this one better.. if (null == is) { ClassLoader cl = source.getClass().g...
python
def replace_with(self, other): """ Replace this instance with the given other. Deletes stale Match objects and updates related TextLogErrorMetadatas' best_classifications to point to the given other. """ match_ids_to_delete = list(self.update_matches(other)) Text...
java
public static <T> void copy(final T source, final T target) { if (isEmpty(source) || isEmpty(target)) { return; } int sourceLength = Array.getLength(source); int targetLength = Array.getLength(target); int minLenght = Math.min(sourceLength, targetLength); copy(source, target, 0, 0, minLen...
python
def add_isosurface_grid_data(self, data, origin, extent, resolution, isolevel=0.3, scale=10, style="wireframe", color=0xffffff): """ Add an isosurface to current scence using pre-computed data on a grid """ spacing = np.ar...
java
public String getValue() { return years + " years " + months + " mons " + days + " days " + hours + " hours " + minutes + " mins " + secondsFormat.format(seconds) + " secs"; }
python
def format_(blocks): """Produce Python module from blocks of tests Arguments: blocks (list): Blocks of tests from func:`parse()` """ tests = list() function_count = 0 # For each test to have a unique name for block in blocks: # Validate docstring format of body if n...
java
public static String padStartDateStr(String timestamp) { return boundTimestamp(padDigits(timestamp,LOWER_TIMESTAMP_LIMIT, UPPER_TIMESTAMP_LIMIT,LOWER_TIMESTAMP_LIMIT)); }
python
def add_textbox(self, id_, name, x, y, cx, cy): """ Append a newly-created textbox ``<p:sp>`` shape having the specified position and size. """ sp = CT_Shape.new_textbox_sp(id_, name, x, y, cx, cy) self.insert_element_before(sp, 'p:extLst') return sp
python
def get_to(self, ins): """ Resolve the output attribute value for 'chromosome_id'. Valid values are immutable, ie. the attribute key is not an actual entity. Mutable values will be changed to match the immutable value if unique. Otherwise an error is thrown. :param ins: iterable...
python
def fail_unknown_tag(self, name, lineno=None): """Called if the parser encounters an unknown tag. Tries to fail with a human readable error message that could help to identify the problem. """ return self._fail_ut_eof(name, self._end_token_stack, lineno)
python
def unflag_field(self, move_x, move_y): """Unflag or unquestion a grid by given position.""" field_status = self.info_map[move_y, move_x] if field_status == 9 or field_status == 10: self.info_map[move_y, move_x] = 11
java
boolean deleteIndexEntry(S userStorable) throws PersistException { try { return makeIndexEntry(userStorable).tryDelete(); } catch (PersistException e) { Throwable cause = e.getCause(); if (cause instanceof IllegalArgumentException) { // Can be ca...
java
private void loadSeqEvalParameters() { this.seqevalParser.addArgument("--metric").required(false) .choices("accuracy", "fmeasure").setDefault("fmeasure").help( "Choose evaluation metric for Sequence Labeler; it defaults to fmeasure.\n"); this.seqevalParser.addArgument("-l", "--language").req...
python
def _perform_scan(args, plugins): """ :param args: output of `argparse.ArgumentParser.parse_args` :param plugins: tuple of initialized plugins :rtype: dict """ old_baseline = _get_existing_baseline(args.import_filename) if old_baseline: plugins = initialize.merge_plugin_from_baselin...
java
protected final int isLeft(double[] a, double[] b, double[] o) { final double cross = getRX(a, o) * getRY(b, o) - getRY(a, o) * getRX(b, o); if(cross == 0) { // Compare manhattan distances - same angle! final double dista = Math.abs(getRX(a, o)) + Math.abs(getRY(a, o)); final double distb = Ma...
java
public TimeStats resetSpentTime(Object projectIdOrPath, Integer issueIid) throws GitLabApiException { if (issueIid == null) { throw new RuntimeException("issue IID cannot be null"); } Response response = post(Response.Status.OK, new GitLabApiForm().asMap(), "project...
java
@SuppressWarnings("unchecked") public EList<IfcSimpleValue> getParameter() { return (EList<IfcSimpleValue>) eGet(Ifc2x3tc1Package.Literals.IFC_TEXTURE_COORDINATE_GENERATOR__PARAMETER, true); }
java
private void checkBasicConstraints(X509Certificate currCert) throws CertPathValidatorException { String msg = "basic constraints"; if (debug != null) { debug.println("---checking " + msg + "..."); debug.println("i = " + i + ", maxPathLength = "...
java
private String getNextTypeName(String className, String groupName, String sequenceName, boolean isLast){ if (isLast) return groupName == null ? className + "Complete" : className; else return className + firstToUpper(sequenceName); }
python
def submit(self, retry_jobs=None): """ Submits all jobs. When *retry_jobs* is *None*, a new job list is built. Otherwise, previously failed jobs defined in the *retry_jobs* dictionary, which maps job numbers to lists of branch numbers, are used. """ task = self.task ...
java
public static final BigInteger printConstraintType(ConstraintType value) { return (value == null ? null : BigInteger.valueOf(value.getValue())); }
python
def start_heartbeat(self): """ Reset hearbeat timer """ self.stop_heartbeat() self._heartbeat_timer = task.LoopingCall(self._heartbeat) self._heartbeat_timer.start(self._heartbeat_interval, False)
python
def write_to_socket(self, frame_data): """Write data to the socket. :param str frame_data: :return: """ self._wr_lock.acquire() try: total_bytes_written = 0 bytes_to_send = len(frame_data) while total_bytes_written < bytes_to_send: ...
python
def load_registry(self, fname): """ Load entries from a file and add them to the registry. Use this if you are managing many files. Each line of the file should have file name and its SHA256 hash separate by a space. Only one file per line is allowed. Custom download URLs for i...
java
public Record openMainRecord() { if (this.getProperty("recordClass") != null) { String strClassName = this.getProperty("recordClass"); if (strClassName != null) return Record.makeRecordFromClassName(strClassName, this); } return sup...
python
def connected(): ''' List all connected minions on a salt-master ''' opts = salt.config.master_config(__opts__['conf_file']) if opts.get('con_cache'): cache_cli = CacheCli(opts) minions = cache_cli.get_cached() else: minions = list(salt.utils.minions.CkMinions(opts).conn...
python
def json_url_error_handler(urls=()): """ Closure: Json URL error handler Checks if request matches provided url prefix and returns json response if it does. Otherwise falls back to template error handler. This is usefull if you want to return json errors for a subset of your routes. Register th...