hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
81ef718aae17c89cc0c979646348ada26576f8bb | 139 |
public interface IMarket {
void buyPlant(Plants plant, Area area);
void sellPlant (Plants plant, Area area) throws Throwable;
}
| 19.857143 | 60 | 0.719424 |
5b76f67ec88f5ebad6e6a419529facc51f727e4a | 1,856 | /*
* Software Name : IoT for technicians
* Version: 1.0
*
* Copyright (c) 2020 Orange
*
* This software is distributed under the Apache License, Version 2.0,
* the text of which is available at http://www.apache.org/licenses/
* or see the "license.txt" file for more details.
*
*/
package com.company.iotfortechnicians.findmydevice.filter;
import android.content.Context;
import com.company.iotfortechnicians.IOTApplication;
import com.company.iotfortechnicians.R;
import com.company.iotfortechnicians.common.dto.devicemanagement.GroupDTO;
import java.util.List;
import lombok.RequiredArgsConstructor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@RequiredArgsConstructor
public class GroupListCallback implements Callback<List<GroupDTO>> {
private final FilterFragment fragment;
@Override
public void onResponse(Call<List<GroupDTO>> call, Response<List<GroupDTO>> response) {
if (response.isSuccessful()) {
List<GroupDTO> groups = getGroupsWithRootGroupName(response);
fragment.onGroupCallbackResponse(groups);
} else {
fragment.onResponseError(response.code(), response.errorBody());
}
}
@Override
public void onFailure(Call<List<GroupDTO>> call, Throwable t) {
fragment.onFailure(t);
}
private String getRootGroupName() {
Context appContext = IOTApplication.getAppContext();
return appContext.getString(R.string.root_group_name);
}
private List<GroupDTO> getGroupsWithRootGroupName(Response<List<GroupDTO>> response) {
String rootGroupName = getRootGroupName();
List<GroupDTO> groups = response.body();
if (groups != null) {
GroupDTO groupDTO = groups.get(0);
groupDTO.setPathNode(rootGroupName);
}
return groups;
}
}
| 29.460317 | 90 | 0.709591 |
4169f640af624f81322fd1f52a9c7a821df856d7 | 10,329 | /*
* MIT License
*
* Copyright (c) 2021-2022 yangrunkang
*
* Author: yangrunkang
* Email: [email protected]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.upupor.web.page;
import com.upupor.service.business.aggregation.MemberAggregateService;
import com.upupor.service.business.aggregation.service.CommentService;
import com.upupor.service.business.aggregation.service.MemberService;
import com.upupor.service.business.aggregation.service.MessageService;
import com.upupor.service.business.profile.service.ProfileAggregateService;
import com.upupor.framework.CcConstant;
import com.upupor.service.dto.page.MemberIndexDto;
import com.upupor.service.types.ViewTargetType;
import com.upupor.service.utils.PageUtils;
import com.upupor.service.utils.ServletUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.Objects;
import static com.upupor.framework.CcConstant.*;
import static com.upupor.framework.CcConstant.Page.SIZE_COMMENT;
/**
* 用户页面跳转控制器
*
* @author YangRunkang(cruise)
* @date 2020/01/19 12:16
*/
@Slf4j
@Api(tags = "用户页面跳转控制器")
@RestController
@RequiredArgsConstructor
public class MemberPageJumpController {
private final MemberAggregateService memberAggregateService;
private final ProfileAggregateService profileAggregateService;
private final MessageService messageService;
private final CommentService commentService;
private final MemberService memberService;
@ApiOperation("列出所有用户")
@GetMapping("/list-user")
public ModelAndView userList(Integer pageNum, Integer pageSize) {
if (Objects.isNull(pageNum)) {
pageNum = CcConstant.Page.NUM;
}
if (Objects.isNull(pageSize)) {
pageSize = CcConstant.Page.SIZE;
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(USER_LIST);
modelAndView.addObject(memberAggregateService.userList(pageNum, pageSize));
modelAndView.addObject(SeoKey.TITLE, "所有用户");
modelAndView.addObject(SeoKey.DESCRIPTION, "所有用户");
return modelAndView;
}
@ApiOperation("登录")
@GetMapping("/login")
public ModelAndView login() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(USER_LOGIN);
modelAndView.addObject(SeoKey.TITLE, "登录");
modelAndView.addObject(SeoKey.DESCRIPTION, "登录");
return modelAndView;
}
@ApiOperation("注册")
@GetMapping("/register")
public ModelAndView register() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(USER_REGISTER);
// Seo
modelAndView.addObject(SeoKey.TITLE, "注册");
modelAndView.addObject(CcConstant.SeoKey.DESCRIPTION, "注册");
return modelAndView;
}
@ApiOperation("退出登录")
@GetMapping("/logout")
public ModelAndView logout() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(USER_LOGOUT);
// Seo
modelAndView.addObject(SeoKey.TITLE, "退出登录");
modelAndView.addObject(CcConstant.SeoKey.DESCRIPTION, "退出登录");
return modelAndView;
}
@ApiOperation("作者主页-文章")
@GetMapping("/profile/{userId}")
public ModelAndView index(@PathVariable("userId") String userId, Integer pageNum, Integer pageSize, String msgId) {
if (Objects.isNull(pageNum)) {
pageNum = CcConstant.Page.NUM;
}
if (Objects.isNull(pageSize)) {
pageSize = CcConstant.Page.SIZE;
}
if (Objects.nonNull(msgId)) {
messageService.tagMsgRead(msgId);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(AUTHOR_PROFILE);
MemberIndexDto memberIndexDto = profileAggregateService.index(userId, pageNum, pageSize, ViewTargetType.PROFILE_CONTENT);
modelAndView.addObject(memberIndexDto);
modelAndView.addObject(SeoKey.TITLE, memberIndexDto.getMember().getUserName());
modelAndView.addObject(SeoKey.DESCRIPTION, memberIndexDto.getMember().getMemberExtend().getIntroduce());
return modelAndView;
}
@ApiOperation("作者主页-关注")
@GetMapping("/profile/{userId}/attention")
public ModelAndView attetion(@PathVariable("userId") String userId, Integer pageNum, Integer pageSize, String msgId) {
if (Objects.isNull(pageNum)) {
pageNum = CcConstant.Page.NUM;
}
if (Objects.isNull(pageSize)) {
pageSize = CcConstant.Page.SIZE;
}
if (Objects.nonNull(msgId)) {
messageService.tagMsgRead(msgId);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(AUTHOR_ATTENTION);
MemberIndexDto memberIndexDto = profileAggregateService.index(userId, pageNum, pageSize, ViewTargetType.PROFILE_ATTENTION);
modelAndView.addObject(memberIndexDto);
modelAndView.addObject(SeoKey.TITLE, memberIndexDto.getMember().getUserName() + "的关注");
modelAndView.addObject(SeoKey.DESCRIPTION, memberIndexDto.getMember().getMemberExtend().getIntroduce());
return modelAndView;
}
@ApiOperation("作者主页-粉丝")
@GetMapping("/profile/{userId}/fans")
public ModelAndView fans(@PathVariable("userId") String userId, Integer pageNum, Integer pageSize, String msgId) {
if (Objects.isNull(pageNum)) {
pageNum = CcConstant.Page.NUM;
}
if (Objects.isNull(pageSize)) {
pageSize = CcConstant.Page.SIZE;
}
if (Objects.nonNull(msgId)) {
messageService.tagMsgRead(msgId);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(AUTHOR_FANS);
MemberIndexDto memberIndexDto = profileAggregateService.index(userId, pageNum, pageSize, ViewTargetType.PROFILE_FANS);
modelAndView.addObject(memberIndexDto);
modelAndView.addObject(SeoKey.TITLE, memberIndexDto.getMember().getUserName() + "的粉丝");
modelAndView.addObject(SeoKey.DESCRIPTION, memberIndexDto.getMember().getMemberExtend().getIntroduce());
return modelAndView;
}
@ApiOperation("作者主页-电台")
@GetMapping("/profile/{userId}/radio")
public ModelAndView indexRadio(@PathVariable("userId") String userId, Integer pageNum, Integer pageSize, String msgId) {
if (Objects.isNull(pageNum)) {
pageNum = CcConstant.Page.NUM;
}
if (Objects.isNull(pageSize)) {
pageSize = CcConstant.Page.SIZE;
}
if (Objects.nonNull(msgId)) {
messageService.tagMsgRead(msgId);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(AUTHOR_RADIO);
MemberIndexDto memberIndexDto = profileAggregateService.index(userId, pageNum, pageSize, ViewTargetType.PROFILE_RADIO);
modelAndView.addObject(memberIndexDto);
modelAndView.addObject(SeoKey.TITLE, memberIndexDto.getMember().getUserName());
modelAndView.addObject(SeoKey.DESCRIPTION, memberIndexDto.getMember().getMemberExtend().getIntroduce());
return modelAndView;
}
@ApiOperation("作者主页-留言板")
@GetMapping("/profile-message/{userId}")
public ModelAndView profileMessage(@PathVariable("userId") String userId, Integer pageNum, Integer pageSize, String msgId) {
if (Objects.isNull(pageNum)) {
// 获取最新的评论
Integer count = commentService.countByTargetId(userId);
pageNum = PageUtils.calcMaxPage(count, SIZE_COMMENT);
}
if (Objects.isNull(pageSize)) {
pageSize = CcConstant.Page.SIZE_COMMENT;
}
if (Objects.nonNull(msgId)) {
messageService.tagMsgRead(msgId);
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName(AUTHOR_MESSAGE);
MemberIndexDto memberIndexDto = profileAggregateService.index(userId, pageNum, pageSize, ViewTargetType.PROFILE_MESSAGE);
modelAndView.addObject(memberIndexDto);
modelAndView.addObject(SeoKey.TITLE, memberIndexDto.getMember().getUserName() + "留言板");
modelAndView.addObject(SeoKey.DESCRIPTION, memberIndexDto.getMember().getMemberExtend().getIntroduce());
return modelAndView;
}
@ApiOperation("退订邮件")
@GetMapping("unsubscribe-mail")
@ResponseBody
public ModelAndView unSubscribeMail() {
String result = "result";
ModelAndView modelAndView = new ModelAndView();
String userId = ServletUtils.getUserId();
Boolean success = memberService.unSubscribeMail(userId);
modelAndView.addObject(result, success);
modelAndView.setViewName(UNSUBSCRIBE_MAIL);
modelAndView.addObject(SeoKey.TITLE, "退订邮件通知");
modelAndView.addObject(SeoKey.DESCRIPTION, "退订,邮件");
return modelAndView;
}
}
| 38.977358 | 131 | 0.70578 |
4833b8b19808809d3af23baa9d57abbb31f0a33f | 3,818 | package org.open.covid19.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 日期工具
* @author wuchao
*/
public class DateUtil {
public static final String FORMAT_TZ = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String FORMAT_TZ000 = "yyyy-MM-dd'T'HH:mm:ss.000'Z'";
public static final String FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
/**
* `yyyy-MM-dd`格式转换为UTC时间
* @param localTime
* @return
*/
public static Date localToUTC(String localTime) {
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT_YYYY_MM_DD);
Date localDate= null;
try {
localDate = sdf.parse(localTime);
} catch (ParseException e) {
e.printStackTrace();
}
long localTimeInMillis=localDate.getTime();
/** long时间转换成Calendar */
Calendar calendar= Calendar.getInstance();
calendar.setTimeInMillis(localTimeInMillis);
/** 取得时间偏移量 */
int zoneOffset = calendar.get(java.util.Calendar.ZONE_OFFSET);
/** 取得夏令时差 */
int dstOffset = calendar.get(java.util.Calendar.DST_OFFSET);
/** 从本地时间里扣除这些差量,即可以取得UTC时间*/
calendar.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
/** 取得的时间就是UTC标准时间 */
Date utcDate=new Date(calendar.getTimeInMillis());
return utcDate;
}
/**
* `yyyy-MM-dd`格式时间转换为`yyyy-MM-dd'T'HH:mm:ss'Z'`格式的时间
* @param dateStr
* @return
*/
public static String local2tz(String dateStr) {
String format = "";
try {
Date localDate = new SimpleDateFormat(FORMAT_YYYY_MM_DD).parse(dateStr);
format = new SimpleDateFormat(FORMAT_TZ).format(localDate);
} catch (ParseException e) {
e.printStackTrace();
}
return format;
}
/**
* 格式化日期
* @param date
* @return
*/
public static String local2tz(Date date) {
if (null == date) {
return "";
}
return new SimpleDateFormat(FORMAT_TZ).format(date);
}
/**
* 格式化日期,例如从 M/d/yy 转为 yyyy-MM-dd
* @param dateStr 日期时间
* @param fromFormat 源格式
* @param toFormat 期望格式
* @return
*/
public static String format(String dateStr, String fromFormat, String toFormat){
try {
Date date = new SimpleDateFormat(fromFormat).parse(dateStr);
return new SimpleDateFormat(toFormat).format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
/**
* 格式化日期:yyyy-MM-dd
* @param date
* @return
*/
public static String local2yyyMMdd(Date date){
if (null == date) return "";
return new SimpleDateFormat("yyyy-MM-dd").format(date);
}
/**
* 指定日期距离现在几天,不足一天算为0。(取绝对值)。
* 例如:昨天0点到今天15点算1天
* @param date
* @return
*/
public static int howManyDaysFromNow(Date date) {
if (null==date) return 0;
long current = System.currentTimeMillis();
long past = date.getTime();
// 绝对值
long residue = Math.abs(current - past);
long days = residue / (1000 * 60 * 60 * 24);
System.out.println("days:" + days);
return (int) (residue / (1000 * 60 * 60 * 24));
}
/**
* 字符串转为Date类型
* @param dateStr
* @return
*/
public static Date stringToDate(String dateStr) {
if(dateStr ==null || "".equals(dateStr)){
return null;
}
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
date = df.parse(dateStr);
} catch (ParseException e) {
}
return date;
}
}
| 27.868613 | 84 | 0.573337 |
857c7efc5bbfe1506edfc691dc788386602d8eb7 | 1,077 | package tech.ibit.structlog4j.test;
import lombok.experimental.UtilityClass;
import org.slf4j.event.Level;
import org.slf4j.impl.LogEntry;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* 测试工具类
*
* @author IBIT程序猿
*/
@UtilityClass
public class TestUtils {
/**
* 消息断言
*
* @param entries 异常实体
* @param entryIndex 异常索引
* @param expectedLevel 期望日志级别
* @param expectedMessage 期望消息
* @param expectedThrowablePresent 期望异常是否出现
*/
public void assertMessage(List<LogEntry> entries, int entryIndex
, Level expectedLevel, String expectedMessage, boolean expectedThrowablePresent) {
assertEquals(entries.toString(), expectedLevel, entries.get(entryIndex).getLevel());
assertEquals(entries.toString(), expectedMessage, entries.get(entryIndex).getMessage());
assertTrue(entries.toString(), entries.get(entryIndex).getThrowable().isPresent() == expectedThrowablePresent);
}
}
| 29.108108 | 119 | 0.684308 |
aa26944c1829f9e62fc500b404f8ab72bbdb89a9 | 2,030 | /**
* Copyright (C) 2015 Fernando Cejas Open Source Project
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wm4n.boilerplate.domain.feature.restaurant.interactor;
import com.wm4n.boilerplate.domain.UseCase;
import com.wm4n.boilerplate.domain.executor.PostExecutionThread;
import com.wm4n.boilerplate.domain.executor.ThreadExecutor;
import com.wm4n.boilerplate.domain.feature.restaurant.model.Restaurant;
import com.wm4n.boilerplate.domain.feature.restaurant.repository.RestaurantRepository;
import javax.inject.Inject;
import io.reactivex.Observable;
/**
* This class is an implementation of {@link UseCase} that represents a use case for
* retrieving data related to an specific {@link Restaurant}.
*/
public class GetRestaurantDetails extends UseCase<Restaurant, GetRestaurantDetails.Params> {
private final RestaurantRepository repository;
@Inject
GetRestaurantDetails(RestaurantRepository repository, ThreadExecutor threadExecutor,
PostExecutionThread postExecutionThread) {
super(threadExecutor, postExecutionThread);
this.repository = repository;
}
@Override
protected Observable<Restaurant> buildUseCaseObservable(Params params) {
checkNotNull(params);
return this.repository.getRestaurant(params.id);
}
public static final class Params {
private final String id;
private Params(String id) {
this.id = id;
}
public static Params forRestaurant(String id) {
return new Params(id);
}
}
}
| 32.741935 | 92 | 0.757635 |
c618db60c1e06260bc313437f5962f0006853a15 | 1,225 | package me.donglin.leetcode.hard;
import org.junit.Assert;
import org.junit.Test;
/**
* 1014. 最佳观光组合
* 给定正整数数组 A,A[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i。
* 一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i - j):景点的评分之和减去它们两者之间的距离。
* 返回一对观光景点能取得的最高分。
*
* 示例:
* 输入:[8,1,5,2,6]
* 输出:11
* 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11
*
*
* 提示:
* 2 <= A.length <= 50000
* 1 <= A[i] <= 1000
*
* @author donglin
* @since 2020-06-17
*/
public class MaxScoreSightseeingPair {
@Test
public void case1() {
Assert.assertEquals(11, maxScoreSightseeingPair(new int[]{8,1,5,2,6}));
Assert.assertEquals(3, maxScoreSightseeingPair(new int[]{2, 2}));
Assert.assertEquals(10, maxScoreSightseeingPair(new int[]{3, 1, 1, 1, 1, 10}));
Assert.assertEquals(11, maxScoreSightseeingPair(new int[]{6, 1, 1, 1, 1, 10}));
}
private int maxScoreSightseeingPair(int[] A) {
int maxScore = 0;
// 表示 max(后面的数-距离)
int maxValue = A[A.length - 1] - 1;
for (int i = A.length - 2; i >= 0; i--) {
maxScore = Math.max(maxScore, maxValue + A[i]);
maxValue = Math.max(maxValue , A[i]) - 1;
}
return maxScore;
}
}
| 26.06383 | 87 | 0.564082 |
9ce199df230f62c8091ab7d39f1773ac0a03ef9d | 441 | package com.example;
import javax.annotation.Generated;
import javax.annotation.Nonnull;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsNonNull;
/**
* Callback has both return type and argument as enums.
*/
@Generated("org.realityforge.webtack")
@JsFunction
@FunctionalInterface
public interface SomeCallbackHandler {
@SpeechRecognitionErrorCode
@JsNonNull
String onInvoke(@TxMode @Nonnull String blah);
}
| 23.210526 | 55 | 0.804989 |
acc0b84f6d16b4ea75c4def44aae9ecb0dbe833e | 1,922 | package usc.cs310.ProEvento.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import usc.cs310.ProEvento.model.Tag;
import java.util.Collections;
import java.util.List;
@Repository
public class TagDao {
@Autowired
private SessionFactory sessionFactory;
public boolean createTag(Tag tag) {
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
session.saveOrUpdate(tag);
session.getTransaction().commit();
return true;
} catch (Exception e) {
e.printStackTrace();
if (session != null) {
session.getTransaction().rollback();
}
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public Tag selectTagById(long tagId) {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
Tag tag = (Tag) session.get(Tag.class, tagId);
session.getTransaction().commit();
return tag;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<Tag> selectAllTags() {
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
Query query = session.createQuery("FROM Tag");
List<Tag> tags= (List<Tag>) query.list();
session.getTransaction().commit();
return tags;
} catch (Exception e) {
e.printStackTrace();
return Collections.emptyList();
}
}
public boolean updateTag(Tag tag) {
return createTag(tag);
}
}
| 28.686567 | 62 | 0.583767 |
ee7b79219b14ef493a10314ea56e5ef6fd50e98e | 8,614 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.complete.game;
import java.util.HashMap;
import java.util.Map;
import org.apache.avro.reflect.Nullable;
import org.apache.beam.examples.complete.game.utils.WriteToText;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.coders.AvroCoder;
import org.apache.beam.sdk.coders.DefaultCoder;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.metrics.Counter;
import org.apache.beam.sdk.metrics.Metrics;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.MapElements;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.Sum;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.apache.beam.sdk.values.TypeDescriptors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is the first in a series of four pipelines that tell a story in a 'gaming' domain.
* Concepts: batch processing, reading input from text files, writing output to
* text files, using standalone DoFns, use of the sum per key transform, and use of
* Java 8 lambda syntax.
*
* <p>In this gaming scenario, many users play, as members of different teams, over the course of a
* day, and their actions are logged for processing. Some of the logged game events may be late-
* arriving, if users play on mobile devices and go transiently offline for a period.
*
* <p>This pipeline does batch processing of data collected from gaming events. It calculates the
* sum of scores per user, over an entire batch of gaming data (collected, say, for each day). The
* batch processing will not include any late data that arrives after the day's cutoff point.
*
* <p>To execute this pipeline, specify the pipeline configuration like this:
* <pre>{@code
* --tempLocation=YOUR_TEMP_DIRECTORY
* --runner=YOUR_RUNNER
* --output=YOUR_OUTPUT_DIRECTORY
* (possibly options specific to your runner or permissions for your temp/output locations)
* }
* </pre>
*
* <p>Optionally include the --input argument to specify a batch input file.
* See the --input default value for example batch data file, or use {@code injector.Injector} to
* generate your own batch data.
*/
public class UserScore {
/**
* Class to hold info about a game event.
*/
@DefaultCoder(AvroCoder.class)
static class GameActionInfo {
@Nullable String user;
@Nullable String team;
@Nullable Integer score;
@Nullable Long timestamp;
public GameActionInfo() {}
public GameActionInfo(String user, String team, Integer score, Long timestamp) {
this.user = user;
this.team = team;
this.score = score;
this.timestamp = timestamp;
}
public String getUser() {
return this.user;
}
public String getTeam() {
return this.team;
}
public Integer getScore() {
return this.score;
}
public String getKey(String keyname) {
if (keyname.equals("team")) {
return this.team;
} else { // return username as default
return this.user;
}
}
public Long getTimestamp() {
return this.timestamp;
}
}
/**
* Parses the raw game event info into GameActionInfo objects. Each event line has the following
* format: username,teamname,score,timestamp_in_ms,readable_time
* e.g.:
* user2_AsparagusPig,AsparagusPig,10,1445230923951,2015-11-02 09:09:28.224
* The human-readable time string is not used here.
*/
static class ParseEventFn extends DoFn<String, GameActionInfo> {
// Log and count parse errors.
private static final Logger LOG = LoggerFactory.getLogger(ParseEventFn.class);
private final Counter numParseErrors = Metrics.counter("main", "ParseErrors");
@ProcessElement
public void processElement(ProcessContext c) {
String[] components = c.element().split(",");
try {
String user = components[0].trim();
String team = components[1].trim();
Integer score = Integer.parseInt(components[2].trim());
Long timestamp = Long.parseLong(components[3].trim());
GameActionInfo gInfo = new GameActionInfo(user, team, score, timestamp);
c.output(gInfo);
} catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
numParseErrors.inc();
LOG.info("Parse error on " + c.element() + ", " + e.getMessage());
}
}
}
/**
* A transform to extract key/score information from GameActionInfo, and sum the scores. The
* constructor arg determines whether 'team' or 'user' info is extracted.
*/
// [START DocInclude_USExtractXform]
public static class ExtractAndSumScore
extends PTransform<PCollection<GameActionInfo>, PCollection<KV<String, Integer>>> {
private final String field;
ExtractAndSumScore(String field) {
this.field = field;
}
@Override
public PCollection<KV<String, Integer>> expand(
PCollection<GameActionInfo> gameInfo) {
return gameInfo
.apply(MapElements
.into(TypeDescriptors.kvs(TypeDescriptors.strings(), TypeDescriptors.integers()))
.via((GameActionInfo gInfo) -> KV.of(gInfo.getKey(field), gInfo.getScore())))
.apply(Sum.<String>integersPerKey());
}
}
// [END DocInclude_USExtractXform]
/**
* Options supported by {@link UserScore}.
*/
public interface Options extends PipelineOptions {
@Description("Path to the data file(s) containing game data.")
// The default maps to two large Google Cloud Storage files (each ~12GB) holding two subsequent
// day's worth (roughly) of data.
@Default.String("gs://apache-beam-samples/game/gaming_data*.csv")
String getInput();
void setInput(String value);
// Set this required option to specify where to write the output.
@Description("Path of the file to write to.")
@Validation.Required
String getOutput();
void setOutput(String value);
}
/**
* Create a map of information that describes how to write pipeline output to text. This map
* is passed to the {@link WriteToText} constructor to write user score sums.
*/
protected static Map<String, WriteToText.FieldFn<KV<String, Integer>>>
configureOutput() {
Map<String, WriteToText.FieldFn<KV<String, Integer>>> config =
new HashMap<String, WriteToText.FieldFn<KV<String, Integer>>>();
config.put("user", (c, w) -> c.element().getKey());
config.put("total_score", (c, w) -> c.element().getValue());
return config;
}
/**
* Run a batch pipeline.
*/
// [START DocInclude_USMain]
public static void main(String[] args) throws Exception {
// Begin constructing a pipeline configured by commandline flags.
Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
Pipeline pipeline = Pipeline.create(options);
// Read events from a text file and parse them.
pipeline
.apply(TextIO.read().from(options.getInput()))
.apply("ParseGameEvent", ParDo.of(new ParseEventFn()))
// Extract and sum username/score pairs from the event data.
.apply("ExtractUserScore", new ExtractAndSumScore("user"))
.apply(
"WriteUserScoreSums",
new WriteToText<KV<String, Integer>>(
options.getOutput(),
configureOutput(),
false));
// Run the batch pipeline.
pipeline.run().waitUntilFinish();
}
// [END DocInclude_USMain]
}
| 36.969957 | 99 | 0.701648 |
0cf8d1e429cb8b91e3dbeabce0a472104ad896a4 | 5,786 | package com.sebix.unittesting.ui.note;
import com.sebix.unittesting.models.Note;
import com.sebix.unittesting.repository.NoteRepository;
import com.sebix.unittesting.ui.Resource;
import com.sebix.unittesting.util.InstantExecutorExtension;
import com.sebix.unittesting.util.LiveDataTestUtil;
import com.sebix.unittesting.util.TestUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.function.Executable;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import io.reactivex.Flowable;
import io.reactivex.internal.operators.single.SingleToFlowable;
import static com.sebix.unittesting.repository.NoteRepository.INSERT_SUCCESS;
import static com.sebix.unittesting.repository.NoteRepository.UPDATE_SUCCESS;
import static com.sebix.unittesting.ui.note.NoteViewModel.NO_CONTNENT_ERROR;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(InstantExecutorExtension.class)
public class NoteViewModelTest {
//system under test
private NoteViewModel noteViewModel;
@Mock
private NoteRepository noteRepository;
@BeforeEach
public void init() {
MockitoAnnotations.initMocks(this);
noteViewModel = new NoteViewModel(noteRepository);
}
// can't observe a note that hasnt been set
@Test
void observeEmptyNote_whenNotSet() throws Exception {
//Arrange
LiveDataTestUtil<Note> liveDataTestUtil = new LiveDataTestUtil<>();
//Act
Note note = liveDataTestUtil.getValue(noteViewModel.observeNote());
//Assert
assertNull(note);
}
//Observe a note has been set and onChanged will trigger in activity
@Test
void observeNote_whenSet() throws Exception {
//Arrange
Note note = new Note(TestUtil.TEST_NOTE_1);
LiveDataTestUtil<Note> liveDataTestUtil = new LiveDataTestUtil<>();
//Act
noteViewModel.setNote(note);
Note observedNote = liveDataTestUtil.getValue(noteViewModel.observeNote());
//Assert
assertEquals(note, observedNote);
}
//insert a new note and observe row returned
@Test
void insertNote_returnRow() throws Exception {
//Arrange
Note note = new Note(TestUtil.TEST_NOTE_1);
LiveDataTestUtil<Resource<Integer>> liveDataTestUtil = new LiveDataTestUtil<>();
final int insertedRow = 1;
Flowable<Resource<Integer>> returnedData = SingleToFlowable.just(Resource.success(insertedRow, INSERT_SUCCESS));
when(noteRepository.insertNote(any(Note.class))).thenReturn(returnedData);
//Act
noteViewModel.setNote(note);
noteViewModel.setIsNewNote(true);
Resource<Integer> returnValue = liveDataTestUtil.getValue(noteViewModel.saveNote());
//Assert
assertEquals(Resource.success(insertedRow, INSERT_SUCCESS), returnValue);
}
//insert:dont return a new row without observer
@Test
void dontReturnInsertRowWithoutObserver() throws Exception {
//Arrange
Note note = new Note(TestUtil.TEST_NOTE_1);
//Act
noteViewModel.setNote(note);
//Assert
verify(noteRepository, never()).insertNote(any(Note.class));
}
//set note , null title, throw exception
@Test
void setNote_nullTitle_throwException() throws Exception {
//Arrange
final Note note = new Note(TestUtil.TEST_NOTE_1);
note.setTitle(null);
//Assert
assertThrows(Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
//Act
noteViewModel.setNote(note);
}
});
}
//update a note and observe row returned
@Test
void updateNote_returnRow() throws Exception {
//Arrange
Note note = new Note(TestUtil.TEST_NOTE_1);
LiveDataTestUtil<Resource<Integer>> liveDataTestUtil = new LiveDataTestUtil<>();
final int updatedRow =1 ;
Flowable<Resource<Integer>> returnedData = SingleToFlowable.just(Resource.success(updatedRow,UPDATE_SUCCESS));
when(noteRepository.updateNote(any(Note.class))).thenReturn(returnedData);
//Act
noteViewModel.setNote(note);
noteViewModel.setIsNewNote(false);
Resource<Integer> returnValue = liveDataTestUtil.getValue(noteViewModel.saveNote());
//Assert
assertEquals(Resource.success(updatedRow,UPDATE_SUCCESS),returnValue);
}
//update: don't return a new row without observer
@Test
void dontReturnUpdateRowNumberWithoutObserver() throws Exception {
//Arrange
Note note = new Note(TestUtil.TEST_NOTE_1);
//Act
noteViewModel.setNote(note);
//Assert
verify(noteRepository, never()).updateNote(any(Note.class));
}
//testin exception
@Test
void saveNote_shouldAllowSave_returnFalse() throws Exception {
//Arrange
Note note=new Note(TestUtil.TEST_NOTE_1);
note.setContent(null);
//Act
noteViewModel.setNote(note);
noteViewModel.setIsNewNote(true);
//Assert
Exception exception = assertThrows(Exception.class, new Executable() {
@Override
public void execute() throws Throwable {
noteViewModel.saveNote();
}
});
assertEquals(NO_CONTNENT_ERROR ,exception.getMessage());
}
}
| 36.1625 | 120 | 0.695299 |
bca5b067272e97e304f39e0e98f05e864f38023d | 2,611 | /*
* MIT License
*
* Copyright (c) 2018 Victor Schappert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.tarro.base.attribute;
import io.tarro.base.Valued;
/**
* <p>
* Enumerates the kinds of type path "steps" in a {@code type_path} structure.
* </p>
*
* <p>
* Each member of this enumeration represents one of the {@code type_path_kind}
* values documented in the Java Virtual Machine Specification's section on the
* {@code type_path} structure. The numeric {@code type_path_kind} value
* corresponding to a particular enumerator may be obtained from the
* {@link #getValue()} method.
* </p>
*
* @author Victor Schappert
* @since 20171113
* @see TargetType
* @see AttributeType#RUNTIME_INVISIBLE_TYPE_ANNOTATIONS
* @see AttributeType#RUNTIME_VISIBLE_TYPE_ANNOTATIONS
*/
public enum TypePathKind implements Valued {
//
// ENUMERATORS
//
/**
* Indicates that reaching the annotation requires stepping deeper into an
* array type.
*/
DEEPER_IN_ARRAY_TYPE,
/**
* Indicates that reaching the annotation requires stepping deeper into a
* nested type.
*/
DEEPER_IN_NESTED_TYPE,
/**
* Indicates that the annotation is on the bound of a wildcard type argument
* of a parameterized type.
*/
ON_TYPE_ARGUMENT_WILDCARD_BOUND,
/**
* Indicates that the annotation is on a type argument of a parameterized
* type.
*/
ON_TYPE_ARGUMENT;
//
// INTERFACE: Valued
//
@Override
public int getValue() {
return ordinal();
}
}
| 31.083333 | 81 | 0.710456 |
e66d374030bdf2eacb2ebeca5d310c59ae8c6396 | 382 | package org.irods.jargon2.common.confg.enumz;
import org.junit.Assert;
import org.junit.Test;
public class EnumIoStyleTest {
@Test
public void testMapIoStyleToEnum() {
String test = EnumIoStyle.NIO.toString();
EnumIoStyle actual = EnumIoStyle.mapIoStyleToEnum(test);
Assert.assertNotNull("null enumIoStyle", actual);
Assert.assertEquals(EnumIoStyle.NIO, actual);
}
}
| 22.470588 | 58 | 0.769634 |
79a92b12b34aca4459b22c6c1131fed0c6bfa6ba | 902 | package org.ovirt.mobile.movirt.model.condition;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.ovirt.mobile.movirt.R;
import org.ovirt.mobile.movirt.model.Vm;
public class StatusCondition extends Condition<Vm> {
private final Vm.Status status;
@JsonCreator
public StatusCondition(@JsonProperty("status") Vm.Status status) {
this.status = status;
}
@Override
public boolean evaluate(Vm entity) {
return entity.getStatus() == getStatus();
}
@Override
public String getMessage(Vm vm) {
return getResources().getString(R.string.vm_status_message, vm.getName(), vm.getStatus().toString());
}
@Override
public String toString() {
return "Status is " + getStatus().toString();
}
public Vm.Status getStatus() {
return status;
}
}
| 25.055556 | 109 | 0.685144 |
13288696d062ac036bef76cfc20ea6be7416f4e0 | 1,437 | package unae.lp3.service;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import unae.lp3.model.Pedido;
import unae.lp3.model.Usuario;
import unae.lp3.repository.PedidosRepository;
import unae.lp3.repository.UsuariosRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
// Registramos esta clase como un Bean en nuestro Root ApplicationContext.
@Service
public class PedidosServiceJPA implements IPedidosService {
// Inyectamos una instancia desde nuestro Root ApplicationContext.
@Autowired
private PedidosRepository pedidosRepo;
@Override
public void guardar(Pedido pedidos) {
pedidosRepo.save(pedidos);
}
@Override
public List<Pedido> buscarTodas() {
return pedidosRepo.findAll();
}
@Override
public void eliminar(int idPedido) {
pedidosRepo.deleteById(idPedido);
}
@Override
public Pedido buscarPorId(int idPedido) {
Optional<Pedido> optional = pedidosRepo.findById(idPedido);
if (optional.isPresent()) {
return optional.get();
}
return null;
}
@Override
public List<Pedido> buscarPorIdUsuario(int usuarioId) {
List<Pedido> pedidosUsu = null;
List<Pedido> listaPedidos = pedidosRepo.findAll();
pedidosUsu = new LinkedList<>();
for (Pedido p : listaPedidos) {
if (p.getUsuario().getUsuario_id() == (usuarioId)) {
pedidosUsu.add(p);
}
}
return pedidosUsu;
}
}
| 23.177419 | 74 | 0.752958 |
8115ca50f117373f62ae1062663bdee9c26b9ddb | 1,996 | package com.tjazi.profilescreator.client;
import com.tjazi.profilescreator.messages.CreateBasicProfileRequestMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**
* Created by Krzysztof Wasiak on 02/11/2015.
*/
@Service
public class ProfilesCreatorClientImpl implements ProfilesCreatorClient {
private Logger log = LoggerFactory.getLogger(ProfilesCreatorClientImpl.class);
@Autowired
private RabbitTemplate rabbitTemplate;
@Value("${profilescreator.inputqueuename}")
private String queueName;
/**
* Create basic profile
* @param userName User name
* @param userEmail User email
* @param passwordHash Password MD5 hash
*/
public void createBasicProfile(String userName, String userEmail, String passwordHash) {
if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("userName parameter is null or empty");
}
if (userEmail == null || userEmail.isEmpty()) {
throw new IllegalArgumentException("userEmail parameter is null or empty");
}
if (passwordHash == null || passwordHash.isEmpty()) {
throw new IllegalArgumentException("passwordHash parameter is null or empty");
}
CreateBasicProfileRequestMessage requestMessage = new CreateBasicProfileRequestMessage();
requestMessage.setUserName(userName);
requestMessage.setUserEmail(userEmail);
requestMessage.setPasswordHash(passwordHash);
rabbitTemplate.convertAndSend(queueName, requestMessage);
}
}
| 34.413793 | 97 | 0.745491 |
f956e3f4072f05caba88e0af38a3e61737a9e799 | 1,340 | package org.springframework.webflow.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
import org.springframework.webflow.core.collection.LocalAttributeMap;
import org.springframework.webflow.execution.Event;
public class MockActionTests {
@Test
public void testMockActionExecute() {
MockAction action = new MockAction();
Event e = action.execute(new MockRequestContext());
assertEquals("success", e.getId());
assertTrue(e.getAttributes().isEmpty());
}
@Test
public void testMockActionExecuteCustomResult() {
MockAction action = new MockAction("foo");
Event e = action.execute(new MockRequestContext());
assertEquals("foo", e.getId());
assertTrue(e.getAttributes().isEmpty());
}
@Test
public void testMockActionExecuteCustomResultAttributes() {
MockAction action = new MockAction("foo");
LocalAttributeMap<Object> resultAttributes = new LocalAttributeMap<>();
resultAttributes.put("bar", "baz");
action.setResultAttributes(resultAttributes);
Event e = action.execute(new MockRequestContext());
assertEquals("foo", e.getId());
assertFalse(e.getAttributes().isEmpty());
assertEquals(e.getAttributes().get("bar"), "baz");
}
}
| 32.682927 | 73 | 0.763433 |
0be40d6a8cf29fa08c31ceef634d97b005ba5610 | 5,978 | /**
* Copyright (c) 2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved.
* <p>
* WSO2.Telco Inc. licences this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wso2telco.workflow.api;
import com.wso2telco.core.dbutils.util.ApprovalRequest;
import com.wso2telco.core.dbutils.util.AssignRequest;
import com.wso2telco.core.dbutils.util.Callback;
import com.wso2telco.core.userprofile.UserProfileRetriever;
import com.wso2telco.core.userprofile.dto.UserProfileDTO;
import org.workflow.core.model.TaskSearchDTO;
import org.workflow.core.service.WorkFlowDelegator;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/subscriptions")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class SubscriptionRest {
@GET
@Path("/search")
public Response load(@HeaderParam("user-name") String userName,
@QueryParam("batchSize") byte batchSize,
@QueryParam("start") int start,
@QueryParam("orderBy") String orderBy,
@QueryParam("sortBy") String sortBy,
@QueryParam("filterBy") String filterBy) {
Response response;
try {
WorkFlowDelegator workFlowDelegator = new WorkFlowDelegator();
TaskSearchDTO searchD = new TaskSearchDTO();
searchD.setStart(start);
searchD.setFilterBy(filterBy);
UserProfileRetriever userProfileRetriever = new UserProfileRetriever();
UserProfileDTO userProfile = userProfileRetriever.getUserProfile(userName);
Callback callback = workFlowDelegator.getPendingSubscriptionApprovals(searchD, userProfile);
response = Response.status(Response.Status.OK).entity(callback).build();
} catch (Exception e) {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return response;
}
@GET
@Path("/search/{assignee}")
public Response load(@HeaderParam("user-name") String userName, @QueryParam("batchSize") int batchSize,
@QueryParam("start") int start, @QueryParam("orderBy") String orderBy,
@QueryParam("sortBy") String sortBy, @QueryParam("filterBy") String filterBy, @PathParam("assignee") String assignee) {
Response response;
try {
WorkFlowDelegator workFlowDelegator = new WorkFlowDelegator();
TaskSearchDTO searchD = new TaskSearchDTO();
searchD.setStart(start);
searchD.setFilterBy(filterBy);
UserProfileRetriever userProfileRetriever = new UserProfileRetriever();
UserProfileDTO userProfile = userProfileRetriever.getUserProfile(userName);
Callback callback = workFlowDelegator.getPendingAssignedSubscriptionApprovals(searchD, userProfile, assignee);
response = Response.status(Response.Status.OK).entity(callback).build();
} catch (Exception e) {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return response;
}
@GET
@Path("/graph")
public Response loadGraph(@HeaderParam("user-name") String userName) {
Response response;
try {
WorkFlowDelegator workFlowDelegator = new WorkFlowDelegator();
UserProfileRetriever userProfileRetriever = new UserProfileRetriever();
UserProfileDTO userProfile = userProfileRetriever.getUserProfile(userName);
Callback callback = workFlowDelegator.getSubscriptionGraphData(userProfile);
response = Response.status(Response.Status.OK).entity(callback).build();
} catch (Exception e) {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return response;
}
@POST
@Path("/assign")
public Response assign(@HeaderParam("user-name") String userName, AssignRequest assignRequest) {
Response response;
try {
WorkFlowDelegator workFlowDelegator = new WorkFlowDelegator();
UserProfileRetriever userProfileRetriever = new UserProfileRetriever();
UserProfileDTO userProfile = userProfileRetriever.getUserProfile(userName);
Callback callback = workFlowDelegator.assignSubscriptionTask(assignRequest, userProfile);
response = Response.status(Response.Status.OK).entity(callback).build();
} catch (Exception e) {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return response;
}
@POST
@Path("/approve")
public Response approve(@HeaderParam("user-name") String userName, ApprovalRequest approvalRequest) {
Response response;
try {
WorkFlowDelegator workFlowDelegator = new WorkFlowDelegator();
UserProfileRetriever userProfileRetriever = new UserProfileRetriever();
UserProfileDTO userProfile = userProfileRetriever.getUserProfile(userName);
Callback callback = workFlowDelegator.approveSubscription(approvalRequest, userProfile);
response = Response.status(Response.Status.OK).entity(callback).build();
} catch (Exception e) {
response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return response;
}
}
| 45.984615 | 144 | 0.682168 |
2def1273ec82e7c3321962ca258d908b93b82e4c | 3,609 | package com.skeqi.mes.pojo.chenj.srm.req;
/**
* @author ChenJ
* @date 2021/6/7
* @Classname CSrmSupplierR
* @Description ${Description}
*/
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* 供应商升降级申请行表
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CSrmSupplierRReq {
/**
* 申请单号
*/
private String requestCode;
/**
* 行号
*/
private String lineNumber;
/**
* 评价项目编号
*/
private String evaluationItemNo;
/**
* 评价项目
*/
private String evaluationItem;
/**
* 评价标准
*/
private String evaluationCriterion;
/**
* 评分方式(1.手工评分2.系统评分)
*/
private String scoreIs;
/**
* 分值从
*/
private String scoreStart;
/**
* 分值至
*/
private String scoreStop;
/**
* 得分
*/
private String score;
/**
* 权重(%)
*/
private String weight;
/**
* 评分人员/评分人信息
*/
private String gradingStaff;
public String getRequestCode() {
return requestCode;
}
public void setRequestCode(String requestCode) {
this.requestCode = requestCode;
}
public String getEvaluationItemNo() {
return evaluationItemNo;
}
public void setEvaluationItemNo(String evaluationItemNo) {
this.evaluationItemNo = evaluationItemNo;
}
public String getEvaluationItem() {
return evaluationItem;
}
public void setEvaluationItem(String evaluationItem) {
this.evaluationItem = evaluationItem;
}
public String getEvaluationCriterion() {
return evaluationCriterion;
}
public void setEvaluationCriterion(String evaluationCriterion) {
this.evaluationCriterion = evaluationCriterion;
}
public String getScoreIs() {
return scoreIs;
}
public void setScoreIs(String scoreIs) {
this.scoreIs = scoreIs;
}
public String getScoreStart() {
return scoreStart;
}
public void setScoreStart(String scoreStart) {
this.scoreStart = scoreStart;
}
public String getScoreStop() {
return scoreStop;
}
public void setScoreStop(String scoreStop) {
this.scoreStop = scoreStop;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getLineNumber() {
return lineNumber;
}
public void setLineNumber(String lineNumber) {
this.lineNumber = lineNumber;
}
public String getGradingStaff() {
return gradingStaff;
}
public void setGradingStaff(String gradingStaff) {
this.gradingStaff = gradingStaff;
}
@Override
public String toString() {
return "CSrmSupplierRReq{" +
"requestCode='" + requestCode + '\'' +
", lineNumber='" + lineNumber + '\'' +
", evaluationItemNo='" + evaluationItemNo + '\'' +
", evaluationItem='" + evaluationItem + '\'' +
", evaluationCriterion='" + evaluationCriterion + '\'' +
", scoreIs='" + scoreIs + '\'' +
", scoreStart='" + scoreStart + '\'' +
", scoreStop='" + scoreStop + '\'' +
", score='" + score + '\'' +
", weight='" + weight + '\'' +
", gradingStaff='" + gradingStaff + '\'' +
'}';
}
}
| 20.05 | 72 | 0.561929 |
3507ccd4197f12b44a10babc171bb0509ec76fea | 446 | package com.progzc.blog;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Description 博客项目的启动类
* @Author zhaochao
* @Date 2020/10/22 23:26
* @Email [email protected]
* @Version V1.0
*/
@SpringBootApplication
public class BlogRunApplication {
public static void main(String[] args) {
SpringApplication.run(BlogRunApplication.class, args);
}
}
| 22.3 | 68 | 0.748879 |
174171699dd750f8a11a21169cb28dab61ce423d | 1,019 | /*
* @(#)MessageListener.java 1.14 02/04/09
*
* Copyright 1997-2002 Sun Microsystems, Inc. All Rights Reserved.
*
* SUN PROPRIETARY/CONFIDENTIAL.
* This software is the proprietary information of Sun Microsystems, Inc.
* Use is subject to license terms.
*
*/
package javax.jms;
/** A <CODE>MessageListener</CODE> object is used to receive asynchronously
* delivered messages.
*
* <P>Each session must insure that it passes messages serially to the
* listener. This means that a listener assigned to one or more consumers
* of the same session can assume that the <CODE>onMessage</CODE> method
* is not called with the next message until the session has completed the
* last call.
*
* @version 1.0 - 13 March 1998
* @author Mark Hapner
* @author Rich Burridge
*/
public interface MessageListener {
/** Passes a message to the listener.
*
* @param message the message passed to the listener
*/
void
onMessage(Message message);
}
| 25.475 | 76 | 0.683023 |
22e2d62345b428114d421ac3913f57371a9e444a | 12,357 | /*PLEASE DO NOT EDIT THIS CODE*/
/*This code was generated using the UMPLE 1.31.1.5860.78bb27cc6 modeling language!*/
package cruise.umple.testgenerator;
import cruise.umple.parser.ParseResult;
import java.util.*;
// line 12 "../../../../ump/TestCaseTemplate_model.ump"
public class TestModel
{
//------------------------
// MEMBER VARIABLES
//------------------------
//TestModel Attributes
private String file;
private String code;
private String givenCode;
private String whereCode;
private String thenCode;
private String coverageType;
private ParseResult parseingResult;
private String codeLang;
//TestModel Associations
private List<TestSuite> testSuites;
private List<Depend> depends;
private List<TestInitialization> testInitializations;
//------------------------
// CONSTRUCTOR
//------------------------
public TestModel(String aFile, String aCode, String aGivenCode, String aWhereCode, String aThenCode, String aCoverageType, ParseResult aParseingResult, String aCodeLang)
{
file = aFile;
code = aCode;
givenCode = aGivenCode;
whereCode = aWhereCode;
thenCode = aThenCode;
coverageType = aCoverageType;
parseingResult = aParseingResult;
codeLang = aCodeLang;
testSuites = new ArrayList<TestSuite>();
depends = new ArrayList<Depend>();
testInitializations = new ArrayList<TestInitialization>();
}
//------------------------
// INTERFACE
//------------------------
public boolean setFile(String aFile)
{
boolean wasSet = false;
file = aFile;
wasSet = true;
return wasSet;
}
public boolean setCode(String aCode)
{
boolean wasSet = false;
code = aCode;
wasSet = true;
return wasSet;
}
public boolean setGivenCode(String aGivenCode)
{
boolean wasSet = false;
givenCode = aGivenCode;
wasSet = true;
return wasSet;
}
public boolean setWhereCode(String aWhereCode)
{
boolean wasSet = false;
whereCode = aWhereCode;
wasSet = true;
return wasSet;
}
public boolean setThenCode(String aThenCode)
{
boolean wasSet = false;
thenCode = aThenCode;
wasSet = true;
return wasSet;
}
public boolean setCoverageType(String aCoverageType)
{
boolean wasSet = false;
coverageType = aCoverageType;
wasSet = true;
return wasSet;
}
public boolean setParseingResult(ParseResult aParseingResult)
{
boolean wasSet = false;
parseingResult = aParseingResult;
wasSet = true;
return wasSet;
}
public boolean setCodeLang(String aCodeLang)
{
boolean wasSet = false;
codeLang = aCodeLang;
wasSet = true;
return wasSet;
}
public String getFile()
{
return file;
}
public String getCode()
{
return code;
}
public String getGivenCode()
{
return givenCode;
}
public String getWhereCode()
{
return whereCode;
}
public String getThenCode()
{
return thenCode;
}
public String getCoverageType()
{
return coverageType;
}
public ParseResult getParseingResult()
{
return parseingResult;
}
public String getCodeLang()
{
return codeLang;
}
/* Code from template association_GetMany */
public TestSuite getTestSuite(int index)
{
TestSuite aTestSuite = testSuites.get(index);
return aTestSuite;
}
public List<TestSuite> getTestSuites()
{
List<TestSuite> newTestSuites = Collections.unmodifiableList(testSuites);
return newTestSuites;
}
public int numberOfTestSuites()
{
int number = testSuites.size();
return number;
}
public boolean hasTestSuites()
{
boolean has = testSuites.size() > 0;
return has;
}
public int indexOfTestSuite(TestSuite aTestSuite)
{
int index = testSuites.indexOf(aTestSuite);
return index;
}
/* Code from template association_GetMany */
public Depend getDepend(int index)
{
Depend aDepend = depends.get(index);
return aDepend;
}
public List<Depend> getDepends()
{
List<Depend> newDepends = Collections.unmodifiableList(depends);
return newDepends;
}
public int numberOfDepends()
{
int number = depends.size();
return number;
}
public boolean hasDepends()
{
boolean has = depends.size() > 0;
return has;
}
public int indexOfDepend(Depend aDepend)
{
int index = depends.indexOf(aDepend);
return index;
}
/* Code from template association_GetMany */
public TestInitialization getTestInitialization(int index)
{
TestInitialization aTestInitialization = testInitializations.get(index);
return aTestInitialization;
}
public List<TestInitialization> getTestInitializations()
{
List<TestInitialization> newTestInitializations = Collections.unmodifiableList(testInitializations);
return newTestInitializations;
}
public int numberOfTestInitializations()
{
int number = testInitializations.size();
return number;
}
public boolean hasTestInitializations()
{
boolean has = testInitializations.size() > 0;
return has;
}
public int indexOfTestInitialization(TestInitialization aTestInitialization)
{
int index = testInitializations.indexOf(aTestInitialization);
return index;
}
/* Code from template association_MinimumNumberOfMethod */
public static int minimumNumberOfTestSuites()
{
return 0;
}
/* Code from template association_AddManyToOne */
public TestSuite addTestSuite()
{
return new TestSuite(this);
}
public boolean addTestSuite(TestSuite aTestSuite)
{
boolean wasAdded = false;
if (testSuites.contains(aTestSuite)) { return false; }
TestModel existingTestModel = aTestSuite.getTestModel();
boolean isNewTestModel = existingTestModel != null && !this.equals(existingTestModel);
if (isNewTestModel)
{
aTestSuite.setTestModel(this);
}
else
{
testSuites.add(aTestSuite);
}
wasAdded = true;
return wasAdded;
}
public boolean removeTestSuite(TestSuite aTestSuite)
{
boolean wasRemoved = false;
//Unable to remove aTestSuite, as it must always have a testModel
if (!this.equals(aTestSuite.getTestModel()))
{
testSuites.remove(aTestSuite);
wasRemoved = true;
}
return wasRemoved;
}
/* Code from template association_AddIndexControlFunctions */
public boolean addTestSuiteAt(TestSuite aTestSuite, int index)
{
boolean wasAdded = false;
if(addTestSuite(aTestSuite))
{
if(index < 0 ) { index = 0; }
if(index > numberOfTestSuites()) { index = numberOfTestSuites() - 1; }
testSuites.remove(aTestSuite);
testSuites.add(index, aTestSuite);
wasAdded = true;
}
return wasAdded;
}
public boolean addOrMoveTestSuiteAt(TestSuite aTestSuite, int index)
{
boolean wasAdded = false;
if(testSuites.contains(aTestSuite))
{
if(index < 0 ) { index = 0; }
if(index > numberOfTestSuites()) { index = numberOfTestSuites() - 1; }
testSuites.remove(aTestSuite);
testSuites.add(index, aTestSuite);
wasAdded = true;
}
else
{
wasAdded = addTestSuiteAt(aTestSuite, index);
}
return wasAdded;
}
/* Code from template association_MinimumNumberOfMethod */
public static int minimumNumberOfDepends()
{
return 0;
}
/* Code from template association_AddManyToOptionalOne */
public boolean addDepend(Depend aDepend)
{
boolean wasAdded = false;
if (depends.contains(aDepend)) { return false; }
TestModel existingTestModel = aDepend.getTestModel();
if (existingTestModel == null)
{
aDepend.setTestModel(this);
}
else if (!this.equals(existingTestModel))
{
existingTestModel.removeDepend(aDepend);
addDepend(aDepend);
}
else
{
depends.add(aDepend);
}
wasAdded = true;
return wasAdded;
}
public boolean removeDepend(Depend aDepend)
{
boolean wasRemoved = false;
if (depends.contains(aDepend))
{
depends.remove(aDepend);
aDepend.setTestModel(null);
wasRemoved = true;
}
return wasRemoved;
}
/* Code from template association_AddIndexControlFunctions */
public boolean addDependAt(Depend aDepend, int index)
{
boolean wasAdded = false;
if(addDepend(aDepend))
{
if(index < 0 ) { index = 0; }
if(index > numberOfDepends()) { index = numberOfDepends() - 1; }
depends.remove(aDepend);
depends.add(index, aDepend);
wasAdded = true;
}
return wasAdded;
}
public boolean addOrMoveDependAt(Depend aDepend, int index)
{
boolean wasAdded = false;
if(depends.contains(aDepend))
{
if(index < 0 ) { index = 0; }
if(index > numberOfDepends()) { index = numberOfDepends() - 1; }
depends.remove(aDepend);
depends.add(index, aDepend);
wasAdded = true;
}
else
{
wasAdded = addDependAt(aDepend, index);
}
return wasAdded;
}
/* Code from template association_MinimumNumberOfMethod */
public static int minimumNumberOfTestInitializations()
{
return 0;
}
/* Code from template association_AddManyToOptionalOne */
public boolean addTestInitialization(TestInitialization aTestInitialization)
{
boolean wasAdded = false;
if (testInitializations.contains(aTestInitialization)) { return false; }
TestModel existingTestModel = aTestInitialization.getTestModel();
if (existingTestModel == null)
{
aTestInitialization.setTestModel(this);
}
else if (!this.equals(existingTestModel))
{
existingTestModel.removeTestInitialization(aTestInitialization);
addTestInitialization(aTestInitialization);
}
else
{
testInitializations.add(aTestInitialization);
}
wasAdded = true;
return wasAdded;
}
public boolean removeTestInitialization(TestInitialization aTestInitialization)
{
boolean wasRemoved = false;
if (testInitializations.contains(aTestInitialization))
{
testInitializations.remove(aTestInitialization);
aTestInitialization.setTestModel(null);
wasRemoved = true;
}
return wasRemoved;
}
/* Code from template association_AddIndexControlFunctions */
public boolean addTestInitializationAt(TestInitialization aTestInitialization, int index)
{
boolean wasAdded = false;
if(addTestInitialization(aTestInitialization))
{
if(index < 0 ) { index = 0; }
if(index > numberOfTestInitializations()) { index = numberOfTestInitializations() - 1; }
testInitializations.remove(aTestInitialization);
testInitializations.add(index, aTestInitialization);
wasAdded = true;
}
return wasAdded;
}
public boolean addOrMoveTestInitializationAt(TestInitialization aTestInitialization, int index)
{
boolean wasAdded = false;
if(testInitializations.contains(aTestInitialization))
{
if(index < 0 ) { index = 0; }
if(index > numberOfTestInitializations()) { index = numberOfTestInitializations() - 1; }
testInitializations.remove(aTestInitialization);
testInitializations.add(index, aTestInitialization);
wasAdded = true;
}
else
{
wasAdded = addTestInitializationAt(aTestInitialization, index);
}
return wasAdded;
}
public void delete()
{
for(int i=testSuites.size(); i > 0; i--)
{
TestSuite aTestSuite = testSuites.get(i - 1);
aTestSuite.delete();
}
while( !depends.isEmpty() )
{
depends.get(0).setTestModel(null);
}
while( !testInitializations.isEmpty() )
{
testInitializations.get(0).setTestModel(null);
}
}
public String toString()
{
return super.toString() + "["+
"file" + ":" + getFile()+ "," +
"code" + ":" + getCode()+ "," +
"givenCode" + ":" + getGivenCode()+ "," +
"whereCode" + ":" + getWhereCode()+ "," +
"thenCode" + ":" + getThenCode()+ "," +
"coverageType" + ":" + getCoverageType()+ "," +
"codeLang" + ":" + getCodeLang()+ "]" + System.getProperties().getProperty("line.separator") +
" " + "parseingResult" + "=" + (getParseingResult() != null ? !getParseingResult().equals(this) ? getParseingResult().toString().replaceAll(" "," ") : "this" : "null");
}
} | 25.115854 | 186 | 0.66084 |
2a7d6020f1d62ecf5ddb17e61005fdbbd0867824 | 2,160 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.yoko.rmi.impl;
import javax.rmi.CORBA.Stub;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.rmi.CORBA.Util.createValueHandler;
import static javax.rmi.PortableRemoteObject.narrow;
/**
* RMIStub's (org.apache.yoko.rmi.impl) implement writeReplace by returning an
* instance of this class; and this class then implements readResolve to narrow
* itself to the correct type. This way, object references to RMI exported
* objects are transferred without loss of the runtime type.
*
* @author Kresten Krab Thorup ([email protected])
*/
public class RMIPersistentStub extends Stub {
static final Logger logger = Logger.getLogger(RMIPersistentStub.class.getName());
/** the class-type to which this object should be narrow'ed */
private final Class<?> type;
public RMIPersistentStub(Stub stub, Class<?> type) {
_set_delegate(stub._get_delegate());
this.type = type;
}
public Object readResolve() throws ClassNotFoundException {
try {
return narrow(this, type);
} catch (RuntimeException ex) {
logger.log(Level.WARNING, "Error narrowing object", ex);
throw ex;
}
}
public String[] _ids() {
return new String[] { createValueHandler().getRMIRepositoryID(type) };
}
}
| 36 | 85 | 0.7125 |
5f997cfc1da0fadfea03c943f4edc55121dbe3ba | 1,418 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ejemplo.dominio;
/**
*
* @author MARTIN
*/
public class Packing extends Carga{
private float pesoCaja;
private int cantidad;
private float pesoEstructura;
public Packing(String contenido, float pesoCaja, int cantidad, float pesoEstructura) {
super(contenido);
this.cantidad = cantidad;
this.pesoCaja = pesoCaja;
this.pesoEstructura = pesoEstructura;
}
public float getPesoCaja() {
return pesoCaja;
}
public void setPesoCaja(float pesoCaja) {
this.pesoCaja = pesoCaja;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
public float getPesoEstructura() {
return pesoEstructura;
}
public void setPesoEstructura(float pesoEstructura) {
this.pesoEstructura = pesoEstructura;
}
@Override
public float calcularPeso() {
float aux = pesoCaja * cantidad + pesoEstructura;
return aux;
}
@Override
public String toString() {
return super.toString() + "|Peso x Caja: " + pesoCaja + " |Cantidad: " + cantidad + " |Peso Estructura:" + pesoEstructura;
}
}
| 23.633333 | 131 | 0.643159 |
3e8f8555e51b34524001bf373dece0a094a9d56c | 588 | package wang.sunnly.modules.auth.service;
import javax.servlet.http.HttpServletRequest;
/**
* AuthService
*
* @author Sunnly
* @since 2020/12/11
*/
public interface AuthService {
/**
* 获取锁定时长
* @param id id
* @return 返回锁定时长
*/
long lockedTime(String id);
/**
* 锁定用户
* @param id ID
*/
void lockedUser(String id);
/**
* 获取登录Token
* @param request 请求
* @param username 用户名
* @param password 密码
* @return 返回Token
*/
String login(HttpServletRequest request, String username, String password);
}
| 17.294118 | 79 | 0.598639 |
f7b3284f2af2688b4b7dc05135a7bc5016f9dce7 | 1,546 | /*
* Copyright (c) 2020 Bixbit s.c. All rights reserved.
* See LICENSE file for licensing information.
*/
package io.imunity.furms.domain.applications;
import io.imunity.furms.domain.users.FURMSUser;
import io.imunity.furms.domain.users.FenixUserId;
import java.util.Objects;
import java.util.Set;
public class ProjectApplicationRemovedEvent implements ProjectApplicationEvent {
public final FenixUserId id;
public final String projectId;
public final Set<FURMSUser> projectAdmins;
public ProjectApplicationRemovedEvent(FenixUserId id, String projectId, Set<FURMSUser> projectAdmins) {
this.id = id;
this.projectId = projectId;
this.projectAdmins = Set.copyOf(projectAdmins);
}
public boolean isTargetedAt(FURMSUser user) {
return projectAdmins.stream().anyMatch(adminUsr -> adminUsr.id.equals(user.id));
}
@Override
public FenixUserId getId() {
return id;
}
@Override
public String getProjectId() {
return projectId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ProjectApplicationRemovedEvent userEvent = (ProjectApplicationRemovedEvent) o;
return Objects.equals(id, userEvent.id) &&
Objects.equals(projectId, userEvent.projectId);
}
@Override
public int hashCode() {
return Objects.hash(id, projectId);
}
@Override
public String toString() {
return "ProjectApplicationRemovedEvent{" +
"id='" + id + '\'' +
", projectId=" + projectId +
", projectAdmins=" + projectAdmins +
'}';
}
}
| 24.935484 | 104 | 0.732212 |
ea8a5d7e229989b2a8026a584c76e757d16e9156 | 387 | package ltd.newbee.mall.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Builder;
import lombok.Data;
/**
* @program: newbee-mall
* @description: 点赞记录表
* @author: chenshutian
* @create: 2021-03-16 11:03
**/
@Data
@Builder
public class ThumbLog {
@TableId
private Integer id;
private Integer aid; //文章id
private Integer uid; //用户id
}
| 18.428571 | 51 | 0.69509 |
dbf0f42989c82513999a6a612a538241755c6746 | 7,051 | package classes;
/**
* @author Eduardo Migueis, Rodrigo Smith and Manuela Benassi.
* @since 2020.
*/
public class Aeroporto implements Cloneable
{
private int idAeroporto;
private String codigoIATA = "";
private String codigoICAO = "";
private String nomeAero = "";
private String pais = "";
private String cidade = "";
private final ListaDuplamenteLigadaDesordenada<Voo> listaVoos;
/**
* Construtor da classe Aeroporto
* @param codigoIATA código IATA do aeroporto
* @param codigoICAO código ICAO do aeroporto
* @param nome nome do aeroporto
* @param pais país onde se localiza o aeroporto
* @param cidade cidade onde se localiza o aeroporto
* @throws Exception é lançada uma exceção se algum parâmetro do tipo String for uma cadeia vazia.
*/
public Aeroporto(String codigoIATA, String codigoICAO, String nome, String pais, String cidade) throws Exception
{
if(codigoIATA.equals("") || codigoICAO.equals("") || nome.equals("") || pais.equals("") || cidade.equals(""))
throw new Exception("Dados ausentes");
this.codigoIATA = codigoIATA;
this.codigoICAO = codigoICAO;
this.nomeAero = nome;
this.pais = pais;
this.cidade = cidade;
this.listaVoos = new ListaDuplamenteLigadaDesordenada<>();
}
/**
* Pega o codigoIATA
* @return retorna o código ICAO do aeroporto
*/
public String getCodigoIATA()
{
return this.codigoIATA;
}
/**
* Pega o codigoICAO
* @return retorna o código ICAO do aeroporto
*/
public String getCodigoICAO()
{
return this.codigoICAO;
}
/**
* Pega o nome do aeroporto
* @return retorna o nome do aeroporto
*/
public String getNome()
{
return this.nomeAero;
}
/**
* Pega o país
* @return retorna o pais
*/
public String getPais()
{
return this.pais;
}
/**
* Pega a cidade
* @return retorna a cidade
*/
public String getCidade()
{
return this.cidade;
}
/**
* Pega os voos da lista
* @return retorna a lista de voos
*/
public ListaDuplamenteLigadaDesordenada<Voo> getVoos()
{
return this.listaVoos;
}
/**
* Seta o valor do parametro ao Código IATA
* @param codigo codigo a ser setado
* @throws Exception Código IATA é inválido
*/
public void setCodigoIATA(String codigo) throws Exception
{
if(codigo.equals(""))
{
throw new Exception("Código IATA inválido.");
}
else
this.codigoIATA = codigo;
}
/**
* Seta o valor do parametro ao Código ICAO
* @param codigo codigo a ser setado
* @throws Exception Código ICAO é inválido
*/
public void setCodigoICAO(String codigo) throws Exception
{
if(codigo.equals(""))
{
throw new Exception("Código ICAO inválido.");
}
else
this.codigoICAO = codigo;
}
/**
* Seta o valor do parametro ao nome
* @param nome nome a ser setado
* @throws Exception nome passado é inválido
*/
public void setNome(String nome) throws Exception
{
if(nome.equals(""))
{
throw new Exception("Nome inválido.");
}
else
this.nomeAero = nome;
}
/**
* Seta o valor do parametro ao pais
* @param pais país a ser setado
* @throws Exception país passado é inválido
*/
public void setPais(String pais) throws Exception
{
if(pais.equals(""))
{
throw new Exception("País inválido.");
}
else
this.pais = pais;
}
/**
* Seta o valor do parametro à cidade
* @param cidade cidade a ser setada
* @throws Exception cidade passada é inválido
*/
public void setCidade(String cidade) throws Exception
{
if(cidade.equals(""))
{
throw new Exception("Cidade inválida.");
}
else
this.cidade = cidade;
}
public void addVoo(Voo voo) throws Exception
{
if(voo == null)
{
throw new Exception("Voo inválido.");
}
else
this.listaVoos.insiraNoFim(voo);
}
/**
* Constrói uma string que representa a classe
* @return uma string com os atributos
*/
@Override
public String toString(){
return
"Codigo IATA: " + codigoIATA + "\n" +
"Codigo ICAO: " + codigoICAO + "\n" +
"Nome areporto: " + nomeAero + "\n" +
"País: " + pais + "\n" +
"Cidade: " + cidade;
}
/**
* Constrói o haschCode da classe
* @return haschCode da classe
*/
@Override
public int hashCode(){
int ret = 111;
ret = ret *5 + this.cidade.hashCode();
ret = ret * 5 + this.codigoIATA.hashCode();
ret = ret * 5 + this.codigoICAO.hashCode();
ret = ret * 5 + new Integer(this.idAeroporto).hashCode();
ret = ret * 5 + this.nomeAero.hashCode();
ret = ret * 5 + this.pais.hashCode();
if(ret<0)
ret = -ret;
return ret;
}
/**
* Clona a classe
* @return o clone
*/
@Override
public Object clone()
{
Aeroporto clone = null;
try
{
clone = new Aeroporto(this);
}
catch(Exception e)
{}
return clone;
}
/**
* Compara se a classe passada é igual a essa
* @param obj objeto a ser verificado se é igual à instância chamante do método
* @return ture se forem iguais e, false, se não
*/
@Override
public boolean equals(Object obj){
if(obj == null)
return false;
if(obj == this)
return true;
if(obj.getClass() != this.getClass())
return false;
Aeroporto aero = (Aeroporto) obj;
if(!this.cidade.equals(aero.cidade) || !this.pais.equals(aero.pais) || !this.codigoIATA.equals(aero.codigoIATA) ||
!this.codigoICAO.equals(aero.codigoICAO) || this.idAeroporto != aero.idAeroporto || !this.nomeAero.equals(aero.nomeAero))
return false;
return true;
}
/**
* Atribui os valores do modelo a essa classe
* @param modelo objeto a ser clonado
* @throws Exception é lançada uma exceção se o parâmetro for nulo
*/
public Aeroporto(Aeroporto modelo) throws Exception
{
if(modelo == null)
{
throw new Exception("modelo para cópia não pode ser nulo");
}
this.cidade = modelo.cidade;
this.codigoIATA = modelo.codigoIATA;
this.codigoICAO = modelo.codigoICAO;
this.nomeAero = modelo.nomeAero;
this.pais = modelo.pais;
this.listaVoos = modelo.listaVoos;
}
}
| 26.309701 | 128 | 0.55907 |
66f2e64f0e3676d9ac39b78a78b24c0bfc2e03cf | 6,225 | import org.junit.Test;
import static org.junit.Assert.*;
// LC221: https://leetcode.com/problems/maximal-square/
//
// Given a 2D binary matrix filled with 0's and 1's, find the largest square
// containing all 1's and return its area.
public class MaxSquare {
// time complexity: O(M * N ^ 2), space complexity: O(N)
// beats 83.29%(10 ms)
public int maximalSquare(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int[] oneCounts = new int[n];
for (int j = 0; j < n; j++) {
for (int i = 0; i < m && matrix[i][j] == '1'; i++) {
oneCounts[j]++;
}
}
int max = maxSide(oneCounts);
for (int i = 1; i < m; i++) {
boolean hasZero = false; // skip all 1's when possible
for (int j = 0; j < n; j++) {
if (oneCounts[j] > 0) {
oneCounts[j]--;
} else {
hasZero = true;
for (int k = i; k < m && matrix[k][j] == '1'; k++) {
oneCounts[j]++;
}
}
}
if (hasZero) {
max = Math.max(max, maxSide(oneCounts));
}
}
return max * max;
}
private int maxSide(int[] heights) {
int max = 0;
int n = heights.length;
int front = 0;
int[] heights2 = heights.clone();
for (int i = 1; i < n; i++) {
if (i - front >= heights2[front]) {
max = Math.max(max, heights2[front]);
if (++front == n) return max;
i--;
continue;
}
int cur = heights[i];
if (heights2[i - 1] > cur) {
max = Math.max(max, i - front);
for (int j = i - 1; j >= front; j--) {
if (heights2[j] > cur) {
heights2[j] = cur;
} else break;
}
}
}
return Math.max(max, Math.min(n - front, heights2[front]));
}
public void testMaxSide(int expected, int ... nums) {
assertEquals(expected, maxSide(nums));
}
// 2D-Dynamic Programming
// time complexity: O(M * N), space complexity: O(M * N)
// beats 45.34%(12 ms for 68 tests)
public int maximalSquare2(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
// largest square side that ends at (i, j)
int[][] dp = new int[m + 1][n + 1];
int maxSide = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (matrix[i - 1][j - 1] != '1') continue;
dp[i][j] = 1 + Math.min(dp[i - 1][j], Math.min(dp[i][j - 1],
dp[i - 1][j - 1]));
maxSide = Math.max(maxSide, dp[i][j]);
}
}
return maxSide * maxSide;
}
// Solution of Choice
// 1D-Dynamic Programming
// time complexity: O(M * N), space complexity: O(M * N)
// beats 45.34%(12 ms for 68 tests)
public int maximalSquare3(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int[] dp = new int[n + 1];
int maxSide = 0;
for (int i = 1, prev = 0; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int tmp = dp[j];
if (matrix[i - 1][j - 1] != '1') {
dp[j] = 0;
} else {
dp[j] = 1 + Math.min(dp[j], Math.min(dp[j - 1], prev));
maxSide = Math.max(maxSide, dp[j]);
}
prev = tmp;
}
}
return maxSide * maxSide;
}
// time complexity: O(M * N), space complexity: O(N)
// beats 67.69%(13 ms)
public int maximalSquare4(char[][] matrix) {
int m = matrix.length;
if (m == 0) return 0;
int n = matrix[0].length;
int[][] sides = new int[2][n];
int maxSide = 0;
for (int j = 0; j < n; j++) {
if (matrix[0][j] == '1') {
sides[0][j] = 1;
maxSide = 1;
}
}
for (int i = 1; i < m; i++) {
int k = i % 2;
sides[k][0] = matrix[i][0] - '0';
maxSide = Math.max(sides[k][0], maxSide);
for (int j = 1; j < n; j++) {
if (matrix[i][j] == '0') {
sides[k][j] = 0;
} else {
sides[k][j] = Math.min(sides[1 - k][j],
Math.min(sides[k][j - 1],
sides[1 - k][j - 1])) + 1;
maxSide = Math.max(sides[k][j], maxSide);
}
}
}
return maxSide * maxSide;
}
@Test
public void testMaxSide() {
testMaxSide(2, 4, 0, 3, 4, 0);
testMaxSide(1, 4, 0, 3, 0, 0);
testMaxSide(4, 0, 2, 3, 6, 4, 5, 4);
testMaxSide(3, 0, 2, 3, 6, 4, 5);
testMaxSide(2, 2, 3, 6, 1, 5);
testMaxSide(2, 2, 3, 1, 1, 5);
testMaxSide(3, 8, 5, 6, 1, 5, 2);
}
void test(int expected, String ... matrixStr) {
char[][] matrix = new char[matrixStr.length][];
for (int i = 0; i < matrixStr.length; i++) {
matrix[i] = matrixStr[i].toCharArray();
}
assertEquals(expected, maximalSquare(matrix));
assertEquals(expected, maximalSquare2(matrix));
assertEquals(expected, maximalSquare3(matrix));
assertEquals(expected, maximalSquare4(matrix));
}
@Test
public void test1() {
test(1, "1");
test(4, "10100", "10111", "11111", "10010");
test(4, "10110", "10111", "11111", "10010");
test(9, "10111", "10111", "11111", "10010");
test(4, "101101","111111","011011","111010","011111","110111");
}
public static void main(String[] args) {
org.junit.runner.JUnitCore.main("MaxSquare");
}
}
| 32.763158 | 82 | 0.423293 |
454cb6866295c8b1393c8d9c90095ec819c40cad | 705 | package com.devotedmc.ExilePearl.util;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import com.devotedmc.ExilePearl.ExilePearlPlugin;
public class SpawnUtil {
/**
* Spawns a player in the world without killing them
* Uses Randomspawn if available, otherwise natural spawn
*
* @param player The player to spawn
* @param world The world in which to spawn the player
*/
public static void spawnPlayer(Player player, World world) {
player.teleport(chooseSpawn(world).add(0, 0.5, 0));
}
public static Location chooseSpawn(World world) {
Location spawn = null;
spawn = world.getSpawnLocation();
return spawn;
}
}
| 24.310345 | 61 | 0.744681 |
d6079bf2a96ab21e811069cf4b88823a48fdb3a7 | 752 | package org.season.ymir.core.annotation;
import org.springframework.stereotype.Component;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 服务导出
*
* @author KevinClair
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Component
@Documented
public @interface Service {
/**
* 权重
*/
int weight() default 50;
/**
* 是否需要注册
*/
boolean register() default true;
/**
* 分组
*/
String group() default "";
/**
* 版本
*/
String version() default "";
/**
* 过滤器
*/
String filter() default "";
}
| 16 | 48 | 0.634309 |
2718711dbf32c14e87be14f609a97f9e216828b5 | 157 | public int hashCode() {
// System.out.println("In hashcode");
int hashcode = 0;
hashcode = a * 20;
hashcode += b * 20;
return hashcode;
} | 22.428571 | 41 | 0.579618 |
b7696f4f7b136a00df05292c4ace1ba76dfbe494 | 9,204 | /*
* Copyright (c) 2002-2017, Mairie de Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.portal.service.util;
import fr.paris.lutece.portal.service.init.LuteceInitException;
import fr.paris.lutece.util.PropertiesService;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* this class provides management services for properties files
*/
public final class AppPropertiesService
{
private static final String FILE_PROPERTIES_CONFIG = "config.properties";
private static final String FILE_PROPERTIES_DATABASE = "db.properties";
private static final String FILE_PROPERTIES_LUTECE = "lutece.properties";
private static final String FILE_PROPERTIES_SEARCH = "search.properties";
private static final String FILE_PROPERTIES_DAEMONS = "daemons.properties";
private static final String FILE_PROPERTIES_CACHES = "caches.properties";
private static final String FILE_PROPERTIES_EDITORS = "editors.properties";
private static final String PATH_PLUGINS = "plugins/";
private static final String PATH_OVERRIDE_CORE = "override/";
private static final String PATH_OVERRIDE_PLUGINS = "override/plugins";
private static PropertiesService _propertiesService;
private static String _strConfPath;
/**
* Private constructor
*/
private AppPropertiesService( )
{
}
/**
* Initializes the service
*
* @param strConfPath
* The configuration path
* @throws LuteceInitException
* If an error occured
*/
public static void init( String strConfPath ) throws LuteceInitException
{
_strConfPath = strConfPath;
_propertiesService = new PropertiesService( AppPathService.getWebAppPath( ) );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_CONFIG );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_DATABASE );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_LUTECE );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_SEARCH );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_DAEMONS );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_CACHES );
_propertiesService.addPropertiesFile( _strConfPath, FILE_PROPERTIES_EDITORS );
_propertiesService.addPropertiesDirectory( _strConfPath + PATH_PLUGINS );
_propertiesService.addPropertiesDirectory( _strConfPath + PATH_OVERRIDE_CORE );
_propertiesService.addPropertiesDirectory( _strConfPath + PATH_OVERRIDE_PLUGINS );
}
/**
* Returns the value of a variable defined in the .properties file of the application as a String
*
* @param strProperty
* The variable name
* @return The variable value read in the properties file
*/
public static String getProperty( String strProperty )
{
return _propertiesService.getProperty( strProperty );
}
/**
* Returns the value of a variable defined in the .properties file of the application as a String
*
* @param strProperty
* The variable name
* @param strDefault
* The default value which is returned if no value is found for the variable in the .properties file.
* @return The variable value read in the properties file
*/
public static String getProperty( String strProperty, String strDefault )
{
return _propertiesService.getProperty( strProperty, strDefault );
}
/**
* Returns the value of a variable defined in the .properties file of the application as an int
*
* @param strProperty
* The variable name
* @param nDefault
* The default value which is returned if no value is found for the variable in the le downloadFile .properties. .properties file.
* @return The variable value read in the properties file
*/
public static int getPropertyInt( String strProperty, int nDefault )
{
return _propertiesService.getPropertyInt( strProperty, nDefault );
}
/**
* Returns the value of a variable defined in the .properties file of the application as an long
*
* @param strProperty
* The variable name
* @param lDefault
* The default value which is returned if no value is found for the variable in the le downloadFile .properties. .properties file.
* @return The variable value read in the properties file
*/
public static long getPropertyLong( String strProperty, long lDefault )
{
return _propertiesService.getPropertyLong( strProperty, lDefault );
}
/**
* Returns the value of a variable defined in the .properties file of the application as a boolean
*
* @param strProperty
* The variable name
* @param bDefault
* The default value which is returned if no value is found for the variable in the le downloadFile .properties. .properties file.
* @return The variable value read in the properties file
*/
public static boolean getPropertyBoolean( String strProperty, boolean bDefault )
{
return _propertiesService.getPropertyBoolean( strProperty, bDefault );
}
/**
* Reloads all the properties files
*/
public static void reloadAll( )
{
_propertiesService.reloadAll( );
}
/**
* Reloads a given properties file
*
* @param strFilename
* The file name
*/
public static void reload( String strFilename )
{
_propertiesService.reload( strFilename );
}
/**
* Gets properties
*
* @return All properties
* @since version 3.0
*/
public static Properties getProperties( )
{
// Return a copy of all properties
return new Properties( _propertiesService.getProperties( ) );
}
/**
* Gets all properties as a Map
*
* @return a Map of all properties
* @since version 5.0
*/
public static Map<String, String> getPropertiesAsMap( )
{
Map<String, String> res = new HashMap<String, String>( );
Properties properties = _propertiesService.getProperties( );
// enumerate over property names to get all properties, including one which are defaults
Enumeration<?> names = properties.propertyNames( );
while ( names.hasMoreElements( ) )
{
String name = (String) names.nextElement( );
res.put( name, properties.getProperty( name ) );
}
return res;
}
/**
* Returns a list of keys that match a given prefix.
*
* @param strPrefix
* the str prefix
* @return A list of keys that match the prefix
* @since version 3.0
*/
public static List<String> getKeys( String strPrefix )
{
List<String> listKeys = new ArrayList<String>( );
Enumeration eList = _propertiesService.getProperties( ).keys( );
while ( eList.hasMoreElements( ) )
{
String strKey = (String) eList.nextElement( );
if ( strKey.startsWith( strPrefix ) )
{
listKeys.add( strKey );
}
}
return listKeys;
}
}
| 37.721311 | 146 | 0.66395 |
cf3773d0d8993fdf7f3edddb08a3a638c6279c64 | 1,395 | /*******************************************************************************
* Copyright (c) 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.toc.document;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.birt.report.engine.toc.ITreeNode;
import org.eclipse.birt.report.engine.toc.TreeNode;
public class MemTreeNode extends TreeNode
{
protected ArrayList<ITreeNode> children;
protected MemTreeNode parent;
public MemTreeNode( )
{
}
public MemTreeNode( TreeNode entry )
{
super( entry );
}
public Collection<ITreeNode> getChildren( )
{
if ( children == null )
{
children = new ArrayList<ITreeNode>( );
}
return children;
}
public void addChild( MemTreeNode node )
{
if ( children == null )
{
children = new ArrayList<ITreeNode>( );
}
children.add( node );
}
public MemTreeNode getParent( )
{
return parent;
}
public void setParent( MemTreeNode parent )
{
this.parent = parent;
}
}
| 21.461538 | 81 | 0.636559 |
c069a8589506f036d00113abcde511fdd7d65ee2 | 7,813 | /*
* (C) Copyright 2014-2017 Nuxeo (http://nuxeo.com/) and others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributors:
* Florent Guillaume
*/
package org.nuxeo.ecm.core;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.Serializable;
import java.util.Map;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ecm.core.api.Blobs;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.query.sql.NXQL;
import org.nuxeo.ecm.core.storage.sql.RepositoryDescriptor;
import org.nuxeo.ecm.core.storage.sql.coremodel.SQLRepositoryService;
import org.nuxeo.ecm.core.test.CoreFeature;
import org.nuxeo.ecm.core.test.StorageConfiguration;
import org.nuxeo.ecm.core.test.annotations.Granularity;
import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
import org.nuxeo.runtime.api.Framework;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import org.nuxeo.runtime.test.runner.HotDeployer;
import org.nuxeo.runtime.transaction.TransactionHelper;
@RunWith(FeaturesRunner.class)
@Features(CoreFeature.class)
@RepositoryConfig(cleanup = Granularity.METHOD)
@Deploy("org.nuxeo.ecm.core.convert")
@Deploy("org.nuxeo.ecm.core.convert.plugins")
@Deploy("org.nuxeo.runtime.reload")
public class TestSQLBinariesIndexingOverride {
@Inject
protected CoreFeature coreFeature;
@Inject
protected CoreSession session;
@Inject
protected HotDeployer deployer;
@Before
public void setUp() throws Exception {
assumeTrue(coreFeature.getStorageConfiguration().isVCS());
// SQL Server fulltext indexes can't easily be updated by Nuxeo
assumeTrue(!coreFeature.getStorageConfiguration().isVCSSQLServer());
// cannot be done through @Deploy, because the framework variables
// about repository configuration aren't ready yet
deployer.deploy("org.nuxeo.ecm.core.test.tests:OSGI-INF/test-override-indexing-contrib.xml");
}
protected void waitForFulltextIndexing() {
nextTransaction();
coreFeature.getStorageConfiguration().waitForFulltextIndexing();
}
protected void nextTransaction() {
if (TransactionHelper.isTransactionActiveOrMarkedRollback()) {
TransactionHelper.commitOrRollbackTransaction();
TransactionHelper.startTransaction();
}
}
@Test
public void testTwoBinaryIndexes() throws Exception {
DocumentModelList res;
DocumentModel doc = session.createDocumentModel("/", "source", "File");
doc.setPropertyValue("file:content", (Serializable) Blobs.createBlob("test"));
doc = session.createDocument(doc);
session.save();
waitForFulltextIndexing();
// main index
res = session.query("SELECT * FROM Document WHERE ecm:fulltext = 'test'");
assertEquals(1, res.size());
// other index
res = session.query("SELECT * FROM Document WHERE ecm:fulltext_binaries = 'test'");
assertEquals(1, res.size());
}
@Test
public void testGetBinaryFulltext() throws Exception {
DocumentModelList res;
DocumentModel doc = session.createDocumentModel("/", "source", "File");
doc.setPropertyValue("file:content", (Serializable) Blobs.createBlob("test"));
doc = session.createDocument(doc);
session.save();
waitForFulltextIndexing();
// main index
res = session.query("SELECT * FROM Document WHERE ecm:fulltext = 'test'");
assertEquals(1, res.size());
Map<String, String> map = session.getBinaryFulltext(res.get(0).getRef());
assertTrue(map.containsValue(" test "));
StorageConfiguration database = coreFeature.getStorageConfiguration();
if (!(database.isVCSMySQL() || database.isVCSSQLServer())) {
// we have 2 binaries field
assertTrue(map.containsKey("binarytext"));
assertTrue(map.containsKey("binarytext_binaries"));
assertEquals(" test ", map.get("binarytext"));
assertEquals(" test ", map.get("binarytext_binaries"));
}
}
@Test
public void testExcludeFieldBlob() throws Exception {
DocumentModelList res;
DocumentModel doc = session.createDocumentModel("/", "source", "File");
doc.setPropertyValue("file:content", (Serializable) Blobs.createBlob("test"));
doc = session.createDocument(doc);
session.save();
waitForFulltextIndexing();
// indexes the skip file:content
res = session.query("SELECT * FROM Document WHERE ecm:fulltext_nofile1 = 'test'");
assertEquals(0, res.size());
res = session.query("SELECT * FROM Document WHERE ecm:fulltext_nofile2 = 'test'");
assertEquals(0, res.size());
res = session.query("SELECT * FROM Document WHERE ecm:fulltext_nofile3 = 'test'");
assertEquals(0, res.size());
res = session.query("SELECT * FROM Document WHERE ecm:fulltext_nofile4 = 'test'");
assertEquals(0, res.size());
}
@Test
public void testEnforceFulltextFieldSizeLimit() throws Exception {
SQLRepositoryService repositoryService = Framework.getService(SQLRepositoryService.class);
RepositoryDescriptor repositoryDescriptor = repositoryService.getRepositoryImpl(
session.getRepositoryName()).getRepositoryDescriptor();
int fulltextFieldSizeLimit = repositoryDescriptor.getFulltextDescriptor().getFulltextFieldSizeLimit();
assertEquals(1024, fulltextFieldSizeLimit); // from XML config
String query = "SELECT * FROM Document WHERE ecm:fulltext = %s";
DocumentModelList res;
for (int i = 0; i < 2; i++) {
boolean regular = i == 0;
String name = regular ? "regContent" : "bigContent";
String content = "";
for (int j = 0; j < 93; j++) {
content += "regContent" + " ";
}
if (!regular) {
for (int j = 0; j < 50; j++) {
content += "bigContent" + " ";
}
}
assertEquals(regular ? 1023 : 1573, content.length()); // > 1024 if not regular
DocumentModel doc = session.createDocumentModel("/", name, "File");
doc.setPropertyValue("file:content", (Serializable) Blobs.createBlob(content));
doc = session.createDocument(doc);
session.save();
waitForFulltextIndexing();
// main index
res = session.query(String.format(query, NXQL.escapeString(content)));
if (regular) {
assertEquals(1, res.size());
} else {
assertEquals(0, res.size());
content = content.substring(0, fulltextFieldSizeLimit - 1);
res = session.query(String.format(query, NXQL.escapeString(content)));
assertEquals(2, res.size());
}
}
}
}
| 38.678218 | 110 | 0.664917 |
424f9c00afdac8c95f363f0b98a68a9ca62ee8e9 | 29,066 | package org.codelibs.elasticsearch.dictionary.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import org.codelibs.elasticsearch.dictionary.DictionaryConstants;
import org.codelibs.elasticsearch.dictionary.DictionaryException;
import org.codelibs.elasticsearch.dictionary.filter.CreateSnapshotActionFilter;
import org.codelibs.elasticsearch.dictionary.filter.DeleteSnapshotActionFilter;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotResponse;
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequestBuilder;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.flush.FlushResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.ActionFilter;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.metadata.SnapshotId;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.common.bytes.ChannelBufferBytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.settings.IndexSettingsService;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.snapshots.SnapshotInfo;
import org.elasticsearch.snapshots.SnapshotMissingException;
import org.elasticsearch.snapshots.SnapshotsService;
import org.elasticsearch.snapshots.SnapshotsService.CreateSnapshotListener;
import org.elasticsearch.snapshots.SnapshotsService.SnapshotRequest;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportChannel;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.transport.TransportRequestHandler;
import org.elasticsearch.transport.TransportResponseHandler;
import org.elasticsearch.transport.TransportService;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
public class DictionarySnapshotService extends AbstractComponent {
private static final String ACTION_DICTIONARY_SNAPSHOT_DELETE = "internal:cluster/snapshot/delete_dictionary";
private SnapshotsService snapshotsService;
private IndicesService indicesService;
private Environment env;
private String[] fileExtensions;
private String dictionaryIndex;
private Client client;
private TimeValue masterNodeTimeout;
private TransportService transportService;
private ClusterService clusterService;
@Inject
public DictionarySnapshotService(final Settings settings, final Client client, final Environment env,
final ClusterService clusterService, final IndicesService indicesService, final TransportService transportService,
final SnapshotsService snapshotsService, final ActionFilters filters) {
super(settings);
this.client = client;
this.env = env;
this.clusterService = clusterService;
this.indicesService = indicesService;
this.transportService = transportService;
this.snapshotsService = snapshotsService;
dictionaryIndex = settings.get("dictionary.index", ".dictionary");
fileExtensions = settings.getAsArray("directory.file_extensions",
new String[] { "txt" });
masterNodeTimeout = settings.getAsTime(
"dictionary.snapshot.master_node_timeout",
TimeValue.timeValueSeconds(30));
for (final ActionFilter filter : filters.filters()) {
if (filter instanceof CreateSnapshotActionFilter) {
((CreateSnapshotActionFilter) filter)
.setDictionarySnapshotService(this);
if (logger.isDebugEnabled()) {
logger.debug("Set CreateSnapshotActionFilter to {}", filter);
}
} else if (filter instanceof DeleteSnapshotActionFilter) {
((DeleteSnapshotActionFilter) filter)
.setDictionarySnapshotService(this);
if (logger.isDebugEnabled()) {
logger.debug("Set DeleteSnapshotActionFilter to {}", filter);
}
}
}
transportService.registerRequestHandler(ACTION_DICTIONARY_SNAPSHOT_DELETE,
DeleteDictionaryRequest.class, ThreadPool.Names.SNAPSHOT,
new DeleteDictionaryRequestHandler());
}
private DiscoveryNode getMasterNode() {
final ClusterState clusterState = clusterService.state();
final DiscoveryNodes nodes = clusterState.nodes();
return nodes.localNodeMaster() ? null : nodes.masterNode();
}
public void deleteDictionarySnapshot(final String repository, final String snapshot, final ActionListener<Void> listener) {
DiscoveryNode masterNode = getMasterNode();
if (masterNode == null) {
deleteDictionarySnapshotOnMaster(repository, snapshot, listener);
} else {
transportService.sendRequest(masterNode, ACTION_DICTIONARY_SNAPSHOT_DELETE, new DeleteDictionaryRequest(repository,snapshot),
new TransportResponseHandler<DeleteDictionaryResponse>() {
@Override
public DeleteDictionaryResponse newInstance() {
return new DeleteDictionaryResponse();
}
@Override
public void handleResponse(DeleteDictionaryResponse response) {
if (response.isAcknowledged()) {
listener.onResponse(null);
} else {
listener.onFailure(new DictionaryException("Could not delete " + repository + ":" + snapshot + ". "
+ response.message));
}
}
@Override
public void handleException(TransportException exp) {
listener.onFailure(exp);
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
});
}
}
public void deleteDictionarySnapshotOnMaster(final String repository,
final String snapshot, final ActionListener<Void> listener) {
final String dictionarySnapshot = snapshot + dictionaryIndex + "_"
+ repository + "_" + snapshot;
client.admin().cluster().prepareGetSnapshots(repository)
.setSnapshots(dictionarySnapshot)
.execute(new ActionListener<GetSnapshotsResponse>() {
@Override
public void onResponse(GetSnapshotsResponse response) {
client.admin()
.cluster()
.prepareDeleteSnapshot(repository,
dictionarySnapshot)
.setMasterNodeTimeout(masterNodeTimeout)
.execute(
new ActionListener<DeleteSnapshotResponse>() {
@Override
public void onResponse(
DeleteSnapshotResponse response) {
if (logger.isDebugEnabled()) {
logger.debug(
"Deleted {} snapshot.",
dictionarySnapshot);
}
listener.onResponse(null);
}
@Override
public void onFailure(Throwable e) {
listener.onFailure(e);
}
});
}
@Override
public void onFailure(Throwable e) {
if (e instanceof SnapshotMissingException) {
listener.onResponse(null);
} else {
listener.onFailure(new DictionaryException(
"Failed to find " + dictionarySnapshot
+ " snapshot.", e));
}
}
});
}
public void createDictionarySnapshot(final SnapshotId snapshotId,
final SnapshotInfo snapshot, final ActionListener<Void> listener) {
// find dictionary files
final Map<String, List<Tuple<String, File>>> indexDictionaryMap = new HashMap<>();
for (final String index : snapshot.indices()) {
final IndexService indexService = indicesService
.indexService(index);
final IndexSettingsService settingsService = indexService
.settingsService();
final Settings indexSettings = settingsService.getSettings();
final List<Tuple<String, File>> dictionaryList = new ArrayList<>();
for (final Map.Entry<String, String> entry : indexSettings
.getAsMap().entrySet()) {
final String value = entry.getValue();
if (isDictionaryFile(value)) {
addDictionaryFile(dictionaryList, value);
}
}
if (!dictionaryList.isEmpty()) {
indexDictionaryMap.put(index, dictionaryList);
}
}
if (!indexDictionaryMap.isEmpty()) {
if (logger.isDebugEnabled()) {
for (final Map.Entry<String, List<Tuple<String, File>>> entry : indexDictionaryMap
.entrySet()) {
for (final Tuple<String, File> dictInfo : entry.getValue()) {
logger.debug("{} => {} is found in {}.", dictInfo.v1(),
dictInfo.v2(), entry.getKey());
}
}
}
snapshotDictionaryIndex(snapshotId, indexDictionaryMap,
new ActionListener<Void>() {
@Override
public void onResponse(final Void response) {
if (logger.isDebugEnabled()) {
logger.debug(
"Created {} snapshot.",
dictionaryIndex + "_"
+ snapshotId.getRepository()
+ "_"
+ snapshotId.getSnapshot());
}
listener.onResponse(null);
}
@Override
public void onFailure(final Throwable e) {
listener.onFailure(e);
}
});
} else {
listener.onResponse(null);
}
}
private void snapshotDictionaryIndex(final SnapshotId snapshotId,
final Map<String, List<Tuple<String, File>>> indexDictionaryMap,
final ActionListener<Void> listener) {
final String index = dictionaryIndex + "_" + snapshotId.getRepository()
+ "_" + snapshotId.getSnapshot();
if (logger.isDebugEnabled()) {
logger.debug("Creating dictionary index: {}", index);
}
try {
final CreateIndexRequestBuilder builder = client.admin().indices()
.prepareCreate(index)
.setSettings(createDictionarySettingBuilder());
for (final String type : indexDictionaryMap.keySet()) {
builder.addMapping(type, createDictionaryMappingBuilder(type));
}
builder.execute(new ActionListener<CreateIndexResponse>() {
@Override
public void onResponse(final CreateIndexResponse response) {
if (!response.isAcknowledged()) {
throw new DictionaryException("Failed to create "
+ index);
}
try {
writeDictionaryIndex(index, snapshotId,
indexDictionaryMap, listener);
} catch (final Exception e) {
deleteDictionaryIndex(index);
throw e;
}
}
@Override
public void onFailure(final Throwable e) {
listener.onFailure(e);
}
});
} catch (final Exception e) {
listener.onFailure(e);
}
}
private void writeDictionaryIndex(final String index,
final SnapshotId snapshotId,
final Map<String, List<Tuple<String, File>>> indexDictionaryMap,
final ActionListener<Void> listener) {
if (logger.isDebugEnabled()) {
logger.debug("Writing dictionary index: {}", index);
}
final Queue<Tuple<String, Tuple<String, File>>> dictionaryQueue = new LinkedList<>();
for (final Map.Entry<String, List<Tuple<String, File>>> entry : indexDictionaryMap
.entrySet()) {
final String type = entry.getKey();
final List<Tuple<String, File>> dictFileList = entry.getValue();
for (final Tuple<String, File> dictionaryInfo : dictFileList) {
final Tuple<String, Tuple<String, File>> dictionarySet = new Tuple<>(
type, dictionaryInfo);
dictionaryQueue.add(dictionarySet);
}
}
writeDictionaryFile(index, dictionaryQueue, new ActionListener<Void>() {
@Override
public void onResponse(final Void response) {
flushDictionaryIndex(index, snapshotId, listener);
}
@Override
public void onFailure(final Throwable e) {
listener.onFailure(e);
deleteDictionaryIndex(index);
}
});
}
private void flushDictionaryIndex(final String index,
final SnapshotId snapshotId, final ActionListener<Void> listener) {
if (logger.isDebugEnabled()) {
logger.debug("Flushing dictionary index: {}", index);
}
client.admin().indices().prepareFlush(index).setWaitIfOngoing(true)
.execute(new ActionListener<FlushResponse>() {
@Override
public void onResponse(final FlushResponse response) {
client.admin()
.cluster()
.prepareHealth(index)
.setWaitForGreenStatus()
.execute(
new ActionListener<ClusterHealthResponse>() {
@Override
public void onResponse(
final ClusterHealthResponse response) {
createDictionarySnapshot(index,
snapshotId, listener);
}
@Override
public void onFailure(
final Throwable e) {
listener.onFailure(e);
deleteDictionaryIndex(index);
}
});
}
@Override
public void onFailure(final Throwable e) {
listener.onFailure(e);
deleteDictionaryIndex(index);
}
});
}
private void createDictionarySnapshot(final String index, final SnapshotId snapshotId, final ActionListener<Void> listener) {
final String repository = snapshotId.getRepository();
final String snapshot = snapshotId.getSnapshot();
final String name = snapshot + index;
if (logger.isDebugEnabled()) {
logger.debug("Creating dictionary snapshot: {}", name);
}
final SnapshotRequest request = new SnapshotRequest(
"create dictionary snapshot", name, repository);
request.indices(new String[] { index });
request.masterNodeTimeout(masterNodeTimeout);
snapshotsService.createSnapshot(request, new CreateSnapshotListener() {
@Override
public void onResponse() {
snapshotsService
.addListener(new SnapshotsService.SnapshotCompletionListener() {
SnapshotId snapshotId = new SnapshotId(repository,
snapshot);
@Override
public void onSnapshotCompletion(
final SnapshotId snapshotId2,
final SnapshotInfo snapshot) {
if (snapshotId.equals(snapshotId)) {
listener.onResponse(null);
deleteDictionaryIndex(index);
snapshotsService.removeListener(this);
}
}
@Override
public void onSnapshotFailure(
final SnapshotId snapshotId2,
final Throwable t) {
if (snapshotId.equals(snapshotId)) {
listener.onFailure(t);
deleteDictionaryIndex(index);
snapshotsService.removeListener(this);
}
}
});
}
@Override
public void onFailure(final Throwable t) {
listener.onFailure(t);
deleteDictionaryIndex(index);
}
});
}
private void deleteDictionaryIndex(final String index) {
if (logger.isDebugEnabled()) {
logger.debug("Deleteing {} index.", index);
}
client.admin().indices().prepareDelete(index)
.execute(new ActionListener<DeleteIndexResponse>() {
@Override
public void onResponse(final DeleteIndexResponse response) {
if (logger.isDebugEnabled()) {
logger.debug("Deleted {} index.", index);
}
}
@Override
public void onFailure(final Throwable e) {
logger.error("Failed to delete {} index.", e, index);
}
});
}
private void writeDictionaryFile(final String index,
final Queue<Tuple<String, Tuple<String, File>>> dictionaryQueue,
final ActionListener<Void> listener) {
final Tuple<String, Tuple<String, File>> dictionarySet = dictionaryQueue
.poll();
if (dictionarySet == null) {
listener.onResponse(null);
return;
}
final String type = dictionarySet.v1();
final String path = dictionarySet.v2().v1();
final File file = dictionarySet.v2().v2();
final String absolutePath = file.getAbsolutePath();
try (FileInputStream fis = new FileInputStream(file)) {
final FileChannel fileChannel = fis.getChannel();
final MappedByteBuffer buffer = fileChannel.map(
FileChannel.MapMode.READ_ONLY, 0L, fileChannel.size());
final ChannelBuffer channelBuffer = ChannelBuffers
.wrappedBuffer(buffer);
final Map<String, Object> source = new HashMap<>();
source.put(DictionaryConstants.PATH_FIELD, path);
source.put(DictionaryConstants.ABSOLUTE_PATH_FIELD, absolutePath);
source.put(DictionaryConstants.DATA_FIELD,
new ChannelBufferBytesReference(channelBuffer));
client.prepareIndex(index, type).setSource(source)
.execute(new ActionListener<IndexResponse>() {
@Override
public void onResponse(final IndexResponse response) {
writeDictionaryFile(index, dictionaryQueue,
listener);
}
@Override
public void onFailure(final Throwable e) {
listener.onFailure(e);
}
});
} catch (final Exception e) {
throw new DictionaryException("Failed to index " + type + ":"
+ path + " to " + index, e);
}
}
private XContentBuilder createDictionarySettingBuilder() throws IOException {
final XContentBuilder builder = XContentFactory.jsonBuilder()//
.startObject()//
.startObject("index")//
.field("number_of_shards", 1)//
.field("number_of_replicas", 0)//
.endObject()//
.endObject();
return builder;
}
private XContentBuilder createDictionaryMappingBuilder(final String type)
throws IOException {
final XContentBuilder mappingBuilder = XContentFactory.jsonBuilder()//
.startObject()//
.startObject(type)//
.startObject("_all")//
.field("enabled", false)//
.endObject()//
.startObject("_source")//
.field("enabled", false)//
.endObject()//
.startObject("properties")//
// path
.startObject(DictionaryConstants.PATH_FIELD)//
.field("type", "string")//
.field("index", "not_analyzed")//
.field("store", true)//
.endObject()//
// absolute_path
.startObject(DictionaryConstants.ABSOLUTE_PATH_FIELD)//
.field("type", "string")//
.field("index", "not_analyzed")//
.field("store", true)//
.endObject()//
// data
.startObject(DictionaryConstants.DATA_FIELD)//
.field("type", "binary")//
.field("store", true)//
// .field("compress", true)//
// .field("compress_threshold", -1)//
.endObject()//
.endObject()//
.endObject()//
.endObject();
return mappingBuilder;
}
private void addDictionaryFile(
final List<Tuple<String, File>> dictionaryList, final String value) {
if (!value.startsWith("/")) {
final File dictFileInConf = env.configFile().resolve(value).toFile();
if (dictFileInConf.exists()) {
dictionaryList.add(new Tuple<String, File>(value,
dictFileInConf));
return;
}
}
final File dictFile = new File(value);
if (dictFile.exists()) {
dictionaryList.add(new Tuple<String, File>(value, dictFile));
} else if (logger.isDebugEnabled()) {
logger.debug("{} is not found.", value);
}
}
private boolean isDictionaryFile(final String value) {
for (final String fileExtension : fileExtensions) {
if (value != null && value.endsWith("." + fileExtension)) {
return true;
}
}
return false;
}
class DeleteDictionaryRequestHandler
extends TransportRequestHandler<DeleteDictionaryRequest> {
@Override
public void messageReceived(final DeleteDictionaryRequest request, final TransportChannel channel) throws Exception {
deleteDictionarySnapshotOnMaster(request.repository, request.snapshot, new ActionListener<Void>() {
@Override
public void onResponse(Void response) {
try {
channel.sendResponse(new DeleteDictionaryResponse(true));
} catch (IOException e) {
throw ExceptionsHelper.convertToRuntime(e);
}
}
@Override
public void onFailure(Throwable e) {
try {
channel.sendResponse(new DeleteDictionaryResponse(false, e.getMessage()));
} catch (IOException e1) {
throw ExceptionsHelper.convertToRuntime(e);
}
}
});
}
}
public static class DeleteDictionaryRequest extends TransportRequest {
private String repository;
private String snapshot;
public DeleteDictionaryRequest() {
}
public DeleteDictionaryRequest(String repository, String snapshot) {
this.repository = repository;
this.snapshot = snapshot;
}
@Override
public void readFrom(final StreamInput in) throws IOException {
super.readFrom(in);
repository = in.readString();
snapshot = in.readString();
}
@Override
public void writeTo(final StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(repository);
out.writeString(snapshot);
}
}
private static class DeleteDictionaryResponse extends AcknowledgedResponse {
private String message;
DeleteDictionaryResponse() {
}
DeleteDictionaryResponse(final boolean acknowledged) {
super(acknowledged);
}
DeleteDictionaryResponse(final boolean acknowledged, final String message) {
super(acknowledged);
this.message = message;
}
@Override
public void readFrom(final StreamInput in) throws IOException {
super.readFrom(in);
readAcknowledged(in);
if (!isAcknowledged()) {
message = in.readString();
}
}
@Override
public void writeTo(final StreamOutput out) throws IOException {
super.writeTo(out);
writeAcknowledged(out);
if (!isAcknowledged()) {
out.writeString(message);
}
}
}
}
| 41.881844 | 137 | 0.539255 |
f5b34b30ae7a1b0a2bd34cf06da9f39b73a65d60 | 2,578 | package org.aikodi.chameleon.eclipse.property;
import org.aikodi.chameleon.core.element.Element;
import org.aikodi.chameleon.eclipse.view.outline.ChameleonOutlineTree;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.IProject;
import java.util.Collection;
/**
* A default class for testing properties. It extracts the
* actual receiver objects from collections and then runs
* more specialized tests.
*
* @author Marko van Dooren
*
*/
public class ChameleonPropertyTester extends PropertyTester {
@Override
public boolean test(Object receiver, String property, Object[] args,
Object expectedValue) {
try {
if(receiver instanceof Collection) {
for(Object object: (Collection)receiver) {
if(! doTest(object, property, args, expectedValue)) {
return false;
}
}
return true;
} else {
return doTest(receiver,property, args, expectedValue);
}
} catch (Exception e) {
return false;
}
}
private boolean doTest(Object receiver, String property, Object[] args,
Object expectedValue) {
boolean result = false;
if(receiver instanceof ChameleonOutlineTree) {
ChameleonOutlineTree selection = (ChameleonOutlineTree) receiver;
result = testChameleonElement(selection.getElement(), property, args, expectedValue);
} else if(receiver instanceof IProject){
result = testProject((IProject)receiver, property, args, expectedValue);
}
if(! result) {
result = testObject(receiver, property, args, expectedValue);
}
return result;
}
/**
* The fallback case when none of the other test methods is applicable or when they return false.
* @param object
* @param property
* @param args
* @param expectedValue
* @return
*/
protected boolean testObject(Object object, String property, Object[] args, Object expectedValue) {
return false;
}
/**
* Test whether the given element passes the test. The default
* return value is false.
*
* @param element The element to be tested.
* @param property The property the element is tested for.
* @return
*/
protected boolean testChameleonElement(Element element, String property, Object[] args, Object expectedValue) {
return false;
}
/**
* Test whether the given project passes the test. The default
* return value is false.
*
* @param element The project to be tested.
* @param property The property the project is tested for.
* @return
*/
protected boolean testProject(IProject project, String property, Object[] args, Object expectedValue) {
return false;
}
}
| 28.644444 | 112 | 0.724593 |
23ab3b35001ea1d2d44aeb066d74234f450a4e91 | 582 | package utilities;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import java.awt.*;
public class FontUtility {
public static UnicodeFont makeFont(int size){
UnicodeFont font = new UnicodeFont(new Font("Comic Sans MS", Font.BOLD, size));
font.getEffects().add(new ColorEffect(Color.WHITE));
font.addAsciiGlyphs();
try {
font.loadGlyphs();
} catch (SlickException e) {
e.printStackTrace();
}
return font;
}
}
| 26.454545 | 87 | 0.652921 |
bd1d1972fddb9ec8e21a29ef884df51ba4b657c4 | 3,030 | package com.unbox.dominio;
import java.util.HashSet;
import java.util.Set;
import com.unbox.exceptions.RegraNegocioException;
public class CPF {
private String cpf;
private static final Set cpfInvalidos = new HashSet();
static {
cpfInvalidos.add("00000000000");
cpfInvalidos.add("11111111111");
cpfInvalidos.add("22222222222");
cpfInvalidos.add("33333333333");
cpfInvalidos.add("44444444444");
cpfInvalidos.add("55555555555");
cpfInvalidos.add("66666666666");
cpfInvalidos.add("77777777777");
cpfInvalidos.add("88888888888");
cpfInvalidos.add("99999999999");
cpfInvalidos.add("00000000191");
cpfInvalidos.add("00000000686");
cpfInvalidos.add("99999994001");
cpfInvalidos.add("00000000686");
}
/**
* Construtor que deve receber um CPF válido, e apenas numérico.
* <p>
* Exemplo: O CPF 10000098744 <strong>não</strong> deve ser conter
* <strong>dígitos separadores</strong>: 100.000.987-44 ou 100000987-44
* </p>
*
* @param cpf
*/
public CPF(String cpf) throws RegraNegocioException {
validateSetCPF(cpf);
}
/**
* Constrói um objeto CPF sem definir o número de CPF em si.
*/
public CPF() {
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
/**
* @see CPF#CPF(String)
*/
public void validateSetCPF(String cpf) throws RegraNegocioException {
validateCPF(cpf);
setCpf(cpf);
}
public static void validateCPF(String cpf) throws RegraNegocioException {
validateCpfNull(cpf);
validateTamanho(cpf);
validateValores(cpf);
validateDV(cpf);
}
/**
* {@link CPF} não pode ser null
*
* @throws RegraNegocioException
*/
private static void validateCpfNull(String cpf) throws RegraNegocioException {
if (cpf == null)
throw new RegraNegocioException("ERRO CPF - CPF NULO");
}
/**
* @see Modulo11CPF
*/
private static void validateDV(String cpf) throws RegraNegocioException {
String cpfSemDV = cpf.substring(0, 9);
String dvCPF = cpf.substring(9);
String primeiroDV = String.valueOf(calculaPrimeiroDV(cpfSemDV));
String segundoDV = String.valueOf(calculaSegundoDV(cpfSemDV + primeiroDV));
if (!dvCPF.equals(primeiroDV + segundoDV))
throw new RegraNegocioException("ERRO CPF - DIGITO INVÁLIDO");
}
/**
* Valida se o CPF não está na lista de CPFs inválidos
*/
private static void validateValores(String cpf) throws RegraNegocioException {
if (cpfInvalidos.contains(cpf)) {
throw new RegraNegocioException("ERRO CPF - CPF VALORES INVÁLIDOS");
}
}
/**
* Valida se o CPF possui tamanho igual a 11
*/
private static void validateTamanho(String cpf) throws RegraNegocioException {
if (cpf.length() != 11) {
throw new RegraNegocioException("ERRO CPF - CPF TAMANHO INVÁLIDO");
}
}
/**
* @see Modulo11CPF
*/
private static int calculaPrimeiroDV(String cpf) {
return new Modulo11CPF(cpf, 10).getDV();
}
/**
* @see Modulo11CPF
*/
private static int calculaSegundoDV(String cpf) {
return new Modulo11CPF(cpf, 11).getDV();
}
}
| 23.307692 | 79 | 0.706601 |
c63630bdfb55724c8a7212bc4862bfaf4675ce25 | 2,586 | /*
*
*
*/
package ujf.verimag.bip.ifinder.analysis.petrinet;
import java.util.HashMap;
import java.util.ArrayList;
import bip2.ujf.verimag.bip.instance.*;
import bip2.ujf.verimag.bip.behavior.*;
/*
*
*
*/
public class XTransition {
// the component instance where the transition is defined
protected ComponentInstance m_instance;
// for visible transitions, their exported port
protected ExportedPortInstance m_port;
// the set of contained transitions
protected HashMap<AtomInstance, Transition> m_support;
// constructor from a transition in atomic component
protected XTransition(AtomInstance atom, Transition transition) {
m_instance = atom;
m_port = null;
m_support = new HashMap<AtomInstance,Transition>();
m_support.put(atom, transition);
}
// constructor from a set of syncronized transitions
protected XTransition(CompoundInstance compound,
ArrayList<XTransition> xtransitionSet) {
m_instance = compound;
m_port = null;
m_support = new HashMap<AtomInstance, Transition>();
for(XTransition xtransition : xtransitionSet) {
for(AtomInstance atom : xtransition.getSupport().keySet()) {
assert( m_support.get(atom) == null );
m_support.put(atom, xtransition.getSupport().get(atom));
}
}
}
// replica constructor (need at copy from subcomponents ...)
protected XTransition(CompoundInstance compound, XTransition xtransition) {
m_instance = compound;
m_port = null;
m_support = new HashMap<AtomInstance, Transition>();
for(AtomInstance atom : xtransition.getSupport().keySet())
m_support.put(atom, xtransition.getSupport().get(atom));
}
// access / update
public HashMap<AtomInstance, Transition> getSupport() { return m_support; }
public ExportedPortInstance getExportedPort() { return m_port; }
public void setExportedPort(ExportedPortInstance port) { m_port = port; }
// dump
public void dump() {
System.out.print("[");
if (m_port != null)
System.out.print(m_port.getDeclaration().getName());
System.out.print("] ");
for(AtomInstance atom : m_support.keySet()) {
Transition t = m_support.get(atom);
for(State s : t.getSources())
System.out.print(atom.getDeclaration().getName() +
"." + s.getName() + " ");
}
System.out.print(" -> ");
for(AtomInstance atom : m_support.keySet()) {
Transition t = m_support.get(atom);
for(State s : t.getDestinations())
System.out.print(atom.getDeclaration().getName() +
"." + s.getName() + " ");
}
System.out.println();
}
}
| 27.221053 | 79 | 0.688708 |
7af19cca07e7a202cd6c88926b4b753ec3135eec | 4,018 | package client;
import classes.User;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
/**
* Class achievements.
*/
public class Achievements {
/**
* Show badges method.
*
* @param grid paramter grid
* @param user parameter user.
* @param window window parameter.
*/
public static void showBadges(final GridPane grid, final User user, final Stage window) {
/**
* Calls method in class to show PolarBadges.
*/
AchievementsPolar.showPolarBadges(user, window);
/**
* Calls method in class to show FoodBadges.
*/
AchievementsFood.showFoodBadges(user, window);
/**
* Calls method in class to show TransportBadges.
*/
AchievementsTransport.showTransportBadges(user, window);
/**
* Calls method in class to show ElectricityBadges.
*/
AchievementsElectricity.showElectricityBadges(user, window);
/**
* Set label for achievements, initialize VBox for badges.
*/
Label myAchievements = new Label("My Achievements!");
myAchievements.setFont(Font.font("Amble CN", FontWeight.BOLD, 45));
myAchievements.setTextFill(Color.web("#0076a3"));
VBox achievements = new VBox();
achievements.setStyle("-fx-padding: 5;");
achievements.setSpacing(10);
achievements.setStyle("-fx-padding: 1;"
+ "-fx-border-style: solid inside; -fx-alignment: center;"
+ "-fx-border-width: 5;" + "-fx-border-insets: 5;"
+ "-fx-border-radius: 5;" + "-fx-border-color: #6dfff3;"
+ "-fx-background-color: rgba(255,255,255,0.4)");
/**
* Label for polar badges.
*/
Label polarLabel = new Label("POLAR");
polarLabel.setFont(Font.font("Amble CN", FontWeight.BOLD, 30));
polarLabel.setTextFill(Color.web("#0076a3"));
/**
* Polar score badges.
*/
HBox polarHbox = AchievementsPolar.getPolarBox();
polarHbox.setSpacing(1);
/**
* Label for food badges.
*/
Label foodLabel = new Label("FOOD");
foodLabel.setFont(Font.font("Amble CN", FontWeight.BOLD, 30));
foodLabel.setTextFill(Color.web("#0076a3"));
/**
* Food score badges.
*/
final HBox foodHbox = AchievementsFood.getFoodBox();
polarHbox.setSpacing(1);
/**
* transport score badges.
*/
HBox transportHbox = AchievementsTransport.getTransportBox();
transportHbox.setSpacing(1);
/**
* transport score badges.
*/
HBox electricityHbox = AchievementsElectricity.getElectricityBox();
electricityHbox.setSpacing(1);
/**
* Label for transport badges.
*/
Label transportLabel = new Label("TRANSPORT");
transportLabel.setFont(Font.font("Amble CN", FontWeight.BOLD, 30));
transportLabel.setTextFill(Color.web("#0076a3"));
/**
* Label for electricity badges.
*/
Label electricityLabel = new Label("ELECTRICITY");
electricityLabel.setFont(Font.font("Amble CN", FontWeight.BOLD, 30));
electricityLabel.setTextFill(Color.web("#0076a3"));
/**
* Adds all badges in specific Hboxes to Vbox // styling.
*/
achievements.getChildren().addAll(myAchievements, polarLabel, polarHbox, foodLabel,
foodHbox, transportLabel,
transportHbox, electricityLabel, electricityHbox);
grid.getChildren().setAll(achievements);
grid.setMinWidth(1500);
grid.setStyle("-fx-font-size: 18pt; -fx-padding: 10px; -fx-alignment: center;");
}
}
| 32.666667 | 93 | 0.60005 |
dbc8b8945140752bc71b0b36a5a22a520877bcce | 306 | package no.hvl.dat104.dataaccess;
import no.hvl.dat104.model.ItemEntity;
import java.util.List;
public interface IItemEAO {
void addItem(ItemEntity v);
ItemEntity findItem(Integer id);
void updateItem(ItemEntity v);
void removeItem(ItemEntity id);
List<ItemEntity> allItems();
}
| 17 | 38 | 0.728758 |
f0120a3f8b072cb75b943f54c142541be07dbc80 | 484 | package edu.washington.cse.instrumentation.tests;
import java.util.Random;
public class StringOverheadTest {
@SuppressWarnings("unused")
public static void main(String[] args) {
long start = System.currentTimeMillis();
Random r = new Random();
for(int i = 0; i < 1000000; i++) {
boolean foo = r.nextBoolean();
String s = foo ? "gorp" : "qux";
String res = "foo" + s + "baz";
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
| 24.2 | 49 | 0.657025 |
45844536e26bc4bf9111432c6e0d958d4f2812f0 | 991 | package ru.geminisystems.entity;
/**
* Created by IntelliJ IDEA.
* User: gb
* Date: 08.07.2009
* Time: 2:25:36
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "statuses")
public class Status {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "statusId", nullable = false)
private Long statusId;
@Column(name = "statusName", nullable = false)
private String statusName;
@Column(name = "alias", nullable = true)
private String alias;
public Long getStatusId() {
return statusId;
}
public void setStatusId(Long statusId) {
this.statusId = statusId;
}
public String getStatusName() {
return statusName;
}
public void setStatusName(String statusName) {
this.statusName = statusName;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
}
| 20.22449 | 64 | 0.632694 |
0d3a362bd4c6cfaf353b6871a3eb551b7d82bd65 | 570 | /**
* Copyright (2018-2019) Institute of Software, Chinese Academy of Sciences
*/
package com.github.isdream.amazon.ec2;
import com.github.isdream.jointware.core.ModelParameterGenerator;
/**
* @author [email protected]
*
* 2018年5月4日
*/
public class AmazonEC2ModelParameterGenerator extends ModelParameterGenerator {
/**
*
*/
public AmazonEC2ModelParameterGenerator() {
super();
}
/**
* @param objectRef
*/
public AmazonEC2ModelParameterGenerator(String objectRef) {
super(objectRef);
}
}
| 18.387097 | 79 | 0.67193 |
1a5e5dab4e5b8ce447d89862bb18f6d6dde131d2 | 3,049 | package com.marcoscg.easyabout.helpers;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.View;
import com.marcoscg.easyabout.items.HeaderAboutItem;
import com.marcoscg.easyabout.items.NormalAboutItem;
/**
* Created by @MarcosCGdev on 21/02/2018.
*/
public final class AboutItemBuilder {
public static HeaderAboutItem.Builder generateAppTitleItem(Context context) {
PackageManager packageManager = context.getPackageManager();
ApplicationInfo applicationInfo = context.getApplicationInfo();
return new HeaderAboutItem.Builder(context)
.setTitle(packageManager.getApplicationLabel(applicationInfo).toString())
.setIcon(packageManager.getApplicationIcon(applicationInfo));
}
public static NormalAboutItem.Builder generateAppVersionItem(Context context, boolean withVersionCode) {
PackageManager packageManager = context.getPackageManager();
String version = "";
try {
version = packageManager.getPackageInfo(context.getPackageName(), 0).versionName;
if (withVersionCode)
version += " (" + packageManager.getPackageInfo(context.getPackageName(), 0).versionCode + ")";
} catch (Exception e) {
e.printStackTrace();
}
return new NormalAboutItem.Builder(context)
.setTitle("Version")
.setSubtitle(version);
}
public static NormalAboutItem.Builder generateLinkItem(final Context context, final String url) {
return new NormalAboutItem.Builder(context)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
public static NormalAboutItem.Builder generateEmailItem(final Context context, final String email) {
return generateLinkItem(context, "mailto:" + email);
}
public static NormalAboutItem.Builder generatePlayStoreItem(final Context context) {
final String appPackageName = context.getPackageName();
return new NormalAboutItem.Builder(context)
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
} catch (ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
});
}
}
| 41.767123 | 160 | 0.648409 |
6ec8222c40c00dc7b18f0a79ad7131796fe3e0ad | 694 | package com.sportsmeeting.serviceimpl;
import com.sportsmeeting.dao.NewsDao;
import com.sportsmeeting.entity.News;
import com.sportsmeeting.service.NewsService;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class NewsServiceImplement implements NewsService {
NewsDao newsDao;
@Autowired
void setNewsDao(NewsDao newsDao) {
this.newsDao = newsDao;
}
@Override
public List<News> getNews() {
return newsDao.getNews();
}
@Override
public List<Object> getNewsByNewsId(Integer newsId) {
return newsDao.getNewsByNewsId(newsId);
}
}
| 21.6875 | 62 | 0.775216 |
4c3a1eabf7f78f4b9415606d8067132877c7717b | 30,180 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* Portions Copyrighted 2007 Sun Microsystems, Inc.
*/
package org.netbeans.modules.cnd.editor.cplusplus;
import org.junit.Ignore;
import org.netbeans.modules.cnd.editor.api.CodeStyle;
import org.netbeans.modules.cnd.editor.options.EditorOptions;
/**
* Class was taken from java
* Links point to java IZ.
* C/C++ specific tests begin from testSystemInclude
*/
public class BracketCompletionTestCase extends EditorBase {
public BracketCompletionTestCase(String testMethodName) {
super(testMethodName);
}
// ------- Tests for raw strings -------------
@Ignore
public void testModifyRawStringInPPDirective() {
// #241929 - AssertionError at org.netbeans.modules.cnd.lexer.CppStringLexer.nextToken
setDefaultsOptions();
typeCharactersInText("#define R|\"\"", "'", "#define R'\"\"");
}
public void testSimpleQuoteInRawString() throws Exception {
setDefaultsOptions();
typeCharactersInText("R|", "\"", "R\"|()\"");
}
public void testLeftParenInRawStringStartDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"|()\"", "(", " R\"(|)\"");
}
public void testRawStringDelete() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R|\"()\"", "\f", " R");
typeCharactersInText(" R\"|()\"", "\f", " R");
typeCharactersInText(" R\"|()\"", "\b", " R");
typeCharactersInText(" R\"(|)\"", "\f", " R");
typeCharactersInText(" R\"(|)\"", "\b", " R");
typeCharactersInText(" R\"()|\"", "\f", " R");
typeCharactersInText(" R\"()|\"", "\b", " R");
}
public void testRawStringNewLine() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"XYZ(te|xt)XYZ\"", "\n", " R\"XYZ(te\n|xt)XYZ\"");
}
public void testRawStringDelStartDelimeter() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"|XYZ()XYZ\"", "\f", " R\"|YZ()YZ\"");
typeCharactersInText(" R\"X|YZ()XYZ\"", "\b", " R\"|YZ()YZ\"");
typeCharactersInText(" R\"X|YZ()XYZ\"", "\f", " R\"X|Z()XZ\"");
typeCharactersInText(" R\"XY|Z()XYZ\"", "\b", " R\"X|Z()XZ\"");
typeCharactersInText(" R\"XY|Z()XYZ\"", "\f", " R\"XY|()XY\"");
typeCharactersInText(" R\"XYZ|()XYZ\"", "\b", " R\"XY|()XY\"");
}
public void testRawStringDelEndDelimeter() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"XYZ()|XYZ\"", "\f", " R\"YZ()|YZ\"");
typeCharactersInText(" R\"XYZ()X|YZ\"", "\b", " R\"YZ()|YZ\"");
typeCharactersInText(" R\"XYZ()X|YZ\"", "\f", " R\"XZ()X|Z\"");
typeCharactersInText(" R\"XYZ()XY|Z\"", "\b", " R\"XZ()X|Z\"");
typeCharactersInText(" R\"XYZ()XY|Z\"", "\f", " R\"XY()XY|\"");
typeCharactersInText(" R\"XYZ()XYZ|\"", "\b", " R\"XY()XY|\"");
}
public void testLeftParenInRawStringStartDelim2() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"XXX|()XXX\"", "(", " R\"XXX(|)XXX\"");
}
public void testQuoteInRawStringEndDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"delim()delim|\" ", "\"", " R\"delim()delim\"| ");
}
public void testQuoteInRawStringEndDelim2() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"()|\" ", "\"", " R\"()\"| ");
}
public void testRightParenInRawStringWithEmptyDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"(|)\" ", ")", " R\"()|\" ");
}
public void testRightParenInRawStringBeforeEndDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"ddd(|)ddd\" ", ")", " R\"ddd()|)ddd\" ");
}
public void testTypeInRawStringStartDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"del|im()delim\" ", "U", " R\"delU|im()delUim\" ");
typeCharactersInText(" R\"delim|()delim\" ", "E", " R\"delimE|()delimE\" ");
typeCharactersInText(" R\"|delim()delim\" ", "S", " R\"S|delim()Sdelim\" ");
}
public void testType2InRawStringStartDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"del|im()delim\" ", "UU", " R\"delUU|im()delUUim\" ");
typeCharactersInText(" R\"delim|()delim\" ", "EE", " R\"delimEE|()delimEE\" ");
typeCharactersInText(" R\"|delim()delim\" ", "SS", " R\"SS|delim()SSdelim\" ");
}
public void testTypeInRawStringEndDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"delim()del|im\" ", "U", " R\"delUim()delU|im\" ");
typeCharactersInText(" R\"delim()delim|\" ", "A", " R\"delimA()delimA|\" ");
typeCharactersInText(" R\"delim()|delim\" ", "B", " R\"Bdelim()B|delim\" ");
}
public void test2TypeInRawStringEndDelim() throws Exception {
setDefaultsOptions();
typeCharactersInText(" R\"delim()del|im\" ", "UU", " R\"delUUim()delUU|im\" ");
typeCharactersInText(" R\"delim()delim|\" ", "AA", " R\"delimAA()delimAA|\" ");
typeCharactersInText(" R\"delim()|delim\" ", "BB", " R\"BBdelim()BB|delim\" ");
}
// ------- Test of . to -> completion
public void testThisDotToArrow() {
setDefaultsOptions();
typeCharactersInText("this|", ".", "this->|");
}
// ------- Tests for completion of right parenthesis ')' -------------
public void testRightParenSimpleMethodCall() {
setDefaultsOptions();
typeCharactersInText("m()|)", ")", "m())|");
}
public void testRightParenSwingInvokeLaterRunnable() {
setDefaultsOptions();
typeCharactersInText(
"SwingUtilities.invokeLater(new Runnable()|))",
")",
"SwingUtilities.invokeLater(new Runnable())|)");
}
public void testRightParenSwingInvokeLaterRunnableRun() {
setDefaultsOptions();
typeCharactersInText(
"SwingUtilities.invokeLater(new Runnable() {\n"
+ " public void run()|)\n"
+ "})",
")",
"SwingUtilities.invokeLater(new Runnable() {\n"
+ " public void run())|\n"
+ "})"
);
}
public void testRightParenIfMethodCall() {
setDefaultsOptions();
typeCharactersInText(
" if (a()|) + 5 > 6) {\n"
+ " }",
")",
" if (a())| + 5 > 6) {\n"
+ " }"
);
}
public void testNotSkipRPAREN() throws Exception {
// #225194 - incorrect skipping of right parent
setDefaultsOptions();
typeCharactersInText(
" if ((n == 0|) {\n"
+ " }",
")",
" if ((n == 0)) {\n"
+ " }");
}
public void testRightParenSkipInPP() throws Exception {
// extra fix for #225194 - incorrect skipping of right parent
setDefaultsOptions();
typeCharactersInText("#define A(|) 1\n", ")", "#define A()| 1\n");
}
public void testRightParenNoSkipNonBracketChar() {
setDefaultsOptions();
typeCharactersInText("m()| ", ")", "m())| ");
}
public void testRightParenNoSkipDocEnd() {
setDefaultsOptions();
typeCharactersInText("m()|", ")", "m())|");
}
// ------- Tests for completion of right brace '}' -------------
public void testAddRightBraceIfLeftBrace() {
setDefaultsOptions();
typeCharactersInText("if (true) {|", "\n", "if (true) {\n |\n}");
}
public void testAddRightBraceIfLeftBraceWhiteSpace() {
setDefaultsOptions();
typeCharactersInText("if (true) { \t|\n",
"\n",
"if (true) { \t\n"
+ " |\n"
+ "}\n");
}
public void testAddRightBraceIfLeftBraceLineComment() {
setDefaultsOptions();
typeCharactersInText("if (true) { // line-comment|\n",
"\n",
"if (true) { // line-comment\n"
+ " |\n"
+ "}\n");
}
public void testAddRightBraceIfLeftBraceBlockComment() {
setDefaultsOptions();
typeCharactersInText("if (true) { /* block-comment */|\n",
"\n",
"if (true) { /* block-comment */\n"
+ " |\n"
+ "}\n");
}
public void testAddRightBraceIfLeftBraceAlreadyPresent() {
setDefaultsOptions();
typeCharactersInText(
"if (true) {|\n"
+ "}",
"\n",
"if (true) {\n" +
" |\n"
+ "}"
);
}
public void testAddRightBraceCaretInComment() {
setDefaultsOptions();
typeCharactersInText(
"if (true) { /* in-block-comment |\n",
"\n",
"if (true) { /* in-block-comment \n"
+ " * |\n"
);
}
public void testSimpleAdditionOfOpeningParenthesisAfterWhile () throws Exception {
setDefaultsOptions();
typeCharactersInText(
"while |",
"(",
"while (|)"
);
}
// ------- Tests for completion of quote (") -------------
public void testSimpleQuoteInEmptyDoc () throws Exception {
setDefaultsOptions();
typeCharactersInText("|", "\"", "\"|\"");
}
public void testSimpleQuoteAtBeginingOfDoc () throws Exception {
setDefaultsOptions();
typeCharactersInText("| ", "\"", "\"|\" ");
}
public void testSimpleQuoteAtEndOfDoc () throws Exception {
setDefaultsOptions();
typeCharactersInText(" |", "\"", " \"|\"");
}
public void testSimpleQuoteInWhiteSpaceArea () throws Exception {
setDefaultsOptions();
typeCharactersInText(" | ", "\"", " \"|\" ");
}
public void testQuoteAtEOL () throws Exception {
setDefaultsOptions();
typeCharactersInText(" |\n", "\"", " \"|\"\n");
}
public void testQuoteWithUnterminatedStringLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" \"unterminated string| \n", "\"",
" \"unterminated string\"| \n");
}
public void testQuoteAtEOLWithUnterminatedStringLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" \"unterminated string |\n", "\"",
" \"unterminated string \"|\n");
}
public void testQuoteInsideStringLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" \"stri|ng literal\" ", "\"",
" \"stri\"|ng literal\" ");
}
public void testQuoteInsideEmptyParentheses() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(|) ", "\"",
" printf(\"|\") ");
}
public void testQuoteInsideNonEmptyParentheses() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(|some text) ", "\"",
" printf(\"|some text) ");
}
public void testQuoteInsideNonEmptyParenthesesBeforeClosingParentheses() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(i+|) ", "\"",
" printf(i+\"|\") ");
}
public void testQuoteInsideNonEmptyParenthesesBeforeClosingParenthesesAndUnterminatedStringLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(\"unterminated string literal |); ", "\"",
" printf(\"unterminated string literal \"|); ");
}
public void testQuoteBeforePlus() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(|+\"string literal\"); ", "\"",
" printf(\"|\"+\"string literal\"); ");
}
public void testQuoteBeforeComma() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s[] = new String[]{|,\"two\"};", "\"",
"String s[] = new String[]{\"|\",\"two\"};");
}
public void testQuoteBeforeBrace() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s[] = new String[]{\"one\",|};", "\"",
"String s[] = new String[]{\"one\",\"|\"};");
}
public void testQuoteBeforeSemicolon() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s = \"\" + |;", "\"",
"String s = \"\" + \"|\";");
}
public void testQuoteBeforeSemicolonWithWhitespace() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s = \"\" +| ;", "\"",
"String s = \"\" +\"|\" ;");
}
public void testQuoteAfterEscapeSequence() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"\\|", "\"",
"\\\"|");
}
/**
* issue #69524
*/
public void testQuoteEaten() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"|",
"\"\"",
"\"\"|");
}
/**
* issue #69935
*/
public void testQuoteInsideComments() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"/** |\n */",
"\"",
"/** \"|\n */");
}
/**
* issue #71880
*/
public void testQuoteAtTheEndOfLineCommentLine() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"// test line comment |\n", "\"",
"// test line comment \"|\n");
}
// ------- Tests for completion of single quote (') -------------
public void testSingleQuoteInEmptyDoc() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"|",
"'",
"'|'");
}
public void testSingleQuoteAtBeginingOfDoc() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"| ",
"'",
"'|' ");
}
public void testSingleQuoteAtEndOfDoc() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" |",
"'",
" '|'");
}
public void testSingleQuoteInWhiteSpaceArea() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" | ",
"'",
" '|' ");
}
public void testSingleQuoteAtEOL() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" |\n",
"'",
" '|'\n");
}
public void testSingleQuoteWithUnterminatedCharLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" '| \n",
"'",
" ''| \n");
}
public void testSingleQuoteAtEOLWithUnterminatedCharLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" ' |\n",
"'",
" ' '|\n");
}
public void testSingleQuoteInsideCharLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" '| ' ",
"'",
" ''| ' ");
}
public void testSingleQuoteInsideEmptyParentheses() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(|) ",
"'",
" printf('|') ");
}
public void testSingleQuoteInsideNonEmptyParentheses() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(|some text) ",
"'",
" printf('|some text) ");
}
public void testSingleQuoteInsideNonEmptyParenthesesBeforeClosingParentheses() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(i+|) ",
"'",
" printf(i+'|') ");
}
public void testSingleQuoteInsideNonEmptyParenthesesBeforeClosingParenthesesAndUnterminatedCharLiteral() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(' |); ",
"'",
" printf(' '|); ");
}
public void testSingleQuoteBeforePlus() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" printf(|+\"string literal\"); ",
"'",
" printf('|'+\"string literal\"); ");
}
public void testSingleQuoteBeforeComma() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s[] = new String[]{|,\"two\"};",
"'",
"String s[] = new String[]{'|',\"two\"};");
}
public void testSingleQuoteBeforeBrace() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s[] = new String[]{\"one\",|};",
"'",
"String s[] = new String[]{\"one\",'|'};");
}
public void testSingleQuoteBeforeSemicolon() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s = \"\" + |;",
"'",
"String s = \"\" + '|';");
}
public void testsingleQuoteBeforeSemicolonWithWhitespace() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"String s = \"\" +| ;",
"'",
"String s = \"\" +'|' ;");
}
public void testSingleQuoteAfterEscapeSequence() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"\\|",
"'",
"\\'|");
}
/**
* issue #69524
*/
public void testSingleQuoteEaten() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"|", "''",
"''|");
}
/**
* issue #69935
*/
public void testSingleQuoteInsideComments() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"/* |\n */",
"'",
"/* \'|\n */");
}
/**
* issue #71880
*/
public void testSingleQuoteAtTheEndOfLineCommentLine() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"// test line comment |\n",
"'",
"// test line comment \'|\n");
}
public void testNoGT() {
setDefaultsOptions();
typeCharactersInText(
"if (a |)\n",
"<",
"if (a <|)\n");
}
public void testNoGTInString() {
setDefaultsOptions();
typeCharactersInText(
"\"hello |\"\n",
"<",
"\"hello <|\"\n");
}
public void testSystemInclude() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include |\n",
"<",
"#include <|>\n");
}
public void testSystemIncludeEOF() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include |",
"<",
"#include <|>");
}
public void testSkipSystemInclude() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include <math.h|>\n",
">",
"#include <math.h>|\n");
}
public void testNotSkipSystemInclude() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include <math|.h>\n",
">",
"#include <math>|.h>\n");
}
public void testUserInclude() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include |\n", "\"",
"#include \"|\"\n");
}
public void testUserIncludeEOF() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include |", "\"",
"#include \"|\"");
}
public void testSkipUserInclude() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"#include \"h.h|\"\n",
"\"",
"#include \"h.h\"|\n");
}
public void testArray() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"int a|\n",
"[",
"int a[|]\n");
}
public void testRightBracePreprocessor() {
setDefaultsOptions();
typeCharactersInText(
"void foo(){\n" +
"#if A\n" +
" if (a){\n" +
"#else\n" +
" if (b){|\n" +
"#endif\n" +
" }\n" +
"}",
"\n",
"void foo(){\n"
+ "#if A\n"
+ " if (a){\n"
+ "#else\n"
+ " if (b){\n"
+ " |\n"
+ "#endif\n"
+ " }\n"
+ "}"
);
}
public void testRightBracePreprocessor2() {
setDefaultsOptions();
typeCharactersInText(
"void foo(){\n" +
"#if A\n" +
" if (a){|\n" +
"#else\n" +
" if (b){\n" +
"#endif\n" +
" }\n" +
"}",
"\n",
"void foo(){\n" +
"#if A\n" +
" if (a){\n" +
" |\n" +
"#else\n" +
" if (b){\n" +
"#endif\n" +
" }\n" +
"}"
);
}
public void testRightBracePreprocessor3() {
setDefaultsOptions();
typeCharactersInText(
"void foo(){\n" +
"#if A\n" +
" if (a){|\n" +
"#else\n" +
" if (b){\n" +
"#endif\n" +
"// }\n" +
"}",
"\n",
"void foo(){\n" +
"#if A\n" +
" if (a){\n" +
" |\n" +
" }\n" +
"#else\n" +
" if (b){\n" +
"#endif\n" +
"// }\n" +
"}"
);
}
public void testRightBracePreprocessor4() {
setDefaultsOptions();
typeCharactersInText(
"void foo(){\n" +
"#if A\n" +
" if (a){\n" +
"#else\n" +
" if (b){\n" +
"#endif\n" +
" if (b){|\n" +
" }\n" +
"}",
"\n",
"void foo(){\n" +
"#if A\n" +
" if (a){\n" +
"#else\n" +
" if (b){\n" +
"#endif\n" +
" if (b){\n" +
" |\n" +
" }\n" +
" }\n" +
"}"
);
}
public void testRightBracePreprocessor5() {
setDefaultsOptions();
typeCharactersInText(
"void foo(){\n" +
"#define PAREN {\n" +
" if (b){|\n" +
" }\n" +
"}",
"\n",
"void foo(){\n" +
"#define PAREN {\n" +
" if (b){\n" +
" |\n" +
" }\n" +
"}"
);
}
public void testIZ102091() throws Exception {
setDefaultsOptions();
EditorOptions.getPreferences(CodeStyle.getDefault(CodeStyle.Language.CPP, getDocument())).
put(EditorOptions.newLineBeforeBrace,
CodeStyle.BracePlacement.NEW_LINE.name());
typeCharactersInText (
"if(i)\n"+
" |",
"{",
"if(i)\n"+
"{|"
);
}
public void testColonAfterPublic() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"class A{\n" +
" public|\n" +
"}\n",
":", // "Colon After Public"
"class A{\n" +
"public:\n" +
"}\n"
);
}
public void testIdentFunctionName() throws Exception {
setDefaultsOptions("GNU");
typeCharactersInText(
"tree\n" +
" |",
"d", // Incorrect identing of main",
"tree\n" +
"d|"
);
}
// test line break
public void testBreakLineInString1() throws Exception {
setDefaultsOptions();
typeCharactersInText(
"char* a = \"|\"",
"\n", // "Incorrect identing of main",
"char* a = \"\"\n" +
"\"|\"");
}
public void testBreakLineInString2() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" char* a = \"\\|\"",
"\n",
" char* a = \"\\\n" +
"|\"");
}
public void testBreakLineInString2_1() throws Exception {
setDefaultsOptions();
// TODO: second line should be in the first column after fixing bug in indentation
typeCharactersInText(
" char* a = \"\\\\|\"",
"\n",
" char* a = \"\\\\\"\n" +
" \"|\"");
}
public void testBreakLineInString3() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" char* a = \"\\|",
"\n",
" char* a = \"\\\n" +
"|");
}
public void testBreakLineInString31() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" char* a = \"\\|\n",
"\n",
" char* a = \"\\\n" +
"|\n");
}
public void testBreakLineInString4() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" char* a = \"\\|\"",
"\n",
" char* a = \"\\\n" +
"|\"");
}
public void testBreakLineInString41() throws Exception {
setDefaultsOptions();
typeCharactersInText(
" char* a = \"\\|\"\n",
"\n",
" char* a = \"\\\n" +
"|\"\n");
}
public void testBreakLineAfterLCurly() {
setDefaultsOptions();
typeCharactersInText(
"void foo() {|",
"\n",
"void foo() {\n" +
" |\n" +
"}");
}
public void testBreakLineAfterLCurly2() {
setDefaultsOptions();
typeCharactersInText(
"struct A {|",
"\n",
"struct A {\n" +
" |\n" +
"};");
}
public void testBlockCommentAutoCompletion() throws Exception {
setDefaultsOptions();
typeCharactersInText("#define A\n/|\nvoid foo() {\n}\n", "*", "#define A\n/*|*/\nvoid foo() {\n}\n");
typeCharactersInText("#define A\n/| \nvoid foo() {\n}\n", "*", "#define A\n/*|*/ \nvoid foo() {\n}\n");
typeCharactersInText("#define A\n /| \nvoid foo() {\n}\n", "*", "#define A\n /*|*/ \nvoid foo() {\n}\n");
typeCharactersInText("int a;\n /| \nvoid foo() {\n}\n", "*", "int a;\n /*|*/ \nvoid foo() {\n}\n");
typeCharactersInText("int a; /|\nvoid foo() {\n}\n", "*", "int a; /*|\nvoid foo() {\n}\n");
typeCharactersInText("int a; /| \nvoid foo() {\n}\n", "*", "int a; /*| \nvoid foo() {\n}\n");
typeCharactersInText("int a;\n/*void| foo() {\n}\n", "*", "int a;\n/*void*| foo() {\n}\n");
typeCharactersInText("int a;\n/*|void foo() {\n}\n", "*", "int a;\n/**|void foo() {\n}\n");
}
}
| 31.569038 | 127 | 0.476077 |
e23c18b6e6438c77d5077e5bcb6a19a94be372cc | 1,223 | package commands;
import basetool.SystemClipboardTools;
import extensions.SoundTypeWriter;
import io.airlift.command.Command;
import io.airlift.command.Option;
/**
* @author linxi
* www.leftvalue.top
* commands
* Date 2018/8/5 3:26 PM
*/
public class Fun {
@Command(name = "qinqin", description = "a magic colorful typewriter, get input from system clipboard, print with G80 sounds")
public static class TypeWriter implements Runnable {
@Option(name = {"-s", "--speed"}, description = "the speed of the type writer:low normal high")
public String speed = "normal";
@Override
public void run() {
String str = SystemClipboardTools.get();
if (str.trim().isEmpty()) {
System.out.println("Sorry but your system clipboard is empty,please copy some words");
return;
}
speed = speed.toUpperCase();
if (speed.startsWith("L")) {
new SoundTypeWriter(str, 1.25).print();
} else if (speed.startsWith("H")) {
new SoundTypeWriter(str, 0.7).print();
} else {
new SoundTypeWriter(str).print();
}
}
}
}
| 30.575 | 130 | 0.588716 |
1b754b6e0faece2d375d176d46c241db604bb475 | 1,292 | package com.example.instagramclone;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LoginActivity extends AppCompatActivity {
public static final String TAG = "LoginActivity";
private EditText etUsername;
private EditText etPassword;
private Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = findViewById(R.id.etUsername);
etPassword = findViewById(R.id.etPassword);
btnLogin = findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i(TAG, "onClick login button");
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
loginUser(username,password);
}
private void loginUser(String username, String password) {
Log.i(TAG, "Attempting to login user" + username);
}
});
}
} | 33.128205 | 70 | 0.662539 |
1f428bc094ae33722827307321dfdb966bfcfb41 | 162 | package com.skmuddamsetty.linkedlists;
public class Node {
public int data;
public Node next;
public Node(int d) {
this.data = d;
this.next = null;
}
}
| 13.5 | 38 | 0.685185 |
744810007b6acf56fdc2dde26eee878450ed965c | 6,189 | package controller_msgs.msg.dds;
/**
*
* Topic data type of the struct "TaskspaceTrajectoryStamped" defined in "TaskspaceTrajectoryStamped_.idl". Use this class to provide the TopicDataType to a Participant.
*
* This file was automatically generated from TaskspaceTrajectoryStamped_.idl by us.ihmc.idl.generator.IDLGenerator.
* Do not update this file directly, edit TaskspaceTrajectoryStamped_.idl instead.
*
*/
public class TaskspaceTrajectoryStampedPubSubType implements us.ihmc.pubsub.TopicDataType<controller_msgs.msg.dds.TaskspaceTrajectoryStamped>
{
public static final java.lang.String name = "controller_msgs::msg::dds_::TaskspaceTrajectoryStamped_";
private final us.ihmc.idl.CDR serializeCDR = new us.ihmc.idl.CDR();
private final us.ihmc.idl.CDR deserializeCDR = new us.ihmc.idl.CDR();
public TaskspaceTrajectoryStampedPubSubType()
{
}
public static int getMaxCdrSerializedSize()
{
return getMaxCdrSerializedSize(0);
}
public static int getMaxCdrSerializedSize(int current_alignment)
{
int initial_alignment = current_alignment;
current_alignment += std_msgs.msg.dds.HeaderPubSubType.getMaxCdrSerializedSize(current_alignment);
current_alignment += 4 + us.ihmc.idl.CDR.alignment(current_alignment, 4);
for (int a = 0; a < 100; ++a)
{
current_alignment += geometry_msgs.msg.dds.PoseStampedPubSubType.getMaxCdrSerializedSize(current_alignment);
}
current_alignment += builtin_interfaces.msg.dds.DurationPubSubType.getMaxCdrSerializedSize(current_alignment);
return current_alignment - initial_alignment;
}
public final static int getCdrSerializedSize(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data)
{
return getCdrSerializedSize(data, 0);
}
public final static int getCdrSerializedSize(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, int current_alignment)
{
int initial_alignment = current_alignment;
current_alignment += std_msgs.msg.dds.HeaderPubSubType.getCdrSerializedSize(data.getHeader(), current_alignment);
current_alignment += 4 + us.ihmc.idl.CDR.alignment(current_alignment, 4);
for (int a = 0; a < data.getTrajectory_points_stamped().size(); ++a)
{
current_alignment += geometry_msgs.msg.dds.PoseStampedPubSubType.getCdrSerializedSize(data.getTrajectory_points_stamped().get(a), current_alignment);
}
current_alignment += builtin_interfaces.msg.dds.DurationPubSubType.getCdrSerializedSize(data.getTime_from_start(), current_alignment);
return current_alignment - initial_alignment;
}
public static void write(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, us.ihmc.idl.CDR cdr)
{
std_msgs.msg.dds.HeaderPubSubType.write(data.getHeader(), cdr);
if (data.getTrajectory_points_stamped().size() <= 100)
cdr.write_type_e(data.getTrajectory_points_stamped());
else
throw new RuntimeException("trajectory_points_stamped field exceeds the maximum length");
builtin_interfaces.msg.dds.DurationPubSubType.write(data.getTime_from_start(), cdr);
}
public static void read(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, us.ihmc.idl.CDR cdr)
{
std_msgs.msg.dds.HeaderPubSubType.read(data.getHeader(), cdr);
cdr.read_type_e(data.getTrajectory_points_stamped());
builtin_interfaces.msg.dds.DurationPubSubType.read(data.getTime_from_start(), cdr);
}
public static void staticCopy(controller_msgs.msg.dds.TaskspaceTrajectoryStamped src, controller_msgs.msg.dds.TaskspaceTrajectoryStamped dest)
{
dest.set(src);
}
@Override
public void serialize(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, us.ihmc.pubsub.common.SerializedPayload serializedPayload)
throws java.io.IOException
{
serializeCDR.serialize(serializedPayload);
write(data, serializeCDR);
serializeCDR.finishSerialize();
}
@Override
public void deserialize(us.ihmc.pubsub.common.SerializedPayload serializedPayload, controller_msgs.msg.dds.TaskspaceTrajectoryStamped data)
throws java.io.IOException
{
deserializeCDR.deserialize(serializedPayload);
read(data, deserializeCDR);
deserializeCDR.finishDeserialize();
}
@Override
public final void serialize(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, us.ihmc.idl.InterchangeSerializer ser)
{
ser.write_type_a("header", new std_msgs.msg.dds.HeaderPubSubType(), data.getHeader());
ser.write_type_e("trajectory_points_stamped", data.getTrajectory_points_stamped());
ser.write_type_a("time_from_start", new builtin_interfaces.msg.dds.DurationPubSubType(), data.getTime_from_start());
}
@Override
public final void deserialize(us.ihmc.idl.InterchangeSerializer ser, controller_msgs.msg.dds.TaskspaceTrajectoryStamped data)
{
ser.read_type_a("header", new std_msgs.msg.dds.HeaderPubSubType(), data.getHeader());
ser.read_type_e("trajectory_points_stamped", data.getTrajectory_points_stamped());
ser.read_type_a("time_from_start", new builtin_interfaces.msg.dds.DurationPubSubType(), data.getTime_from_start());
}
@Override
public controller_msgs.msg.dds.TaskspaceTrajectoryStamped createData()
{
return new controller_msgs.msg.dds.TaskspaceTrajectoryStamped();
}
@Override
public int getTypeSize()
{
return us.ihmc.idl.CDR.getTypeSize(getMaxCdrSerializedSize());
}
@Override
public java.lang.String getName()
{
return name;
}
public void serialize(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, us.ihmc.idl.CDR cdr)
{
write(data, cdr);
}
public void deserialize(controller_msgs.msg.dds.TaskspaceTrajectoryStamped data, us.ihmc.idl.CDR cdr)
{
read(data, cdr);
}
public void copy(controller_msgs.msg.dds.TaskspaceTrajectoryStamped src, controller_msgs.msg.dds.TaskspaceTrajectoryStamped dest)
{
staticCopy(src, dest);
}
@Override
public TaskspaceTrajectoryStampedPubSubType newInstance()
{
return new TaskspaceTrajectoryStampedPubSubType();
}
} | 36.839286 | 169 | 0.751979 |
5e1477e614b0189b9ee9672c31443d8c8d3d31aa | 695 | package org.nutz.dao.impl.sql.callback;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
public class FetchMapCallback implements SqlCallback {
public static SqlCallback me = new FetchMapCallback();
public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
if (null != rs && rs.next()) {
LinkedHashMap<String, Object> re = new LinkedHashMap<String, Object>();
Record.create(re, rs, null);
return re;
}
return null;
}
}
| 26.730769 | 86 | 0.683453 |
dd38a6bdd0b5cd2823856fa0471772afbcf56211 | 1,162 | package com.example.endpoints;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.messaging.MessageChannel;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
@SpringJUnitConfig
@ContextConfiguration(classes = FilterFlow.class)
class FilterFlowTest {
@Autowired
private MessageChannel input;
@Autowired
private QueueChannel output;
@Test
void test() {
for (int i = 0; i < 10; i++) {
input.send(MessageBuilder.withPayload(i).build());
}
assertEquals(1, output.receive().getPayload());
assertEquals(3, output.receive().getPayload());
assertEquals(5, output.receive().getPayload());
assertEquals(7, output.receive().getPayload());
assertEquals(9, output.receive().getPayload());
assertEquals(0, output.getQueueSize());
}
}
| 32.277778 | 72 | 0.728916 |
556ea463cc305faf2dd52765d04f447677b46af7 | 656 | package org.ric.strukdat.project;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author MONICA
*/
public class Stack<E> {
LinkedList<E> list;
public Stack() {
list = new LinkedList<E>();
}
public E pop() {
return list.removeLast();
}
public void push(E data) {
list.addLast(data);
}
public boolean isEmpty() {
return list.isEmpty();
}
public E peek() {
return (E) (list.getLast().getData());
}
public int size() {
// TODO Auto-generated method stub
return list.size();
}
}
| 16 | 52 | 0.550305 |
979117a488fcd6d0c82415c7637f7d655b5a2d08 | 863 | package com.example.fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by zhoujunyu on 2019/3/25.
*/
public class MyFragment extends Fragment {
private String mContent;
public MyFragment(String content) {
mContent = content;
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment,container,false);
TextView textView = view.findViewById(R.id.tv_fg);
textView.setText(mContent);
return view;
}
}
| 26.96875 | 132 | 0.738123 |
d3cc65c01744c0b554daed2bf0d4209a09066e1f | 8,931 | /*
* Copyright 1999-2021 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.fastffi.llvm;
public class LLVMTypeRefiner {
public static Constant refine(Constant c) {
return (Constant) refine((Value) c);
}
public static Value refine(Value v) {
if (v == null) {
return null;
}
ValueTy valueTy = v.getValueID();
switch (valueTy) {
case FunctionVal:
return Function.dyn_cast(v);
case GlobalAliasVal:
return GlobalAlias.dyn_cast(v);
case GlobalIFuncVal:
return GlobalIFunc.dyn_cast(v);
case GlobalVariableVal:
return GlobalVariable.dyn_cast(v);
case BlockAddressVal:
return BlockAddress.dyn_cast(v);
case ConstantExprVal:
return ConstantExpr.dyn_cast(v);
case ConstantArrayVal:
return ConstantArray.dyn_cast(v);
case ConstantStructVal:
return ConstantStruct.dyn_cast(v);
case ConstantVectorVal:
return ConstantVector.dyn_cast(v);
case UndefValueVal:
return UndefValue.dyn_cast(v);
case ConstantAggregateZeroVal:
return ConstantAggregateZero.dyn_cast(v);
case ConstantDataArrayVal:
return ConstantDataArray.dyn_cast(v);
case ConstantDataVectorVal:
return ConstantDataVector.dyn_cast(v);
case ConstantIntVal:
return ConstantInt.dyn_cast(v);
case ConstantFPVal:
return ConstantFP.dyn_cast(v);
case ConstantPointerNullVal:
return ConstantPointerNull.dyn_cast(v);
case ConstantTokenNoneVal:
return ConstantTokenNone.dyn_cast(v);
case ArgumentVal:
return Argument.dyn_cast(v);
case BasicBlockVal:
return BasicBlock.dyn_cast(v);
case MetadataAsValueVal:
return MetadataAsValue.dyn_cast(v);
case InlineAsmVal:
return null;
case MemoryUseVal:
case MemoryDefVal:
case MemoryPhiVal:
throw new IllegalArgumentException("Unsupported valueId " + valueTy);
case InstructionVal:
return refine(Instruction.dyn_cast(v));
default:
throw new IllegalArgumentException("Invalid valueId " + valueTy);
}
}
public static Instruction refine(Instruction inst) {
if (inst == null) {
return null;
}
Opcode opcode = inst.getOpcode();
switch (opcode) {
case Ret:
return ReturnInst.dyn_cast(inst);
case Br:
return BranchInst.dyn_cast(inst);
case Switch:
return SwitchInst.dyn_cast(inst);
case IndirectBr:
return IndirectBrInst.dyn_cast(inst);
case Invoke:
return InvokeInst.dyn_cast(inst);
case Resume:
return ResumeInst.dyn_cast(inst);
case Unreachable:
return UnreachableInst.dyn_cast(inst);
case CleanupRet:
return CleanupReturnInst.dyn_cast(inst);
case CatchSwitch:
return CatchSwitchInst.dyn_cast(inst);
case CallBr:
return CallBrInst.dyn_cast(inst);
case FNeg:
return UnaryOperator.dyn_cast(inst);
case Add:
case FAdd:
case Sub:
case FSub:
case Mul:
case FMul:
case UDiv:
case SDiv:
case FDiv:
case URem:
case SRem:
case FRem:
case Shl:
case LShr:
case AShr:
case And:
case Or:
case Xor:
return BinaryOperator.dyn_cast(inst);
case Alloca:
return AllocaInst.dyn_cast(inst);
case Load:
return LoadInst.dyn_cast(inst);
case Store:
return StoreInst.dyn_cast(inst);
case GetElementPtr:
return GetElementPtrInst.dyn_cast(inst);
case Fence:
return FenceInst.dyn_cast(inst);
case AtomicCmpXchg:
return AtomicCmpXchgInst.dyn_cast(inst);
case AtomicRMW:
return AtomicRMWInst.dyn_cast(inst);
case Trunc:
return TruncInst.dyn_cast(inst);
case ZExt:
return ZExtInst.dyn_cast(inst);
case SExt:
return SExtInst.dyn_cast(inst);
case FPToUI:
return FPToUIInst.dyn_cast(inst);
case FPToSI:
return FPToSIInst.dyn_cast(inst);
case UIToFP:
return UIToFPInst.dyn_cast(inst);
case SIToFP:
return SIToFPInst.dyn_cast(inst);
case FPTrunc:
return FPTruncInst.dyn_cast(inst);
case FPExt:
return FPExtInst.dyn_cast(inst);
case PtrToInt:
return PtrToIntInst.dyn_cast(inst);
case IntToPtr:
return IntToPtrInst.dyn_cast(inst);
case BitCast:
return BitCastInst.dyn_cast(inst);
case AddrSpaceCast:
return AddrSpaceCastInst.dyn_cast(inst);
case CleanupPad:
return CleanupPadInst.dyn_cast(inst);
case CatchPad:
return CatchPadInst.dyn_cast(inst);
case ICmp:
return ICmpInst.dyn_cast(inst);
case FCmp:
return FCmpInst.dyn_cast(inst);
case PHI:
return PHINode.dyn_cast(inst);
case Call:
if (IntrinsicInst.isa(inst)) {
return IntrinsicInst.cast(inst);
}
return CallInst.dyn_cast(inst);
case Select:
return SelectInst.dyn_cast(inst);
case UserOp1:
case UserOp2:
throw new UnsupportedOperationException();
case VAArg:
return VAArgInst.dyn_cast(inst);
case ExtractElement:
return ExtractElementInst.dyn_cast(inst);
case InsertElement:
return InsertElementInst.dyn_cast(inst);
case ShuffleVector:
return ShuffleVectorInst.dyn_cast(inst);
case ExtractValue:
return ExtractValueInst.dyn_cast(inst);
case InsertValue:
return InsertValueInst.dyn_cast(inst);
case LandingPad:
return LandingPadInst.dyn_cast(inst);
case Freeze:
return FreezeInst.dyn_cast(inst);
default:
throw new IllegalArgumentException("Unsupported opcode: " + opcode);
}
}
public static Type refine(Type type) {
if (type == null) {
return null;
}
TypeID typeID = type.getTypeID();
switch (typeID) {
case VoidTyID:
case HalfTyID:
case FloatTyID:
case DoubleTyID:
case X86_FP80TyID:
case FP128TyID:
case PPC_FP128TyID:
case LabelTyID:
case MetadataTyID:
case X86_MMXTyID:
case TokenTyID:
return type;
case IntegerTyID:
return IntegerType.dyn_cast(type);
case FunctionTyID:
return FunctionType.dyn_cast(type);
case StructTyID:
return StructType.dyn_cast(type);
case ArrayTyID:
return ArrayType.dyn_cast(type);
case PointerTyID:
return PointerType.dyn_cast(type);
case FixedVectorTyID:
return FixedVectorType.dyn_cast(type);
case ScalableVectorTyID:
return ScalableVectorType.dyn_cast(type);
default:
throw new IllegalArgumentException("Unsupported typeId " + typeID);
}
}
}
| 36.012097 | 85 | 0.540813 |
83d73d67dd88f82fb21bc426f6164d4a3ce8be3b | 1,041 | package me.mckoxu.mckmagazyn.skript.conditions;
import ch.njol.skript.lang.Condition;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.util.Kleenean;
import com.sun.istack.internal.Nullable;
import me.mckoxu.mckmagazyn.MCKMagazyn;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.event.Event;
public class MagExist extends Condition{
private Expression<Number> number;
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] expr, int i, Kleenean kl, SkriptParser.ParseResult pr) {
number = (Expression<Number>) expr[0];
return true;
}
@Override
public String toString(@Nullable Event e, boolean b) {
return null;
}
@Override
public boolean check(Event e){
int i = number.getSingle(e).intValue();
ConfigurationSection csk = MCKMagazyn.getInst().getConfig().getConfigurationSection("data.magazyny."+i);
if(csk != null) {
return true;
} else{
return false;
}
}
}
| 28.135135 | 106 | 0.716619 |
0b79ab4da6d1b195cdb817e6c4534faea6929c61 | 1,578 |
package eu.doppel_helix.jna.tlb.excel1;
import com.sun.jna.platform.win32.COM.util.IComEnum;
public enum XlParameterDataType implements IComEnum {
/**
* (0)
*/
xlParamTypeUnknown(0),
/**
* (1)
*/
xlParamTypeChar(1),
/**
* (2)
*/
xlParamTypeNumeric(2),
/**
* (3)
*/
xlParamTypeDecimal(3),
/**
* (4)
*/
xlParamTypeInteger(4),
/**
* (5)
*/
xlParamTypeSmallInt(5),
/**
* (6)
*/
xlParamTypeFloat(6),
/**
* (7)
*/
xlParamTypeReal(7),
/**
* (8)
*/
xlParamTypeDouble(8),
/**
* (12)
*/
xlParamTypeVarChar(12),
/**
* (9)
*/
xlParamTypeDate(9),
/**
* (10)
*/
xlParamTypeTime(10),
/**
* (11)
*/
xlParamTypeTimestamp(11),
/**
* (-1)
*/
xlParamTypeLongVarChar(-1),
/**
* (-2)
*/
xlParamTypeBinary(-2),
/**
* (-3)
*/
xlParamTypeVarBinary(-3),
/**
* (-4)
*/
xlParamTypeLongVarBinary(-4),
/**
* (-5)
*/
xlParamTypeBigInt(-5),
/**
* (-6)
*/
xlParamTypeTinyInt(-6),
/**
* (-7)
*/
xlParamTypeBit(-7),
/**
* (-8)
*/
xlParamTypeWChar(-8),
;
private XlParameterDataType(long value) {
this.value = value;
}
private long value;
public long getValue() {
return this.value;
}
} | 12.934426 | 53 | 0.404943 |
d66b773ab6c1e9d4f63a7921b6524e83eaa06498 | 1,066 | package id.my.avmmartin.matched.data.prefs;
import android.content.Context;
import android.content.SharedPreferences;
import id.my.avmmartin.matched.utils.Constants;
public class PreferencesHelper {
private SharedPreferences sharedPreferences;
// username
public String getUsername() {
return sharedPreferences.getString(Constants.SHARED_PREFS_USERNAME, null);
}
public void setUsername(String username) {
sharedPreferences.edit().putString(Constants.SHARED_PREFS_USERNAME, username).apply();
}
// user token
public String getUserToken() {
return sharedPreferences.getString(Constants.SHARED_PREFS_USER_TOKEN, null);
}
public void setUserToken(String userToken) {
sharedPreferences.edit().putString(Constants.SHARED_PREFS_USER_TOKEN, userToken).apply();
}
// constructor
public PreferencesHelper(Context context) {
sharedPreferences = context.getSharedPreferences(
Constants.SHARED_PREFS_FILE_NAME,
Context.MODE_PRIVATE
);
}
}
| 26.65 | 97 | 0.722326 |
f862aaa7dedbc639ba6976f90095a240da3ac435 | 6,746 | /*
* Copyright 2009 Mike Cumings
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.igniterealtime.jbosh;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.xlightweb.IFutureResponse;
import org.xlightweb.IHttpResponse;
import org.xlightweb.PostRequest;
import org.xlightweb.client.HttpClient;
final class XLightWebResponse implements HTTPResponse {
/**
* Name of the accept encoding header.
*/
private static final String ACCEPT_ENCODING = "Accept-Encoding";
/**
* Value to use for the ACCEPT_ENCODING header.
*/
private static final String ACCEPT_ENCODING_VAL =
ZLIBCodec.getID() + ", " + GZIPCodec.getID();
/**
* Name of the content encoding header.
*/
private static final String CONTENT_ENCODING = "Content-Encoding";
/**
* Name of the character set to encode the body to/from.
*/
private static final String CHARSET = "UTF-8";
/**
* Content type to use when transmitting the body data.
*/
private static final String CONTENT_TYPE = "text/xml; charset=utf-8";
/**
* Lock used for internal synchronization.
*/
private final Lock lock = new ReentrantLock();
/**
* Response future that we'll pull our results from.
*/
private final IFutureResponse future;
/**
* The response after it's been pulled from the future, or {@code null}
* if that has not yet happened.
*/
private IHttpResponse httpResp;
/**
* The response body after it's been pulled from the future, or {@code null}
* if that has not yet happened.
*/
private AbstractBody resp;
/**
* Exception to throw when the response data is attempted to be accessed,
* or {@code null} if no exception should be thrown.
*/
private BOSHException toThrow;
/**
* Create and send a new request to the upstream connection manager,
* providing deferred access to the results to be returned.
*
* @param client client instance to use when sending the request
* @param cfg client configuration
* @param params connection manager parameters from the session creation
* response, or {@code null} if the session has not yet been established
* @param request body of the client request
*/
XLightWebResponse(
final HttpClient client,
final BOSHClientConfig cfg,
final CMSessionParams params,
final AbstractBody request) {
super();
IFutureResponse futureVal;
try {
String xml = request.toXML();
byte[] data = xml.getBytes(CHARSET);
String encoding = null;
if (cfg.isCompressionEnabled() && params != null) {
AttrAccept accept = params.getAccept();
if (accept != null) {
if (accept.isAccepted(ZLIBCodec.getID())) {
encoding = ZLIBCodec.getID();
data = ZLIBCodec.encode(data);
} else if (accept.isAccepted(GZIPCodec.getID())) {
encoding = GZIPCodec.getID();
data = GZIPCodec.encode(data);
}
}
}
PostRequest post = new PostRequest(
cfg.getURI().toString(), CONTENT_TYPE, data);
if (encoding != null) {
post.setHeader(CONTENT_ENCODING, encoding);
}
post.setTransferEncoding(null);
post.setContentLength(data.length);
if (cfg.isCompressionEnabled()) {
post.setHeader(ACCEPT_ENCODING, ACCEPT_ENCODING_VAL);
}
futureVal = client.send(post);
} catch (IOException iox) {
toThrow = new BOSHException("Could not send request", iox);
futureVal = null;
}
future = futureVal;
}
/**
* Abort the client transmission and response processing.
*/
public void abort() {
if (future != null) {
future.cancel(true);
}
}
/**
* Wait for and then return the response HTTP status.
*
* @return http status of the response
* @throws InterruptedException if interrupted while awaiting the response
* @throws BOSHException on communication cfailure
*/
public int getHTTPStatus() throws InterruptedException, BOSHException {
awaitResponse();
return httpResp.getStatus();
}
/**
* Wait for and then return the response body.
*
* @return body of the response
* @throws InterruptedException if interrupted while awaiting the response
* @throws BOSHException on communication cfailure
*/
public AbstractBody getBody() throws InterruptedException, BOSHException {
awaitResponse();
return resp;
}
/**
* Await the response, storing the result in the instance variables of
* this class when they arrive.
*
* @throws InterruptedException if interrupted while awaiting the response
* @throws BOSHException on communicationf ailure
*/
private void awaitResponse() throws InterruptedException, BOSHException {
lock.lock();
try {
if (toThrow != null) {
throw(toThrow);
}
if (httpResp != null) {
return;
}
httpResp = future.getResponse();
byte[] data = httpResp.getBlockingBody().readBytes();
String encoding = httpResp.getHeader(CONTENT_ENCODING);
if (ZLIBCodec.getID().equalsIgnoreCase(encoding)) {
data = ZLIBCodec.decode(data);
} else if (GZIPCodec.getID().equalsIgnoreCase(encoding)) {
data = GZIPCodec.decode(data);
}
String bodyStr = new String(data, CHARSET);
resp = StaticBody.fromString(bodyStr);
} catch (IOException iox) {
toThrow = new BOSHException("Could not obtain response", iox);
throw(toThrow);
} finally {
lock.unlock();
}
}
}
| 32.907317 | 80 | 0.608805 |
b1b06b5a5432bf40377792dfbd4b80abea1ebc86 | 4,998 | /*
* BSD 2-Clause License
*
* Copyright (c) 2020, dutta64 <https://github.com/dutta64>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.playerattacktimer;
import java.awt.Color;
import java.awt.Font;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.runelite.client.config.Alpha;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;
import net.runelite.client.config.ConfigSection;
import net.runelite.client.config.Range;
import net.runelite.client.config.Units;
@ConfigGroup("playerattacktimer")
public interface PlayerAttackTimerConfig extends Config
{
@ConfigSection(
name = "Settings",
description = "",
position = 0,
keyName = "settings"
)
String settings = "Settings";
@ConfigSection(
name = "Font Settings",
description = "",
position = 1,
keyName = "fontSettings"
)
String fontSettings = "Font Settings";
//------------------------------------------------------------//
// Settings
//------------------------------------------------------------//
@ConfigItem(
name = "Debug animation ids",
description = "Show your player's current animation ID."
+ "<br>Animation IDs can be viewed by wielding a weapon and attacking an NPC.",
position = 0,
keyName = "debugAnimationIds",
section = settings,
disabledBy = "playerAttackTimer"
)
default boolean debugAnimationIds()
{
return false;
}
@ConfigItem(
name = "Custom animations (one per line)",
description = "Syntax AnimationID:TickDelay"
+ "<br>e.g. Abyssal whip would be 1658:4"
+ "<br>Animation Ids can be obtained by enabling the above debug setting."
+ "<br>Weapon tick delays can be found on the wiki.",
position = 1,
keyName = "customAnimations",
section = settings,
parse = true,
clazz = ConfigParser.class,
method = "parse"
)
default String customAnimations()
{
return "";
}
//------------------------------------------------------------//
// Font Settings
//------------------------------------------------------------//
@ConfigItem(
name = "Font style",
description = "Font style can be bold, plain, or italicized.",
position = 0,
keyName = "fontStyle",
section = fontSettings,
enumClass = FontStyle.class
)
default FontStyle fontStyle()
{
return FontStyle.BOLD;
}
@ConfigItem(
name = "Font shadow",
description = "Toggle font shadow.",
position = 1,
keyName = "fontShadow",
section = fontSettings
)
default boolean fontShadow()
{
return true;
}
@Range(
min = 12,
max = 64
)
@ConfigItem(
name = "Font size",
description = "Adjust font size.",
position = 2,
keyName = "fontSize",
section = fontSettings
)
@Units(Units.POINTS)
default int fontSize()
{
return 20;
}
@Alpha
@ConfigItem(
name = "Font color",
description = "Adjust font color.",
position = 3,
keyName = "fontColor",
section = fontSettings
)
default Color fontColor()
{
return new Color(255, 0, 0, 255);
}
@Range(
min = -100,
max = 100
)
@ConfigItem(
name = "Font zOffset",
description = "Adjust the Z coordinate offset.",
position = 4,
keyName = "fontZOffset",
section = fontSettings
)
@Units(Units.POINTS)
default int fontZOffset()
{
return 0;
}
//------------------------------------------------------------//
// Constants
//------------------------------------------------------------//
@Getter
@AllArgsConstructor
enum FontStyle
{
BOLD("Bold", Font.BOLD),
ITALIC("Italic", Font.ITALIC),
PLAIN("Plain", Font.PLAIN);
private final String name;
private final int font;
@Override
public String toString()
{
return name;
}
}
}
| 25.630769 | 82 | 0.655662 |
e8ba7cade36b72ab0baa19d5173da892c151520b | 703 | package org.webswing.server.services.security.modules.keycloak;
import org.webswing.server.common.model.Config;
import org.webswing.server.common.model.meta.ConfigField;
import org.webswing.server.common.model.meta.ConfigFieldOrder;
import org.webswing.server.common.model.meta.ConfigFieldVariables;
/**
* Created by vikto on 09-Feb-17.
*/
@ConfigFieldOrder({ "realm", "logoutUrl" })
public interface RealmEntry extends Config {
@ConfigField(label = "Realm Name")
@ConfigFieldVariables
String getRealm();
@ConfigField(label = "Logout URL", description = "Webswing will redirect to this URL after logout for user logged in against this realm.")
@ConfigFieldVariables
String getLogoutUrl();
}
| 31.954545 | 139 | 0.783784 |
f4fac25a49b39ecf063398871a9fa661c2708709 | 3,654 | package tk.slicecollections.maxteer.titles;
import com.mongodb.client.MongoCursor;
import org.bson.Document;
import org.bukkit.inventory.ItemStack;
import tk.slicecollections.maxteer.database.Database;
import tk.slicecollections.maxteer.database.MongoDBDatabase;
import tk.slicecollections.maxteer.player.Profile;
import tk.slicecollections.maxteer.utils.BukkitUtils;
import tk.slicecollections.maxteer.utils.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* @author Maxter
*/
public class Title {
private String id;
private String icon;
private String title;
public Title(String id, String title, String desc) {
this.id = id;
this.icon = "%material%:%durability% : 1 : esconder>tudo : nome>%name% : desc>&fTítulo: " + title + "\n \n" + desc + "\n \n%action%";
this.title = title;
}
public String getId() {
return this.id;
}
public String getTitle() {
return this.title;
}
public void give(Profile profile) {
if (!this.has(profile)) {
profile.getTitlesContainer().add(this);
}
}
public boolean has(Profile profile) {
return profile.getTitlesContainer().has(this);
}
public ItemStack getIcon(Profile profile) {
boolean has = this.has(profile);
Title selected = profile.getSelectedContainer().getTitle();
return BukkitUtils.deserializeItemStack(
this.icon.replace("%material%", has ? (selected != null && selected.equals(this)) ? "MAP" : "EMPTY_MAP" : "STAINED_GLASS_PANE").replace("%durability%", has ? "0" : "14")
.replace("%name%", (has ? "&a" : "&c") + StringUtils.stripColors(this.title))
.replace("%action%", (has ? (selected != null && selected.equals(this)) ? "&eClique para deselecionar!" : "&eClique para selecionar!" : "&cVocê não possui este título.")));
}
private static final List<Title> TITLES = new ArrayList<>();
public static void setupTitles() {
TITLES.add(new Title("tbk", "§cSentinela da Ponte", "&8Pode ser desbloqueado através do\n&8Desafio \"Assassino das Pontes\"&8."));
TITLES.add(new Title("tbw", "§6Líder da Ponte", "&8Pode ser desbloqueado através do\n&8Desafio \"Glorioso sobre Pontes\"&8."));
TITLES.add(new Title("tbp", "§ePontuador Mestre", "&8Pode ser desbloqueado através do\n&8Desafio \"Maestria em Pontuação\"&8."));
TITLES.add(new Title("swk", "§cAnjo da Morte", "&8Pode ser desbloqueado através do\n&8Desafio \"Traidor Celestial\"&8."));
TITLES.add(new Title("sww", "§bRei Celestial", "&8Pode ser desbloqueado através do\n&8Desafio \"Destrono Celestial\"&8."));
TITLES.add(new Title("swa", "§6Companheiro de Asas", "&8Pode ser desbloqueado através do\n&8Desafio \"Anjo Guardião\"&8."));
TITLES.add(new Title("mmd", "§6Sherlock Holmes", "&8Pode ser desbloqueado através do\n&8Desafio \"Detetive\"&8."));
TITLES.add(new Title("mmk", "§4Jef the Killer", "&8Pode ser desbloqueado através do\n&8Desafio \"Serial Killer\"&8."));
if (Database.getInstance() instanceof MongoDBDatabase) {
MongoDBDatabase database = ((MongoDBDatabase) Database.getInstance());
MongoCursor<Document> titles = database.getDatabase().getCollection("mCoreTitles").find().cursor();
while (titles.hasNext()) {
Document title = titles.next();
TITLES.add(new Title(title.getString("_id"), title.getString("name"), title.getString("description")));
}
titles.close();
}
}
public static Title getById(String id) {
return TITLES.stream().filter(title -> title.getId().equals(id)).findFirst().orElse(null);
}
public static Collection<Title> listTitles() {
return TITLES;
}
}
| 38.87234 | 180 | 0.686371 |
9c9a3165c66b365b58a0e857d04673c0caa8962b | 3,015 | package com.progwml6.natura.world;
import com.progwml6.natura.Natura;
import com.progwml6.natura.common.ClientEventBase;
import com.progwml6.natura.world.block.TreeType;
import com.progwml6.natura.world.client.LeavesColorizer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.color.BlockColors;
import net.minecraft.client.renderer.color.ItemColors;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockDisplayReader;
import net.minecraft.world.biome.BiomeColors;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import javax.annotation.Nullable;
@SuppressWarnings("unused")
@Mod.EventBusSubscriber(modid = Natura.MOD_ID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD)
public class WorldClientEvents extends ClientEventBase {
@SubscribeEvent
static void clientSetup(FMLClientSetupEvent event) {
for (TreeType type : TreeType.values()) {
RenderTypeLookup.setRenderLayer(NaturaWorld.leaves.get(type), RenderType.getCutoutMipped());
RenderTypeLookup.setRenderLayer(NaturaWorld.sapling.get(type), RenderType.getCutout());
}
RenderTypeLookup.setRenderLayer(NaturaWorld.redwood_leaves.get(), RenderType.getCutoutMipped());
RenderTypeLookup.setRenderLayer(NaturaWorld.redwood_sapling.get(), RenderType.getCutout());
RenderTypeLookup.setRenderLayer(NaturaWorld.cotton_crop.get(), RenderType.getCutout());
RenderTypeLookup.setRenderLayer(NaturaWorld.barley_crop.get(), RenderType.getCutout());
}
@SubscribeEvent
static void registerColorHandlers(ColorHandlerEvent.Item event) {
BlockColors blockColors = event.getBlockColors();
ItemColors itemColors = event.getItemColors();
for (TreeType type : TreeType.values()) {
blockColors.register(
(state, reader, pos, index) -> getLeavesColorByPos(reader, pos, type),
NaturaWorld.leaves.get(type)
);
}
blockColors.register((state, reader, pos, index) -> getLeavesColorByPos(reader, pos), NaturaWorld.redwood_leaves.get());
registerBlockItemColorAlias(blockColors, itemColors, NaturaWorld.leaves);
registerBlockItemColorAlias(blockColors, itemColors, NaturaWorld.redwood_leaves);
}
private static int getLeavesColorByPos(@Nullable IBlockDisplayReader reader, @Nullable BlockPos pos, TreeType type) {
if (pos == null || reader == null) {
return LeavesColorizer.getColorStatic(type);
}
return LeavesColorizer.getColorForPos(reader, pos, type);
}
private static int getLeavesColorByPos(@Nullable IBlockDisplayReader reader, @Nullable BlockPos pos) {
if (pos == null || reader == null) {
return LeavesColorizer.leaves2Color;
}
return BiomeColors.getFoliageColor(reader, pos);
}
}
| 40.743243 | 124 | 0.779104 |
ec543c6032bb690e9d09386b430be2620ad5fe9e | 713 | package com.prasertcbs;
public class Main {
public static void main(String[] args) {
demo3();
}
public static void demo() {
Person p1 = new Person();
p1.setFirstName("Peter");
p1.setLastName("Parker");
p1.setGender("M");
p1.setNickName("Pete");
}
public static void demo2() {
Person p2 = new Person("peTEr", "Parker", "Pete", "M");
System.out.println(p2.getFirstName());
}
public static void demo3() {
Person p3 = new Person("peTEr", "pete");
System.out.println(p3.getFirstName());
p3.setFirstName("abCDEf");
System.out.println(p3.getFirstName());
}
}
| 24.586207 | 64 | 0.539972 |
03df4d799c3a6451f80757b7a4662b2023240e16 | 2,948 | package com.example.android.abnd_project3_jonathanfernandezgomez;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int score = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void calculateScore() {
RadioButton vegeta = findViewById(R.id.vegeta);
if (vegeta.isChecked()) {
score++;
}
EditText attackName = findViewById(R.id.attack_editText);
String attackEntry = attackName.getText().toString().trim().toLowerCase();
if (attackEntry.equals("kamehameha")) {
score++;
}
CheckBox sonGohan = findViewById(R.id.gohan_checkBox);
CheckBox sonGoku = findViewById(R.id.goku_checkBox);
CheckBox videl = findViewById(R.id.videl_checkBox);
CheckBox trunks = findViewById(R.id.trunks_checkBox);
CheckBox yamcha = findViewById(R.id.yamcha_checkBox);
CheckBox popo = findViewById(R.id.popo_checkBox);
CheckBox krillin = findViewById(R.id.krillin_checkBox);
if ((videl.isChecked() && yamcha.isChecked() && krillin.isChecked()) && !(sonGohan.isChecked() || sonGoku.isChecked() || trunks.isChecked() || popo.isChecked())) {
score = score + 3;
} else if ((videl.isChecked() && yamcha.isChecked() || krillin.isChecked() && videl.isChecked() || krillin.isChecked() && yamcha.isChecked()) && !(sonGohan.isChecked() || sonGoku.isChecked() || trunks.isChecked() || popo.isChecked())) {
score = score + 2;
} else if ((videl.isChecked() || krillin.isChecked() || yamcha.isChecked()) && !(sonGohan.isChecked() || sonGoku.isChecked() || trunks.isChecked() || popo.isChecked())) {
score++;
}
EditText authorName = findViewById(R.id.author_editText);
String authorEntry = authorName.getText().toString().trim().toLowerCase();
if (authorEntry.equals("akira toriyama")) {
score++;
}
}
public void displayScore(View view) {
score = 0;
calculateScore();
if (score == 0) {
Toast.makeText(this, "Try it harder the next time, INSECT!", Toast.LENGTH_LONG).show();
} else if (score <= 3) {
Toast.makeText(this, "Keep training and you'll defeat Yamcha (maybe).", Toast.LENGTH_LONG).show();
} else if (score <= 5) {
Toast.makeText(this, "Let's protect the Earth together!", Toast.LENGTH_LONG).show();
} else if (score == 6) {
Toast.makeText(this, "You're an ALL MIGHTY SUPER SAIYAN!", Toast.LENGTH_LONG).show();
}
}
} | 42.724638 | 244 | 0.63806 |
323c574eede06b529514450d7bef3fcd6f993294 | 2,631 | package l04;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class App {
public static void main(String[] args) {
long count = 0;
try {
Random random = new Random();
List<Integer[]> list = new ArrayList<>();
while (true) {
for (int i = 0; i < 10; i++) {
list.add(new Integer[500]);
count += 500;
if (random.nextBoolean()) {
list.remove(random.nextInt(list.size()));
}
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
throw new RuntimeException();
}
}
} catch (OutOfMemoryError error) {
System.out.println(count);
}
}
}
/*
java -verbose:gc -XX:+UseSerialGC -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:SerialGC.log -Xms1500m -Xmx1500m -jar target/L04-1.0-SNAPSHOT.jar
752998000 интов
java -verbose:gc -XX:+UseParallelGC -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:ParallelGC.log -Xms1500m -Xmx1500m -jar target/L04-1.0-SNAPSHOT.jar
713311500 интов
java -verbose:gc -XX:+UseParNewGC -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:ParNewGC.log -Xms1500m -Xmx1500m -jar target/L04-1.0-SNAPSHOT.jar
752174500 интов
java -verbose:gc -XX:+UseG1GC -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:G1GC.log -Xms1500m -Xmx1500m -jar target/L04-1.0-SNAPSHOT.jar
777752000 интов
Результат обработки логов:
---------------------------------
G1GC
[16:16]: 0.4059362
[16:17]: 0.9766377
[16:18]: 0.3349364
[16:19]: 1.2107481
[16:20]: 3.2138809
[16:21]: 1.620251
[16:22]: 6.7817123
[16:23]: 12.7618063
Total: 27.3059089
ParallelGC
[16:01]: 0.2345259
[16:02]: 0.4438332
[16:03]: 0.5259364
[16:04]: 0.5292354
[16:05]: 0.6187218
[16:06]: 4.4280492
[16:07]: 20.9968867
Total: 27.7771886
ParNewGC
[16:08]: 0.1257852
[16:09]: 0.1887278
[16:10]: 0.1974144
[16:11]: 0.5709091
[16:12]: 0.7190586
[16:13]: 1.7040784
[16:14]: 11.4238248
[16:15]: 25.4836721
Total: 40.4134704
SerialGC
[15:52]: 0.197957
[15:53]: 0.2915809
[15:54]: 0.30458
[15:55]: 0.5708216
[15:56]: 0.6423111
[15:57]: 0.7908907
[15:58]: 4.0285227
[15:59]: 34.9548546
Total: 41.7815186
Выводы:
----------------------------------
Все типы GC в последнюю минуту проявляют максимум активности, что логично. Для данной программы выгоднее всего оказался G1,
так как меньше всего потрачено на сборку мусора суммарно. И больше полезных действий выполнено
*/
| 24.361111 | 159 | 0.607374 |
7e23e515f4cb5f70161f3909554b4a7bb803339c | 76 | package us.eunoians.mcrpg.api.displays;
public interface ActionBarBase {
}
| 15.2 | 39 | 0.802632 |
f263614de90e6cf7c30179a0d7132237c4426044 | 1,047 | /*
* Copyright (C) 2017 the original author or authors.
*
* This file is part of jBB Application Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.jbb.lib.commons.vo;
import org.hibernate.validator.constraints.Length;
import java.io.Serializable;
import javax.validation.constraints.NotEmpty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.experimental.Tolerate;
@Getter
@AllArgsConstructor
@Builder
@EqualsAndHashCode(of = "value")
public class Email implements Serializable {
@javax.validation.constraints.Email
@NotEmpty
@Length(min = 3, max = 254)
String value;
@Tolerate
Email() {
// for JPA
}
public static Email of(String value) {
return Email.builder().value(value).build();
}
@Override
public String toString() {
return value;
}
}
| 20.94 | 67 | 0.69723 |
0b6f6490063eb7bfbf17f66cb4577bcde8ea8860 | 2,160 | /**
*
* Copyright 2017 Florian Erhard
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package gedi.util.functions;
import java.util.Comparator;
import java.util.Spliterator;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* The supplier ctor can be used if this spliterator is supposed to use a single mutable object for its iteration, i.e. the map function will
* always return the same object that is changed accordingly after every call to apply.
* @author erhard
*
* @param <S>
* @param <T>
*/
public class MappedSpliterator<S,T> implements Spliterator<T> {
private Spliterator<S> ssplit;
private Supplier<Function<S, T>> mapSupplier;
private Function<S, T> mapper;
public MappedSpliterator(Spliterator<S> ssplit, Supplier<Function<S,T>> mapSupplier) {
this.ssplit = ssplit;
this.mapSupplier = mapSupplier;
this.mapper = mapSupplier.get();
}
public MappedSpliterator(Spliterator<S> ssplit, Function<S,T> mapper) {
this.ssplit = ssplit;
this.mapper = mapper;
}
@Override
public boolean tryAdvance(Consumer<? super T> action) {
return ssplit.tryAdvance(o->action.accept(mapper.apply(o)));
}
@Override
public Spliterator<T> trySplit() {
Spliterator<S> s = ssplit.trySplit();
if (s==null) return null;
if (mapSupplier!=null)
return new MappedSpliterator<S,T>(s,mapSupplier);
return new MappedSpliterator<S,T>(s,mapper);
}
@Override
public long estimateSize() {
return ssplit.estimateSize();
}
@Override
public int characteristics() {
return ssplit.characteristics() & ~SORTED;
}
}
| 27.341772 | 141 | 0.721296 |
6898b2185444e9084bd5c4ab9cc4f23cc6d1e37f | 6,860 | package models;
import c195.*;
import java.time.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import javafx.beans.property.*;
public class Appointment extends DBEntity {
private ReadOnlyIntegerWrapper appointmentId = new ReadOnlyIntegerWrapper();
private SimpleIntegerProperty customerId = new SimpleIntegerProperty();
private SimpleIntegerProperty userId = new SimpleIntegerProperty();
private SimpleStringProperty title = new SimpleStringProperty();
private SimpleStringProperty description = new SimpleStringProperty();
private SimpleStringProperty location = new SimpleStringProperty();
private SimpleStringProperty contact = new SimpleStringProperty();
private SimpleStringProperty type = new SimpleStringProperty();
private SimpleStringProperty url = new SimpleStringProperty();
private SimpleObjectProperty<ZonedDateTime> start = new SimpleObjectProperty();
private SimpleObjectProperty<ZonedDateTime> end = new SimpleObjectProperty();
public int getAppointmentId() { return appointmentId.get(); }
protected void setAppointmentId(int value) { appointmentId.set(value); }
public ReadOnlyIntegerProperty appointmentIdProperty() { return appointmentId.getReadOnlyProperty(); }
public int getCustomerId() { return customerId.get(); }
public void setCustomerId(int value) { customerId.set(value); }
public SimpleIntegerProperty customerIdProperty() { return customerId; }
public int getUserId() { return userId.get(); }
public void setUserId(int value) { userId.set(value); }
public SimpleIntegerProperty userIdProperty() { return userId; }
public String getTitle() { return title.get(); }
public void setTitle(String value) { title.set(value); }
public SimpleStringProperty titleProperty() { return title; }
public String getDescription() { return description.get(); }
public void setDescription(String value) { description.set(value); }
public SimpleStringProperty descriptionProperty() { return description; }
public String getLocation() { return location.get(); }
public void setLocation(String value) { location.set(value); }
public SimpleStringProperty locationProperty() { return location; }
public String getContact() { return contact.get(); }
public void setContact(String value) { contact.set(value); }
public SimpleStringProperty contactProperty() { return contact; }
public String getType() { return type.get(); }
public void setType(String value) { type.set(value); }
public SimpleStringProperty typeProperty() { return type; }
public String getUrl() { return url.get(); }
public void setUrl(String value) { url.set(value); }
public SimpleStringProperty urlProperty() { return url; }
public ZonedDateTime getStart() { return start.get(); }
public void setStart(ZonedDateTime value) { start.set(value); }
public SimpleObjectProperty<ZonedDateTime> startProperty() { return start; }
public ZonedDateTime getEnd() { return end.get(); }
public void setEnd(ZonedDateTime value) { end.set(value); }
public SimpleObjectProperty<ZonedDateTime> endProperty() { return end; }
protected int getId() { return getAppointmentId(); }
protected void setId(int value) { setAppointmentId(value); }
private final String[] columnNames = new String[] { "customerId", "userId",
"title", "description", "location", "contact", "type", "url", "start", "end" };
protected String[] getColumnNames() { return columnNames; }
private final String tableName = "appointment";
protected String getTableName() { return tableName; }
public List<Appointment> checkForOverlap(String idColumnName, int id, ZonedDateTime newStart, ZonedDateTime newEnd) {
List<Appointment> list = new ArrayList<Appointment>();
try (Connection connection = Application.getInstance().getDBConnection()) {
String sql = "SELECT * FROM appointment WHERE " + idColumnName + " = ?"
+ " AND ((start >= ? AND start <= ?) OR (end >= ? AND end <= ?))"
+ " AND appointmentId <> ?";
PreparedStatement statement = connection.prepareStatement(sql);
int i = 1;
statement.setInt(i++, id);
Timestamp startUtc = Application.toTimestamp(newStart);
Timestamp endUtc = Application.toTimestamp(newEnd);
statement.setTimestamp(i++, startUtc);
statement.setTimestamp(i++, endUtc);
statement.setTimestamp(i++, startUtc);
statement.setTimestamp(i++, endUtc);
statement.setInt(i++, getAppointmentId());
ResultSet rs = statement.executeQuery();
while (rs.next()) {
Appointment appointment = new Appointment();
appointment.fromResultSet(rs);
list.add(appointment);
}
} catch (Exception ex) {
Application.alertForError(
"An error occurred retrieving data from the database", ex.getMessage());
}
return list;
}
public void commitToDb() throws Exception {
try (Connection connection = Application.getInstance().getDBConnection()) {
PreparedStatement statement = getPreparedStatement(connection);
int i = 1;
statement.setInt(i++, getCustomerId());
statement.setInt(i++, getUserId());
statement.setString(i++, getTitle());
statement.setString(i++, getDescription());
statement.setString(i++, getLocation());
statement.setString(i++, getContact());
statement.setString(i++, getType());
statement.setString(i++, getUrl());
statement.setTimestamp(i++, Application.toTimestamp(getStart()));
statement.setTimestamp(i++, Application.toTimestamp(getEnd()));
super.commitToDb(statement);
} catch (Exception ex) {
throw ex;
}
}
@Override
public void fromResultSet(ResultSet rs) throws SQLException {
int i = 0;
setCustomerId(rs.getInt(columnNames[i++]));
setUserId(rs.getInt(columnNames[i++]));
setTitle(rs.getString(columnNames[i++]));
setDescription(rs.getString(columnNames[i++]));
setLocation(rs.getString(columnNames[i++]));
setContact(rs.getString(columnNames[i++]));
setType(rs.getString(columnNames[i++]));
setUrl(rs.getString(columnNames[i++]));
setStart(Application.toZonedDateTime(rs.getTimestamp(columnNames[i++])));
setEnd(Application.toZonedDateTime(rs.getTimestamp(columnNames[i++])));
super.fromResultSet(rs);
}
} | 48.309859 | 121 | 0.664869 |
c80aaa0297f91f22c2a5fcf543aa9421d35f7c8b | 556 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package it.av.fac.messaging.client;
/**
*
* @author Diogo Regateiro <[email protected]>
*/
public enum RequestType {
GetPolicy,
AddPolicy,
GetMetadata,
LogInfo,
LogWarning,
LogError,
Decision,
AddMetadata,
AddSubject,
GetSubjectInfo,
AddUserContribution,
GetUserContributions,
GetLastUserContribution;
}
| 20.592593 | 79 | 0.690647 |
84766b70f3a1d9f98d3c015bd915ebfd6289e1b9 | 3,730 | package GUI;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.FileNotFoundException;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import App.DatConPanel;
import Files.ConvertDat;
import Files.DatConLog;
import Files.FileBeingUsed;
@SuppressWarnings("serial")
public class HPElevation extends JPanel
implements PropertyChangeListener, IDatConPanel {
DatConPanel datCon = null;
private JFormattedTextField homePointElevationField = null;
private double homePointElevation = 0.0;
public HPElevation(DatConPanel datCon) {
this.datCon = datCon;
Font font = new Font("Verdana", Font.BOLD, 14);
setLayout(new GridBagLayout());
setBorder(new LineBorder(Color.BLACK, 1, true));
setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weighty = 1.0;
gbc.gridwidth = 3;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
JLabel label = new JLabel("Home Point Elevation");
label.setFont(font);
add(label, gbc);
gbc.weightx = 0.5;
gbc.weighty = 0.5;
gbc.gridwidth = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridx = 2;
gbc.gridy = 3;
homePointElevationField = new JFormattedTextField(
Formatters.DoubleFormatter());
homePointElevationField.setColumns(15);
homePointElevationField.addPropertyChangeListener("value", this);
add(homePointElevationField, gbc);
gbc.gridx = 2;
gbc.gridy = 4;
gbc.gridwidth = 2;
add(new JLabel("Enter Home Point Elevation from Google Earth"), gbc);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
try {
JComponent source = (JComponent) (evt.getSource());
if (source == homePointElevationField) {
Double newHPE = (Double) evt.getNewValue();
if (newHPE != null) {
homePointElevation = newHPE;
datCon.kmlPanel.setHPelevation(homePointElevation);
}
}
} catch (Exception exception) {
DatConLog.Exception(exception);
}
}
public void reset() {
homePointElevationField.setText("");
homePointElevationField.setValue(null);
homePointElevation = 0.0;
}
// @Override
// public void setArgs(ConvertDat convertDat) {
// convertDat.homePointElevation = (float) homePointElevation;
// }
@Override
public void createPrintStreams(String outDirName)
throws FileBeingUsed, FileNotFoundException {
}
@Override
public void closePrintStreams() {
}
@Override
public void createFileNames(String flyFileNameRoot) {
}
public void setHPelevation(double elevation) {
homePointElevationField.setValue(elevation);
homePointElevation = elevation;
datCon.kmlPanel.setHPelevation(elevation);
}
@Override
public void setArgs(ConvertDat convertDat) {
throw new RuntimeException("HPElevation.setArgs called");
}
}
| 29.84 | 78 | 0.626273 |
7ed55004f386c7a332b939ad5bae988eb0b15c69 | 7,989 | /*
* Copyright 2013
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package org.openntf.domino.impl;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Vector;
import lotus.domino.NotesException;
import lotus.domino.XSLTResultTarget;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.utils.DominoUtils;
import org.xml.sax.InputSource;
// TODO: Auto-generated Javadoc
/**
* The Class EmbeddedObject.
*/
public class EmbeddedObject extends Base<org.openntf.domino.EmbeddedObject, lotus.domino.EmbeddedObject> implements
org.openntf.domino.EmbeddedObject {
/** The temp. */
private lotus.domino.EmbeddedObject temp;
/**
* Instantiates a new embedded object.
*
* @param delegate
* the delegate
* @param parent
* the parent
*/
public EmbeddedObject(final lotus.domino.EmbeddedObject delegate, final org.openntf.domino.Base<?> parent) {
super(delegate, parent);
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#activate(boolean)
*/
public int activate(final boolean paramBoolean) {
try {
return getDelegate().activate(paramBoolean);
} catch (NotesException e) {
DominoUtils.handleException(e);
return 0;
} finally {
if (delegate_ instanceof lotus.domino.local.EmbeddedObject) {
((lotus.domino.local.EmbeddedObject) delegate_).markInvalid();
}
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#doVerb(java.lang.String)
*/
public void doVerb(final String paramString) {
try {
getDelegate().doVerb(paramString);
} catch (NotesException e) {
DominoUtils.handleException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#extractFile(java.lang.String)
*/
public void extractFile(final String paramString) {
try {
getDelegate().extractFile(paramString);
} catch (NotesException e) {
DominoUtils.handleException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getClassName()
*/
public String getClassName() {
try {
return getDelegate().getClassName();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getFileSize()
*/
public int getFileSize() {
try {
return getDelegate().getFileSize();
} catch (NotesException e) {
DominoUtils.handleException(e);
return 0;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getName()
*/
public String getName() {
try {
return getDelegate().getName();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getObject()
*/
public int getObject() {
try {
return getDelegate().getObject();
} catch (NotesException e) {
DominoUtils.handleException(e);
return 0;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.impl.Base#getParent()
*/
@Override
public RichTextItem getParent() {
// The original spec returns either an RT item or null
org.openntf.domino.Base<?> parent = super.getParent();
if (parent instanceof org.openntf.domino.RichTextItem) {
return (RichTextItem) parent;
}
return null;
}
/* (non-Javadoc)
* @see org.openntf.domino.EmbeddedObject#getParentDocument()
*/
public Document getParentDocument() {
org.openntf.domino.Base<?> parent = super.getParent();
if (parent instanceof org.openntf.domino.RichTextItem) {
return ((RichTextItem) parent).getParent();
}
return (Document) parent;
}
public org.openntf.domino.Database getParentDatabase() {
return getParentDocument().getParentDatabase();
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getSource()
*/
public String getSource() {
try {
return getDelegate().getSource();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getType()
*/
public int getType() {
try {
return getDelegate().getType();
} catch (NotesException e) {
DominoUtils.handleException(e);
return 0;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getVerbs()
*/
@SuppressWarnings("unchecked")
public Vector<String> getVerbs() {
try {
return getDelegate().getVerbs();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#remove()
*/
public void remove() {
markDirty();
try {
getDelegate().remove();
} catch (NotesException e) {
DominoUtils.handleException(e);
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getReader()
*/
public Reader getReader() {
try {
return getDelegate().getReader();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
} finally {
if (delegate_ instanceof lotus.domino.local.EmbeddedObject) {
((lotus.domino.local.EmbeddedObject) delegate_).markInvalid();
}
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getInputSource()
*/
public InputSource getInputSource() {
try {
return getDelegate().getInputSource();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
} finally {
if (delegate_ instanceof lotus.domino.local.EmbeddedObject) {
((lotus.domino.local.EmbeddedObject) delegate_).markInvalid();
}
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#getInputStream()
*/
public InputStream getInputStream() {
try {
return getDelegate().getInputStream();
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
} finally {
if (delegate_ instanceof lotus.domino.local.EmbeddedObject) {
((lotus.domino.local.EmbeddedObject) delegate_).markInvalid();
}
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#parseXML(boolean)
*/
public org.w3c.dom.Document parseXML(final boolean paramBoolean) throws IOException {
try {
return getDelegate().parseXML(paramBoolean);
} catch (NotesException e) {
DominoUtils.handleException(e);
return null;
}
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.EmbeddedObject#transformXML(java.lang.Object, lotus.domino.XSLTResultTarget)
*/
public void transformXML(final Object paramObject, final XSLTResultTarget paramXSLTResultTarget) {
try {
getDelegate().transformXML(paramObject, paramXSLTResultTarget);
} catch (NotesException e) {
DominoUtils.handleException(e);
}
}
void markDirty() {
getParentDocument().markDirty();
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.types.DocumentDescendant#getAncestorDocument()
*/
@Override
public Document getAncestorDocument() {
return this.getParentDocument();
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.types.DatabaseDescendant#getAncestorDatabase()
*/
@Override
public Database getAncestorDatabase() {
return this.getAncestorDocument().getAncestorDatabase();
}
/*
* (non-Javadoc)
*
* @see org.openntf.domino.types.SessionDescendant#getAncestorSession()
*/
@Override
public Session getAncestorSession() {
return this.getAncestorDocument().getAncestorSession();
}
}
| 21.650407 | 115 | 0.685693 |
aa9de86412b50527890223f8c582e089ccc3f3a8 | 558 | package io.manbang.ebatis.core.provider;
import io.manbang.ebatis.core.domain.Aggregation;
/**
* 聚合条件提供者
*
* @author 章多亮
* @since 2020/1/2 19:51
*/
public interface AggProvider extends Provider {
/**
* 获取多聚合
*
* @return 多个聚合
*/
default Aggregation[] getAggregations() {
Aggregation agg = getAggregation();
return agg == null ? new Aggregation[0] : new Aggregation[]{agg};
}
/**
* 获取单聚合
*
* @return 单个聚合
*/
default Aggregation getAggregation() {
return null;
}
}
| 18 | 73 | 0.584229 |
f87ce061b2e545dee619fb178ca5de92260320ff | 666 | package com.xunlei.downloadprovider.homepage.relax.d;
import android.view.View;
import android.view.View.OnClickListener;
import com.xunlei.downloadprovider.model.protocol.b.d;
// compiled from: RelaxItemAdaper.java
final class e implements OnClickListener {
final /* synthetic */ a$b a;
final /* synthetic */ d b;
final /* synthetic */ a c;
e(a aVar, a$b com_xunlei_downloadprovider_homepage_relax_d_a_b, d dVar) {
this.c = aVar;
this.a = com_xunlei_downloadprovider_homepage_relax_d_a_b;
this.b = dVar;
}
public final void onClick(View view) {
a.a(this.c, this.a);
a.a(this.c).c(this.b);
}
}
| 27.75 | 77 | 0.678679 |
57f6526b0cd7c291d1a89649cea6e960df9c7488 | 1,777 | /**
* Copyright (c) 2020-2021 Mauro Trevisan
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.mtrevisan.boxon.annotations.checksummers;
import io.github.mtrevisan.boxon.annotations.Checksum;
/** The checksum algorithm to be applied to {@link Checksum Checksum}. */
public interface Checksummer{
/**
* Method used to calculate the checksum.
*
* @param data The byte array from which to calculate the checksum.
* @param start The starting byte on the given array.
* @param end The ending byte on the given array.
* @param startValue The starting value of the checksum.
* @return The checksum.
*/
short calculateChecksum(final byte[] data, final int start, final int end, final short startValue);
}
| 39.488889 | 100 | 0.751266 |
cd6c76a7762be9c3a236190402c765fcbaa53244 | 1,454 | import java.util.Scanner;
public class Histogram {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
double under200 = 0;
double from200to399 = 0;
double from400to599 = 0;
double from600to799 = 0;
double from800 = 0;
double p1 = 0;
double p2 = 0;
double p3 = 0;
double p4 = 0;
double p5 = 0;
for (int i = 1; i <= n; i++) {
double currentNum = Double.parseDouble(scan.nextLine());
if (currentNum < 200)
under200++;
else if (currentNum < 400)
from200to399++;
else if (currentNum < 600)
from400to599++;
else if (currentNum < 800)
from600to799++;
else
from800++;
}
p1 = under200 / n * 100;
p2 = from200to399 / n * 100;
p3 = from400to599 / n * 100;
p4 = from600to799 / n * 100;
p5 = from800 / n * 100;
System.out.printf("%.2f", p1);
System.out.println("%");
System.out.printf("%.2f", p2);
System.out.println("%");
System.out.printf("%.2f", p3);
System.out.println("%");
System.out.printf("%.2f", p4);
System.out.println("%");
System.out.printf("%.2f", p5);
System.out.println("%");
}
}
| 26.925926 | 68 | 0.482118 |
48075c33bfb6c6a93547e8f054c6e2412e1fb92a | 10,463 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.druid.timeline;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.druid.java.util.common.DateTimes;
import org.apache.druid.java.util.common.Intervals;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class SegmentIdTest
{
@Test
public void testBasic()
{
String datasource = "datasource";
SegmentId desc = SegmentId.of(datasource, Intervals.of("2015-01-02/2015-01-03"), "ver_0", 1);
Assert.assertEquals("datasource_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
desc = desc.withInterval(Intervals.of("2014-10-20T00:00:00Z/P1D"));
Assert.assertEquals("datasource_2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z_ver_0_1", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
desc = SegmentId.of(datasource, Intervals.of("2015-01-02/2015-01-03"), "ver", 0);
Assert.assertEquals("datasource_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
desc = desc.withInterval(Intervals.of("2014-10-20T00:00:00Z/P1D"));
Assert.assertEquals("datasource_2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z_ver", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
}
@Test
public void testDataSourceWithUnderscore()
{
String datasource = "datasource_1";
SegmentId desc = SegmentId.of(datasource, Intervals.of("2015-01-02/2015-01-03"), "ver_0", 1);
Assert.assertEquals("datasource_1_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
desc = desc.withInterval(Intervals.of("2014-10-20T00:00:00Z/P1D"));
Assert.assertEquals("datasource_1_2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z_ver_0_1", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
desc = SegmentId.of(datasource, Intervals.of("2015-01-02/2015-01-03"), "ver", 0);
Assert.assertEquals("datasource_1_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
desc = desc.withInterval(Intervals.of("2014-10-20T00:00:00Z/P1D"));
Assert.assertEquals("datasource_1_2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z_ver", desc.toString());
Assert.assertEquals(desc, SegmentId.tryParse(datasource, desc.toString()));
}
/**
* Test the ambiguity of a datasource name ending with '_yyyy-mm-dd..' string that could be considered either as the
* end of the datasource name or the interval start in the segment id's string representation.
*/
@Test
public void testDataSourceWithUnderscoreAndTimeStringInDataSourceName()
{
String dataSource = "datasource_2015-01-01T00:00:00.000Z";
SegmentId desc = SegmentId.of(dataSource, Intervals.of("2015-01-02/2015-01-03"), "ver_0", 1);
Assert.assertEquals(
"datasource_2015-01-01T00:00:00.000Z_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1",
desc.toString()
);
Assert.assertEquals(desc, SegmentId.tryParse(dataSource, desc.toString()));
desc = desc.withInterval(Intervals.of("2014-10-20T00:00:00Z/P1D"));
Assert.assertEquals(
"datasource_2015-01-01T00:00:00.000Z_2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z_ver_0_1",
desc.toString()
);
Assert.assertEquals(desc, SegmentId.tryParse(dataSource, desc.toString()));
desc = SegmentId.of(dataSource, Intervals.of("2015-01-02/2015-01-03"), "ver", 0);
Assert.assertEquals(
"datasource_2015-01-01T00:00:00.000Z_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver",
desc.toString()
);
Assert.assertEquals(desc, SegmentId.tryParse(dataSource, desc.toString()));
desc = desc.withInterval(Intervals.of("2014-10-20T00:00:00Z/P1D"));
Assert.assertEquals(
"datasource_2015-01-01T00:00:00.000Z_2014-10-20T00:00:00.000Z_2014-10-21T00:00:00.000Z_ver",
desc.toString()
);
Assert.assertEquals(desc, SegmentId.tryParse(dataSource, desc.toString()));
}
/**
* The interval start is later than the end
*/
@Test
public void testInvalidFormat0()
{
Assert.assertNull(
SegmentId.tryParse("datasource", "datasource_2015-01-02T00:00:00.000Z_2014-10-20T00:00:00.000Z_version")
);
}
/**
* No interval dates
*/
@Test
public void testInvalidFormat1()
{
Assert.assertNull(SegmentId.tryParse("datasource", "datasource_invalid_interval_version"));
}
/**
* Not enough interval dates
*/
@Test
public void testInvalidFormat2()
{
Assert.assertNull(SegmentId.tryParse("datasource", "datasource_2015-01-02T00:00:00.000Z_version"));
}
/**
* Tests that {@link SegmentId#tryExtractMostProbableDataSource} successfully extracts data sources from some
* reasonable segment ids.
*/
@Test
public void testTryParseHeuristically()
{
List<String> segmentIds = Arrays.asList(
"datasource_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1",
"datasource_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver",
"datasource_1_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1",
"datasource_1_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver",
"datasource_2015-01-01T00:00:00.000Z_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1",
"datasource_2015-01-01T00:00:00.000Z_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver"
);
for (String segmentId : segmentIds) {
String dataSource = SegmentId.tryExtractMostProbableDataSource(segmentId);
Assert.assertTrue("datasource".equals(dataSource) || "datasource_1".equals(dataSource));
Assert.assertTrue(!SegmentId.iteratePossibleParsingsWithDataSource(dataSource, segmentId).isEmpty());
}
}
@Test
public void testTryParseVersionAmbiguity()
{
SegmentId segmentId =
SegmentId.tryParse("datasource", "datasource_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0");
Assert.assertNotNull(segmentId);
Assert.assertEquals("ver_0", segmentId.getVersion());
Assert.assertEquals(0, segmentId.getPartitionNum());
}
@Test
public void testIterateAllPossibleParsings()
{
String segmentId = "datasource_2015-01-01T00:00:00.000Z_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_ver_0_1";
List<SegmentId> possibleParsings = ImmutableList.copyOf(SegmentId.iterateAllPossibleParsings(segmentId));
DateTime dt1 = DateTimes.of("2015-01-01T00:00:00.000Z");
DateTime dt2 = DateTimes.of("2015-01-02T00:00:00.000Z");
DateTime dt3 = DateTimes.of("2015-01-03T00:00:00.000Z");
Set<SegmentId> expected = ImmutableSet.of(
SegmentId.of("datasource", new Interval(dt1, dt2), "2015-01-03T00:00:00.000Z_ver_0", 1),
SegmentId.of("datasource", new Interval(dt1, dt2), "2015-01-03T00:00:00.000Z_ver_0_1", 0),
SegmentId.of("datasource_2015-01-01T00:00:00.000Z", new Interval(dt2, dt3), "ver_0", 1),
SegmentId.of("datasource_2015-01-01T00:00:00.000Z", new Interval(dt2, dt3), "ver_0_1", 0)
);
Assert.assertEquals(4, possibleParsings.size());
Assert.assertEquals(expected, ImmutableSet.copyOf(possibleParsings));
}
@Test
public void testIterateAllPossibleParsingsWithEmptyVersion()
{
String segmentId = "datasource_2015-01-01T00:00:00.000Z_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z__1";
List<SegmentId> possibleParsings = ImmutableList.copyOf(SegmentId.iterateAllPossibleParsings(segmentId));
DateTime dt1 = DateTimes.of("2015-01-01T00:00:00.000Z");
DateTime dt2 = DateTimes.of("2015-01-02T00:00:00.000Z");
DateTime dt3 = DateTimes.of("2015-01-03T00:00:00.000Z");
Set<SegmentId> expected = ImmutableSet.of(
SegmentId.of("datasource", new Interval(dt1, dt2), "2015-01-03T00:00:00.000Z_", 1),
SegmentId.of("datasource", new Interval(dt1, dt2), "2015-01-03T00:00:00.000Z__1", 0),
SegmentId.of("datasource_2015-01-01T00:00:00.000Z", new Interval(dt2, dt3), "", 1),
SegmentId.of("datasource_2015-01-01T00:00:00.000Z", new Interval(dt2, dt3), "_1", 0)
);
Assert.assertEquals(4, possibleParsings.size());
Assert.assertEquals(expected, ImmutableSet.copyOf(possibleParsings));
}
/**
* Three DateTime strings included, but not ascending, that makes a pair of parsings impossible, compared to {@link
* #testIterateAllPossibleParsings}.
*/
@Test
public void testIterateAllPossibleParsings2()
{
String segmentId = "datasource_2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z_2015-01-02T00:00:00.000Z_ver_1";
List<SegmentId> possibleParsings = ImmutableList.copyOf(SegmentId.iterateAllPossibleParsings(segmentId));
DateTime dt1 = DateTimes.of("2015-01-02T00:00:00.000Z");
DateTime dt2 = DateTimes.of("2015-01-03T00:00:00.000Z");
Set<SegmentId> expected = ImmutableSet.of(
SegmentId.of("datasource", new Interval(dt1, dt2), "2015-01-02T00:00:00.000Z_ver", 1),
SegmentId.of("datasource", new Interval(dt1, dt2), "2015-01-02T00:00:00.000Z_ver_1", 0)
);
Assert.assertEquals(2, possibleParsings.size());
Assert.assertEquals(expected, ImmutableSet.copyOf(possibleParsings));
}
}
| 45.099138 | 119 | 0.722642 |
5e1b65a27c3a0e82f98c09d85ec35f1390f3c766 | 237 | package test.dependsongroup;
import org.testng.annotations.Test;
@Test(
groups = {"second"},
dependsOnGroups = {"zero"})
public class SecondSampleTest {
@Test
public void secondA() {}
@Test
public void secondB() {}
}
| 14.8125 | 35 | 0.670886 |
63c3e90d53bc6707edcefd7df73ec661667a1ff6 | 280 | package com.github.knightliao.vpaas.api.base;
import lombok.Data;
/**
* @author knightliao
* @email [email protected]
* @date 2021/8/22 15:11
*/
@Data
public class VpaasRpcResponseBase {
private String traceId;
private String info;
private int statusCode;
}
| 16.470588 | 45 | 0.714286 |
57917f0087306ecf6d07cb54f1824f6f3ec248b7 | 1,467 | package umm3601.todo;
import org.junit.Test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.*;
/**
* Tests umm3601.todo.ToDoDatabase filterToDosByLimit
* and listToDos with _limit_ query parameters
*/
public class FilterToDosByLimitFromDB {
@Test
public void filterToDosByLimit() throws IOException {
ToDoDatabase db = new ToDoDatabase("src/main/data/todos.json");
ToDo[] allToDos = db.listToDos(new HashMap<>());
ToDo[] limit7ToDos = db.filterToDosByLimit(allToDos, 7);
assertEquals("Incorrect number of todos", 7, limit7ToDos.length);
ToDo[] limit0ToDos = db.filterToDosByLimit(allToDos, 0);
assertEquals("Incorrect number of todos", 0, limit0ToDos.length);
ToDo[] limit1000ToDos = db.filterToDosByLimit(allToDos, 1000);
assertEquals("Incorrect number of todos", allToDos.length, limit1000ToDos.length);
}
@Test
public void listToDosWithLimitFilter() throws IOException {
ToDoDatabase db = new ToDoDatabase("src/main/data/todos.json");
Map<String, String[]> queryParams = new HashMap<>();
queryParams.put("limit", new String[]{"7"});
ToDo[] limit7ToDos = db.listToDos(queryParams);
assertEquals("Incorrect number of todos", 7, limit7ToDos.length);
queryParams.put("limit", new String[]{"15"});
ToDo[] limit15ToDos = db.listToDos(queryParams);
assertEquals("Incorrect number of todos", 15, limit15ToDos.length);
}
}
| 31.891304 | 86 | 0.724608 |
2b6def1c5736fd2204df1bb9a531a9422ad2b3b8 | 1,508 | package org.myddd.security.account.application.assembler;
import org.myddd.security.account.domain.LoginEntity;
import org.myddd.security.api.LoginDTO;
import javax.inject.Named;
import java.util.Objects;
@Named
public class LoginAssembler {
public LoginEntity toEntity(LoginDTO dto){
if(Objects.isNull(dto))return null;
LoginEntity entity = new LoginEntity();
entity.setUsername(dto.getUsername());
entity.setPassword(dto.getPassword());
entity.setDisplayName(dto.getDisplayName());
entity.setDisabled(dto.isDisabled());
entity.setCreateDate(dto.getCreated());
entity.setUpdateDate(dto.getUpdated());
entity.setSuperUser(dto.isSuperUser());
entity.setId(dto.getId());
return entity;
}
public LoginDTO toDTOWithoutPassword(LoginEntity entity){
LoginDTO dto = toDTO(entity);
dto.setPassword("");
dto.setNewPassword("");
return dto;
}
public LoginDTO toDTO(LoginEntity entity){
if(Objects.isNull(entity))return null;
LoginDTO dto = new LoginDTO();
dto.setUpdated(entity.getUpdateDate());
dto.setCreated(entity.getCreateDate());
dto.setUsername(entity.getUsername());
dto.setDisplayName(entity.getDisplayName());
dto.setPassword(entity.getPassword());
dto.setDisabled(entity.isDisabled());
dto.setSuperUser(entity.isSuperUser());
dto.setId(entity.getId());
return dto;
}
}
| 32.085106 | 61 | 0.668435 |
7068088437d6ba13df09028bd40d4fce0e46e26d | 987 | package com.jvmausa.algafood.auth.core;
import javax.validation.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Validated
@Component
@ConfigurationProperties("algafood.jwt.keystore")
public class JwtKeyStoreProperties {
@NotBlank
private String path;
@NotBlank
private String password;
@NotBlank
private String keypairAlias;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getKeypairAlias() {
return keypairAlias;
}
public void setKeypairAlias(String keypairAlias) {
this.keypairAlias = keypairAlias;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
| 21 | 75 | 0.701114 |
4274d27400f083c60b21b99d5e31dd3bfec2f7f5 | 2,374 | // Code generated by Wire protocol buffer compiler, do not edit.
// Source file: com/ppdai/framework/raptor/proto/Result.proto
package com.ppdai.framework.raptor.proto;
import com.ppdai.framework.raptor.annotation.RaptorField;
import com.ppdai.framework.raptor.annotation.RaptorMessage;
import java.util.List;
import java.util.Objects;
@RaptorMessage(
protoFile = "Result"
)
public final class Result {
private static final long serialVersionUID = 0L;
@RaptorField(
fieldType = "string",
order = 1,
name = "url"
)
private String url;
@RaptorField(
fieldType = "string",
order = 2,
name = "title"
)
private String title;
@RaptorField(
fieldType = "string",
order = 3,
name = "snippets",
repeated = true
)
private List<String> snippets;
public Result() {
}
public Result(String url, String title, List<String> snippets) {
this.url = url;
this.title = title;
this.snippets = snippets;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url=url;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title=title;
}
public List<String> getSnippets() {
return this.snippets;
}
public void setSnippets(List<String> snippets) {
this.snippets=snippets;
}
@Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof Result)) return false;
Result o = (Result) other;
return true
&& Objects.equals(url, o.url)
&& Objects.equals(title, o.title)
&& Objects.equals(snippets, o.snippets);
}
@Override
public int hashCode() {
int result = 0;
result = result * 37 + (url != null ? url.hashCode() : 0);
result = result * 37 + (title != null ? title.hashCode() : 0);
result = result * 37 + (snippets != null ? snippets.hashCode() : 0);
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (url != null) builder.append(", url=").append(url);
if (title != null) builder.append(", title=").append(title);
if (snippets != null && !snippets.isEmpty()) builder.append(", snippets=").append(snippets);
return builder.replace(0, 2, "Result{").append('}').toString();
}
}
| 23.50495 | 97 | 0.637321 |
b94692a7277ae28a8c3324bd8ef0a1a1edb01af3 | 4,690 | package org.ovirt.engine.core.common.utils.pm;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.ovirt.engine.core.common.businessentities.pm.FenceProxySourceType.CLUSTER;
import static org.ovirt.engine.core.common.businessentities.pm.FenceProxySourceType.DC;
import static org.ovirt.engine.core.common.businessentities.pm.FenceProxySourceType.OTHER_DC;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
import org.ovirt.engine.core.common.businessentities.pm.FenceProxySourceType;
public class FenceProxySourceTypeHelperTest {
/**
* Tests if empty list is returned when parsing {@code null} string
*/
@Test
public void parseNullString() {
List<FenceProxySourceType> result = FenceProxySourceTypeHelper.parseFromString(null);
assertNotNull(result);
assertEquals(0, result.size());
}
/**
* Tests if empty list is returned when parsing empty string
*/
@Test
public void parseEmptyString() {
List<FenceProxySourceType> result = FenceProxySourceTypeHelper.parseFromString(null);
assertNotNull(result);
assertEquals(0, result.size());
}
/**
* Tests parsing valid strings
*/
@Test
public void parseValidString() {
String[] validValues = {
CLUSTER.getValue(),
DC.getValue(),
OTHER_DC.getValue(),
CLUSTER.getValue() + "," + DC.getValue() + "," + OTHER_DC.getValue()
};
for (String invalidValue : validValues) {
FenceProxySourceTypeHelper.parseFromString(invalidValue);
}
}
/**
* Tests if {@code IllegalArgumentException} is thrown when parsing invalid string
*/
@Test
public void parseInvalidString() {
String[] invalidValues = {
"clust", // invalid fence proxy source type
"clust,dc", // invalid fence proxy source type
"cluster,d", // invalid fence proxy source type
"cluster, dc" // space should not be used
};
for (String invalidValue : invalidValues) {
try {
FenceProxySourceTypeHelper.parseFromString(invalidValue);
fail(String.format(
"Value '%s' is not valid argument of FenceProxySourceTypeHelper.parseFromString.",
invalidValue));
} catch (IllegalArgumentException ignore) {
}
}
}
/**
* Tests if null is returned when saving {@code null} list
*/
@Test
public void saveNullList() {
String result = FenceProxySourceTypeHelper.saveAsString(null);
assertNull(result);
}
/**
* Tests if null string is returned when saving empty list
*/
@Test
public void saveEmptyList() {
String result = FenceProxySourceTypeHelper.saveAsString(Collections.emptyList());
assertNull(result);
}
/**
* Tests saving lists with valid values
*/
@Test
public void saveListWithValidValues() {
List<List<FenceProxySourceType>> validLists = new ArrayList<>();
validLists.add(Collections.singletonList(CLUSTER));
validLists.add(Collections.singletonList(DC));
validLists.add(Collections.singletonList(OTHER_DC));
validLists.add(Arrays.asList(CLUSTER, DC, OTHER_DC));
for (List<FenceProxySourceType> validList : validLists) {
FenceProxySourceTypeHelper.saveAsString(validList);
}
}
/**
* Tests if {@code IllegalArgumentException} is thrown when saving a list containing invalid values
*/
@Test
public void saveListWithInvalidValues() {
List<List<FenceProxySourceType>> invalidLists = new ArrayList<>();
List<FenceProxySourceType> listWithNullValue = new ArrayList<>();
listWithNullValue.add(null);
invalidLists.add(listWithNullValue);
invalidLists.add(Arrays.asList(CLUSTER, null));
for (List<FenceProxySourceType> invalidList : invalidLists) {
try {
FenceProxySourceTypeHelper.saveAsString(invalidList);
fail(String.format(
"Value '%s' is not valid argument of FenceProxySourceTypeHelper.parseFromString.",
Arrays.toString(invalidList.toArray())));
} catch (IllegalArgumentException ignore) {
}
}
}
}
| 32.797203 | 106 | 0.635608 |
74b86d931b2e4092a700226aa73e78da4be9f118 | 1,459 | package com.zy.demo.base;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.zy.multistatepage.MultiStateContainer;
import com.zy.multistatepage.MultiStatePage;
import com.zy.multistatepage.OnNotifyListener;
import com.zy.demo.state.LottieOtherState;
/**
* @ProjectName: MultiStatePage
* @Author: 赵岩
* @Email: [email protected]
* @Description: TODO
* @CreateDate: 2020/9/19 12:39
*/
class Test extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = new View(this);
MultiStatePage.bindMultiState(this);
MultiStatePage.bindMultiState(view);
MultiStateContainer multiStateContainer = MultiStatePage.bindMultiState(view);
multiStateContainer.show(LottieOtherState.class);
multiStateContainer.show(LottieOtherState.class, true, new OnNotifyListener<LottieOtherState>() {
@Override
public void onNotify(LottieOtherState multiState) {
System.out.println("");
}
});
LottieOtherState lottieOtherState = new LottieOtherState();
lottieOtherState.setRetry(() -> {
Toast.makeText(this, "", Toast.LENGTH_SHORT);
return null;
});
multiStateContainer.show(lottieOtherState);
}
}
| 27.528302 | 105 | 0.695682 |
626c5a3cc59dbcb76108a40830dca3fa867f6539 | 1,610 | //路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不
//一定经过根节点。
//
// 路径和 是路径中各节点值的总和。
//
// 给你一个二叉树的根节点 root ,返回其 最大路径和 。
//
//
//
// 示例 1:
//
//
//输入:root = [1,2,3]
//输出:6
//解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
//
// 示例 2:
//
//
//输入:root = [-10,9,20,null,null,15,7]
//输出:42
//解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
//
//
//
//
// 提示:
//
//
// 树中节点数目范围是 [1, 3 * 10⁴]
// -1000 <= Node.val <= 1000
//
// Related Topics 树 深度优先搜索 动态规划 二叉树 👍 1303 👎 0
package leetcode.editor.cn;
// 124.二叉树中的最大路径和
public class Code124_BinaryTreeMaximumPathSum {
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode left; TreeNode
* right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left,
* TreeNode right) { this.val = val; this.left = left; this.right = right; } }
*/
class Solution {
int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
dfs(root);
return maxSum;
}
// 计算子树对路径和的贡献值
private int dfs(TreeNode root) {
// base case
if (root == null) {
return 0;
}
// 计算左右子树的贡献值,如果贡献值小于0,就不要
int leftValue = Math.max(dfs(root.left), 0);
int rightValue = Math.max(dfs(root.right), 0);
// 更新maxSum
maxSum = Math.max(maxSum, leftValue + rightValue + root.val);
// 当前节点root的贡献值
return Math.max(leftValue, rightValue) + root.val;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | 21.756757 | 96 | 0.603727 |
d0fcf8dbf5530cfcdc55e2e9223a681d5b6955a5 | 103 | package com.cts.training.initialpublicofferingservice;
public interface InitialPublicOfferingDAO {
}
| 17.166667 | 54 | 0.854369 |
3c4fec6434029aa375e86419dea4afea00d97cf2 | 1,900 | package mage.cards.p;
import mage.MageInt;
import mage.abilities.Ability;
import mage.abilities.common.DiesSourceTriggeredAbility;
import mage.abilities.condition.Condition;
import mage.abilities.decorator.ConditionalInterveningIfTriggeredAbility;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.SubType;
import mage.counters.CounterType;
import mage.game.Game;
import mage.game.permanent.Permanent;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class PromisingDuskmage extends CardImpl {
public PromisingDuskmage(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{2}{B}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.WARLOCK);
this.power = new MageInt(2);
this.toughness = new MageInt(3);
// When Promising Duskmage dies, if it had a +1/+1 counter on it, draw a card.
this.addAbility(new ConditionalInterveningIfTriggeredAbility(
new DiesSourceTriggeredAbility(new DrawCardSourceControllerEffect(1)),
PromisingDuskmageCondition.instance, "When {this} dies, " +
"if it had a +1/+1 counter on it, draw a card."
));
}
private PromisingDuskmage(final PromisingDuskmage card) {
super(card);
}
@Override
public PromisingDuskmage copy() {
return new PromisingDuskmage(this);
}
}
enum PromisingDuskmageCondition implements Condition {
instance;
@Override
public boolean apply(Game game, Ability source) {
Permanent permanent = (Permanent) source.getEffects().get(0).getValue("permanentLeftBattlefield");
return permanent != null && permanent.getCounters(game).containsKey(CounterType.P1P1);
}
}
| 32.20339 | 106 | 0.718421 |
4154e8378e034c66ff789dd5ff4f3cdbe07b8cfe | 482 | package uk.gov.hmcts.reform.sscs.servicebus.messaging;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class MessagingConfigTest {
private final MessagingConfig messagingConfig = new MessagingConfig();
@Test
public void jmsUrlStringFormatsTheAmqpString() {
final String url = messagingConfig.jmsUrlString("myHost");
assertTrue("Jms url string should begin with amqps://<host> ", url.startsWith("amqps://myHost?"));
}
}
| 26.777778 | 106 | 0.732365 |
90cb1f775165ece43552688af5854621cef73208 | 3,393 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.atlas.pc;
import org.testng.annotations.Test;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class WorkItemConsumerWithResultsTest {
private class IntegerConsumerSpy extends WorkItemConsumer<Integer> {
int payload = -1;
public IntegerConsumerSpy(BlockingQueue<Integer> queue) {
super(queue);
}
@Override
protected void doCommit() {
addResult(payload);
}
@Override
protected void processItem(Integer item) {
payload = item.intValue();
}
@Override
protected void commitDirty() {
super.commitDirty();
}
}
private class IntegerConsumerThrowingError extends WorkItemConsumer<Integer> {
int payload = -1;
public IntegerConsumerThrowingError(BlockingQueue<Integer> queue) {
super(queue);
}
@Override
protected void doCommit() {
throw new NullPointerException();
}
@Override
protected void processItem(Integer item) {
payload = item.intValue();
}
@Override
protected void commitDirty() {
super.commitDirty();
}
}
@Test
public void runningConsumerWillPopulateResults() {
CountDownLatch countDownLatch = new CountDownLatch(1);
BlockingQueue<Integer> bc = new LinkedBlockingQueue<>(5);
LinkedBlockingQueue<Object> results = new LinkedBlockingQueue<>();
IntegerConsumerSpy ic = new IntegerConsumerSpy(bc);
ic.setResults(results);
ic.setCountDownLatch(countDownLatch);
ic.run();
assertTrue(bc.isEmpty());
assertEquals(results.size(), bc.size());
assertEquals(countDownLatch.getCount(), 0);
}
@Test
public void errorInConsumerWillDecrementCountdownLatch() {
CountDownLatch countDownLatch = new CountDownLatch(1);
BlockingQueue<Integer> bc = new LinkedBlockingQueue<>(5);
LinkedBlockingQueue<Object> results = new LinkedBlockingQueue<>();
IntegerConsumerThrowingError ic = new IntegerConsumerThrowingError(bc);
ic.setCountDownLatch(countDownLatch);
ic.setResults(results);
ic.run();
assertTrue(bc.isEmpty());
assertTrue(results.isEmpty());
assertEquals(countDownLatch.getCount(), 0);
}
}
| 31.12844 | 82 | 0.669909 |
af6e1c99f5d0dfe225ac8cfe5c409c97e989703f | 2,111 | package ru.fizteh.fivt.students.pershik.FileMap;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
* Created by pershik on 10/4/14.
*/
public class Runner {
protected boolean exited;
protected boolean batchMode;
protected boolean checkArguments(int min, int max, int real) {
return min <= real && real <= max;
}
protected void errorCntArguments(String command)
throws InvalidCommandException {
throw new InvalidCommandException(
command + ": invalid number of arguments");
}
protected void errorUnknownCommand(String command)
throws InvalidCommandException {
throw new InvalidCommandException(
command + ": unknown command");
}
protected String[] parseCommand(String command) {
return command.trim().split("\\s+");
}
protected void execute(String command) {
}
public void runCommands(String[] commands) {
for (String command : commands) {
execute(command);
if (exited) {
break;
}
}
}
private void execLine(String line) {
String[] commands = line.trim().split(";");
runCommands(commands);
}
public void runInteractive() {
try (Scanner sc = new Scanner(System.in)) {
while (true) {
System.out.print("$ ");
if (!sc.hasNextLine()) {
break;
}
String allCommands = sc.nextLine();
execLine(allCommands);
if (exited) {
break;
}
}
} catch (NoSuchElementException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
public void runBatch(String[] args) {
batchMode = true;
StringBuilder allCommands = new StringBuilder();
for (String arg : args) {
allCommands.append(arg);
allCommands.append(" ");
}
execLine(allCommands.toString());
}
}
| 26.3875 | 66 | 0.54666 |
1c050fbeb9c6f5952cbe7e07b42b9665728e0080 | 276 | package org.dominokit.cli.generator;
import java.util.Map;
import java.util.function.Supplier;
public interface ProjectFile {
String getName();
void write(String path, Map<String, Object> context);
default Supplier<Boolean> condition() { return () -> true;}
}
| 21.230769 | 63 | 0.721014 |
347ae25e72a698987b4221004b0a7171af6a4632 | 1,207 | package cc.vihackerframework.uaa.controller;
import cc.vihackerframework.core.api.ViHackerResult;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
/**
* <p>
*
* @author Ranger
* @email [email protected]
* @since 2021/6/8
*/
@Controller
@RequiredArgsConstructor
public class SecurityController {
private final ConsumerTokenServices consumerTokenServices;
@GetMapping("user/info")
public@ResponseBody Principal currentUser(Principal principal) {
return principal;
}
@GetMapping("login")
public String login() {
return "login";
}
@DeleteMapping("signout")
public @ResponseBody
ViHackerResult signout(HttpServletRequest request, @RequestHeader("Authorization") String token) {
token = StringUtils.replace(token, "bearer ", "");
consumerTokenServices.revokeToken(token);
return ViHackerResult.success("signout");
}
}
| 26.822222 | 102 | 0.747307 |
18f6b06c20a871240fcf3ef0063635b8f6e3eb3e | 6,082 | /*******************************************************************************
* Copyright 2012 Internet2
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
/*
Copyright 2004-2007 University Corporation for Advanced Internet Development, Inc.
Copyright 2004-2007 The University Of Bristol
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package edu.internet2.middleware.grouper.ui.actions;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.internet2.middleware.grouper.GrouperHelper;
import edu.internet2.middleware.grouper.GrouperSession;
import edu.internet2.middleware.grouper.ui.GroupOrStem;
/**
* Top level Strut's action which does any setup for stem creation.
* <p/>
<table width="75%" border="1">
<tr bgcolor="#CCCCCC">
<td width="51%"><strong><font face="Arial, Helvetica, sans-serif">Request
Parameter</font></strong></td>
<td width="12%"><strong><font face="Arial, Helvetica, sans-serif">Direction</font></strong></td>
<td width="37%"><strong><font face="Arial, Helvetica, sans-serif">Description</font></strong></td>
</tr>
<tr>
<td><p> </p></td>
<td> </td>
<td> </td>
</tr>
<tr bgcolor="#CCCCCC">
<td><strong><font face="Arial, Helvetica, sans-serif">Request Attribute</font></strong></td>
<td><strong><font face="Arial, Helvetica, sans-serif">Direction</font></strong></td>
<td><strong><font face="Arial, Helvetica, sans-serif">Description</font></strong></td>
</tr>
<tr bgcolor="#FFFFFF">
<td><font face="Arial, Helvetica, sans-serif">isNewStem=true</font></td>
<td><font face="Arial, Helvetica, sans-serif">OUT</font></td>
<td><font face="Arial, Helvetica, sans-serif">Indicates a new stem</font></td>
</tr>
<tr bgcolor="#FFFFFF">
<td><font face="Arial, Helvetica, sans-serif">browseParent</font></td>
<td><font face="Arial, Helvetica, sans-serif">OUT</font></td>
<td><font face="Arial, Helvetica, sans-serif">Map for stem of current stem</font></td>
</tr>
<tr bgcolor="#CCCCCC">
<td><strong><font face="Arial, Helvetica, sans-serif">Session Attribute</font></strong></td>
<td><strong><font face="Arial, Helvetica, sans-serif">Direction</font></strong></td>
<td><strong><font face="Arial, Helvetica, sans-serif">Description</font></strong></td>
</tr>
<tr bgcolor="#FFFFFF">
<td><font face="Arial, Helvetica, sans-serif">title=stems.create</font></td>
<td><font face="Arial, Helvetica, sans-serif">OUT</font></td>
<td><font face="Arial, Helvetica, sans-serif">Key resolved in nav ResourceBundle</font></td>
</tr>
<tr bgcolor="#FFFFFF">
<td><font face="Arial, Helvetica, sans-serif">subtitle=stems.action.create</font></td>
<td><font face="Arial, Helvetica, sans-serif">OUT</font></td>
<td><font face="Arial, Helvetica, sans-serif">Key resolved in nav ResourceBundle</font></td>
</tr>
<tr bgcolor="#CCCCCC">
<td><strong><font face="Arial, Helvetica, sans-serif">Strut's Action Parameter</font></strong></td>
<td><strong><font face="Arial, Helvetica, sans-serif">Direction</font></strong></td>
<td><strong><font face="Arial, Helvetica, sans-serif">Description</font></strong></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
*
* @author Gary Brown.
* @version $Id: PopulateCreateStemAction.java,v 1.7 2008-04-13 08:52:12 isgwb Exp $
*/
public class PopulateCreateStemAction extends GrouperCapableAction {
protected static final Log LOG = LogFactory.getLog(PopulateCreateStemAction.class);
//------------------------------------------------------------ Local
// Forwards
static final private String FORWARD_CreateStem = "CreateStem";
//------------------------------------------------------------ Action
// Methods
public ActionForward grouperExecute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response,
HttpSession session,GrouperSession grouperSession)
throws Exception {
//session.setAttribute("title", "stems.create");
session.setAttribute("subtitle", "stems.action.create");
session.setAttribute("isNewStem", Boolean.TRUE);
GroupOrStem groupOrStem = getCurrentGroupOrStem(grouperSession,session);
Map parent = null;
if(!groupOrStem.isStem()) {
parent = new HashMap();
}else {
parent = GrouperHelper.stem2Map(
grouperSession, groupOrStem.getStem());
}
request.setAttribute("browseParent", parent);
return mapping.findForward(FORWARD_CreateStem);
}
}
| 42.830986 | 104 | 0.663104 |
420d36a82bdc2e269fe8540890195fefa48682d7 | 3,669 | package com.alinv0.other;
/**
* Given a binary square matrix of nxn
* Find longest sequence of 1s on row, column or diagonal
*/
public class LongestOneStreak {
public static int getMatrixMaxSum(int[][] matrix) {
int maxSum = 0;
for (int i = 0; i < matrix.length; i++) {
maxSum = Math.max(getDiagonalRightUpper(matrix, i), maxSum);
maxSum = Math.max(getDiagonalLeftLower(matrix, i), maxSum);
maxSum = Math.max(getDiagonalLeftUpper(matrix, i), maxSum);
maxSum = Math.max(getDiagonalRightLower(matrix, i), maxSum);
maxSum = Math.max(getColumnSum(matrix, i), maxSum);
maxSum = Math.max(getRowSum(matrix, i), maxSum);
}
System.out.println("MAX SUM: " + maxSum);
return maxSum;
}
private static int getColumnSum(int[][] matrix, int i) {
int c = 0;
StringBuilder sb = new StringBuilder();
while (c < 5) {
sb.append(matrix[i][c]);
c++;
}
return getMaxSum(sb);
}
private static int getRowSum(int[][] matrix, int i) {
int r = 0;
StringBuilder sb = new StringBuilder();
while (r < 5) {
sb.append(matrix[r][i]);
r++;
}
return getMaxSum(sb);
}
/**
* [0][0]
* [0][1] [1][0]
* [0][2] [1][1] [2][0]
* [0][3] [1][2] [2][1] [3][0]
**/
private static int getDiagonalLeftUpper(int[][] matrix, int i) {
int d = 0;
StringBuilder sb = new StringBuilder();
while (d <= i) {
sb.append(matrix[d][i - d]);
d++;
}
return getMaxSum(sb);
}
/**
* [5][5]
* [5][4] [4][5]
* [5][3] [4][4] [3][5]
* [5][2] [4][3] [3][4] [2][5]
*/
private static int getDiagonalRightLower(int[][] matrix, int i) {
int n = matrix.length - 1;
int d = 0;
StringBuilder sb = new StringBuilder();
while (d <= i) {
sb.append(matrix[n - d][n - i + d]);
d++;
}
return getMaxSum(sb);
}
/**
* [0][5]
* [0][4] [1][5]
* [0][3] [1][4] [2][5]
* [0][2] [1][3] [2][4] [3][5]
*/
private static int getDiagonalRightUpper(int[][] matrix, int i) {
int d = 0;
int n = matrix.length - 1;
StringBuilder sb = new StringBuilder();
while (d <= i) {
sb.append(matrix[i - d][n - d]);
d++;
}
return getMaxSum(sb);
}
/**
* [5][0]
* [4][0] [5][1]
* [3][0] [4][1] [5][2]
* [2][0] [3][1] [4][2] [5][3]
*/
private static int getDiagonalLeftLower(int[][] matrix, int i) {
int n = matrix.length - 1;
int d = 0;
StringBuilder sb = new StringBuilder();
while (d <= i) {
sb.append(matrix[n - d][i - d]);
d++;
}
return getMaxSum(sb);
}
private static int getMaxSum(StringBuilder sb) {
String[] split = sb.toString().split("0");
int diagonalSum = 0;
for (String value : split) {
if (diagonalSum < value.length()) {
diagonalSum = value.length();
}
}
return diagonalSum;
}
public static void main(String[] args) {
int[][] matrix = new int[][]
{{0, 0, 0, 1, 0, 0},
{1, 0, 0, 0, 1, 0},
{0, 1, 0, 1, 1, 1},
{0, 0, 1, 0, 0, 0},
{0, 0, 0, 1, 0, 0},
{1, 0, 0, 0, 0, 0}};
int sum = getMatrixMaxSum(matrix);
System.out.println(sum);
}
}
| 24.790541 | 72 | 0.452439 |
4024ffd20da0784a248e3baf374656d1ea096af4 | 1,681 | package specialmembershipservice.bootstrap;
import static org.apache.kafka.clients.producer.ProducerConfig.ACKS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.BATCH_SIZE_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.BUFFER_MEMORY_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.LINGER_MS_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.RETRIES_CONFIG;
import static org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG;
import java.util.HashMap;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import org.apache.kafka.common.serialization.StringSerializer;
public class EventPublisherConfiguration {
@NotBlank
private String topic;
@NotEmpty
private Map<String, Object> configs;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Map<String, Object> getConfigs() {
Map<String, Object> configs = new HashMap<>();
configs.put(ACKS_CONFIG, "all");
configs.put(RETRIES_CONFIG, 1);
configs.put(BATCH_SIZE_CONFIG, 16384);
configs.put(LINGER_MS_CONFIG, 1);
configs.put(BUFFER_MEMORY_CONFIG, 33554432);
configs.put(KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configs.put(VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
configs.putAll(this.configs);
return configs;
}
public void setConfigs(Map<String, Object> configs) {
this.configs = configs;
}
}
| 33.62 | 93 | 0.791791 |
438d9208ab835ca1e046eae00afb2fdf10bc6947 | 42,648 | /*
* Copyright (c) 2016-2019 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.labkey.test.tests.cds;
import org.apache.commons.lang3.tuple.Pair;
import org.junit.Before;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.labkey.test.Locator;
import org.labkey.test.pages.cds.CDSExport;
import org.labkey.test.pages.cds.CDSPlot;
import org.labkey.test.pages.cds.ColorAxisVariableSelector;
import org.labkey.test.pages.cds.DataGrid;
import org.labkey.test.pages.cds.DataGridVariableSelector;
import org.labkey.test.pages.cds.DataspaceVariableSelector;
import org.labkey.test.pages.cds.XAxisVariableSelector;
import org.labkey.test.pages.cds.YAxisVariableSelector;
import org.labkey.test.util.cds.CDSAsserts;
import org.labkey.test.util.cds.CDSHelper;
import org.openqa.selenium.WebElement;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.labkey.test.util.cds.CDSHelper.GRID_COL_SUBJECT_ID;
import static org.labkey.test.util.cds.CDSHelper.GRID_TITLE_NAB;
@Category({})
public class CDSGridTest extends CDSReadOnlyTest
{
private final CDSHelper cds = new CDSHelper(this);
private final CDSAsserts _asserts = new CDSAsserts(this);
@Override
@Before
public void preTest()
{
cds.enterApplication();
// clean up groups
cds.goToAppHome();
sleep(CDSHelper.CDS_WAIT_ANIMATION); // let the group display load
cds.ensureNoFilter();
cds.ensureNoSelection();
// go back to app starting location
cds.goToAppHome();
}
@BeforeClass
public static void setShowHiddenVariables()
{
CDSGridTest currentTest = (CDSGridTest) getCurrentTest();
currentTest.cds.initModuleProperties(true); //set ShowHiddenVariables property to true
}
@AfterClass
public static void resetShowHiddenVariables()
{
CDSGridTest currentTest = (CDSGridTest) getCurrentTest();
currentTest.cds.initModuleProperties(false); // reset ShowHiddenVariables property back to false
}
@Override
public BrowserType bestBrowser()
{
return BrowserType.CHROME;
}
@Override
public List<String> getAssociatedModules()
{
return Arrays.asList("CDS");
}
@Test
public void verifyGrid()
{
log("Verify Grid");
DataGrid grid = new DataGrid(this);
DataGridVariableSelector gridColumnSelector = new DataGridVariableSelector(this, grid);
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
waitForText("View data grid"); // grid warning
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_ASSAY, true, true);
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_LAB, false, true);
grid.goToDataTab(GRID_TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_ASSAY, CDSHelper.NAB_LAB);
if (CDSHelper.validateCounts)
{
grid.assertPageTotal(432); // TODO Test data dependent.
}
//
// Check paging buttons with known dataset. Verify with first and last subject id on page.
//
log("Verify grid paging");
grid.goToLastPage();
if (CDSHelper.validateCounts)
{
grid.assertCurrentPage(432); // TODO Test data dependent.
grid.assertCellContent("z139-2398"); // TODO Test data dependent.
grid.assertCellContent("z139-2500"); // TODO Test data dependent.
}
grid.clickPreviousBtn();
if (CDSHelper.validateCounts)
{
grid.assertCurrentPage(431); // TODO Test data dependent.
grid.assertCellContent("z139-2157"); // TODO Test data dependent.
grid.assertCellContent("z139-2358"); // TODO Test data dependent.
}
grid.goToFirstPage();
if (CDSHelper.validateCounts)
{
grid.assertCellContent("q2-003"); // TODO Test data dependent.
}
//
// Navigate to Summary to apply a filter
//
cds.goToSummary();
cds.clickBy("Studies");
cds.hideEmpty();
cds.selectBars(CDSHelper.STUDIES[1]);
cds.useSelectionAsSubjectFilter();
waitForElement(CDSHelper.Locators.filterMemberLocator(CDSHelper.STUDIES[1]));
//
// Check to see if grid is properly filtering based on explorer filter
//
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
if (CDSHelper.validateCounts)
{
sleep(CDSHelper.CDS_WAIT_ANIMATION);
grid.assertPageTotal(43); // TODO Test data dependent.
}
cds.clearFilters();
_ext4Helper.waitForMaskToDisappear();
if (CDSHelper.validateCounts)
{
grid.assertRowCount(10783); // TODO Test data dependent.
assertElementPresent(DataGrid.Locators.cellLocator("q2-003")); // TODO Test data dependent.
}
gridColumnSelector.addGridColumn(CDSHelper.SUBJECT_CHARS, CDSHelper.DEMO_SEX, true, true);
gridColumnSelector.addGridColumn(CDSHelper.SUBJECT_CHARS, CDSHelper.DEMO_RACE, false, true);
grid.ensureColumnsPresent(CDSHelper.NAB_ASSAY, CDSHelper.NAB_LAB);
if (CDSHelper.validateCounts)
{
grid.assertRowCount(10783); // TODO Test data dependent.
}
grid.goToDataTab("Subject characteristics");
grid.ensureSubjectCharacteristicsColumnsPresent(CDSHelper.DEMO_SEX, CDSHelper.DEMO_RACE);
if (CDSHelper.validateCounts)
{
grid.assertPageTotal(332); // TODO Test data dependent.
}
log("Remove a column");
gridColumnSelector.removeGridColumn(CDSHelper.NAB, CDSHelper.NAB_ASSAY, false);
grid.goToDataTab("NAb");
grid.assertColumnsNotPresent(CDSHelper.NAB_ASSAY);
grid.ensureColumnsPresent(CDSHelper.NAB_LAB); // make sure other columns from the same source still exist
if (CDSHelper.validateCounts)
{
grid.assertRowCount(10783); // TODO Test data dependent.
}
grid.goToDataTab("Subject characteristics");
grid.setFacet(CDSHelper.DEMO_RACE, "White");
if (CDSHelper.validateCounts)
{
grid.assertPageTotal(32); // TODO Test data dependent.
grid.assertRowCount(792); // TODO Test data dependent.
_asserts.assertFilterStatusCounts(777, 48, 1, 3, 152); // TODO Test data dependent.
}
//
// More page button tests
//
log("Verify grid paging with filtered dataset");
grid.goToDataTab("NAb");
grid.sort(GRID_COL_SUBJECT_ID);
grid.clickNextBtn();
grid.assertCurrentPage(2);
if (CDSHelper.validateCounts)
{
grid.assertCellContent("z139-0599"); // TODO Test data dependent.
}
grid.clickPreviousBtn();
grid.goToPreviousPage();
grid.assertCurrentPage(3);
if (CDSHelper.validateCounts)
{
grid.assertCellContent("z135-197"); // TODO Test data dependent.
}
grid.goToNextPage();
grid.assertCurrentPage(5);
if (CDSHelper.validateCounts)
{
grid.assertCellContent("z135-030"); // TODO Test data dependent.
grid.assertCellContent("z135-005"); // TODO Test data dependent.
}
log("Change column set and ensure still filtered");
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_TITERID50, false, true);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50);
if (CDSHelper.validateCounts)
{
grid.assertPageTotal(32); // TODO Test data dependent.
grid.assertRowCount(792); // TODO Test data dependent.
_asserts.assertFilterStatusCounts(777, 48, 1, 3, 152); // TODO Test data dependent.
}
log("Verify Aligned Time Point Columns");
Map<String, Boolean> columns = new HashMap<>();
columns.put(CDSHelper.TIME_POINTS_DAYS, false);
columns.put(CDSHelper.TIME_POINTS_WEEKS, true);
columns.put(CDSHelper.TIME_POINTS_MONTHS, true);
columns.put(CDSHelper.TIME_POINTS_DAYS_FIRST_VACC, true);
columns.put(CDSHelper.TIME_POINTS_WEEKS_FIRST_VACC, true);
columns.put(CDSHelper.TIME_POINTS_MONTHS_FIRST_VACC, true);
columns.put(CDSHelper.TIME_POINTS_DAYS_LAST_VACC, true);
columns.put(CDSHelper.TIME_POINTS_WEEKS_LAST_VACC, true);
columns.put(CDSHelper.TIME_POINTS_MONTHS_LAST_VACC, true);
gridColumnSelector.openSelectorWindow();
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.TIME_POINTS, columns);
}
@Test
public void verifyNAbColumns() throws IOException
{
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(1000);
DataGrid grid = new DataGrid(this);
DataGridVariableSelector gridColumnSelector = new DataGridVariableSelector(this, grid);
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_TITERID50, false, true);
grid.goToDataTab(CDSHelper.GRID_TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50, CDSHelper.NAB_INIT_DILUTION, CDSHelper.NAB_VIRUS_NAME, CDSHelper.NAB_VIRUS_FULL_NAME, CDSHelper.NAB_VIRUS_SPECIES, CDSHelper.NAB_VIRUS_HOST_CELL, CDSHelper.NAB_VIRUS_BACKBONE);
}
@Test
public void verifyGridExport() throws IOException
{
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(1000);
DataGrid grid = new DataGrid(this);
log("Export without filter or additional columns");
CDSExport exported = new CDSExport(Arrays.asList(Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT, 14285)));
exported.setDataTabHeaders(Arrays.asList(Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days"))));
exported.setAssays(Collections.emptyList());
exported.setFieldLabels(Collections.emptyList());
grid.verifyCDSExcel(exported, false);
grid.verifyCDSCSV(exported);
setUpGridStep1();
exported = new CDSExport(Arrays.asList(Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT, 495),
Pair.of(CDSHelper.TITLE_ICS, 658)));
exported.setDataTabHeaders(Arrays.asList(
Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days")),
Pair.of(CDSHelper.GRID_TITLE_ICS,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days", "Antigen name", "Antigens aggregated"))
));
exported.setFilterTitles(Arrays.asList("Intracellular Cytokine Staining", "", "", "", "Subject (Race)"));
exported.setFilterValues(Arrays.asList("Data summary level: Protein Panel", "Functional marker name: IL2/ifngamma", "", "", "Subjects related to any: Asian"));
exported.setStudyNetworks(Arrays.asList("HVTN", "HVTN", "HVTN", "HVTN", "HVTN", "HVTN", "HVTN", "HVTN", "HVTN", "HVTN", "ROGER", "ROGER", "ROGER"));
exported.setStudies(Arrays.asList("ZAP 102", "ZAP 105", "ZAP 106", "ZAP 134",
"ZAP 136", "ZAP 113", "ZAP 115", "ZAP 116", "ZAP 117", "ZAP 118", "RED 4", "RED 5", "RED 6"));
exported.setAssays(Arrays.asList("Intracellular Cytokine Staining", "Intracellular Cytokine Staining", "Intracellular Cytokine Staining"));
exported.setAssayProvenances(Arrays.asList("VISC analysis dataset", "VISC analysis dataset", "LabKey dataset", "VISC analysis dataset", "VISC analysis dataset"));
exported.setFieldLabels(Arrays.asList("Antigen name", "Antigens aggregated", "Cell type", "Data summary level", "Functional marker name", "Lab ID", "Magnitude (% cells) - Background subtracted",
"Peptide Pool", "Protein", "Protein panel", "Specimen type"));
grid.verifyCDSExcel(exported, false);
grid.verifyCDSCSV(exported);
setUpGridStep2(false);
exported = new CDSExport(Arrays.asList(Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT, 7),
Pair.of(CDSHelper.GRID_TITLE_DEMO, 2),
Pair.of(CDSHelper.GRID_TITLE_ICS, 2),
Pair.of(CDSHelper.GRID_TITLE_NAB, 13)));
exported.setDataTabHeaders(Arrays.asList(
Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days")),
Pair.of(CDSHelper.GRID_TITLE_DEMO,
Arrays.asList("Subject Id", "Study Name", "Treatment Summary", "Sex at birth")),
Pair.of(CDSHelper.GRID_TITLE_ICS,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days", "Antigen name", "Antigens aggregated"))
));
exported.setFilterTitles(Arrays.asList("Demographics",
"",
"",
"Intracellular Cytokine Staining",
"",
"",
"",
"",
"Subject (Race)"));
exported.setFilterValues(Arrays.asList("Sex at birth = Male",
"",
"",
"Data summary level: Protein Panel",
"Functional marker name: IL2/ifngamma",
"Magnitude (% cells) - Background subtracted >= 1",
"",
"",
"Subjects related to any: Asian"));
exported.setStudyNetworks(Arrays.asList("HVTN", "HVTN"));
exported.setStudies(Arrays.asList("ZAP 134", "ZAP 117"));
exported.setAssays(Arrays.asList("HIV Neutralizing Antibody",
"HIV Neutralizing Antibody",
"Intracellular Cytokine Staining",
"Intracellular Cytokine Staining"));
exported.setAssayProvenances(Arrays.asList("LabKey dataset",
"VISC analysis dataset",
"VISC analysis dataset",
"VISC analysis dataset"));
exported.setFieldLabels(Arrays.asList("Subject Id",
"Study Name",
"Treatment Summary",
"Sex at birth",
"Antigen name",
"Antigens aggregated",
"Cell type",
"Data summary level",
"Functional marker name",
"Lab ID",
"Magnitude (% cells) - Background subtracted",
"Peptide Pool",
"Protein",
"Protein panel",
"Specimen type",
"Data summary level",
"Initial dilution",
"Lab ID",
"Specimen type",
"Target cell",
"Titer ID50",
"Virus name",
"Virus full name",
"Virus type",
"Virus species",
"Virus clade",
"Virus host cell",
"Virus backbone"
));
grid.verifyCDSExcel(exported, false);
grid.verifyCDSCSV(exported);
}
@Test
public void verifyGridWithPlotAndFilters()
{
log("Verify Grid with gridbase field filters.");
cds.openStatusInfoPane("Studies");
String studyMember = "RED 5";
cds.selectInfoPaneItem(studyMember, true);
click(CDSHelper.Locators.cdsButtonLocator("Filter", "filterinfoaction"));
waitForElement(CDSHelper.Locators.filterMemberLocator(studyMember));
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(5000);
DataGrid grid = new DataGrid(this);
assertTrue(GRID_COL_SUBJECT_ID + " column facet is not as expected", grid.isHasData(GRID_COL_SUBJECT_ID, "r5-120"));
assertTrue(GRID_COL_SUBJECT_ID + " column facet is not as expected", grid.isNoData(GRID_COL_SUBJECT_ID, "q1-001"));
log("Create a plot with Study on X axis.");
CDSHelper.NavigationLink.PLOT.makeNavigationSelection(this);
YAxisVariableSelector yAxis = new YAxisVariableSelector(this);
XAxisVariableSelector xAxis = new XAxisVariableSelector(this);
yAxis.openSelectorWindow();
yAxis.pickSource(CDSHelper.ICS);
yAxis.pickVariable(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
yAxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
xAxis.openSelectorWindow();
xAxis.pickSource(CDSHelper.TIME_POINTS);
xAxis.pickVariable(CDSHelper.TIME_POINTS_DAYS);
sleep(CDSHelper.CDS_WAIT_ANIMATION);
xAxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
CDSPlot cdsPlot = new CDSPlot(this);
assertTrue("Plot is not rendered as expected.", cdsPlot.hasStudyAxis());
cds.ensureNoFilter();
cds.ensureNoSelection();
log("Verify Grid with filters.");
setUpGridStep1();
log("Validate expected columns are present.");
grid.goToDataTab(CDSHelper.TITLE_ICS);
grid.ensureColumnsPresent(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
log("Validating grid counts");
_asserts.assertFilterStatusCounts(159, 13, 1, 3, 45);
grid.assertPageTotal(27);
setUpGridStep2(true);
_asserts.assertFilterStatusCounts(2, 2, 1, 3, 2);
grid.assertPageTotal(1);
grid.goToDataTab(CDSHelper.GRID_TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50, CDSHelper.NAB_INIT_DILUTION, CDSHelper.NAB_VIRUS_NAME);
grid.assertRowCount(13);
grid.goToDataTab(CDSHelper.GRID_TITLE_ICS);
grid.ensureColumnsPresent(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
grid.assertRowCount(2);
log("Remove the plot and validate that the columns stay the same, but the counts could change.");
cds.clearFilter(0);
_asserts.assertFilterStatusCounts(2, 2, 1, 3, 2);
grid.assertPageTotal(1);
grid.goToDataTab(CDSHelper.GRID_TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50, CDSHelper.NAB_INIT_DILUTION, CDSHelper.NAB_VIRUS_NAME);
grid.assertRowCount(13);
grid.goToDataTab(CDSHelper.GRID_TITLE_ICS);
grid.ensureColumnsPresent(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
grid.assertRowCount(4);
cds.goToAppHome();
cds.clearFilters();
}
private void setUpGridStep1()
{
DataGrid grid = new DataGrid(this);
DataGridVariableSelector gridColumnSelector = new DataGridVariableSelector(this, grid);
cds.goToSummary();
cds.clickBy(CDSHelper.SUBJECT_CHARS);
cds.pickSort("Race");
cds.selectBars(CDSHelper.RACE_ASIAN);
log("Create a plot that will filter.");
CDSHelper.NavigationLink.PLOT.makeNavigationSelection(this);
YAxisVariableSelector yAxis = new YAxisVariableSelector(this);
// There was a regression when only the y axis was set the filter counts would go to 0.
// That is why this test is here.
yAxis.openSelectorWindow();
yAxis.pickSource(CDSHelper.ICS);
yAxis.pickVariable(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
yAxis.setCellType("All");
yAxis.setScale(DataspaceVariableSelector.Scale.Linear);
yAxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(1000);
}
private void setUpGridStep2(boolean verifyGrid)
{
DataGrid grid = new DataGrid(this);
DataGridVariableSelector gridColumnSelector = new DataGridVariableSelector(this, grid);
log("Applying a column filter.");
grid.goToDataTab(CDSHelper.TITLE_ICS);
grid.setFilter(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB, "Is Greater Than or Equal To", "1");
sleep(1000); // There is a brief moment where the grid refreshes because of filters applied in the grid.
if (verifyGrid)
{
_asserts.assertFilterStatusCounts(4, 3, 1, 3, 3);
grid.assertPageTotal(1);
grid.ensureColumnsPresent(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
}
log("Go back to the grid and apply a color to it. Validate it appears as a column.");
// Can't use CDSHelper.NavigationLink.Grid.makeNavigationSelection. It expects that it will be going to a blank plot.
click(CDSHelper.NavigationLink.PLOT.getLinkLocator());
sleep(1000); // There is a brief moment where the grid refreshes because of filters applied in the grid.
ColorAxisVariableSelector coloraxis = new ColorAxisVariableSelector(this);
coloraxis.openSelectorWindow();
coloraxis.pickSource(CDSHelper.SUBJECT_CHARS);
coloraxis.pickVariable(CDSHelper.DEMO_SEX);
coloraxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(1000); // There is a brief moment where the grid refreshes because of filters applied in the grid.
grid.goToDataTab(CDSHelper.GRID_TITLE_DEMO);
if (verifyGrid)
{
log("Validate new column added to grid.");
grid.ensureSubjectCharacteristicsColumnsPresent(CDSHelper.DEMO_SEX);
}
log("Filter on new column.");
grid.setCheckBoxFilter(CDSHelper.DEMO_SEX, true, "Male");
sleep(1000); // There is a brief moment where the grid refreshes because of filters applied in the grid.
if (verifyGrid)
{
_asserts.assertFilterStatusCounts(2, 2, 1, 3, 2);
grid.assertRowCount(2);
}
log("Now add a new column to the mix.");
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_TITERID50, false, true);
_ext4Helper.waitForMaskToDisappear();
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(1000);
}
@Test
public void verifyGridTabsAndColumns()
{
/*
* Default Study And Time | Added Study And Treatment | Added Time | Subject Characteristics
* Study And Treatment Y Y N N
* Subject Characteristics N (demographics version) Y N Y
* Assays Y N Y N
*/
DataGrid grid = new DataGrid(this);
DataGridVariableSelector gridColumnSelector = new DataGridVariableSelector(this, grid);
log("Verify Default Grid: " + CDSHelper.GRID_TITLE_STUDY_TREATMENT);
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
Locator.XPathLocator activeTabLoc = DataGrid.Locators.getActiveHeader(CDSHelper.GRID_TITLE_STUDY_TREATMENT);
waitForElement(activeTabLoc);
grid.ensureColumnsPresent(); // verify default columns
log("Verify grid with added study and treatment columns");
gridColumnSelector.addGridColumn(CDSHelper.STUDY_TREATMENT_VARS, CDSHelper.STUDY_TREATMENT_VARS, CDSHelper.DEMO_NETWORK, true, true);
gridColumnSelector.confirmSelection();
sleep(2000);
assertTrue("Grid tabs are not as expected", grid.isDataTabsEquals(Arrays.asList(CDSHelper.GRID_TITLE_STUDY_TREATMENT)));
grid.ensureColumnsPresent(CDSHelper.DEMO_NETWORK);
log("Verify grid with added assay columns");
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_ASSAY, true, true);
gridColumnSelector.addGridColumn(CDSHelper.NAB, GRID_TITLE_NAB, CDSHelper.NAB_LAB, false, true);
assertTrue("Grid tabs are not as expected", grid.isDataTabsEquals(Arrays.asList(CDSHelper.GRID_TITLE_STUDY_TREATMENT, CDSHelper.GRID_TITLE_NAB)));
grid.goToDataTab(GRID_TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_ASSAY, CDSHelper.NAB_LAB);
log("Verify grid with subject characteristics and time point columns");
gridColumnSelector.addGridColumn(CDSHelper.SUBJECT_CHARS, CDSHelper.DEMO_SEX, true, true);
gridColumnSelector.addGridColumn(CDSHelper.SUBJECT_CHARS, CDSHelper.DEMO_RACE, false, true);
assertTrue("Grid tabs are not as expected", grid.isDataTabsEquals(Arrays.asList(CDSHelper.GRID_TITLE_STUDY_TREATMENT, CDSHelper.GRID_TITLE_DEMO, CDSHelper.GRID_TITLE_NAB)));
gridColumnSelector.addGridColumn(CDSHelper.TIME_POINTS, CDSHelper.TIME_POINTS_MONTHS, true, true);
gridColumnSelector.confirmSelection();
sleep(2000);
assertTrue("Grid tabs are not as expected", grid.isDataTabsEquals(Arrays.asList(CDSHelper.GRID_TITLE_STUDY_TREATMENT, CDSHelper.GRID_TITLE_DEMO, CDSHelper.GRID_TITLE_NAB)));
// go to another page and come back to grid
cds.goToSummary();
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
assertEquals("Grid tab selection should not have changed", GRID_TITLE_NAB, grid.getActiveDataTab());
grid.ensureColumnsPresent(CDSHelper.NAB_ASSAY, CDSHelper.NAB_LAB, CDSHelper.TIME_POINTS_MONTHS);
log("Verify subject characteristics and study treatment columns are not added to assay tabs");
grid.assertColumnsNotPresent(CDSHelper.DEMO_SEX, CDSHelper.DEMO_RACE, CDSHelper.DEMO_NETWORK);
log("Verify assay and time columns are not added to subject characteristics tab");
grid.goToDataTab(CDSHelper.GRID_TITLE_DEMO);
grid.ensureSubjectCharacteristicsColumnsPresent(CDSHelper.DEMO_SEX, CDSHelper.DEMO_RACE, CDSHelper.DEMO_NETWORK);
grid.assertColumnsNotPresent(CDSHelper.NAB_ASSAY, CDSHelper.NAB_LAB, CDSHelper.TIME_POINTS_MONTHS);
log("Verify subject characteristics columns are not added to study and treatment tab");
grid.goToDataTab(CDSHelper.GRID_TITLE_STUDY_TREATMENT);
grid.assertColumnsNotPresent(CDSHelper.DEMO_SEX, CDSHelper.DEMO_RACE);
}
@Test
public void verifyGridColumnSelector()
{
CDSHelper cds = new CDSHelper(this);
log("Verify Grid column selector.");
DataGrid grid = new DataGrid(this);
DataGridVariableSelector gridColumnSelector = new DataGridVariableSelector(this, grid);
log("Create a plot that will filter.");
CDSHelper.NavigationLink.PLOT.makeNavigationSelection(this);
YAxisVariableSelector yAxis = new YAxisVariableSelector(this);
XAxisVariableSelector xAxis = new XAxisVariableSelector(this);
ColorAxisVariableSelector colorAxis = new ColorAxisVariableSelector(this);
yAxis.openSelectorWindow();
yAxis.pickSource(CDSHelper.NAB);
yAxis.pickVariable(CDSHelper.NAB_TITERID50);
yAxis.setVirusName(cds.buildIdentifier(CDSHelper.TITLE_NAB, CDSHelper.COLUMN_ID_NEUTRAL_TIER, CDSHelper.NEUTRAL_TIER_1));
yAxis.setScale(DataspaceVariableSelector.Scale.Linear);
sleep(CDSHelper.CDS_WAIT_ANIMATION);
yAxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
xAxis.openSelectorWindow();
xAxis.pickSource(CDSHelper.ICS);
xAxis.pickVariable(CDSHelper.ICS_ANTIGEN);
sleep(CDSHelper.CDS_WAIT_ANIMATION);
xAxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
colorAxis.openSelectorWindow();
colorAxis.pickSource(CDSHelper.SUBJECT_CHARS);
colorAxis.pickVariable(CDSHelper.DEMO_RACE);
colorAxis.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
waitForText("View data grid"); // grid warning
_ext4Helper.waitForMaskToDisappear();
log("Validate expected columns are present.");
grid.goToDataTab(CDSHelper.TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50);
grid.goToDataTab(CDSHelper.TITLE_ICS);
grid.ensureColumnsPresent(CDSHelper.ICS_ANTIGEN);
grid.goToDataTab(CDSHelper.SUBJECT_CHARS);
grid.ensureSubjectCharacteristicsColumnsPresent(CDSHelper.DEMO_RACE);
gridColumnSelector.openSelectorWindow();
Map<String, Boolean> columns = new HashMap<>();
columns.put(CDSHelper.ICS_ANTIGEN, false);
columns.put(CDSHelper.NAB_TITERID50, false);
columns.put(CDSHelper.DEMO_RACE, false);
log("Validate that Current columns are as expected and not selectable.");
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_CUR_COL, columns);
log("Validate that All columns are as expected and not selectable.");
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_ALL_VARS, columns);
log("Validate that column selectors are as expected in their specific variable selector.");
Map<String, Boolean> oneColumn = new HashMap<>();
oneColumn.put(CDSHelper.DEMO_RACE, false);
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.SUBJECT_CHARS, oneColumn);
oneColumn.clear();
oneColumn.put(CDSHelper.ICS_ANTIGEN, false);
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.ICS, oneColumn);
oneColumn.clear();
oneColumn.put(CDSHelper.NAB_TITERID50, false);
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.NAB, oneColumn);
oneColumn.clear();
log("Now add a new column to the mix.");
gridColumnSelector.pickSource(CDSHelper.ICS);
click(Locator.xpath("//div[contains(@class, 'column-axis-selector')]//div[contains(@class, 'x-grid-cell-inner')][text()='" + CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB + "']"));
log("Validate that Current columns are as expected and enabled or not as appropriate.");
columns.put(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB, true);
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_CUR_COL, columns);
log("Validate that All columns are as expected and enabled or not as appropriate.");
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_ALL_VARS, columns);
gridColumnSelector.confirmSelection();
_ext4Helper.waitForMaskToDisappear();
grid.goToDataTab(CDSHelper.TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50);
grid.goToDataTab(CDSHelper.TITLE_ICS);
grid.ensureColumnsPresent(CDSHelper.ICS_ANTIGEN, CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
grid.goToDataTab(CDSHelper.SUBJECT_CHARS);
grid.ensureSubjectCharacteristicsColumnsPresent(CDSHelper.DEMO_RACE);
log("Filter on added column, check to make sure it is now 'locked' in the selector.");
grid.goToDataTab(CDSHelper.TITLE_ICS);
grid.setFilter(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB, "Is Less Than or Equal To", "0.003");
gridColumnSelector.openSelectorWindow();
columns.replace(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB, false);
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_CUR_COL, columns);
log("Validate that All columns are as expected and enabled or not as appropriate.");
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_ALL_VARS, columns);
gridColumnSelector.cancelSelection();
log("Remove the filter on the column, and validate that the selector goes back to as before.");
grid.clearFilters(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB);
columns.replace(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB, true);
gridColumnSelector.openSelectorWindow();
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_CUR_COL, columns);
log("Validate that All columns are as expected and enabled or not as appropriate.");
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_ALL_VARS, columns);
log("Remove the column and validate the columns are as expected.");
gridColumnSelector.pickSource(CDSHelper.ICS);
click(Locator.xpath("//div[contains(@class, 'column-axis-selector')]//div[contains(@class, 'x-grid-cell-inner')][text()='" + CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB + "']"));
gridColumnSelector.confirmSelection();
grid.goToDataTab(CDSHelper.TITLE_NAB);
grid.ensureColumnsPresent(CDSHelper.NAB_TITERID50);
grid.goToDataTab(CDSHelper.TITLE_ICS);
grid.ensureColumnsPresent(CDSHelper.ICS_ANTIGEN);
grid.goToDataTab(CDSHelper.SUBJECT_CHARS);
grid.ensureSubjectCharacteristicsColumnsPresent(CDSHelper.DEMO_RACE);
log("Validate the column chooser is correct when a column is removed.");
String selectorText, selectorTextClean;
String expectedText, expectedTextClean;
gridColumnSelector.openSelectorWindow();
gridColumnSelector.pickSource(CDSHelper.GRID_COL_ALL_VARS);
assertElementPresent("Could not find unchecked checkbox with text: '" + CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB + "'", Locator.xpath("//div[contains(@class, 'column-axis-selector')]//table[contains(@role, 'presentation')]//tbody//tr[not(contains(@class, 'x-grid-row-selected'))]//div[contains(@class, 'x-grid-cell-inner')][text()='" + CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB + "']"), 1);
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_ALL_VARS, columns);
gridColumnSelector.pickSource(CDSHelper.GRID_COL_CUR_COL);
selectorText = Locator.xpath("//div[contains(@class, 'column-axis-selector')]//table[contains(@role, 'presentation')]").findElement(getDriver()).getText();
assertFalse("Found '" + CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB + "' in current columns and it should not be there.", selectorText.contains(CDSHelper.ICS_MAGNITUDE_BACKGROUND_SUB));
gridColumnSelector.confirmSelection();
log("Clear the filters and make sure the selector reflects this.");
cds.clearFilters();
waitForText(5000, "Filter removed.");
_ext4Helper.waitForMaskToDisappear();
gridColumnSelector.openSelectorWindow();
gridColumnSelector.pickSource(CDSHelper.GRID_COL_ALL_VARS);
selectorText = Locator.xpath("//div[contains(@class, 'column-axis-selector')]//table[contains(@role, 'presentation')]").findElement(getDriver()).getText();
selectorTextClean = selectorText.toLowerCase().replaceAll("\\n", "");
selectorTextClean = selectorTextClean.replaceAll("\\s+", "");
expectedText = "ICS (Intracellular Cytokine Staining)\n Magnitude (% cells) - Background subtracted\n Antigen name\n Antigens aggregated\n Cell type\n Data summary level\n Functional marker name\n" +
" Lab ID\n Peptide Pool\n Protein\n Protein panel\n Specimen type\nNAb (Neutralizing antibody)\n Titer ID50\nStudy and treatment variables\n Study Name\n Treatment Summary\n" +
"Subject characteristics\n Race\n Subject Id\nTime points\n Study days";
expectedTextClean = expectedText.toLowerCase().replaceAll("\\n", "");
expectedTextClean = expectedTextClean.replaceAll("\\s+", "");
assertTrue("Values not as expected in all variables. Expected: '" + expectedText + "' Actual: '" + selectorText + "'.", expectedTextClean.equals(selectorTextClean));
gridColumnSelector.pickSource(CDSHelper.GRID_COL_CUR_COL);
selectorText = Locator.xpath("//div[contains(@class, 'column-axis-selector')]//table[contains(@role, 'presentation')]").findElement(getDriver()).getText();
selectorText = selectorText.trim();
assertTrue("Expected no text in Current columns. Found: '" + selectorText + "'.", selectorText.equals("Study and treatment variables\n Study Name\n Treatment Summary\nSubject characteristics\n" +
" Subject Id\nTime points\n Study days"));
gridColumnSelector.confirmSelection();
log("Validating treatment and study variables");
gridColumnSelector.openSelectorWindow();
gridColumnSelector.pickSource(CDSHelper.STUDY_TREATMENT_VARS);
click(Locator.xpath("//div[contains(@class, 'column-axis-selector')]//div[contains(@class, 'x-column-header-checkbox')]"));
gridColumnSelector.confirmSelection();
sleep(500); //Wait for mask to appear.
_ext4Helper.waitForMaskToDisappear();
grid.ensureColumnsPresent();
columns.clear();
columns.put(CDSHelper.DEMO_STUDY_NAME, false);
columns.put(CDSHelper.DEMO_TREAT_SUMM, false);
columns.put(CDSHelper.DEMO_DATE_SUBJ_ENR, true);
columns.put(CDSHelper.DEMO_DATE_FUP_COMP, true);
columns.put(CDSHelper.DEMO_DATE_PUB, true);
columns.put(CDSHelper.DEMO_DATE_START, true);
columns.put(CDSHelper.DEMO_NETWORK, true);
columns.put(CDSHelper.DEMO_STRATEGY, true);
columns.put(CDSHelper.DEMO_PI, true);
columns.put(CDSHelper.DEMO_PROD_CLASS, true);
columns.put(CDSHelper.DEMO_PROD_COMB, true);
columns.put(CDSHelper.DEMO_STUDY_TYPE, true);
columns.put(CDSHelper.DEMO_TREAT_ARM, true);
columns.put(CDSHelper.DEMO_TREAT_CODED, true);
columns.put(CDSHelper.DEMO_VACC_PLAC, true);
gridColumnSelector.openSelectorWindow();
log("Validate that Current columns are as expected and selectable.");
gridColumnSelectorValidator(gridColumnSelector, CDSHelper.GRID_COL_CUR_COL, columns);
gridColumnSelector.cancelSelection();
cds.goToAppHome();
}
private void gridColumnSelectorValidator(DataGridVariableSelector gridColumnSelector, String source, Map<String, Boolean> columns)
{
String xpathColumnNameTemplate = "//div[contains(@class, 'column-axis-selector')]//table[contains(@role, 'presentation')]//td[contains(@role, 'gridcell')]//div[contains(@class, 'x-grid-cell-inner')][text()='*']";
String xpathSelectorColumnName;
String xpathSpecificCheckboxesTemplate = "//div[contains(@class, 'column-axis-selector')]//table[contains(@role, 'presentation')]//tr//td//div[text()='*']/./ancestor::tr//div[contains(@class, 'x-grid-row-checker')]";
String xpathSpecificCheckbox;
WebElement checkBox;
gridColumnSelector.pickSource(source);
for (Map.Entry<String, Boolean> entry : columns.entrySet())
{
xpathSelectorColumnName = xpathColumnNameTemplate.replaceAll("[*]", entry.getKey());
assertElementVisible(Locator.xpath(xpathSelectorColumnName));
xpathSpecificCheckbox = xpathSpecificCheckboxesTemplate.replaceAll("[*]", entry.getKey());
checkBox = Locator.xpath(xpathSpecificCheckbox).findElement(getDriver());
// Should the checkbox be enabled/checkable?
if (entry.getValue())
{
assertFalse("Check-box for " + entry.getKey() + " is disabled and it should not be.", checkBox.getAttribute("class").toLowerCase().contains("checker-disabled"));
}
else
{
assertTrue("Check-box for " + entry.getKey() + " is not disabled.", checkBox.getAttribute("class").toLowerCase().contains("checker-disabled"));
}
}
gridColumnSelector.backToSource();
}
@Test
public void verifyPKPlotGrid()
{
goToProjectHome();
cds.enterApplication();
CDSHelper.NavigationLink.SUMMARY.makeNavigationSelection(this);
cds.addRaceFilter(CDSHelper.RACE_WHITE);
CDSHelper.NavigationLink.PLOT.makeNavigationSelection(this);
YAxisVariableSelector yaxis = new YAxisVariableSelector(this);
log("Plot PK MAb");
yaxis.openSelectorWindow();
yaxis.pickSource(CDSHelper.PKMAB);
yaxis.pickVariable(CDSHelper.PKMAB_CONCENTRATION);
yaxis.confirmSelection();
CDSHelper.NavigationLink.GRID.makeNavigationSelection(this);
sleep(5000);
DataGrid grid = new DataGrid(this);
log("Validate additional mab and visit columns are present in grid.");
grid.goToDataTab(CDSHelper.TITLE_PKMAB);
grid.ensureColumnsPresent(CDSHelper.PKMAB_MAB_LABEL, CDSHelper.PKMAB_MAB_ID, CDSHelper.PKMAB_VISIT_CODE, CDSHelper.PKMAB_VISIT_DESC);
log("Verify PKMAb grid export");
CDSExport exported = new CDSExport(Arrays.asList(Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT, 80),
Pair.of(CDSHelper.TITLE_PKMAB, 116)));
exported.setDataTabHeaders(Arrays.asList(
Pair.of(CDSHelper.GRID_TITLE_STUDY_TREATMENT,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days")),
Pair.of(CDSHelper.TITLE_PKMAB,
Arrays.asList("Subject Id", "Study", "Treatment Summary", "Study days", "Data summary level", "Lab ID",
"MAb concentration", "MAb or mixture id", "MAb or mixture label", "MAb or mixture standardized name",
"Source assay", "Specimen type", "Visit code", "Visit description"))
));
exported.setStudyNetworks(Arrays.asList("HVTN"));
exported.setAssays(Arrays.asList("Monoclonal Antibody Pharmacokinetics"));
exported.setAssayProvenances(Arrays.asList("VISC analysis dataset"));
exported.setFieldLabels(Arrays.asList("Data summary level", "Lab ID", "MAb concentration", "MAb or mixture id",
"MAb or mixture label", "MAb or mixture standardized name", "Source assay", "Specimen type", "Visit code", "Visit description"));
grid.verifyCDSExcel(exported, false);
}
}
| 46.406964 | 393 | 0.675811 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.