_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q24000
GitDirLocator.findProjectGitDirectory
train
@Nullable private File findProjectGitDirectory() { if (this.mavenProject == null) { return null; } File basedir = mavenProject.getBasedir(); while (basedir != null) { File gitdir = new File(basedir, Constants.DOT_GIT); if (gitdir.exists()) { if (gitdir.isDirectory()) { ...
java
{ "resource": "" }
q24001
GitRepositoryState.toJson
train
public String toJson() { StringBuilder sb = new StringBuilder("{"); appendProperty(sb, "branch", branch); appendProperty(sb, "commitId", commitId); appendProperty(sb, "commitIdAbbrev", commitIdAbbrev); appendProperty(sb, "commitTime", commitTime); appendProperty(sb, "commitUserName", commitUser...
java
{ "resource": "" }
q24002
Handler.markIsTransaction
train
private synchronized boolean markIsTransaction(String channelId, String uuid, boolean isTransaction) { if (this.isTransaction == null) { return false; } String key = getTxKey(channelId, uuid); this.isTransaction.put(key, isTransaction); return true; }
java
{ "resource": "" }
q24003
Handler.getState
train
ByteString getState(String channelId, String txId, String collection, String key) { return invokeChaincodeSupport(newGetStateEventMessage(channelId, txId, collection, key)); }
java
{ "resource": "" }
q24004
SimpleChaincode.delete
train
private Response delete(ChaincodeStub stub, List<String> args) { if (args.size() != 1) { return newErrorResponse("Incorrect number of arguments. Expecting 1"); } String key = args.get(0); // Delete the key from the state in ledger stub.delState(key); return newSuccessResponse(); }
java
{ "resource": "" }
q24005
StateBasedEndorsementUtils.nOutOf
train
static SignaturePolicy nOutOf(int n, List<SignaturePolicy> policies) { return SignaturePolicy .newBuilder() .setNOutOf(NOutOf .newBuilder() .setN(n) .addAllRules(policies) .build()) ...
java
{ "resource": "" }
q24006
SimpleChaincode.query
train
private Response query(ChaincodeStub stub, List<String> args) { if (args.size() != 1) { return newErrorResponse("Incorrect number of arguments. Expecting name of the person to query"); } String key = args.get(0); //byte[] stateBytes String val = stub.getStringState(ke...
java
{ "resource": "" }
q24007
SimpleAsset.init
train
@Override public Response init(ChaincodeStub stub) { try { // Get the args from the transaction proposal List<String> args = stub.getParameters(); if (args.size() != 2) { newErrorResponse("Incorrect arguments. Expecting a key and a value"); } ...
java
{ "resource": "" }
q24008
SimpleAsset.invoke
train
@Override public Response invoke(ChaincodeStub stub) { try { // Extract the function and args from the transaction proposal String func = stub.getFunction(); List<String> params = stub.getParameters(); if (func.equals("set")) { // Return result...
java
{ "resource": "" }
q24009
SimpleAsset.get
train
private String get(ChaincodeStub stub, List<String> args) { if (args.size() != 1) { throw new RuntimeException("Incorrect arguments. Expecting a key"); } String value = stub.getStringState(args.get(0)); if (value == null || value.isEmpty()) { throw new RuntimeExc...
java
{ "resource": "" }
q24010
Mail.addContent
train
public void addContent(Content content) { Content newContent = new Content(); newContent.setType(content.getType()); newContent.setValue(content.getValue()); this.content = addToList(newContent, this.content); }
java
{ "resource": "" }
q24011
Mail.addAttachments
train
public void addAttachments(Attachments attachments) { Attachments newAttachment = new Attachments(); newAttachment.setContent(attachments.getContent()); newAttachment.setType(attachments.getType()); newAttachment.setFilename(attachments.getFilename()); newAttachment.setDisposition(attachments.getDis...
java
{ "resource": "" }
q24012
Mail.addSection
train
public void addSection(String key, String value) { this.sections = addToMap(key, value, this.sections); }
java
{ "resource": "" }
q24013
Mail.addHeader
train
public void addHeader(String key, String value) { this.headers = addToMap(key, value, this.headers); }
java
{ "resource": "" }
q24014
Mail.addCustomArg
train
public void addCustomArg(String key, String value) { this.customArgs = addToMap(key, value, this.customArgs); }
java
{ "resource": "" }
q24015
Mail.buildPretty
train
public String buildPretty() throws IOException { try { ObjectMapper mapper = new ObjectMapper(); return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this); } catch (IOException ex) { throw ex; } }
java
{ "resource": "" }
q24016
SendGrid.addRequestHeader
train
public Map<String, String> addRequestHeader(String key, String value) { this.requestHeaders.put(key, value); return getRequestHeaders(); }
java
{ "resource": "" }
q24017
SendGrid.removeRequestHeader
train
public Map<String, String> removeRequestHeader(String key) { this.requestHeaders.remove(key); return getRequestHeaders(); }
java
{ "resource": "" }
q24018
SendGrid.api
train
public Response api(Request request) throws IOException { Request req = new Request(); req.setMethod(request.getMethod()); req.setBaseUri(this.host); req.setEndpoint("/" + version + "/" + request.getEndpoint()); req.setBody(request.getBody()); for (Map.Entry<String, String> header : this.request...
java
{ "resource": "" }
q24019
SendGrid.attempt
train
public void attempt(Request request) { this.attempt(request, new APICallback() { @Override public void error(Exception ex) { } public void response(Response r) { } }); }
java
{ "resource": "" }
q24020
SendGrid.attempt
train
public void attempt(final Request request, final APICallback callback) { this.pool.execute(new Runnable() { @Override public void run() { Response response; // Retry until the retry limit has been reached. for (int i = 0; i < rateLimitRetry; ++i) { try { re...
java
{ "resource": "" }
q24021
Example.buildDynamicTemplate
train
public static Mail buildDynamicTemplate() throws IOException { Mail mail = new Mail(); Email fromEmail = new Email(); fromEmail.setName("Example User"); fromEmail.setEmail("test@example.com"); mail.setFrom(fromEmail); mail.setTemplateId("d-c6dcf1f72bdd4beeb15a9aa6c72fcd2c"); Personalizati...
java
{ "resource": "" }
q24022
Example.buildHelloEmail
train
public static Mail buildHelloEmail() throws IOException { Email from = new Email("test@example.com"); String subject = "Hello World from the SendGrid Java Library"; Email to = new Email("test@example.com"); Content content = new Content("text/plain", "some text here"); // Note that when you use this...
java
{ "resource": "" }
q24023
SymbolOptions.withLatLng
train
public SymbolOptions withLatLng(LatLng latLng) { geometry = Point.fromLngLat(latLng.getLongitude(), latLng.getLatitude()); return this; }
java
{ "resource": "" }
q24024
SymbolOptions.getLatLng
train
public LatLng getLatLng() { if (geometry == null) { return null; } return new LatLng(geometry.latitude(), geometry.longitude()); }
java
{ "resource": "" }
q24025
PlaceAutocomplete.clearRecentHistory
train
public static void clearRecentHistory(Context context) { SearchHistoryDatabase database = SearchHistoryDatabase.getInstance(context); SearchHistoryDatabase.deleteAllData(database); }
java
{ "resource": "" }
q24026
AnnotationManager.create
train
@UiThread public T create(S options) { T t = options.build(currentId, this); annotations.put(t.getId(), t); currentId++; updateSource(); return t; }
java
{ "resource": "" }
q24027
AnnotationManager.create
train
@UiThread public List<T> create(List<S> optionsList) { List<T> annotationList = new ArrayList<>(); for (S options : optionsList) { T annotation = options.build(currentId, this); annotationList.add(annotation); annotations.put(annotation.getId(), annotation); currentId++; } upda...
java
{ "resource": "" }
q24028
AnnotationManager.delete
train
@UiThread public void delete(List<T> annotationList) { for (T annotation : annotationList) { annotations.remove(annotation.getId()); } updateSource(); }
java
{ "resource": "" }
q24029
AnnotationManager.update
train
@UiThread public void update(T annotation) { if (annotations.containsValue(annotation)) { annotations.put(annotation.getId(), annotation); updateSource(); } else { Logger.e(TAG, "Can't update annotation: " + annotation.toString() + ", the annotation isn't active annotation.")...
java
{ "resource": "" }
q24030
AnnotationManager.update
train
@UiThread public void update(List<T> annotationList) { for (T annotation : annotationList) { annotations.put(annotation.getId(), annotation); } updateSource(); }
java
{ "resource": "" }
q24031
AnnotationManager.onDestroy
train
@UiThread public void onDestroy() { mapboxMap.removeOnMapClickListener(mapClickResolver); mapboxMap.removeOnMapLongClickListener(mapClickResolver); dragListeners.clear(); clickListeners.clear(); longClickListeners.clear(); }
java
{ "resource": "" }
q24032
OfflineDownloadOptions.builder
train
public static Builder builder() { return new AutoValue_OfflineDownloadOptions.Builder() .uuid(UUID.randomUUID().getMostSignificantBits()) .metadata(new byte[] {}) .progress(0); // TODO user must provide a notificationOptions object }
java
{ "resource": "" }
q24033
FillOptions.withLatLngs
train
public FillOptions withLatLngs(List<List<LatLng>> latLngs) { List<List<Point>> points = new ArrayList<>(); for (List<LatLng> innerLatLngs : latLngs) { List<Point>innerList = new ArrayList<>(); for (LatLng latLng : innerLatLngs) { innerList.add(Point.fromLngLat(latLng.getLongitude(), latLng.g...
java
{ "resource": "" }
q24034
TrafficPlugin.setVisibility
train
public void setVisibility(boolean visible) { this.visible = visible; if (!style.isFullyLoaded()) { // We are in progress of loading a new style return; } Source source = style.getSource(TrafficData.SOURCE_ID); if (source == null) { initialise(); } List<Layer> layers = st...
java
{ "resource": "" }
q24035
TrafficPlugin.initialise
train
private void initialise() { try { addTrafficSource(); addTrafficLayers(); } catch (Exception exception) { Timber.e(exception, "Unable to attach Traffic to current style: "); } catch (UnsatisfiedLinkError error) { Timber.e(error, "Unable to load native libraries: "); } }
java
{ "resource": "" }
q24036
TrafficPlugin.addTrafficSource
train
private void addTrafficSource() { VectorSource trafficSource = new VectorSource(TrafficData.SOURCE_ID, TrafficData.SOURCE_URL); style.addSource(trafficSource); }
java
{ "resource": "" }
q24037
TrafficPlugin.addLocalLayer
train
private void addLocalLayer() { LineLayer local = TrafficLayer.getLineLayer( Local.BASE_LAYER_ID, Local.ZOOM_LEVEL, Local.FILTER, Local.FUNCTION_LINE_COLOR, Local.FUNCTION_LINE_WIDTH, Local.FUNCTION_LINE_OFFSET ); LineLayer localCase = TrafficLayer.getLineLayer( Loc...
java
{ "resource": "" }
q24038
TrafficPlugin.placeLayerBelow
train
private String placeLayerBelow() { if (belowLayer == null || belowLayer.isEmpty()) { List<Layer> styleLayers = style.getLayers(); Layer layer; for (int i = styleLayers.size() - 1; i >= 0; i--) { layer = styleLayers.get(i); if (!(layer instanceof SymbolLayer)) { return lay...
java
{ "resource": "" }
q24039
TrafficPlugin.addSecondaryLayer
train
private void addSecondaryLayer() { LineLayer secondary = TrafficLayer.getLineLayer( Secondary.BASE_LAYER_ID, Secondary.ZOOM_LEVEL, Secondary.FILTER, Secondary.FUNCTION_LINE_COLOR, Secondary.FUNCTION_LINE_WIDTH, Secondary.FUNCTION_LINE_OFFSET ); LineLayer secondaryCase = ...
java
{ "resource": "" }
q24040
TrafficPlugin.addPrimaryLayer
train
private void addPrimaryLayer() { LineLayer primary = TrafficLayer.getLineLayer( Primary.BASE_LAYER_ID, Primary.ZOOM_LEVEL, Primary.FILTER, Primary.FUNCTION_LINE_COLOR, Primary.FUNCTION_LINE_WIDTH, Primary.FUNCTION_LINE_OFFSET ); LineLayer primaryCase = TrafficLayer.getLi...
java
{ "resource": "" }
q24041
TrafficPlugin.addTrunkLayer
train
private void addTrunkLayer() { LineLayer trunk = TrafficLayer.getLineLayer( Trunk.BASE_LAYER_ID, Trunk.ZOOM_LEVEL, Trunk.FILTER, Trunk.FUNCTION_LINE_COLOR, Trunk.FUNCTION_LINE_WIDTH, Trunk.FUNCTION_LINE_OFFSET ); LineLayer trunkCase = TrafficLayer.getLineLayer( Tru...
java
{ "resource": "" }
q24042
TrafficPlugin.addMotorwayLayer
train
private void addMotorwayLayer() { LineLayer motorWay = TrafficLayer.getLineLayer( MotorWay.BASE_LAYER_ID, MotorWay.ZOOM_LEVEL, MotorWay.FILTER, MotorWay.FUNCTION_LINE_COLOR, MotorWay.FUNCTION_LINE_WIDTH, MotorWay.FUNCTION_LINE_OFFSET ); LineLayer motorwayCase = TrafficLa...
java
{ "resource": "" }
q24043
TrafficPlugin.addTrafficLayersToMap
train
private void addTrafficLayersToMap(Layer layerCase, Layer layer, String idAboveLayer) { style.addLayerBelow(layerCase, idAboveLayer); style.addLayerAbove(layer, layerCase.getId()); layerIds.add(layerCase.getId()); layerIds.add(layer.getId()); }
java
{ "resource": "" }
q24044
OfflinePlugin.cancelDownload
train
public void cancelDownload(OfflineDownloadOptions offlineDownload) { Intent intent = new Intent(context, OfflineDownloadService.class); intent.setAction(OfflineConstants.ACTION_CANCEL_DOWNLOAD); intent.putExtra(KEY_BUNDLE, offlineDownload); context.startService(intent); }
java
{ "resource": "" }
q24045
OfflinePlugin.getActiveDownloadForOfflineRegion
train
@Nullable public OfflineDownloadOptions getActiveDownloadForOfflineRegion(OfflineRegion offlineRegion) { OfflineDownloadOptions offlineDownload = null; if (!offlineDownloads.isEmpty()) { for (OfflineDownloadOptions download : offlineDownloads) { if (download.uuid() == offlineRegion.getID()) { ...
java
{ "resource": "" }
q24046
OfflinePlugin.removeDownload
train
void removeDownload(OfflineDownloadOptions offlineDownload, boolean canceled) { if (canceled) { stateChangeDispatcher.onCancel(offlineDownload); } else { stateChangeDispatcher.onSuccess(offlineDownload); } offlineDownloads.remove(offlineDownload); }
java
{ "resource": "" }
q24047
OfflinePlugin.errorDownload
train
void errorDownload(OfflineDownloadOptions offlineDownload, String error, String errorMessage) { stateChangeDispatcher.onError(offlineDownload, error, errorMessage); offlineDownloads.remove(offlineDownload); }
java
{ "resource": "" }
q24048
BuildingPlugin.initLayer
train
private void initLayer(String belowLayer) { light = style.getLight(); fillExtrusionLayer = new FillExtrusionLayer(LAYER_ID, "composite"); fillExtrusionLayer.setSourceLayer("building"); fillExtrusionLayer.setMinZoom(minZoomLevel); fillExtrusionLayer.setProperties( visibility(visible ? VISIBLE :...
java
{ "resource": "" }
q24049
BuildingPlugin.setVisibility
train
public void setVisibility(boolean visible) { this.visible = visible; if (!style.isFullyLoaded()) { // We are in progress of loading a new style return; } fillExtrusionLayer.setProperties(visibility(visible ? VISIBLE : NONE)); }
java
{ "resource": "" }
q24050
BuildingPlugin.setOpacity
train
public void setOpacity(@FloatRange(from = 0.0f, to = 1.0f) float opacity) { this.opacity = opacity; if (!style.isFullyLoaded()) { // We are in progress of loading a new style return; } fillExtrusionLayer.setProperties(fillExtrusionOpacity(opacity)); }
java
{ "resource": "" }
q24051
BuildingPlugin.setMinZoomLevel
train
public void setMinZoomLevel(@FloatRange(from = MINIMUM_ZOOM, to = MAXIMUM_ZOOM) float minZoomLevel) { this.minZoomLevel = minZoomLevel; if (!style.isFullyLoaded()) { // We are in progress of loading a new style return; } fillExtrusionLayer.setMinZoom(minZoomL...
java
{ "resource": "" }
q24052
OfflineDownloadService.finishDownload
train
void finishDownload(OfflineDownloadOptions offlineDownload, OfflineRegion offlineRegion) { OfflineDownloadStateReceiver.dispatchSuccessBroadcast(this, offlineDownload); offlineRegion.setDownloadState(OfflineRegion.STATE_INACTIVE); offlineRegion.setObserver(null); removeOfflineRegion(offlineDownload.uuid...
java
{ "resource": "" }
q24053
LocalizationPlugin.sourceIsFromMapbox
train
private boolean sourceIsFromMapbox(Source singleSource) { if (singleSource instanceof VectorSource) { String url = ((VectorSource) singleSource).getUrl(); if (url != null) { for (String supportedSource : SUPPORTED_SOURCES) { if (url.contains(supportedSource)) { return true;...
java
{ "resource": "" }
q24054
PgConnectionFactory.close
train
private void close(Handler<AsyncResult<Void>> completionHandler) { client.close(); completionHandler.handle(Future.succeededFuture()); }
java
{ "resource": "" }
q24055
PgConnectOptions.init
train
private void init() { host = DEFAULT_HOST; port = DEFAULT_PORT; database = DEFAULT_DATABASE; user = DEFAULT_USER; password = DEFAULT_PASSWORD; cachePreparedStatements = DEFAULT_CACHE_PREPARED_STATEMENTS; pipeliningLimit = DEFAULT_PIPELINING_LIMIT; sslMode = DEFAULT_SSLMODE; }
java
{ "resource": "" }
q24056
DataTypeCodec.textDecodeMultiplePoints
train
private static List<Point> textDecodeMultiplePoints(int index, int len, ByteBuf buff) { // representation: p1,p2,p3...pn List<Point> points = new ArrayList<>(); int start = index; int end = index + len - 1; while (start < end) { int rightParenthesis = buff.indexOf(start, end + 1, (byte) ')'); ...
java
{ "resource": "" }
q24057
PgConnectionUriParser.doParse
train
private static void doParse(String connectionUri, JsonObject configuration) { Pattern pattern = Pattern.compile(FULL_URI_REGEX); Matcher matcher = pattern.matcher(connectionUri); if (matcher.matches()) { // parse the user and password parseUserandPassword(matcher.group(USER_INFO_GROUP), configu...
java
{ "resource": "" }
q24058
MapBuilder.addNumber
train
public MapBuilder addNumber(String fieldName, boolean include, Supplier<Number> supplier) { if (include) { Number value = supplier.get(); if (value != null) { map.put(getFieldName(fieldName), value); } } return this; }
java
{ "resource": "" }
q24059
MapBuilder.addMap
train
public MapBuilder addMap(String fieldName, boolean include, Supplier<Map<String, ?>> supplier) { if (include) { Map<String, ?> value = supplier.get(); if (value != null && !value.isEmpty()) { map.put(getFieldName(fieldName), value); } } return ...
java
{ "resource": "" }
q24060
MapBuilder.addTimestamp
train
public MapBuilder addTimestamp(String fieldName, boolean include, long timestamp) { if (include && timestamp > 0) { map.put(getFieldName(fieldName), timestampFormatter.format(timestamp)); } return this; }
java
{ "resource": "" }
q24061
Command.onError
train
public void onError(Cli cli, Namespace namespace, Throwable e) { e.printStackTrace(cli.getStdErr()); }
java
{ "resource": "" }
q24062
CachingAuthorizer.invalidate
train
public void invalidate(P principal, String role) { cache.invalidate(ImmutablePair.of(principal, role)); }
java
{ "resource": "" }
q24063
CachingAuthorizer.invalidate
train
public void invalidate(P principal) { final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream() .filter(cacheKey -> cacheKey.getLeft().equals(principal)) .collect(Collectors.toSet()); cache.invalidateAll(keys); }
java
{ "resource": "" }
q24064
CachingAuthorizer.invalidateAll
train
public void invalidateAll(Iterable<P> principals) { final Set<P> principalSet = Sets.of(principals); final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream() .filter(cacheKey -> principalSet.contains(cacheKey.getLeft())) .collect(Collectors.toSet()); ...
java
{ "resource": "" }
q24065
CachingAuthorizer.invalidateAll
train
public void invalidateAll(Predicate<? super P> predicate) { final Set<ImmutablePair<P, String>> keys = cache.asMap().keySet().stream() .filter(cacheKey -> predicate.test(cacheKey.getLeft())) .collect(Collectors.toSet()); cache.invalidateAll(keys); }
java
{ "resource": "" }
q24066
HttpsConnectorFactory.logSslInfoOnStart
train
protected AbstractLifeCycle.AbstractLifeCycleListener logSslInfoOnStart(final SslContextFactory sslContextFactory) { return new AbstractLifeCycle.AbstractLifeCycleListener() { @Override public void lifeCycleStarted(LifeCycle event) { logSupportedParameters(sslContextFacto...
java
{ "resource": "" }
q24067
ConstraintMessage.getMessage
train
public static String getMessage(ConstraintViolation<?> v, Invocable invocable) { final Pair<Path, ? extends ConstraintDescriptor<?>> of = Pair.of(v.getPropertyPath(), v.getConstraintDescriptor()); final String cachePrefix = PREFIX_CACHE.getIfPresent(of); if (cachePrefix == null) ...
java
{ "resource": "" }
q24068
ConstraintMessage.getMethodReturnValueName
train
private static Optional<String> getMethodReturnValueName(ConstraintViolation<?> violation) { int returnValueNames = -1; final StringBuilder result = new StringBuilder("server response"); for (Path.Node node : violation.getPropertyPath()) { if (node.getKind().equals(ElementKind.RETUR...
java
{ "resource": "" }
q24069
ServletEnvironment.addServlet
train
public ServletRegistration.Dynamic addServlet(String name, Servlet servlet) { final ServletHolder holder = new NonblockingServletHolder(requireNonNull(servlet)); holder.setName(name); handler.getServletHandler().addServlet(holder); final ServletRegistration.Dynamic registration = holder...
java
{ "resource": "" }
q24070
ServletEnvironment.addFilter
train
public FilterRegistration.Dynamic addFilter(String name, Filter filter) { return addFilter(name, new FilterHolder(requireNonNull(filter))); }
java
{ "resource": "" }
q24071
ServletEnvironment.addFilter
train
public FilterRegistration.Dynamic addFilter(String name, Class<? extends Filter> klass) { return addFilter(name, new FilterHolder(requireNonNull(klass))); }
java
{ "resource": "" }
q24072
ServletEnvironment.setProtectedTargets
train
public void setProtectedTargets(String... targets) { handler.setProtectedTargets(Arrays.copyOf(targets, targets.length)); }
java
{ "resource": "" }
q24073
ServletEnvironment.setSessionHandler
train
public void setSessionHandler(SessionHandler sessionHandler) { handler.setSessionsEnabled(sessionHandler != null); handler.setSessionHandler(sessionHandler); }
java
{ "resource": "" }
q24074
ServletEnvironment.setSecurityHandler
train
public void setSecurityHandler(SecurityHandler securityHandler) { handler.setSecurityEnabled(securityHandler != null); handler.setSecurityHandler(securityHandler); }
java
{ "resource": "" }
q24075
ServletEnvironment.addMimeMapping
train
public void addMimeMapping(String extension, String type) { handler.getMimeTypes().addMimeMapping(extension, type); }
java
{ "resource": "" }
q24076
JerseyParameterNameProvider.getParameterNameFromAnnotations
train
public static Optional<String> getParameterNameFromAnnotations(Annotation[] memberAnnotations) { for (Annotation a : memberAnnotations) { if (a instanceof QueryParam) { return Optional.of("query param " + ((QueryParam) a).value()); } else if (a instanceof PathParam) { ...
java
{ "resource": "" }
q24077
OAuthCredentialAuthFilter.getCredentials
train
@Nullable private String getCredentials(String header) { if (header == null) { return null; } final int space = header.indexOf(' '); if (space <= 0) { return null; } final String method = header.substring(0, space); if (!prefix.equals...
java
{ "resource": "" }
q24078
Generics.getTypeParameter
train
public static <T> Class<T> getTypeParameter(Class<?> klass, Class<? super T> bound) { Type t = requireNonNull(klass); while (t instanceof Class<?>) { t = ((Class<?>) t).getGenericSuperclass(); } /* This is not guaranteed to work for all cases with convoluted piping *...
java
{ "resource": "" }
q24079
DefaultLoggingFactory.clear
train
void clear() { // This is volatile, read once for performance. final String name = loggerName; if (name != null) { CHANGE_LOGGER_CONTEXT_LOCK.lock(); try { loggerContext.stop(); final Logger logger = loggerContext.getLogger(org.slf4j.Logg...
java
{ "resource": "" }
q24080
LogConfigurationTask.getTimer
train
@Nonnull private Timer getTimer() { return timerReference.updateAndGet(timer -> timer == null ? new Timer(LogConfigurationTask.class.getSimpleName(), true) : timer); }
java
{ "resource": "" }
q24081
HttpClientBuilder.createUserAgent
train
protected String createUserAgent(String name) { final String defaultUserAgent = environmentName == null ? name : String.format("%s (%s)", environmentName, name); return configuration.getUserAgent().orElse(defaultUserAgent); }
java
{ "resource": "" }
q24082
HttpClientBuilder.createConnectionManager
train
protected InstrumentedHttpClientConnectionManager createConnectionManager(Registry<ConnectionSocketFactory> registry, String name) { final Duration ttl = configuration.getTimeToLive(); final InstrumentedHttpClientConnectionMan...
java
{ "resource": "" }
q24083
HttpClientBuilder.configureCredentials
train
protected Credentials configureCredentials(AuthConfiguration auth) { if (null != auth.getCredentialType() && auth.getCredentialType().equalsIgnoreCase(AuthConfiguration.NT_CREDS)) { return new NTCredentials(auth.getUsername(), auth.getPassword(), auth.getHostname(), auth.getDomain()); } els...
java
{ "resource": "" }
q24084
AbstractDAO.uniqueResult
train
protected E uniqueResult(CriteriaQuery<E> criteriaQuery) throws HibernateException { return AbstractProducedQuery.uniqueElement( currentSession() .createQuery(requireNonNull(criteriaQuery)) .getResultList() ); }
java
{ "resource": "" }
q24085
AbstractDAO.uniqueResult
train
@SuppressWarnings("unchecked") protected E uniqueResult(Criteria criteria) throws HibernateException { return (E) requireNonNull(criteria).uniqueResult(); }
java
{ "resource": "" }
q24086
AbstractDAO.list
train
protected List<E> list(Query<E> query) throws HibernateException { return requireNonNull(query).list(); }
java
{ "resource": "" }
q24087
JerseyEnvironment.getProperty
train
@SuppressWarnings({"unchecked", "TypeParameterUnusedInFormals"}) @Nullable public <T> T getProperty(String name) { return (T) config.getProperties().get(name); }
java
{ "resource": "" }
q24088
Servlets.getFullUrl
train
public static String getFullUrl(HttpServletRequest request) { if (request.getQueryString() == null) { return request.getRequestURI(); } return request.getRequestURI() + "?" + request.getQueryString(); }
java
{ "resource": "" }
q24089
Cli.run
train
public boolean run(String... arguments) throws Exception { try { if (isFlag(HELP, arguments)) { parser.printHelp(stdOut); } else if (isFlag(VERSION, arguments)) { parser.printVersion(stdOut); } else { final Namespace namespace =...
java
{ "resource": "" }
q24090
Bootstrap.registerMetrics
train
public void registerMetrics() { if (metricsAreRegistered) { return; } getMetricRegistry().register("jvm.attribute", new JvmAttributeGaugeSet()); getMetricRegistry().register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory ...
java
{ "resource": "" }
q24091
Bootstrap.run
train
public void run(T configuration, Environment environment) throws Exception { for (ConfiguredBundle<? super T> bundle : configuredBundles) { bundle.run(configuration, environment); } }
java
{ "resource": "" }
q24092
BasicCredentialAuthFilter.getCredentials
train
@Nullable private BasicCredentials getCredentials(String header) { if (header == null) { return null; } final int space = header.indexOf(' '); if (space <= 0) { return null; } final String method = header.substring(0, space); if (!pre...
java
{ "resource": "" }
q24093
Resources.toByteArray
train
public static byte[] toByteArray(URL url) throws IOException { try (InputStream inputStream = url.openStream()) { return ByteStreams.toByteArray(inputStream); } }
java
{ "resource": "" }
q24094
Resources.copy
train
public static void copy(URL from, OutputStream to) throws IOException { try (InputStream inputStream = from.openStream()) { ByteStreams.copy(inputStream, to); } }
java
{ "resource": "" }
q24095
RequestIdFilter.generateRandomUuid
train
private static UUID generateRandomUuid() { final Random rnd = ThreadLocalRandom.current(); long mostSig = rnd.nextLong(); long leastSig = rnd.nextLong(); // Identify this as a version 4 UUID, that is one based on a random value. mostSig &= 0xffffffffffff0fffL; mostSig |...
java
{ "resource": "" }
q24096
Reflect.isSimilarSignature
train
private boolean isSimilarSignature(Method possiblyMatchingMethod, String desiredMethodName, Class<?>[] desiredParamTypes) { return possiblyMatchingMethod.getName().equals(desiredMethodName) && match(possiblyMatchingMethod.getParameterTypes(), desiredParamTypes); }
java
{ "resource": "" }
q24097
Reflect.match
train
private boolean match(Class<?>[] declaredTypes, Class<?>[] actualTypes) { if (declaredTypes.length == actualTypes.length) { for (int i = 0; i < actualTypes.length; i++) { if (actualTypes[i] == NULL.class) continue; if (wrapper(declaredTypes[i]).is...
java
{ "resource": "" }
q24098
Reflect.on
train
private static Reflect on(Constructor<?> constructor, Object... args) throws ReflectException { try { return on(constructor.getDeclaringClass(), accessible(constructor).newInstance(args)); } catch (Exception e) { throw new ReflectException(e); } }
java
{ "resource": "" }
q24099
Reflect.on
train
private static Reflect on(Method method, Object object, Object... args) throws ReflectException { try { accessible(method); if (method.getReturnType() == void.class) { method.invoke(object, args); return on(object); } else { ...
java
{ "resource": "" }