id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
5445246_4 | public LiteralExtractor() {
} |
5449213_0 | public long round(final long timestamp) {
final long rounded = _cache.get(timestamp);
if(rounded == _noEntryKey)
return roundAndCache(timestamp);
else
return rounded;
} |
5455271_0 | public void loadSubclusters(String subclustersString) {
ConcurrentHashMap<String, List<String>> map = new ConcurrentHashMap<String, List<String>>();
if(subclustersString != null) {
subclustersString = subclustersString.replaceAll(" ", "");
String[] groups = subclustersString.split("\\)\\(");
for(int q=0; q<groups.length; q++) {
String group = groups[q];
group = group.replaceAll("\\(", "").replaceAll("\\)","");
String[] hosts = group.split(",");
LinkedList<String> hostGroupList = new LinkedList<String>();
for(String host:hosts) {
if(host.length()>0) {
if(hostGroupList.contains(host)) {
throw new RuntimeException("Duplicate host " + host + " in " + hosts);
}
hostGroupList.add(host);
}
}
for(String host:hosts) {
List<String> tmp = new LinkedList<String>(hostGroupList);
tmp.remove(host);
map.put(host, tmp);
}
}
}
nodeToNodeGroup = map;
} |
5455433_389 | @Override
public boolean equals(Object other) {
if (other == null) {
return false;
}
if (!(other instanceof Text)) {
return false;
}
Text t = (Text) other;
if (this.len != t.len) {
return false;
}
//return this.hashCode() == t.hashCode();
return compareChars(t.chars, t.pos);
} |
5455441_14 | public String getSerializedData() {
if (this.data == null)
return "";
else {
boolean isFirst = true;
StringBuilder sb = new StringBuilder();
for (long l : data) {
if (isFirst)
isFirst = false;
else
sb.append(".");
sb.append(l);
}
return sb.toString();
}
} |
5455452_5 | public byte[] readIndefinite() throws AsnException, IOException {
int startPos = this.pos;
this.advanceIndefiniteLength();
byte[] res = new byte[this.pos - startPos - 2];
System.arraycopy(this.buffer, this.start + startPos, res, 0, this.pos - startPos - 2);
return res;
} |
5455458_5 | @Override
public String toString() {
final StringBuilder buffer = new StringBuilder();
if (!initialPrompts.isEmpty()) {
buffer.append("ip=");
for (int index = 0; index < initialPrompts.size(); index++) {
buffer.append(initialPrompts.get(index));
if (index < initialPrompts.size() - 1) {
//https://github.com/RestComm/Restcomm-Connect/issues/1988
buffer.append(",");
}
}
}
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("dr=").append(driver);
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("ln=").append(lang);
if (endInputKey != null) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("eik=").append(endInputKey);
}
if (maximumRecTimer > 0) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("mrt=").append(maximumRecTimer * 10);
}
if (waitingInputTimer > 0) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("wit=").append(waitingInputTimer * 10);
}
if (timeAfterSpeech > 0) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("pst=").append(timeAfterSpeech * 10);
}
if (hotWords != null) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("hw=").append(Hex.encodeHexString(hotWords.getBytes()));
}
if (input != null) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("in=").append(input);
}
if (minNumber > 0) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("mn=").append(minNumber);
}
if (maxNumber > 0) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("mx=").append(maxNumber);
}
if (partialResult) {
if (buffer.length() > 0)
buffer.append(SPACE_CHARACTER);
buffer.append("pr=").append(partialResult);
}
return buffer.toString();
} |
5455474_2 | @Override
public void addCcMccmnc(String countryCode, String mccMnc, String smsc) throws Exception {
CcMccmncImpl ccMccmnc = new CcMccmncImpl(countryCode, mccMnc, smsc);
ccMccmncCollection.addCcMccmnc(ccMccmnc);
this.store();
} |
5455483_0 | public String getUssdString() {
return ussdString;
} |
5473913_0 | public TransactionManager() {
final File dir = new File("data");
dir.mkdirs();
timer = new Timer("TransactionTimeoutThread", false);
timer.schedule(new TimerTask() {
@Override
public void run() {
lock.lock();
try {
long start = System.currentTimeMillis();
for (File file : dir.listFiles()) {
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
String line = in.readLine();
long timestamp = Long.parseLong(line);
long now = System.currentTimeMillis();
// Check if the transaction has timed-out and if yes, kill it
if (timestamp + now > TIMEOUT) {
file.delete();
}
} catch (IOException e) {
file.delete(); // kill the transaction
}
}
long stop = System.currentTimeMillis();
System.out.printf("Time: %d%n", stop - start);
} finally {
lock.unlock();
}
TransactionManager.this.notifyAll();
}
}, 0, 30000);
} |
5487921_15 | public static int compare(String oneVersion, String anotherVersion) {
return new Version(oneVersion).compareTo(new Version(anotherVersion));
} |
5495870_6 | protected static boolean installedFromMarket(WeakReference<? extends Context> weakContext) {
boolean result = false;
Context context = weakContext.get();
if (context != null) {
try {
String installer = context.getPackageManager().getInstallerPackageName(context.getPackageName());
// if installer string is not null it might be installed by market
if (!TextUtils.isEmpty(installer)) {
result = true;
// on Android Nougat and up when installing an app through the package installer (which HockeyApp uses itself), the installer will be
// "com.google.android.packageinstaller" or "com.android.packageinstaller" which is also not to be considered as a market installation
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && (TextUtils.equals(installer, INSTALLER_PACKAGE_INSTALLER_NOUGAT) || TextUtils.equals(installer, INSTALLER_PACKAGE_INSTALLER_NOUGAT2))) {
result = false;
}
// on some devices (Xiaomi) the installer identifier will be "adb", which is not to be considered as a market installation
if (TextUtils.equals(installer, INSTALLER_ADB)) {
result = false;
}
}
} catch (Throwable ignored) {
}
}
return result;
} |
5502061_0 | @Override
public org.slf4j.Logger getLogger(String name)
{
LoggerAdapter logger = loggers.get(name);
if (logger == null) {
logger = createLogger(name);
LoggerAdapter logger2 = loggers.putIfAbsent(name, logger);
if (logger2 != null) logger = logger2;
}
return logger;
} |
5509523_13 | @Override
public Stats stats() {
return this.statistics;
} |
5510832_6 | @Override
public boolean write(boolean isByteMode, int address, int value) {
return false;
} |
5517956_3 | @Override
public int compare( final ProjectRelationship<?, ?> one, final ProjectRelationship<?, ?> two )
{
if ( one.getType() == two.getType() )
{
if ( one.getPomLocation()
.equals( RelationshipConstants.POM_ROOT_URI ) && !two.getPomLocation()
.equals( RelationshipConstants.POM_ROOT_URI ) )
{
return -1;
}
else if ( !one.getPomLocation()
.equals( RelationshipConstants.POM_ROOT_URI ) && two.getPomLocation()
.equals( RelationshipConstants.POM_ROOT_URI ) )
{
return 1;
}
int res = one.getDeclaring().compareTo( two.getDeclaring() );
if ( res == 0 )
{
res = one.getIndex() - two.getIndex();
}
return res;
}
else
{
return one.getType()
.ordinal() - two.getType()
.ordinal();
}
} |
5529658_109 | protected List<ModuleBuildFuture> collectFutures(ModuleList moduleList, HttpServletRequest request)
throws IOException {
final String sourceMethod = "collectFutures"; //$NON-NLS-1$
final boolean isTraceLogging = log.isLoggable(Level.FINER);
if (isTraceLogging) {
log.entering(sourceClass, sourceMethod, new Object[]{moduleList, request});
}
IAggregator aggr = (IAggregator)request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME);
List<ModuleBuildFuture> futures = new ArrayList<ModuleBuildFuture>();
IModuleCache moduleCache = aggr.getCacheManager().getCache().getModules();
// For each source file, add a Future<IModule.ModuleReader> to the list
for(ModuleList.ModuleListEntry moduleListEntry : moduleList) {
IModule module = moduleListEntry.getModule();
Future<ModuleBuildReader> future = null;
try {
future = moduleCache.getBuild(request, module);
} catch (NotFoundException e) {
if (log.isLoggable(Level.FINER)) {
log.logp(Level.FINER, sourceClass, sourceMethod, moduleListEntry.getModule().getModuleId() + " not found."); //$NON-NLS-1$
}
future = new NotFoundModule(module.getModuleId(), module.getURI()).getBuild(request);
if (!moduleListEntry.isServerExpanded()) {
// Treat as error. Return error response, or if debug mode, then include
// the NotFoundModule in the response.
if (options.isDevelopmentMode() || options.isDebugMode()) {
// Don't cache responses containing error modules.
request.setAttribute(ILayer.NOCACHE_RESPONSE_REQATTRNAME, Boolean.TRUE);
} else {
// Rethrow the exception to return an error response
throw e;
}
} else {
// Not an error if we're doing server-side expansion, but if debug mode
// then get the error message from the completed future so that we can output
// a console warning in the browser.
if (options.isDevelopmentMode() || options.isDebugMode()) {
try {
nonErrorMessages.add(future.get().getErrorMessage());
} catch (Exception ex) {
// Sholdn't ever happen as this is a CompletedFuture
throw new RuntimeException(ex);
}
}
if (isTraceLogging) {
log.logp(Level.FINER, sourceClass, sourceMethod, "Ignoring exception for server expanded module " + e.getMessage(), e); //$NON-NLS-1$
}
// Don't add the future for the error module to the response.
continue;
}
} catch (UnsupportedOperationException ex) {
// Missing resource factory or module builder for this resource
if (moduleListEntry.isServerExpanded()) {
// ignore the error if it's a server expanded module
if (isTraceLogging) {
log.logp(Level.FINER, sourceClass, sourceMethod, "Ignoring exception for server expanded module " + ex.getMessage(), ex); //$NON-NLS-1$
}
continue;
} else {
// re-throw the exception
throw ex;
}
}
futures.add(new ModuleBuildFuture(
module,
future,
moduleListEntry.getSource()
));
}
if (isTraceLogging) {
log.exiting(sourceClass, sourceMethod, futures);
}
return futures;
} |
5551767_0 | public static void main(String[] args) {
String file = "C:/Users/Kerwyn/Desktop/pg17989.txt";
String preprocessed_file = "";
try {
preprocessed_file = preprocess(file);
} catch (FileNotFoundException e) {
/* file doesn't exist */
System.err.println(file + " doesn't exists. Pick one instead.");
JFileChooser f = new JFileChooser();
f.showOpenDialog(null);
file = f.getSelectedFile().getPath();
try {
preprocessed_file = preprocess(file);
} catch (FileNotFoundException e1) {
System.err.println(file + " doesn't exist either. Exiting.");
return;
}
}
System.out.println("Finished writing "+ preprocessed_file);
} |
5561881_3 | public Object run(final String functionReference, final Object... values) {
// Create a local copy of the bindings so we can multi-thread.
Context context = enterContext();
try {
Scriptable object = this.localScope;
Iterator<String> parts = Splitter.on('.').split(functionReference).iterator();
while (parts.hasNext()) {
String property = parts.next();
if (parts.hasNext()) {
object = (Scriptable) ScriptableObject.getProperty(object, property);
} else {
return unwrap(ScriptableObject.callMethod(context, object, property, jsValues(values)));
}
}
throw new IllegalArgumentException("functionName is empty");
} finally {
exitContext();
}
} |
5590873_13 | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNotContainedArgumentException.class })
public static <T extends Object> void contains(final boolean condition, @Nonnull final Collection<T> haystack, @Nonnull final T needle) {
if (condition) {
Check.contains(haystack, needle);
}
} |
5598875_74 | public synchronized boolean cancel(boolean block)
{
switch (state) {
case COMPLETED:
case CANCELLED:
// the task has already completed or been cancelled
return false;
case RUNNING:
if (block) {
while (state == State.RUNNING) {
// if the task is already running, we just wait for
// it to complete
try {
wait();
} catch (InterruptedException ie) {
// ignore this exception because we must block
// until the task has completed
}
}
if (!isDone()) {
cancel();
return true;
}
}
return false;
case RUNNABLE:
case INTERRUPTED:
// the task has not started yet or has already been interrupted,
// so we can cancel it safely
cancel();
return true;
default:
// should never get here
return false;
}
} |
5601676_139 | public String getApplicationDescription() {
return applicationDescription;
} |
5610434_1 | public static Page createPage(String rawJSON) throws FacebookException {
try {
JSONObject json = new JSONObject(rawJSON);
return pageConstructor.newInstance(json);
} catch (InstantiationException e) {
throw new FacebookException(e);
} catch (IllegalAccessException e) {
throw new AssertionError(e);
} catch (InvocationTargetException e) {
throw new FacebookException(e);
} catch (JSONException e) {
throw new FacebookException(e);
}
} |
5615967_1 | protected ModelEvent remove(EditorModel em, String key) {
elementMap.remove(key);
return new DefaultModelEvent(commandName, this, null, null, changed);
} |
5626414_3 | @Override
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
if (lookupPath.startsWith(serviceRootPathWithSlash)) {
doHandleMatch(doCreateRequestMappingInfo(), lookupPath, request);
return new HandlerMethod(handler, handlerMethod);
}
return super.lookupHandlerMethod(lookupPath, request);
} |
5632139_73 | public String getInstanceId() {
return instanceId;
} |
5634637_2 | private Schema getSchema() {
try {
return Utils.getSchemaFromString(getProperties().getProperty(SCHEMA));
} catch (ParserException e) {
throw new RuntimeException("can not get schema from context", e);
}
} |
5643380_43 | @Override
public int hashCode() {
int hash = 7;
hash = 89 * hash + fileIssue.hashCode();
return hash;
} |
5661262_0 | public boolean changeCallSiteTarget(String methodType, String oldTarget, String newTarget) throws IOException {
Map obj = new LinkedHashMap();
obj.put("call", "changeCallSiteTarget");
obj.put("methodType", methodType);
obj.put("oldTarget", oldTarget);
obj.put("newTarget", newTarget);
String stringResult = send(JSONValue.toJSONString(obj));
JSONObject jsonResult = (JSONObject) JSONValue.parse(stringResult);
return isThatOk(jsonResult);
} |
5674787_263 | public static CFG buildCFG(List<? extends Tree> trees, boolean ignoreBreak) {
return new CFG(trees, null, ignoreBreak);
} |
5675901_29 | @Override
public <A extends RestAction<R>, R> R deserialize(A action, Response response) throws ActionException {
if (isSuccessStatusCode(response)) {
return getDeserializedResponse(action, response);
} else {
throw new ActionException(response.getStatusText());
}
} |
5683980_4 | @SuppressWarnings("unchecked")
@Override
public void execute() {
log(Main.getAntVersion());
log("SonarQube Ant Task version: " + SonarQubeTaskUtils.getTaskVersion());
log("Loaded from: " + SonarQubeTaskUtils.getJarPath());
Map<String, String> allProps = new HashMap<>();
allProps.put(PROJECT_BASEDIR_PROPERTY, getProject().getBaseDir().getAbsolutePath());
if (SonarQubeTaskUtils.getAntLoggerLever(getProject()) >= 3) {
allProps.put(VERBOSE_PROPERTY, "true");
}
putAll(Utils.loadEnvironmentProperties(getEnv()), allProps);
allProps.putAll(getProject().getProperties());
if ("true".equalsIgnoreCase(allProps.get(ScanProperties.SKIP))) {
log("SonarQube Scanner analysis skipped");
return;
}
launchAnalysis(allProps);
} |
5686301_34 | @CheckForNull
public File get(String filename, String hash) {
Path cachedFile = dir.resolve(hash).resolve(filename);
if (Files.exists(cachedFile)) {
return cachedFile.toFile();
}
logger.debug(String.format("No file found in the cache with name %s and hash %s", filename, hash));
return null;
} |
5704054_2 | @Override
public void update(final Entity e) throws URISyntaxException, MessageProcessingException, IOException,
SLIClientException {
URL url = URLBuilder.create(restClient.getBaseURL()).entityType(e.getEntityType()).id(e.getId()).build();
Response response = restClient.putRequest(url, mapper.writeValueAsString(e));
checkResponse(response, Status.NO_CONTENT, "Unable to update entity.");
} |
5706983_1 | static public int findSampleLessOrEqual(ChartSampleSequence samples, double x)
{
synchronized (samples)
{
ChartSampleSearch binary = new ChartSampleSearch();
if (binary.search(samples, x))
return binary.mid;
// Didn't find exact match.
if (binary.cmp < 0) // 'mid' sample is smaller than x, so it's OK
return binary.mid;
// cmp > 0, 'mid' sample is greater than x.
// If there is a sample before, use that
if (binary.mid > 0)
return binary.mid-1;
return -1;
}
} |
5710819_3 | protected void setNumTTVMsForCluster(VHMInputMessage input) {
CompoundStatus thisStatus = new CompoundStatus("setNumTTVMsForCluster");
CompoundStatus vmChooserStatus = null;
CompoundStatus edPolicyStatus = null;
try {
HadoopCluster cluster = new HadoopCluster(input.getClusterName(), input.getJobTrackerAddress());
EnableDisableTTPolicy edPolicy = _config._enableDisablePolicy;
VMChooserAlgorithm vmChooser = _config._vmChooser;
_pLog.registerProgress(10);
_log.log(Level.INFO, "Getting cluster inventory information...");
VMDTO[] allTTs = getAllTTsForAllHosts(thisStatus, input.getTTFolderNames(),
input.getSerengetiRootFolder(), input.getClusterName());
if ((allTTs == null) || (allTTs.length == 0)) {
processCompoundStatuses(thisStatus, vmChooserStatus, edPolicyStatus);
return;
}
TTStatesForHost[] ttStatesForHosts = _config._enableDisablePolicy.getStateForTTs(allTTs);
int totalEnabled = 0;
for (TTStatesForHost ttStatesForHost : ttStatesForHosts) {
totalEnabled += ttStatesForHost.getEnabled().size();
}
int targetTTs = 0;
if (input.getTargetTTs() == UNLIMIT_CMD) {
_log.log(Level.INFO, "Request to unlimit TT VMs");
targetTTs = allTTs.length;
} else {
targetTTs = input.getTargetTTs();
}
int delta = (targetTTs - totalEnabled);
_log.log(Level.INFO, "Total TT VMs = "+allTTs.length+", total powered-on TT VMs = "+totalEnabled+", target powered-on TT VMs = "+targetTTs);
_pLog.registerProgress(30);
if (input.getTargetTTs() == UNLIMIT_CMD) {
VMDTO[] ttsToEnable = chooseAllTTVMs(ttStatesForHosts);
_pLog.registerProgress(40);
/* The expectation is that enableVMs is blocking */
vmChooserStatus = new CompoundStatus("Null VMChooser"); /* Ensure it's not null */
edPolicyStatus = edPolicy.enableTTs(ttsToEnable, ttsToEnable.length, cluster);
_pLog.registerProgress(90);
} else if (delta > 0) {
_log.log(Level.INFO, "Target TT VMs to enable/disable = "+delta);
VMCAResult chooserResult = vmChooser.chooseVMsToEnable(ttStatesForHosts, allTTs.length, delta);
VMDTO[] ttsToEnable = chooserResult.getChosenVMs();
vmChooserStatus = chooserResult.getChooserStatus();
_pLog.registerProgress(40);
/* The expectation is that enableVMs is blocking */
edPolicyStatus = edPolicy.enableTTs(ttsToEnable, (ttsToEnable.length + totalEnabled), cluster);
_pLog.registerProgress(90);
} else if (delta < 0) {
_log.log(Level.INFO, "Target TT VMs to enable/disable = "+delta);
VMCAResult chooserResult = vmChooser.chooseVMsToDisable(ttStatesForHosts, allTTs.length, 0 - delta);
VMDTO[] ttsToDisable = chooserResult.getChosenVMs();
vmChooserStatus = chooserResult.getChooserStatus();
_pLog.registerProgress(40);
/* The expectation is that disableVMs is blocking */
edPolicyStatus = edPolicy.disableTTs(ttsToDisable, (totalEnabled - ttsToDisable.length), cluster);
_pLog.registerProgress(90);
}
} catch (Exception e) {
_log.log(Level.SEVERE, "Unexpected error in core VHM: "+e);
thisStatus.registerTaskFailed(true, e.getMessage());
}
processCompoundStatuses(thisStatus, vmChooserStatus, edPolicyStatus);
} |
5722110_54 | @Override
public <T> T convert(Object source, T target, String... tags) {
if (null == source || null == target) {
throw new JTransfoException("Source and target are required to be not-null.");
}
source = replaceObject(source);
boolean targetIsTo = false;
if (!toHelper.isTo(source)) {
targetIsTo = true;
if (!toHelper.isTo(target)) {
throw new JTransfoException(String.format("Neither source nor target are annotated with DomainClass " +
"on classes %s and %s.", source.getClass().getName(), target.getClass().getName()));
}
}
if (0 == tags.length) {
tags = DEFAULT_TAGS_WHEN_NO_TAGS;
}
return convertInterceptorChain.convert(source, target, targetIsTo, tags);
} |
5726012_9 | public DeviceControllerDeviceStatus getDeviceStatus() throws IOException {
// get status from device
int deviceStatus = read(MEMADDR_STATUS);
// check formal criterias
int reservedValue = deviceStatus & STATUS_RESERVED_MASK;
if (reservedValue != STATUS_RESERVED_VALUE) {
throw new IOException(
"status-bits 4 to 8 must be 1 according to documentation chapter 4.2.2.1. got '"
+ Integer.toString(reservedValue, 2)
+ "'!");
}
// build the result
boolean eepromWriteActive
= (deviceStatus & STATUS_EEPROM_WRITEACTIVE_BIT) > 0;
boolean eepromWriteProtection
= (deviceStatus & STATUS_EEPROM_WRITEPROTECTION_BIT) > 0;
boolean wiperLock0
= (deviceStatus & STATUS_WIPERLOCK0_BIT) > 0;
boolean wiperLock1
= (deviceStatus & STATUS_WIPERLOCK1_BIT) > 0;
return new DeviceControllerDeviceStatus(
eepromWriteActive, eepromWriteProtection,
wiperLock0, wiperLock1);
} |
5740378_0 | @Override
public final int compareTo(final StorageUnit<?> that) {
return this.bytes.compareTo(that.bytes);
} |
5745625_3 | ; |
5754848_4 | @DELETE
public void deleteAll() {
dao.deleteAll();
} |
5770443_0 | public JDefinedClass build() {
JPackage _package = determinePackage();
try {
definedClass = _package._enum(typeName);
} catch (JClassAlreadyExistsException e) {
throw new RuntimeException(e.getExistingClass().fullName() + " is already defined in the code model.", e);
}
addJavadocs();
addInterfaces();
addEnumConstants();
addFields();
addConstructor();
addNameGetter();
addValueGetter();
// TODO add static findValue method: use a case statement, the compiler should be able to convert that into a binary search
// alternative: use the holder pattern to lazily and thread-safely initialize (and perhaps expose, but read-only) a data structure
addToString();
return definedClass;
} |
5793618_42 | public Collection<T> createAll(final Object... arguments) {
Collection<T> instances = new ArrayList<T>(classes.size());
for (String className : classes) {
T instance = createInstance(className, arguments);
if (instance != null) {
instances.add(instance);
}
}
return instances;
} |
5793738_15 | public CreateTaskVariablePayload handleCreateTaskVariablePayload(CreateTaskVariablePayload createTaskVariablePayload) {
checkNotValidCharactersInVariableName(createTaskVariablePayload.getName(),
"Variable has not a valid name: ");
Object value = createTaskVariablePayload.getValue();
if (value instanceof String) {
handleAsDate((String)value).ifPresent(createTaskVariablePayload::setValue);
}
return createTaskVariablePayload;
} |
5832036_1 | @Override
public void add(Network network) {
switch (network.getType()) {
case WIFI:
addWiFi( network );
break;
case CDMA:
case GSM:
case WCDMA:
case LTE:
addCell(network);
break;
case BT:
addBluetooth(network);
break;
case BLE:
addBluetoothLe(network);
break;
}
} |
5839179_20 | public String getForegroundColor() {
return foregroundColor;
} |
5841522_1 | public void updateIndex() {
long startTime = System.currentTimeMillis();
try {
if (searchStatusHolder.getStatus() != SearchStatus.WAITING) {
throw new IndexingUnderwayException();
}
JochreSearchManager manager = JochreSearchManager.getInstance(configId);
searchStatusHolder.setStatus(SearchStatus.PREPARING);
Map<String, Analyzer> analyzerPerField = new HashMap<>();
analyzerPerField.put(JochreIndexField.text.name(), new JochreTextLayerAnalyser(this, configId));
analyzerPerField.put(JochreIndexField.author.name(), new JochreKeywordAnalyser(configId));
analyzerPerField.put(JochreIndexField.authorEnglish.name(), new JochreKeywordAnalyser(configId));
analyzerPerField.put(JochreIndexField.publisher.name(), new JochreKeywordAnalyser(configId));
PerFieldAnalyzerWrapper analyzer = new PerFieldAnalyzerWrapper(new JochreMetaDataAnalyser(configId),
analyzerPerField);
IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
iwc.setOpenMode(OpenMode.CREATE_OR_APPEND);
try (IndexWriter indexWriter = new IndexWriter(manager.getIndexDir(), iwc)) {
File[] subdirs = contentDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
if (subdirs.length == 0)
throw new IllegalArgumentException("content dir is empty: " + contentDir.getPath());
Arrays.sort(subdirs);
searchStatusHolder.setStatus(SearchStatus.BUSY);
searchStatusHolder.setTotalCount(subdirs.length);
for (File subdir : subdirs) {
try {
searchStatusHolder.setAction("Indexing " + subdir.getName());
this.processDocument(manager, indexWriter, subdir, forceUpdate);
searchStatusHolder.incrementSuccessCount(1);
} catch (Exception e) {
LOG.error("Failed to index " + subdir.getName(), e);
searchStatusHolder.incrementFailureCount(1);
}
}
LOG.info("Commiting index...");
searchStatusHolder.setStatus(SearchStatus.COMMITING);
indexWriter.commit();
indexWriter.close();
manager.getManager().maybeRefresh();
}
} catch (IOException e) {
LOG.error("Failed to update index", e);
throw new RuntimeException(e);
} catch (RuntimeException e) {
LOG.error("Failed to update index", e);
throw e;
} catch (Exception e) {
LOG.error("Failed to update index", e);
throw new RuntimeException(e);
} finally {
searchStatusHolder.setStatus(SearchStatus.WAITING);
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
LOG.info("Total time (ms): " + totalTime);
}
} |
5853673_2 | @Override
public String classToTableName(String className) {
return super.classToTableName(className).toUpperCase();
} |
5861549_2 | boolean renderMarker(List<Point3D_F64> marker, Se3_F64 BodyToCamera, List<Point2D_F64> pixels) {
Point3D_F64 p3 = new Point3D_F64();
for (int indexCorner = 0; indexCorner < marker.size(); indexCorner++) {
BodyToCamera.transform(marker.get(indexCorner), p3);
if( p3.z <= 0 )
return false;
Point2D_F64 pixel = pixels.get(indexCorner);
normToPixel.compute(p3.x / p3.z, p3.y / p3.z, pixel);
pixel.x += random.nextGaussian() * stdevPixel;
pixel.y += random.nextGaussian() * stdevPixel;
// make sure it's inside image and could be observed
if (pixel.x < 0 || pixel.x >= imageWidth - 1)
return false;
if (pixel.y < 0 || pixel.y >= imageHeight - 1)
return false;
}
return true;
} |
5874016_2 | @Override
public void annotate(JCas aJCas) throws AlignmentComponentException {
// get T lemma sequence as one single string
String tLemmaSeq = null; // TEXTVIEW Lemma sequences (ordered) as one string, for quick existence check
/ String hLemmaSeq = null; // HYPOTHESISVIEW Lemma sequences (ordered) as one string, for candidate generation
Lemma[] tSideLemmas = null;
/ Lemma[] hSideLemmas = null;
List<Lemma[]> allHSideCandidates = null;
try {
tLemmaSeq = getLemmasAsStringSequence(aJCas.getView(LAP_ImplBase.TEXTVIEW));
Collection<Lemma> lemmas = JCasUtil.select(aJCas.getView(LAP_ImplBase.TEXTVIEW), Lemma.class);
tSideLemmas = lemmas.toArray(new Lemma[lemmas.size()]);
/ hLemmaSeq = getLemmasAsStringSequence(aJCas.getView(LAP_ImplBase.HYPOTHESISVIEW));
allHSideCandidates = getAllPossibleCandidates(aJCas.getView(LAP_ImplBase.HYPOTHESISVIEW));
}
catch (CASException ce)
{
throw new AlignmentComponentException("unable to access views (text or hypothesis) of the given CAS");
}
// for each candidate, query the underlying resource,
// check for applicable rules; and if found, add alignment.link.
try {
for (Lemma[] oneCand : allHSideCandidates)
{
// TEXT -> HYPOTHESIS SIDE first
String candVal = lemmaArrAsString(oneCand);
//logger.debug("check cand: " + candVal);
for (LexicalRule<? extends RuleInfo> rule : underlyingResource.getRulesForRight(candVal, null))
{
// does this rule applicable in this T-H pair?
if (tLemmaSeq.contains(rule.getLLemma()))
{
// if so, add an alignment link!
addAlignmentLinkT2H(aJCas, rule, tSideLemmas, oneCand);
}
}
// TODO (MAYBE?) Reflect POS (especially one-word entry)
// please note that here, getRulesForRight call is done without POS info. (null)
// This is mainly because that we do "phrase" level support where we
// can't really tell POS apart (multiple POSes).
// But for single-word queries, we might still can use POS; but for now,
// we don't pass POS, just as old lexical aligner did not.
// TODO (PROLLY)
// HYPOTHESIS -> TEXT side too, if we need.
}
} catch (LexicalResourceException le)
{
throw new AlignmentComponentException("Underlying Lexical Resource raised an exception: " + le.getMessage(), le);
}
} |
5887512_0 | @Override
public boolean matches(RenderContext context) {
if (expression == null) {
throw new IllegalStateException("Missing expression statement.");
}
ExpressionEvaluator evaluator = context.getExpressionEvaluator();
Object result = evaluator.evaluate(expression,
context.getExpressionContext());
if (result != null) {
return "true".equalsIgnoreCase(result.toString().trim());
} else {
return false;
}
} |
5947247_22 | public void setOrdinate(int index, int ordinateIndex, double value) {
switch (ordinateIndex) {
case 0:
x[index] = value;
break;
case 1:
y[index] = value;
break;
default:
throw new IllegalArgumentException("invalid ordinate index: " + ordinateIndex);
}
} |
5970660_5 | public String createDate(Date d) {
// Shift the timezone to UTC
SimpleDateFormat dateFormatter = new SimpleDateFormat(YEAR_MONTH_DAY_FORMAT);
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
// ICal DATE pattern: <yyyyMMdd>
return dateFormatter.format(d);
} |
5973879_0 | @Override
public void beforeSave(StorageItem storageItem, StorageItemUploadPart part) throws IOException {
if (part == null) {
return;
}
String fileContentType = part.getContentType();
if (fileContentType == null) {
return;
}
String groupsPattern = Settings.get(String.class, "cms/tool/fileContentTypeGroups");
Set<String> contentTypeGroups = new SparseSet(ObjectUtils.isBlank(groupsPattern) ? "+/" : groupsPattern);
Preconditions.checkState(contentTypeGroups.contains(fileContentType),
"Invalid content type " + fileContentType + ". Must match the pattern " + contentTypeGroups + ".");
// Disallow HTML disguising as other content types per:
// http://www.adambarth.com/papers/2009/barth-caballero-song.pdf
if (!contentTypeGroups.contains("text/html")) {
if (part.getFile() == null) {
return;
}
try (InputStream input = new FileInputStream(part.getFile())) {
byte[] buffer = new byte[1024];
String data = new String(buffer, 0, input.read(buffer)).toLowerCase(Locale.ENGLISH);
String ptr = data.trim();
if (ptr.startsWith("<!")
|| ptr.startsWith("<?")
|| data.startsWith("<html")
|| data.startsWith("<script")
|| data.startsWith("<title")
|| data.startsWith("<body")
|| data.startsWith("<head")
|| data.startsWith("<plaintext")
|| data.startsWith("<table")
|| data.startsWith("<img")
|| data.startsWith("<pre")
|| data.startsWith("text/html")
|| data.startsWith("<a")
|| ptr.startsWith("<frameset")
|| ptr.startsWith("<iframe")
|| ptr.startsWith("<link")
|| ptr.startsWith("<base")
|| ptr.startsWith("<style")
|| ptr.startsWith("<div")
|| ptr.startsWith("<p")
|| ptr.startsWith("<font")
|| ptr.startsWith("<applet")
|| ptr.startsWith("<meta")
|| ptr.startsWith("<center")
|| ptr.startsWith("<form")
|| ptr.startsWith("<isindex")
|| ptr.startsWith("<h1")
|| ptr.startsWith("<h2")
|| ptr.startsWith("<h3")
|| ptr.startsWith("<h4")
|| ptr.startsWith("<h5")
|| ptr.startsWith("<h6")
|| ptr.startsWith("<b")
|| ptr.startsWith("<br")) {
throw new IOException("Can't upload [" + fileContentType + "] file disguising as HTML!");
}
}
}
} |
5999841_31 | public List<LogEntry> getLogEntriesForTenant(int tenantId, int offset, int limit) {
Preconditions.checkArgument(offset >= 0, "offset must be greater than or equal to 0");
Preconditions.checkArgument(limit >= 0, "limit must be greater than or equal to 0");
return getLogEntriesForTenant.execute(tenantId, offset, limit);
} |
6002930_4 | @Override
protected void check(MappedClass mc, MappedField mf, Set<ConstraintViolation> ve) {
if (mf.isMap()) {
if (mf.hasAnnotation(Serialized.class)) {
Class<?> keyClass = ReflectionUtils.getParameterizedClass(mf.getField(), 0);
Class<?> valueClass = ReflectionUtils.getParameterizedClass(mf.getField(), 1);
if (keyClass != null) {
if (!Serializable.class.isAssignableFrom(keyClass))
ve.add(new ConstraintViolation(Level.FATAL, mc, mf, this.getClass(), "Key class (" + keyClass.getName()
+ ") is not Serializable"));
}
if (valueClass != null) {
if (!Serializable.class.isAssignableFrom(keyClass))
ve.add(new ConstraintViolation(Level.FATAL, mc, mf, this.getClass(), "Value class (" + valueClass.getName()
+ ") is not Serializable"));
}
}
}
} |
6010090_33 | public Collection<Link> getAll() {
return links;
} |
6017453_1 | public static <T extends Throwable> T anyCauseOf(Throwable ex, Class<T> type) {
if (type.isInstance(ex)) {
return (T) ex;
}
Throwable cause = ex.getCause();
if (cause != null) {
return anyCauseOf(cause, type);
}
return null;
} |
6018023_3 | @Override
public void authenticate(final String username, final String passwdOrToken)
throws UnauthorizedException {
try {
userService.checkUserAndHash(username, passwdOrToken);
LOG.info(String.format("User \'%s\' logged", username));
} catch (final Exception e) {
final String msg = String.format(USER_NOT_LOGGED, username);
LOG.warn(msg, e);
throw new UnauthorizedException(msg);
}
LOG.info(String.format("User \'%s\' logged", username));
} |
6022685_4 | public static Picture fromBitmap(Bitmap src) {
return inst().fromBitmapImpl(src);
} |
6051489_17 | @Override
public void onOpen(ResourceContext context) throws ItemStreamException {
context.setRowsToSkip(rowsToSkip);
} |
6064729_0 | @Override
public void outgoingBroadcast(Object message) {
getTopic().publish(message);
} |
6084210_1 | @Override
public boolean add(E e)
{
checkSize( 1 );
return super.add( e );
} |
6090885_1 | public static List<String> getGroups(String path, String regex) {
List<String> captures = new ArrayList<String>();
Matcher m = Pattern.compile(regex).matcher(path);
if (m.lookingAt()) {
for (int i = 1; i <= m.groupCount(); i++) {
if (m.group(i) != null) captures.add(m.group(i));
}
}
return captures;
} |
6092163_487 | @Override
public synchronized <T> T getService(Class<T> iface) {
Object service = this.serviceMap.get(iface);
if (service == null) {
service = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {iface}, new RemoteInvocationHandler(iface, false) {
@Override
protected SocketServerInstanceImpl getInstance() {
return SocketServerInstanceImpl.this;
}
});
this.serviceMap.put(iface, service);
}
return iface.cast(service);
} |
6104876_0 | @Override
public String toString() {
StringBuffer outBuf = new StringBuffer();
outBuf.append(this.DeviceType.name());
outBuf.append(": MAC(" + this.GetMacAddressString() + "), ");
outBuf.append("IP(" + this.IpAddress.toString() + "), ");
outBuf.append("Protocol Ver(" + this.ProtocolVersion + "), ");
outBuf.append("Vendor ID(" + this.VendorId + "), ");
outBuf.append("Product ID(" + this.ProductId + "), ");
outBuf.append("HW Rev(" + this.HardwareRevision + "), ");
outBuf.append("SW Rev(" + this.SoftwareRevision + "), ");
outBuf.append("Link Spd(" + this.LinkSpeed + "), ");
return outBuf.toString();
} |
6114161_12 | public static long getPercentile(List<Long> longList, int p, long defaultValue) {
if (longList == null || longList.isEmpty()) {
return defaultValue;
}
if (p < 0 || p > 100) {
return defaultValue;
}
int size = longList.size();
if (((long) size * (long) p) % 100L == 0) {
// 割り切れる→二値の平均
int n = (int) (((long) size - 1L) * (long) p / 100L);
long a = longList.get(n);
long b = longList.get(n + 1);
return (a + b) / 2L;
} else {
// 割り切れない→切り上げ
int n = (int) ((long) size * (long) p / 100L);
if (n >= size) {
n = size - 1;
}
return longList.get(n);
}
} |
6123097_32 | @Override
public void calculateFeatures(DocumentAffiliation affiliation) {
List<Token<AffiliationLabel>> tokens = affiliation.getTokens();
for (Token<AffiliationLabel> token : tokens) {
for (BinaryTokenFeatureCalculator binaryFeatureCalculator : binaryFeatures) {
if (binaryFeatureCalculator.calculateFeaturePredicate(token, affiliation)) {
token.addFeature(binaryFeatureCalculator.getFeatureName());
}
}
String wordFeatureString = wordFeature.calculateFeatureValue(token, affiliation);
if (wordFeatureString != null) {
token.addFeature(wordFeatureString);
}
}
for (KeywordFeatureCalculator<Token<AffiliationLabel>> dictionaryFeatureCalculator
: keywordFeatures) {
dictionaryFeatureCalculator.calculateDictionaryFeatures(tokens);
}
} |
6123437_2 | public static String getPropertyFromClassPath(String propertyFileResourcePath,String propertyName ) throws Exception {
Properties p = new Properties();
InputStream inStream = null;
try {
inStream = ClassSearchUtil.class.getClassLoader().getResourceAsStream(propertyFileResourcePath);
if (inStream == null){
throw new IOException("Property file not found in classpath. " + propertyFileResourcePath );
}
p.load(inStream);
} finally{
if (inStream != null){
inStream.close();
}
}
return p.getProperty(propertyName);
} |
6154058_11 | @Deprecated
public static void assemble(GraphCollection namedSignedGraph, Dataset graphOrigin) throws Exception {
Ontology o = prepareSignatureOntology(namedSignedGraph);
verifyGraphCollectionContainsExactlyOneNamedGraph(namedSignedGraph);
addSignatureTriplesToOrigin(namedSignedGraph, o, graphOrigin);
} |
6161685_14 | public Genotype asGenotype() {
return asGenotype(Locations.locations());
} |
6172406_648 | @Transactional
public void approve(Report report, Long requisitionId, Long userId) {
Rnr requisition = report.getRequisition(requisitionId, userId);
Rnr savedRequisition = requisitionService.getFullRequisitionById(requisition.getId());
if (!savedRequisition.getFacility().getVirtualFacility()) {
throw new DataException("error.approval.not.allowed");
}
if (savedRequisition.getNonSkippedLineItems().size() != report.getProducts().size()) {
throw new DataException("error.number.of.line.items.mismatch");
}
restRequisitionCalculator.validateProducts(report.getProducts(), savedRequisition);
requisitionService.save(requisition);
requisitionService.approve(requisition, report.getApproverName());
} |
6179560_1 | public KeySet(byte[] key, byte[] nonce) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException {
MaskGenerationFunction mgf = null;
mgf = new MaskGenerationFunction(MessageDigest.getInstance("SHA256"));
byte[] seed = new byte[key.length + nonce.length];
System.arraycopy(key, 0, seed, 0, key.length);
System.arraycopy(nonce, 0, seed, key.length, nonce.length);
byte[] mkey = mgf.generateMask(seed, 48);
Mac h = Mac.getInstance("HmacSHA256");
SecretKey hmacKey = new SecretKeySpec(mkey, h.getAlgorithm());
h.init(hmacKey);
this.serverEncrKey = h.doFinal("ServerEncr".getBytes(UTF_8));
h.reset();
this.serverAuthKey = h.doFinal("ServerAuth".getBytes(UTF_8));
h.reset();
this.clientAuthKey = h.doFinal("ClientAuth".getBytes(UTF_8));
h.reset();
this.clientEncrKey = h.doFinal("ClientEncr".getBytes(UTF_8));
h.reset();
this.encryptCipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
this.decryptCipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
byte[] iv = new byte[IV_LENGTH];
for (int i = 0; i < iv.length; i++) {
iv[i] = 0;
}
IvParameterSpec ivspec = new IvParameterSpec(iv);
SecretKeySpec clik = new SecretKeySpec(clientEncrKey, "AES");
this.encryptCipher.init(Cipher.ENCRYPT_MODE, clik, ivspec);
SecretKeySpec srvk = new SecretKeySpec(serverEncrKey, "AES");
this.decryptCipher.init(Cipher.DECRYPT_MODE, srvk, ivspec);
this.clientHmac = Mac.getInstance("HmacSHA256");
SecretKey cliAuthK = new SecretKeySpec(clientAuthKey, this.clientHmac.getAlgorithm());
clientHmac.init(cliAuthK);
this.serverHmac = Mac.getInstance("HmacSHA256");
SecretKey srvAuthK = new SecretKeySpec(serverAuthKey, this.serverHmac.getAlgorithm());
serverHmac.init(srvAuthK);
} |
6179800_6 | public T variable(String name, Object value) {
return param(name, value);
} |
6187281_10 | @Override
public TaskRegistration scheduleTask(TaskConfiguration config, Object bean) throws TaskSchedulerException {
if (config == null) {
throw new IllegalArgumentException("config is null");
}
if (bean == null) {
throw new IllegalArgumentException("bean is null");
}
if (this.scheduler == null) {
throw new IllegalStateException("schedule is null");
}
try {
// Argument 'bean' should implement either 'Task' or 'org.quartz.Job'
if (Task.class.isAssignableFrom(bean.getClass())) {
// this is the expected type, carry on
} else if (Job.class.isAssignableFrom(bean.getClass())) {
log.warn("[DEPRECATION] '{}' Implementing {} directly is deprecated, please implement {}",
bean.getClass().getCanonicalName(), Job.class.getName(), Task.class.getName());
} else {
throw new IllegalArgumentException(String.format("argument 'bean' does not implement interface " +
Task.class.getName()));
}
CronTrigger trigger = new CronTrigger(config.getName(), config.getGroup(), config.getCron());
JobDetail jobDetail = new JobDetail(config.getName(), config.getGroup(), this.getJobClass(config));
JobDataMap map = new JobDataMap();
map.put(BEAN_ID, bean);
map.put(JOB_LOCK_SERVICE, this.jobLockService);
map.put("name", trigger.getKey().toString());
jobDetail.setJobDataMap(map);
scheduler.scheduleJob(jobDetail, trigger);
return new QuartzTaskRegistration(scheduler, config);
} catch (ParseException | org.quartz.SchedulerException e) {
throw new TaskSchedulerException(e);
}
} |
6212860_2 | public Object[] getValues() {
final List<Object> arr = new ArrayList<Object>();
this.traverse_(this.root_, new Func() {
@Override
public void call(QuadTree quadTree, Node node) {
arr.add(node.getPoint().getValue());
}
});
return arr.toArray(new Object[arr.size()]);
} |
6215833_5 | public void insert(KeyClass key, ValueClass value) {
if (root == null) {
root = BTreeNode.createLeaf(null, null);
}
if (root.ckeckExists(key)) {
throw new DuplicateKeyException();
}
BTreeNode.InsertResult insertResult = root.insert(key, value, this);
if (insertResult != null) {
BTreeNode newRoot =
BTreeNode
.createDirectory(
new Comparable[]{insertResult.median},
new BTreeNode[] {insertResult.getLeft(), insertResult.getRight()}
);
root = newRoot;
}
} |
6257768_8 | static Vector splitSpace(String triple){
final Vector results = new Vector();
String remaining = triple;
int nextPos;
do{
nextPos = remaining.indexOf(' ');
if(nextPos >= 0){
results.addElement(remaining.substring(0, nextPos));
remaining = remaining.substring(nextPos + 1);
}
}while(nextPos >= 0);
results.addElement(remaining);
return results;
} |
6269725_1 | public static final boolean isNullOrEmpty(final StringValue stringValue)
{
return (stringValue == null) || stringValue.isNull() || stringValue.isEmpty();
} |
6275822_36 | public static ImmutableList<String> glob(final String glob) {
Path path = getGlobPath(glob);
int globIndex = getGlobIndex(path);
if (globIndex < 0) {
return of(glob);
}
return doGlob(path, searchPath(path, globIndex));
} |
6278839_0 | public Connection getConnection() {
return this.connection;
} |
6280863_22 | public static String parseFromPath(final String path) {
try {
return fromPathToStringCache.get(path, new Callable<String>() {
@Override
public String call() throws Exception {
return _parseFromPath(path);
}
});
}
catch (ExecutionException e) {
throw new RuntimeException(e);
}
catch (UncheckedExecutionException e) {
if (e.getCause() instanceof JirmIllegalStateException
|| e.getCause() instanceof JirmIllegalArgumentException) {
throw (RuntimeException) e.getCause();
}
throw e;
}
} |
6281707_79 | @Override
public void cacheToken(Token requestToken) {
if (requestToken == null || requestToken.getToken() == null) {
return;
}
tokenCache.put(requestToken.getToken(), requestToken);
} |
6290993_103 | public static <K, U, V, T> PCollection<T> oneToManyJoin(PTable<K, U> left, PTable<K, V> right,
DoFn<Pair<U, Iterable<V>>, T> postProcessFn, PType<T> ptype) {
return oneToManyJoin(left, right, postProcessFn, ptype, -1);
} |
6293402_212 | public static <C extends Comparable<? super C>> RangeValidator<C> of(
String errorMessage, C minValue, C maxValue) {
return new RangeValidator<>(errorMessage,
Comparator.nullsFirst(Comparator.naturalOrder()), minValue,
maxValue);
} |
6331476_36 | public Aspect.Builder getAspect() {
final Aspect.Builder aspect = Aspect.all();
final All all = ClassReflection.getAnnotation(c, All.class);
if (all != null) {
aspect.all(all.value());
}
final One one = ClassReflection.getAnnotation(c, One.class);
if (one != null) {
aspect.one(one.value());
}
final Exclude exclude = ClassReflection.getAnnotation(c, Exclude.class);
if (exclude != null) {
aspect.exclude(exclude.value());
}
return (all != null || exclude != null || one != null) ? aspect : null;
} |
6332635_3 | public String getContentType() {
return getFirstValue(CONTENT_TYPE);
} |
6357227_0 | public float evaluate(
final int numberOfUnits, final Text key, final float value) {
LinkedList<Float> list = map.get(key);
if (list == null) {
list = new LinkedList<Float>();
map.put(key, list);
}
list.add(value);
if (list.size() > numberOfUnits) {
list.removeFirst();
}
if (numberOfUnits == 0) {
return 0.0f;
} else {
int size = list.size();
int n = size < numberOfUnits ? size : numberOfUnits;
return sum(list) / (1.0f * n);
}
} |
6358188_343 | @Override
public VectorAggregator factorizeVector(VectorColumnSelectorFactory selectorFactory)
{
ColumnCapabilities capabilities = selectorFactory.getColumnCapabilities(fieldName);
if (capabilities == null || capabilities.getType().isNumeric()) {
return new FloatAnyVectorAggregator(selectorFactory.makeValueSelector(fieldName));
} else {
return NumericNilVectorAggregator.floatNilVectorAggregator();
}
} |
6370211_54 | public List<StageTransition> getStageTransitions(Interview interview, Stage stage) {
StageTransition template = new StageTransition();
template.setInterview(interview);
template.setStage(stage.getName());
List<StageTransition> stageTransitions = getPersistenceManager().match(template, new SortingClause("action.dateTime"));
return stageTransitions;
} |
6405716_25 | @Override
public Character convert(String value)
{
if (value != null && value.length() > 0)
{
return value.charAt(0);
}
return null;
} |
6426016_1 | public String getXMLAsString(Store store) throws UnsupportedEncodingException, JAXBException {
String xml = null;
ByteArrayOutputStream xmlOutput = null;
xmlOutput = getXMLAsByteArrayOutputStream(store);
if (xmlOutput != null) {
xml = xmlOutput.toString("UTF-8");
}
return xml;
} |
6434628_5 | public static Set<String> permutateSQL(String delimiter, String... frag) {
return new PermutationGenerator(frag).setDelimiter(delimiter).permutateSQL();
} |
6437134_0 | public Route parse() throws IOException {
Route route = new Route();
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(reader));
// Normalize text representation
doc.getDocumentElement().normalize();
Element summariesElement = getSummariesElement(doc);
String name = getChildElementText(summariesElement, "Name");
String departureTime = getChildElementText(summariesElement, "DepartureTime");
SortedMap<Integer, Element> controlPointsElements = getControlPointsElements(doc, name);
route.setName(name);
for (Entry<Integer, Element> entry : controlPointsElements.entrySet()) {
Element controlPointsElement = entry.getValue();
String controlPointsName = getChildElementText(controlPointsElement, "Name");
String sequenceNumber = getChildElementText(controlPointsElement, "SequenceNumber");
String latitude = getChildElementText(controlPointsElement, "Latitude");
String longitude = getChildElementText(controlPointsElement, "Longitude");
String turnRadius = getChildElementText(controlPointsElement, "TurnRadius");
String departingControlLineType = getChildElementText(controlPointsElement, "DepartingControlLineType");
String turnSpeed = getChildElementText(controlPointsElement, "DepartingTrackSpeed");
Waypoint wp = new Waypoint();
RouteLeg leg = new RouteLeg();
wp.setRouteLeg(leg);
route.getWaypoints().add(wp);
Double turningRadius = Double.parseDouble(turnRadius);
turningRadius = turningRadius/(1.852 * 1000);
wp.setName(waypointName(controlPointsName, Integer.parseInt(sequenceNumber)));
wp.setTurnRad(turningRadius);
wp.setLatitude(Math.toDegrees(Double.parseDouble(latitude)));
wp.setLongitude(Math.toDegrees(Double.parseDouble(longitude)));
leg.setHeading("RhumbLine".equals(departingControlLineType.trim()) ? Heading.RL : Heading.GC);
leg.setSpeed(Double.parseDouble(turnSpeed) * 1.943844492);
// default values
leg.setXtdPort(defaults.getDefaultXtd());
leg.setXtdStarboard(defaults.getDefaultXtd());
// leg.setSFWidth(sFWidth);
// leg.setSFLen(sFLen);
}
if (route.getWaypoints().size() > 0) {
route.getWaypoints().get(0).setEta(DATE_FORMAT.parse(departureTime));
}
} catch (IOException e) {
throw new IOException("Error reading ROUTE file", e);
} catch (Exception e) {
throw new IOException("Error parsing ROUTE file", e);
} finally {
if (closeReader) {
reader.close();
}
}
return route;
} |
6444116_54 | @Override
public boolean onCommand(final CommonSender sender, CommandParser parser) {
final boolean isSilent = parser.isSilent();
if (isSilent && !sender.hasPermission(getPermission() + ".silent")) {
sender.sendMessage(Message.getString("sender.error.noPermission"));
return true;
}
if (parser.args.length < 2) {
return false;
}
if (parser.isInvalidReason()) {
Message.get("sender.error.invalidReason")
.set("reason", parser.getReason().getMessage())
.sendTo(sender);
return true;
}
final String name = parser.args[0];
final Reason reason = parser.getReason();
getPlugin().getScheduler().runAsync(() -> {
final boolean isBanned = getPlugin().getNameBanStorage().isBanned(name);
if (isBanned && !sender.hasPermission("bm.command.banname.override")) {
Message message = Message.get("banname.error.exists");
message.set("name", name);
sender.sendMessage(message.toString());
return;
}
final PlayerData actor = sender.getData();
if (actor == null) return;
if (isBanned) {
NameBanData ban = getPlugin().getNameBanStorage().getBan(name);
if (ban != null) {
try {
getPlugin().getNameBanStorage().unban(ban, actor);
} catch (SQLException e) {
sender.sendMessage(Message.get("sender.error.exception").toString());
e.printStackTrace();
return;
}
}
}
final NameBanData ban = new NameBanData(name, actor, reason.getMessage(), isSilent);
boolean created;
try {
created = getPlugin().getNameBanStorage().ban(ban);
} catch (SQLException e) {
handlePunishmentCreateException(e, sender, Message.get("banname.error.exists").set("name",
name));
return;
}
if (!created) {
return;
}
// Find online players
getPlugin().getScheduler().runSync(() -> {
Message kickMessage = Message.get("banname.name.kick")
.set("reason", ban.getReason())
.set("actor", actor.getName())
.set("name", name);
for (CommonPlayer onlinePlayer : getPlugin().getServer().getOnlinePlayers()) {
if (onlinePlayer.getName().equalsIgnoreCase(name)) {
onlinePlayer.kick(kickMessage.toString());
}
}
});
});
return true;
} |
6448810_170 | public QueryHolder bindToUri(String name, String uri) {
String regex = "\\?" + name + "\\b";
String replacement = "<" + uri + ">";
String bound = replaceWithinBraces(regex, replacement);
return new QueryHolder(bound);
} |
6454766_0 | public boolean isLeader() {
boolean leader = false;
for (Member member : hazelcast.getCluster().getMembers()) {
String zone = member.getStringAttribute("zone");
if (zone == null) {
continue;
}
if (info.getZoneName().equals(zone)) {
if (member.localMember()) {
leader = true;
}
break;
}
}
return leader;
} |
6457784_0 | public static <A> boolean analyse(A analysedObject, Matcher assertion) {
return assertion.matches(analysedObject);
} |
6476959_9 | static String run(File file, String fileTitle, boolean renderHtml) throws IOException, LinkTargetException, EngineException
{
// Set-up a simple wiki configuration
WikiConfig config = DefaultConfigEnWp.generate();
final int wrapCol = 80;
// Instantiate a compiler for wiki pages
WtEngineImpl engine = new WtEngineImpl(config);
// Retrieve a page
PageTitle pageTitle = PageTitle.make(config, fileTitle);
PageId pageId = new PageId(pageTitle, -1);
String wikitext = FileUtils.readFileToString(file, Charset.defaultCharset().name());
// Compile the retrieved page
EngProcessedPage cp = engine.postprocess(pageId, wikitext, null);
// Convert the AST to a WOM document
Wom3Document womDoc = AstToWomConverter.convert(
config.getParserConfig(),
null /*pageNamespace*/,
null /*pagePath*/,
pageId.getTitle().getTitle(),
"Mr. Tester",
DateTime.parse("2012-12-07T12:15:30.000+01:00"),
cp.getPage());
if (renderHtml)
{
throw new UnsupportedOperationException(
"HTML rendering is not yet supported!");
/*
String ourHtml = HtmlRenderer.print(new MyRendererCallback(), config, pageTitle, cp.getPage());
String template = IOUtils.toString(App.class.getResourceAsStream("/render-template.html"), "UTF8");
String html = template;
html = html.replace("{$TITLE}", StringUtils.escHtml(pageTitle.getDenormalizedFullTitle()));
html = html.replace("{$CONTENT}", ourHtml);
return html;
*/
}
else
{
TextConverter p = new TextConverter(config, wrapCol);
return (String) p.go(womDoc);
}
} |
6489406_31 | static boolean isTrackStale(long lastAnyUpdate, long lastPositionUpdate, long currentUpdate) {
long lastUpdate = Math.max(lastAnyUpdate, lastPositionUpdate);
boolean trackStale = lastUpdate > 0L && currentUpdate - lastUpdate >= TRACK_STALE_MILLIS;
if (trackStale) {
LOG.debug("Track is stale (" + currentUpdate + ", " + lastUpdate + ")");
}
return trackStale;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.