Unnamed: 0
int64 0
403
| cwe_id
stringclasses 1
value | source
stringlengths 56
2.02k
| target
stringlengths 50
1.97k
|
---|---|---|---|
0 | public boolean update(Context context, KvPairs pairs, AnyKey anyKey){
LOGGER.trace("update: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ") + anyKey.getAny().toString());
String table = anyKey.getKey().getTable();
if (table == null) {
if (!kvSave(context, pairs, anyKey)) {
LOGGER.debug("update kvSave failed: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
return false;
} else {
LOGGER.debug("updated kvSave Ok: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
}
} else {
Query query = new Query(context, jdbcTemplate, pairs, anyKey);
if (!query.prepareUpdate() || !query.executeUpdate()) {
if (enableDbFallback) {
if (!kvSave(context, pairs, anyKey)) {
LOGGER.debug("update fallback to kvSave failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
return false;
} else {
String msg = "updated fallbacked to kvSave OK: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ");
context.logTraceMessage(msg);
LOGGER.warn(msg);
}
} else {
LOGGER.debug("update failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
return false;
}
} else {
LOGGER.debug("updated Ok: " + anyKey.size() + " record(s) from " + table);
}
}
AppCtx.getKeyInfoRepo().save(context, pairs, anyKey);
return true;
} | public boolean update(Context context, KvPairs pairs, AnyKey anyKey){
LOGGER.trace("update: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ") + anyKey.getAny().toString());
String table = anyKey.getKey().getTable();
if (table == null) {
if (!kvSave(context, pairs, anyKey)) {
LOGGER.debug("update kvSave failed: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
return false;
} else {
LOGGER.debug("updated kvSave Ok: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
}
} else {
Query query = new Query(context, jdbcTemplate, pairs, anyKey);
if (!query.ifUpdateOk() || !query.executeUpdate()) {
if (enableDbFallback) {
if (!kvSave(context, pairs, anyKey)) {
LOGGER.debug("update fallback to kvSave failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
return false;
} else {
String msg = "updated fallbacked to kvSave OK: " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " ");
context.logTraceMessage(msg);
LOGGER.warn(msg);
}
} else {
LOGGER.debug("update failed - " + pairs.getPair().getId() + (pairs.size() > 1 ? " ... " : " "));
return false;
}
} else {
LOGGER.debug("updated Ok: " + anyKey.size() + " record(s) from " + table);
}
}
return true;
} |
|
1 | private static String internalDecode(ProtonBuffer buffer, final int length, CharsetDecoder decoder){
final char[] chars = new char[length];
final int bufferInitialPosition = buffer.getReadIndex();
int offset;
for (offset = 0; offset < length; offset++) {
final byte b = buffer.getByte(bufferInitialPosition + offset);
if (b < 0) {
break;
}
chars[offset] = (char) b;
}
buffer.setReadIndex(bufferInitialPosition + offset);
if (offset == length) {
return new String(chars, 0, length);
} else {
return internalDecodeUTF8(buffer, length, chars, offset, decoder);
}
} | private static String internalDecode(ProtonBuffer buffer, final int length, CharsetDecoder decoder, char[] scratch){
final int bufferInitialPosition = buffer.getReadIndex();
int offset;
for (offset = 0; offset < length; offset++) {
final byte b = buffer.getByte(bufferInitialPosition + offset);
if (b < 0) {
break;
}
scratch[offset] = (char) b;
}
buffer.setReadIndex(bufferInitialPosition + offset);
if (offset == length) {
return new String(scratch, 0, length);
} else {
return internalDecodeUTF8(buffer, length, scratch, offset, decoder);
}
} |
|
2 | public PartyDTO getPartyByPartyCode(String partyCode){
if (Strings.isNullOrEmpty(partyCode))
throw new InvalidDataException("Party Code is required");
final TMsParty tMsParty = partyRepository.findByPrtyCodeAndPrtyStatus(partyCode, Constants.STATUS_ACTIVE.getShortValue());
if (tMsParty == null)
throw new DataNotFoundException("Party not found for the Code : " + partyCode);
PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty);
final List<PartyContactDTO> contactDTOList = partyContactService.getContactsByPartyCode(partyDTO.getPartyCode(), true);
partyDTO.setContactList(contactDTOList);
return partyDTO;
} | public PartyDTO getPartyByPartyCode(String partyCode){
final TMsParty tMsParty = validateByPartyCode(partyCode);
PartyDTO partyDTO = PartyMapper.INSTANCE.entityToDTO(tMsParty);
setReferenceData(tMsParty, partyDTO);
final List<PartyContactDTO> contactDTOList = partyContactService.getContactsByPartyCode(partyDTO.getPartyCode(), true);
partyDTO.setContactList(contactDTOList);
return partyDTO;
} |
|
3 | public static long findMyBoardingPass(String fileName){
List<String> passes = readInBoardingPasses(fileName);
List<Long> seatIds = passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.toList());
long mySeatId = -1;
for (Long seatId : seatIds) {
if (mySeatId == -1) {
mySeatId = seatId;
continue;
}
if (seatId > mySeatId + 1) {
mySeatId++;
break;
}
mySeatId = seatId;
}
return mySeatId;
} | public static long findMyBoardingPass(String fileName){
List<String> passes = readInBoardingPasses(fileName);
return passes.stream().map(boardingPass -> getBoardingPassSeatId(boardingPass)).sorted().collect(Collectors.reducing(-1, (mySeatId, seatId) -> (mySeatId.longValue() == -1L || seatId.longValue() <= mySeatId.longValue() + 1) ? seatId : mySeatId)).longValue() + 1L;
} |
|
4 | public Set<Car> findAllByOwnerId(long id) throws SQLException, NamingException{
Context ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:comp/env");
DataSource dataSource = (DataSource) envContext.lookup("jdbc/TestDB");
Connection con = null;
try {
con = dataSource.getConnection();
PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement("SELECT * FROM cars WHERE owner_id = ?");
findAllCarsByOwnerIdStatement.setLong(1, id);
ResultSet cars = findAllCarsByOwnerIdStatement.executeQuery();
Set<Car> carSet = new HashSet();
while (cars.next()) {
Car car = CarUtils.initializeCar(cars);
carSet.add(car);
}
findAllCarsByOwnerIdStatement.close();
cars.close();
return carSet;
} finally {
if (con != null)
try {
con.close();
} catch (Exception ignore) {
}
}
} | public Set<Car> findAllByOwnerId(long id) throws SQLException, NamingException{
Connection con = null;
try {
con = dataSource.getConnection();
PreparedStatement findAllCarsByOwnerIdStatement = con.prepareStatement("SELECT * FROM cars WHERE owner_id = ?");
findAllCarsByOwnerIdStatement.setLong(1, id);
ResultSet cars = findAllCarsByOwnerIdStatement.executeQuery();
Set<Car> carSet = new HashSet();
while (cars.next()) {
Car car = CarUtils.initializeCar(cars);
carSet.add(car);
}
findAllCarsByOwnerIdStatement.close();
cars.close();
return carSet;
} finally {
if (con != null)
try {
con.close();
} catch (Exception ignore) {
}
}
} |
|
5 | public String getEncryptedData(String alias){
if (alias == null || "".equals(alias)) {
return alias;
}
if (!initialize || encryptedData.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("There is no secret found for alias '" + alias + "' returning itself");
}
return alias;
}
StringBuffer sb = new StringBuffer();
sb.append(alias);
String encryptedValue = encryptedData.get(sb.toString());
if (encryptedValue == null || "".equals(encryptedValue)) {
if (log.isDebugEnabled()) {
log.debug("There is no secret found for alias '" + alias + "' returning itself");
}
return alias;
}
return encryptedValue;
} | public String getEncryptedData(String alias){
if (alias == null || "".equals(alias)) {
return alias;
}
if (!initialize || encryptedData.isEmpty()) {
if (log.isDebugEnabled()) {
log.debug("There is no secret found for alias '" + alias + "' returning itself");
}
return alias;
}
String encryptedValue = encryptedData.get(alias);
if (encryptedValue == null || "".equals(encryptedValue)) {
if (log.isDebugEnabled()) {
log.debug("There is no secret found for alias '" + alias + "' returning itself");
}
return alias;
}
return encryptedValue;
} |
|
6 | public List<Diff> apply(Object beforeObject, Object afterObject, String description){
List<Diff> diffs = new LinkedList<>();
Collection before = (Collection) beforeObject;
Collection after = (Collection) afterObject;
if (!isNullOrEmpty(before) && isNullOrEmpty(after)) {
for (Object object : before) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description));
}
} else if (isNullOrEmpty(before) && !isNullOrEmpty(after)) {
for (Object object : after) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(null, object, description));
}
} else {
for (Object object : before) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, findCorrespondingObject(object, after), description));
} else {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, getCorrespondingObject(object, after), description));
}
}
List<Diff> temp;
for (Object object : after) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
temp = getDiffComputeEngine().evaluateAndExecute(findCorrespondingObject(object, before), object, description);
} else {
temp = getDiffComputeEngine().evaluateAndExecute(getCorrespondingObject(object, before), object, description);
}
if (temp != null && temp.size() > 0) {
temp.removeIf(delta -> delta.getChangeType().equals(ChangeType.NO_CHANGE) || delta.getChangeType().equals(ChangeType.UPDATED));
diffs.addAll(temp);
}
}
}
return diffs;
} | public List<Diff> apply(Object beforeObject, Object afterObject, String description){
List<Diff> diffs = new LinkedList<>();
Collection before = (Collection) beforeObject;
Collection after = (Collection) afterObject;
if (!isNullOrEmpty(before) && isNullOrEmpty(after)) {
before.forEach(object -> diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description)));
} else if (isNullOrEmpty(before) && !isNullOrEmpty(after)) {
after.forEach(object -> diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, null, description)));
} else {
for (Object object : before) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, findCorrespondingObject(object, after), description));
} else {
diffs.addAll(getDiffComputeEngine().evaluateAndExecute(object, getCorrespondingObject(object, after), description));
}
}
List<Diff> temp = new LinkedList<>();
for (Object object : after) {
if (ReflectionUtil.isBaseClass(object.getClass())) {
temp.addAll(getDiffComputeEngine().evaluateAndExecute(findCorrespondingObject(object, before), object, description));
} else {
temp.addAll(getDiffComputeEngine().evaluateAndExecute(getCorrespondingObject(object, before), object, description));
}
}
if (temp != null && temp.size() > 0) {
temp.removeIf(delta -> delta.getChangeType().equals(ChangeType.NO_CHANGE) || delta.getChangeType().equals(ChangeType.UPDATED));
diffs.addAll(temp);
}
}
return diffs;
} |
|
7 | public final ASTNode visitExpr(final ExprContext ctx){
if (null != ctx.booleanPrimary()) {
return visit(ctx.booleanPrimary());
}
if (null != ctx.LP_()) {
return visit(ctx.expr(0));
}
if (null != ctx.logicalOperator()) {
BinaryOperationExpression result = new BinaryOperationExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setLeft((ExpressionSegment) visit(ctx.expr(0)));
result.setRight((ExpressionSegment) visit(ctx.expr(1)));
result.setOperator(ctx.logicalOperator().getText());
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
}
NotExpression result = new NotExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setExpression((ExpressionSegment) visit(ctx.expr(0)));
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
} | public final ASTNode visitExpr(final ExprContext ctx){
if (null != ctx.booleanPrimary()) {
return visit(ctx.booleanPrimary());
}
if (null != ctx.LP_()) {
return visit(ctx.expr(0));
}
if (null != ctx.logicalOperator()) {
BinaryOperationExpression result = new BinaryOperationExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setLeft((ExpressionSegment) visit(ctx.expr(0)));
result.setRight((ExpressionSegment) visit(ctx.expr(1)));
result.setOperator(ctx.logicalOperator().getText());
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
}
NotExpression result = new NotExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setExpression((ExpressionSegment) visit(ctx.expr(0)));
return result;
} |
|
8 | public void createPatients(Table table) throws Exception{
Patient patient = transformTableToPatient(table);
registrationFirstPage.registerPatient(patient);
waitForAppReady();
String path = driver.getCurrentUrl();
String uuid = path.substring(path.lastIndexOf('/') + 1);
if (!Objects.equals(uuid, "new")) {
patient.setUuid(uuid);
registrationFirstPage.storePatientInSpecStore(patient);
}
} | public void createPatients(Table table) throws Exception{
registrationFirstPage.createPatients(table);
} |
|
9 | public Set<Driver> findAll() throws SQLException, NamingException{
Context ctx = new InitialContext();
Context envContext = (Context) ctx.lookup("java:comp/env");
DataSource dataSource = (javax.sql.DataSource) envContext.lookup("jdbc/TestDB");
Connection con = null;
try {
con = dataSource.getConnection();
PreparedStatement findAllDriversStatement = con.prepareStatement("SELECT * FROM drivers ORDER BY id");
ResultSet drivers = findAllDriversStatement.executeQuery();
Set<Driver> driverSet = new HashSet();
while (drivers.next()) {
Driver driver = new Driver();
driver.setId(drivers.getInt("id"));
driver.setName(drivers.getString("name"));
driver.setPassportSerialNumbers(drivers.getString("passport_serial_numbers"));
driver.setPhoneNumber(drivers.getString("phone_number"));
driverSet.add(driver);
}
findAllDriversStatement.close();
drivers.close();
return driverSet;
} finally {
if (con != null)
try {
con.close();
} catch (Exception ignore) {
}
}
} | public Set<Driver> findAll() throws SQLException, NamingException{
Connection con = null;
try {
con = dataSource.getConnection();
PreparedStatement findAllDriversStatement = con.prepareStatement("SELECT * FROM drivers ORDER BY id");
ResultSet drivers = findAllDriversStatement.executeQuery();
Set<Driver> driverSet = new HashSet();
while (drivers.next()) {
Driver driver = new Driver();
driver.setId(drivers.getInt("id"));
driver.setName(drivers.getString("name"));
driver.setPassportSerialNumbers(drivers.getString("passport_serial_numbers"));
driver.setPhoneNumber(drivers.getString("phone_number"));
driverSet.add(driver);
}
findAllDriversStatement.close();
drivers.close();
return driverSet;
} finally {
if (con != null)
try {
con.close();
} catch (Exception ignore) {
}
}
} |
|
10 | String transform(){
final String specialCharactersRegex = "[^a-zA-Z0-9\\s+]";
final String inputCharacters = "abcdefghijklmnopqrstuvwxyz";
Map<Character, ArrayList<String>> letterOccurenceMap = new LinkedHashMap<Character, ArrayList<String>>();
if (input.equals("")) {
return input;
}
input = input.toLowerCase();
input = input.replaceAll(specialCharactersRegex, "");
String[] words = input.split(" ");
for (Character letter : inputCharacters.toCharArray()) {
for (String word : words) {
if (word.contains(letter.toString())) {
ArrayList<String> letterWordsList = letterOccurenceMap.get(letter);
if (letterWordsList == null) {
letterWordsList = new ArrayList<String>();
}
if (!letterWordsList.contains(word)) {
letterWordsList.add(word);
Collections.sort(letterWordsList);
}
letterOccurenceMap.put(letter, letterWordsList);
}
}
}
return buildResult(letterOccurenceMap);
} | String transform(){
Map<Character, ArrayList<String>> letterOccurrenceMap = new LinkedHashMap<Character, ArrayList<String>>();
if (input.equals("")) {
return input;
}
input = input.toLowerCase();
input = input.replaceAll(specialCharactersRegex, "");
String[] words = input.split(" ");
for (Character letter : inputCharacters.toCharArray()) {
for (String word : words) {
if (word.contains(letter.toString())) {
ArrayList<String> letterWordsList = letterOccurrenceMap.get(letter);
if (letterWordsList == null) {
letterWordsList = new ArrayList<String>();
}
if (!letterWordsList.contains(word)) {
letterWordsList.add(word);
Collections.sort(letterWordsList);
}
letterOccurrenceMap.put(letter, letterWordsList);
}
}
}
return buildResult(letterOccurrenceMap);
} |
|
11 | public Response simpleSearchWithSchemaName(@PathParam("index") final String index, @PathParam("schemaName") final String schemaName, @QueryParam("q") final String queryString, @QueryParam("f") final Integer from, @Context final UriInfo uriInfo){
final SearchResult results = dox.searchWithSchemaName(index, schemaName, queryString, 50, from);
final JsonArrayBuilder hitsBuilder = Json.createArrayBuilder();
for (final IndexView hit : results.getHits()) {
final JsonObjectBuilder hitBuilder = Json.createObjectBuilder();
final String id = hit.getDoxID().toString();
for (final Entry<String, BigDecimal> entry : hit.getNumbers()) {
hitBuilder.add(entry.getKey(), entry.getValue());
}
for (final Entry<String, String> entry : hit.getStrings()) {
hitBuilder.add(entry.getKey(), entry.getValue());
}
hitBuilder.add("_collection", hit.getCollection());
if (!hit.isMasked()) {
hitBuilder.add("_id", id);
hitBuilder.add("_url", uriInfo.getBaseUriBuilder().path(hit.getCollection()).path(id).build().toString());
}
hitsBuilder.add(hitBuilder);
}
final JsonObjectBuilder jsonBuilder = Json.createObjectBuilder().add("totalHits", results.getTotalHits()).add("hits", hitsBuilder);
if (results.getBottomDoc() != null) {
final String nextPage = uriInfo.getBaseUriBuilder().path("search").path(index).queryParam("q", queryString).queryParam("f", results.getBottomDoc()).build().toASCIIString();
jsonBuilder.add("bottomDoc", results.getBottomDoc()).add("next", nextPage);
}
final JsonObject resultJson = jsonBuilder.build();
return Response.ok(resultJson).cacheControl(NO_CACHE).build();
} | public Response simpleSearchWithSchemaName(@PathParam("index") final String index, @PathParam("schemaName") final String schemaName, @QueryParam("q") final String queryString, @QueryParam("f") final Integer from, @Context final UriInfo uriInfo){
final SearchResult results = dox.searchWithSchemaName(index, schemaName, queryString, 50, from);
final JsonObjectBuilder resultBuilder = searchResultBuilder(uriInfo, results);
if (results.getBottomDoc() != null) {
final String nextPage = uriInfo.getBaseUriBuilder().path("search").path(index).path(schemaName).queryParam("q", queryString).queryParam("f", results.getBottomDoc()).build().toASCIIString();
resultBuilder.add("bottomDoc", results.getBottomDoc()).add("next", nextPage);
}
final JsonObject resultJson = resultBuilder.build();
return Response.ok(resultJson).cacheControl(NO_CACHE).build();
} |
|
12 | public boolean checkLoginExistInDB(String login) throws LoginExistException{
boolean isLoginExists = UserDB.Request.Create.checkLoginExist(login);
if (isLoginExists) {
throw new LoginExistException();
}
return false;
} | public boolean checkLoginExistInDB(String login){
return UserDB.Request.checkLoginExist(login);
} |
|
13 | public List<Map<String, Object>> items(@PathVariable String table){
LOGGER.info("Getting items for " + table);
List<Map<String, Object>> items = new ArrayList<>();
ScanRequest scanRequest = new ScanRequest().withTableName(table);
try {
List<Map<String, AttributeValue>> list = amazonDynamoDBClient.scan(scanRequest).getItems();
LOGGER.info("raw items ", list);
for (Map<String, AttributeValue> item : list) {
items.add(InternalUtils.toSimpleMapValue(item));
}
} catch (AmazonClientException ex) {
LOGGER.error(ex.getMessage());
}
return items;
} | public List<Map<String, Object>> items(@PathVariable String table){
LOGGER.info("Getting items for " + table);
List<Map<String, Object>> items = new ArrayList<>();
scanRequest.withTableName(table);
List<Map<String, AttributeValue>> list = amazonDynamoDBClient.scan(scanRequest).getItems();
LOGGER.info("raw items ", list);
for (Map<String, AttributeValue> item : list) {
items.add(InternalUtils.toSimpleMapValue(item));
}
return items;
} |
|
14 | public ExtractedFileSet extract(DownloadConfig runtime, File source, FilesToExtract toExtract) throws IOException{
Builder builder = ExtractedFileSet.builder(toExtract.baseDir()).baseDirIsGenerated(toExtract.baseDirIsGenerated());
ProgressListener progressListener = runtime.getProgressListener();
String progressLabel = "Extract (not really) " + source;
progressListener.start(progressLabel);
IExtractionMatch match = toExtract.find(new FileAsArchiveEntry(source));
if (match != null) {
FileInputStream fin = new FileInputStream(source);
try {
BufferedInputStream in = new BufferedInputStream(fin);
File file = match.write(in, source.length());
FileType type = match.type();
if (type == FileType.Executable) {
builder.executable(file);
} else {
builder.addLibraryFiles(file);
}
if (!toExtract.nothingLeft()) {
progressListener.info(progressLabel, "Something went a little wrong. Listener say something is left, but we dont have anything");
}
progressListener.done(progressLabel);
} finally {
fin.close();
}
}
return builder.build();
} | public ExtractedFileSet extract(DownloadConfig runtime, File source, FilesToExtract toExtract) throws IOException{
Builder builder = ExtractedFileSet.builder(toExtract.baseDir()).baseDirIsGenerated(toExtract.baseDirIsGenerated());
ProgressListener progressListener = runtime.getProgressListener();
String progressLabel = "Extract (not really) " + source;
progressListener.start(progressLabel);
IExtractionMatch match = toExtract.find(new FileAsArchiveEntry(source));
if (match != null) {
try (FileInputStream fin = new FileInputStream(source);
BufferedInputStream in = new BufferedInputStream(fin)) {
File file = match.write(in, source.length());
FileType type = match.type();
if (type == FileType.Executable) {
builder.executable(file);
} else {
builder.addLibraryFiles(file);
}
if (!toExtract.nothingLeft()) {
progressListener.info(progressLabel, "Something went a little wrong. Listener say something is left, but we dont have anything");
}
progressListener.done(progressLabel);
}
}
return builder.build();
} |
|
15 | private void processData(ByteBuffer data) throws IOException, InterruptedException{
int firstPacketElement = data.getInt();
int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK;
boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0);
if (seqNum > maxSeqNum || seqNum < 0) {
throw new IllegalStateException("got insane sequence number");
}
int offset = seqNum * DATA_PER_FULL_PACKET_WITH_SEQUENCE_NUM * WORD_SIZE;
int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE;
if (trueDataLength > dataReceiver.capacity()) {
throw new IllegalStateException("received more data than expected");
}
if (!isEndOfStream || data.limit() != END_FLAG_SIZE) {
data.position(SEQUENCE_NUMBER_SIZE);
data.get(dataReceiver.array(), offset, trueDataLength - offset);
}
receivedSeqNums.set(seqNum);
if (isEndOfStream) {
if (!checkAllReceived()) {
finished |= retransmitMissingSequences();
} else {
finished = true;
}
}
} | private void processData(ByteBuffer data) throws IOException, InterruptedException{
int firstPacketElement = data.getInt();
int seqNum = firstPacketElement & ~LAST_MESSAGE_FLAG_BIT_MASK;
boolean isEndOfStream = ((firstPacketElement & LAST_MESSAGE_FLAG_BIT_MASK) != 0);
if (seqNum > maxSeqNum || seqNum < 0) {
throw new IllegalStateException("got insane sequence number");
}
int offset = seqNum * DATA_WORDS_PER_PACKET * WORD_SIZE;
int trueDataLength = offset + data.limit() - SEQUENCE_NUMBER_SIZE;
if (trueDataLength > dataReceiver.capacity()) {
throw new IllegalStateException("received more data than expected");
}
if (!isEndOfStream || data.limit() != END_FLAG_SIZE) {
data.position(SEQUENCE_NUMBER_SIZE);
data.get(dataReceiver.array(), offset, trueDataLength - offset);
}
receivedSeqNums.set(seqNum);
if (isEndOfStream) {
finished = retransmitMissingSequences();
}
} |
|
16 | public DistributionQueue getQueue(@NotNull String queueName) throws DistributionException{
String key = getKey(queueName);
return queueMap.computeIfAbsent(key, k -> {
statusMap.put(key, new ConcurrentHashMap<>());
if (isActive) {
return new ActiveResourceQueue(resolverFactory, serviceName, queueName, agentRootPath);
} else {
return new ResourceQueue(resolverFactory, serviceName, queueName, agentRootPath);
}
});
} | public DistributionQueue getQueue(@NotNull String queueName) throws DistributionException{
return queueMap.computeIfAbsent(queueName, name -> {
if (isActive) {
return new ActiveResourceQueue(resolverFactory, serviceName, name, agentRootPath);
} else {
return new ResourceQueue(resolverFactory, serviceName, name, agentRootPath);
}
});
} |
|
17 | public Object clone() throws CloneNotSupportedException{
StatementTree v = (StatementTree) super.clone();
HashMap cloned_map = new HashMap();
v.map = cloned_map;
Iterator i = map.keySet().iterator();
while (i.hasNext()) {
Object key = i.next();
Object entry = map.get(key);
entry = cloneSingleObject(entry);
cloned_map.put(key, entry);
}
return v;
} | public Object clone() throws CloneNotSupportedException{
StatementTree v = (StatementTree) super.clone();
HashMap cloned_map = new HashMap();
v.map = cloned_map;
for (Object key : map.keySet()) {
Object entry = map.get(key);
entry = cloneSingleObject(entry);
cloned_map.put(key, entry);
}
return v;
} |
|
18 | private Document getDocument(String xml){
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return parser.parse(new InputSource(new StringReader(xml)));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return null;
} | private Document getDocument(String xml){
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return parser.parse(new InputSource(new StringReader(xml)));
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new RuntimeException(e);
}
} |
|
19 | public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{
if (key.getKeyType() == KeyType.Asymmetric) {
if (usedAlgorithm == null) {
ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption();
for (int i = 0; i < algorithms.size(); i++) {
SCCAlgorithm sccalgorithmID = algorithms.get(i);
if (getEnums().contains(sccalgorithmID)) {
switch(sccalgorithmID) {
case RSA_SHA_512:
return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_512, key);
case RSA_SHA_256:
return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_256, key);
case RSA_ECB:
return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_ECB, key);
default:
break;
}
}
}
} else {
switch(usedAlgorithm) {
case RSA_SHA_512:
return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_512, key);
case RSA_SHA_256:
return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_OAEP_SHA_256, key);
case RSA_ECB:
return SecureCryptoConfig.createAsymMessage(plaintext, AlgorithmID.RSA_ECB, key);
default:
break;
}
}
} else {
throw new SCCException("The used SCCKey has the wrong KeyType for this use case.", new InvalidKeyException());
}
throw new SCCException("No supported algorithm", new CoseException(null));
} | public SCCCiphertext encryptAsymmetric(AbstractSCCKey key, PlaintextContainerInterface plaintext) throws SCCException{
if (key.getKeyType() == KeyType.Asymmetric) {
if (usedAlgorithm == null) {
ArrayList<SCCAlgorithm> algorithms = currentSCCInstance.getUsage().getAsymmetricEncryption();
for (int i = 0; i < algorithms.size(); i++) {
SCCAlgorithm sccalgorithmID = algorithms.get(i);
if (getEnums().contains(sccalgorithmID)) {
return decideForAlgoAsymmetric(sccalgorithmID, key, plaintext);
}
}
} else {
return decideForAlgoAsymmetric(usedAlgorithm, key, plaintext);
}
} else {
throw new SCCException("The used SCCKey has the wrong KeyType for this use case.", new InvalidKeyException());
}
throw new SCCException("No supported algorithm", new CoseException(null));
} |
|
20 | public List<RelationshipVector> getRelationships(final String relationshipName){
List<RelationshipVector> myrelationships = relationships.get(relationshipName.toLowerCase());
ArrayList<RelationshipVector> retRels = new ArrayList<RelationshipVector>(myrelationships);
return retRels;
} | public List<RelationshipVector> getRelationships(final String relationshipName){
List<RelationshipVector> myrelationships = relationships.get(relationshipName.toLowerCase());
return new ArrayList<>(myrelationships);
} |
|
21 | public void openSecureChannel(EnumSet<SecurityLevel> securityLevel) throws IOException, JavaCardException{
if (securityLevel.contains(SecurityLevel.C_DECRYPTION) && !securityLevel.contains(SecurityLevel.C_MAC)) {
throw new IllegalArgumentException("C_DECRYPTION must be combined with C_MAC");
}
if (securityLevel.contains(SecurityLevel.R_DECRYPTION) && !securityLevel.contains(SecurityLevel.R_MAC)) {
throw new IllegalArgumentException("R_DECRYPTION must be combined with R_MAC");
}
byte hostKeyVersionNumber = context.getCardProperties().getKeyVersionNumber();
Scp02Context scp02Context = initializeUpdate(hostKeyVersionNumber);
byte[] icv = externalAuthenticate(scp02Context, securityLevel);
channel = new Scp02ApduChannel(context, securityLevel, icv);
channel.setRicv(icv);
} | public void openSecureChannel(EnumSet<SecurityLevel> securityLevel) throws IOException, JavaCardException{
if (securityLevel.contains(SecurityLevel.C_DECRYPTION) && !securityLevel.contains(SecurityLevel.C_MAC)) {
throw new IllegalArgumentException("C_DECRYPTION must be combined with C_MAC");
}
byte hostKeyVersionNumber = context.getCardProperties().getKeyVersionNumber();
Scp02Context scp02Context = initializeUpdate(hostKeyVersionNumber);
byte[] icv = externalAuthenticate(scp02Context, securityLevel);
channel = new Scp02ApduChannel(context, securityLevel, icv);
channel.setRicv(icv);
} |
|
22 | public void run(){
LOGGER_RECEIVER.info("Start the datagramm receiver.");
byte[] receiveBuffer = new byte[512];
while (!exit) {
try {
DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);
LOGGER_RECEIVER.info("Wait for packet ...");
socket.receive(packet);
LOGGER_RECEIVER.info("Received a packet: {}", packet);
if (PacketConverter.responseFromPacket(packet) != null) {
Z21Response response = PacketConverter.responseFromPacket(packet);
for (Z21ResponseListener listener : responseListeners) {
for (ResponseTypes type : listener.getListenerTypes()) {
if (type == response.boundType) {
listener.responseReceived(type, response);
}
}
}
} else {
Z21Broadcast broadcast = PacketConverter.broadcastFromPacket(packet);
if (broadcast != null) {
for (Z21BroadcastListener listener : broadcastListeners) {
for (BroadcastTypes type : listener.getListenerTypes()) {
if (type == broadcast.boundType) {
listener.onBroadCast(type, broadcast);
}
}
}
}
}
} catch (IOException e) {
if (!exit)
LOGGER_RECEIVER.warn("Failed to get a message from z21... ", e);
}
}
LOGGER_RECEIVER.info("The receiver has terminated.");
} | public void run(){
LOGGER_RECEIVER.info("Start the datagramm receiver.");
byte[] receiveBuffer = new byte[512];
while (!exit) {
try {
DatagramPacket packet = new DatagramPacket(receiveBuffer, receiveBuffer.length);
LOGGER_RECEIVER.info("Wait for packet ...");
socket.receive(packet);
z21Drive.record.Z21Record z21Record = Z21RecordFactory.fromPacket(packet);
if (z21Record != null) {
LOGGER_RECEIVER.info("Received '{}'", z21Record);
if (z21Record.isResponse()) {
for (Z21ResponseListener listener : responseListeners) {
for (Z21RecordType type : listener.getListenerTypes()) {
if (type == z21Record.getRecordType()) {
listener.responseReceived(type, z21Record);
}
}
}
} else if (z21Record.isBroadCast()) {
for (Z21BroadcastListener listener : broadcastListeners) {
for (Z21RecordType type : listener.getListenerTypes()) {
if (type == z21Record.getRecordType()) {
listener.onBroadCast(type, z21Record);
}
}
}
}
}
} catch (IOException e) {
if (!exit)
LOGGER_RECEIVER.warn("Failed to get a message from z21... ", e);
}
}
LOGGER_RECEIVER.info("The receiver has terminated.");
} |
|
23 | public void processAnnotation(final JNDIProperty jndiPropertyAnnotation, final Field field, final Object object) throws AnnotationProcessingException{
if (context == null) {
try {
context = new InitialContext();
} catch (NamingException e) {
throw new AnnotationProcessingException("Unable to initialize JNDI context", e);
}
}
String name = jndiPropertyAnnotation.value().trim();
if (name.isEmpty()) {
throw new AnnotationProcessingException(missingAttributeValue("name", "@JNDIProperty", field, object));
}
Object value;
try {
value = context.lookup(name);
} catch (NamingException e) {
throw new AnnotationProcessingException(String.format("Unable to lookup object %s from JNDI context", name), e);
}
if (value == null) {
throw new AnnotationProcessingException("JNDI object " + name + " not found in JNDI context.");
}
processAnnotation(object, field, name, value);
} | public void processAnnotation(final JNDIProperty jndiPropertyAnnotation, final Field field, final Object object) throws AnnotationProcessingException{
if (context == null) {
try {
context = new InitialContext();
} catch (NamingException e) {
throw new AnnotationProcessingException("Unable to initialize JNDI context", e);
}
}
String name = jndiPropertyAnnotation.value().trim();
checkIfEmpty(name, missingAttributeValue("name", "@JNDIProperty", field, object));
Object value;
try {
value = context.lookup(name);
} catch (NamingException e) {
throw new AnnotationProcessingException(format("Unable to lookup object %s from JNDI context", name), e);
}
if (value == null) {
throw new AnnotationProcessingException(String.format("JNDI object %s not found in JNDI context.", name));
}
processAnnotation(object, field, name, value);
} |
|
24 | public void add(T value, int index){
if (index < 0 || index > size) {
throw new ArrayListIndexOutOfBoundsException("Index are not exist, your index is " + index + " last index is " + size);
} else if (index == size && ensureCapacity()) {
arrayData[index] = value;
size++;
} else if (indexCapacity(index) && ensureCapacity()) {
arrayCopyAdd(index);
arrayData[index] = value;
size++;
} else {
grow();
arrayCopyAdd(index);
arrayData[index] = value;
size++;
}
} | public void add(T value, int index){
if (index < 0 || index > size) {
throw new ArrayListIndexOutOfBoundsException("Index are not exist, your index is " + index + " last index is " + size);
} else if (index == size && ensureCapacity()) {
arrayData[index] = value;
size++;
} else if (indexCapacity(index) && ensureCapacity()) {
arrayCopyAdd(index);
arrayData[index] = value;
} else {
grow();
arrayCopyAdd(index);
arrayData[index] = value;
}
} |
|
25 | public void testInsert(){
GeneratedAlwaysRecord record = new GeneratedAlwaysRecord();
record.setId(100);
record.setFirstName("Bob");
record.setLastName("Jones");
InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record).into(generatedAlways).map(id).toProperty("id").map(firstName).toProperty("firstName").map(lastName).toProperty("lastName").build().render(RenderingStrategy.SPRING_NAMED_PARAMETER);
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord());
KeyHolder keyHolder = new GeneratedKeyHolder();
int rows = template.update(insertStatement.getInsertStatement(), parameterSource, keyHolder);
String generatedKey = (String) keyHolder.getKeys().get("FULL_NAME");
assertThat(rows).isEqualTo(1);
assertThat(generatedKey).isEqualTo("Bob Jones");
} | public void testInsert(){
GeneratedAlwaysRecord record = new GeneratedAlwaysRecord();
record.setId(100);
record.setFirstName("Bob");
record.setLastName("Jones");
InsertStatementProvider<GeneratedAlwaysRecord> insertStatement = insert(record).into(generatedAlways).map(id).toProperty("id").map(firstName).toProperty("firstName").map(lastName).toProperty("lastName").build().render(RenderingStrategy.SPRING_NAMED_PARAMETER);
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(insertStatement.getRecord());
KeyHolder keyHolder = new GeneratedKeyHolder();
} |
|
26 | public static void addRecipe(Recipe recipe){
String recipeJSON = gson.toJson(recipe);
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
jsch.addIdentity(DBUtils.ENV_SSH_KEY);
ssh = null;
ssh = jsch.getSession("ubuntu", DBUtils.ENV_DB_ADDRESS, DBUtils.SSH_PORT);
ssh.setConfig(config);
ssh.connect();
ssh.setPortForwardingL(6666, DBUtils.ENV_DB_ADDRESS, DBUtils.ENV_DB_PORT);
MongoClient mongo = new MongoClient("localhost", 6666);
MongoDatabase database = mongo.getDatabase(DBUtils.ENV_DB_NAME);
MongoCollection<Document> recipes = database.getCollection("recipes");
recipes.insertOne(Document.parse(recipeJSON));
} catch (JSchException ex) {
Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
ssh.delPortForwardingL(6666);
} catch (JSchException ex) {
Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex);
}
ssh.disconnect();
}
} | public static void addRecipe(Recipe recipe){
String recipeJSON = gson.toJson(recipe);
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
jsch.addIdentity(DBUtils.ENV_SSH_KEY);
ssh = jsch.getSession("ubuntu", DBUtils.ENV_DB_ADDRESS, DBUtils.SSH_PORT);
ssh.setConfig(config);
ssh.connect();
ssh.setPortForwardingL(DBUtils.DB_PORT_FORWARDING, DBUtils.ENV_DB_ADDRESS, DBUtils.ENV_DB_PORT);
MongoClient mongo = new MongoClient("localhost", DBUtils.DB_PORT_FORWARDING);
MongoDatabase database = mongo.getDatabase(DBUtils.ENV_DB_NAME);
MongoCollection<Document> recipes = database.getCollection("recipes");
recipes.insertOne(Document.parse(recipeJSON));
} catch (JSchException ex) {
Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
ssh.delPortForwardingL(DBUtils.DB_PORT_FORWARDING);
} catch (JSchException ex) {
Logger.getLogger(VirtualRefrigerator.class.getName()).log(Level.SEVERE, null, ex);
}
ssh.disconnect();
}
} |
|
27 | public List<MealView> getAll(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "25") int limit){
if (page > 0)
page = page - 1;
return mealService.getAll(page, limit);
} | public List<MealView> getAll(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "25") int limit){
return mealService.getAll(page, limit);
} |
|
28 | public double GetExchangeRate(Currency currency) throws IOException{
double rate = 0;
CloseableHttpResponse response = null;
try {
response = this.httpclient.execute(httpget);
switch(response.getStatusLine().getStatusCode()) {
case 200:
HttpEntity entity = response.getEntity();
InputStream inputStream = response.getEntity().getContent();
var json = new BufferedReader(new InputStreamReader(inputStream));
@SuppressWarnings("deprecation")
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
String n = jsonObject.get("bpi").getAsJsonObject().get(currency.toString()).getAsJsonObject().get("rate").getAsString();
NumberFormat nf = NumberFormat.getInstance();
rate = nf.parse(n).doubleValue();
break;
default:
rate = -1;
}
} catch (Exception ex) {
rate = -1;
} finally {
response.close();
}
return rate;
} | public double GetExchangeRate(Currency currency){
double rate = 0;
try (CloseableHttpResponse response = this.httpclient.execute(httpget)) {
switch(response.getStatusLine().getStatusCode()) {
case 200:
HttpEntity entity = response.getEntity();
InputStream inputStream = response.getEntity().getContent();
var json = new BufferedReader(new InputStreamReader(inputStream));
@SuppressWarnings("deprecation")
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
String n = jsonObject.get("bpi").getAsJsonObject().get(currency.toString()).getAsJsonObject().get("rate").getAsString();
NumberFormat nf = NumberFormat.getInstance();
rate = nf.parse(n).doubleValue();
break;
default:
rate = -1;
}
response.close();
} catch (Exception ex) {
rate = -1;
}
return rate;
} |
|
29 | public boolean equals(Object obj){
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final OAuth2AllowDomain other = (OAuth2AllowDomain) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
} | public boolean equals(Object obj){
return ObjectEquals.of(this).equals(obj, (origin, other) -> {
return Objects.equals(origin.getId(), other.getId());
});
} |
|
30 | public Key max(){
if (isEmpty())
throw new NoSuchElementException("calls max() with empty symbol table");
return st.lastKey();
} | public Key max(){
noSuchElement(isEmpty(), "calls max() with empty symbol table");
return st.lastKey();
} |
|
31 | private static void triggerJenkinsJob(String token) throws IOException{
URL url = new URL(remoteUrl + token);
String user = "salahin";
String pass = "11d062d7023e11765b4d8ee867b67904f9";
String authStr = user + ":" + pass;
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(authStr.getBytes("utf-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", basicAuth);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:27.0) Gecko/20100101 Firefox/27.0.2 Waterfox/27.0");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
System.out.println("Step Tiger Jenkins Jobs: " + connection.getResponseCode());
connection.disconnect();
} | private void triggerJenkinsJob(URL url) throws IOException{
String authStr = userId + ":" + jenkinsToken;
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(authStr.getBytes("utf-8"));
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", basicAuth);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:27.0) Gecko/20100101 Firefox/27.0.2 Waterfox/27.0");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
System.out.println("Step Tiger Jenkins Jobs: " + connection.getResponseCode());
connection.disconnect();
} |
|
32 | public void run(){
if (Sesnor2Data == true) {
Sesnor2Data = false;
} else if (Sesnor2Data == false) {
Sesnor2Data = true;
}
sensorStates.setLaserSensor2data(Sesnor2Data);
System.out.println("fahim sesnor from laser2 = " + sensorStates.isLaserSensor2data());
changed();
} | public void run(){
if (Sesnor2Data == true) {
Sesnor2Data = false;
} else if (Sesnor2Data == false) {
Sesnor2Data = true;
}
sensorStates.setLaserSensor2data(Sesnor2Data);
changed();
} |
|
33 | public ModelAndView process(ModelAndView mav, Locale locale){
mav.setViewName("memoryleak");
mav.addObject("title", msg.getMessage("title.heap.memory.usage", null, locale));
mav.addObject("note", msg.getMessage("msg.java.heap.space.leak.occur", null, locale));
try {
toDoRemove();
List<MemoryPoolMXBean> heapPoolMXBeans = new ArrayList<>();
List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
if (MemoryType.HEAP.equals(memoryPoolMXBean.getType())) {
heapPoolMXBeans.add(memoryPoolMXBean);
}
}
mav.addObject("memoryPoolMXBeans", heapPoolMXBeans);
} catch (Exception e) {
log.error("Exception occurs: ", e);
mav.addObject("errmsg", msg.getMessage("msg.unknown.exception.occur", new String[] { e.getMessage() }, null, locale));
}
return mav;
} | public ModelAndView process(ModelAndView mav, Locale locale){
mav.setViewName("memoryleak");
mav.addObject("title", msg.getMessage("title.heap.memory.usage", null, locale));
mav.addObject("note", msg.getMessage("msg.java.heap.space.leak.occur", null, locale));
toDoRemove();
List<MemoryPoolMXBean> heapPoolMXBeans = new ArrayList<>();
List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
if (MemoryType.HEAP.equals(memoryPoolMXBean.getType())) {
heapPoolMXBeans.add(memoryPoolMXBean);
}
}
mav.addObject("memoryPoolMXBeans", heapPoolMXBeans);
return mav;
} |
|
34 | private BoundStatement buildStatementLatestVideoPage(String yyyymmdd, Optional<String> pagingState, AtomicBoolean cassandraPagingStateUsed, Optional<Instant> startingAddedDate, Optional<UUID> startingVideoId, int recordNeeded){
BoundStatementBuilder statementBuilder;
if (startingAddedDate.isPresent() && startingVideoId.isPresent()) {
statementBuilder = latestVideoPreview_startingPointPrepared.boundStatementBuilder(yyyymmdd, startingAddedDate.get(), startingVideoId.get());
} else {
statementBuilder = latestVideoPreview_noStartingPointPrepared.boundStatementBuilder(yyyymmdd);
}
statementBuilder.setPageSize(recordNeeded);
pagingState.ifPresent(x -> {
statementBuilder.setPagingState(Bytes.fromHexString(x));
cassandraPagingStateUsed.compareAndSet(false, true);
});
statementBuilder.setConsistencyLevel(ConsistencyLevel.ONE);
return statementBuilder.build();
} | private BoundStatement buildStatementLatestVideoPage(String yyyymmdd, Optional<String> pagingState, AtomicBoolean cassandraPagingStateUsed, Optional<Instant> startingAddedDate, Optional<UUID> startingVideoId, int recordNeeded){
BoundStatementBuilder statementBuilder = getBoundStatementBuilder(yyyymmdd, startingAddedDate, startingVideoId);
statementBuilder.setPageSize(recordNeeded);
pagingState.ifPresent(x -> {
statementBuilder.setPagingState(Bytes.fromHexString(x));
cassandraPagingStateUsed.compareAndSet(false, true);
});
statementBuilder.setConsistencyLevel(ConsistencyLevel.ONE);
return statementBuilder.build();
} |
|
35 | public void sendMessage(ChannelId id, ByteBuf message){
Channel channel = allChannels.find(id);
if (channel != null) {
WebSocketFrame frame = new BinaryWebSocketFrame(message);
channel.writeAndFlush(frame);
}
} | public void sendMessage(ChannelId id, Message message){
Channel channel = allChannels.find(id);
if (channel != null) {
channel.writeAndFlush(message);
}
} |
|
36 | public void test_isTogglePatternAvailable() throws Exception{
when(element.getPropertyValue(anyInt())).thenReturn(1);
IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class);
UIAutomation instance = new UIAutomation(mocked_automation);
AutomationWindow window = new AutomationWindow(new ElementBuilder(element).itemContainer(container).automation(instance).window(pattern));
boolean value = window.isTogglePatternAvailable();
assertTrue(value);
} | public void test_isTogglePatternAvailable() throws Exception{
Toggle pattern = Mockito.mock(Toggle.class);
when(pattern.isAvailable()).thenReturn(true);
AutomationWindow window = new AutomationWindow(new ElementBuilder(element).addPattern(pattern));
boolean value = window.isTogglePatternAvailable();
assertTrue(value);
} |
|
37 | static EbicsBank sendHPB(final EbicsSession session) throws IOException, GeneralSecurityException, EbicsException{
final HPBRequestElement request = new HPBRequestElement(session);
final EbicsNoPubKeyDigestsRequest ebicsNoPubKeyDigestsRequest = request.build();
final byte[] xml = XmlUtil.prettyPrint(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest);
session.getTraceManager().trace(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest, session.getUser());
XmlUtil.validate(xml);
final HttpEntity httpEntity = HttpUtil.sendAndReceive(session.getBank(), new ByteArrayContentFactory(xml), session.getMessageProvider());
final KeyManagementResponseElement response = new KeyManagementResponseElement(httpEntity, session.getMessageProvider());
final EbicsKeyManagementResponse keyManagementResponse = response.build();
session.getTraceManager().trace(XmlUtil.prettyPrint(EbicsKeyManagementResponse.class, keyManagementResponse), "HBPResponse", session.getUser());
final ContentFactory factory = new ByteArrayContentFactory(ZipUtil.uncompress(CryptoUtil.decrypt(response.getOrderData(), response.getTransactionKey(), session.getUser().getEncryptionKey().getPrivateKey())));
final HPBResponseOrderDataElement orderData = new HPBResponseOrderDataElement(factory);
final HPBResponseOrderDataType orderDataResponse = orderData.build();
session.getTraceManager().trace(HPBResponseOrderDataType.class, orderDataResponse, session.getUser());
return session.getBank().withAuthenticationKey(orderData.getBankAuthenticationKey()).withEncryptionKey(orderData.getBankEncryptionKey());
} | static EbicsBank sendHPB(final EbicsSession session) throws IOException, GeneralSecurityException, EbicsException{
final EbicsNoPubKeyDigestsRequest ebicsNoPubKeyDigestsRequest = HPBRequestElement.create(session);
final byte[] xml = XmlUtil.prettyPrint(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest);
session.getTraceManager().trace(EbicsNoPubKeyDigestsRequest.class, ebicsNoPubKeyDigestsRequest, session.getUser());
XmlUtil.validate(xml);
final HttpEntity httpEntity = HttpUtil.sendAndReceive(session.getBank(), new ByteArrayContentFactory(xml), session.getMessageProvider());
final KeyManagementResponseElement response = new KeyManagementResponseElement(httpEntity, session.getMessageProvider());
final EbicsKeyManagementResponse keyManagementResponse = response.build();
session.getTraceManager().trace(XmlUtil.prettyPrint(EbicsKeyManagementResponse.class, keyManagementResponse), "HBPResponse", session.getUser());
final ContentFactory factory = new ByteArrayContentFactory(ZipUtil.uncompress(CryptoUtil.decrypt(response.getOrderData(), response.getTransactionKey(), session.getUser().getEncryptionKey().getPrivateKey())));
final HPBResponseOrderDataElement orderData = HPBResponseOrderDataElement.parse(factory);
session.getTraceManager().trace(IOUtil.read(factory.getContent()), "HPBResponseOrderData", session.getUser());
return session.getBank().withAuthenticationKey(orderData.getBankAuthenticationKey()).withEncryptionKey(orderData.getBankEncryptionKey());
} |
|
38 | public FxNode eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){
FxObjNode srcObj = (FxObjNode) src;
boolean expr = FxNodeValueUtils.getBooleanOrThrow(srcObj, "expr");
FxNode templateNode;
if (expr) {
templateNode = srcObj.get("then");
} else {
templateNode = srcObj.get("else");
}
FxNode res = null;
if (templateNode != null) {
res = FxNodeCopyVisitor.copyTo(dest, templateNode);
}
return res;
} | public void eval(FxChildWriter dest, FxEvalContext ctx, FxNode src){
FxObjNode srcObj = (FxObjNode) src;
boolean expr = FxNodeValueUtils.getBooleanOrThrow(srcObj, "expr");
FxNode templateNode;
if (expr) {
templateNode = srcObj.get("then");
} else {
templateNode = srcObj.get("else");
}
if (templateNode != null) {
FxNodeCopyVisitor.copyTo(dest, templateNode);
}
} |
|
39 | public Election registerElection(final Election election){
try {
jdbcTemplate.update(REGISTER_ELECTION_QUERY, new Object[] { election.getElectionTitle(), election.getElectionId(), election.getElectionDescription(), election.getAdminVoterId(), "1" }, new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
return election;
} catch (DataAccessException ex) {
ConsoleLogger.Log(ControllerOperations.DB_PUT_ELECTION, ex.getMessage(), election);
throw new RestrictedActionException("Error While Creating Entry in Election");
}
} | public void registerElection(final Election election){
try {
jdbcTemplate.update(REGISTER_ELECTION_QUERY, new Object[] { election.getElectionTitle(), election.getElectionId(), election.getElectionDescription(), election.getAdminVoterId(), "1" }, new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
} catch (DataAccessException ex) {
ConsoleLogger.Log(ControllerOperations.DB_PUT_ELECTION, ex.getMessage(), election);
throw new RestrictedActionException("Error While Creating Entry in Election");
}
} |
|
40 | public MappingJacksonValue lessons(){
MappingJacksonValue result = new MappingJacksonValue(this.lessonService.findAll());
return result;
} | public MappingJacksonValue lessons(){
return new MappingJacksonValue(this.lessonService.findAll());
} |
|
41 | public String execute(HttpServletRequest request, HttpServletResponse response){
String email = (String) request.getParameter("email");
String password = (String) request.getParameter("password");
User user = userService.findByEmail(email);
if (user == null) {
return LOGIN_PAGE;
} else if (!user.getPassword().equals(password)) {
return LOGIN_PAGE;
}
request.getSession().setAttribute(X_AUTH_TOKEN, user.getId());
return INDEX_PAGE;
} | public String execute(HttpServletRequest request, HttpServletResponse response){
String email = (String) request.getParameter("email");
String password = (String) request.getParameter("password");
User user = userService.findByEmail(email);
if (user == null || !user.getPassword().equals(password)) {
return Pages.LOGIN;
}
request.getSession().setAttribute(X_AUTH_TOKEN, user.getId());
return Pages.INDEX;
} |
|
42 | public void takeDamage(int damageValue, Weapon weapon){
if (damageValue <= 0)
return;
if (equipment.canBlockHit()) {
equipment.blockHitFrom(weapon);
return;
}
int damageToTake = damageValue - equipment.calculateTotalDamageResistance();
damageToTake = Math.max(damageToTake, 0);
hp -= damageToTake;
} | public void takeDamage(int damageValue, Weapon weapon){
if (damageValue <= 0)
return;
if (equipment.canBlockHit()) {
equipment.blockHitFrom(weapon);
return;
}
int damageToTake = damageValue - equipment.calculateTotalDamageResistance();
hp -= damageToTake;
} |
|
43 | public Object createFromResultSet(ResultSetHelper rs) throws SQLException{
Object object = newEntityInstance();
for (int i = 0; i < fieldColumnMappings.size(); i++) {
FieldColumnMapping fieldColumnMapping = fieldColumnMappings.get(i);
fieldColumnMapping.setFromResultSet(object, rs);
if (i == lastPrimaryKeyIndex) {
Object existing = objectCache.get(classRowMapping, object);
if (existing != null) {
return existing;
}
}
}
objectCache.add(classRowMapping, object);
return object;
} | public Object createFromResultSet(ResultSetHelper rs) throws SQLException{
Object object = newEntityInstance();
for (int i = 0; i < fieldColumnMappings.size(); i++) {
fieldColumnMappings.get(i).setFromResultSet(object, rs, i + 1);
if (i == lastPrimaryKeyIndex) {
Object existing = objectCache.get(classRowMapping, object);
if (existing != null) {
return existing;
}
}
}
objectCache.add(classRowMapping, object);
return object;
} |
|
44 | private void getInstalledOs(SQLConnection connection, Handler<AsyncResult<List<JsonObject>>> next){
String query = "SELECT * FROM app_installer";
connection.query(query, selectHandler -> {
if (selectHandler.failed()) {
handleFailure(logger, selectHandler);
} else {
logger.info("Installed OS: ", Json.encodePrettily(selectHandler.result().getRows()));
next.handle(Future.succeededFuture(selectHandler.result().getRows()));
}
});
} | private void getInstalledOs(SQLConnection connection, Handler<AsyncResult<List<JsonObject>>> next){
connection.query(SELECT_APP_INSTALLER_QUERY, selectHandler -> {
if (selectHandler.failed()) {
handleFailure(logger, selectHandler);
} else {
logger.info("Installed OS: ", Json.encodePrettily(selectHandler.result().getRows()));
next.handle(Future.succeededFuture(selectHandler.result().getRows()));
}
});
} |
|
45 | public Integer[] flattenArray(Object[] inputArray){
List<Integer> flattenedIntegerList = new ArrayList<Integer>();
for (Object element : inputArray) {
if (element instanceof Integer[]) {
Integer[] elementArray = (Integer[]) element;
for (Integer currentElement : elementArray) {
flattenedIntegerList.add(currentElement);
}
} else if (element instanceof Integer) {
flattenedIntegerList.add((Integer) element);
}
}
return flattenedIntegerList.toArray(new Integer[flattenedIntegerList.size()]);
} | public Integer[] flattenArray(Object[] inputArray){
List<Integer> flattenedIntegerList = new ArrayList<Integer>();
for (Object element : inputArray) {
if (element instanceof Integer[]) {
Integer[] elementArray = (Integer[]) element;
Collections.addAll(flattenedIntegerList, elementArray);
} else if (element instanceof Integer) {
flattenedIntegerList.add((Integer) element);
}
}
return flattenedIntegerList.toArray(new Integer[flattenedIntegerList.size()]);
} |
|
46 | public void process(UserDTO dto){
UserEntity entity = repository.findFirstByEmail(dto.getEmail()).orElseGet(UserEntity::new);
entity.setOuterId(dto.getId());
entity.setEmail(dto.getEmail());
entity.setFirstName(dto.getFirstName());
entity.setLastName(dto.getLastName());
entity.setDateModified(dto.getDateModified());
if (isNull(entity.getId())) {
entity.setRegisteredDate(dto.getRegisteredDate());
entity.setExportDate(LocalDateTime.now());
}
List<EmploymentEntity> employment = dto.getEmployments().stream().map(eDto -> {
EmploymentEntity employmentEntity = new EmploymentEntity();
employmentEntity.setStart(eDto.getStart());
employmentEntity.setEnd(eDto.getEnd());
employmentEntity.setDepartment(departmentRepository.findFirstByOuterId(eDto.getDepartment().getIdentifier()).orElseGet(() -> new DepartmentEntity(eDto.getDepartment().getIdentifier(), eDto.getDepartment().getName())));
return employmentEntity;
}).collect(toList());
entity.setEmployments(employment);
repository.save(entity);
} | public void process(UserDTO dto){
UserEntity entity = repository.findFirstByEmail(dto.getEmail()).orElseGet(UserEntity::new);
entity.setOuterId(dto.getId());
entity.setEmail(dto.getEmail());
entity.setFirstName(dto.getFirstName());
entity.setLastName(dto.getLastName());
entity.setDateModified(dto.getDateModified());
entity.setRegisteredDate(dto.getRegisteredDate());
repository.save(entity);
} |
|
47 | public void testSetOverallPositionAndWaitTimePhysical(){
int position = 2;
physicalQueueStatus.setPosition(position);
int numStudents = 1;
long timeSpent = 5L;
employee.setTotalTimeSpent(timeSpent);
employee.setNumRegisteredStudents(numStudents);
int expectedWaitTime = (int) ((position - 1.) * timeSpent / numStudents);
queueService.setOverallPositionAndWaitTime(physicalQueueStatus);
assertEquals(physicalQueueStatus.getCompanyId(), "c1");
assertEquals(physicalQueueStatus.getQueueId(), "pq1");
assertEquals(physicalQueueStatus.getRole(), Role.SWE);
assertEquals(physicalQueueStatus.getPosition(), position);
assertEquals(physicalQueueStatus.getQueueType(), QueueType.PHYSICAL);
assertEquals(physicalQueueStatus.getWaitTime(), expectedWaitTime);
assertEquals(physicalQueueStatus.getEmployee(), employee);
} | public void testSetOverallPositionAndWaitTimePhysical(){
int position = 2;
physicalQueueStatus.setPosition(position);
int numStudents = 1;
long timeSpent = 5L;
employee.setTotalTimeSpent(timeSpent);
employee.setNumRegisteredStudents(numStudents);
int expectedWaitTime = (int) ((position - 1.) * timeSpent / numStudents);
queueService.setOverallPositionAndWaitTime(physicalQueueStatus);
validatePhysicalQueueStatus(physicalQueueStatus, position, expectedWaitTime);
} |
|
48 | public void returnOnePositionForOneItemInInvoice(){
bookKeeper = new BookKeeper(new InvoiceFactory());
when(productData.getType()).thenReturn(productType);
InvoiceBuilderImpl invoiceBuilderImpl = new InvoiceBuilderImpl();
invoiceBuilderImpl.setItemsQuantity(1);
invoiceBuilderImpl.setProductData(productData);
invoiceBuilderImpl.setMoney(money);
request = invoiceBuilderImpl.build();
when(taxPolicy.calculateTax(productType, money)).thenReturn(tax);
invoice = bookKeeper.issuance(request, taxPolicy);
invoiceLines = invoice.getItems();
assertThat(invoice, notNullValue());
assertThat(invoiceLines, notNullValue());
assertThat(invoiceLines.size(), Matchers.equalTo(1));
} | public void returnOnePositionForOneItemInInvoice(){
bookKeeper = new BookKeeper(new InvoiceFactory());
when(productData.getType()).thenReturn(productType);
request = buildRequest(1);
when(taxPolicy.calculateTax(productType, money)).thenReturn(tax);
invoice = bookKeeper.issuance(request, taxPolicy);
invoiceLines = invoice.getItems();
assertThat(invoice, notNullValue());
assertThat(invoiceLines, notNullValue());
assertThat(invoiceLines.size(), Matchers.equalTo(1));
} |
|
49 | public Double removeBetEventOnTicket(@RequestBody String json){
Long id = Long.parseLong(JSON.parseObject(json).get("id").toString());
Character type = JSON.parseObject(json).get("type").toString().charAt(0);
BetEvent betEvent = betEventService.getBetEventById(id);
playedEvents.removeIf((PlayedEvent event) -> event.getEvent().equals(betEvent));
return calculateQuotaService.decreaseSumQuota(type, betEvent);
} | public Double removeBetEventOnTicket(@RequestBody String json){
Long id = Long.parseLong(JSON.parseObject(json).get("id").toString());
Character type = JSON.parseObject(json).get("type").toString().charAt(0);
BetEvent betEvent = betEventService.getBetEventById(id);
return calculateQuotaService.decreaseSumQuota(type, betEvent);
} |
|
50 | public void testRemoveJavadoc() throws ParseException{
String code = "public class B { /**\n* This class is awesome**/\npublic void foo(){} }";
DefaultJavaParser parser = new DefaultJavaParser();
CompilationUnit cu = parser.parse(code, false);
CompilationUnit cu2 = parser.parse(code, false);
MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0);
md.setJavaDoc(null);
ChangeLogVisitor visitor = new ChangeLogVisitor();
VisitorContext ctx = new VisitorContext();
ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2);
visitor.visit((CompilationUnit) cu, ctx);
List<Action> actions = visitor.getActionsToApply();
Assert.assertEquals(1, actions.size());
assertCode(actions, code, "public class B { public void foo(){} }");
} | public void testRemoveJavadoc() throws ParseException{
String code = "public class B { /**\n* This class is awesome**/\npublic void foo(){} }";
DefaultJavaParser parser = new DefaultJavaParser();
CompilationUnit cu = parser.parse(code, false);
CompilationUnit cu2 = parser.parse(code, false);
MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0);
md.setJavaDoc(null);
List<Action> actions = getActions(cu2, cu);
Assert.assertEquals(1, actions.size());
assertCode(actions, code, "public class B { public void foo(){} }");
} |
|
51 | public void addGrantToAllTablesInSchema(String schema, Privileges privs, String grantee, boolean grant_option, String granter) throws DatabaseException{
TableName[] list = connection.getTableList();
for (int i = 0; i < list.length; ++i) {
TableName tname = list[i];
if (tname.getSchema().equals(schema)) {
addGrant(privs, TABLE, tname.toString(), grantee, grant_option, granter);
}
}
} | public void addGrantToAllTablesInSchema(String schema, Privileges privs, String grantee, boolean grant_option, String granter) throws DatabaseException{
TableName[] list = connection.getTableList();
for (TableName tname : list) {
if (tname.getSchema().equals(schema)) {
addGrant(privs, TABLE, tname.toString(), grantee, grant_option, granter);
}
}
} |
|
52 | private static void setupPluginBootService(final Collection<PluginConfiguration> pluginConfigurations){
PluginServiceManager.setUpAllService(pluginConfigurations);
PluginServiceManager.startAllService(pluginConfigurations);
Runtime.getRuntime().addShutdownHook(new Thread(PluginServiceManager::cleanUpAllService));
} | private static void setupPluginBootService(final Map<String, PluginConfiguration> pluginConfigurationMap){
PluginServiceManager.startAllService(pluginConfigurationMap);
Runtime.getRuntime().addShutdownHook(new Thread(PluginServiceManager::closeAllService));
} |
|
53 | public void testCreateListing6() throws CommandParseFailException, UnsupportCommandException{
List<String> arg = new ArrayList<String>();
arg = CommandPaser.parse(clistCommand6);
createListingCommand.setCommands(arg);
createListingCommand.execute();
ResponseObject ret = registerUserCommand.getRetObj();
System.out.println(ret.getMessage());
} | public void testCreateListing6() throws CommandParseFailException, UnsupportCommandException{
List<String> arg = new ArrayList<String>();
arg = CommandPaser.parse(clistCommand6);
createListingCommand.setCommands(arg);
ResponseObject ret = createListingCommand.execute();
System.out.println(ret.getMessage());
} |
|
54 | public String paymentSuccess(@QueryParam("PayerID") String payerID){
System.out.println(payerID);
return payService.executePayment(payerID).toJSON();
} | public String paymentSuccess(@QueryParam("PayerID") String payerID, @QueryParam("paymentId") String paymentId){
return payService.executePayment(payerID, paymentId).toJSON();
} |
|
55 | public String getToken(){
JwtRequest jwtRequest = JwtRequest.builder().username("javainuse").password("password").build();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<JwtRequest> entity = new HttpEntity<JwtRequest>(jwtRequest, headers);
logger.info("url: {}", this.createURLWithPort("/authenticate"));
ResponseEntity<JwtResponse> response = restTemplate.exchange(this.createURLWithPort("/authenticate"), HttpMethod.POST, entity, JwtResponse.class);
logger.info("response: {}", response);
assertEquals(HttpStatus.OK, response.getStatusCode());
return response.getBody().getJwtToken();
} | public String getToken(){
JwtRequest jwtRequest = JwtRequest.builder().username("javainuse").password("password").build();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
logger.info("url: {}", this.createURLWithPort("/authenticate"));
ResponseEntity<JwtResponse> response = restTemplate.exchange(this.createURLWithPort("/authenticate"), HttpMethod.POST, new HttpEntity<JwtRequest>(jwtRequest, headers), JwtResponse.class);
logger.info("response: {}", response);
assertEquals(HttpStatus.OK, response.getStatusCode());
return response.getBody().getJwtToken();
} |
|
56 | public List<Donation> getDonation(@QueryParam("filters") Optional<String> filters){
if (filters.isPresent()) {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new ProtobufModule());
DonationsFilters donationFilters;
try {
donationFilters = mapper.readValue(URLDecoder.decode(filters.get(), "UTF-8"), DonationsFilters.class);
if (donationFilters.hasLimit()) {
if (donationFilters.getLimit() > this.maxLimit) {
donationFilters = donationFilters.toBuilder().setLimit(this.maxLimit).build();
} else {
donationFilters = donationFilters.toBuilder().setLimit(this.defaultLimit).build();
}
}
return this.manager.getDonations(donationFilters);
} catch (IOException e) {
LOG.error(e.getMessage());
throw new BadRequestException("Donations filters were malformed. Could not parse JSON content in query param", ApiDocs.DONATIONS_FILTERS);
}
} else {
return this.manager.getDonations();
}
} | public List<Donation> getDonation(@QueryParam("limit") Optional<Integer> maybeLimit, @QueryParam("filters") Optional<String> maybeFilters){
Integer limit = ResourcesHelper.limit(maybeLimit, defaultLimit, maxLimit);
if (maybeFilters.isPresent()) {
DonationsFilters filters = ResourcesHelper.decodeUrlEncodedJson(maybeFilters.get(), DonationsFilters.class);
return this.manager.getDonations(limit, filters);
} else {
return this.manager.getDonations();
}
} |
|
57 | private BetweenExpression createBetweenSegment(final PredicateContext ctx){
BetweenExpression result = new BetweenExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setLeft((ExpressionSegment) visit(ctx.bitExpr(0)));
result.setBetweenExpr((ExpressionSegment) visit(ctx.bitExpr(1)));
result.setAndExpr((ExpressionSegment) visit(ctx.predicate()));
String text = ctx.start.getInputStream().getText(new Interval(ctx.start.getStartIndex(), ctx.stop.getStopIndex()));
result.setText(text);
return result;
} | private BetweenExpression createBetweenSegment(final PredicateContext ctx){
BetweenExpression result = new BetweenExpression();
result.setStartIndex(ctx.start.getStartIndex());
result.setStopIndex(ctx.stop.getStopIndex());
result.setLeft((ExpressionSegment) visit(ctx.bitExpr(0)));
result.setBetweenExpr((ExpressionSegment) visit(ctx.bitExpr(1)));
result.setAndExpr((ExpressionSegment) visit(ctx.predicate()));
return result;
} |
|
58 | public void generateBuildTree(){
System.out.println("Starting optimization of blueprint '" + blueprint.getName() + "'");
BuildTreeBlueprintNode tree = generateBuildTree(1, blueprint);
tree.updateTreePrices();
BuildTreePrinter printer = new BuildTreePrinter(System.out);
printer.printTree(tree);
Map<Integer, Long> shoppingList = new HashMap<>();
Map<Integer, Long> buildList = new HashMap<>();
tree.generateBuildBuyLists(shoppingList, buildList);
String[] buyHeaders = { "Buy", "Quantity" };
String[] buildHeaders = { "Build", "Quantity" };
Class<?>[] classes = new Class<?>[] { String.class, String.class };
DecimalFormat decimalFormat = new DecimalFormat("#");
decimalFormat.setGroupingUsed(true);
decimalFormat.setGroupingSize(3);
List<String[]> buyData = new LinkedList<>();
for (Map.Entry<Integer, Long> entries : shoppingList.entrySet()) {
buyData.add(new String[] { typeLoader.getType(entries.getKey()).getName(), decimalFormat.format(entries.getValue()) });
}
List<String[]> buildData = new LinkedList<>();
for (Map.Entry<Integer, Long> entries : buildList.entrySet()) {
buildData.add(new String[] { typeLoader.getType(entries.getKey()).getName(), decimalFormat.format(entries.getValue()) });
}
ColumnOutputPrinter buyPrinter = new ColumnOutputPrinter(buyHeaders, classes, buyData);
ColumnOutputPrinter buildPrinter = new ColumnOutputPrinter(buyHeaders, classes, buildData);
buyPrinter.output();
buildPrinter.output();
} | public BuildManifest generateBuildTree(){
System.out.println("Starting optimization of blueprint '" + blueprint.getName() + "'");
BuildTreeBlueprintNode tree = generateBuildTree(1, blueprint);
tree.updateTreePrices();
Map<EveType, Long> shoppingList = new HashMap<>();
Map<EveType, Long> buildList = new HashMap<>();
tree.generateBuildBuyLists(typeLoader, shoppingList, buildList);
return BuildManifest.builder().tree(tree).shoppingList(shoppingList).buildList(buildList).build();
} |
|
59 | public Milestone getMilestone(String name) throws TracRpcException{
Object[] params = new Object[] { name };
HashMap result = (HashMap) this.call("ticket.milestone.get", params);
Milestone m = new Milestone();
m.setAttribs(result);
return m;
} | public Milestone getMilestone(String name) throws TracRpcException{
return this.getBasicStruct(name, "ticket.milestone.get", Milestone.class);
} |
|
60 | public List<UserReport> findDeletedUserReports() throws ServiceException{
try {
List<UserReport> reports = dao.findUserReportsByAvailability(false);
return reports;
} catch (DaoException e) {
throw new ServiceException(e);
}
} | public List<UserReport> findDeletedUserReports() throws ServiceException{
try {
return dao.findUserReportsByAvailability(false);
} catch (DaoException e) {
throw new ServiceException(e);
}
} |
|
61 | public Set<User> getParticipantOfTournament(@PathVariable Integer tournamentId){
Tournament tournament = tournamentService.getTournamenById(tournamentId);
System.out.println(tournament.getUsers().size());
return tournament.getUsers();
} | public Set<User> getParticipantOfTournament(@PathVariable Integer tournamentId){
Tournament tournament = tournamentService.getTournamenById(tournamentId);
return tournament.getUsers();
} |
|
62 | public final void read(InputStream source) throws IOException{
checkNotNull(source);
progressTimer = new Timer(true);
progressTimer.schedule(new ProgressTimer(source), 10_000, 30_000);
try {
run(new BufferedInputStream(source));
} catch (Exception e) {
throw new IOException(e);
} finally {
progressTimer.cancel();
BasicNamespace.Registry.getInstance().clean();
}
} | public final void read(InputStream source) throws IOException{
checkNotNull(source);
try {
run(new BufferedInputStream(source));
} catch (Exception e) {
throw new IOException(e);
} finally {
BasicNamespace.Registry.getInstance().clean();
}
} |
|
63 | public static Optional<Violation> minRule(String field, Integer value, int min){
Optional<Violation> isNotNull = notNullRule(field, value);
if (isNotNull.isPresent()) {
return isNotNull;
}
if (value < min) {
return Optional.of(Violation.of(field, "validation.error.integer.value.smaller.than.min", "Value is smaller than min.", singletonMap("min", min)));
}
return Optional.empty();
} | public static Optional<Violation> minRule(String field, Integer value, int min){
Optional<Violation> isNotNull = notNullRule(field, value);
if (isNotNull.isPresent()) {
return isNotNull;
}
return isTrueRule(() -> value >= min, Violation.of(field, "validation.error.integer.value.smaller.than.min", "Value is smaller than min.", singletonMap("min", min)));
} |
|
64 | static int maxSubArray(int[] nums){
int cf = 0;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= cf + nums[i])
cf = nums[i];
else
cf += nums[i];
if (maxSum < cf)
maxSum = cf;
}
return maxSum;
} | static int maxSubArray(int[] nums){
int cf = nums[0];
int maxSum = nums[0];
for (int i = 1; i < nums.length; i++) {
cf = cf + nums[i];
if (nums[i] > cf)
cf = nums[i];
if (cf > maxSum)
maxSum = cf;
}
return maxSum;
} |
|
65 | public void positiveEvaluteEqualsToInteger() throws Exception{
Map<String, Object> attributes = new HashMap<>();
attributes.put("age", 25);
String feature = "Age Feature";
String expression = "age == 25";
final GatingValidator validator = new GatingValidator();
Assert.assertTrue(validator.isAllowed(expression, feature, attributes));
} | public void positiveEvaluteEqualsToInteger() throws Exception{
Map<String, Object> attributes = new HashMap<>();
attributes.put("age", 25);
String feature = "Age Feature";
String expression = "age == 25";
Assert.assertTrue(validator.isAllowed(expression, feature, attributes));
} |
|
66 | void invalidate(List<MovieRating> movieRatings){
Map<Integer, MovieRating> newActualMovieRating = new HashMap<>();
for (MovieRating movieRating : movieRatings) {
newActualMovieRating.put(movieRating.getMovie().getId(), movieRating);
}
Lock writeLock = LOCK.writeLock();
try {
writeLock.lock();
actualMovieRating = newActualMovieRating;
} finally {
writeLock.unlock();
}
} | void invalidate(List<MovieRating> movieRatings){
Map<Integer, MovieRating> newActualMovieRating = new ConcurrentHashMap<>();
for (MovieRating movieRating : movieRatings) {
newActualMovieRating.put(movieRating.getMovie().getId(), movieRating);
}
actualMovieRating = newActualMovieRating;
} |
|
67 | private void resize(int capacity){
assert capacity > n;
Key[] temp = (Key[]) new Object[capacity];
for (int i = 1; i <= n; i++) {
temp[i] = pq[i];
}
pq = temp;
} | private void resize(int capacity){
assert capacity > n;
pq = Arrays.copyOf(pq, capacity);
} |
|
68 | public void returnTenPositionsForTenItemInInvoiceTaxCalculatedTenTimes(){
bookKeeper = new BookKeeper(new InvoiceFactory());
when(productData.getType()).thenReturn(productType);
InvoiceBuilderImpl invoiceBuilderImpl = new InvoiceBuilderImpl();
invoiceBuilderImpl.setItemsQuantity(10);
invoiceBuilderImpl.setProductData(productData);
invoiceBuilderImpl.setMoney(money);
request = invoiceBuilderImpl.build();
when(taxPolicy.calculateTax(productType, money)).thenReturn(tax);
invoice = bookKeeper.issuance(request, taxPolicy);
invoiceLines = invoice.getItems();
verify(taxPolicy, times(10)).calculateTax(productType, money);
assertThat(invoiceLines, notNullValue());
assertThat(invoiceLines.size(), Matchers.equalTo(10));
} | public void returnTenPositionsForTenItemInInvoiceTaxCalculatedTenTimes(){
bookKeeper = new BookKeeper(new InvoiceFactory());
when(productData.getType()).thenReturn(productType);
request = buildRequest(10);
when(taxPolicy.calculateTax(productType, money)).thenReturn(tax);
invoice = bookKeeper.issuance(request, taxPolicy);
invoiceLines = invoice.getItems();
verify(taxPolicy, times(10)).calculateTax(productType, money);
assertThat(invoiceLines, notNullValue());
assertThat(invoiceLines.size(), Matchers.equalTo(10));
} |
|
69 | public void test_isSelectionPatternAvailable() throws Exception{
when(element.getPropertyValue(anyInt())).thenReturn(1);
IUIAutomation mocked_automation = Mockito.mock(IUIAutomation.class);
UIAutomation instance = new UIAutomation(mocked_automation);
AutomationWindow window = new AutomationWindow(new ElementBuilder(element).itemContainer(container).automation(instance).window(pattern));
boolean value = window.isSelectionPatternAvailable();
assertTrue(value);
} | public void test_isSelectionPatternAvailable() throws Exception{
Selection pattern = Mockito.mock(Selection.class);
when(pattern.isAvailable()).thenReturn(true);
AutomationWindow window = new AutomationWindow(new ElementBuilder(element).addPattern(pattern));
boolean value = window.isSelectionPatternAvailable();
assertTrue(value);
} |
|
70 | public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception{
if (doesCheckerAppy(context)) {
if (!check(exchange, context)) {
MongoClient client = MongoDBClientSingleton.getInstance().getClient();
MongoDatabase mdb = client.getDatabase(context.getDBName());
MongoCollection<BsonDocument> coll = mdb.getCollection(context.getCollectionName(), BsonDocument.class);
StringBuilder sb = new StringBuilder();
sb.append("request check failed");
List<String> warnings = context.getWarnings();
if (warnings != null && !warnings.isEmpty()) {
warnings.stream().forEach(w -> {
sb.append(", ").append(w);
});
}
BsonDocument oldData = context.getDbOperationResult().getOldData();
Object newEtag = context.getDbOperationResult().getEtag();
if (oldData != null) {
DAOUtils.restoreDocument(coll, oldData.get("_id"), context.getShardKey(), oldData, newEtag);
if (oldData.get("$set") != null && oldData.get("$set").isDocument() && oldData.get("$set").asDocument().get("_etag") != null) {
exchange.getResponseHeaders().put(Headers.ETAG, oldData.get("$set").asDocument().get("_etag").asObjectId().getValue().toString());
} else {
exchange.getResponseHeaders().remove(Headers.ETAG);
}
} else {
Object newId = context.getDbOperationResult().getNewData().get("_id");
coll.deleteOne(and(eq("_id", newId), eq("_etag", newEtag)));
}
ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST, sb.toString());
next(exchange, context);
return;
}
}
next(exchange, context);
} | public void handleRequest(HttpServerExchange exchange, RequestContext context) throws Exception{
if (doesCheckerAppy(context)) {
if (!check(exchange, context)) {
MongoClient client = MongoDBClientSingleton.getInstance().getClient();
MongoDatabase mdb = client.getDatabase(context.getDBName());
MongoCollection<BsonDocument> coll = mdb.getCollection(context.getCollectionName(), BsonDocument.class);
BsonDocument oldData = context.getDbOperationResult().getOldData();
Object newEtag = context.getDbOperationResult().getEtag();
if (oldData != null) {
DAOUtils.restoreDocument(coll, oldData.get("_id"), context.getShardKey(), oldData, newEtag);
if (oldData.get("$set") != null && oldData.get("$set").isDocument() && oldData.get("$set").asDocument().get("_etag") != null) {
exchange.getResponseHeaders().put(Headers.ETAG, oldData.get("$set").asDocument().get("_etag").asObjectId().getValue().toString());
} else {
exchange.getResponseHeaders().remove(Headers.ETAG);
}
} else {
Object newId = context.getDbOperationResult().getNewData().get("_id");
coll.deleteOne(and(eq("_id", newId), eq("_etag", newEtag)));
}
ResponseHelper.endExchangeWithMessage(exchange, context, HttpStatus.SC_BAD_REQUEST, "request check failed");
next(exchange, context);
return;
}
}
next(exchange, context);
} |
|
71 | public List<String> tables(){
List<String> tables = new ArrayList<>();
for (DaoDescriptor descriptor : descriptorsSet) {
tables.add(createRegularTableSql(descriptor));
}
return tables;
} | public List<String> tables(){
return descriptorsSet.stream().map(this::tablesSql).collect(Collectors.toList());
} |
|
72 | private void init(){
MainPanel mainPanel = (MainPanel) parentPanel.getParentPanel().getParentPanel();
Properties uiStylesProperties = mainPanel.getUiStylesProperties();
Properties uiPositionProperties = mainPanel.getUiPositionProperties();
Properties generalProperties = mainPanel.getGeneralProperties();
setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_MAIN_BG_COLOR));
Panel headerPanel = new Panel(ChildName.VideoListPage.MainPanel.TOPICS_HEADING_PANEL.name(), getTopicsHeaderBounds(uiPositionProperties), this, mainPanel);
headerPanel.setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_BG_COLOR));
Label topicsLabel = getTopicsLabel(headerPanel, uiPositionProperties, uiStylesProperties, generalProperties);
headerPanel.addChild(ChildName.General.LABEL.name(), topicsLabel);
addChild(ChildName.VideoListPage.MainPanel.TOPICS_HEADING_PANEL.name(), headerPanel);
initTopics();
} | private void init(){
Properties uiStylesProperties = mainPanel.getUiStylesProperties();
Properties uiPositionProperties = mainPanel.getUiPositionProperties();
Properties generalProperties = mainPanel.getGeneralProperties();
setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_MAIN_BG_COLOR));
Panel headerPanel = new Panel(ChildName.VideoListPage.MainPanel.TOPICS_HEADING_PANEL.name(), getTopicsHeaderBounds(uiPositionProperties), this, mainPanel);
headerPanel.setBackground(PropertyUtil.getColor(uiStylesProperties, UIConstants.Styles.VIDEOLIST_MAIN_PANEL_TOPICS_BG_COLOR));
Label topicsLabel = getTopicsLabel(headerPanel, uiPositionProperties, uiStylesProperties, generalProperties);
headerPanel.addChild(ChildName.General.LABEL.name(), topicsLabel);
addChild(headerPanel);
initTopics();
} |
|
73 | public List<Double> get(@PathParam("userID") String userID, @PathParam("itemID") List<PathSegment> pathSegmentsList) throws OryxServingException{
ALSServingModel model = getALSServingModel();
float[] userFeatures = model.getUserVector(userID);
checkExists(userFeatures != null, userID);
List<Double> results = new ArrayList<>(pathSegmentsList.size());
for (PathSegment pathSegment : pathSegmentsList) {
float[] itemFeatures = model.getItemVector(pathSegment.getPath());
if (itemFeatures == null) {
results.add(0.0);
} else {
double value = VectorMath.dot(itemFeatures, userFeatures);
Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), "Bad estimate");
results.add(value);
}
}
return results;
} | public List<Double> get(@PathParam("userID") String userID, @PathParam("itemID") List<PathSegment> pathSegmentsList) throws OryxServingException{
ALSServingModel model = getALSServingModel();
float[] userFeatures = model.getUserVector(userID);
checkExists(userFeatures != null, userID);
return pathSegmentsList.stream().map(pathSegment -> {
float[] itemFeatures = model.getItemVector(pathSegment.getPath());
if (itemFeatures == null) {
return 0.0;
} else {
double value = VectorMath.dot(itemFeatures, userFeatures);
Preconditions.checkState(!(Double.isInfinite(value) || Double.isNaN(value)), "Bad estimate");
return value;
}
}).collect(Collectors.toList());
} |
|
74 | public void testRemoveParenthesesReturn() throws ParseException{
String code = "public class B{ public boolean bar() { return(true); }}";
DefaultJavaParser parser = new DefaultJavaParser();
CompilationUnit cu = parser.parse(code, false);
CompilationUnit cu2 = parser.parse(code, false);
MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0);
ReturnStmt stmt = (ReturnStmt) md.getBody().getStmts().get(0);
EnclosedExpr expr = (EnclosedExpr) stmt.getExpr();
stmt.replaceChildNode(expr, expr.getInner());
ChangeLogVisitor visitor = new ChangeLogVisitor();
VisitorContext ctx = new VisitorContext();
ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2);
visitor.visit((CompilationUnit) cu, ctx);
List<Action> actions = visitor.getActionsToApply();
Assert.assertEquals(1, actions.size());
assertCode(actions, code, "public class B{ public boolean bar() { return true; }}");
} | public void testRemoveParenthesesReturn() throws ParseException{
String code = "public class B{ public boolean bar() { return(true); }}";
DefaultJavaParser parser = new DefaultJavaParser();
CompilationUnit cu = parser.parse(code, false);
CompilationUnit cu2 = parser.parse(code, false);
MethodDeclaration md = (MethodDeclaration) cu.getTypes().get(0).getMembers().get(0);
ReturnStmt stmt = (ReturnStmt) md.getBody().getStmts().get(0);
EnclosedExpr expr = (EnclosedExpr) stmt.getExpr();
stmt.replaceChildNode(expr, expr.getInner());
List<Action> actions = getActions(cu2, cu);
Assert.assertEquals(1, actions.size());
assertCode(actions, code, "public class B{ public boolean bar() { return true; }}");
} |
|
75 | public int max(int first, int second, int third){
int temp = max(first, second);
int result = max(temp, third);
return result;
} | public int max(int first, int second, int third){
return max(max(first, second), third);
} |
|
76 | public long getTimeForProcessQueue() throws InterruptedException{
long startTime = System.currentTimeMillis();
for (int i = 0; i < countCashboxes; i++) {
Cashbox cashbox = new Cashbox(queue, "cashbox_" + i);
cashbox.start();
threadList.add(cashbox);
}
for (Customer customer : customerList) {
queue.put(customer);
}
for (Cashbox cashbox : threadList) {
cashbox.disable();
}
for (Cashbox cashbox : threadList) {
cashbox.join();
}
return Math.round((System.currentTimeMillis() - startTime) / 1000);
} | public long getTimeForProcessQueue() throws InterruptedException{
long startTime = System.currentTimeMillis();
for (int i = 0; i < countCashboxes; i++) {
Cashbox cashbox = new Cashbox(queue, "cashbox_" + i);
cashbox.start();
threadList.add(cashbox);
}
for (Customer customer : customerList) {
queue.put(customer);
}
threadList.forEach(cb -> cb.disable());
for (Cashbox cashbox : threadList) {
cashbox.join();
}
return Math.round((System.currentTimeMillis() - startTime) / 1000f);
} |
|
77 | public TypeSpec generateView(ViewDesc typeDesc){
final TypeSpec.Builder builder = viewInitialiser.create(typeDesc);
for (final PropertyDesc propertyDesc : typeDesc.getProperties()) {
final JavaDocMethodBuilder javaDocMethodBuilder = docMethod();
if (propertyDesc.getDescription() == null || "".equals(propertyDesc.getDescription())) {
javaDocMethodBuilder.setMethodDescription("Getter for the property $1L.\n");
} else {
javaDocMethodBuilder.setMethodDescription("Getter for the property $1L.\n<p>\n" + propertyDesc.getDescription() + "\n");
}
builder.addMethod(methodBuilder(getAccessorName(propertyDesc.getName())).addJavadoc(javaDocMethodBuilder.setReturnsDescription("the value of $1L").toJavaDoc(), propertyDesc.getName()).addModifiers(ABSTRACT, PUBLIC).returns(getType(propertyDesc)).build());
}
return builder.build();
} | public TypeSpec generateView(ViewDesc typeDesc){
final TypeSpec.Builder builder = viewInitialiser.create(typeDesc);
for (final PropertyDesc propertyDesc : typeDesc.getProperties()) {
builder.addMethod(methodBuilder(getAccessorName(propertyDesc.getName())).addJavadoc(accessorJavadocGenerator.generateJavaDoc(propertyDesc)).addModifiers(ABSTRACT, PUBLIC).returns(getType(propertyDesc)).build());
}
return builder.build();
} |
|
78 | private static void add(ConfigObject config, String prefix, Map<String, String> values){
for (Map.Entry<String, ConfigValue> e : config.entrySet()) {
String nextPrefix = prefix + "." + e.getKey();
ConfigValue value = e.getValue();
switch(value.valueType()) {
case OBJECT:
add((ConfigObject) value, nextPrefix, values);
break;
case NULL:
break;
default:
values.put(nextPrefix, String.valueOf(value.unwrapped()));
}
}
} | private static void add(ConfigObject config, String prefix, Map<String, String> values){
config.forEach((key, value) -> {
String nextPrefix = prefix + "." + key;
switch(value.valueType()) {
case OBJECT:
add((ConfigObject) value, nextPrefix, values);
break;
case NULL:
break;
default:
values.put(nextPrefix, String.valueOf(value.unwrapped()));
}
});
} |
|
79 | public Integer decrypt(IntegerWrapper message){
Integer value = message.getEncryptedValue();
boolean isNegative = value < 0;
int[] values = getInts(value, isNegative);
NumberComposer composer = new NumberComposer(isNegative);
Arrays.stream(values).map(new DigitDecryptor(message.getOneTimePad())).forEach(composer);
return composer.getInteger();
} | public Integer decrypt(IntegerWrapper message){
Integer value = message.getEncryptedValue();
NumberComposer composer = digitStreamCipher.decrypt(value.toString(), message.getOneTimePad());
return composer.getInteger();
} |
|
80 | public String showInactiveBugs(Model theModel, @RequestParam("page") Optional<Integer> page, @RequestParam("size") Optional<Integer> size){
String myUserName;
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
myUserName = ((UserDetails) principal).getUsername();
} else {
myUserName = principal.toString();
}
int currentPage = page.orElse(1);
int pageSize = size.orElse(15);
Page<Bug> inactiveBugPage = bugService.findPaginatedUserInactiveBugs(PageRequest.of(currentPage - 1, pageSize), myUserName);
theModel.addAttribute("inactiveBugPage", inactiveBugPage);
int totalPages = inactiveBugPage.getTotalPages();
if (totalPages > 0) {
List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList());
theModel.addAttribute("pageNumbers", pageNumbers);
}
List<Bug> myBugList = bugService.getListOfInactiveBugsForUser(myUserName);
List<String> listOfApplicableProjectNames = new ArrayList<>();
for (Bug bug : myBugList) {
Project project = projectService.getProjectById(bug.getProjectId());
String projectName = project.getProjectName();
listOfApplicableProjectNames.add(projectName);
}
theModel.addAttribute("projectNames", listOfApplicableProjectNames);
return "inactiveBugsPage";
} | public String showInactiveBugs(Model theModel, @RequestParam("page") Optional<Integer> page, @RequestParam("size") Optional<Integer> size){
UserUtility userUtility = new UserUtility();
int currentPage = page.orElse(1);
int pageSize = size.orElse(15);
Page<Bug> inactiveBugPage = bugService.findPaginatedUserInactiveBugs(PageRequest.of(currentPage - 1, pageSize), userUtility.getMyUserName());
theModel.addAttribute("inactiveBugPage", inactiveBugPage);
int totalPages = inactiveBugPage.getTotalPages();
if (totalPages > 0) {
List<Integer> pageNumbers = IntStream.rangeClosed(1, totalPages).boxed().collect(Collectors.toList());
theModel.addAttribute("pageNumbers", pageNumbers);
}
List<Bug> myBugList = bugService.getListOfInactiveBugsForUser(userUtility.getMyUserName());
List<String> listOfApplicableProjectNames = new ArrayList<>();
for (Bug bug : myBugList) {
Project project = projectService.getProjectById(bug.getProjectId());
String projectName = project.getProjectName();
listOfApplicableProjectNames.add(projectName);
}
theModel.addAttribute("projectNames", listOfApplicableProjectNames);
return "inactiveBugsPage";
} |
|
81 | public Object getMethodValue(EntityBean bean, String fieldName){
try {
Method m = bean.getClass().getMethod(getString + fieldName);
return m.invoke(bean);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
log.error(ex.getMessage());
}
return null;
} | public Object getMethodValue(EntityBean bean, String fieldName){
try {
Method m = bean.getClass().getMethod(getString + fieldName);
return m.invoke(bean);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
}
return null;
} |
|
82 | static int rob(int[] nums, int s, int e){
int p1 = nums[s];
int p2 = p1;
if (0 < e - s)
p2 = Math.max(p1, nums[s + 1]);
for (int i = s + 2; i <= e; i++) {
final int tmp = p1 + nums[i];
p1 = p2;
p2 = Math.max(tmp, p2);
}
return p2;
} | static int rob(int[] nums, int s, int e){
int p1 = 0;
int p2 = 0;
for (int i = s; i <= e; i++) {
final int tmp = p1 + nums[i];
p1 = p2;
p2 = Math.max(tmp, p2);
}
return p2;
} |
|
83 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
if (!isExecution(method)) {
return method.invoke(delegate, args);
}
Subsegment subsegment = createSubsegment();
if (subsegment == null) {
try {
return method.invoke(delegate, args);
} catch (Throwable t) {
if (t instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException) t;
if (ite.getTargetException() != null) {
throw ite.getTargetException();
}
if (ite.getCause() != null) {
throw ite.getCause();
}
}
throw t;
}
}
logger.debug("Invoking statement execution with X-Ray tracing.");
try {
return method.invoke(delegate, args);
} catch (Throwable t) {
if (t instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException) t;
if (ite.getTargetException() != null) {
subsegment.addException(ite.getTargetException());
throw ite.getTargetException();
}
if (ite.getCause() != null) {
subsegment.addException(ite.getCause());
throw ite.getCause();
}
subsegment.addException(ite);
throw ite;
}
subsegment.addException(t);
throw t;
} finally {
AWSXRay.endSubsegment();
}
} | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
Subsegment subsegment = null;
if (isExecution(method)) {
subsegment = createSubsegment();
}
logger.debug(String.format("Invoking statement execution with X-Ray tracing. Tracing active: %s", subsegment != null));
try {
return method.invoke(delegate, args);
} catch (Throwable t) {
Throwable rootThrowable = t;
if (t instanceof InvocationTargetException) {
InvocationTargetException ite = (InvocationTargetException) t;
if (ite.getTargetException() != null) {
rootThrowable = ite.getTargetException();
} else if (ite.getCause() != null) {
rootThrowable = ite.getCause();
}
}
if (subsegment != null) {
subsegment.addException(rootThrowable);
}
throw rootThrowable;
} finally {
if (isExecution(method)) {
AWSXRay.endSubsegment();
}
}
} |
|
84 | public int getDamageOutput(){
triggerValue = 0.3;
if (fighter.getHp() <= fighter.getInitialHp() * triggerValue)
return fighter.calculateEquipmentDamageOutput() * damageMultiplier;
return fighter.calculateEquipmentDamageOutput();
} | public int getDamageOutput(){
if (fighter.getHp() <= fighter.getInitialHp() * triggerValue)
return fighter.calculateEquipmentDamageOutput() * damageMultiplier;
return fighter.calculateEquipmentDamageOutput();
} |
|
85 | private static void loadProperties(File propertiesFile, Properties properties) throws IOException{
InputStream inStream = new FileInputStream(propertiesFile);
try {
properties.load(inStream);
} finally {
inStream.close();
}
} | private static void loadProperties(File propertiesFile, Properties properties) throws IOException{
try (InputStream inStream = new FileInputStream(propertiesFile)) {
properties.load(inStream);
}
} |
|
86 | public void run() throws InterruptedException{
EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(String.format("%s-boss", name)));
EventLoopGroup workerGroup = new NioEventLoopGroup(10, new DefaultThreadFactory(String.format("%s-worker", name)));
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(channelHandler);
}
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = serverBootstrap.bind(port).sync();
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
} | public void run() throws InterruptedException{
EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory(String.format("%s-boss", name)));
EventLoopGroup workerGroup = new NioEventLoopGroup(10, new DefaultThreadFactory(String.format("%s-worker", name)));
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(channelInitializer).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture future = serverBootstrap.bind(port).sync();
future.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
} |
|
87 | public User getUser(Observer observer){
User user = (User) observer;
return user;
} | public User getUser(Observer observer){
return (User) observer;
} |
|
88 | public void generate(Long shiftId, LocalDate from, LocalDate to, int offset){
logger.debug("Starting schedule generation for shift id={} from={} to={} with offset={}", shiftId, from, to, offset);
var shift = shiftRepository.findById(shiftId).orElseThrow();
var pattern = shiftPatternRepository.findById(shift.getPatternId()).orElseThrow();
var holidays = holidayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to);
var compositions = shiftCompositionRepository.findAllByShiftIdAndToGreaterThanEqualAndFromLessThanEqual(shiftId, from, to);
var extraWeekends = extraWeekendRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to);
var extraWorkDays = extraWorkDayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to);
logger.debug("Data for generation:\r\n" + "Shift: {}\r\n" + "Pattern: {}\r\n" + "Compositions: {}\r\n" + "Holidays: {}\r\n" + "ExtraWeekends: {}\r\n" + "ExtraWorkDays: {}", shift, pattern, compositions, holidays, extraWeekends, extraWorkDays);
var workDays = generateSchedule(from, to, offset, pattern, holidays, compositions, extraWeekends, extraWorkDays);
logger.debug("Saving generated schedule to database...");
scheduleRepository.saveAll(workDays);
} | public void generate(Long shiftId, LocalDate from, LocalDate to, int offset){
logger.debug("Starting schedule generation for shift id={} from={} to={} with offset={}", shiftId, from, to, offset);
var shift = shiftRepository.findById(shiftId).orElseThrow();
var holidays = holidayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to);
var compositions = shiftCompositionRepository.findAllByShiftIdAndToGreaterThanEqualAndFromLessThanEqual(shiftId, from, to);
var extraWeekends = extraWeekendRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to);
var extraWorkDays = extraWorkDayRepository.findAllByEnterpriseIdAndDateBetween(shift.getDepartmentId(), from, to);
logger.debug("Data for generation:\r\n" + "Shift: {}\r\n" + "Compositions: {}\r\n" + "Holidays: {}\r\n" + "ExtraWeekends: {}\r\n" + "ExtraWorkDays: {}", shift, compositions, holidays, extraWeekends, extraWorkDays);
var workDays = generateSchedule(from, to, offset, shift, holidays, compositions, extraWeekends, extraWorkDays);
logger.debug("Saving generated schedule to database...");
scheduleRepository.saveAll(workDays);
} |
|
89 | public void testSelectRequest_Query_Filter(){
@SuppressWarnings("unchecked")
MultivaluedMap<String, String> params = mock(MultivaluedMap.class);
when(params.getFirst("query")).thenReturn("Bla");
when(params.getFirst(SenchaRequestParser.FILTER)).thenReturn("[{\"property\":\"name\",\"value\":\"xyz\"}]");
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(params);
ResourceEntity<E2> resourceEntity = parser.parseSelect(getLrEntity(E2.class), uriInfo, E2.NAME.getName());
assertNotNull(resourceEntity.getQualifier());
assertEquals(exp("name likeIgnoreCase 'Bla%' and name likeIgnoreCase 'xyz%'"), resourceEntity.getQualifier());
} | public void testSelectRequest_Query_Filter(){
@SuppressWarnings("unchecked")
MultivaluedMap<String, String> params = mock(MultivaluedMap.class);
when(params.get("query")).thenReturn(Collections.singletonList("Bla"));
when(params.get(SenchaRequestParser.FILTER)).thenReturn(Collections.singletonList("[{\"property\":\"name\",\"value\":\"xyz\"}]"));
ResourceEntity<E2> resourceEntity = parser.parseSelect(getLrEntity(E2.class), params, E2.NAME.getName());
assertNotNull(resourceEntity.getQualifier());
assertEquals(exp("name likeIgnoreCase 'Bla%' and name likeIgnoreCase 'xyz%'"), resourceEntity.getQualifier());
} |
|
90 | public boolean estDansUnGarage(){
if (myStationnements.size() != 0) {
Stationnement dernierStationnement = myStationnements.get(myStationnements.size() - 1);
return dernierStationnement.estEnCours();
} else {
return false;
}
} | public boolean estDansUnGarage(){
if (myStationnements.size() != 0) {
Stationnement dernierStationnement = myStationnements.get(myStationnements.size() - 1);
return dernierStationnement.estEnCours();
}
return false;
} |
|
91 | public static int fib(int n){
if (n < 2)
return n;
final int[] fibSeries = new int[2];
fibSeries[0] = 0;
fibSeries[1] = 1;
for (int i = 2; i <= n; i++) {
final int f = fibSeries[0] + fibSeries[1];
fibSeries[0] = fibSeries[1];
fibSeries[1] = f;
}
return fibSeries[1];
} | public static int fib(int n){
if (n < 2)
return n;
int beforePrev = 0;
int prev = 1;
for (int i = 2; i <= n; i++) {
final int tmp = beforePrev + prev;
beforePrev = prev;
prev = tmp;
}
return prev;
} |
|
92 | public int getProductOfTwo(){
Map<Integer, Integer> map = numbers.stream().collect(Collectors.toMap(n -> n, n -> n));
for (int i = 0; i < numbers.size(); i++) {
Integer currentNum = numbers.get(i);
Integer otherNum = map.get(2020 - currentNum);
if (otherNum != null) {
System.out.println("this num = " + currentNum);
System.out.println("other num = " + otherNum);
int result = otherNum * currentNum;
System.out.println("result = " + result);
return result;
}
}
return -1;
} | public int getProductOfTwo(){
Map<Integer, Integer> map = numbers.stream().collect(Collectors.toMap(n -> n, n -> n));
for (Integer currentNum : numbers) {
Integer otherNum = map.get(2020 - currentNum);
if (otherNum != null) {
System.out.println("this num = " + currentNum);
System.out.println("other num = " + otherNum);
int result = otherNum * currentNum;
System.out.println("result = " + result);
return result;
}
}
return -1;
} |
|
93 | public void encodeJson(StringBuffer sb){
sb.append("{");
sb.append("\"code\": \"");
sb.append(getCode());
sb.append("\", ");
sb.append("\"color\": \"");
sb.append(getColor());
sb.append("\", ");
if (getSize() != null) {
sb.append("\"size\": \"");
sb.append(getSize());
sb.append("\", ");
}
sb.append("\"price\": ");
sb.append(getPrice());
sb.append(", ");
sb.append("\"currency\": \"");
sb.append(getCurrency());
sb.append("\"}");
} | public void encodeJson(StringBuffer sb){
sb.append("{");
ToJson.appendFieldTo(sb, "code", getCode());
ToJson.appendFieldTo(sb, "color", getColor().toString());
if (getSize() != null) {
ToJson.appendFieldTo(sb, "size", getSize().toString());
}
sb.append("\"price\": ");
sb.append(getPrice());
sb.append(", ");
ToJson.appendFieldTo(sb, "currency", getCurrency());
sb.delete(sb.length() - 2, sb.length());
sb.append("}");
} |
|
94 | public String toString(){
if (html == null || html.isEmpty()) {
return "No data parsed yet";
} else {
return getHtml();
}
} | public String toString(){
return (html == null || html.isEmpty()) ? "No data parsed yet" : getHtml();
} |
|
95 | private PlaceArmy generatePlaceArmyOrder(Adjutant adjutant, Game game){
_log.info(" ----- generate place army order -----");
if (_placementsToMake == null) {
_log.info(" computing placements ");
_placementsToMake = computePlacements(game);
}
Map.Entry<Country, Integer> entry = new ArrayList<>(_placementsToMake.entrySet()).get(0);
PlaceArmy order = new PlaceArmy(adjutant, entry.getKey(), entry.getValue());
_placementsToMake.remove(entry.getKey());
return order;
} | private PlaceArmy generatePlaceArmyOrder(Adjutant adjutant, Game game){
if (_placementsToMake == null) {
_placementsToMake = computePlacements(game);
}
Map.Entry<Country, Integer> entry = new ArrayList<>(_placementsToMake.entrySet()).get(0);
PlaceArmy order = new PlaceArmy(adjutant, entry.getKey(), entry.getValue());
_placementsToMake.remove(entry.getKey());
return order;
} |
|
96 | public void add(TransactionBean transactionBean){
Date transactionTime = transactionBean.getTimestamp();
Calendar calendar = Calendar.getInstance();
calendar.setTime(transactionTime);
int transactionSecond = calendar.get(Calendar.SECOND);
StatisticBean statistic = statistics.get(transactionSecond);
Date currentDate = new Date();
long diff = getDateDiffInSeconds(currentDate, statistic.getLastAddedTime());
if (diff <= TRANSACTION_SECONDS) {
double sum = statistic.getSum() + transactionBean.getAmount();
double min = Math.min(statistic.getMin(), transactionBean.getAmount());
double max = Math.max(statistic.getMax(), transactionBean.getAmount());
int count = statistic.getCount() + 1;
statistic.setSum(sum);
statistic.setMin(min);
statistic.setMax(max);
statistic.setCount(count);
} else {
double amount = transactionBean.getAmount();
StatisticBean statisticBean = statistics.get(transactionSecond);
statisticBean.setMax(amount);
statisticBean.setMin(amount);
statisticBean.setSum(amount);
statisticBean.setCount(1);
statisticBean.setLastAddedTime(currentDate);
}
} | public void add(TransactionBean transactionBean){
Date transactionTime = transactionBean.getTimestamp();
Calendar calendar = Calendar.getInstance();
calendar.setTime(transactionTime);
int transactionSecond = calendar.get(Calendar.SECOND);
StatisticBean statisticBean = statistics.get(transactionSecond);
Date currentDate = new Date();
long diff = getDateDiffInSeconds(currentDate, statisticBean.getLastAddedTime());
if (diff <= TRANSACTION_SECONDS) {
updateStatisticData(statisticBean, transactionBean);
} else {
initStatisticData(transactionSecond, transactionBean);
}
} |
|
97 | private static int decodeTuple(TupleType tupleType, byte[] buffer, final int idx_, int end, Object[] parentElements, int pei){
final ABIType<?>[] elementTypes = tupleType.elementTypes;
final int len = elementTypes.length;
final Object[] elements = new Object[len];
int idx = end;
Integer mark = null;
for (int i = len - 1; i >= 0; i--) {
final ABIType<?> type = elementTypes[i];
if (type.dynamic) {
mark = i;
break;
}
if (type.typeCode() == TYPE_CODE_ARRAY) {
final ArrayType<? extends ABIType<?>, ?> arrayType = (ArrayType<? extends ABIType<?>, ?>) type;
end = idx -= (arrayType.elementType.byteLengthPacked(null) * arrayType.length);
decodeArray(arrayType, buffer, idx, end, elements, i);
} else if (type.typeCode() == TYPE_CODE_TUPLE) {
TupleType inner = (TupleType) type;
int innerLen = inner.byteLengthPacked(null);
end = idx -= decodeTupleStatic(inner, buffer, idx - innerLen, end, elements, i);
} else {
end = idx -= decode(elementTypes[i], buffer, idx - type.byteLengthPacked(null), end, elements, i);
}
}
if (mark != null) {
final int m = mark;
idx = idx_;
for (int i = 0; i <= m; i++) {
idx += decode(elementTypes[i], buffer, idx, end, elements, i);
}
}
Tuple t = new Tuple(elements);
parentElements[pei] = t;
return tupleType.byteLengthPacked(t);
} | private static int decodeTuple(TupleType tupleType, byte[] buffer, final int idx_, int end, Object[] parentElements, int pei){
final ABIType<?>[] elementTypes = tupleType.elementTypes;
final int len = elementTypes.length;
final Object[] elements = new Object[len];
int mark = -1;
for (int i = len - 1; i >= 0; i--) {
final ABIType<?> type = elementTypes[i];
if (type.dynamic) {
mark = i;
break;
}
final int typeCode = type.typeCode();
if (TYPE_CODE_ARRAY == typeCode) {
final ArrayType<? extends ABIType<?>, ?> arrayType = (ArrayType<? extends ABIType<?>, ?>) type;
end -= (arrayType.elementType.byteLengthPacked(null) * arrayType.length);
decodeArray(arrayType, buffer, end, end, elements, i);
} else if (TYPE_CODE_TUPLE == typeCode) {
TupleType inner = (TupleType) type;
int innerLen = inner.byteLengthPacked(null);
end -= decodeTupleStatic(inner, buffer, end - innerLen, end, elements, i);
} else {
end -= decode(elementTypes[i], buffer, end - type.byteLengthPacked(null), end, elements, i);
}
}
if (mark > -1) {
int idx = idx_;
for (int i = 0; i <= mark; i++) {
idx += decode(elementTypes[i], buffer, idx, end, elements, i);
}
}
Tuple t = new Tuple(elements);
parentElements[pei] = t;
return tupleType.byteLengthPacked(t);
} |
|
98 | public BookRecord createBookRecord(BookRecord bookRecord, String isbn, Integer userCode){
Book book = bookRepository.findBookByIsbn(isbn);
User user = userRepository.findByUserCode(userCode);
if (book == null) {
throw new ResourceNotFoundException("Book with ISBN " + isbn + " does not exist");
} else if (user == null) {
throw new ResourceNotFoundException("User with code #" + userCode + " does not exist");
} else if (!book.getIsAvailable()) {
throw new ResourceNotCreatedException("Book is not available");
} else if (user.getBorrowedBooks() >= Constants.MAX_RENEWALS) {
throw new ResourceNotCreatedException("User has already borrow 3 books");
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date currentDate = new Date();
dateFormat.format(currentDate);
Calendar c = Calendar.getInstance();
c.setTime(currentDate);
c.add(Calendar.DATE, 7);
Date currentDataPlusSeven = c.getTime();
bookRecord.setDueDate(currentDataPlusSeven);
bookRecord.setRenewalCont(0);
bookRecord.setIsReturned(false);
bookRecord.setUser(user);
bookRecord.setBook(book);
book.setIsAvailable(false);
user.setBorrowedBooks(user.getBorrowedBooks() + 1);
try {
return bookRecordRepository.save(bookRecord);
} catch (Exception e) {
throw new ResourceNotCreatedException("Invoice #" + bookRecord.getTransaction() + " already exists");
}
} | public BookRecord createBookRecord(BookRecord bookRecord, String isbn, Integer userCode){
Book book = bookRepository.findBookByIsbn(isbn);
User user = userRepository.findByUserCode(userCode);
if (book == null) {
throw new ResourceNotFoundException("Book with ISBN " + isbn + " does not exist");
} else if (user == null) {
throw new ResourceNotFoundException("User with code #" + userCode + " does not exist");
} else if (!book.getIsAvailable()) {
throw new ResourceNotCreatedException("Book is not available");
} else if (user.getBorrowedBooks() >= Constants.MAX_RENEWALS) {
throw new ResourceNotCreatedException("User has already borrow 3 books");
}
Date currentDataPlusSeven = sumSevenDays(new Date());
bookRecord.setDueDate(currentDataPlusSeven);
bookRecord.setRenewalCont(0);
bookRecord.setIsReturned(false);
bookRecord.setUser(user);
bookRecord.setBook(book);
book.setIsAvailable(false);
user.setBorrowedBooks(user.getBorrowedBooks() + 1);
try {
return bookRecordRepository.save(bookRecord);
} catch (Exception e) {
throw new ResourceNotCreatedException("Invoice #" + bookRecord.getTransaction() + " already exists");
}
} |
|
99 | public void deleteCinemaHall(long id) throws SQLException, NotFoundException{
projectionDAO.deleteProjectionsByHallId(id);
try (Connection connection = jdbcTemplate.getDataSource().getConnection();
PreparedStatement ps = connection.prepareStatement(DELETE_CINEMA_HALL_SQL)) {
ps.setLong(1, id);
if (ps.executeUpdate() == 0) {
throw new NotFoundException("Cinema hall was not found.");
}
}
} | public void deleteCinemaHall(long id) throws SQLException, NotFoundException{
projectionDAO.deleteProjectionsByHallId(id);
try (Connection connection = jdbcTemplate.getDataSource().getConnection();
PreparedStatement ps = connection.prepareStatement(DELETE_CINEMA_HALL_SQL)) {
ps.setLong(1, id);
ps.executeUpdate();
}
} |
End of preview. Expand
in Dataset Viewer.
README.md exists but content is empty.
Use the Edit dataset card button to edit it.
- Downloads last month
- 36