language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static <T, R extends Collection<T>> R reject( Iterable<T> iterable, Predicate<? super T> predicate, R target, boolean allowReorderedResult) { return ParallelIterate.reject( iterable, predicate, target, ...
python
def recvProxyData(self, data): """Write data to server""" if self.initialized: self.sendData(data) else: self.queued_data.append(data)
java
public static <T> Observable<T> map(Observable<?> fromObservable, final T toValue) { if (fromObservable != null) { return fromObservable.subscribeOn(Schedulers.io()) .map(new RXMapper<T>(toValue)); } else { return Observable.empty(); } }
java
private static double[] angleToCbCr(double angle) { double cb = Math.cos(angle); double cr = Math.sin(angle); double acb = Math.abs(cb); double acr = Math.abs(cr); double factor; if (acr > acb) { factor = 0.5 / acr; } else { factor = 0.5 /...
java
public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { if ((iChangeType == DBConstants.AFTER_ADD_TYPE) || (iChangeType == DBConstants.AFTER_UPDATE_TYPE)) if (!this.getOwner().getField(MessageLog.TIMEOUT_TIME).isNull()) { Date timeTimeout = ((Dat...
java
private void cookieError(final OtpLocalNode local, final OtpErlangAtom cookie) throws OtpAuthException { try { @SuppressWarnings("resource") final OtpOutputStream header = new OtpOutputStream(headerLen); // preamble: 4 byte length + "passthrough" tag + version ...
java
@Override public String findNodeId(XPathExpression xpathExpression) throws PortalException { try { return xpathExpression.evaluate(this.layout); } catch (XPathExpressionException e) { throw new PortalException( "Exception while executing XPathExpression: "...
python
def namingConventionDecorator(self, namingConvention): """ :type namingConvention:INamingConvention """ def decoratorFunction(cls): SyntheticClassController(cls).setNamingConvention(namingConvention) return cls return decoratorFunction
python
def logout_handler(self, **args): """Handler for logout button. Delete cookies and return HTML that immediately closes window """ response = make_response( "<html><script>window.close();</script></html>", 200, {'Content-Type': "text/html"}) response.set_c...
java
public void marshall(ExportBundleRequest exportBundleRequest, ProtocolMarshaller protocolMarshaller) { if (exportBundleRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(exportBundleRequest.ge...
java
public final void mT__85() throws RecognitionException { try { int _type = T__85; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalSARL.g:71:7: ( 'strictfp' ) // InternalSARL.g:71:9: 'strictfp' { match("strictfp"); } ...
python
def sectionByID(self, sectionID): """ Returns the :class:`~plexapi.library.LibrarySection` that matches the specified sectionID. Parameters: sectionID (str): ID of the section to return. """ if not self._sectionsByID or sectionID not in self._sectionsByID: ...
python
def posterior_predictive_to_xarray(self): """Convert posterior_predictive samples to xarray.""" posterior = self.posterior posterior_predictive = self.posterior_predictive data = get_draws(posterior, variables=posterior_predictive) return dict_to_dataset(data, library=self.p...
python
def get_stream(self, stream_name: str) -> StreamWrapper: """ Get a :py:class:`StreamWrapper` with the given name. :param stream_name: stream name :return: dataset function name providing the respective stream :raise AttributeError: if the dataset does not provide the function cr...
java
public static void setImage(String path, Map<String, String> attributes) { CmsJSONMap attributesJS = CmsJSONMap.createJSONMap(); for (Entry<String, String> entry : attributes.entrySet()) { attributesJS.put(entry.getKey(), entry.getValue()); } nativeSetImage(path, attributesJ...
python
def template_str(tem, queue=False, **kwargs): ''' Execute the information stored in a string from an sls template CLI Example: .. code-block:: bash salt '*' state.template_str '<Template String>' ''' conflict = _check_queue(queue, kwargs) if conflict is not None: return co...
python
def _return_wrapper(fits, return_all, start, trace): """If the user wants to get all of the models back, this will return a list of the ARIMA models, otherwise it will just return the model. If this is called from the end of the function, ``fits`` will already be a list. We *know* that if a functio...
python
def _VerifyHMAC(self, comms=None): """Verifies the HMAC. This method raises a DecryptionError if the received HMAC does not verify. If the HMAC verifies correctly, True is returned. Args: comms: The comms RdfValue to verify. Raises: DecryptionError: The HMAC did not verify. Retur...
java
public DashedHorizontalLine dashedHorizontalLineInstance() { LineObject lineObject = new LineObject(); DashedHorizontalLine dashedHorizontalLine = lineObject.dashedHorizontalLineInstance(); objectsInstance().add(lineObject); return dashedHorizontalLine; }
java
@RestrictTo(RestrictTo.Scope.LIBRARY) public int incrementDepthBy(String key, int depth) { if (isContainer(key)) { // If it's a container then we added programatically and it isn't a part of the keypath. return 0; } if (!keys.get(depth).equals("**")) { // If it's not a globstar then it i...
java
public final void configure(Properties props, FormatterBuilder formatterBuilder) { Map<URI, ImporterConfig> configs = m_factory.createImporterConfigurations(props, formatterBuilder); m_configs = new ImmutableMap.Builder<URI, ImporterConfig>() .putAll(configs) .putAll(...
python
def diskdata(): """Get total disk size in GB.""" p = os.popen("/bin/df -l -P") ddata = {} tsize = 0 for line in p.readlines(): d = line.split() if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]): tsize = tsize + int(d[1]) ddata["Disk_GB"] = int(tsize...
python
def log_future_exceptions(logger, f, ignore=()): """Log any exceptions set to a future Parameters ---------- logger : logging.Logger instance logger.exception(...) is called if the future resolves with an exception f : Future object Future to be monitored for exceptions ignore :...
python
def create_refobject(self, ): """Create a refobject in the scene that represents the :class:`Reftrack` instance. .. Note:: This will not set the reftrack object. :returns: the created reftrack object :rtype: scene object :raises: None """ parent = self.get_paren...
java
private Address chooseTargetReplica(Collection<Address> excludedAddresses) { final List<Address> replicaAddresses = getReplicaAddresses(excludedAddresses); if (replicaAddresses.isEmpty()) { return null; } final int randomReplicaIndex = ThreadLocalRandomProvider.get().nextInt(...
java
protected Map<String, String> getElementAttributes() { // Preserve order of attributes Map<String, String> attrs = new HashMap<>(); if (this.getName() != null) { attrs.put("name", this.getName()); } if (this.getValue() != null) { attrs.put("value", this.g...
python
def merge(bedfiles): """ given a BED file or list of BED files merge them an return a bedtools object """ if isinstance(bedfiles, list): catted = concat(bedfiles) else: catted = concat([bedfiles]) if catted: return concat(bedfiles).sort().merge() else: return ...
python
def get_value(self, label, takeable=False): """ Retrieve single value at passed index label .. deprecated:: 0.21.0 Please use .at[] or .iat[] accessors. Parameters ---------- index : label takeable : interpret the index as indexers, default False ...
java
public static double[] logs2probs(double[] a) { double max = a[maxIndex(a)]; double sum = 0.0; double[] result = new double[a.length]; for(int i = 0; i < a.length; i++) { result[i] = Math.exp(a[i] - max); sum += result[i]; } normalize(result, sum); return result; }
python
def _create_struct_field(self, env, stone_field): """ This function resolves symbols to objects that we've instantiated in the current environment. For example, a field with data type named "String" is pointed to a String() object. The caller needs to ensure that this stone_fiel...
java
@Override public CommerceWishListItem findByCommerceWishListId_Last( long commerceWishListId, OrderByComparator<CommerceWishListItem> orderByComparator) throws NoSuchWishListItemException { CommerceWishListItem commerceWishListItem = fetchByCommerceWishListId_Last(commerceWishListId, orderByComparator); ...
python
def read(self, include_deleted=False): """Return only read items in the current queryset""" if is_soft_delete() and not include_deleted: return self.filter(unread=False, deleted=False) # When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field. # In this ...
java
public Object[] jcrValues( Property<?> property ) { @SuppressWarnings( "unchecked" ) List<Object> values = (List<Object>)property.getValues(); // convert CMIS values to JCR values switch (property.getType()) { case STRING: return asStrings(values); ...
python
def split_multimol2(mol2_path): r""" Splits a multi-mol2 file into individual Mol2 file contents. Parameters ----------- mol2_path : str Path to the multi-mol2 file. Parses gzip files if the filepath ends on .gz. Returns ----------- A generator object for lists for every ex...
python
def archive_url(self, entity_id, channel=None): '''Generate a URL for the archive of an entity.. @param entity_id The ID of the entity to look up as a string or reference. @param channel Optional channel name. ''' url = '{}/{}/archive'.format(self.url, _get_path(e...
java
@Override public CounterOperation decrement(final String counterName, final long amount) { Preconditions.checkNotNull(counterName); Preconditions.checkArgument(!StringUtils.isBlank(counterName)); Preconditions.checkArgument(amount > 0, "Decrement amounts must be positive!"); // Perform the Decrement final ...
java
@Override public final Map<String, Object> getUserAttributes(final String uid, final IPersonAttributeDaoFilter filter) { if (!this.enabled) { return null; } Validate.notNull(uid, "uid may not be null."); //Get the at...
python
def get_stp_brief_info_output_has_more(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_brief_info = ET.Element("get_stp_brief_info") config = get_stp_brief_info output = ET.SubElement(get_stp_brief_info, "output") has_more = ET.Su...
java
public Object endPoint(Object point, String from, String to) { JSONArray coords = ((JSONArray) ((LinkedHashMap) point) .get("coordinates")); try { double[] xy = GeotoolsUtils.transform( from, to, new double[] { Double.valueOf(String.valueOf(coords.get(0))), Double.valueOf(String...
java
public StyleSheet parse(Object source, NetworkProcessor network, String encoding, SourceType type, URL base) throws IOException, CSSException { if (type == SourceType.INLINE) throw new IllegalArgumentException( "Missing element for INLINE input"); return pars...
python
def generate(self): """ Generates and returns a numeric captcha image in base64 format. Saves the correct answer in `session['captcha_answer']` Use later as: src = captcha.generate() <img src="{{src}}"> """ answer = self.rand.randrange(se...
java
public int getCumulativeProgress(){ int numChildren = getChildCount(); int total = 0; for (int i = 0; i < numChildren; i++) { total += getChildProgress(i); } checkCumulativeSmallerThanMax(maxProgress, total); return total; }
java
public void init(Marshaller marshaller, OperationsFactory operationsFactory, int estimateKeySize, int estimateValueSize, int batchSize) { this.defaultMarshaller = marshaller; this.operationsFactory = operationsFactory; this.estimateKeySize = estimateKeySize; this.estimateValu...
java
public void retrieveMatchingConsumerPoints( SIBUuid12 destUuid, SIBUuid8 cmUuid, JsMessage msg, MessageProcessorSearchResults searchResults) throws SIDiscriminatorSyntaxException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "retrieveMatc...
java
public static boolean reflectionEquals(final Object lhs, final Object rhs, final boolean testTransients, final Class<?> reflectUpToClass, final String... excludeFields) { if (lhs == rhs) { return true; } if (lhs == null || rhs == null) { return false; ...
java
protected String handleClientError(HttpServletRequest request, HttpServletResponse response, RequestClientErrorException cause) throws IOException { final boolean beforeHandlingCommitted = response.isCommitted(); // basically false processClientErrorCallback(request, response, cause); ...
java
static public void close(FileObject fo){ if (fo != null){ try { fo.close(); } catch (FileSystemException e) { log.debug("Exception when closing FileObject: " + fo.getName(), e); } } }
python
def default(self, style_type): """ Return the default style for *style_type* or |None| if no default is defined for that type (not common). """ style = self._element.default_for(style_type) if style is None: return None return StyleFactory(style)
java
File findRepoPath(final String repoAlias) { if ("user".equals(repoAlias)) { return new File(System.getProperty("user.home") + CeylonUtil.PATH_SEPARATOR + ".ceylon/repo"); } else if ("cache".equals(repoAlias)) { return new File(System.getPro...
java
@Override public Byte set(int index, Byte element) { return set(index, element.byteValue()); }
python
def _all_number_groups_are_exactly_present(numobj, normalized_candidate, formatted_number_groups): """Returns True if the groups of digits found in our candidate phone number match our expectations. Arguments: numobj -- the original number we found when parsing normalized_candidate -- the candidate...
java
public <X> DataSet<X> runOperation(CustomUnaryOperation<T, X> operation) { Validate.notNull(operation, "The custom operator must not be null."); operation.setInput(this); return operation.createResult(); }
python
def bethe_fermi_ene(energy, quasipart, shift, hopping, beta): """product of the bethe lattice dos, fermi distribution an weighted by energy""" return energy * bethe_fermi(energy, quasipart, shift, hopping, beta)
python
def old(self): """Assess to the state value(s) at beginning of the time step, which has been processed most recently. When using *HydPy* in the normal manner. But it can be helpful for demonstration and debugging purposes. """ value = getattr(self.fastaccess_old, self.n...
java
public List<TaskSummary> doCriteriaQuery(String userId, UserGroupCallback userGroupCallback, QueryWhere queryWhere) { // 1. create builder and query instances CriteriaBuilder builder = getCriteriaBuilder(); CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery(); // 2. query ba...
python
def api_reference(root_url, service, version): """Generate URL for a Taskcluster api reference.""" root_url = root_url.rstrip('/') if root_url == OLD_ROOT_URL: return 'https://references.taskcluster.net/{}/{}/api.json'.format(service, version) else: return '{}/references/{}/{}/api.json'....
java
protected void scheduleResize() { if (m_updateSizeTimer != null) { m_updateSizeTimer.cancel(); } m_updateSizeTimer = new Timer() { @Override public void run() { updateContentSize(); } }; m_updateSizeTimer.schedule...
java
static PrefsTransform getUtilTransform(TypeName type) { String typeName = type.toString(); // Integer.class.getCanonicalName().equals(typeName) if (Date.class.getCanonicalName().equals(typeName)) { return new DatePrefsTransform(); } if (Locale.class.getCanonicalName().equals(typeName)) { return new Loc...
python
def tax_class_based_on(self, tax_class_based_on): """Sets the tax_class_based_on of this TaxSettings. :param tax_class_based_on: The tax_class_based_on of this TaxSettings. :type: str """ allowed_values = ["shippingAddress", "billingAddress"] # noqa: E501 if tax_class_...
python
def start_step(self, lineno, name="Unnamed step", timestamp=None): """Create a new step and update the state to reflect we're now in the middle of a step.""" self.state = self.STATES['step_in_progress'] self.stepnum += 1 self.steps.append({ "name": name, "started"...
python
def remove_html_tag(input_str='', tag=None): """ Returns a string with the html tag and all its contents from a string """ result = input_str if tag is not None: pattern = re.compile('<{tag}[\s\S]+?/{tag}>'.format(tag=tag)) result = re.sub(pattern, '', str(input_str)) return res...
python
def isubset(self, *keys): # type: (*Hashable) -> ww.g """Return key, self[key] as generator for key in keys. Raise KeyError if a key does not exist Args: keys: Iterable containing keys Example: >>> from ww import d >>> list(d({1: 1, 2: 2, 3...
python
def is_one2one(fmt): """ Runs a check to evaluate if the format string has a one to one correspondence. I.e. that successive composing and parsing opperations will result in the original data. In other words, that input data maps to a string, which then maps back to the original data without an...
java
static int execute(Arg arguments, PrintStream stream, PrintStream errorStream) { if (arguments == null) { return 2; } if (arguments.checkBcryptHash != null) { // verify mode BCrypt.Result result = BCrypt.verifyer().verify(arguments.password, arguments.checkBcryptHash); ...
python
def match_dim_specs(specs1, specs2): """Matches dimension specs used to link axes. Axis dimension specs consists of a list of tuples corresponding to each dimension, each tuple spec has the form (name, label, unit). The name and label must match exactly while the unit only has to match if both spec...
java
public final void setNewVertexValue(VV newValue) { if (setNewVertexValueCalled) { throw new IllegalStateException("setNewVertexValue should only be called at most once per updateVertex"); } setNewVertexValueCalled = true; outVertex.f1 = newValue; out.collect(Either.Left(outVertex)); }
java
public boolean containsKey(Object key, Transaction transaction) throws ObjectManagerException { try { for (Iterator iterator = entrySet().iterator();;) { Entry entry = (Entry) iterator.next(transaction); Object en...
java
@Deprecated public SingleOutputStreamOperator<T> assignTimestamps(TimestampExtractor<T> extractor) { // match parallelism to input, otherwise dop=1 sources could lead to some strange // behaviour: the watermark will creep along very slowly because the elements // from the source go to each extraction operator ro...
python
def get_user_roles(self): """Returns a list of roles for the current user """ if self.is_anonymous_user(): return [] current_user = ploneapi.user.get_current() return ploneapi.user.get_roles(user=current_user)
python
def FormatProblem(self, d=None): """Return a text string describing the problem. Args: d: map returned by GetDictToFormat with with formatting added """ if not d: d = self.GetDictToFormat() output_error_text = self.__class__.ERROR_TEXT % d if ('reason' in d) and d['reason']: ...
java
protected void addImagesToBook(final BuildData buildData, final String locale, final String imageFolder, boolean revertToDefaultLocale, boolean logErrors) { // Load the database constants final byte[] failpenguinPng = blobConstantProvider.getBlobConstant( buildData.getServerE...
python
def parse_limits_list(path, limits): """Parse a structured list of flux limits as obtained from a YAML file Yields tuples of reaction ID, lower and upper flux bounds. Path can be given as a string or a context. """ context = FilePathContext(path) for limit_def in limits: if 'include' ...
python
def receive_response(self, message, insecure=False): """Read the response for the given message. @type message: OmapiMessage @type insecure: bool @param insecure: avoid an OmapiError about a wrong authenticator @rtype: OmapiMessage @raises OmapiError: @raises socket.error: """ response = self.receive_...
python
def show_cimreferences(server_name, server, org_vm): """ Show info about the CIM_ReferencedProfile instances. Goal. Clearly show what the various refs look like by using profile names for the antecedent and dependent rather than instances. """ try: ref_insts = server.conn.EnumerateInstan...
java
@Override public void moduleMetaDataCreated(MetaDataEvent<ModuleMetaData> event) throws MetaDataException { if (!MetaDataUtils.copyModuleMetaDataSlot(event, mmdSlot)) { getModuleBindingMap(event.getMetaData()); } }
python
def timezone(self): """The name of the time zone for the location. A list of time zone names can be obtained from pytz. For example. >>> from pytz import all_timezones >>> for timezone in all_timezones: ... print(timezone) """ if not self._timezone_group an...
python
def install_js(): ''' Copy built BokehJS files into the Python source tree. Returns: None ''' target_jsdir = join(SERVER, 'static', 'js') target_cssdir = join(SERVER, 'static', 'css') target_tslibdir = join(SERVER, 'static', 'lib') STATIC_ASSETS = [ join(JS, 'bokeh.js'), ...
java
protected synchronized void clear() throws ObjectManagerException { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass , "clear" ); super.clear(); managedObjectsOnDisk = n...
java
public boolean showSize() { CmsListItemDetails details = getList().getMetadata().getItemDetailDefinition(LIST_DETAIL_SIZE); return (details != null) && details.isVisible(); }
python
def _freq_parser(self, freq): """ day, hour, min, sec, """ freq = freq.lower().strip() try: if "day" in freq: freq = freq.replace("day", "") return timedelta(days=int(freq)) elif "hour" in freq: freq = freq.r...
java
public TVInfo getTVInfo(int tvID, String language, String... appendToResponse) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); parameters.add(Param.LANGUAGE, language); parameters.add(Param.APPEND, appendToResponse); UR...
java
public Property createProperty(final String name) { final PropertyFactory factory = getFactory(name); if (factory != null) { return factory.createProperty(); } else if (isExperimentalName(name)) { return new XProperty(name); } else if (allowIllegalNames()) { ...
java
public static boolean isOverlappingBefore(final Interval timeRange, final Interval timeRangeToCheck) { return ((timeRange.getStart() != null && timeRange.getStart().isAfter(timeRangeToCheck.getStart())) && (timeRange.getEnd() != null && timeRange.getEnd().isAfter(timeRangeToCheck.getEnd()))); }
python
def setup(db_class, simple_object_cls, primary_keys): """A simple API to configure the metadata""" table_name = simple_object_cls.__name__ column_names = simple_object_cls.FIELDS metadata = MetaData() table = Table(table_name, metadata, *[Column(cname, _get_best_column_type(cname)...
java
public void addMainKeyBehavior() { // Add the read keyed listener to all unique keys with one field Record record = this.getMainRecord(); if (record == null) return; int keyCount = record.getKeyAreaCount(); for (int keyNumber = DBConstants.MAIN_KEY_AREA; keyNumber < key...
java
protected List<PropertyData> getChildPropertiesData(final NodeData nodeData, boolean forcePersistentRead) throws RepositoryException { List<PropertyData> childProperties = null; if (!forcePersistentRead) { childProperties = getCachedCleanChildPropertiesData(nodeData); if (c...
java
public void refresh(ExtensionComponentSet delta) { boolean fireOnChangeListeners = false; synchronized (getLoadLock()) { if (extensions==null) return; // not yet loaded. when we load it, we'll load everything visible by then, so no work needed Collection<Exte...
java
public static Point QuadKeyToTileXY(final String quadKey, final Point reuse) { final Point out = reuse == null ? new Point() : reuse; if (quadKey == null || quadKey.length() == 0) { throw new IllegalArgumentException("Invalid QuadKey: " + quadKey); } int tileX = 0; int tileY = 0; final int zoom = quadKey...
java
@GwtIncompatible("incompatible method") @Nullable public static Properties splitArrayElementsIntoProperties(final String[] array, final String delimiter) { return StringUtils.splitArrayElementsIntoProperties(array, delimiter, null); }
java
String rrToString() { StringBuffer sb = new StringBuffer(); sb.append(priority + " "); sb.append(weight + " "); sb.append(port + " "); sb.append(target); return sb.toString(); }
java
public static Model readPom(String path, JarFile jar) throws AnalysisException { final ZipEntry entry = jar.getEntry(path); Model model = null; if (entry != null) { //should never be null //noinspection CaughtExceptionImmediatelyRethrown try { final PomPar...
java
private String stem(int del, String add, String affix) { int stem_length = yylength() - del; int i = 0; String result=yytext().substring(0,stem_length); if (option(change_case)) { result=result.toLowerCase(); } if (!(add.length()==0)) result+=add; if(option(print_affixes)) { result+...
java
private static void isCompletePartitionKeyPresentInQuery(Queue filterQueue, MetamodelImpl metaModel, EntityMetadata metadata) { Set<String> partitionKeyFields = new HashSet<String>(); populateEmbeddedIdFields(metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType()).getAttrib...
python
def runprofile(mainfunction, output, timeout = 0, calibrate=False): ''' Run the functions profiler and save the result If timeout is greater than 0, the profile will automatically stops after timeout seconds ''' if noprofiler == True: print('ERROR: profiler and/or pstats library missing ...
python
def CheckSameObj(obj0, obj1, LFields=None): """ Check if two variables are the same instance of a ToFu class Checks a list of attributes, provided by LField Parameters ---------- obj0 : tofu object A variable refering to a ToFu object of any class obj1 : tofu object A...
python
def _connect(contact_points=None, port=None, cql_user=None, cql_pass=None, protocol_version=None): ''' Connect to a Cassandra cluster. :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str or list of str :param cql_u...
python
def _migrate0to1(previous: Mapping[str, Any]) -> SettingsMap: """ Migrate to version 1 of the feature flags file. Replaces old IDs with new IDs and sets any False values to None """ next: SettingsMap = {} for s in settings: id = s.id old_id = s.old_id if previous.get(id...
java
static Throwable[] getSuppressed(Throwable throwable) { try { Method getSuppressed = throwable.getClass().getMethod("getSuppressed"); return (Throwable[]) getSuppressed.invoke(throwable); } catch (NoSuchMethodException e) { return new Throwable[0]; } catch (IllegalAccessException e) { ...
python
def highlight_block(context, nodelist, lexer, **kwargs): """ Code is nodelist ``rendered`` in ``context`` Returns highlighted code ``div`` tag from ``HtmlFormatter`` Lexer is guessed by ``lexer`` name arguments are passed into the formatter Syntax:: {% highlight_block [lexer na...
python
async def _wait_for_new(self, entity_type, entity_id): """Wait for a new object to appear in the Model and return it. Waits for an object of type ``entity_type`` with id ``entity_id`` to appear in the model. This is similar to watching for the object using ``block_until``, but uses the...