_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q18500 | StencilOperands.lessThanOrEqual | train | public boolean lessThanOrEqual(Object left, Object right) {
if (left == right) {
return true;
}
else if (left == null || right == null) {
return false;
}
else {
return compare(left, right, "<=") <= 0;
}
} | java | {
"resource": ""
} |
q18501 | StencilOperands.greaterThanOrEqual | train | public boolean greaterThanOrEqual(Object left, Object right) {
if (left == right) {
return true;
}
else if (left == null || right == null) {
return false;
}
else {
return compare(left, right, ">=") >= 0;
}
} | java | {
"resource": ""
} |
q18502 | StencilOperands.toInteger | train | public int toInteger(Object val) {
if (val == null) {
return 0;
}
else if (val instanceof Double) {
if (!Double.isNaN(((Double) val).doubleValue())) {
return 0;
}
else {
return ((Double) val).intValue();
}
}
else if (val instanceof Number) {
return ((Number) val).intValue();
}
else if (val instanceof String) {
if ("".equals(val)) {
return 0;
}
return Integer.parseInt((String) val);
}
else if (val instanceof Boolean) {
return ((Boolean) val).booleanValue() ? 1 : 0;
}
else if (val instanceof Character) {
return ((Character) val).charValue();
}
throw new ArithmeticException("Integer coercion: " + val.getClass().getName() + ":(" + val + ")");
} | java | {
"resource": ""
} |
q18503 | StencilOperands.toBigInteger | train | public BigInteger toBigInteger(Object val) {
if (val == null) {
return BigInteger.ZERO;
}
else if (val instanceof BigInteger) {
return (BigInteger) val;
}
else if (val instanceof Double) {
if (!Double.isNaN(((Double) val).doubleValue())) {
return new BigInteger(val.toString());
}
else {
return BigInteger.ZERO;
}
}
else if (val instanceof Number) {
return new BigInteger(val.toString());
}
else if (val instanceof String) {
String string = (String) val;
if ("".equals(string.trim())) {
return BigInteger.ZERO;
}
else {
return new BigInteger(string);
}
}
else if (val instanceof Character) {
int i = ((Character) val).charValue();
return BigInteger.valueOf(i);
}
throw new ArithmeticException("BigInteger coercion: " + val.getClass().getName() + ":(" + val + ")");
} | java | {
"resource": ""
} |
q18504 | StencilOperands.toBigDecimal | train | public BigDecimal toBigDecimal(Object val) {
if (val instanceof BigDecimal) {
return roundBigDecimal((BigDecimal) val);
}
else if (val == null) {
return BigDecimal.ZERO;
}
else if (val instanceof String) {
String string = ((String) val).trim();
if ("".equals(string)) {
return BigDecimal.ZERO;
}
return roundBigDecimal(new BigDecimal(string, getMathContext()));
}
else if (val instanceof Double) {
if (!Double.isNaN(((Double) val).doubleValue())) {
return roundBigDecimal(new BigDecimal(val.toString(), getMathContext()));
}
else {
return BigDecimal.ZERO;
}
}
else if (val instanceof Number) {
return roundBigDecimal(new BigDecimal(val.toString(), getMathContext()));
}
else if (val instanceof Character) {
int i = ((Character) val).charValue();
return new BigDecimal(i);
}
throw new ArithmeticException("BigDecimal coercion: " + val.getClass().getName() + ":(" + val + ")");
} | java | {
"resource": ""
} |
q18505 | StencilOperands.toDouble | train | public double toDouble(Object val) {
if (val == null) {
return 0;
}
else if (val instanceof Double) {
return ((Double) val).doubleValue();
}
else if (val instanceof Number) {
// The below construct is used rather than ((Number)val).doubleValue() to ensure
// equality between comparing new Double( 6.4 / 3 ) and the stencil expression of 6.4 / 3
return Double.parseDouble(String.valueOf(val));
}
else if (val instanceof Boolean) {
return ((Boolean) val).booleanValue() ? 1. : 0.;
}
else if (val instanceof String) {
String string = ((String) val).trim();
if ("".equals(string)) {
return Double.NaN;
}
else {
// the spec seems to be iffy about this. Going to give it a wack anyway
return Double.parseDouble(string);
}
}
else if (val instanceof Character) {
int i = ((Character) val).charValue();
return i;
}
throw new ArithmeticException("Double coercion: " + val.getClass().getName() + ":(" + val + ")");
} | java | {
"resource": ""
} |
q18506 | StencilOperands.toCollection | train | public Collection<?> toCollection(Object val) {
if (val == null) {
return Collections.emptyList();
}
else if (val instanceof Collection<?>) {
return (Collection<?>) val;
}
else if (val.getClass().isArray()) {
return newArrayList((Object[]) val);
}
else if (val instanceof Map<?,?>) {
return ((Map<?,?>)val).entrySet();
}
else {
return newArrayList(val);
}
} | java | {
"resource": ""
} |
q18507 | StencilOperands.narrowAccept | train | protected boolean narrowAccept(Class<?> narrow, Class<?> source) {
return narrow == null || narrow.equals(source);
} | java | {
"resource": ""
} |
q18508 | StencilOperands.narrowNumber | train | protected Number narrowNumber(Number original, Class<?> narrow) {
if (original == null) {
return original;
}
Number result = original;
if (original instanceof BigDecimal) {
BigDecimal bigd = (BigDecimal) original;
// if it's bigger than a double it can't be narrowed
if (bigd.compareTo(BIGD_DOUBLE_MAX_VALUE) > 0) {
return original;
}
else {
try {
long l = bigd.longValueExact();
// coerce to int when possible (int being so often used in method
// parms)
if (narrowAccept(narrow, Integer.class) && l <= Integer.MAX_VALUE && l >= Integer.MIN_VALUE) {
return Integer.valueOf((int) l);
}
else if (narrowAccept(narrow, Long.class)) {
return Long.valueOf(l);
}
}
catch (ArithmeticException xa) {
// ignore, no exact value possible
}
}
}
if (original instanceof Double || original instanceof Float || original instanceof BigDecimal) {
double value = original.doubleValue();
if (narrowAccept(narrow, Float.class) && value <= Float.MAX_VALUE && value >= Float.MIN_VALUE) {
result = Float.valueOf(result.floatValue());
}
// else it fits in a double only
}
else {
if (original instanceof BigInteger) {
BigInteger bigi = (BigInteger) original;
// if it's bigger than a Long it can't be narrowed
if (bigi.compareTo(BIGI_LONG_MAX_VALUE) > 0 || bigi.compareTo(BIGI_LONG_MIN_VALUE) < 0) {
return original;
}
}
long value = original.longValue();
if (narrowAccept(narrow, Byte.class) && value <= Byte.MAX_VALUE && value >= Byte.MIN_VALUE) {
// it will fit in a byte
result = Byte.valueOf((byte) value);
}
else if (narrowAccept(narrow, Short.class) && value <= Short.MAX_VALUE && value >= Short.MIN_VALUE) {
result = Short.valueOf((short) value);
}
else if (narrowAccept(narrow, Integer.class) && value <= Integer.MAX_VALUE && value >= Integer.MIN_VALUE) {
result = Integer.valueOf((int) value);
}
// else it fits in a long
}
return result;
} | java | {
"resource": ""
} |
q18509 | AttributeSet.get | train | public static AttributeSet get(final String _typeName,
final String _name)
throws CacheReloadException
{
return (AttributeSet) Type.get(AttributeSet.evaluateName(_typeName, _name));
} | java | {
"resource": ""
} |
q18510 | AttributeSet.find | train | public static AttributeSet find(final String _typeName,
final String _name)
throws CacheReloadException
{
AttributeSet ret = (AttributeSet) Type.get(AttributeSet.evaluateName(_typeName, _name));
if (ret == null) {
if (Type.get(_typeName).getParentType() != null) {
ret = AttributeSet.find(Type.get(_typeName).getParentType().getName(), _name);
}
}
return ret;
} | java | {
"resource": ""
} |
q18511 | ClassificationValueSelect.getClassification | train | private Set<Classification> getClassification(final List<Long> _classIds)
throws CacheReloadException
{
final Set<Classification> noadd = new HashSet<>();
final Set<Classification> add = new HashSet<>();
if (_classIds != null) {
for (final Long id : _classIds) {
Classification clazz = (Classification) Type.get(id);
if (!noadd.contains(clazz)) {
add.add(clazz);
while (clazz.getParentClassification() != null) {
clazz = clazz.getParentClassification();
if (add.contains(clazz)) {
add.remove(clazz);
}
noadd.add(clazz);
}
}
}
}
return add;
} | java | {
"resource": ""
} |
q18512 | ClassificationValueSelect.executeOneCompleteStmt | train | protected boolean executeOneCompleteStmt(final String _complStmt,
final List<Instance> _instances)
throws EFapsException
{
final boolean ret = false;
ConnectionResource con = null;
try {
con = Context.getThreadContext().getConnectionResource();
final Statement stmt = con.createStatement();
final ResultSet rs = stmt.executeQuery(_complStmt.toString());
final Map<Long, List<Long>> link2clazz = new HashMap<>();
while (rs.next()) {
final long linkId = rs.getLong(2);
final long classificationID = rs.getLong(3);
final List<Long> templ;
if (link2clazz.containsKey(linkId)) {
templ = link2clazz.get(linkId);
} else {
templ = new ArrayList<>();
link2clazz.put(linkId, templ);
}
templ.add(classificationID);
}
for (final Instance instance : _instances) {
this.instances2classId.put(instance, link2clazz.get(instance.getId()));
}
rs.close();
stmt.close();
} catch (final SQLException e) {
throw new EFapsException(ClassificationValueSelect.class, "executeOneCompleteStmt", e);
}
return ret;
} | java | {
"resource": ""
} |
q18513 | KoanWriter.writeSourceToFile | train | public static void writeSourceToFile(Class<?> koanClass, String newSource) {
Path currentRelativePath = Paths.get("");
String workingDirectory = currentRelativePath.toAbsolutePath().toString();
String packagePath = koanClass.getPackage().getName();
packagePath = packagePath.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR);
String className = koanClass.getSimpleName();
File file = new File(workingDirectory + KOAN_JAVA_PATH + packagePath + PATH_SEPARATOR + className + JAVA_EXTENSION);
try {
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newSource);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q18514 | LoginHandler.createPerson | train | protected Person createPerson(final LoginContext _login)
throws EFapsException
{
Person person = null;
for (final JAASSystem system : JAASSystem.getAllJAASSystems()) {
final Set<?> users = _login.getSubject().getPrincipals(system.getPersonJAASPrincipleClass());
for (final Object persObj : users) {
try {
final String persKey = (String) system.getPersonMethodKey().invoke(persObj);
final String persName = (String) system.getPersonMethodName().invoke(persObj);
if (person == null) {
person = Person.createPerson(system, persKey, persName, null);
} else {
person.assignToJAASSystem(system, persKey);
}
} catch (final IllegalAccessException e) {
LoginHandler.LOG.error("could not execute a person method for system " + system.getName(), e);
throw new EFapsException(LoginHandler.class, "IllegalAccessException", e);
} catch (final IllegalArgumentException e) {
LoginHandler.LOG.error("could not execute a person method for system " + system.getName(), e);
throw new EFapsException(LoginHandler.class, "IllegalArgumentException", e);
} catch (final InvocationTargetException e) {
LoginHandler.LOG.error("could not execute a person method for system " + system.getName(), e);
throw new EFapsException(LoginHandler.class, "InvocationTargetException", e);
}
}
}
return person;
} | java | {
"resource": ""
} |
q18515 | LoginHandler.updatePerson | train | protected void updatePerson(final LoginContext _login,
final Person _person)
throws EFapsException
{
for (final JAASSystem system : JAASSystem.getAllJAASSystems()) {
final Set<?> users = _login.getSubject().getPrincipals(system.getPersonJAASPrincipleClass());
for (final Object persObj : users) {
try {
for (final Map.Entry<Person.AttrName, Method> entry
: system.getPersonMethodAttributes().entrySet()) {
_person.updateAttrValue(entry.getKey(), (String) entry.getValue().invoke(persObj));
}
} catch (final IllegalAccessException e) {
LoginHandler.LOG.error("could not execute a person method for system " + system.getName(), e);
throw new EFapsException(LoginHandler.class, "IllegalAccessException", e);
} catch (final IllegalArgumentException e) {
LoginHandler.LOG.error("could not execute a person method for system " + system.getName(), e);
throw new EFapsException(LoginHandler.class, "IllegalArgumentException", e);
} catch (final InvocationTargetException e) {
LoginHandler.LOG.error("could not execute a person method for system " + system.getName(), e);
throw new EFapsException(LoginHandler.class, "InvocationTargetException", e);
}
}
}
_person.commitAttrValuesInDB();
} | java | {
"resource": ""
} |
q18516 | LoginHandler.updateRoles | train | protected void updateRoles(final LoginContext _login,
final Person _person)
throws EFapsException
{
for (final JAASSystem system : JAASSystem.getAllJAASSystems()) {
if (system.getRoleJAASPrincipleClass() != null) {
final Set<?> rolesJaas = _login.getSubject().getPrincipals(system.getRoleJAASPrincipleClass());
final Set<Role> rolesEfaps = new HashSet<>();
for (final Object roleObj : rolesJaas) {
try {
final String roleKey = (String) system.getRoleMethodKey().invoke(roleObj);
final Role roleEfaps = Role.getWithJAASKey(system, roleKey);
if (roleEfaps != null) {
rolesEfaps.add(roleEfaps);
}
} catch (final IllegalAccessException e) {
LoginHandler.LOG.error("could not execute role key method for system " + system.getName(), e);
} catch (final IllegalArgumentException e) {
LoginHandler.LOG.error("could not execute role key method for system " + system.getName(), e);
} catch (final InvocationTargetException e) {
LoginHandler.LOG.error("could not execute role key method for system " + system.getName(), e);
}
}
_person.setRoles(system, rolesEfaps);
}
}
} | java | {
"resource": ""
} |
q18517 | LoginHandler.updateGroups | train | protected void updateGroups(final LoginContext _login,
final Person _person)
throws EFapsException
{
for (final JAASSystem system : JAASSystem.getAllJAASSystems()) {
if (system.getGroupJAASPrincipleClass() != null) {
final Set<?> groupsJaas = _login.getSubject().getPrincipals(system.getGroupJAASPrincipleClass());
final Set<Group> groupsEfaps = new HashSet<>();
for (final Object groupObj : groupsJaas) {
try {
final String groupKey = (String) system.getGroupMethodKey().invoke(groupObj);
final Group groupEfaps = Group.getWithJAASKey(system, groupKey);
if (groupEfaps != null) {
groupsEfaps.add(groupEfaps);
}
} catch (final IllegalAccessException e) {
LoginHandler.LOG.error("could not execute group key method for system " + system.getName(), e);
} catch (final IllegalArgumentException e) {
LoginHandler.LOG.error("could not execute group key method for system " + system.getName(), e);
} catch (final InvocationTargetException e) {
LoginHandler.LOG.error("could not execute group key method for system " + system.getName(), e);
}
}
_person.setGroups(system, groupsEfaps);
}
}
} | java | {
"resource": ""
} |
q18518 | Attachment.updateWithUploadDetails | train | public Attachment updateWithUploadDetails(UploadContentResponse response) {
this.id = response.getId();
this.url = response.getUrl();
this.size = response.getSize();
this.type = response.getType();
return this;
} | java | {
"resource": ""
} |
q18519 | DerbyDatabase.initTableInfoUniqueKeys | train | @Override
protected void initTableInfoUniqueKeys(final Connection _con,
final String _sql,
final Map<String, TableInformation> _cache4Name)
throws SQLException
{
final String sqlStmt = new StringBuilder()
.append("select t.tablename as TABLE_NAME, c.CONSTRAINTNAME as INDEX_NAME, g.DESCRIPTOR as COLUMN_NAME")
.append(" from SYS.SYSTABLES t, SYS.SYSCONSTRAINTS c, SYS.SYSKEYS k, SYS.SYSCONGLOMERATES g ")
.append(" where t.TABLEID=c.TABLEID")
.append(" AND c.TYPE='U'")
.append(" AND c.CONSTRAINTID = k.CONSTRAINTID")
.append(" AND k.CONGLOMERATEID = g.CONGLOMERATEID")
.toString();
super.initTableInfoUniqueKeys(_con, sqlStmt, _cache4Name);
} | java | {
"resource": ""
} |
q18520 | VFSStoreResource.backup | train | private void backup(final FileObject _backup,
final int _number)
throws FileSystemException
{
if (_number < this.numberBackup) {
final FileObject backFile = this.manager.resolveFile(this.manager.getBaseFile(),
this.storeFileName + VFSStoreResource.EXTENSION_BACKUP + _number);
if (backFile.exists()) {
backup(backFile, _number + 1);
}
_backup.moveTo(backFile);
} else {
_backup.delete();
}
} | java | {
"resource": ""
} |
q18521 | VFSStoreResource.recover | train | @Override
public Xid[] recover(final int _flag)
{
if (VFSStoreResource.LOG.isDebugEnabled()) {
VFSStoreResource.LOG.debug("recover (flag = " + _flag + ")");
}
return null;
} | java | {
"resource": ""
} |
q18522 | ChatController.sendMessageWithAttachments | train | Observable<ChatResult> sendMessageWithAttachments(@NonNull final String conversationId, @NonNull final MessageToSend message, @Nullable final List<Attachment> attachments) {
final MessageProcessor messageProcessor = attCon.createMessageProcessor(message, attachments, conversationId, getProfileId());
return checkState()
.flatMap(client ->
{
messageProcessor.preparePreUpload(); // convert fom too large message parts to attachments, adds temp upload parts for all attachments
return upsertTempMessage(messageProcessor.createTempMessage()) // create temporary message
.flatMap(isOk -> attCon.uploadAttachments(messageProcessor.getAttachments(), client)) // upload attachments
.flatMap(uploaded -> {
if (uploaded != null && !uploaded.isEmpty()) {
messageProcessor.preparePostUpload(uploaded); // remove temp upload parts, add parts with upload data
return upsertTempMessage(messageProcessor.createTempMessage()); // update message with attachments details like url
} else {
return Observable.fromCallable(() -> true);
}
})
.flatMap(isOk -> client.service().messaging().sendMessage(conversationId, messageProcessor.prepareMessageToSend()) // send message with attachments details as additional message parts
.flatMap(result -> result.isSuccessful() ? updateStoreWithSentMsg(messageProcessor, result) : handleMessageError(messageProcessor, new ComapiException(result.getErrorBody()))) // update temporary message with a new message id obtained from the response
.onErrorResumeNext(t -> handleMessageError(messageProcessor, t))); // if error occurred update message status list adding error status
});
} | java | {
"resource": ""
} |
q18523 | ChatController.handleParticipantsAdded | train | public Observable<ChatResult> handleParticipantsAdded(final String conversationId) {
return persistenceController.getConversation(conversationId).flatMap(conversation -> {
if (conversation == null) {
return handleNoLocalConversation(conversationId);
} else {
return Observable.fromCallable(() -> new ChatResult(true, null));
}
});
} | java | {
"resource": ""
} |
q18524 | ChatController.handleMessageError | train | private Observable<ChatResult> handleMessageError(MessageProcessor mp, Throwable t) {
return persistenceController.updateStoreForSentError(mp.getConversationId(), mp.getTempId(), mp.getSender())
.map(success -> new ChatResult(false, new ChatResult.Error(0, t)));
} | java | {
"resource": ""
} |
q18525 | ChatController.checkState | train | Observable<RxComapiClient> checkState() {
final RxComapiClient client = clientReference.get();
if (client == null) {
return Observable.error(new ComapiException("No client instance available in controller."));
} else {
return Observable.fromCallable(() -> client);
}
} | java | {
"resource": ""
} |
q18526 | ChatController.handleNoLocalConversation | train | Observable<ChatResult> handleNoLocalConversation(String conversationId) {
return checkState().flatMap(client -> client.service().messaging().getConversation(conversationId)
.flatMap(result -> {
if (result.isSuccessful() && result.getResult() != null) {
return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build())
.map(success -> new ChatResult(success, success ? null : new ChatResult.Error(0, "External store reported failure.", "Error when inserting conversation "+conversationId)));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(result));
}
}));
} | java | {
"resource": ""
} |
q18527 | ChatController.markDelivered | train | Observable<ComapiResult<Void>> markDelivered(String conversationId, Set<String> ids) {
final List<MessageStatusUpdate> updates = new ArrayList<>();
updates.add(MessageStatusUpdate.builder().setMessagesIds(ids).setStatus(MessageStatus.delivered).setTimestamp(DateHelper.getCurrentUTC()).build());
return checkState().flatMap(client -> client.service().messaging().updateMessageStatus(conversationId, updates)
.retryWhen(observable -> {
return observable.zipWith(Observable.range(1, 3), (Func2<Throwable, Integer, Integer>) (throwable, integer) -> integer).flatMap(new Func1<Integer, Observable<Long>>() {
@Override
public Observable<Long> call(Integer retryCount) {
return Observable.timer((long) Math.pow(1, retryCount), TimeUnit.SECONDS);
}
});
}
));
} | java | {
"resource": ""
} |
q18528 | ChatController.getProfileId | train | String getProfileId() {
final RxComapiClient client = clientReference.get();
return client != null ? client.getSession().getProfileId() : null;
} | java | {
"resource": ""
} |
q18529 | ChatController.synchroniseStore | train | Observable<ChatResult> synchroniseStore() {
if (isSynchronising.getAndSet(true)) {
log.i("Synchronisation in progress.");
return Observable.fromCallable(() -> new ChatResult(true, null));
}
log.i("Synchronising store.");
return synchroniseConversations()
.onErrorReturn(t -> new ChatResult(false, new ChatResult.Error(0, t)))
.doOnNext(i -> {
if (i.isSuccessful()) {
log.i("Synchronisation successfully finished.");
} else {
log.e("Synchronisation finished with error. " + (i.getError() != null ? i.getError().getDetails() : ""));
}
isSynchronising.compareAndSet(true, false);
});
} | java | {
"resource": ""
} |
q18530 | ChatController.handleConversationCreated | train | Observable<ChatResult> handleConversationCreated(ComapiResult<ConversationDetails> result) {
if (result.isSuccessful()) {
return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()).map(success -> adapter.adaptResult(result, success));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(result));
}
} | java | {
"resource": ""
} |
q18531 | ChatController.handleConversationDeleted | train | Observable<ChatResult> handleConversationDeleted(String conversationId, ComapiResult<Void> result) {
if (result.getCode() != ETAG_NOT_VALID) {
return persistenceController.deleteConversation(conversationId).map(success -> adapter.adaptResult(result, success));
} else {
return checkState().flatMap(client -> client.service().messaging().getConversation(conversationId)
.flatMap(newResult -> {
if (newResult.isSuccessful()) {
return persistenceController.upsertConversation(ChatConversation.builder().populate(newResult.getResult(), newResult.getETag()).build())
.flatMap(success -> Observable.fromCallable(() -> new ChatResult(false, success ? new ChatResult.Error(ETAG_NOT_VALID, "Conversation updated, try delete again.", "Conversation "+conversationId+" updated in response to wrong eTag error when deleting.") : new ChatResult.Error(0, "Error updating custom store.", null))));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(newResult));
}
}));
}
} | java | {
"resource": ""
} |
q18532 | ChatController.handleConversationUpdated | train | Observable<ChatResult> handleConversationUpdated(ConversationUpdate request, ComapiResult<ConversationDetails> result) {
if (result.isSuccessful()) {
return persistenceController.upsertConversation(ChatConversation.builder().populate(result.getResult(), result.getETag()).build()).map(success -> adapter.adaptResult(result, success));
}
if (result.getCode() == ETAG_NOT_VALID) {
return checkState().flatMap(client -> client.service().messaging().getConversation(request.getId())
.flatMap(newResult -> {
if (newResult.isSuccessful()) {
return persistenceController.upsertConversation(ChatConversation.builder().populate(newResult.getResult(), newResult.getETag()).build())
.flatMap(success -> Observable.fromCallable(() -> new ChatResult(false, success ? new ChatResult.Error(ETAG_NOT_VALID, "Conversation updated, try delete again.", "Conversation "+request.getId()+" updated in response to wrong eTag error when updating."): new ChatResult.Error(1500, "Error updating custom store.", null))));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(newResult));
}
}));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(result));
}
} | java | {
"resource": ""
} |
q18533 | ChatController.handleMessageStatusToUpdate | train | Observable<ChatResult> handleMessageStatusToUpdate(String conversationId, List<MessageStatusUpdate> msgStatusList, ComapiResult<Void> result) {
if (result.isSuccessful() && msgStatusList != null && !msgStatusList.isEmpty()) {
return persistenceController.upsertMessageStatuses(conversationId, getProfileId(), msgStatusList).map(success -> adapter.adaptResult(result, success));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(result));
}
} | java | {
"resource": ""
} |
q18534 | ChatController.upsertTempMessage | train | private Observable<Boolean> upsertTempMessage(ChatMessage message) {
return persistenceController.updateStoreWithNewMessage(message, noConversationListener)
.doOnError(t -> log.e("Error saving temp message " + t.getLocalizedMessage()))
.onErrorReturn(t -> false);
} | java | {
"resource": ""
} |
q18535 | ChatController.updateStoreWithSentMsg | train | Observable<ChatResult> updateStoreWithSentMsg(MessageProcessor mp, ComapiResult<MessageSentResponse> response) {
if (response.isSuccessful()) {
return persistenceController.updateStoreWithNewMessage(mp.createFinalMessage(response.getResult()), noConversationListener).map(success -> adapter.adaptResult(response, success));
} else {
return Observable.fromCallable(() -> adapter.adaptResult(response));
}
} | java | {
"resource": ""
} |
q18536 | ChatController.synchroniseConversations | train | private Observable<ChatResult> synchroniseConversations() {
return checkState().flatMap(client -> client.service().messaging()
.getConversations(false)
.flatMap(result -> persistenceController.loadAllConversations()
.map(chatConversationBases -> compare(result.isSuccessful(), result.getResult(), chatConversationBases)))
.flatMap(this::updateLocalConversationList)
.flatMap(result -> lookForMissingEvents(client, result))
.map(result -> new ChatResult(result.isSuccessful, null)));
} | java | {
"resource": ""
} |
q18537 | ChatController.compare | train | ConversationComparison compare(boolean successful, List<Conversation> remote, List<ChatConversationBase> local) {
return new ConversationComparison(successful, makeMapFromDownloadedConversations(remote), makeMapFromSavedConversations(local));
} | java | {
"resource": ""
} |
q18538 | ChatController.synchroniseConversation | train | Observable<ChatResult> synchroniseConversation(String conversationId) {
return checkState().flatMap(client -> client.service().messaging()
.queryMessages(conversationId, null, 1)
.map(result -> {
if (result.isSuccessful() && result.getResult() != null) {
return (long) result.getResult().getLatestEventId();
}
return -1L;
})
.flatMap(result -> persistenceController.getConversation(conversationId).map(loaded -> compare(result, loaded)))
.flatMap(this::updateLocalConversationList)
.flatMap(result -> lookForMissingEvents(client, result))
.map(result -> new ChatResult(result.isSuccessful, null)));
} | java | {
"resource": ""
} |
q18539 | ChatController.lookForMissingEvents | train | private Observable<ConversationComparison> lookForMissingEvents(final RxComapiClient client, ConversationComparison conversationComparison) {
if (!conversationComparison.isSuccessful || conversationComparison.conversationsToUpdate.isEmpty()) {
return Observable.fromCallable(() -> conversationComparison);
}
return synchroniseEvents(client, conversationComparison.conversationsToUpdate, new ArrayList<>())
.map(result -> {
if (conversationComparison.isSuccessful && !result) {
conversationComparison.addSuccess(false);
}
return conversationComparison;
});
} | java | {
"resource": ""
} |
q18540 | ChatController.updateLocalConversationList | train | private Observable<ConversationComparison> updateLocalConversationList(final ConversationComparison conversationComparison) {
return Observable.zip(persistenceController.deleteConversations(conversationComparison.conversationsToDelete),
persistenceController.upsertConversations(conversationComparison.conversationsToAdd),
persistenceController.updateConversations(conversationComparison.conversationsToUpdate),
(success1, success2, success3) -> success1 && success2 && success3)
.map(result -> {
conversationComparison.addSuccess(result);
return conversationComparison;
});
} | java | {
"resource": ""
} |
q18541 | ChatController.synchroniseEvents | train | private Observable<Boolean> synchroniseEvents(final RxComapiClient client, @NonNull final List<ChatConversation> conversationsToUpdate, @NonNull final List<Boolean> successes) {
final List<ChatConversation> limited = limitNumberOfConversations(conversationsToUpdate);
if (limited.isEmpty()) {
return Observable.fromCallable(() -> true);
}
return Observable.from(limited)
.onBackpressureBuffer()
.flatMap(conversation -> persistenceController.getConversation(conversation.getConversationId()))
.flatMap(conversation -> {
if (conversation.getLastRemoteEventId() > conversation.getLastLocalEventId()) {
final long from = conversation.getLastLocalEventId() >= 0 ? conversation.getLastLocalEventId() : 0;
return queryEventsRecursively(client, conversation.getConversationId(), from, 0, successes).map(ComapiResult::isSuccessful);
} else {
return Observable.fromCallable((Callable<Object>) () -> true);
}
})
.flatMap(res -> Observable.from(successes).all(Boolean::booleanValue));
} | java | {
"resource": ""
} |
q18542 | ChatController.queryEventsRecursively | train | private Observable<ComapiResult<ConversationEventsResponse>> queryEventsRecursively(final RxComapiClient client, final String conversationId, final long lastEventId, final int count, final List<Boolean> successes) {
return client.service().messaging().queryConversationEvents(conversationId, lastEventId, eventsPerQuery)
.flatMap(result -> processEventsQueryResponse(result, successes))
.flatMap(result -> {
if (result.getResult() != null && result.getResult().getEventsInOrder().size() >= eventsPerQuery && count < maxEventQueries) {
return queryEventsRecursively(client, conversationId, lastEventId + result.getResult().getEventsInOrder().size(), count + 1, successes);
} else {
return Observable.just(result);
}
});
} | java | {
"resource": ""
} |
q18543 | ChatController.processEventsQueryResponse | train | private Observable<ComapiResult<ConversationEventsResponse>> processEventsQueryResponse(ComapiResult<ConversationEventsResponse> result, final List<Boolean> successes) {
ConversationEventsResponse response = result.getResult();
successes.add(result.isSuccessful());
if (response != null && response.getEventsInOrder().size() > 0) {
Collection<Event> events = response.getEventsInOrder();
List<Observable<Boolean>> list = new ArrayList<>();
for (Event event : events) {
if (event instanceof MessageSentEvent) {
MessageSentEvent messageEvent = (MessageSentEvent) event;
list.add(persistenceController.updateStoreWithNewMessage(ChatMessage.builder().populate(messageEvent).build(), noConversationListener));
} else if (event instanceof MessageDeliveredEvent) {
list.add(persistenceController.upsertMessageStatus(ChatMessageStatus.builder().populate((MessageDeliveredEvent) event).build()));
} else if (event instanceof MessageReadEvent) {
list.add(persistenceController.upsertMessageStatus(ChatMessageStatus.builder().populate((MessageReadEvent) event).build()));
}
}
return Observable.from(list)
.flatMap(task -> task)
.doOnNext(successes::add)
.toList()
.map(results -> result);
}
return Observable.fromCallable(() -> result);
} | java | {
"resource": ""
} |
q18544 | ChatController.limitNumberOfConversations | train | private List<ChatConversation> limitNumberOfConversations(List<ChatConversation> conversations) {
List<ChatConversation> noEmptyConversations = new ArrayList<>();
for (ChatConversation c : conversations) {
if (c.getLastRemoteEventId() != null && c.getLastRemoteEventId() >= 0) {
noEmptyConversations.add(c);
}
}
List<ChatConversation> limitedList;
if (noEmptyConversations.size() <= maxConversationsSynced) {
limitedList = noEmptyConversations;
} else {
SortedMap<Long, ChatConversation> sorted = new TreeMap<>();
for (ChatConversation conversation : noEmptyConversations) {
Long updatedOn = conversation.getUpdatedOn();
if (updatedOn != null) {
sorted.put(updatedOn, conversation);
}
}
limitedList = new ArrayList<>();
Object[] array = sorted.values().toArray();
for (int i = 0; i < Math.min(maxConversationsSynced, array.length); i++) {
limitedList.add((ChatConversation) array[i]);
}
}
return limitedList;
} | java | {
"resource": ""
} |
q18545 | ChatController.handleMessage | train | public Observable<Boolean> handleMessage(final ChatMessage message) {
String sender = message.getSentBy();
Observable<Boolean> replaceMessages = persistenceController.updateStoreWithNewMessage(message, noConversationListener);
if (!TextUtils.isEmpty(sender) && !sender.equals(getProfileId())) {
final Set<String> ids = new HashSet<>();
ids.add(message.getMessageId());
return Observable.zip(replaceMessages, markDelivered(message.getConversationId(), ids), (saved, result) -> saved && result.isSuccessful());
} else {
return replaceMessages;
}
} | java | {
"resource": ""
} |
q18546 | NFA.analyzeEndStop | train | public void analyzeEndStop()
{
DFA<T> dfa = constructDFA(new Scope<DFAState<T>>("analyzeEndStop"));
for (DFAState<T> s : dfa)
{
if (s.isAccepting())
{
if (s.isEndStop())
{
for (NFAState<T> n : s.getNfaSet())
{
if (n.isAccepting())
{
n.setEndStop(true);
}
}
}
}
}
} | java | {
"resource": ""
} |
q18547 | NFA.constructDFA | train | public DFA<T> constructDFA(Scope<DFAState<T>> scope)
{
return new DFA<>(first.constructDFA(scope), scope.count());
} | java | {
"resource": ""
} |
q18548 | NFA.concat | train | public void concat(NFA<T> nfa)
{
last.addEpsilon(nfa.getFirst());
last = nfa.last;
} | java | {
"resource": ""
} |
q18549 | Application.getApplicationFromSource | train | public static Application getApplicationFromSource(final File _versionFile,
final List<String> _classpathElements,
final File _eFapsDir,
final File _outputDir,
final List<String> _includes,
final List<String> _excludes,
final Map<String, String> _file2typeMapping)
throws InstallationException
{
final Map<String, String> file2typeMapping = _file2typeMapping == null
? Application.DEFAULT_TYPE_MAPPING
: _file2typeMapping;
final Application appl;
try {
appl = Application.getApplication(_versionFile.toURI().toURL(),
_eFapsDir.toURI().toURL(),
_classpathElements);
for (final String fileName : Application.getFiles(_eFapsDir, _includes, _excludes)) {
final String type = file2typeMapping.get(fileName.substring(fileName.lastIndexOf(".") + 1));
appl.install.addFile(new InstallFile().setType(type).setURL(
new File(_eFapsDir, fileName).toURI().toURL()));
}
if (_outputDir.exists()) {
for (final String fileName : Application.getFiles(_outputDir, _includes, _excludes)) {
final String type = file2typeMapping.get(fileName.substring(fileName.lastIndexOf(".") + 1));
appl.install.addFile(new InstallFile().setType(type).setURL(
new File(_outputDir, fileName).toURI().toURL()));
}
}
} catch (final IOException e) {
throw new InstallationException("Could not open / read version file " + "'" + _versionFile + "'", e);
// CHECKSTYLE:OFF
} catch (final Exception e) {
// CHECKSTYLE:ON
throw new InstallationException("Read version file '" + _versionFile + "' failed", e);
}
return appl;
} | java | {
"resource": ""
} |
q18550 | Application.getApplicationFromClassPath | train | public static Application getApplicationFromClassPath(final String _application,
final List<String> _classpath)
throws InstallationException
{
return Application.getApplicationsFromClassPath(_application, _classpath).get(_application);
} | java | {
"resource": ""
} |
q18551 | Application.getApplicationsFromClassPath | train | public static Map<String, Application> getApplicationsFromClassPath(final String _application,
final List<String> _classpath)
throws InstallationException
{
final Map<String, Application> appls = new HashMap<>();
try {
final ClassLoader parent = Application.class.getClassLoader();
final List<URL> urls = new ArrayList<>();
for (final String pathElement : _classpath) {
urls.add(new File(pathElement).toURI().toURL());
}
final URLClassLoader cl = URLClassLoader.newInstance(urls.toArray(new URL[urls.size()]), parent);
// get install application (read from all install xml files)
final Enumeration<URL> urlEnum = cl.getResources("META-INF/efaps/install.xml");
while (urlEnum.hasMoreElements()) {
// TODO: why class path?
final URL url = urlEnum.nextElement();
final Application appl = Application.getApplication(url, new URL(url, "../../../"), _classpath);
appls.put(appl.getApplication(), appl);
}
} catch (final IOException e) {
throw new InstallationException("Could not access the install.xml file "
+ "(in path META-INF/efaps/ path of each eFaps install jar).", e);
}
return appls;
} | java | {
"resource": ""
} |
q18552 | Application.updateLastVersion | train | public void updateLastVersion(final String _userName,
final String _password,
final Set<Profile> _profiles)
throws Exception
{
// reload cache (if possible)
reloadCache();
// load installed versions
Context.begin();
EFapsClassLoader.getOfflineInstance(getClass().getClassLoader());
final Map<String, Integer> latestVersions = this.install.getLatestVersions();
Context.rollback();
final long latestVersion = latestVersions.get(this.application);
final ApplicationVersion version = getLastVersion();
if (version.getNumber() == latestVersion) {
Application.LOG.info("Update version '{}' of application '{}' ", version.getNumber(), this.application);
version.install(this.install, version.getNumber(), _profiles, _userName, _password);
Application.LOG.info("Finished update of version '{}'", version.getNumber());
} else {
Application.LOG.error("Version {}' of application '{}' not installed and could not updated!",
version.getNumber(), this.application);
}
} | java | {
"resource": ""
} |
q18553 | Application.reloadCache | train | protected void reloadCache()
throws InstallationException
{
try {
LOG.info("Reloading Cache");
Context.begin();
if (RunLevel.isInitialisable()) {
RunLevel.init("shell");
RunLevel.execute();
}
Context.commit();
} catch (final EFapsException e) {
throw new InstallationException("Reload cache failed", e);
}
} | java | {
"resource": ""
} |
q18554 | CharInput.getString | train | @Override
public String getString(long start, int length)
{
if (length == 0)
{
return "";
}
if (array != null)
{
int ps = (int) (start % size);
int es = (int) ((start+length) % size);
if (ps < es)
{
return new String(array, ps, length);
}
else
{
StringBuilder sb = new StringBuilder();
sb.append(array, ps, size-ps);
sb.append(array, 0, es);
return sb.toString();
}
}
else
{
StringBuilder sb = new StringBuilder();
for (int ii=0;ii<length;ii++)
{
sb.append((char)get(start+ii));
}
return sb.toString();
}
} | java | {
"resource": ""
} |
q18555 | GravityNameValue.groupNameToSet | train | static Map<String, Set<String>> groupNameToSet(GravityNameValue[] nameValues) {
Map<String, Set<String>> result = new HashMap<>();
for (GravityNameValue nameValue : nameValues) {
if (nameValue.name == null || nameValue.value == null) continue;
if (!result.containsKey(nameValue.name)) result.put(nameValue.name, new LinkedHashSet<String>());
Collections.addAll(result.get(nameValue.name), nameValue.value);
}
return result;
} | java | {
"resource": ""
} |
q18556 | AbstractStoreResource.setFileInfo | train | protected void setFileInfo(final String _filename,
final long _fileLength)
throws EFapsException
{
if (!_filename.equals(this.fileName) || _fileLength != this.fileLength) {
ConnectionResource res = null;
try {
res = Context.getThreadContext().getConnectionResource();
final AbstractDatabase<?> db = Context.getDbType();
final StringBuilder cmd = new StringBuilder().append(db.getSQLPart(SQLPart.UPDATE)).append(" ")
.append(db.getTableQuote()).append(AbstractStoreResource.TABLENAME_STORE)
.append(db.getTableQuote())
.append(" ").append(db.getSQLPart(SQLPart.SET)).append(" ")
.append(db.getColumnQuote())
.append(AbstractStoreResource.COLNAME_FILENAME)
.append(db.getColumnQuote()).append(db.getSQLPart(SQLPart.EQUAL)).append("? ")
.append(db.getSQLPart(SQLPart.COMMA))
.append(db.getColumnQuote())
.append(AbstractStoreResource.COLNAME_FILELENGTH)
.append(db.getColumnQuote()).append(db.getSQLPart(SQLPart.EQUAL)).append("? ")
.append(db.getSQLPart(SQLPart.WHERE)).append(" ")
.append(db.getColumnQuote()).append("ID").append(db.getColumnQuote())
.append(db.getSQLPart(SQLPart.EQUAL)).append(getGeneralID());
final PreparedStatement stmt = res.prepareStatement(cmd.toString());
try {
stmt.setString(1, _filename);
stmt.setLong(2, _fileLength);
stmt.execute();
} finally {
stmt.close();
}
} catch (final EFapsException e) {
throw e;
} catch (final SQLException e) {
throw new EFapsException(JDBCStoreResource.class, "write.SQLException", e);
}
}
} | java | {
"resource": ""
} |
q18557 | AbstractStoreResource.getGeneralID | train | private void getGeneralID(final String _complStmt)
throws EFapsException
{
ConnectionResource con = null;
try {
con = Context.getThreadContext().getConnectionResource();
final Statement stmt = con.createStatement();
final ResultSet rs = stmt.executeQuery(_complStmt.toString());
while (rs.next()) {
this.generalID = rs.getLong(1);
this.fileName = rs.getString(2);
if (this.fileName != null && !this.fileName.isEmpty()) {
this.fileName = this.fileName.trim();
}
this.fileLength = rs.getLong(3);
for (int i = 0; i < this.exist.length; i++) {
this.exist[i] = rs.getLong(4 + i) > 0;
}
getAdditionalInfo(rs);
}
rs.close();
stmt.close();
} catch (final SQLException e) {
throw new EFapsException(InstanceQuery.class, "executeOneCompleteStmt", e);
}
} | java | {
"resource": ""
} |
q18558 | AbstractStoreResource.getCompress | train | protected Compress getCompress()
{
final Compress compress;
if (this.store.getResourceProperties().containsKey(Store.PROPERTY_COMPRESS)) {
compress = Compress.valueOf(this.store.getResourceProperties().get(Store.PROPERTY_COMPRESS).toUpperCase());
} else {
compress = Compress.NONE;
}
return compress;
} | java | {
"resource": ""
} |
q18559 | Queue.registerUpdate | train | public static void registerUpdate(final Instance _instance)
throws EFapsException
{
// check if SystemConfiguration exists, necessary during install
if (EFapsSystemConfiguration.get() != null
&& EFapsSystemConfiguration.get().getAttributeValueAsBoolean(KernelSettings.INDEXACTIVATE)) {
if (_instance != null && _instance.getType() != null
&& IndexDefinition.get(_instance.getType().getUUID()) != null) {
final AdvancedCache<String, String> cache = InfinispanCache.get()
.<String, String>getIgnReCache(CACHENAME);
cache.put(RandomUtil.random(12), _instance.getOid());
}
}
} | java | {
"resource": ""
} |
q18560 | AbstractDataModelObject.initialize | train | public static void initialize()
throws CacheReloadException
{
Context.getDbType().initialize(AbstractDataModelObject.class);
AttributeType.initialize(AbstractDataModelObject.class);
SQLTable.initialize(AbstractDataModelObject.class);
Type.initialize(AbstractDataModelObject.class);
Dimension.initialize(AbstractDataModelObject.class);
Attribute.initialize(AbstractDataModelObject.class);
Status.initialize(AbstractDataModelObject.class);
} | java | {
"resource": ""
} |
q18561 | StringUtil.nullifyBadInput | train | public static String nullifyBadInput(String input)
{
if (input != null)
{
if (input.matches(emptyRegex))
{
return null;
}
return input.trim();
}
return null;
} | java | {
"resource": ""
} |
q18562 | StringUtil.nullifyBadInput | train | public static String[] nullifyBadInput(String[] input)
{
if (input != null)
{
if (input.length > 0)
{
return input;
}
}
return null;
} | java | {
"resource": ""
} |
q18563 | StringUtil.removeDuplicates | train | public static String[] removeDuplicates(String[] input)
{
if (input != null)
{
if (input.length > 0)
{
Set<String> inputSet = new HashSet<String>(Arrays.asList(input));
if (inputSet.size() > 0)
{
return inputSet.toArray(new String[inputSet.size()]);
}
}
}
return null;
} | java | {
"resource": ""
} |
q18564 | UserAttributesSet.getString | train | public String getString(final String _key)
{
String ret = null;
if (this.attributes.containsKey(_key)) {
ret = this.attributes.get(_key).getValue();
}
return ret;
} | java | {
"resource": ""
} |
q18565 | UserAttributesSet.set | train | public void set(final String _key,
final String _value,
final UserAttributesDefinition _definition)
throws EFapsException
{
if (_key == null || _value == null) {
throw new EFapsException(this.getClass(), "set", _key, _value, _definition);
} else {
final UserAttribute userattribute = this.attributes.get(_key);
if (userattribute == null) {
this.attributes.put(_key, new UserAttribute(_definition.name, _value.trim(), true));
} else if (!userattribute.getValue().equals(_value.trim())) {
userattribute.setUpdate(true);
userattribute.setValue(_value.trim());
}
}
} | java | {
"resource": ""
} |
q18566 | FormatValueSelect.get | train | @Override
public Object get(final Attribute _attribute,
final Object _object)
throws EFapsException
{
Object ret = null;
if (_object != null && _attribute.getAttributeType().getDbAttrType() instanceof IFormattableType) {
final IFormattableType attrType = (IFormattableType) _attribute.getAttributeType().getDbAttrType();
if (_object instanceof List<?>) {
final List<?> objectList = (List<?>) _object;
final List<Object> temp = new ArrayList<>();
for (final Object object : objectList) {
temp.add(attrType.format(object, this.pattern));
}
ret = temp;
} else {
ret = attrType.format(_object, this.pattern);
}
}
return ret;
} | java | {
"resource": ""
} |
q18567 | CachedMultiPrintQuery.get4Request | train | public static CachedMultiPrintQuery get4Request(final List<Instance> _instances)
throws EFapsException
{
return new CachedMultiPrintQuery(_instances, Context.getThreadContext().getRequestId()).setLifespan(5)
.setLifespanUnit(TimeUnit.MINUTES);
} | java | {
"resource": ""
} |
q18568 | Insert.set | train | public Insert set(final CIAttribute _attr, final Object _value)
throws EFapsException
{
return super.set(_attr.name, Converter.convert(_value));
} | java | {
"resource": ""
} |
q18569 | Point.set | train | public void set(double x, double y, double z) {
this.MODE = POINTS_3D;
this.x = x;
this.y = y;
this.z = z;
} | java | {
"resource": ""
} |
q18570 | SQLTable.addType | train | protected void addType(final Long _typeId)
{
if (!this.types.contains(_typeId)) {
this.types.add(_typeId);
setDirty();
}
} | java | {
"resource": ""
} |
q18571 | Store.loadResourceProperties | train | private void loadResourceProperties(final long _id)
throws EFapsException
{
this.resourceProperties.clear();
final QueryBuilder queryBldr = new QueryBuilder(CIAdminCommon.Property);
queryBldr.addWhereAttrEqValue(CIAdminCommon.Property.Abstract, _id);
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CIAdminCommon.Property.Name, CIAdminCommon.Property.Value);
multi.executeWithoutAccessCheck();
while (multi.next()) {
this.resourceProperties.put(multi.<String>getAttribute(CIAdminCommon.Property.Name),
multi.<String>getAttribute(CIAdminCommon.Property.Value));
}
} | java | {
"resource": ""
} |
q18572 | Store.getResource | train | public Resource getResource(final Instance _instance)
throws EFapsException
{
Resource ret = null;
try {
Store.LOG.debug("Getting resource for: {} with properties: {}", this.resource, this.resourceProperties);
ret = (Resource) Class.forName(this.resource).newInstance();
ret.initialize(_instance, this);
} catch (final InstantiationException e) {
throw new EFapsException(Store.class, "getResource.InstantiationException", e, this.resource);
} catch (final IllegalAccessException e) {
throw new EFapsException(Store.class, "getResource.IllegalAccessException", e, this.resource);
} catch (final ClassNotFoundException e) {
throw new EFapsException(Store.class, "getResource.ClassNotFoundException", e, this.resource);
}
return ret;
} | java | {
"resource": ""
} |
q18573 | Image.copyImage | train | public BufferedImage copyImage(BufferedImage image) {
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
Graphics2D g2d = newImage.createGraphics();
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
return newImage;
} | java | {
"resource": ""
} |
q18574 | Image.loadTexture | train | public final void loadTexture() {
texture = null;
texture = AWTTextureIO.newTexture(GLProfile.get(GLProfile.GL2), img, true);
if (texture == null) {
throw new CasmiRuntimeException("Cannot load texture");
}
} | java | {
"resource": ""
} |
q18575 | Image.getColor | train | public final Color getColor(int x, int y) {
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
int idx = x + y * width;
return new RGBColor((pixels[idx] >> 16 & 0x000000ff) / 255.0,
(pixels[idx] >> 8 & 0x000000ff) / 255.0,
(pixels[idx] & 0x000000ff) / 255.0,
(pixels[idx] >> 24) / 255.0);
} | java | {
"resource": ""
} |
q18576 | Image.getRed | train | public final double getRed(int x, int y) {
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
int idx = x + y * width;
return (pixels[idx] >> 16 & 0x000000ff);
} | java | {
"resource": ""
} |
q18577 | Image.setColor | train | public final void setColor(Color color, int x, int y) {
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
int red = (int)(color.getRed() * 255.0);
int green = (int)(color.getGreen() * 255.0);
int blue = (int)(color.getBlue() * 255.0);
int alpha = (int)(color.getAlpha() * 255.0);
pixels[x + y * width] = alpha << 24 |
red << 16 |
green << 8 |
blue;
} | java | {
"resource": ""
} |
q18578 | Image.setA | train | public final void setA(double alpha, int x, int y){
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
int idx = x + y * width;
int tmpR = pixels[idx] >> 16 & 0x000000ff;
int tmpG = pixels[idx] >> 8 & 0x000000ff;
int tmpB = pixels[idx] & 0x000000ff;
pixels[idx] = (int)alpha << 24 |
tmpR << 16 |
tmpG << 8 |
tmpB;
} | java | {
"resource": ""
} |
q18579 | Image.setColors | train | public final void setColors(Color[] colors) {
int[] pixels = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
int idx = x + y * width;
if (colors.length <= idx) break;
int red = (int)(colors[idx].getRed() * 255.0);
int green = (int)(colors[idx].getGreen() * 255.0);
int blue = (int)(colors[idx].getBlue() * 255.0);
int alpha = (int)(colors[idx].getAlpha() * 255.0);
pixels[idx] = alpha << 24 |
red << 16 |
green << 8 |
blue;
}
}
} | java | {
"resource": ""
} |
q18580 | JSONCI.getCI | train | public static AbstractCI<?> getCI(final ICIPrintStmt _stmt)
throws CacheReloadException
{
AbstractCI<?> ret = null;
switch (_stmt.getCINature()) {
case TYPE:
final Type type;
if (UUIDUtil.isUUID(_stmt.getCI())) {
type = Type.get(UUID.fromString(_stmt.getCI()));
} else {
type = Type.get(_stmt.getCI());
}
if (type != null) {
final org.efaps.json.ci.Type jsonType = new org.efaps.json.ci.Type()
.setName(type.getName())
.setUUID(type.getUUID())
.setId(type.getId());
for (final Attribute attr : type.getAttributes().values()) {
final AttributeType attrType = new AttributeType()
.setName(attr.getAttributeType().getName());
switch (DMAttributeType.fromValue(attr.getAttributeType().getName())) {
case LINK:
case LINK_WITH_RANGES:
case STATUS:
if (attr.hasLink()) {
attrType.setInfo(attr.getLink().getName() + ", " + attr.getLink().getUUID());
}
break;
default:
break;
}
jsonType.addAttribute(new org.efaps.json.ci.Attribute()
.setName(attr.getName())
.setType(attrType));
}
ret = jsonType;
}
break;
default:
break;
}
return ret;
} | java | {
"resource": ""
} |
q18581 | TableInformation.addUniqueKeyColumn | train | public void addUniqueKeyColumn(final String _ukName,
final int _colIndex,
final String _colName)
{
final String ukName = _ukName.toUpperCase();
final UniqueKeyInformation uki;
if (!this.ukMap.containsKey(ukName)) {
uki = new UniqueKeyInformation(_ukName);
this.ukMap.put(ukName, uki);
} else {
uki = this.ukMap.get(ukName);
}
uki.appendColumnName(_colIndex, _colName);
// this.ukColMap.put(uki.getColumnNames(), uki);
} | java | {
"resource": ""
} |
q18582 | TableInformation.addForeignKey | train | public void addForeignKey(final String _fkName,
final String _colName,
final String _refTableName,
final String _refColName,
final boolean _cascade)
{
this.fkMap.put(_fkName.toUpperCase(),
new ForeignKeyInformation(_fkName, _colName, _refTableName, _refColName, _cascade));
} | java | {
"resource": ""
} |
q18583 | RegistryListenerBindingHandler.addListenerToRegistry | train | @SuppressWarnings("unchecked")
private List<ListenerRegistration> addListenerToRegistry() {
List<ListenerRegistration> registrationsBuilder = newArrayList();
for (Pair<IdMatcher, Watcher> guiceWatcherRegistration : getRegisteredWatchers()) {
Watcher watcher = guiceWatcherRegistration.right();
IdMatcher idMatcher = guiceWatcherRegistration.left();
Registration registration = registry.addWatcher(idMatcher, watcher);
ListenerRegistration listenerRegistration = new ListenerRegistration(registration, idMatcher, watcher);
registrationsBuilder.add(listenerRegistration);
}
return registrationsBuilder;
} | java | {
"resource": ""
} |
q18584 | PasswordStore.initConfig | train | private void initConfig()
{
SystemConfiguration config = null;
try {
config = EFapsSystemConfiguration.get();
if (config != null) {
final Properties confProps = config.getAttributeValueAsProperties(KernelSettings.PWDSTORE);
this.digesterConfig.setAlgorithm(confProps.getProperty(PasswordStore.ALGORITHM,
this.digesterConfig.getAlgorithm()));
this.digesterConfig.setIterations(confProps.getProperty(PasswordStore.ITERATIONS,
this.digesterConfig.getIterations().toString()));
this.digesterConfig.setSaltSizeBytes(confProps.getProperty(PasswordStore.SALTSIZE,
this.digesterConfig.getSaltSizeBytes().toString()));
this.threshold = config.getAttributeValueAsInteger(KernelSettings.PWDTH);
}
} catch (final EFapsException e) {
PasswordStore.LOG.error("Error on reading SystemConfiguration for PasswordStore", e);
}
} | java | {
"resource": ""
} |
q18585 | PasswordStore.read | train | public void read(final String _readValue)
throws EFapsException
{
if (_readValue != null) {
try {
this.props.load(new StringReader(_readValue));
} catch (final IOException e) {
throw new EFapsException(PasswordStore.class.getName(), e);
}
}
} | java | {
"resource": ""
} |
q18586 | PasswordStore.check | train | private boolean check(final String _plainPassword,
final int _pos)
{
boolean ret = false;
if (this.props.containsKey(PasswordStore.DIGEST + _pos)) {
final ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
this.digesterConfig.setAlgorithm(this.props.getProperty(PasswordStore.ALGORITHM + _pos));
this.digesterConfig.setIterations(this.props.getProperty(PasswordStore.ITERATIONS + _pos));
this.digesterConfig.setSaltSizeBytes(this.props.getProperty(PasswordStore.SALTSIZE + _pos));
passwordEncryptor.setConfig(this.digesterConfig);
ret = passwordEncryptor.checkPassword(_plainPassword, this.props.getProperty(PasswordStore.DIGEST + _pos));
}
return ret;
} | java | {
"resource": ""
} |
q18587 | PasswordStore.isRepeated | train | public boolean isRepeated(final String _plainPassword)
{
boolean ret = false;
for (int i = 1; i < this.threshold + 1; i++) {
ret = check(_plainPassword, i);
if (ret) {
break;
}
}
return ret;
} | java | {
"resource": ""
} |
q18588 | PasswordStore.setNew | train | public void setNew(final String _plainPassword,
final String _currentValue)
throws EFapsException
{
initConfig();
read(_currentValue);
final ConfigurablePasswordEncryptor passwordEncryptor = new ConfigurablePasswordEncryptor();
passwordEncryptor.setConfig(this.digesterConfig);
final String encrypted = passwordEncryptor.encryptPassword(_plainPassword);
shiftAll();
this.props.setProperty(PasswordStore.DIGEST + 0, encrypted);
this.props.setProperty(PasswordStore.ALGORITHM + 0, this.digesterConfig.getAlgorithm());
this.props.setProperty(PasswordStore.ITERATIONS + 0, this.digesterConfig.getIterations().toString());
this.props.setProperty(PasswordStore.SALTSIZE + 0, this.digesterConfig.getSaltSizeBytes().toString());
} | java | {
"resource": ""
} |
q18589 | PasswordStore.shiftAll | train | private void shiftAll()
{
shift(PasswordStore.DIGEST);
shift(PasswordStore.ALGORITHM);
shift(PasswordStore.ITERATIONS);
shift(PasswordStore.SALTSIZE);
} | java | {
"resource": ""
} |
q18590 | PasswordStore.shift | train | private void shift(final String _key)
{
for (int i = this.threshold; i > 0; i--) {
this.props.setProperty(_key + i, this.props.getProperty(_key + (i - 1), "").trim());
}
int i = this.threshold + 1;
while (this.props.contains(_key + i)) {
this.props.remove(_key + i);
i++;
}
} | java | {
"resource": ""
} |
q18591 | TedDriverImpl.createBatch | train | public Long createBatch(String batchTaskName, String data, String key1, String key2, List<TedTask> tedTasks) {
if (tedTasks == null || tedTasks.isEmpty())
return null;
if (batchTaskName == null) {
throw new IllegalStateException("batchTaskName is required!");
}
TaskConfig batchTC = context.registry.getTaskConfig(batchTaskName);
if (batchTC == null)
throw new IllegalArgumentException("Batch task '" + batchTaskName + "' is not known for TED");
Long batchId = context.tedDao.createTaskPostponed(batchTC.taskName, Model.CHANNEL_BATCH, data, key1, key2, 30 * 60);
createTasksBulk(tedTasks, batchId);
context.tedDao.setStatusPostponed(batchId, TedStatus.NEW, Model.BATCH_MSG, new Date());
return batchId;
} | java | {
"resource": ""
} |
q18592 | DFA.maxDepth | train | public int maxDepth()
{
Map<DFAState<T>,Integer> indexOf = new NumMap<>();
Map<DFAState<T>,Long> depth = new NumMap<>();
Deque<DFAState<T>> stack = new ArrayDeque<>();
maxDepth(root, indexOf, stack, depth);
long d = depth.get(root);
assert d >= 0;
if (d >= Integer.MAX_VALUE)
{
return Integer.MAX_VALUE;
}
else
{
return (int) d;
}
} | java | {
"resource": ""
} |
q18593 | DFA.calculateMaxFindSkip | train | public void calculateMaxFindSkip()
{
Map<DFAState<T>,Integer> indexOf = new NumMap<>();
Map<DFAState<T>,Integer> skip = new NumMap<>();
Deque<DFAState<T>> stack = new ArrayDeque<>();
findSkip(root, indexOf, stack, new LinkedList());
root.setAcceptStartLength(1);
} | java | {
"resource": ""
} |
q18594 | Server.register | train | public void register() {
logger.debug("[register] uri = {}", getManagementUri());
JsonNode jsonNode;
ObjectMapper objectMapper = jsonObjectMapper.getObjectMapperBinary();
ObjectNode objectNode = objectMapper.createObjectNode();
objectNode.put(CommandParameters.METHOD, "register");
try {
jsonNode = objectMapper.readTree(managementConnection.sendWithResult(objectMapper.writeValueAsBytes(objectNode)));
}
catch (Exception e) {
logger.error("[register] could not register at server");
return;
}
id = jsonNode.get("id").asText();
setMaster(jsonNode.get("isMaster").asBoolean());
managementConnection.setServerId(id);
logger.debug("[register] id = {}, isMaster = {}, uri = {}", getId(), isMaster(), getManagementUri());
} | java | {
"resource": ""
} |
q18595 | Server.getConnection | train | public DataConnection getConnection() {
DataConnection connection;
for (connection = availableConnections.poll();
connection != null && !connection.isUsable();
connection = availableConnections.poll())
{
if (!connection.isUsable()) {
connection.close();
}
}
if (connection == null) {
connection = new DataConnection(getDataUri());
try {
connection.connect();
}
catch (Exception e) {
logger.error("[getConnection] could not connect to database", e);
return null;
}
}
connection.setLocale(threadLocale.getLocale());
return connection;
} | java | {
"resource": ""
} |
q18596 | Server.returnConnection | train | public void returnConnection(DataConnection connection) {
if (connection.isUsable()) {
connection.setLastUsage(new Date());
availableConnections.add(connection);
}
else {
connection.close();
}
usedConnections.remove(connection);
} | java | {
"resource": ""
} |
q18597 | ManagementConnection.connect | train | public void connect() throws Exception {
logger.debug("[connect] initializing new connection");
if (timer != null) {
timer.cancel();
}
if (isConnected()) {
return;
}
synchronized (webSocketHandler.getNotifyConnectionObject()) {
webSocketConnectionManager.start();
try {
webSocketHandler.getNotifyConnectionObject().wait(TimeUnit.SECONDS.toMillis(WEBSOCKET_TIMEOUT));
}
catch (InterruptedException e) {
onConnectionClosed();
logger.debug("[connect] not open");
throw new Exception("websocket connection not open");
}
if (!isConnected()) {
onConnectionClosed();
logger.debug("[connect] timeout");
throw new Exception("websocket connection timeout");
}
}
} | java | {
"resource": ""
} |
q18598 | ManagementConnection.onConnectionClosed | train | public void onConnectionClosed() {
logger.debug("[onConnectionClosed] '{}', isConnected = {}", uri, isConnected());
webSocketConnectionManager.stop();
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
logger.debug("[onConnectionClosed:run]");
synchronized (webSocketHandler.getNotifyConnectionObject()) {
webSocketConnectionManager.start();
try {
webSocketHandler.getNotifyConnectionObject().wait(TimeUnit.SECONDS.toMillis(WEBSOCKET_RECONNECT_TIMEOUT));
} catch (InterruptedException e) {
logger.debug("[onConnectionClose]", e);
}
if (isConnected()) {
logger.debug("[onConnectionClosed:run] connected");
clusterListener.onServerReconnected(getServerId(), uri);
this.cancel();
} else {
logger.debug("[onConnectionClosed:run] NOT connected");
webSocketConnectionManager.stop();
}
}
}
}, TimeUnit.SECONDS.toMillis(WEBSOCKET_TIMEOUT), TimeUnit.SECONDS.toMillis(WEBSOCKET_RECONNECT_TIMEOUT));
} | java | {
"resource": ""
} |
q18599 | ManagementConnection.sendWithResult | train | public byte[] sendWithResult(final byte[] message) {
synchronized (webSocketHandler.getNotifyResultObject()) {
webSocketHandler.sendMessage(message);
try {
webSocketHandler.getNotifyResultObject().wait(TimeUnit.SECONDS.toMillis(ANSWER_TIMEOUT));
}
catch (InterruptedException e) {
return null;
}
return webSocketHandler.getResultBytes();
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.