_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14000 | BMPCLocalLauncher.install | train | public synchronized static void install() {
if (!isInstalled()) {
InputStream is = BMPCLocalLauncher.class.getResourceAsStream(BMP_LOCAL_ZIP_RES);
try {
// Unzip BrowserMob Proxy contained in the project "/resources"
unzip(is, BMPC_USER_DIR);
// Set executable permissions on the BrowserMob Proxy lanching scripts
new File(BMP_LOCAL_EXEC_UNIX).setExecutable(true);
new File(BMP_LOCAL_EXEC_WIN).setExecutable(true);
// Check there is an installed version
installedVersion();
} catch (Exception e) {
throw new BMPCUnexpectedErrorException("Installation failed", e);
}
}
} | java | {
"resource": ""
} |
q14001 | BMPCLocalLauncher.installedVersion | train | public synchronized static String installedVersion() {
BufferedReader versionReader = null;
try {
versionReader = new BufferedReader(new FileReader(BMP_LOCAL_VERSION_FILE));
// Read version and verify it's there
String version = versionReader.readLine();
if (null == version) throw new Exception();
return version;
} catch(Exception e) {
throw new BMPCLocalNotInstalledException(
"Version file not found: " + BMP_LOCAL_VERSION_FILE);
} finally {
try {
if (null != versionReader) versionReader.close();
} catch (IOException e) {
// Do nothing here
}
}
} | java | {
"resource": ""
} |
q14002 | BMPCLocalLauncher.delete | train | private synchronized static void delete(File file) {
// Check if file is directory
if (file.isDirectory()) {
// Get all files in the folder
File[] files = file.listFiles();
// Delete each file in the folder
for (int i = 0; i < files.length; ++i) {
delete(files[i]);
}
// Delete the folder
file.delete();
} else {
// Delete the file if it is not a folder
file.delete();
}
} | java | {
"resource": ""
} |
q14003 | LuceneParser.parse | train | public List<LuceneToken> parse(String fieldName, String text)
throws IOException {
return readTokens(analyzer.tokenStream(fieldName, text));
} | java | {
"resource": ""
} |
q14004 | CompositeResultHandler.handleResult | train | @Override
public void handleResult(RHI result) {
for (ResultHandler<RHI> resultHandler : resultHandlers) {
resultHandler.handleResult(result);
}
} | java | {
"resource": ""
} |
q14005 | CreateJarEclipseTask.getPublishedDependencyLibs | train | public static Set<File> getPublishedDependencyLibs(@Nonnull final Task pTask,
@Nonnull final DependencyConfig pDepConfig)
{
Set<File> result = new HashSet<>();
Configuration cfg = new ClasspathBuilder(pTask.getProject()).buildMainRuntimeConfiguration(pDepConfig);
for (ResolvedDependency dep : cfg.getResolvedConfiguration().getFirstLevelModuleDependencies()) {
if (!isCheckstyle(dep)) {
for (ResolvedArtifact artifact : dep.getAllModuleArtifacts()) {
result.add(artifact.getFile());
}
}
}
return result;
} | java | {
"resource": ""
} |
q14006 | DefaultMappableValidator.processTrigger | train | @Override
protected void processTrigger(final Trigger trigger) {
// Get data providers matching the trigger
final List<DataProvider<RI>> mappedDataProviders = triggersToDataProviders.get(trigger);
if ((mappedDataProviders == null) || mappedDataProviders.isEmpty()) {
LOGGER.warn("No matching data provider in mappable validator for trigger: " + trigger);
} else {
// Process all matching data providers
for (final DataProvider<RI> dataProvider : mappedDataProviders) {
processDataProvider(dataProvider);
}
}
} | java | {
"resource": ""
} |
q14007 | DefaultMappableValidator.processDataProvider | train | private void processDataProvider(final DataProvider<RI> dataProvider) {
// Get rules matching the data provider
final List<Rule<RI, RO>> mappedRules = dataProvidersToRules.get(dataProvider);
if ((mappedRules == null) || mappedRules.isEmpty()) {
LOGGER.warn("No matching rule in mappable validator for data provider: " + dataProvider);
} else {
// Get data to be validated
final RI data = dataProvider.getData();
// Process all matching rules
for (final Rule<RI, RO> rule : mappedRules) {
processRule(rule, data);
}
}
} | java | {
"resource": ""
} |
q14008 | DefaultMappableValidator.processRule | train | private void processRule(final Rule<RI, RO> rule, final RI data) {
// Get result handlers matching the rule
final List<ResultHandler<RO>> mappedResultHandlers = rulesToResultHandlers.get(rule);
if ((mappedResultHandlers == null) || mappedResultHandlers.isEmpty()) {
LOGGER.warn("No matching result handler in mappable validator for rule: " + rule);
} else {
// Check rule
final RO result = rule.validate(data);
// Process result with all matching result handlers
for (final ResultHandler<RO> resultHandler : mappedResultHandlers) {
processResultHandler(resultHandler, result);
}
}
} | java | {
"resource": ""
} |
q14009 | ValidatorContext.handleWith | train | public ValidatorContext<D, O> handleWith(final ResultHandler<O>... resultHandlers) {
if (resultHandlers != null) {
Collections.addAll(registeredResultHandlers, resultHandlers);
}
return this;
} | java | {
"resource": ""
} |
q14010 | MetricsUtils.buildCombinedType | train | static String buildCombinedType(String eventType, Optional<String> objectType) {
return Joiner.on("/").skipNulls().join(eventType, objectType.orNull());
} | java | {
"resource": ""
} |
q14011 | MetricsUtils.buildVirtualPageTitle | train | static String buildVirtualPageTitle(Map<String, String> metadata) {
checkNotNull(metadata);
List<String> escapedMetadata = new ArrayList<>();
for (Map.Entry<String, String> entry : metadata.entrySet()) {
escapedMetadata.add(METADATA_ESCAPER.escape(entry.getKey()) + "="
+ METADATA_ESCAPER.escape(entry.getValue()));
}
return Joiner.on(",").join(escapedMetadata);
} | java | {
"resource": ""
} |
q14012 | MetricsUtils.buildParameters | train | static ImmutableList<NameValuePair> buildParameters(
String analyticsId,
String clientId,
String virtualPageName,
String virtualPageTitle,
String eventType,
String eventName,
boolean isUserSignedIn,
boolean isUserInternal,
Optional<Boolean> isUserTrialEligible,
Optional<String> projectNumberHash,
Optional<String> billingIdHash,
Optional<String> clientHostname,
Random random) {
checkNotNull(analyticsId);
checkNotNull(clientId);
checkNotNull(virtualPageTitle);
checkNotNull(virtualPageName);
checkNotNull(eventType);
checkNotNull(eventName);
checkNotNull(projectNumberHash);
checkNotNull(billingIdHash);
checkNotNull(clientHostname);
checkNotNull(random);
ImmutableList.Builder<NameValuePair> listBuilder = new ImmutableList.Builder<>();
// Analytics information
// Protocol version
listBuilder.add(new BasicNameValuePair(PARAM_PROTOCOL, "1"));
// Analytics ID to send report to
listBuilder.add(new BasicNameValuePair(PARAM_PROPERTY_ID, analyticsId));
// Always report as a pageview
listBuilder.add(new BasicNameValuePair(PARAM_TYPE, VALUE_TYPE_PAGEVIEW));
// Always report as interactive
listBuilder.add(new BasicNameValuePair(PARAM_IS_NON_INTERACTIVE, VALUE_FALSE));
// Add a randomly generated cache buster
listBuilder.add(new BasicNameValuePair(PARAM_CACHEBUSTER, Long.toString(random.nextLong())));
// Event information
listBuilder.add(new BasicNameValuePair(PARAM_EVENT_TYPE, eventType));
listBuilder.add(new BasicNameValuePair(PARAM_EVENT_NAME, eventName));
if (clientHostname.isPresent() && !clientHostname.get().isEmpty()) {
listBuilder.add(new BasicNameValuePair(PARAM_HOSTNAME, clientHostname.get()));
}
// User information
listBuilder.add(new BasicNameValuePair(PARAM_CLIENT_ID, clientId));
if (projectNumberHash.isPresent() && !projectNumberHash.get().isEmpty()) {
listBuilder.add(new BasicNameValuePair(PARAM_PROJECT_NUM_HASH, projectNumberHash.get()));
}
if (billingIdHash.isPresent() && !billingIdHash.get().isEmpty()) {
listBuilder.add(new BasicNameValuePair(PARAM_BILLING_ID_HASH, billingIdHash.get()));
}
listBuilder.add(new BasicNameValuePair(PARAM_USER_SIGNED_IN, toValue(isUserSignedIn)));
listBuilder.add(new BasicNameValuePair(PARAM_USER_INTERNAL, toValue(isUserInternal)));
if (isUserTrialEligible.isPresent()) {
listBuilder.add(new BasicNameValuePair(PARAM_USER_TRIAL_ELIGIBLE,
toValue(isUserTrialEligible.get())));
}
// Virtual page information
listBuilder.add(new BasicNameValuePair(PARAM_IS_VIRTUAL, VALUE_TRUE));
listBuilder.add(new BasicNameValuePair(PARAM_PAGE, virtualPageName));
if (!virtualPageTitle.isEmpty()) {
listBuilder.add(new BasicNameValuePair(PARAM_PAGE_TITLE, virtualPageTitle));
}
return listBuilder.build();
} | java | {
"resource": ""
} |
q14013 | RuleContext.read | train | public RuleContext<D> read(final DataProvider<D>... dataProviders) {
if (dataProviders != null) {
Collections.addAll(registeredDataProviders, dataProviders);
}
return this;
} | java | {
"resource": ""
} |
q14014 | CompositeReadableProperty.updateFromProperties | train | private void updateFromProperties() {
// Get value from all properties: use a new collection so that equals() returns false
List<R> newValues = new ArrayList<R>();
for (ReadableProperty<R> master : properties) {
newValues.add(master.getValue());
}
// Notify slaves
setValue(newValues);
} | java | {
"resource": ""
} |
q14015 | AbstractSimpleValidator.dispose | train | private void dispose(Collection<?> elements) {
// Dispose all disposable elements
for (Object element : elements) {
if (element instanceof Disposable) {
((Disposable) element).dispose();
}
}
// Clear collection
dataProviders.clear();
} | java | {
"resource": ""
} |
q14016 | SimpleBond.init | train | private void init(ReadableProperty<MO> master, Transformer<MO, SI> transformer, WritableProperty<SI> slave) {
this.master = master;
this.transformer = transformer;
this.slave = slave;
master.addValueChangeListener(masterAdapter);
// Slave initial values
updateSlaves(master.getValue());
} | java | {
"resource": ""
} |
q14017 | SimpleBond.updateSlaves | train | private void updateSlaves(MO masterOutputValue) {
// Transform value
SI slaveInputValue = transformer.transform(masterOutputValue);
// Notify slave(s)
slave.setValue(slaveInputValue);
} | java | {
"resource": ""
} |
q14018 | TransactionalTridentEventHubEmitter.getOrCreatePartitionManager | train | private ITridentPartitionManager getOrCreatePartitionManager(Partition partition) {
ITridentPartitionManager pm;
if(!pmMap.containsKey(partition.getId())) {
IEventHubReceiver receiver = recvFactory.create(spoutConfig, partition.getId());
pm = pmFactory.create(receiver);
pmMap.put(partition.getId(), pm);
}
else {
pm = pmMap.get(partition.getId());
}
return pm;
} | java | {
"resource": ""
} |
q14019 | TriggerContext.on | train | public DataProviderContext on(final Trigger... triggers) {
final List<Trigger> registeredTriggers = new ArrayList<Trigger>();
if (triggers != null) {
Collections.addAll(registeredTriggers, triggers);
}
return new DataProviderContext(registeredTriggers);
} | java | {
"resource": ""
} |
q14020 | JMDictSenseLazy.create | train | public static JMDictSense create() {
if (index >= instances.size()) {
instances.add(new JMDictSense());
}
return instances.get(index++);
} | java | {
"resource": ""
} |
q14021 | JMDictSenseLazy.clear | train | public static void clear() {
for (int i = 0; i < index; ++i) {
instances.get(i).clear();
}
index = 0;
} | java | {
"resource": ""
} |
q14022 | AnchorLink.getRelativeSlaveLocation | train | public Point getRelativeSlaveLocation(final Component masterComponent, final Component slaveComponent) {
return getRelativeSlaveLocation(masterComponent.getWidth(), masterComponent.getHeight(),
slaveComponent.getWidth(), slaveComponent.getHeight());
} | java | {
"resource": ""
} |
q14023 | AbstractMappableValidator.unhookFromTrigger | train | private void unhookFromTrigger(final T trigger) {
// Unhook from trigger
final TriggerListener triggerAdapter = triggersToTriggerAdapters.get(trigger);
trigger.removeTriggerListener(triggerAdapter);
// Check if trigger was added several times
if (!triggersToTriggerAdapters.containsKey(trigger)) {
// All occurrences of the same trigger have been removed
triggersToTriggerAdapters.remove(trigger);
}
} | java | {
"resource": ""
} |
q14024 | AbstractMappableValidator.unmapTriggerFromAllDataProviders | train | private void unmapTriggerFromAllDataProviders(final T trigger) {
if (trigger != null) {
unhookFromTrigger(trigger);
triggersToDataProviders.remove(trigger);
}
} | java | {
"resource": ""
} |
q14025 | AbstractMappableValidator.unmapDataProviderFromAllTriggers | train | private void unmapDataProviderFromAllTriggers(final DP dataProvider) {
if (dataProvider != null) {
for (final List<DP> mappedDataProviders : triggersToDataProviders.values()) {
mappedDataProviders.remove(dataProvider);
}
}
} | java | {
"resource": ""
} |
q14026 | AbstractMappableValidator.unmapRuleFromAllDataProviders | train | private void unmapRuleFromAllDataProviders(final R rule) {
if (rule != null) {
for (final List<R> mappedRules : dataProvidersToRules.values()) {
mappedRules.remove(rule);
}
}
} | java | {
"resource": ""
} |
q14027 | AbstractMappableValidator.unmapResultHandlerFromAllRules | train | private void unmapResultHandlerFromAllRules(final RH resultHandler) {
if (resultHandler != null) {
for (final List<RH> mappedResultHandlers : rulesToResultHandlers.values()) {
mappedResultHandlers.remove(resultHandler);
}
}
} | java | {
"resource": ""
} |
q14028 | AbstractMappableValidator.disposeTriggersAndDataProviders | train | private void disposeTriggersAndDataProviders() {
for (final Map.Entry<T, List<DP>> entry : triggersToDataProviders.entrySet()) {
// Disconnect from trigger
unhookFromTrigger(entry.getKey());
// Dispose trigger itself
final T trigger = entry.getKey();
if (trigger instanceof Disposable) {
((Disposable) trigger).dispose();
}
// Dispose data providers
final List<DP> dataProviders = entry.getValue();
if (dataProviders != null) {
for (final DP dataProvider : dataProviders) {
if (dataProvider instanceof Disposable) {
((Disposable) dataProvider).dispose();
}
}
}
}
// Clears all triggers
triggersToDataProviders.clear();
} | java | {
"resource": ""
} |
q14029 | AbstractMappableValidator.disposeRulesAndResultHandlers | train | private void disposeRulesAndResultHandlers() {
for (final Map.Entry<R, List<RH>> entry : rulesToResultHandlers.entrySet()) {
// Dispose rule
final R rule = entry.getKey();
if (rule instanceof Disposable) {
((Disposable) rule).dispose();
}
// Dispose result handlers
final List<RH> resultHandlers = entry.getValue();
if (resultHandlers != null) {
for (final RH resultHandler : resultHandlers) {
if (resultHandler instanceof Disposable) {
((Disposable) resultHandler).dispose();
}
}
}
}
// Clears all triggers
rulesToResultHandlers.clear();
} | java | {
"resource": ""
} |
q14030 | ComponentRolloverProperty.setValue | train | private void setValue(boolean rollover) {
if (!ValueUtils.areEqual(this.rollover, rollover)) {
boolean oldValue = this.rollover;
this.rollover = rollover;
maybeNotifyListeners(oldValue, rollover);
}
} | java | {
"resource": ""
} |
q14031 | ResultHandlerContext.build | train | private GeneralValidator<DPO, RI, RO, RHI> build() {
// Create validator
GeneralValidator<DPO, RI, RO, RHI> validator = new GeneralValidator<DPO, RI, RO, RHI>();
// Add triggers
for (Trigger trigger : addedTriggers) {
validator.addTrigger(trigger);
}
// Add data providers
for (DataProvider<DPO> dataProvider : addedDataProviders) {
validator.addDataProvider(dataProvider);
}
// Map data providers output to rules input
validator.setDataProviderToRuleMappingStrategy(dataProviderToRuleMapping);
validator.setRuleInputTransformers(addedRuleInputTransformers);
// Add rules
for (Rule<RI, RO> rule : addedRules) {
validator.addRule(rule);
}
// Map rules output to result handlers input
validator.setRuleToResultHandlerMappingStrategy(ruleToResultHandlerMapping);
validator.setResultHandlerInputTransformers(addedResultHandlerInputTransformers);
// Add result handlers
for (ResultHandler<RHI> resultHandler : addedResultHandlers) {
validator.addResultHandler(resultHandler);
}
return validator;
} | java | {
"resource": ""
} |
q14032 | BMPCProxy.asSeleniumProxy | train | public Proxy asSeleniumProxy() {
Proxy seleniumProxyConfig = new Proxy();
seleniumProxyConfig.setProxyType(Proxy.ProxyType.MANUAL);
seleniumProxyConfig.setHttpProxy(asHostAndPort());
return seleniumProxyConfig;
} | java | {
"resource": ""
} |
q14033 | BMPCProxy.newHar | train | public JsonObject newHar(String initialPageRef,
boolean captureHeaders,
boolean captureContent,
boolean captureBinaryContent) {
try {
// Request BMP to create a new HAR for this Proxy
HttpPut request = new HttpPut(requestURIBuilder()
.setPath(proxyURIPath() + "/har")
.build());
// Add form parameters to the request
applyFormParamsToHttpRequest(request,
new BasicNameValuePair("initialPageRef", initialPageRef),
new BasicNameValuePair("captureHeaders", Boolean.toString(captureHeaders)),
new BasicNameValuePair("captureContent", Boolean.toString(captureContent)),
new BasicNameValuePair("captureBinaryContent", Boolean.toString(captureBinaryContent)));
// Execute request
CloseableHttpResponse response = HTTPclient.execute(request);
// Parse response into JSON
JsonObject previousHar = httpResponseToJsonObject(response);
// Close HTTP Response
response.close();
return previousHar;
} catch (Exception e) {
throw new BMPCUnableToCreateHarException(e);
}
} | java | {
"resource": ""
} |
q14034 | BMPCProxy.newPage | train | public void newPage(String pageRef) {
try {
// Request BMP to create a new HAR for this Proxy
HttpPut request = new HttpPut(requestURIBuilder()
.setPath(proxyURIPath() + "/har/pageRef")
.build());
// Add form parameters to the request
applyFormParamsToHttpRequest(request,
new BasicNameValuePair("pageRef", pageRef));
// Execute request
CloseableHttpResponse response = HTTPclient.execute(request);
// Check request was successful
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
throw new BMPCUnableToCreatePageException(
"Invalid HTTP Response when attempting to create"
+ "new Page in HAR: "
+ statusCode
);
}
// Close HTTP Response
response.close();
} catch (Exception e) {
throw new BMPCUnableToCreateHarException(e);
}
} | java | {
"resource": ""
} |
q14035 | BMPCProxy.har | train | public JsonObject har() {
try {
// Request BMP to create a new HAR for this Proxy
HttpGet request = new HttpGet(requestURIBuilder()
.setPath(proxyURIPath() + "/har")
.build());
// Execute request
CloseableHttpResponse response = HTTPclient.execute(request);
// Parse response into JSON
JsonObject har = httpResponseToJsonObject(response);
// Close HTTP Response
response.close();
return har;
} catch (Exception e) {
throw new BMPCUnableToCreateHarException(e);
}
} | java | {
"resource": ""
} |
q14036 | BMPCProxy.harToFile | train | public static void harToFile(JsonObject har, String destinationDir, String destinationFile) {
// Prepare HAR destination directory
File harDestinationDir = new File(destinationDir);
if (!harDestinationDir.exists()) harDestinationDir.mkdirs();
// Store HAR to disk
PrintWriter harDestinationFileWriter = null;
try {
// Prepare Writer
harDestinationFileWriter = new PrintWriter(
destinationDir + File.separator + destinationFile);
// Store HAR if any, otherwise empty file
if (null != har) {
harDestinationFileWriter.print(har.toString());
} else {
harDestinationFileWriter.print("");
}
} catch (FileNotFoundException e) {
throw new BMPCUnableToSaveHarToFileException(e);
} finally {
if (null != harDestinationFileWriter) {
harDestinationFileWriter.flush();
harDestinationFileWriter.close();
}
}
} | java | {
"resource": ""
} |
q14037 | ResultCollectorValidator.processResult | train | protected void processResult(RO result) {
for (ResultHandler<RO> resultHandler : resultHandlers) {
resultHandler.handleResult(result);
}
} | java | {
"resource": ""
} |
q14038 | TaskCreator.setupCrossCheckTasks | train | public void setupCrossCheckTasks()
{
final TaskContainer tasks = project.getTasks();
final Task xtest = tasks.create(XTEST_TASK_NAME);
xtest.setGroup(XTEST_GROUP_NAME);
xtest.setDescription("Run the unit tests against all supported Checkstyle runtimes");
tasks.getByName(JavaBasePlugin.BUILD_TASK_NAME).dependsOn(xtest);
for (final DependencyConfig depConfig : buildUtil.getDepConfigs().getAll().values()) {
final JavaVersion javaLevel = depConfig.getJavaLevel();
final String csBaseVersion = depConfig.getCheckstyleBaseVersion();
for (final String csRuntimeVersion : depConfig.getCompatibleCheckstyleVersions()) {
if (csBaseVersion.equals(csRuntimeVersion)) {
continue;
}
final TestTask testTask = tasks.create(TaskNames.xtest.getName(depConfig, csRuntimeVersion),
TestTask.class);
testTask.configureFor(depConfig, csRuntimeVersion);
testTask.setGroup(XTEST_GROUP_NAME);
testTask.setDescription("Run the unit tests compiled for Checkstyle " + csBaseVersion
+ " against a Checkstyle " + csRuntimeVersion + " runtime (Java level: " + javaLevel + ")");
testTask.getReports().getHtml().setEnabled(false);
xtest.dependsOn(testTask);
}
}
} | java | {
"resource": ""
} |
q14039 | TaskCreator.adjustTaskGroupAssignments | train | public void adjustTaskGroupAssignments()
{
final TaskContainer tasks = project.getTasks();
tasks.getByName(BasePlugin.ASSEMBLE_TASK_NAME).setGroup(ARTIFACTS_GROUP_NAME);
tasks.getByName(JavaPlugin.JAR_TASK_NAME).setGroup(ARTIFACTS_GROUP_NAME);
final SourceSet sqSourceSet = buildUtil.getSourceSet(BuildUtil.SONARQUBE_SOURCE_SET_NAME);
tasks.getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME).setGroup(BasePlugin.BUILD_GROUP);
tasks.getByName(sqSourceSet.getCompileJavaTaskName()).setGroup(BasePlugin.BUILD_GROUP);
tasks.getByName(JavaPlugin.COMPILE_TEST_JAVA_TASK_NAME).setGroup(BasePlugin.BUILD_GROUP);
for (final SpotBugsTask sbTask : tasks.withType(SpotBugsTask.class)) {
sbTask.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
}
for (final Checkstyle csTask : tasks.withType(Checkstyle.class)) {
csTask.setGroup(LifecycleBasePlugin.VERIFICATION_GROUP);
}
for (final Copy task : tasks.withType(Copy.class)) {
if (task.getName().startsWith("process") && task.getName().endsWith("Resources")) {
task.setGroup(LifecycleBasePlugin.BUILD_GROUP);
}
}
} | java | {
"resource": ""
} |
q14040 | ResultHandlerContext.check | train | public ResultHandlerContext<D, O> check(final Rule<D, O>... rules) {
if (rules != null) {
Collections.addAll(registeredRules, rules);
}
return this;
} | java | {
"resource": ""
} |
q14041 | IconUtils.loadImageIcon | train | public static ImageIcon loadImageIcon(final String iconName, final Class<?> clazz) {
ImageIcon icon = null;
if (iconName != null) {
final URL iconResource = clazz.getResource(iconName);
if (iconResource == null) {
LOGGER.error("Icon could not be loaded: '" + iconName);
icon = null;
} else {
icon = new ImageIcon(iconResource);
}
}
return icon;
} | java | {
"resource": ""
} |
q14042 | CreateJarTask.mfAttrStd | train | public static Map<String, String> mfAttrStd(final Project pProject)
{
Map<String, String> result = new HashMap<>();
result.put("Manifest-Version", "1.0");
result.put("Website", new BuildUtil(pProject).getExtraPropertyValue(ExtProp.Website));
result.put("Created-By", GradleVersion.current().toString());
result.put("Built-By", System.getProperty("user.name"));
result.put("Build-Jdk", Jvm.current().toString());
return result;
} | java | {
"resource": ""
} |
q14043 | JTableRowCountProperty.updateValue | train | private void updateValue() {
if (table != null) {
int oldCount = this.count;
this.count = table.getRowCount();
maybeNotifyListeners(oldCount, count);
}
} | java | {
"resource": ""
} |
q14044 | MongoDBQueryUtils.queryParamsOperatorAlwaysMatchesOperator | train | private static boolean queryParamsOperatorAlwaysMatchesOperator(QueryParam.Type type, List<String> queryParamList,
ComparisonOperator operator) {
for (String queryItem : queryParamList) {
Matcher matcher = getPattern(type).matcher(queryItem);
String op = "";
if (matcher.find()) {
op = matcher.group(1);
}
if (operator != getComparisonOperator(op, type)) {
return false;
}
}
return true;
} | java | {
"resource": ""
} |
q14045 | MongoDBQueryUtils.removeOperatorsFromQueryParamList | train | private static List<Object> removeOperatorsFromQueryParamList(QueryParam.Type type, List<String> queryParamList) {
List<Object> newQueryParamList = new ArrayList<>();
for (String queryItem : queryParamList) {
Matcher matcher = getPattern(type).matcher(queryItem);
String queryValueString = queryItem;
if (matcher.find()) {
queryValueString = matcher.group(2);
}
switch (type) {
case STRING:
case TEXT:
case TEXT_ARRAY:
newQueryParamList.add(queryValueString);
break;
case LONG:
case LONG_ARRAY:
case INTEGER:
case INTEGER_ARRAY:
newQueryParamList.add(Long.parseLong(queryValueString));
break;
case DOUBLE:
case DECIMAL:
case DECIMAL_ARRAY:
newQueryParamList.add(Double.parseDouble(queryValueString));
break;
case BOOLEAN:
case BOOLEAN_ARRAY:
newQueryParamList.add(Boolean.parseBoolean(queryValueString));
break;
default:
break;
}
}
return newQueryParamList;
} | java | {
"resource": ""
} |
q14046 | MongoDBQueryUtils.createDateFilter | train | private static Bson createDateFilter(String mongoDbField, List<String> dateValues, ComparisonOperator comparator,
QueryParam.Type type) {
Bson filter = null;
Object date = null;
if (QueryParam.Type.DATE.equals(type)) {
date = convertStringToDate(dateValues.get(0));
} else if (QueryParam.Type.TIMESTAMP.equals(type)) {
date = convertStringToDate(dateValues.get(0)).getTime();
}
if (date != null) {
switch (comparator) {
case BETWEEN:
if (dateValues.size() == 2) {
Date to = convertStringToDate(dateValues.get(1));
if (QueryParam.Type.DATE.equals(type)) {
filter = new Document(mongoDbField, new Document()
.append("$gte", date)
.append("$lt", to));
} else if (QueryParam.Type.TIMESTAMP.equals(type)) {
filter = new Document(mongoDbField, new Document()
.append("$gte", date)
.append("$lt", to.getTime()));
}
}
break;
case EQUALS:
filter = Filters.eq(mongoDbField, date);
break;
case GREATER_THAN:
filter = Filters.gt(mongoDbField, date);
break;
case GREATER_THAN_EQUAL:
filter = Filters.gte(mongoDbField, date);
break;
case LESS_THAN:
filter = Filters.lt(mongoDbField, date);
break;
case LESS_THAN_EQUAL:
filter = Filters.lte(mongoDbField, date);
break;
default:
break;
}
}
return filter;
} | java | {
"resource": ""
} |
q14047 | MongoDBQueryUtils.checkOperator | train | public static LogicalOperator checkOperator(String value) throws IllegalArgumentException {
boolean containsOr = value.contains(OR);
boolean containsAnd = value.contains(AND);
if (containsAnd && containsOr) {
throw new IllegalArgumentException("Cannot merge AND and OR operators in the same query filter.");
} else if (containsAnd && !containsOr) {
return LogicalOperator.AND;
} else if (containsOr && !containsAnd) {
return LogicalOperator.OR;
} else { // !containsOr && !containsAnd
return null;
}
} | java | {
"resource": ""
} |
q14048 | EasyJaSubDictionary.getEntry | train | public EasyJaSubDictionaryEntry getEntry(String word) {
if (word == null || word.length() == 0) {
throw new RuntimeException("Invalid word");
}
EasyJaSubTrie.Value<EasyJaSubDictionaryEntry> value = trie
.get(new CharacterIterator(word));
if (value == null) {
return null;
}
return value.getValue();
} | java | {
"resource": ""
} |
q14049 | BuildUtil.getExtraPropertyValue | train | @SuppressWarnings("unchecked")
public <T> T getExtraPropertyValue(@Nonnull final ExtProp pExtraPropName)
{
ExtraPropertiesExtension extraProps = project.getExtensions().getByType(ExtraPropertiesExtension.class);
if (extraProps.has(pExtraPropName.getPropertyName())) {
return (T) extraProps.get(pExtraPropName.getPropertyName());
}
throw new GradleException(
"Reference to non-existent project extra property '" + pExtraPropName.getPropertyName() + "'");
} | java | {
"resource": ""
} |
q14050 | BuildUtil.getTask | train | @Nonnull
public Task getTask(@Nonnull final TaskNames pTaskName, @Nonnull final DependencyConfig pDepConfig)
{
return project.getTasks().getByName(pTaskName.getName(pDepConfig));
} | java | {
"resource": ""
} |
q14051 | BuildUtil.addBuildTimestampDeferred | train | public void addBuildTimestampDeferred(@Nonnull final Task pTask, @Nonnull final Attributes pAttributes)
{
pTask.doFirst(new Closure<Void>(pTask)
{
@Override
@SuppressWarnings("MethodDoesntCallSuperMethod")
public Void call()
{
addBuildTimestamp(pAttributes);
return null;
}
});
} | java | {
"resource": ""
} |
q14052 | BuildUtil.inheritManifest | train | public void inheritManifest(@Nonnull final Jar pTask, @Nonnull final DependencyConfig pDepConfig)
{
pTask.doFirst(new Closure<Void>(pTask)
{
@Override
@SuppressWarnings("MethodDoesntCallSuperMethod")
public Void call()
{
final Jar jarTask = (Jar) getTask(TaskNames.jar, pDepConfig);
pTask.setManifest(jarTask.getManifest());
addBuildTimestamp(pTask.getManifest().getAttributes());
return null;
}
});
} | java | {
"resource": ""
} |
q14053 | Anchor.getAnchorPoint | train | public Point getAnchorPoint(int width, int height) {
return new Point((int) (relativeX * width + offsetX), (int) (relativeY * height + offsetY));
} | java | {
"resource": ""
} |
q14054 | AbstractReadableProperty.setInhibited | train | public void setInhibited(boolean inhibited) {
boolean wasInhibited = this.inhibited;
this.inhibited = inhibited;
if (wasInhibited && !inhibited) {
if (inhibitCount > 0) {
maybeNotifyListeners(lastNonInhibitedValue, lastInhibitedValue);
}
inhibitCount = 0;
}
} | java | {
"resource": ""
} |
q14055 | AbstractReadableProperty.notifyListenersIfUninhibited | train | private void notifyListenersIfUninhibited(R oldValue, R newValue) {
if (inhibited) {
inhibitCount++;
lastInhibitedValue = newValue;
} else {
lastInhibitedValue = newValue; // Just in case, even though not really necessary
lastNonInhibitedValue = newValue;
doNotifyListeners(oldValue, newValue);
}
} | java | {
"resource": ""
} |
q14056 | AbstractReadableProperty.doNotifyListeners | train | private void doNotifyListeners(R oldValue, R newValue) {
List<ValueChangeListener<R>> listenersCopy = new ArrayList<ValueChangeListener<R>>(listeners);
notifyingListeners = true;
for (ValueChangeListener<R> listener : listenersCopy) {
listener.valueChanged(this, oldValue, newValue);
}
notifyingListeners = false;
} | java | {
"resource": ""
} |
q14057 | BDSup2SubWrapper.validateTimes | train | private void validateTimes(int idx, SubPicture subPic,
SubPicture subPicNext, SubPicture subPicPrev) {
long startTime = subPic.getStartTime();
long endTime = subPic.getEndTime();
final long delay = 5000 * 90; // default delay for missing end time (5
// seconds)
idx += 1; // only used for display
// get end time of last frame
long lastEndTime = subPicPrev != null ? subPicPrev.getEndTime() : -1;
if (startTime < lastEndTime) {
startTime = lastEndTime;
}
// get start time of next frame
long nextStartTime = subPicNext != null ? subPicNext.getStartTime() : 0;
if (nextStartTime == 0) {
if (endTime > startTime) {
nextStartTime = endTime;
} else {
// completely messed up:
// end time and next start time are invalid
nextStartTime = startTime + delay;
}
}
if (endTime <= startTime) {
endTime = startTime + delay;
if (endTime > nextStartTime) {
endTime = nextStartTime;
}
} else if (endTime > nextStartTime) {
endTime = nextStartTime;
}
int minTimePTS = configuration.getMinTimePTS();
if (endTime - startTime < minTimePTS) {
if (configuration.getFixShortFrames()) {
endTime = startTime + minTimePTS;
if (endTime > nextStartTime) {
endTime = nextStartTime;
}
}
}
if (subPic.getStartTime() != startTime) {
subPic.setStartTime(SubtitleUtils.syncTimePTS(startTime,
configuration.getFpsTrg(), configuration.getFpsTrg()));
}
if (subPic.getEndTime() != endTime) {
subPic.setEndTime(SubtitleUtils.syncTimePTS(endTime,
configuration.getFpsTrg(), configuration.getFpsTrg()));
}
} | java | {
"resource": ""
} |
q14058 | BDSup2SubWrapper.getSubPicturesToBeExported | train | private List<Integer> getSubPicturesToBeExported() {
List<Integer> subPicturesToBeExported = new ArrayList<Integer>();
for (int i = 0; i < subPictures.length; i++) {
SubPicture subPicture = subPictures[i];
if (!subPicture.isExcluded()
&& (!configuration.isExportForced() || subPicture
.isForced())) {
subPicturesToBeExported.add(i);
}
}
return subPicturesToBeExported;
} | java | {
"resource": ""
} |
q14059 | BDSup2SubWrapper.determineFramePal | train | private void determineFramePal(int index) {
if ((inMode != InputMode.VOBSUB && inMode != InputMode.SUPIFO)
|| configuration.getPaletteMode() != PaletteMode.KEEP_EXISTING) {
// get the primary color from the source palette
int rgbSrc[] = subtitleStream.getPalette().getRGB(
subtitleStream.getPrimaryColorIndex());
// match with primary color from 16 color target palette
// note: skip index 0 , primary colors at even positions
// special treatment for index 1: white
Palette trgPallete = currentDVDPalette;
int minDistance = 0xffffff; // init > 0xff*0xff*3 = 0x02fa03
int colIdx = 0;
for (int idx = 1; idx < trgPallete.getSize(); idx += 2) {
int rgb[] = trgPallete.getRGB(idx);
// distance vector (skip sqrt)
int rd = rgbSrc[0] - rgb[0];
int gd = rgbSrc[1] - rgb[1];
int bd = rgbSrc[2] - rgb[2];
int distance = rd * rd + gd * gd + bd * bd;
// new minimum distance ?
if (distance < minDistance) {
colIdx = idx;
minDistance = distance;
if (minDistance == 0) {
break;
}
}
// special treatment for index 1 (white)
if (idx == 1) {
idx--; // -> continue with index = 2
}
}
// set new frame palette
int palFrame[] = new int[4];
palFrame[0] = 0; // black - transparent color
palFrame[1] = colIdx; // primary color
if (colIdx == 1) {
palFrame[2] = colIdx + 2; // special handling: white + dark grey
} else {
palFrame[2] = colIdx + 1; // darker version of primary color
}
palFrame[3] = 0; // black - opaque
subVobTrg.setAlpha(DEFAULT_ALPHA);
subVobTrg.setPal(palFrame);
trgPal = SupDvdUtil.decodePalette(subVobTrg, trgPallete);
}
} | java | {
"resource": ""
} |
q14060 | ChainedTransformer.chain | train | @SuppressWarnings("unchecked")
public <TO> ChainedTransformer<I, TO> chain(Transformer<O, TO> transformer) {
if (transformer != null) {
transformers.add(transformer);
}
return (ChainedTransformer<I, TO>) this;
} | java | {
"resource": ""
} |
q14061 | ResultAggregationValidator.processResult | train | protected void processResult(RHI aggregatedResult) {
// Process the result with all result handlers
for (ResultHandler<RHI> resultHandler : resultHandlers) {
resultHandler.handleResult(aggregatedResult);
}
} | java | {
"resource": ""
} |
q14062 | Util.getFirstIdent | train | @CheckForNull
public static String getFirstIdent(@Nonnull final DetailAST pAst)
{
String result = null;
DetailAST ast = pAst.findFirstToken(TokenTypes.IDENT);
if (ast != null) {
result = ast.getText();
}
return result;
} | java | {
"resource": ""
} |
q14063 | Util.getFullIdent | train | @CheckForNull
public static String getFullIdent(@Nonnull final DetailAST pAst)
{
String result = null;
DetailAST ast = checkTokens(pAst.getFirstChild(), TokenTypes.DOT, TokenTypes.IDENT);
if (ast != null) {
StringBuilder sb = new StringBuilder();
if (getFullIdentInternal(ast, sb)) {
result = sb.toString();
}
}
return result;
} | java | {
"resource": ""
} |
q14064 | Util.containsString | train | public static boolean containsString(@Nullable final Iterable<String> pIterable, @Nullable final String pSearched,
final boolean pCaseSensitive)
{
boolean result = false;
if (pSearched != null && pIterable != null) {
for (String s : pIterable) {
if (stringEquals(pSearched, s, pCaseSensitive)) {
result = true;
break;
}
}
}
return result;
} | java | {
"resource": ""
} |
q14065 | Util.stringEquals | train | public static boolean stringEquals(@Nullable final String pStr1, @Nullable final String pStr2,
final boolean pCaseSensitive)
{
boolean result = false;
if (pStr1 == null && pStr2 == null) {
result = true;
}
else if (pStr1 != null) {
if (pCaseSensitive) {
result = pStr1.equals(pStr2);
}
else {
result = pStr1.equalsIgnoreCase(pStr2);
}
}
return result;
} | java | {
"resource": ""
} |
q14066 | Util.findLeftMostTokenInLine | train | @Nonnull
public static DetailAST findLeftMostTokenInLine(@Nonnull final DetailAST pAst)
{
return findLeftMostTokenInLineInternal(pAst, pAst.getLineNo(), pAst.getColumnNo());
} | java | {
"resource": ""
} |
q14067 | IconComponentDecoration.setToolTipText | train | public void setToolTipText(String text) {
this.toolTipText = text;
if (toolTipDialog != null) {
toolTipDialog.setText(text);
}
} | java | {
"resource": ""
} |
q14068 | IconComponentDecoration.updateToolTipDialogVisibility | train | private void updateToolTipDialogVisibility() {
// Determine whether tooltip should be/remain visible
boolean shouldBeVisible = isOverDecorationPainter() || isOverToolTipDialog();
// Create tooltip dialog if needed
if (shouldBeVisible) {
createToolTipDialogIfNeeded();
}
// Update tooltip dialog visibility if changed
if ((toolTipDialog != null) && (toolTipDialog.isVisible() != shouldBeVisible)) {
toolTipDialog.setVisible(shouldBeVisible);
}
} | java | {
"resource": ""
} |
q14069 | MetricsSender.send | train | public void send(Event event) throws MetricsException {
HttpPost request = new HttpPost(MetricsUtils.GA_ENDPOINT_URL);
request.setEntity(MetricsUtils.buildPostBody(event, analyticsId, random));
try {
client.execute(request, RESPONSE_HANDLER);
} catch (IOException e) {
// All errors in the request execution, including non-2XX HTTP codes,
// will throw IOException or one of its subclasses.
throw new MetricsCommunicationException("Problem sending request to server", e);
}
} | java | {
"resource": ""
} |
q14070 | BMPCLocalManager.isRunning | train | public synchronized boolean isRunning() {
if (null == process) return false;
try {
process.exitValue();
return false;
} catch(IllegalThreadStateException itse) {
return true;
}
} | java | {
"resource": ""
} |
q14071 | EasyJaSubJapaneseTextConverter.convertToRomaji | train | private static String convertToRomaji(String katakana)
throws EasyJaSubException {
try {
return Kurikosu.convertKatakanaToRomaji(katakana);
} catch (EasyJaSubException ex) {
try {
return LuceneUtil.katakanaToRomaji(katakana);
} catch (Throwable luceneEx) {
throw ex;
}
}
} | java | {
"resource": ""
} |
q14072 | DataProviderContext.on | train | public DataProviderContext on(final Trigger... triggers) {
if (triggers != null) {
Collections.addAll(registeredTriggers, triggers);
}
return this;
} | java | {
"resource": ""
} |
q14073 | DataProviderContext.read | train | public <D> RuleContext<D> read(final DataProvider<D>... dataProviders) {
final List<DataProvider<D>> registeredDataProviders = new ArrayList<DataProvider<D>>();
if (dataProviders != null) {
Collections.addAll(registeredDataProviders, dataProviders);
}
return new RuleContext<D>(registeredTriggers, registeredDataProviders);
} | java | {
"resource": ""
} |
q14074 | ClasspathBuilder.buildClassPath | train | public FileCollection buildClassPath(@Nonnull final DependencyConfig pDepConfig,
@Nullable final String pCsVersionOverride, final boolean pIsTestRun, @Nonnull final SourceSet pSourceSet1,
@Nullable final SourceSet... pOtherSourceSets)
{
FileCollection cp = getClassesDirs(pSourceSet1, pDepConfig).plus(
project.files(pSourceSet1.getOutput().getResourcesDir()));
if (pOtherSourceSets != null && pOtherSourceSets.length > 0) {
for (final SourceSet sourceSet : pOtherSourceSets) {
cp = cp.plus(getClassesDirs(sourceSet, pDepConfig)).plus(
project.files(sourceSet.getOutput().getResourcesDir()));
}
}
cp = cp.plus(project.files(//
calculateDependencies(pDepConfig, pCsVersionOverride, getConfigName(pSourceSet1, pIsTestRun))));
if (pOtherSourceSets != null && pOtherSourceSets.length > 0) {
for (final SourceSet sourceSet : pOtherSourceSets) {
cp = cp.plus(project.files(//
calculateDependencies(pDepConfig, pCsVersionOverride, getConfigName(sourceSet, pIsTestRun))));
}
}
// final Logger logger = task.getLogger();
// logger.lifecycle("---------------------------------------------------------------------------");
// logger.lifecycle("Classpath of " + task.getName() + " (" + task.getClass().getSimpleName() + "):");
// for (File f : cp) {
// logger.lifecycle("\t- " + f.getAbsolutePath());
// }
// logger.lifecycle("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
return cp;
} | java | {
"resource": ""
} |
q14075 | GeneralValidatorBuilder.on | train | public static TriggerContext on(Trigger trigger) {
List<Trigger> addedTriggers = new ArrayList<Trigger>();
if (trigger != null) {
addedTriggers.add(trigger);
}
return new TriggerContext(addedTriggers);
} | java | {
"resource": ""
} |
q14076 | FileLoader.getFileName | train | public static String getFileName(final ConfigurationSourceKey source){
//ensure an exception is thrown if we are not file.
if (source.getType()!=ConfigurationSourceKey.Type.FILE)
throw new AssertionError("Can only load configuration sources with type "+ConfigurationSourceKey.Type.FILE);
return source.getName()+ '.' +source.getFormat().getExtension();
} | java | {
"resource": ""
} |
q14077 | PickerFragment.setExtraFields | train | public void setExtraFields(Collection<String> fields) {
extraFields = new HashSet<String>();
if (fields != null) {
extraFields.addAll(fields);
}
} | java | {
"resource": ""
} |
q14078 | KeyValueStoreData.data | train | public Map<String,String> data() {
try {
return event().get();
} catch (InterruptedException e) {
// Can only happen if invoked before completion
throw new IllegalStateException(e);
}
} | java | {
"resource": ""
} |
q14079 | EchoServer.onRead | train | @Handler
public void onRead(Input<ByteBuffer> event)
throws InterruptedException {
for (IOSubchannel channel : event.channels(IOSubchannel.class)) {
ManagedBuffer<ByteBuffer> out = channel.byteBufferPool().acquire();
out.backingBuffer().put(event.buffer().backingBuffer());
channel.respond(Output.fromSink(out, event.isEndOfRecord()));
}
} | java | {
"resource": ""
} |
q14080 | TcpConnectionManager.onOutput | train | @Handler
public void onOutput(Output<ByteBuffer> event,
TcpChannelImpl channel) throws InterruptedException {
if (channels.contains(channel)) {
channel.write(event);
}
} | java | {
"resource": ""
} |
q14081 | Replacer.replace | train | public String replace(CharSequence text) {
TextBuffer tb = wrap(new StringBuilder(text.length()));
replace(pattern.matcher(text), substitution, tb);
return tb.toString();
} | java | {
"resource": ""
} |
q14082 | Replacer.replace | train | public int replace(CharSequence text, StringBuilder sb) {
return replace(pattern.matcher(text), substitution, wrap(sb));
} | java | {
"resource": ""
} |
q14083 | LanguageSelector.onProtocolSwitchAccepted | train | @Handler(priority = 1000)
public void onProtocolSwitchAccepted(
ProtocolSwitchAccepted event, IOSubchannel channel) {
event.requestEvent().associated(Selection.class)
.ifPresent(
selection -> channel.setAssociated(Selection.class, selection));
} | java | {
"resource": ""
} |
q14084 | LanguageSelector.associatedLocale | train | public static Locale associatedLocale(Associator assoc) {
return assoc.associated(Selection.class)
.map(sel -> sel.get()[0]).orElse(Locale.getDefault());
} | java | {
"resource": ""
} |
q14085 | IndexScanStrategy.fetch | train | private DataContainer fetch(String tableAlias, IndexBooleanExpression condition, Map<String, String> tableAliases) {
String tableName = tableAliases.get(tableAlias);
Set<String> ids = getIdsFromIndex(tableName, tableAlias, condition);
return fetchContainer(tableName, tableAlias, ids);
} | java | {
"resource": ""
} |
q14086 | IndexScanStrategy.conditionToKeys | train | private static Set<Key> conditionToKeys(int keyLength, Map<String, Set<Object>> condition) {
return crossProduct(new ArrayList<>(condition.values())).stream()
.map(v -> Keys.key(keyLength, v.toArray()))
.collect(Collectors.toSet());
} | java | {
"resource": ""
} |
q14087 | Attribute.getValue | train | public Value getValue(final Environment in){
log.debug("looking up value for "+name+" in "+in);
return attributeValue.get(in);
} | java | {
"resource": ""
} |
q14088 | KeyValueStoreUpdate.update | train | public KeyValueStoreUpdate update(String key, String value) {
actions.add(new Update(key, value));
return this;
} | java | {
"resource": ""
} |
q14089 | KeyValueStoreUpdate.storeAs | train | public KeyValueStoreUpdate storeAs(String value, String... segments) {
actions.add(new Update("/" + String.join("/", segments), value));
return this;
} | java | {
"resource": ""
} |
q14090 | KeyValueStoreUpdate.clearAll | train | public KeyValueStoreUpdate clearAll(String... segments) {
actions.add(new Deletion("/" + String.join("/", segments)));
return this;
} | java | {
"resource": ""
} |
q14091 | AttributeValue.set | train | public void set(Value value, Environment in){
values.put(in.expandedStringForm(), value);
} | java | {
"resource": ""
} |
q14092 | ComponentProxy.getComponentProxy | train | @SuppressWarnings({ "PMD.DataflowAnomalyAnalysis" })
/* default */ static ComponentVertex getComponentProxy(
ComponentType component, Channel componentChannel) {
ComponentProxy componentProxy = null;
try {
Field field = getManagerField(component.getClass());
synchronized (component) {
if (!field.isAccessible()) { // NOPMD, handle problem first
field.setAccessible(true);
componentProxy = (ComponentProxy) field.get(component);
if (componentProxy == null) {
componentProxy = new ComponentProxy(
field, component, componentChannel);
}
field.setAccessible(false);
} else {
componentProxy = (ComponentProxy) field.get(component);
if (componentProxy == null) {
componentProxy = new ComponentProxy(
field, component, componentChannel);
}
}
}
} catch (SecurityException | IllegalAccessException e) {
throw (RuntimeException) (new IllegalArgumentException(
"Cannot access component's manager attribute")).initCause(e);
}
return componentProxy;
} | java | {
"resource": ""
} |
q14093 | Response.getGraphObjectAs | train | public final <T extends GraphObject> T getGraphObjectAs(Class<T> graphObjectClass) {
if (graphObject == null) {
return null;
}
if (graphObjectClass == null) {
throw new NullPointerException("Must pass in a valid interface that extends GraphObject");
}
return graphObject.cast(graphObjectClass);
} | java | {
"resource": ""
} |
q14094 | Response.getGraphObjectListAs | train | public final <T extends GraphObject> GraphObjectList<T> getGraphObjectListAs(Class<T> graphObjectClass) {
if (graphObjectList == null) {
return null;
}
return graphObjectList.castToListOf(graphObjectClass);
} | java | {
"resource": ""
} |
q14095 | Response.getRequestForPagedResults | train | public Request getRequestForPagedResults(PagingDirection direction) {
String link = null;
if (graphObject != null) {
PagedResults pagedResults = graphObject.cast(PagedResults.class);
PagingInfo pagingInfo = pagedResults.getPaging();
if (pagingInfo != null) {
if (direction == PagingDirection.NEXT) {
link = pagingInfo.getNext();
} else {
link = pagingInfo.getPrevious();
}
}
}
if (Utility.isNullOrEmpty(link)) {
return null;
}
if (link != null && link.equals(request.getUrlForSingleRequest())) {
// We got the same "next" link as we just tried to retrieve. This could happen if cached
// data is invalid. All we can do in this case is pretend we have finished.
return null;
}
Request pagingRequest;
try {
pagingRequest = new Request(request.getSession(), new URL(link));
} catch (MalformedURLException e) {
return null;
}
return pagingRequest;
} | java | {
"resource": ""
} |
q14096 | FreeMarkerRequestHandler.freemarkerConfig | train | protected Configuration freemarkerConfig() {
if (fmConfig == null) {
fmConfig = new Configuration(Configuration.VERSION_2_3_26);
fmConfig.setClassLoaderForTemplateLoading(
contentLoader, contentPath);
fmConfig.setDefaultEncoding("utf-8");
fmConfig.setTemplateExceptionHandler(
TemplateExceptionHandler.RETHROW_HANDLER);
fmConfig.setLogTemplateExceptions(false);
}
return fmConfig;
} | java | {
"resource": ""
} |
q14097 | FreeMarkerRequestHandler.fmSessionModel | train | protected Map<String, Object> fmSessionModel(Optional<Session> session) {
@SuppressWarnings("PMD.UseConcurrentHashMap")
final Map<String, Object> model = new HashMap<>();
Locale locale = session.map(
sess -> sess.locale()).orElse(Locale.getDefault());
model.put("locale", locale);
final ResourceBundle resourceBundle = resourceBundle(locale);
model.put("resourceBundle", resourceBundle);
model.put("_", new TemplateMethodModelEx() {
@Override
@SuppressWarnings("PMD.EmptyCatchBlock")
public Object exec(@SuppressWarnings("rawtypes") List arguments)
throws TemplateModelException {
@SuppressWarnings("unchecked")
List<TemplateModel> args = (List<TemplateModel>) arguments;
if (!(args.get(0) instanceof SimpleScalar)) {
throw new TemplateModelException("Not a string.");
}
String key = ((SimpleScalar) args.get(0)).getAsString();
try {
return resourceBundle.getString(key);
} catch (MissingResourceException e) {
// no luck
}
return key;
}
});
return model;
} | java | {
"resource": ""
} |
q14098 | FreeMarkerRequestHandler.resourceBundle | train | protected ResourceBundle resourceBundle(Locale locale) {
return ResourceBundle.getBundle(
contentPath.replace('/', '.') + ".l10n", locale,
contentLoader, ResourceBundle.Control.getNoFallbackControl(
ResourceBundle.Control.FORMAT_DEFAULT));
} | java | {
"resource": ""
} |
q14099 | ManagedBufferPool.removeBuffer | train | private void removeBuffer(W buffer) {
createdBufs.decrementAndGet();
if (bufferMonitor.remove(buffer) == null) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.WARNING,
"Attempt to remove unknown buffer from pool.",
new Throwable());
} else {
logger.warning("Attempt to remove unknown buffer from pool.");
}
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.