id
stringlengths 7
14
| text
stringlengths 1
37.2k
|
---|---|
7695110_20 | public static InetSocketAddress forUaddrString(String uaddr) {
int secondPort = uaddr.lastIndexOf('.');
if( secondPort == -1 ) {
throw new IllegalArgumentException("address " + uaddr + " doesn't match rfc5665");
}
int firstPort = uaddr.lastIndexOf('.', secondPort -1);
if( firstPort == -1 ) {
throw new IllegalArgumentException("address " + uaddr + " doesn't match rfc5665");
}
InetAddress inetAddr = forString(uaddr.substring(0, firstPort));
int p1 = Integer.parseInt(uaddr.substring(firstPort +1, secondPort));
int p2 = Integer.parseInt(uaddr.substring(secondPort +1));
int port = (p1 << 8) + p2;
return new InetSocketAddress(inetAddr, port);
} |
7707976_1 | @Override
public void add(ChronologicalRecord item) {
add(Collections.singleton(item).iterator(), 0);
} |
7710120_32 | public static <T> ConditionRoot<T> criteriaFor(Class<T> clazz) {
return new ConditionalCriteriaBuilder<T>().new RootBuilderImpl();
} |
7723306_12 | @Override
public <H, V> Table<H, V> getTable(String tableName, Serde<H> hashKeySerde, Serde<V> valueSerde) {
return getTable(tableName, hashKeySerde, ByteSerde.get, valueSerde);
} |
7731254_63 | public static Node[] parse(String id) {
if (id.length() == 0) {
return EMPTY_NODES_ARRAY;
}
List<Node> result = Lists.newArrayList();
Iterable<String> split = SeparatorChar.SPLITTER.split(id);
for (String s : split) {
if (s.charAt(0) == META_COMPONENT_SEPARATOR_CHAR) {
int startImageIdx = s.indexOf(FUNCTION_IMAGE_START_TOKEN);
if (startImageIdx < 0) {
result.add(new Node(s));
} else {
if (s.charAt(s.length() - 1) != FUNCTION_IMAGE_END_TOKEN) {
throw new IllegalArgumentException(id);
}
if (startImageIdx + 1 > s.length() - 1) {
throw new IllegalArgumentException(id);
}
String image = s.substring(startImageIdx + 1, s.length() - 1);
String functionName = s.substring(1, startImageIdx);
result.add(new Node(image, functionName));
}
} else {
result.add(new Node(s));
}
}
return result.toArray(new Node[result.size()]);
} |
7742400_8 | ; |
7748336_49 | public static <T> List<T> safe(final List<T> list) {
if (list == null) {
return Collections.emptyList();
}
return list;
} |
7762720_25 | public int getExonCount() {
return this.exonCount;
} |
7766448_1 | public static String sign(String appKey, String secret, Map<String, String> paramMap)
{
// 对参数名进行字典排序
String[] keyArray = paramMap.keySet().toArray(new String[0]);
Arrays.sort(keyArray);
// 拼接有序的参数名-值串
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(appKey);
for (String key : keyArray)
{
stringBuilder.append(key).append(paramMap.get(key));
}
stringBuilder.append(secret);
String codes = stringBuilder.toString();
// SHA-1编码, 这里使用的是Apache
// codec,即可获得签名(shaHex()会首先将中文转换为UTF8编码然后进行sha1计算,使用其他的工具包请注意UTF8编码转换)
/*
* 以下sha1签名代码效果等同 byte[] sha =
* org.apache.commons.codec.digest.DigestUtils
* .sha(org.apache.commons.codec
* .binary.StringUtils.getBytesUtf8(codes)); String sign =
* org.apache.commons
* .codec.binary.Hex.encodeHexString(sha).toUpperCase();
*/
String sign = org.apache.commons.codec.digest.DigestUtils.shaHex(codes).toUpperCase();
return sign;
} |
7767145_4 | public void createOrUpdate(Quote quote) throws Exception {
log.info( "Updating 1234-" + quote.getQuoteNumber() + " version " + quote.getQuoteVers() + " for potential: " + quote.getPotentialId());
String modifiedQuoteNumber = "1234-" + quote.getQuoteNumber(); // So we can fake a search for all
quote.setQuoteNumber(modifiedQuoteNumber);
em.persist( quote );
} |
7767313_22 | public synchronized void loadData(String dbLocation) throws DSPException {
try {
if ((dbLocation != null) && (dbLocation != "")) {
this.dbLocation = dbLocation;
} else { // otherwise use a default location and filename relative to this class
this.dbLocation = getClass().getResource("dspConf.json").getFile();
}
//mapper.enableDefaultTyping();
// read the properties as an object using ObjectMapper
DSPProps props = mapper.readValue(new File(this.dbLocation), DSPProps.class);
this.properties.put("server_port", props.dspServerPort);
this.properties.put("request_timeout", props.defaultReqTimeout);
this.properties.put("offer_timeout", props.defaultOfferTimeout);
for (RTBExchange ex : props.exchanges) {
this.exchanges.put(ex.getOrgName(), ex);
}
for (RTBAdvertiser adv : props.advertisers) {
this.advertisers.put(adv.getLandingPage(), adv);
}
} catch (Exception e) {
logger.error("JsonFileBackedDAO-Error in loading Configuration data : " + StringUtils.stackTraceToString(e));
throw new DSPException(e.getMessage());
}
} |
7783162_11 | public MonetaryAmount addAll(MonetaryAmount... amounts) {
throw new UnsupportedOperationException();
} |
7807584_1 | @Override
public Exception decode(String methodKey, Response response) {
try {
// in case of error parsing, we can access the original contents.
response = bufferResponse(response);
UltraDNSError error = UltraDNSError.class.cast(decoder.decode(response, UltraDNSError.class));
if (error == null) {
return FeignException.errorStatus(methodKey, response);
}
String message = format("%s failed", methodKey);
if (error.code != -1) {
message = format("%s with error %s", message, error.code);
}
if (error.description != null) {
message = format("%s: %s", message, error.description);
}
if (error.code == UltraDNSException.SYSTEM_ERROR) {
return new RetryableException(message, null);
}
return new UltraDNSException(message, error.code);
} catch (IOException ignored) {
return FeignException.errorStatus(methodKey, response);
} catch (Exception propagate) {
return propagate;
}
} |
7819929_4 | public Price getVolumeGigabyteRate(String regionName) throws IOException {
getEc2OnDemandPrices();
Map<String, Object> region = getRegion(regionName, ebsPrices);
Map<String, Object> ebsVols = getJsonElementFromList(region, "types", "name", "ebsVols");
Map<String, Object> prices = getJsonElementFromList(ebsVols, "values", "rate", "perGBmoProvStorage");
if (prices != null){
String price = (String) getSubElement(prices, "prices").get("USD");
return Price.createUsdMonthly(new BigDecimal(price));
}
return null;
} |
7823906_2 | public static String getResourceLabel(String key) {
try {
ResourceBundle res = ResourceBundle.getBundle("labels",
new EncodedControl("UTF-8"));
return res.getString(key);
} catch (MissingResourceException me) {
logger.warn("Unable to find ResourceBUndle", me);
return key;
}
} |
7826526_51 | public final Boolean exec(final Tuple input) throws ExecException {
if (input == null || input.get(0) == null) {
return false;
}
if (mode.equals("default")) {
String xCS = (String) input.get(1);
if (containsXcsValue(xCS)) {
String carrierName = xCSCarrierMap.get(this.xCS);
ZeroConfig zeroConfig = carrierName != null ? getZeroConfig(carrierName) : getZeroConfig("default");
return isValidZeroRequest((String) input.get(0), zeroConfig);
} else {
return false;
}
} else {
String simpleFilename = simplifyFilename((String) input.get(1));
ZeroConfig zeroConfig = getZeroConfig(simpleFilename);
return isValidZeroRequest((String) input.get(0), zeroConfig);
}
} |
7832943_3 | @VisibleForTesting
String getActualPath() throws ExecutionException, InterruptedException {
return _async.getActualPath();
} |
7837044_3 | protected MulticastSocket createSocket() throws UnknownHostException, IOException {
InetAddress address = InetAddress.getByName(multicastAddress);
MulticastSocket socket = new MulticastSocket(port);
socket.joinGroup(address);
return socket;
} |
7842918_5 | public static void setEntityRefsFromEntities(Collection<String> refs, Collection<Entity> entities)
{
refs.clear();
for (Iterator<Entity> i = entities.iterator(); i.hasNext();)
{
Entity entity = i.next();
refs.add(entity.getReference());
}
} |
7891529_103 | @UiHandler("cancelButton")
public void handleCancelClick(final ClickEvent event) {
this.actionDelegate.cancelled();
} |
7891564_7 | public static Pair<String, String> modifyBodyWithReferences(Message message, String body) {
if (body == null || body.isEmpty() || body.trim().isEmpty()) return new Pair<>(body, null);
List<ExtensionElement> elements = message.getExtensions(ReferenceElement.ELEMENT, ReferenceElement.NAMESPACE);
if (elements == null || elements.size() == 0) return new Pair<>(body, null);
List<ReferenceElement> references = getReferences(elements);
if (references.isEmpty()) return new Pair<>(body, null);
// encode HTML and split into chars
String[] chars = stringToChars(Utils.xmlEncode(body));
// modify chars with references except markup and mention
for (ReferenceElement reference : references) {
if (!(reference instanceof Markup) && !(reference instanceof Mention) && !(reference instanceof Quote))
chars = modifyBodyWithReferences(chars, reference);
}
// chars to string and decode from html
String regularBody = Html.fromHtml(charsToString(chars).replace("\n", "<br/>")).toString();
String markupBody = null;
// modify chars with markup and mention references
for (ReferenceElement reference : references) {
if (reference instanceof Markup || reference instanceof Mention || reference instanceof Quote)
chars = modifyBodyWithReferences(chars, reference);
}
markupBody = charsToString(chars);
if (regularBody.equals(markupBody)) markupBody = null;
return new Pair<>(regularBody, markupBody);
} |
7905539_3 | synchronized void close() {
mCondition = false;
} |
7908045_0 | @Override
public String toTarget(Translator translator, Symbol symbol) {
Release release;
try {
release = new Release(symbol.getProperty(OptionType.RELEASE.name()));
} catch (Exception e) {
return "<strong>Malformed release: " + e.getMessage() + "</strong>";
}
String href = symbol.getProperty(OptionType.HREF.name());
TagGroup html = new TagGroup();
addTitle(html, release, href);
if (release.exists()) {
addFilesHtml(html, release);
release.saveInfo();
} else
html.add("The release directory could not be found.");
return html.html();
} |
7923123_11 | public FluentInitializer init(Date minDate, Date maxDate, TimeZone timeZone, Locale locale) {
if (minDate == null || maxDate == null) {
throw new IllegalArgumentException(
"minDate and maxDate must be non-null. " + dbg(minDate, maxDate));
}
if (minDate.after(maxDate)) {
throw new IllegalArgumentException(
"minDate must be before maxDate. " + dbg(minDate, maxDate));
}
if (locale == null) {
throw new IllegalArgumentException("Locale is null.");
}
if (timeZone == null) {
throw new IllegalArgumentException("Time zone is null.");
}
// Make sure that all calendar instances use the same time zone and locale.
this.timeZone = timeZone;
this.locale = locale;
today = Calendar.getInstance(timeZone, locale);
minCal = Calendar.getInstance(timeZone, locale);
maxCal = Calendar.getInstance(timeZone, locale);
monthCounter = Calendar.getInstance(timeZone, locale);
for (MonthDescriptor month : months) {
month.setLabel(formatMonthDate(month.getDate()));
}
weekdayNameFormat =
new SimpleDateFormat(getContext().getString(R.string.day_name_format), locale);
weekdayNameFormat.setTimeZone(timeZone);
fullDateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
fullDateFormat.setTimeZone(timeZone);
monthFormatter = new Formatter(monthBuilder, locale);
this.selectionMode = SelectionMode.SINGLE;
// Clear out any previously-selected dates/cells.
selectedCals.clear();
selectedCells.clear();
highlightedCals.clear();
highlightedCells.clear();
// Clear previous state.
cells.clear();
months.clear();
minCal.setTime(minDate);
maxCal.setTime(maxDate);
setMidnight(minCal);
setMidnight(maxCal);
displayOnly = false;
// maxDate is exclusive: bump back to the previous day so if maxDate is the first of a month,
// we don't accidentally include that month in the view.
maxCal.add(MINUTE, -1);
// Now iterate between minCal and maxCal and build up our list of months to show.
monthCounter.setTime(minCal.getTime());
final int maxMonth = maxCal.get(MONTH);
final int maxYear = maxCal.get(YEAR);
while ((monthCounter.get(MONTH) <= maxMonth // Up to, including the month.
|| monthCounter.get(YEAR) < maxYear) // Up to the year.
&& monthCounter.get(YEAR) < maxYear + 1) { // But not > next yr.
Date date = monthCounter.getTime();
MonthDescriptor month =
new MonthDescriptor(monthCounter.get(MONTH), monthCounter.get(YEAR),
date, formatMonthDate(date));
cells.put(monthKey(month), getMonthCells(month, monthCounter));
Logr.d("Adding month %s", month);
months.add(month);
monthCounter.add(MONTH, 1);
}
validateAndUpdate();
return new FluentInitializer();
} |
7968180_69 | public CytoPanelState getNewState() {
return newState;
} |
7968744_1 | public void start(BundleContext bc) {
CySwingApplication cytoscapeDesktopService = getService(bc,CySwingApplication.class);
MyControlPanel myControlPanel = new MyControlPanel();
ControlPanelAction controlPanelAction = new ControlPanelAction(cytoscapeDesktopService,myControlPanel);
registerService(bc,myControlPanel,CytoPanelComponent.class, new Properties());
registerService(bc,controlPanelAction,CyAction.class, new Properties());
} |
7983535_9 | public final static Type getCollectionType(Type type) {
if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
} else if (type instanceof Class<?>) {
Class<?> clazz = (Class<?>) type;
if (clazz.isArray())
return clazz.getComponentType();
else if (Collection.class.isAssignableFrom(clazz)) {
return Object.class;
}
} else if (type instanceof ParameterizedType && Collection.class.isAssignableFrom(getRawClass(type))) {
return typeOf(0, type);
}
throw new IllegalArgumentException(
"Could not extract parametrized type, are you sure it is a Collection or an Array?");
} |
7997879_106 | public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException {
/* See http://prometheus.io/docs/instrumenting/exposition_formats/
* for the output format specification. */
while(mfs.hasMoreElements()) {
Collector.MetricFamilySamples metricFamilySamples = mfs.nextElement();
writer.write("# HELP ");
writer.write(metricFamilySamples.name);
writer.write(' ');
writeEscapedHelp(writer, metricFamilySamples.help);
writer.write('\n');
writer.write("# TYPE ");
writer.write(metricFamilySamples.name);
writer.write(' ');
writer.write(typeString(metricFamilySamples.type));
writer.write('\n');
for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) {
writer.write(sample.name);
if (sample.labelNames.size() > 0) {
writer.write('{');
for (int i = 0; i < sample.labelNames.size(); ++i) {
writer.write(sample.labelNames.get(i));
writer.write("=\"");
writeEscapedLabelValue(writer, sample.labelValues.get(i));
writer.write("\",");
}
writer.write('}');
}
writer.write(' ');
writer.write(Collector.doubleToGoString(sample.value));
if (sample.timestampMs != null){
writer.write(' ');
writer.write(sample.timestampMs.toString());
}
writer.write('\n');
}
}
} |
8000878_7 | public RaygunMessage onBeforeSend(RaygunClient client, RaygunMessage message) {
if(message.getDetails() != null
&& message.getDetails().getError() != null
&& message.getDetails().getError().getInnerError() != null
&& message.getDetails().getError().getThrowable() != null) {
for (Class<?> stripClass : stripClasses) {
if (stripClass.isAssignableFrom(message.getDetails().getError().getThrowable().getClass())) {
RaygunErrorMessage innerError = message.getDetails().getError().getInnerError();
message.getDetails().setError(innerError);
// rerun check on the reassigned error
onBeforeSend(client, message);
return message;
}
}
}
return message;
} |
8010626_2018 | @Transactional
@Override
public EntityImportReport doImport(
RepositoryCollection source,
MetadataAction metadataAction,
DataAction dataAction,
@Nullable @CheckForNull String packageId) {
if (dataAction != DataAction.ADD) {
throw new IllegalArgumentException("Only ADD is supported");
}
Package importPackage = null;
if (packageId != null) {
importPackage =
metaDataService
.getPackage(packageId)
.orElseThrow(() -> new UnknownEntityException(PACKAGE, packageId));
}
List<EntityType> addedEntities = new ArrayList<>();
EntityImportReport report;
Iterator<String> it = source.getEntityTypeIds().iterator();
if (it.hasNext()) {
try (Repository<Entity> repo = source.getRepository(it.next())) {
report = importVcf(repo, addedEntities, importPackage);
} catch (IOException e) {
throw new MolgenisDataException(e);
}
} else {
report = new EntityImportReport();
}
return report;
} |
8015168_6 | public Vector vectorise(Document document) {
Vector body = luceneEncode(bodyCard, document.getBody());
Vector title = luceneEncode(titleCard, document.getTitle());
//Vector tags = luceneEncode(tagCard, Strings.collectionToCommaDelimitedString(document.getTags()));
//Vector reputation = Vectors.newSequentialAccessSparseVector(document.getReputation());
return Vectors.append(body, title);//, tags);//, reputation);
} |
8022939_8 | @Override
public String getString(String key) {
return getPropertyResolver().getString(checkNotNull(key));
} |
8025185_0 | public AppleLanguage getLanguage() {
return language;
} |
8031741_0 | public static Position findPosition(Position startingLocation,
Position endLocation, double distanceTravelled) {
double distance = distanceTravelled / 6371000;
LatLonPoint result = GreatCircle.pointAtDistanceBetweenPoints(
Math.toRadians(startingLocation.getLatitude()),
Math.toRadians(startingLocation.getLongitude()),
Math.toRadians(endLocation.getLatitude()),
Math.toRadians(endLocation.getLongitude()), distance / 2, 512);
return Position.create(result.getLatitude(), result.getLongitude());
} |
8033805_0 | public int returnInputValue(int input) {
return input;
} |
8037199_2 | public static String renderWhereStringTemplate(String sqlWhereString, Dialect dialect, SQLFunctionRegistry functionRegistry) {
return renderWhereStringTemplate(sqlWhereString, TEMPLATE, dialect, functionRegistry);
} |
8049046_20 | @Override
public void execute(final AddToList command) {
final List<Object> list = getListOrFail(command);
final Object value = valueMapper.map(command.getValue());
silentChangeExecutor.execute(list, new Runnable() {
@Override
public void run() {
list.add(command.getPosition(), value);
}
});
updateVersion(command);
} |
8054843_6 | public static HackedObject into(final Object source) {
return new HackedMirrorObject(source);
} |
8087042_25 | protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
} |
8131104_25 | @Override
public void update(T newPage) {
decoder.update(newPage);
} |
8134070_1 | public User getUser(String userId) {
return dao.get(new Integer(userId));
} |
8135809_1 | @Override
public void execute(SensorContext context) {
FileSystem fileSystem = context.fileSystem();
FilePredicates predicates = fileSystem.predicates();
List<SquidAstVisitor<LexerlessGrammar>> visitors = new ArrayList<>(checks.all());
visitors.add(new FileLinesVisitor(fileLinesContextFactory, fileSystem));
LuaConfiguration configuration = new LuaConfiguration(fileSystem.encoding());
scanner = LuaAstScanner.create(configuration, visitors);
Iterable<java.io.File> files = fileSystem.files(
predicates.and(
predicates.hasType(InputFile.Type.MAIN),
predicates.hasLanguage(Lua.KEY),
inputFile -> !inputFile.absolutePath().endsWith("mxml")
));
scanner.scanFiles(ImmutableList.copyOf(files));
Collection<SourceCode> squidSourceFiles = scanner.getIndex().search(new QueryByType(SourceFile.class));
save(context, squidSourceFiles);
} |
8139882_0 | @PostConstruct
public void init() {
appFormerJsBridge.init("org.kie.bc.KIEWebapp");
homeConfiguration.setMonitoring(true);
workbench.addStartupBlocker(KieWorkbenchEntryPoint.class);
// Due to a limitation in the Menus API the number of levels in the workbench's menu bar
// navigation tree node must be limited to 2 (see https://issues.jboss.org/browse/GUVNOR-2992)
navigationExplorerScreen.getNavTreeEditor().setMaxLevels(NavTreeDefinitions.GROUP_WORKBENCH,
2);
} |
8143599_92 | static public void setDebug(Debug dbg) {
debug = dbg;
} |
8147920_29 | public static long estimatedSizeOf(Statement statement) {
Value object = statement.getObject();
Resource context = statement.getContext();
long result = STATEMENT_OVERHEAD
+ 2 * URI_BNODE_OVERHEAD // subject, predicate
+ OBJ_REF // reference to the statement
+ StringSizeEstimator.estimatedSizeOf(statement.getSubject().stringValue())
+ StringSizeEstimator.estimatedSizeOf(statement.getPredicate().stringValue());
// object
if (object instanceof Literal) {
Literal literal = (Literal) object;
result += LITERAL_OVERHEAD + StringSizeEstimator.estimatedSizeOf(literal.stringValue());
if (literal.getLanguage() != null) {
result += StringSizeEstimator.estimatedSizeOf(literal.getLanguage());
}
if (literal.getDatatype() != null) {
result += URI_BNODE_OVERHEAD + StringSizeEstimator.estimatedSizeOf(literal.getDatatype().stringValue());
}
} else {
result += URI_BNODE_OVERHEAD + StringSizeEstimator.estimatedSizeOf(object.stringValue());
}
// context
if (context != null) {
result += URI_BNODE_OVERHEAD + StringSizeEstimator.estimatedSizeOf(context.stringValue());
}
return result;
} |
8155767_6 | public WeatherStatusResponse currentWeatherAtCity (float lat, float lon, int cnt) throws IOException, JSONException { //, boolean cluster, OwmClient.Lang lang) {
String subUrl = String.format (Locale.ROOT, "find/city?lat=%f&lon=%f&cnt=%d&cluster=yes",
Float.valueOf (lat), Float.valueOf (lon), Integer.valueOf (cnt));
JSONObject response = doQuery (subUrl);
return new WeatherStatusResponse (response);
} |
8166928_10 | @Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
long deliveryTag = envelope.getDeliveryTag();
Stopwatch stopwatch = Stopwatch.createStarted();
try {
T message = MAPPER.readValue(body, type);
if (log.isTraceEnabled()) {
log.trace("Received message '{}' with data '{}'.", deliveryTag, new String(body));
}
processor.apply(message);
getChannel().basicAck(deliveryTag, false);
stopwatch.stop();
successCount.mark();
successDuration.update(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
log.info("Processed {} message '{}' succesfully in {} ms.", type.getSimpleName(), deliveryTag, stopwatch.elapsed(TimeUnit.MILLISECONDS));
} catch (Exception e) {
getChannel().basicNack(deliveryTag, false, true);
stopwatch.stop();
failureCount.mark();
failureDuration.update(stopwatch.elapsed(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
log.error("Processing {} message '{}' failed with exception:", type.getSimpleName(), deliveryTag, e);
}
} |
8176370_4 | public void setHref(String href) {
this.href = href;
} |
8188105_4 | public OftpSettings getSettings() {
return settings;
} |
8197357_346 | public void add(long xVal, double yVal) {
if (getFirstTime() == Long.MIN_VALUE) {
firstTime = xVal;
}
if (xVal > maxX) {
maxX = xVal;
}
if (xVal < minX) {
minX = xVal;
}
} |
8201183_0 | public System(EngineManager engine) {
setName("System");
this.engine = engine;
} |
8201494_8 | @Override
public boolean equals(Object obj) {
if (obj instanceof WGS84Point) {
WGS84Point other = (WGS84Point) obj;
return latitude == other.latitude && longitude == other.longitude;
}
return false;
} |
8204840_6 | @Override
public void onChange()
{
refresh();
} |
8212556_25 | public static boolean isBlank(CharSequence sourceSequence) {
int sequenceLength;
if (sourceSequence == null || (sequenceLength = sourceSequence.length()) == 0) {
return true;
}
for (int i = 0; i < sequenceLength; i++) {
if ((Character.isWhitespace(sourceSequence.charAt(i)) == false)) {
return false;
}
}
return true;
} |
8236056_71 | public V remove (short key) {
if (key == 0) {
if (!hasZeroValue) return null;
V oldValue = zeroValue;
zeroValue = null;
hasZeroValue = false;
size--;
return oldValue;
}
int index = (int)(key & mask);
if (keyTable[index] == key) {
keyTable[index] = EMPTY;
V oldValue = valueTable[index];
valueTable[index] = null;
size--;
return oldValue;
}
index = hash2(key);
if (keyTable[index] == key) {
keyTable[index] = EMPTY;
V oldValue = valueTable[index];
valueTable[index] = null;
size--;
return oldValue;
}
index = hash3(key);
if (keyTable[index] == key) {
keyTable[index] = EMPTY;
V oldValue = valueTable[index];
valueTable[index] = null;
size--;
return oldValue;
}
return removeStash(key);
} |
8249432_1 | @Override
public List<Map<String, Object>> queryForMapList(String sql, Object... args)
throws DataAccessException {
return (List<Map<String, Object>>) query(sql, args, new MapListResultSetExtractor());
} |
8262372_172 | Map<HRegionInfo, ServerName[]> placeSecondaryAndTertiaryRS(
Map<HRegionInfo, ServerName> primaryRSMap) {
Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap =
new HashMap<HRegionInfo, ServerName[]>();
for (Map.Entry<HRegionInfo, ServerName> entry : primaryRSMap.entrySet()) {
// Get the target region and its primary region server rack
HRegionInfo regionInfo = entry.getKey();
ServerName primaryRS = entry.getValue();
try {
// Create the secondary and tertiary region server pair object.
ServerName[] favoredNodes;
// Get the rack for the primary region server
String primaryRack = rackManager.getRack(primaryRS);
if (getTotalNumberOfRacks() == 1) {
favoredNodes = singleRackCase(regionInfo, primaryRS, primaryRack);
} else {
favoredNodes = multiRackCase(regionInfo, primaryRS, primaryRack);
}
if (favoredNodes != null) {
secondaryAndTertiaryMap.put(regionInfo, favoredNodes);
LOG.debug("Place the secondary and tertiary region server for region "
+ regionInfo.getRegionNameAsString());
}
} catch (Exception e) {
LOG.warn("Cannot place the favored nodes for region " +
regionInfo.getRegionNameAsString() + " because " + e, e);
continue;
}
}
return secondaryAndTertiaryMap;
} |
8266524_10 | public static <T> void runEach(final Iterable<T> elements, final Action1<T> action) {
shouldNotBeNull(elements, "elements");
shouldNotBeNull(action, "function");
if (isDebugEnabled) log.debug("병렬로 작업을 수행합니다... workerCount=[{}]", getWorkerCount());
ExecutorService executor = Executors.newFixedThreadPool(getWorkerCount());
try {
List<T> elemList = Lists.newArrayList(elements);
int partitionSize = getPartitionSize(elemList.size(), getWorkerCount());
Iterable<List<T>> partitions = Iterables.partition(elemList, partitionSize);
List<Callable<Void>> tasks = Lists.newLinkedList();
for (final List<T> partition : partitions) {
Callable<Void> task =
new Callable<Void>() {
@Override
public Void call() throws Exception {
for (final T element : partition)
action.perform(element);
return null;
}
};
tasks.add(task);
}
List<Future<Void>> results = executor.invokeAll(tasks);
for (Future<Void> result : results) {
result.get();
}
if (isDebugEnabled)
log.debug("모든 작업을 병렬로 수행하였습니다. workerCount=[{}]", getWorkerCount());
} catch (Exception e) {
log.error("데이터에 대한 병렬 작업 중 예외가 발생했습니다.", e);
throw new RuntimeException(e);
} finally {
executor.shutdown();
}
} |
8276360_0 | protected String getEnqueueRecordsDestinationUri() {
return "activemq:queue:" + recordsQueueName;
} |
8279377_2 | static Double calculateDurationAgainstDvTemporal(String value, DvTemporal operationTemporal, String symbol) {
DateTime dateTime = getDateTime(operationTemporal, value);
return calculateDurationAgainstDateTime(value, dateTime, symbol);
} |
8289370_122 | public boolean updateAttachmentContent(String name, EntityRef parent, IndicatingInputStream is, long length, boolean silent) {
Map<String,String> headers = Collections.singletonMap("Content-Type", "application/octet-stream");
MyResultInfo result = new MyResultInfo();
if(restService.put(new MyInputData(is, length, headers), result, "{0}s/{1}/attachments/{2}", parent.type, parent.id, EntityQuery.encode(name)) != HttpStatus.SC_OK) {
if(!silent) {
errorService.showException(new RestException(result));
}
return false;
} else {
EntityList list = EntityList.create(result.getBodyAsStream(), true);
if(!list.isEmpty()) {
entityService.fireEntityLoaded(list.get(0), EntityListener.Event.GET);
}
return true;
}
} |
8296012_4 | @Override
public void run() {
String line;
try {
while ((line = bufferedReader.readLine()) != null) {
log.info(line);
}
} catch (IOException e) {
throw new TaskException("Exception while intercepting stream.", e);
}
IOUtils.closeQuietly(bufferedReader);
IOUtils.closeQuietly(inputStreamReader);
} |
8322886_1 | protected void logActivity(JSONObject payload) throws JSONException, IOException {
String eventName = payload.getString("event");
JSONObject properties = payload.getJSONObject("properties");
// Adjust the time from milliseconds to seconds...
Long time = properties.optLong("time", 0L);
if (time == 0L) {
time = System.currentTimeMillis();
}
time = time/1000;
properties.put("time", time);
MixpanelAPI mixpanel = getMixpanelAPI();
MessageBuilder messageBuilder = new MessageBuilder(token);
String distinct_id = properties.getString("distinct_id");
JSONObject mixPanelMessage = messageBuilder.event(distinct_id, eventName, properties);
sendMessageToMixpanel(mixpanel, mixPanelMessage);
} |
8328088_66 | public Attendant getAttendant() {
return attendant;
} |
8333478_3 | @RequestMapping(value = "/execute",method=RequestMethod.POST)
public ModelAndView executeTask(@RequestParam String spaceName,@RequestParam String locators,@RequestBody SpaceTaskRequest body)
{
return execute(spaceName,locators,body);
} |
8369425_1 | public static double calculateTickSpacing( double delta, int maxTicks ) {
if ( delta == 0.0 )
return 0.0;
if ( delta <= 0.0 )
throw new IllegalArgumentException( "delta must be positive" );
if ( maxTicks < 1 )
throw new IllegalArgumentException( "must be at least one tick" );
//The factor will be close to the log10, this just optimizes the search
int factor = (int) Math.log10( delta );
int divider = 0;
double numTicks = delta / ( dividers[divider] * Math.pow( 10, factor ) );
//We don't have enough ticks, so increase ticks until we're over the limit, then back off once.
if ( numTicks < maxTicks ) {
while ( numTicks < maxTicks ) {
//Move up
--divider;
if ( divider < 0 ) {
--factor;
divider = dividers.length - 1;
}
numTicks = delta / ( dividers[divider] * Math.pow( 10, factor ) );
}
//Now back off once unless we hit exactly
//noinspection FloatingPointEquality
if ( numTicks != maxTicks ) {
++divider;
if ( divider >= dividers.length ) {
++factor;
divider = 0;
}
}
} else {
//We have too many ticks or exactly max, so decrease until we're just under (or at) the limit.
while ( numTicks > maxTicks ) {
++divider;
if ( divider >= dividers.length ) {
++factor;
divider = 0;
}
numTicks = delta / ( dividers[divider] * Math.pow( 10, factor ) );
}
}
/ System.out.printf( "calculateTickSpacing( %f, %d ) = %f%n",
/ delta, maxTicks, dividers[divider] * Math.pow( 10, factor ) );
return dividers[divider] * Math.pow( 10, factor );
} |
8406849_42 | public JSONObject toJSON(ModelView o) throws JSONConverterException {
ModelViewConverter c = java2json.get(o.getClass());
if (c == null) {
throw new JSONConverterException("No converter available for a view with the '" + o.getClass() + "' className");
}
return c.toJSON(o);
} |
8411032_2 | public T check(final String aString) {
final char[] chars = aString.toCharArray();
for (int i = 0; i < chars.length; i++) {
final Node<T> root = this.roots.get(chars[i]);
if (root != null) {
final T res = root.check(chars, i);
if (res != null) {
return res;
}
}
}
return null;
} |
8417769_0 | static public List<Record> readTable(String urlString, String format, int maxLines) throws IOException, NumberFormatException {
InputStream ios;
if (urlString.startsWith("http:")) {
URL url = new URL(urlString);
ios = url.openStream();
} else {
ios = new FileInputStream(urlString);
}
return readTable(ios, format, maxLines);
} |
8426406_624 | public boolean matches(String matched) {
return matches(null, string(matched));
} |
8427412_17 | public void calculateReservations(StockOperation operation) {
if (operation == null) {
throw new IllegalArgumentException("The operation must be defined");
}
/*
We want to ensure that duplicated transactions are combined so they don't cause issues when they are processed.
To do this, we loop through each transaction and build a tuple containing the Item, Expiration Date, and Batch
Operation and look for it in a map. If it is not found, we add it and continue to the next transaction. If it
is found we update the existing transaction to add the quantity and set the calculated batch operation and
expiration. The rule for the calculated qualifiers is that if either of the transactions (existing or current)
was set to be calculated then the calculated field is set to true.
*/
List<ReservedTransaction> removeList = findDuplicateReservedTransactions(operation);
for (ReservedTransaction tx : removeList) {
operation.getReserved().remove(tx);
}
// Sort the transactions by item and then non-calculated versus calculated
List<ReservedTransaction> transactions = sortReservedTransactions(operation);
/*
Now we need to check each transaction against the source stockroom item stock (if there is a source stockroom)
and figure out exactly which specific item stock (called an item stock detail) to take. This can result in
new transactions being created if a transaction cannot be fulfilled by a single detail. The calculation
also needs to take into account others transactions for the same item. To manage this, a Map is created to
store copies of the item stock detail and then these copies are then updated so that a running tally can be kept
of what is actually available when processing a specific transaction without modifying the actual detail records.
*/
Map<Pair<Stockroom, Item>, ItemStock> stockMap = new HashMap<Pair<Stockroom, Item>, ItemStock>();
List<ReservedTransaction> newTransactions = new ArrayList<ReservedTransaction>();
boolean hasSource = operation.getSource() != null;
boolean isAdjustment = operation.isAdjustmentType();
for (ReservedTransaction tx : transactions) {
if (hasSource && (!isAdjustment || (isAdjustment && tx.getQuantity() < 0))) {
// Clone the item stock and find the detail record
ItemStock stock = findAndCloneStock(stockMap, operation.getSource(), tx.getItem());
findAndUpdateSourceDetail(newTransactions, operation, stock, tx);
} else {
// Set the batch operation to the current operation because this must be some type of receipt operation
if (tx.getBatchOperation() == null) {
tx.setBatchOperation(operation);
tx.setCalculatedBatch(false);
}
}
}
// Add any newly created transactions to the operation
for (ReservedTransaction newTx : newTransactions) {
operation.addReserved(newTx);
}
} |
8428305_19 | @Override
public final void onUpdate(List<? extends ActorStateUpdate> updates) {
updates.stream().filter(
update -> update.getActorClass().getAnnotation(IndexConfig.class) != null
).forEach(update ->
{
IndexConfig indexConfig = update.getActorClass().getAnnotation(IndexConfig.class);
Class messageClass = update.getMessageClass();
ActorLifecycleStep lifecycleStep = update.getLifecycleStep();
if (messageClass != null && contains(indexConfig.includedMessages(), messageClass)) {
indexActorState(indexConfig, update);
} else if (lifecycleStep != null) {
if (lifecycleStep == ActorLifecycleStep.DESTROY) {
deleteActorState(indexConfig, update);
} else if (Arrays.binarySearch(indexConfig.indexOn(), lifecycleStep) >= 0) {
indexActorState(indexConfig, update);
}
if (lifecycleStep == ActorLifecycleStep.ACTIVATE && indexConfig.versioningStrategy() == REINDEX_ON_ACTIVATE) {
if (!activatedActors.contains(update.getActorRef().getActorId())) {
deleteOldVersionsOfActor(indexConfig, update);
activatedActors.add(update.getActorRef().getActorId());
}
}
}
}
);
} |
8436798_1 | @Override
public String extractValue(IHttpRequest request) {
return StringUtils.defaultIfEmpty(request.getFormParameterValue(key), null);
} |
8467178_18 | public void setEndpoints(String notify, String sessions) throws IllegalArgumentException {
if (notify == null || notify.isEmpty()) {
throw new IllegalArgumentException("Notify endpoint cannot be empty or null.");
} else {
if (delivery instanceof HttpDelivery) {
((HttpDelivery) delivery).setEndpoint(notify);
} else {
LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set notify endpoint");
}
}
boolean invalidSessionsEndpoint = sessions == null || sessions.isEmpty();
String sessionEndpoint = null;
if (invalidSessionsEndpoint && this.autoCaptureSessions.get()) {
LOGGER.warn("The session tracking endpoint has not been"
+ " set. Session tracking is disabled");
this.autoCaptureSessions.set(false);
} else {
sessionEndpoint = sessions;
}
if (sessionDelivery instanceof HttpDelivery) {
// sessionEndpoint may be invalid (e.g. typo in the protocol) here, which
// should result in the default
// HttpDelivery throwing a MalformedUrlException which prevents delivery.
((HttpDelivery) sessionDelivery).setEndpoint(sessionEndpoint);
} else {
LOGGER.warn("Delivery is not instance of HttpDelivery, cannot set sessions endpoint");
}
} |
8483862_136 | public void appendReferenceField(final char[] tag, final String value) {
appendReferenceField(tag, defaultImplDefinedPart, value);
} |
8497273_2 | public static String relativePath(File parent, File child) {
Preconditions.checkArgument(contains(parent, child));
String parentName = conventPath(parent);
String childName = conventPath(child);
String relative = childName.substring(parentName.length());
if (relative.length() == 0) return "/";
return "/" + relative.substring(0, relative.length() - 1);
} |
8504385_1 | public static Gson getGson() {
Gson gson = new GsonBuilder().
registerTypeAdapter(ServerOption.class, new ServerOptionParentDeserializer()).
excludeFieldsWithoutExposeAnnotation().
create();
return gson;
} |
8530120_97 | public void copyAssetsFromContent(File path) {
copy(path, config.getDestinationFolder(), FileUtil.getNotContentFileFilter());
} |
8560742_3 | public RecordWriter<Data, NullWritable> getRecordWriter() {
consumerFuture = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat
("OutputFormatLoader-consumer").build()).submit(
new ConsumerThread());
return producer;
} |
8570603_1 | protected Promise<? extends D_OUT, ? extends F_OUT, ? extends P_OUT> pipe(
Promise<? extends D_OUT, ? extends F_OUT, ? extends P_OUT> promise) {
promise.done(new DoneCallback<D_OUT>() {
@Override
public void onDone(D_OUT result) {
PipedPromise.this.resolve(result);
}
}).fail(new FailCallback<F_OUT>() {
@Override
public void onFail(F_OUT result) {
PipedPromise.this.reject(result);
}
}).progress(new ProgressCallback<P_OUT>() {
@Override
public void onProgress(P_OUT progress) {
PipedPromise.this.notify(progress);
}
});
return promise;
} |
8571000_2 | @Override
public void close() throws IOException {
// TODO Auto-generated method stub
synonymFilter.close();
} |
8575137_0 | static String asHumanDescription(Collection<? extends MemberViewBinding> bindings) {
Iterator<? extends MemberViewBinding> iterator = bindings.iterator();
switch (bindings.size()) {
case 1:
return iterator.next().getDescription();
case 2:
return iterator.next().getDescription() + " and " + iterator.next().getDescription();
default:
StringBuilder builder = new StringBuilder();
for (int i = 0, count = bindings.size(); i < count; i++) {
if (i != 0) {
builder.append(", ");
}
if (i == count - 1) {
builder.append("and ");
}
builder.append(iterator.next().getDescription());
}
return builder.toString();
}
} |
8578424_1 | @Nullable
public Repository parseRepositoryUrl(@NotNull String uri) {
return parseRepositoryUrl(uri, null);
} |
8582237_64 | @Override
public long rangeSelectivity(ExecRow start, ExecRow stop, boolean includeStart, boolean includeStop, boolean useExtrapolation) {
double startSelectivity = start==null?0.0d:quantilesSketch.getCDF(new ExecRow[]{start})[0];
double stopSelectivity = stop==null?1.0d:quantilesSketch.getCDF(new ExecRow[]{stop})[0];
return (long) ((stopSelectivity-startSelectivity)*quantilesSketch.getN());
} |
8595333_34 | public int getMaxHttpConnection() {
return maxHttpConnection;
} |
8599516_1 | @Override public final void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
int viewType = getItemViewType(position);
if (viewType != IGNORE_ITEM_VIEW_TYPE) {
recycleBin.addScrapView(view, position, viewType);
}
} |
8621768_4 | public ClassLoader getClassLoader() {
// get jars if somehing changed
File[] jars = getJarsIfSomeIsModifiedAfterInterval();
if (jars == null)
return currentClassLoader;
// update classloader
synchronized (this) {
try {
// copy jars to a new spooldir
File newSpoolDir = copyJarsToTempDir(jars);
// create a new classloader
List<File> list = new LinkedList<File>();
for (File f : newSpoolDir.listFiles(onlyJars))
list.add(f);
// adding lib jars
for (File f : libDir.listFiles(onlyJars)) {
// allow a jar with the same name
// to replace a jar in the lib dir
if (!new File(jarDir, f.getName()).exists())
list.add(f);
else if (log.debug())
log.debug("jar %s override the same in the lib dir",
f.getName());
}
if (log.debug()) {
//System.out.println("Loader: reloader " + newSpoolDir);
log.debug("reloaded from %s", newSpoolDir.toString());
if (log.trace()) {
for (File f : list)
log.trace("jar %s", f.toString());
}
}
// create a class loader according the current choice
//log.error("using JCL classloader without parent");
currentClassLoader = new JarClassLoader(toUrlArray(list));
currentSpoolDir = newSpoolDir;
cleanup();
} catch (Exception ex) {
log.error(ex, "[Loader.getClassLoader]");
}
return currentClassLoader;
}
} |
8629076_1 | public static File doChoosePath() {
JFileChooser fileChooser = new JFileChooser(System.getProperty("user.home"));
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (fileChooser.showOpenDialog(MainWindow.getInstance()) == JFileChooser.APPROVE_OPTION) {
return fileChooser.getCurrentDirectory();
}
return null;
} |
8648747_53 | public synchronized long toDigest(final String key) throws DigestException, UnsupportedEncodingException {
if (key == null) {
throw new NullPointerException("You attempted to convert a null string into a hash digest");
}
final byte[] bytes = key.getBytes("UTF-8");
return toDigest(bytes);
} |
8667914_0 | public static String wrapString(String str) {
return wrapString(str, MAX_LENGTH);
} |
8672234_4 | public List<String> replaceRunOnWords(final String original) {
final List<CandidateData> candidateData = replaceRunOnWordCandidates(original);
final List<String> candidates = new ArrayList<>();
for (CandidateData candidate : candidateData) {
candidates.add(candidate.word);
}
return candidates;
} |
8680105_8 | @NotNull
@Override
protected EntityCoordinates getDestination() throws TeleportException {
MultiverseWorld mvWorld = this.getApi().getWorldManager().getWorld(world);
if (mvWorld == null) {
throw new TeleportException(Message.bundleMessage(NOT_LOADED, world));
}
return Locations.getEntityCoordinates(world, getApi().getWorldManager().getWorldUUID(world),
mvWorld.getSpawnLocation());
} |
8682860_4 | public static void roundTimeUp(Calendar calendar) {
calendar.set(Calendar.SECOND, 0);
// Round to the nearest MINUTE_INCREMENT, advancing the clock at least MINIMUM_INCREMENT.
int remainder = calendar.get(Calendar.MINUTE) % MINUTE_INCREMENT;
int increment = -remainder + MINUTE_INCREMENT;
calendar.add(Calendar.MINUTE, increment);
if (increment < MINIMUM_INCREMENT) {
calendar.add(Calendar.MINUTE, MINUTE_INCREMENT);
}
} |
8693016_2 | public VersionRows extractVersionRows() {
// Read all the concepts from the raw data
List<ConceptRow> crs = new ArrayList<ConceptRow>();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(conceptsFile));
String line = br.readLine(); // Skip first line
while (null != (line = br.readLine())) {
line = new String(line.getBytes(), "UTF8");
if (line.trim().length() < 1) {
continue;
}
int idx1 = line.indexOf('\t');
int idx2 = line.indexOf('\t', idx1 + 1);
int idx3 = line.indexOf('\t', idx2 + 1);
int idx4 = line.indexOf('\t', idx3 + 1);
int idx5 = line.indexOf('\t', idx4 + 1);
// 0..idx1 == conceptId
// idx1+1..idx2 == conceptStatus
// idx2+1..idx3 == fullySpecifiedName
// idx3+1..idx4 == ctv3Id
// idx4+1..idx5 == snomedId
// idx5+1..end == isPrimitive
if (idx1 < 0 || idx2 < 0 || idx3 < 0 || idx4 < 0 || idx5 < 0) {
br.close();
throw new RuntimeException(
"Concepts: Mis-formatted "
+ "line, expected at least 6 tab-separated fields, "
+ "got: " + line);
}
final String conceptId = line.substring(0, idx1);
final String conceptStatus = line.substring(idx1 + 1, idx2);
final String fullySpecifiedName = line.substring(idx2 + 1, idx3);
final String ctv3Id = line.substring(idx3 + 1, idx4);
final String snomedId = line.substring(idx4 + 1, idx5);
final String isPrimitive = line.substring(idx5 + 1);
crs.add(new ConceptRow(conceptId, conceptStatus, fullySpecifiedName, ctv3Id, snomedId, isPrimitive));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if(br != null) {
try { br.close(); } catch(Exception e) {}
}
}
// Read all the relationships from the raw data
List<RelationshipRow> rrs = new ArrayList<RelationshipRow>();
try {
br = new BufferedReader(
new InputStreamReader(relationshipsFile));
String line = br.readLine(); // Skip first line
while (null != (line = br.readLine())) {
if (line.trim().length() < 1) {
continue;
}
int idx1 = line.indexOf('\t');
int idx2 = line.indexOf('\t', idx1 + 1);
int idx3 = line.indexOf('\t', idx2 + 1);
int idx4 = line.indexOf('\t', idx3 + 1);
int idx5 = line.indexOf('\t', idx4 + 1);
int idx6 = line.indexOf('\t', idx5 + 1);
// 0..idx1 == relationshipId
// idx1+1..idx2 == conceptId1
// idx2+1..idx3 == relationshipType
// idx3+1..idx4 == conceptId2
// idx4+1..idx5 == characteristicType
// idx5+1..idx6 == refinability
// idx6+1..end == relationshipGroup
if (idx1 < 0 || idx2 < 0 || idx3 < 0 || idx4 < 0 || idx5 < 0
|| idx6 < 0) {
br.close();
throw new RuntimeException("Concepts: Mis-formatted "
+ "line, expected 7 tab-separated fields, "
+ "got: " + line);
}
final String relationshipId = line.substring(0, idx1);
final String conceptId1 = line.substring(idx1 + 1, idx2);
final String relationshipType = line.substring(idx2 + 1, idx3);
final String conceptId2 = line.substring(idx3 + 1, idx4);
final String characteristicType = line.substring(idx4 + 1, idx5);
final String refinability = line.substring(idx5 + 1, idx6);
final String relationshipGroup = line.substring(idx6 + 1);
rrs.add(new RelationshipRow(relationshipId, conceptId1, relationshipType, conceptId2,
characteristicType, refinability, relationshipGroup));
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if(br != null) {
try { br.close(); } catch(Exception e) {}
}
}
// In this case we know we are dealing with a single version so we need
// to generate a single version row
VersionRows vr = new VersionRows(version);
vr.getConceptRows().addAll(crs);
vr.getRelationshipRows().addAll(rrs);
return vr;
} |
8701655_107 | public Registration add(final ListenerT l) {
if (isEmpty()) {
beforeFirstAdded();
}
if (myFireDepth > 0) {
myListeners.add(new ListenerOp<>(l, true));
} else {
if (myListeners == null) {
myListeners = new ArrayList<>(1);
}
myListeners.add(l);
myListenersCount++;
}
return new Registration() {
@Override
protected void doRemove() {
if (myFireDepth > 0) {
myListeners.add(new ListenerOp<>(l, false));
} else {
myListeners.remove(l);
myListenersCount--;
}
if (isEmpty()) {
afterLastRemoved();
}
}
};
} |
8706918_55 | @Override
public Result apply(PathData item) throws IOException {
if(getFileStatus(item).getModificationTime() > filetime) {
return Result.PASS;
}
return Result.FAIL;
} |
8714569_2 | public Set<Inclusion> normalise(final Set<? extends Axiom> inclusions) {
// Exhaustively apply NF1 to NF4
Set<Inclusion> newIs = transformAxiom(inclusions);
Set<Inclusion> oldIs = new HashSet<Inclusion>(newIs.size());
final Set<Inclusion> done = new HashSet<Inclusion>(newIs.size());
do {
final Set<Inclusion> tmp = oldIs;
oldIs = newIs;
newIs = tmp;
newIs.clear();
for (Inclusion i : oldIs) {
Inclusion[] s = i.normalise1(factory);
if (null != s) {
for (int j = 0; j < s.length; j++) {
if (null != s[j]) {
newIs.add(s[j]);
}
}
} else {
done.add(i);
}
}
} while (!newIs.isEmpty());
newIs.addAll(done);
done.clear();
// Then exhaustively apply NF5 to NF7
do {
final Set<Inclusion> tmp = oldIs;
oldIs = newIs;
newIs = tmp;
newIs.clear();
for (Inclusion i : oldIs) {
Inclusion[] s = i.normalise2(factory);
if (null != s) {
for (int j = 0; j < s.length; j++) {
if (null != s[j]) {
newIs.add(s[j]);
}
}
} else {
done.add(i);
}
}
} while (!newIs.isEmpty());
if(log.isTraceEnabled()) {
log.trace("Normalised axioms:");
for(Inclusion inc : done) {
StringBuilder sb = new StringBuilder();
if(inc instanceof GCI) {
GCI gci = (GCI)inc;
sb.append(printInternalObject(gci.lhs()));
sb.append(" [ ");
sb.append(printInternalObject(gci.rhs()));
} else if(inc instanceof RI) {
RI ri = (RI)inc;
int[] lhs = ri.getLhs();
sb.append(factory.lookupRoleId(lhs[0]));
for(int i = 1; i < lhs.length; i++) {
sb.append(" * ");
sb.append(factory.lookupRoleId(lhs[i]));
}
sb.append(" [ ");
sb.append(factory.lookupRoleId(ri.getRhs()));
}
log.trace(sb.toString());
}
}
return done;
} |
8715861_5 | @Override
public String getSQL(Version currentVersion) {
return Tables.getSQL(SQL, currentVersion);
} |
8731044_81 | public Property inheritProperty(Node content, String relPath) throws RepositoryException {
if (content == null) {
return null;
}
if (StringUtils.isBlank(relPath)) {
throw new IllegalArgumentException("relative path cannot be null or empty");
}
try {
Node inheritedNode = wrapForInheritance(content);
return inheritedNode.getProperty(relPath);
} catch (PathNotFoundException e) {
// TODO fgrilli: rethrow exception?
} catch (RepositoryException e) {
// TODO fgrilli:rethrow exception?
}
return null;
} |
8742308_0 | public static long predictNext(TreeMap<Integer, Long> laps)
{
float smoothing = (((float) 2) / (laps.size() + 1));
long previousEMA = laps.get(laps.firstKey());
Set<Integer> keys = laps.keySet();
for (Iterator<Integer> i = keys.iterator(); i.hasNext();) {
Integer key = i.next();
previousEMA = (long) ((laps.get(key) - previousEMA) * smoothing + previousEMA);
}
return (long) ((previousEMA - previousEMA) * smoothing + previousEMA);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.