Unnamed: 0
int64 0
9.45k
| cwe_id
stringclasses 1
value | source
stringlengths 37
2.53k
| target
stringlengths 19
2.4k
|
---|---|---|---|
200 | public Map<String, Object> queryTaskListByProcessId(User loginUser, String projectName, Integer processId) throws IOException{
Map<String, Object> result = new HashMap<>();
Project project = projectMapper.queryByName(projectName);
Map<String, Object> checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
Status resultEnum = (Status) checkResult.get(Constants.STATUS);
if (resultEnum != Status.SUCCESS) {
return checkResult;
}
ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
List<TaskInstance> taskInstanceList = processService.findValidTaskListByProcessId(processId);
addDependResultForTaskList(taskInstanceList);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put(PROCESS_INSTANCE_STATE, processInstance.getState().toString());
resultMap.put(TASK_LIST, taskInstanceList);
result.put(DATA_LIST, resultMap);
putMsg(result, Status.SUCCESS);
return result;
} | public Result<Map<String, Object>> queryTaskListByProcessId(User loginUser, String projectName, Integer processId) throws IOException{
Project project = projectMapper.queryByName(projectName);
CheckParamResult checkResult = projectService.checkProjectAndAuth(loginUser, project, projectName);
if (!Status.SUCCESS.equals(checkResult.getStatus())) {
return Result.error(checkResult);
}
ProcessInstance processInstance = processService.findProcessInstanceDetailById(processId);
List<TaskInstance> taskInstanceList = processService.findValidTaskListByProcessId(processId);
addDependResultForTaskList(taskInstanceList);
Map<String, Object> resultMap = new HashMap<>();
resultMap.put(PROCESS_INSTANCE_STATE, processInstance.getState().toString());
resultMap.put(TASK_LIST, taskInstanceList);
return Result.success(resultMap);
} |
|
201 | public ModelAndView searchLast(@Valid @ModelAttribute("searchRecordsRequest") SearchRecordsRequest searchRecordsRequest, BindingResult result, Model model){
searchRecordsRequest.setSearchResultRows(null);
searchRecordsRequest.setPageNumber(searchRecordsRequest.getTotalPageCount() - 1);
searchRecordsUtil.searchAndBuildResults(searchRecordsRequest);
return new ModelAndView("searchRecords", "searchRecordsRequest", searchRecordsRequest);
} | public ModelAndView searchLast(@Valid @ModelAttribute("searchRecordsRequest") SearchRecordsRequest searchRecordsRequest, BindingResult result, Model model){
searchRecordsRequest.setPageNumber(searchRecordsRequest.getTotalPageCount() - 1);
searchAndSetResults(searchRecordsRequest);
return new ModelAndView("searchRecords", "searchRecordsRequest", searchRecordsRequest);
} |
|
202 | public static void countFileLines(String fileName){
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Constant.UTF_8));
boolean stop = false;
while (!stop) {
final String line = in.readLine();
if (line != null) {
countLineTypes(line);
} else {
stop = true;
}
}
numberOfFiles++;
} catch (final IOException exception) {
Verbose.exception(exception);
}
UtilStream.safeClose(in);
} | public static void countFileLines(String fileName){
try (BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Constant.UTF_8))) {
boolean stop = false;
while (!stop) {
final String line = in.readLine();
if (line != null) {
countLineTypes(line);
} else {
stop = true;
}
}
numberOfFiles++;
} catch (final IOException exception) {
Verbose.exception(exception);
}
} |
|
203 | private ApplicationWithPrograms deployApp(Id.Namespace namespace, @Nullable String appName, @Nullable String configStr, ProgramTerminator programTerminator, ArtifactDetail artifactDetail) throws Exception{
authorizerInstantiatorService.get().enforce(namespace.toEntityId(), SecurityRequestContext.toPrincipal(), Action.WRITE);
Id.Artifact artifactId = Id.Artifact.from(namespace, artifactDetail.getDescriptor().getArtifactId());
Set<ApplicationClass> appClasses = artifactDetail.getMeta().getClasses().getApps();
if (appClasses.isEmpty()) {
throw new InvalidArtifactException(String.format("No application classes found in artifact '%s'.", artifactId));
}
String className = appClasses.iterator().next().getClassName();
Location location = artifactDetail.getDescriptor().getLocation();
AppDeploymentInfo deploymentInfo = new AppDeploymentInfo(artifactId, className, location, configStr);
Manager<AppDeploymentInfo, ApplicationWithPrograms> manager = managerFactory.create(programTerminator);
ApplicationWithPrograms applicationWithPrograms = manager.deploy(namespace, appName, deploymentInfo).get();
authorizerInstantiatorService.get().grant(namespace.toEntityId().app(applicationWithPrograms.getId().getId()), SecurityRequestContext.toPrincipal(), ImmutableSet.of(Action.ALL));
return applicationWithPrograms;
} | private ApplicationWithPrograms deployApp(NamespaceId namespaceId, @Nullable String appName, @Nullable String configStr, ProgramTerminator programTerminator, ArtifactDetail artifactDetail) throws Exception{
authorizerInstantiatorService.get().enforce(namespaceId, SecurityRequestContext.toPrincipal(), Action.WRITE);
ApplicationClass appClass = Iterables.getFirst(artifactDetail.getMeta().getClasses().getApps(), null);
if (appClass == null) {
throw new InvalidArtifactException(String.format("No application class found in artifact '%s' in namespace '%s'.", artifactDetail.getDescriptor().getArtifactId(), namespaceId));
}
AppDeploymentInfo deploymentInfo = new AppDeploymentInfo(artifactDetail.getDescriptor(), namespaceId, appClass.getClassName(), appName, configStr);
Manager<AppDeploymentInfo, ApplicationWithPrograms> manager = managerFactory.create(programTerminator);
ApplicationWithPrograms applicationWithPrograms = manager.deploy(deploymentInfo).get();
authorizerInstantiatorService.get().grant(applicationWithPrograms.getApplicationId(), SecurityRequestContext.toPrincipal(), ImmutableSet.of(Action.ALL));
return applicationWithPrograms;
} |
|
204 | public Future<?> reloadTimeDependentDataInContacts(){
return this.executor.submit(() -> {
final Context context = getApplication().getApplicationContext();
final ZodiacCalculator zodiacCalculator = new ZodiacCalculator();
final DateConverter dateConverter = new DateConverter();
final EventTypeLabelService eventTypeLabelService = new EventTypeLabelService(context);
final ContactFactory contactFactory = new ContactFactory(zodiacCalculator, dateConverter, eventTypeLabelService);
final LocalDate now = LocalDate.now();
final List<Contact> newContacts = contacts.getValue().stream().map(c -> contactFactory.calculateTimeDependentData(c, now)).collect(Collectors.toList());
contacts.postValue(newContacts);
});
} | public Future<?> reloadTimeDependentDataInContacts(){
return this.executor.submit(() -> {
final Context context = getApplication().getApplicationContext();
final ContactCreator contactCreator = new ContactCreatorFactory().createContactCreator(context);
final LocalDate now = LocalDate.now();
final List<Contact> contacts = this.contacts.getValue();
if (contacts != null) {
this.contacts.postValue(contacts.stream().map(c -> contactCreator.calculateTimeDependentData(c, now)).collect(Collectors.toList()));
}
});
} |
|
205 | public Map<String, Object> countCommandState(User loginUser, int projectId, String startDate, String endDate){
Map<String, Object> result = new HashMap<>();
boolean checkProject = checkProject(loginUser, projectId, result);
if (!checkProject) {
return result;
}
Date start = null;
if (StringUtils.isNotEmpty(startDate)) {
start = DateUtils.getScheduleDate(startDate);
if (Objects.isNull(start)) {
putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, Constants.START_END_DATE);
return result;
}
}
Date end = null;
if (StringUtils.isNotEmpty(endDate)) {
end = DateUtils.getScheduleDate(endDate);
if (Objects.isNull(end)) {
putMsg(result, Status.REQUEST_PARAMS_NOT_VALID_ERROR, Constants.START_END_DATE);
return result;
}
}
Integer[] projectIdArray = getProjectIdsArrays(loginUser, projectId);
Map<CommandType, Integer> normalCountCommandCounts = commandMapper.countCommandState(loginUser.getId(), start, end, projectIdArray).stream().collect(Collectors.toMap(CommandCount::getCommandType, CommandCount::getCount));
Map<CommandType, Integer> errorCommandCounts = errorCommandMapper.countCommandState(start, end, projectIdArray).stream().collect(Collectors.toMap(CommandCount::getCommandType, CommandCount::getCount));
List<CommandStateCount> list = Arrays.stream(CommandType.values()).map(commandType -> new CommandStateCount(errorCommandCounts.getOrDefault(commandType, 0), normalCountCommandCounts.getOrDefault(commandType, 0), commandType)).collect(Collectors.toList());
result.put(Constants.DATA_LIST, list);
putMsg(result, Status.SUCCESS);
return result;
} | public Result<List<CommandStateCount>> countCommandState(User loginUser, int projectId, String startDate, String endDate){
CheckParamResult checkResult = checkProject(loginUser, projectId);
if (!Status.SUCCESS.equals(checkResult.getStatus())) {
return Result.error(checkResult);
}
Date start = null;
if (StringUtils.isNotEmpty(startDate)) {
start = DateUtils.getScheduleDate(startDate);
if (Objects.isNull(start)) {
putMsg(checkResult, Status.REQUEST_PARAMS_NOT_VALID_ERROR, Constants.START_END_DATE);
return Result.error(checkResult);
}
}
Date end = null;
if (StringUtils.isNotEmpty(endDate)) {
end = DateUtils.getScheduleDate(endDate);
if (Objects.isNull(end)) {
putMsg(checkResult, Status.REQUEST_PARAMS_NOT_VALID_ERROR, Constants.START_END_DATE);
return Result.error(checkResult);
}
}
Integer[] projectIdArray = getProjectIdsArrays(loginUser, projectId);
Map<CommandType, Integer> normalCountCommandCounts = commandMapper.countCommandState(loginUser.getId(), start, end, projectIdArray).stream().collect(Collectors.toMap(CommandCount::getCommandType, CommandCount::getCount));
Map<CommandType, Integer> errorCommandCounts = errorCommandMapper.countCommandState(start, end, projectIdArray).stream().collect(Collectors.toMap(CommandCount::getCommandType, CommandCount::getCount));
List<CommandStateCount> list = Arrays.stream(CommandType.values()).map(commandType -> new CommandStateCount(errorCommandCounts.getOrDefault(commandType, 0), normalCountCommandCounts.getOrDefault(commandType, 0), commandType)).collect(Collectors.toList());
return Result.success(list);
} |
|
206 | String transform(){
final String specialCharactersRegex = "[^a-zA-Z0-9\\s+]";
final String inputCharacters = "abcdefghijklmnopqrstuvwxyz";
Map<Character, ArrayList<String>> letterOccurenceMap = new LinkedHashMap<Character, ArrayList<String>>();
if (input.equals("")) {
return input;
}
input = input.toLowerCase();
input = input.replaceAll(specialCharactersRegex, "");
String[] words = input.split(" ");
for (Character letter : inputCharacters.toCharArray()) {
for (String word : words) {
if (word.contains(letter.toString())) {
ArrayList<String> letterWordsList = letterOccurenceMap.get(letter);
if (letterWordsList == null) {
letterWordsList = new ArrayList<String>();
}
if (!letterWordsList.contains(word)) {
letterWordsList.add(word);
Collections.sort(letterWordsList);
}
letterOccurenceMap.put(letter, letterWordsList);
}
}
}
return buildResult(letterOccurenceMap);
} | String transform(){
Map<Character, ArrayList<String>> letterOccurrenceMap = new LinkedHashMap<Character, ArrayList<String>>();
if (input.equals("")) {
return input;
}
input = input.toLowerCase();
input = input.replaceAll(specialCharactersRegex, "");
String[] words = input.split(" ");
for (Character letter : inputCharacters.toCharArray()) {
for (String word : words) {
if (word.contains(letter.toString())) {
ArrayList<String> letterWordsList = letterOccurrenceMap.get(letter);
if (letterWordsList == null) {
letterWordsList = new ArrayList<String>();
}
if (!letterWordsList.contains(word)) {
letterWordsList.add(word);
Collections.sort(letterWordsList);
}
letterOccurrenceMap.put(letter, letterWordsList);
}
}
}
return buildResult(letterOccurrenceMap);
} |
|
207 | public Response simpleSearchWithSchemaName(@PathParam("index") final String index, @PathParam("schemaName") final String schemaName, @QueryParam("q") final String queryString, @QueryParam("f") final Integer from, @Context final UriInfo uriInfo){
final SearchResult results = dox.searchWithSchemaName(index, schemaName, queryString, 50, from);
final JsonArrayBuilder hitsBuilder = Json.createArrayBuilder();
for (final IndexView hit : results.getHits()) {
final JsonObjectBuilder hitBuilder = Json.createObjectBuilder();
final String id = hit.getDoxID().toString();
for (final Entry<String, BigDecimal> entry : hit.getNumbers()) {
hitBuilder.add(entry.getKey(), entry.getValue());
}
for (final Entry<String, String> entry : hit.getStrings()) {
hitBuilder.add(entry.getKey(), entry.getValue());
}
hitBuilder.add("_collection", hit.getCollection());
if (!hit.isMasked()) {
hitBuilder.add("_id", id);
hitBuilder.add("_url", uriInfo.getBaseUriBuilder().path(hit.getCollection()).path(id).build().toString());
}
hitsBuilder.add(hitBuilder);
}
final JsonObjectBuilder jsonBuilder = Json.createObjectBuilder().add("totalHits", results.getTotalHits()).add("hits", hitsBuilder);
if (results.getBottomDoc() != null) {
final String nextPage = uriInfo.getBaseUriBuilder().path("search").path(index).queryParam("q", queryString).queryParam("f", results.getBottomDoc()).build().toASCIIString();
jsonBuilder.add("bottomDoc", results.getBottomDoc()).add("next", nextPage);
}
final JsonObject resultJson = jsonBuilder.build();
return Response.ok(resultJson).cacheControl(NO_CACHE).build();
} | public Response simpleSearchWithSchemaName(@PathParam("index") final String index, @PathParam("schemaName") final String schemaName, @QueryParam("q") final String queryString, @QueryParam("f") final Integer from, @Context final UriInfo uriInfo){
final SearchResult results = dox.searchWithSchemaName(index, schemaName, queryString, 50, from);
final JsonObjectBuilder resultBuilder = searchResultBuilder(uriInfo, results);
if (results.getBottomDoc() != null) {
final String nextPage = uriInfo.getBaseUriBuilder().path("search").path(index).path(schemaName).queryParam("q", queryString).queryParam("f", results.getBottomDoc()).build().toASCIIString();
resultBuilder.add("bottomDoc", results.getBottomDoc()).add("next", nextPage);
}
final JsonObject resultJson = resultBuilder.build();
return Response.ok(resultJson).cacheControl(NO_CACHE).build();
} |
|
208 | public void createUsers() throws IOException{
AddressBook ab = new AddressBook();
Person salvador = new Person();
salvador.setName("Salvador");
salvador.setId(ab.nextId());
ab.getPersonList().add(salvador);
launchServer(ab);
final Client CLIENT = ClientBuilder.newClient();
Person juan = new Person();
juan.setName("Juan");
int juanId = 2;
URI juanURI = URI.create("http://localhost:8282/contacts/person/" + juanId);
Person maria = new Person();
maria.setName("Maria");
int mariaId = 3;
URI mariaURI = URI.create("http://localhost:8282/contacts/person/" + mariaId);
createPerson(CLIENT, juan);
Person mariaUpdated = createPerson(CLIENT, maria);
assertEquals(maria.getName(), mariaUpdated.getName());
assertEquals(mariaId, mariaUpdated.getId());
assertEquals(mariaURI, mariaUpdated.getHref());
mariaUpdated = requestPerson(CLIENT, mariaId);
assertEquals(maria.getName(), mariaUpdated.getName());
assertEquals(mariaId, mariaUpdated.getId());
assertEquals(mariaURI, mariaUpdated.getHref());
Person initialMaria = ab.getPersonList().get(mariaId - 1);
Person newMaria = requestPerson(CLIENT, mariaId);
assertEquals(initialMaria.getId(), newMaria.getId());
assertEquals(mariaUpdated.getId(), newMaria.getId());
} | public void createUsers() throws IOException{
AddressBook ab = new AddressBook();
Person salvador = new Person();
salvador.setName("Salvador");
salvador.setId(ab.nextId());
ab.getPersonList().add(salvador);
launchServer(ab);
Person juan = new Person();
juan.setName("Juan");
int juanId = 2;
URI juanURI = URI.create("http://localhost:8282/contacts/person/" + juanId);
Person maria = new Person();
maria.setName("Maria");
int mariaId = 3;
URI mariaURI = URI.create("http://localhost:8282/contacts/person/" + mariaId);
createPerson(juan);
Person mariaUpdated = createPerson(maria);
assertEquals(maria.getName(), mariaUpdated.getName());
assertEquals(mariaId, mariaUpdated.getId());
assertEquals(mariaURI, mariaUpdated.getHref());
mariaUpdated = requestPerson(mariaId);
assertEquals(maria.getName(), mariaUpdated.getName());
assertEquals(mariaId, mariaUpdated.getId());
assertEquals(mariaURI, mariaUpdated.getHref());
Person initialMaria = ab.getPersonList().get(mariaId - 1);
Person newMaria = requestPerson(mariaId);
assertEquals(initialMaria.getId(), newMaria.getId());
assertEquals(mariaUpdated.getId(), newMaria.getId());
} |
|
209 | public boolean switchIsOperable(SwitchId switchId){
if (cacheContainsSwitch(switchId)) {
SwitchState switchState = switchPool.get(switchId).getState();
if (SwitchState.ADDED == switchState || SwitchState.ACTIVATED == switchState) {
return true;
}
}
return false;
} | public boolean switchIsOperable(SwitchId switchId){
if (cacheContainsSwitch(switchId)) {
SwitchChangeType switchState = switchPool.get(switchId).getState();
return SwitchChangeType.ADDED == switchState || SwitchChangeType.ACTIVATED == switchState;
}
return false;
} |
|
210 | public static void startGame(Scanner sc){
Player player = new Player();
boolean playGame = true;
int roomID = 0;
while (playGame) {
System.out.println("You are in " + GameMap.getRooms().get(roomID).getRoomName());
System.out.println(GameMap.getRooms().get(roomID).getRoomDesc());
System.out.println("Which direction do you want to go? N S E W?");
String playerInput = sc.next();
if (playerInput.equalsIgnoreCase("n") || playerInput.equalsIgnoreCase("north")) {
String direction = GameMap.getRooms().get(roomID).getNorth();
player.map.getRoom(direction);
} else if (playerInput.equalsIgnoreCase("s") || playerInput.equalsIgnoreCase("south")) {
String direction = GameMap.getRooms().get(roomID).getSouth();
player.map.getRoom(direction);
} else if (playerInput.equalsIgnoreCase("e") || playerInput.equalsIgnoreCase("east")) {
String direction = GameMap.getRooms().get(roomID).getEast();
player.map.getRoom(direction);
} else if (playerInput.equalsIgnoreCase("w") || playerInput.equalsIgnoreCase("west")) {
String direction = GameMap.getRooms().get(roomID).getWest();
player.map.getRoom(direction);
} else if (playerInput.equalsIgnoreCase("quit")) {
System.out.println("Thanks for playing!");
playGame = false;
} else {
System.out.println("Invalid input, please enter a direction (N, S, E, W)");
}
GameMap.getRooms().get(roomID).setVisitedRoom(true);
roomID = Player.getPlayerLocation();
}
} | public static void startGame(Scanner sc){
Player player = new Player();
GameMap map = new GameMap();
boolean playGame = true;
int roomID = 0;
while (playGame) {
System.out.println("You are in " + GameMap.getRooms().get(roomID).getRoomName());
System.out.println(GameMap.getRooms().get(roomID).getRoomDesc());
System.out.println("Which direction do you want to go? N S E W?");
int currentRoom = 1;
System.out.println("You are in " + GameMap.getRooms().get(currentRoom).getRoomName());
System.out.println(GameMap.getRooms().get(currentRoom).getExitRooms());
while (playGame) {
String playerInput = sc.next();
if (GameMap.getRooms().get(currentRoom).getExitRooms().containsKey(playerInput)) {
currentRoom = GameMap.getRooms().get(currentRoom).getExitRooms().get(playerInput);
System.out.println("You are in room: " + GameMap.rooms.get(currentRoom).getRoomName());
System.out.println(GameMap.rooms.get(currentRoom).getRoomDesc());
} else {
System.out.println("Not a valid direction");
System.out.println(currentRoom);
}
}
}
} |
|
211 | protected void buildConditions(ContextEl _cont){
AssignedBooleanVariables res_ = (AssignedBooleanVariables) _cont.getAnalyzing().getAssignedVariables().getFinalVariables().getVal(this);
for (EntryCust<String, Assignment> e : res_.getLastFieldsOrEmpty().entryList()) {
BooleanAssignment ba_ = e.getValue().toBoolAssign().copy();
res_.getFieldsRootAfter().put(e.getKey(), ba_);
}
for (StringMap<Assignment> s : res_.getLastVariablesOrEmpty()) {
StringMap<BooleanAssignment> sm_;
sm_ = new StringMap<BooleanAssignment>();
for (EntryCust<String, Assignment> e : s.entryList()) {
BooleanAssignment ba_ = e.getValue().toBoolAssign().copy();
sm_.put(e.getKey(), ba_);
}
res_.getVariablesRootAfter().add(sm_);
}
for (StringMap<Assignment> s : res_.getLastMutableLoopOrEmpty()) {
StringMap<BooleanAssignment> sm_;
sm_ = new StringMap<BooleanAssignment>();
for (EntryCust<String, Assignment> e : s.entryList()) {
BooleanAssignment ba_ = e.getValue().toBoolAssign().copy();
sm_.put(e.getKey(), ba_);
}
res_.getMutableLoopRootAfter().add(sm_);
}
} | protected void buildConditions(ContextEl _cont){
AssignedBooleanVariables res_ = (AssignedBooleanVariables) _cont.getAnalyzing().getAssignedVariables().getFinalVariables().getVal(this);
res_.getFieldsRootAfter().putAllMap(AssignmentsUtil.toBoolAssign(res_.getLastFieldsOrEmpty()));
res_.getVariablesRootAfter().addAllElts(AssignmentsUtil.toBoolAssign(res_.getLastVariablesOrEmpty()));
res_.getMutableLoopRootAfter().addAllElts(AssignmentsUtil.toBoolAssign(res_.getLastMutableLoopOrEmpty()));
} |
|
212 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ArrayList<String> forecasts = new ArrayList<>();
forecasts.add(0, "Today β Sunny β 88 / 63");
forecasts.add(1, "Tomorrow β Foggy β 70 / 46");
forecasts.add(2, "Weds β Cloudy β 72 / 63");
forecasts.add(3, "Thurs β Rainy β 64 / 51");
forecasts.add(4, "Fri β Foggy β 70 / 46");
forecasts.add(5, "Sat β Sunny β 76 / 88");
forecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, forecasts);
ListView lv = (ListView) rootView.findViewById(R.id.listview_forecast);
lv.setAdapter(forecastAdapter);
FetchWeatherTask weatherTask = new FetchWeatherTask("44203");
weatherTask.execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detailActivityIntent = new Intent(getActivity(), DetailActivity.class);
detailActivityIntent.putExtra(INTENT_KEY, forecastAdapter.getItem(position));
startActivity(detailActivityIntent);
}
});
return rootView;
} | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ArrayList<String> forecasts = new ArrayList<>();
forecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, forecasts);
ListView lv = (ListView) rootView.findViewById(R.id.listview_forecast);
lv.setAdapter(forecastAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detailActivityIntent = new Intent(getActivity(), DetailActivity.class);
detailActivityIntent.putExtra(INTENT_KEY, forecastAdapter.getItem(position));
startActivity(detailActivityIntent);
}
});
return rootView;
} |
|
213 | public boolean checkLoginExistInDB(String login) throws LoginExistException{
boolean isLoginExists = UserDB.Request.Create.checkLoginExist(login);
if (isLoginExists) {
throw new LoginExistException();
}
return false;
} | public boolean checkLoginExistInDB(String login){
return UserDB.Request.checkLoginExist(login);
} |
|
214 | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
mBucketItems = new ArrayList<>();
fab = findViewById(R.id.fab);
mListView = findViewById(R.id.listView);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("users").child(user.getUid());
mListAdapter = new ListAdapter(this, mBucketItems, myRef);
mListView.setAdapter(mListAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(ListActivity.this, i + "", Toast.LENGTH_SHORT).show();
}
});
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
getBucketList(dataSnapshot);
mListAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ListActivity.this, AddItemActivity.class);
startActivity(intent);
}
});
} | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
mBucketItems = new ArrayList<>();
fab = findViewById(R.id.fab);
mListView = findViewById(R.id.listView);
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("users").child(user.getUid());
mListAdapter = new ListAdapter(this, mBucketItems, myRef);
mListView.setAdapter(mListAdapter);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
getBucketList(dataSnapshot);
mListAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(ListActivity.this, AddItemActivity.class);
startActivity(intent);
}
});
} |
|
215 | public static StandardResponse<User> loginUser(Request request, Response response, Datastore datastore){
var map = new Gson().fromJson(request.body(), Map.class);
String password = (String) map.get("password");
String username = (String) map.get("username");
User user = datastore.find(User.class).filter(and(eq("username", username), eq("active", true))).first();
boolean verified = user != null && user.verifyPassword(password).verified;
String message;
String status;
if (verified) {
List<String> tokens = user.getIssuedTokens();
String token;
if (tokens == null || tokens.size() == 0) {
token = UserService.getToken(user);
user.setIssuedTokens(Arrays.asList(token));
datastore.save(user);
} else {
token = tokens.get(0);
}
response.header("Authorization", UserService.getAuthHeaderValue(token));
status = "success";
message = "Successfull user auth by token";
return new StandardResponse<User>(status, message, user);
} else {
status = "fail";
message = "Can not auth by current username & password";
return new StandardResponse<User>(status, message, null);
}
} | public static StandardResponse<User> loginUser(Request request, Response response, Datastore datastore){
var map = new Gson().fromJson(request.body(), Map.class);
String password = (String) map.get("password");
String username = (String) map.get("username");
User user = datastore.find(User.class).filter(and(eq("username", username), eq("active", true))).first();
boolean verified = user != null && user.verifyPassword(password).verified;
if (verified) {
List<String> tokens = user.getIssuedTokens();
String token;
if (tokens == null || tokens.size() == 0) {
token = JsonWebToken.encode(user);
user.setIssuedTokens(Arrays.asList(token));
datastore.save(user);
} else {
token = tokens.get(0);
}
response.header("Authorization", UserService.getAuthHeaderValue(token));
String status = "success";
String message = "Successfull user auth by token";
return new StandardResponse<User>(status, message, user);
} else {
String status = "fail";
String message = "Can not auth by current username & password";
return new StandardResponse<User>(status, message, null);
}
} |
|
216 | public JsonArray readNotifications(OffsetDateTime start, OffsetDateTime end){
logger.info("********************");
logger.info("ReadNotifications...");
logger.info("********************");
try {
while (!this.active) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
logger.debug(e.getMessage(), e);
}
}
Future<JsonArray> future = this.executorService.submit(new SourceNotificationsReader(start, end));
JsonArray jsonArray = future.get(10000, TimeUnit.MILLISECONDS);
return jsonArray;
} catch (InterruptedException ie) {
logger.debug(ie.getMessage(), ie);
return new JsonArray();
} catch (ExecutionException ie) {
logger.debug(ie.getMessage(), ie);
return new JsonArray();
} catch (TimeoutException te) {
logger.debug(te.getMessage(), te);
return new JsonArray();
}
} | public JsonArray readNotifications(OffsetDateTime start, OffsetDateTime end){
try {
while (!this.active) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
logger.debug(e.getMessage(), e);
}
}
Future<JsonArray> future = this.executorService.submit(new SourceNotificationsReader(start, end));
JsonArray jsonArray = future.get(10000, TimeUnit.MILLISECONDS);
return jsonArray;
} catch (InterruptedException ie) {
logger.debug(ie.getMessage(), ie);
return new JsonArray();
} catch (ExecutionException ie) {
logger.debug(ie.getMessage(), ie);
return new JsonArray();
} catch (TimeoutException te) {
logger.debug(te.getMessage(), te);
return new JsonArray();
}
} |
|
217 | void writeBranching(String command, String label){
if (AssemblyCommand.LABEL.equals(command)) {
aw.addLabel(label);
} else if (AssemblyCommand.GOTO.equals(command)) {
aw.jumpTo(label);
} else if (AssemblyCommand.IF_GOTO.equals(command)) {
aw.pop();
aw.add("D=M");
aw.select(label);
aw.add("D;JNE");
}
} | void writeBranching(String command, String label){
if (AssemblyCommand.LABEL.equals(command)) {
aw.addLabel(label);
} else if (AssemblyCommand.GOTO.equals(command)) {
aw.jumpTo(label);
} else if (AssemblyCommand.IF_GOTO.equals(command)) {
aw.conditionallyJumpTo(label);
}
} |
|
218 | public StringBuffer getRequestURL(){
StringBuffer url = new StringBuffer();
String scheme = getScheme();
int port = getServerPort();
if (port < 0)
port = 80;
url.append(scheme);
url.append("://");
url.append(getServerName());
if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) {
url.append(':');
url.append(port);
}
url.append(getRequestURI());
return (url);
} | public StringBuffer getRequestURL(){
return RequestUtil.getRequestURL(this);
} |
|
219 | public List<Requirement> loadByCarrierIdAndStatus(@PathVariable(value = "carrierId") long carrierId, @PathVariable(value = "status") int status){
List<RequirementData> requirementList = requirementService.getByCarrierIdAndStatus(carrierId, status);
List<Requirement> requirements = new ArrayList<Requirement>();
for (RequirementData requirement : requirementList) {
Requirement tempRequirement = new Requirement();
tempRequirement.setStartDate(requirement.getStartDate());
tempRequirement.setEndDate(requirement.getEndDate());
tempRequirement.setCapacityWeight(requirement.getCapacityWeight());
tempRequirement.setVehicleType(requirement.getVehicleTypeName());
requirements.add(tempRequirement);
}
return requirements;
} | public List<Requirement> loadByCarrierIdAndStatus(@PathVariable(value = "carrierId") long carrierId, @PathVariable(value = "status") int status){
return requirementService.getByCarrierIdAndStatus(carrierId, status);
} |
|
220 | public void doCheck(String productNum){
theBasket.clear();
String theAction = "";
pn = productNum.trim();
int amount = 1;
try {
if (theStock.exists(pn)) {
Product pr = theStock.getDetails(pn);
if (pr.getQuantity() >= amount) {
theAction = String.format("%s : %7.2f (%2d) ", pr.getDescription(), pr.getPrice(), pr.getQuantity());
pr.setQuantity(amount);
theBasket.add(pr);
thePic = theStock.getImage(pn);
} else {
theAction = pr.getDescription() + " not in stock";
}
} else {
theAction = "Unknown product number " + pn;
}
} catch (StockException e) {
DEBUG.error("CustomerClient.doCheck()\n%s", e.getMessage());
}
setChanged();
notifyObservers(theAction);
} | public void doCheck(String productNum){
theBasket.clear();
String theAction = "";
pn = productNum.trim();
int amount = 1;
try {
if (theStock.exists(pn)) {
Product pr = theStock.getDetails(pn);
if (pr.getQuantity() >= amount) {
theAction = String.format("%s : %7.2f (%2d) ", pr.getDescription(), pr.getPrice(), pr.getQuantity());
pr.setQuantity(amount);
theBasket.add(pr);
thePic = theStock.getImage(pn);
} else {
theAction = pr.getDescription() + " not in stock";
}
} else {
theAction = "Unknown product number " + pn;
}
} catch (StockException e) {
DEBUG.error("CustomerClient.doCheck()\n%s", e.getMessage());
}
subscriber.onNext(theAction);
} |
|
221 | public void add(IDT id, T obj, Object source){
if (obj == null) {
throw new IllegalArgumentException("Object to add may not be null");
}
Map<T, Set<Object>> map = getConstructingCachedMap(id);
Set<Object> set = map.get(obj);
boolean fireNew = (set == null);
if (fireNew) {
set = new WrappedMapSet<>(IdentityHashMap.class);
map.put(obj, set);
}
set.add(source);
if (fireNew) {
fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_ADDED);
}
} | public void add(IDT id, T obj, Object source){
Objects.requireNonNull(obj);
Map<T, Set<Object>> map = getConstructingCachedMap(id);
Set<Object> set = map.get(obj);
boolean fireNew = (set == null);
if (fireNew) {
set = new WrappedMapSet<>(IdentityHashMap.class);
map.put(obj, set);
}
set.add(source);
if (fireNew) {
fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_ADDED);
}
} |
|
222 | public static void Tooltip(final Variables variables){
variables.view.setVertexToolTipTransformer(new ToStringLabeller() {
@Override
public String transform(Object v) {
if (v instanceof Graph) {
return "<html>" + GraphTooltip(v) + "</html>";
}
((Vertex) v).setTimeScalePrint(variables.config.timeScale, variables.selectedTimeScale);
return "<html>" + v.toString() + "</html>";
}
});
variables.view.setEdgeToolTipTransformer(new Transformer<Edge, String>() {
@Override
public String transform(Edge n) {
return "<html><font size=\"4\">" + n.getEdgeTooltip() + "</html>";
}
});
} | public static void Tooltip(final Variables variables){
variables.view.setVertexToolTipTransformer(new ToStringLabeller() {
@Override
public String transform(Object v) {
((Vertex) v).setTimeScalePrint(variables.config.timeScale, variables.selectedTimeScale);
return "<html>" + v.toString() + "</html>";
}
});
variables.view.setEdgeToolTipTransformer(new Transformer<Edge, String>() {
@Override
public String transform(Edge n) {
return "<html><font size=\"4\">" + n.getEdgeTooltip() + "</html>";
}
});
} |
|
223 | private boolean initializeRobot(){
boolean robotCheck = false;
int[] values = null;
Character direction = null;
if (!this.running) {
return false;
}
while (!robotCheck) {
System.out.println("Submit robot starting position and direction. " + "Enter two numbers and a direction (i.e. 5 5 N). " + "Separate values with a space.");
String[] lines = new String[0];
try {
lines = this.br.readLine().trim().split("\\s+");
} catch (IOException e) {
e.printStackTrace();
}
if (lines[0].equals("quit"))
return false;
if (lines.length == 3) {
values = convertInputToIntArray(lines);
} else {
System.out.println("Incorrect number of values.");
}
if (lines[2].length() == 1 && Direction.getDirectionFromChar(lines[2].charAt(0)) != null) {
direction = lines[2].charAt(0);
} else {
System.out.println("Incorrect direction. Try one of the following: N, E, S or W.");
}
if (values != null && direction != null && isValidPosition(values)) {
robot = new Robot(values[0], values[1], Direction.getDirectionFromChar(direction));
robotCheck = true;
} else if (testMode) {
return false;
}
}
return true;
} | private boolean initializeRobot(){
boolean robotCheck = false;
int[] values = null;
Character direction = null;
if (!this.running) {
return false;
}
while (!robotCheck) {
System.out.println("\nSubmit robot starting position and direction. " + "Enter two numbers and a direction (i.e. 5 5 N). " + "Separate values with a space.");
String[] lines = inputLines();
if (lines[0].equals("quit"))
return false;
if (lines.length == 3) {
values = convertInputToIntArray(lines, 2);
} else {
System.out.println("Incorrect number of values.");
lines = null;
}
if (lines != null && lines[2].length() == 1 && Direction.getDirectionFromChar(lines[2].charAt(0)) != null) {
direction = lines[2].charAt(0);
} else {
System.out.println("Incorrect direction. Try one of the following: N, E, S or W.");
}
if (values != null && direction != null && isValidPosition(values)) {
robot = new Robot(values[0], values[1], Direction.getDirectionFromChar(direction));
robotCheck = true;
} else if (testMode) {
return false;
}
}
return true;
} |
|
224 | public void removeAll(CharID id, Object source){
Map<T, Set<Object>> componentMap = getCachedMap(id);
if (componentMap != null) {
List<T> removedKeys = new ArrayList<>();
for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) {
Entry<T, Set<Object>> me = it.next();
Set<Object> set = me.getValue();
if (set.remove(source) && set.isEmpty()) {
T obj = me.getKey();
it.remove();
removedKeys.add(obj);
}
}
if (componentMap.isEmpty()) {
removeCache(id);
}
for (T obj : removedKeys) {
fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED);
}
}
} | public void removeAll(CharID id, Object source){
Map<T, Set<Object>> componentMap = getCachedMap(id);
if (componentMap != null) {
Collection<T> removedKeys = new ArrayList<>();
for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) {
Entry<T, Set<Object>> me = it.next();
Set<Object> set = me.getValue();
if (set.remove(source) && set.isEmpty()) {
T obj = me.getKey();
it.remove();
removedKeys.add(obj);
}
}
if (componentMap.isEmpty()) {
removeCache(id);
}
removedKeys.forEach(obj -> fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED));
}
} |
|
225 | public static void buildFilesBodies(StringMap<String> _files, boolean _predefined, AnalyzedPageEl _page){
for (EntryCust<String, String> f : _files.entryList()) {
String file_ = f.getKey();
String content_ = f.getValue();
FileBlock fileBlock_ = new FileBlock(new OffsetsBlock(), _predefined);
fileBlock_.setFileName(file_);
fileBlock_.setNumberFile(_page.getFilesBodies().size());
_page.putFileBlock(file_, fileBlock_);
fileBlock_.processLinesTabsWithError(content_, _page);
}
} | public static void buildFilesBodies(StringMap<String> _files, boolean _predefined, AnalyzedPageEl _page){
for (EntryCust<String, String> f : _files.entryList()) {
String file_ = f.getKey();
String content_ = f.getValue();
FileBlock fileBlock_ = new FileBlock(new OffsetsBlock(), _predefined, file_);
fileBlock_.setNumberFile(_page.getFilesBodies().size());
_page.putFileBlock(file_, fileBlock_);
fileBlock_.processLinesTabsWithError(content_, _page);
}
} |
|
226 | private static String[] getArgsArray(Map<String, String> props){
String[] args = FluentIterable.from(props.entrySet()).transform(new Function<Entry<String, String>, String>() {
@Override
public String apply(Entry<String, String> input) {
return "--" + input.getKey() + "=" + input.getValue();
}
}).toArray(String.class);
return args;
} | private static String[] getArgsArray(Map<String, String> props){
String[] args = props.entrySet().stream().map(input -> "--" + input.getKey() + "=" + input.getValue()).toArray(String[]::new);
return args;
} |
|
227 | private void onDataLoadComplete(){
Log.d(TAG, "onDataLoadComplete()");
mProgressBar.setVisibility(View.INVISIBLE);
mPopularMoviesAdaptor = new PopularMoviesAdaptor(getNumberOfItems(), this);
mMoviePostersRecyclerView.setAdapter(mPopularMoviesAdaptor);
} | private void onDataLoadComplete(){
Log.d(TAG, "onDataLoadComplete()");
mProgressBar.setVisibility(View.INVISIBLE);
mMoviePostersRecyclerView.setAdapter(new PopularMoviesAdaptor(getNumberOfItems(), this));
} |
|
228 | private Member findMember(){
Member member = JDAHelper.getMemberByID(JDAHelper.splitString(commandParameters)[1]);
if (member == null) {
member = JDAHelper.getMemberByUsername(JDAHelper.splitString(commandParameters)[1]);
if (member == null) {
member = JDAHelper.getMember(event.getMessage().getMentionedUsers().get(0));
}
}
return member;
} | private Member findMember(GuildMessageReceivedEvent event){
if (!event.getMessage().getMentionedUsers().isEmpty()) {
return JDAHelper.getMember(event.getMessage().getMentionedUsers().get(0));
}
sendMessage("Please mention a valid user");
return null;
} |
|
229 | public Task deleteTask(int i) throws DukeInputException{
Task t;
try {
t = lst.get(i);
lst.remove(i);
} catch (IndexOutOfBoundsException e) {
throw new DukeInputException(String.format("\"%d\" is an invalid number!", i - 1));
}
return t;
} | public Task deleteTask(int i) throws DukeInputException{
Task t;
try {
t = lst.remove(i);
} catch (IndexOutOfBoundsException e) {
throw new DukeInputException(String.format("\"%d\" is an invalid number!", i - 1));
}
return t;
} |
|
230 | public void AddNoiseLevelTest(){
try {
Scope.enter();
final Frame fr = new TestFrameBuilder().withColNames("ColA", "ColB", "ColC").withVecTypes(Vec.T_NUM, Vec.T_NUM, Vec.T_NUM).withDataForCol(0, ard(1, 2, 3)).withDataForCol(1, ard(1, 2, 3)).withDataForCol(2, ard(1, 2, 3)).build();
Scope.track(fr);
double noiseLevel = 1e-2;
String[] teColumns = { "" };
TargetEncoder tec = new TargetEncoder(teColumns);
tec.addNoise(fr, "ColA", noiseLevel, 1234);
tec.addNoise(fr, "ColB", noiseLevel, 5678);
tec.addNoise(fr, "ColC", noiseLevel, 1234);
Vec expected = vec(1, 2, 3);
assertVecEquals(expected, fr.vec(0), 1e-2);
try {
assertVecEquals(fr.vec(0), fr.vec(1), 0.0);
fail();
} catch (AssertionError ex) {
}
assertVecEquals(fr.vec(0), fr.vec(2), 0.0);
} finally {
Scope.exit();
}
} | public void AddNoiseLevelTest(){
try {
Scope.enter();
final Frame fr = new TestFrameBuilder().withColNames("ColA", "ColB", "ColC").withVecTypes(Vec.T_NUM, Vec.T_NUM, Vec.T_NUM).withDataForCol(0, ard(1, 2, 3)).withDataForCol(1, ard(1, 2, 3)).withDataForCol(2, ard(1, 2, 3)).build();
double noiseLevel = 1e-2;
String[] teColumns = { "" };
TargetEncoder tec = new TargetEncoder(teColumns);
tec.addNoise(fr, "ColA", noiseLevel, 1234);
tec.addNoise(fr, "ColB", noiseLevel, 5678);
tec.addNoise(fr, "ColC", noiseLevel, 1234);
Vec expected = vec(1, 2, 3);
assertVecEquals(expected, fr.vec(0), 1e-2);
try {
assertVecEquals(fr.vec(0), fr.vec(1), 0.0);
fail();
} catch (AssertionError ex) {
}
assertVecEquals(fr.vec(0), fr.vec(2), 0.0);
} finally {
Scope.exit();
}
} |
|
231 | private static void processLeftIndexer(VariablesOffsets _vars, String _currentFileName, int _sum, OperationNode _val, CustList<PartOffset> _parts){
if (_val instanceof ArrOperation) {
ArrOperation par_ = (ArrOperation) _val;
ClassMethodId classMethodId_ = par_.getCallFctContent().getClassMethodId();
if (classMethodId_ != null) {
AnaTypeFct function_;
if (par_.getArrContent().isVariable()) {
function_ = par_.getFunctionSet();
} else {
function_ = par_.getFunctionGet();
}
int offsetEnd_ = _sum + _val.getIndexInEl();
addParts(_vars, _currentFileName, function_, offsetEnd_, 1, _val.getErrs(), _val.getErrs(), _parts);
} else if (!_val.getErrs().isEmpty()) {
int i_ = _sum + _val.getIndexInEl();
_parts.add(new PartOffset("<a title=\"" + LinkageUtil.transform(StringUtil.join(_val.getErrs(), "\n\n")) + "\" class=\"e\">", i_));
_parts.add(new PartOffset("</a>", i_ + 1));
}
}
} | private static void processLeftIndexer(VariablesOffsets _vars, String _currentFileName, int _sum, OperationNode _val, CustList<PartOffset> _parts){
if (_val instanceof ArrOperation) {
ArrOperation par_ = (ArrOperation) _val;
AnaTypeFct function_;
if (par_.getArrContent().isVariable()) {
function_ = par_.getFunctionSet();
} else {
function_ = par_.getFunctionGet();
}
if (function_ != null) {
int offsetEnd_ = _sum + _val.getIndexInEl();
addParts(_vars, _currentFileName, function_, offsetEnd_, 1, _val.getErrs(), _val.getErrs(), _parts);
} else if (!_val.getErrs().isEmpty()) {
int i_ = _sum + _val.getIndexInEl();
_parts.add(new PartOffset("<a title=\"" + LinkageUtil.transform(StringUtil.join(_val.getErrs(), "\n\n")) + "\" class=\"e\">", i_));
_parts.add(new PartOffset("</a>", i_ + 1));
}
}
} |
|
232 | private FieldSpec buildSpec(DataGeneratorSpec genSpec, String column){
DataType dataType = genSpec.getDataTypesMap().get(column);
FieldType fieldType = genSpec.getFieldTypesMap().get(column);
FieldSpec spec;
switch(fieldType) {
case DIMENSION:
spec = new DimensionFieldSpec();
break;
case METRIC:
spec = new MetricFieldSpec();
break;
case TIME:
spec = new TimeFieldSpec(column, dataType, genSpec.getTimeUnitMap().get(column));
break;
default:
throw new RuntimeException("Invalid Field type.");
}
spec.setDataType(dataType);
spec.setFieldType(fieldType);
spec.setName(column);
spec.setSingleValueField(true);
return spec;
} | private FieldSpec buildSpec(DataGeneratorSpec genSpec, String column){
DataType dataType = genSpec.getDataTypesMap().get(column);
FieldType fieldType = genSpec.getFieldTypesMap().get(column);
FieldSpec spec;
switch(fieldType) {
case DIMENSION:
spec = new DimensionFieldSpec();
break;
case METRIC:
spec = new MetricFieldSpec();
break;
case TIME:
spec = new TimeFieldSpec(column, dataType, genSpec.getTimeUnitMap().get(column));
break;
default:
throw new RuntimeException("Invalid Field type.");
}
spec.setName(column);
spec.setDataType(dataType);
spec.setSingleValueField(true);
return spec;
} |
|
233 | public void createNewUserAndDelete() throws Exception{
UserDTO newUser = new UserDTO(organizacionAdmin);
newUser.setId(null);
newUser.setUsername(NEW_USER_USERNAME);
String uri = mvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(asJsonString(newUser)).with(SecurityMockMvcRequestPostProcessors.user(SITMUN_ADMIN_USERNAME))).andExpect(status().isCreated()).andReturn().getResponse().getHeader("Location");
assertThat(uri).isNotNull();
mvc.perform(get(uri).with(SecurityMockMvcRequestPostProcessors.user(SITMUN_ADMIN_USERNAME))).andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON)).andExpect(jsonPath("$.username", equalTo(NEW_USER_USERNAME)));
mvc.perform(delete(uri).with(SecurityMockMvcRequestPostProcessors.user(SITMUN_ADMIN_USERNAME))).andExpect(status().isNoContent());
} | public void createNewUserAndDelete() throws Exception{
User newUser = organizacionAdmin.toBuilder().id(null).username(NEW_USER_USERNAME).build();
String uri = mvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(asJsonString(newUser)).with(SecurityMockMvcRequestPostProcessors.user(SITMUN_ADMIN_USERNAME))).andExpect(status().isCreated()).andReturn().getResponse().getHeader("Location");
assertThat(uri).isNotNull();
mvc.perform(get(uri).with(SecurityMockMvcRequestPostProcessors.user(SITMUN_ADMIN_USERNAME))).andExpect(status().isOk()).andExpect(content().contentType(MediaTypes.HAL_JSON)).andExpect(jsonPath("$.username", equalTo(NEW_USER_USERNAME)));
mvc.perform(delete(uri).with(SecurityMockMvcRequestPostProcessors.user(SITMUN_ADMIN_USERNAME))).andExpect(status().isNoContent());
} |
|
234 | public void delete() throws Exception{
underTest.delete("123");
;
} | public void delete() throws Exception{
underTest.delete("123");
} |
|
235 | public Move evaluate(Maze pMaze){
if (pMaze.isWallNorth()) {
return Move.WEST;
} else {
if ((pMaze.isWallSouthEast() || pMaze.isWallSouth())) {
if (pMaze.isWallEast()) {
return Move.NORTH;
} else {
return Move.EAST;
}
} else {
if (pMaze.isWallNorthEast()) {
if (pMaze.isWallNorth()) {
return Move.WEST;
} else {
return Move.NORTH;
}
} else {
if (pMaze.isWallNorth()) {
if (pMaze.isWallNorth()) {
return Move.EAST;
} else {
return Move.WEST;
}
} else {
if ((pMaze.isWallSouth() || pMaze.isWallSouth())) {
if (pMaze.isWallNorthEast()) {
return Move.NORTH;
} else {
return Move.SOUTH;
}
} else {
return Move.SOUTH;
}
}
}
}
}
} | public Move evaluate(Maze pMaze){
return null;
} |
|
236 | public void getRemoteImage(final BodyPosition position){
final PostImage postImage = new PostImage();
postImage.ObjectID = position.Content.ImageID;
final SharedPreferences.Editor editor = preferences.edit();
String Image = preferences.getString(position.Content.ImageID, "");
if (Image != null && !Image.equals("")) {
position.Content.Image = preferences.getString(position.Content.ImageID, "");
onSuccess();
} else {
NetworkService.getInstance().getApi().getImage(postImage).enqueue(new Callback<PostImageRequestResult>() {
@Override
public void onResponse(@NonNull Call<PostImageRequestResult> call, @NonNull Response<PostImageRequestResult> response) {
PostImageRequestResult post = response.body();
if (post != null) {
position.Content.Image = post.Body.ImageData;
editor.putString(position.Content.ImageID, post.Body.ImageData);
editor.apply();
onSuccess();
} else {
Log.d(TAG, getString(R.string.no_image_text) + position.Content.Title);
}
}
@Override
public void onFailure(@NonNull Call<PostImageRequestResult> call, @NonNull Throwable t) {
Log.d(TAG, getString(R.string.no_image_text) + position.Content.Title);
Log.d(TAG, "Error occurred while getting request!" + t.toString());
}
});
}
} | private void getRemoteImage(final BodyPosition position){
final PostImage postImage = new PostImage(position.getContent().getImageID());
final SharedPreferences.Editor editor = preferences.edit();
String ImageData = preferences.getString(position.getContent().getImageID(), "");
if (ImageData != null && !ImageData.equals("")) {
position.getContent().setImage(preferences.getString(position.getContent().getImageID(), ""));
onSuccess();
} else {
NetworkService.getInstance().getApi().getImage(postImage).enqueue(new Callback<PostImageRequestResult>() {
@Override
public void onResponse(@NonNull Call<PostImageRequestResult> call, @NonNull Response<PostImageRequestResult> response) {
PostImageRequestResult post = response.body();
if (post != null) {
position.getContent().setImage(post.getBody().getImageData());
editor.putString(position.getContent().getImageID(), post.getBody().getImageData());
editor.apply();
onSuccess();
} else {
Log.d(TAG, getString(R.string.no_image_text) + position.getContent().getTitle());
}
}
@Override
public void onFailure(@NonNull Call<PostImageRequestResult> call, @NonNull Throwable t) {
Log.d(TAG, getString(R.string.no_image_text) + position.getContent().getTitle());
Log.d(TAG, "Error occurred while getting request!" + t.toString());
}
});
}
} |
|
237 | public Boolean getMapFiles(String s){
Boolean mapAvailable = false;
File folder = new File(s);
File[] listOfFiles = null;
if (folder.exists()) {
listOfFiles = folder.listFiles();
}
if (listOfFiles != null) {
mapAvailable = true;
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].toString().endsWith(".map")) {
files.add(listOfFiles[i].getName().substring(0, listOfFiles[i].getName().length() - 4));
}
}
}
return mapAvailable;
} | public ArrayList<String> getMapFiles(String folderPath){
ArrayList<String> files = new ArrayList<String>();
File folder = new File(folderPath);
File[] listOfFiles = null;
if (folder.exists()) {
listOfFiles = folder.listFiles();
}
if (listOfFiles != null) {
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile() && listOfFiles[i].toString().endsWith(".map")) {
files.add(listOfFiles[i].getName().substring(0, listOfFiles[i].getName().length() - 4));
}
}
}
return files;
} |
|
238 | public void testZSession_Jdbc_Submit() throws Exception{
Map<String, String> intpProperties = new HashMap<>();
intpProperties.put("default.driver", "com.mysql.jdbc.Driver");
intpProperties.put("default.url", "jdbc:mysql://localhost:3306/");
intpProperties.put("default.user", "root");
intpProperties.put("default.password", "123456");
ZSession session = ZSession.builder().setClientConfig(clientConfig).setInterpreter("jdbc").setIntpProperties(intpProperties).build();
try {
session.start();
assertNull(session.getWeburl());
assertNotNull(session.getNoteId());
ExecuteResult result = session.submit("show databases");
result = session.waitUntilFinished(result.getStatementId());
assertEquals(result.toString(), Status.FINISHED, result.getStatus());
assertEquals(1, result.getResults().size());
assertEquals("TABLE", result.getResults().get(0).getType());
assertTrue(result.getResults().get(0).getData(), result.getResults().get(0).getData().contains("Database"));
result = session.submit("SELECT 1 as c1, 2 as c2");
result = session.waitUntilFinished(result.getStatementId());
assertEquals(result.toString(), Status.FINISHED, result.getStatus());
assertEquals(1, result.getResults().size());
assertEquals("TABLE", result.getResults().get(0).getType());
assertEquals("c1\tc2\n1\t2\n", result.getResults().get(0).getData());
} finally {
session.stop();
}
} | public void testZSession_Jdbc_Submit() throws Exception{
Map<String, String> intpProperties = new HashMap<>();
intpProperties.put("default.driver", "com.mysql.jdbc.Driver");
intpProperties.put("default.url", "jdbc:mysql://localhost:3306/");
intpProperties.put("default.user", "root");
ZSession session = ZSession.builder().setClientConfig(clientConfig).setInterpreter("jdbc").setIntpProperties(intpProperties).build();
try {
session.start();
assertEquals("", session.getWeburl());
assertNotNull(session.getNoteId());
ExecuteResult result = session.submit("show databases");
result = session.waitUntilFinished(result.getStatementId());
assertEquals(result.toString(), Status.FINISHED, result.getStatus());
assertEquals(1, result.getResults().size());
assertEquals("TABLE", result.getResults().get(0).getType());
assertTrue(result.getResults().get(0).getData(), result.getResults().get(0).getData().contains("Database"));
result = session.submit("SELECT 1 as c1, 2 as c2");
result = session.waitUntilFinished(result.getStatementId());
assertEquals(result.toString(), Status.FINISHED, result.getStatus());
assertEquals(1, result.getResults().size());
assertEquals("TABLE", result.getResults().get(0).getType());
assertEquals("c1\tc2\n1\t2\n", result.getResults().get(0).getData());
} finally {
session.stop();
}
} |
|
239 | private void openLine() throws LineUnavailableException{
logger.info("Entered OpenLine()!:\n");
if (sourceDataLine != null) {
AudioFormat audioFormat = audioInputStream.getFormat();
int bufferSize = (bufferSize = lineBufferSize) >= 0 ? bufferSize : sourceDataLine.getBufferSize();
currentLineBufferSize = bufferSize;
sourceDataLine.open(audioFormat, currentLineBufferSize);
if (sourceDataLine.isOpen()) {
logger.info(() -> "Open Line Buffer Size=" + bufferSize + "\n");
gainControl = sourceDataLine.isControlSupported(FloatControl.Type.MASTER_GAIN) ? (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN) : null;
panControl = sourceDataLine.isControlSupported(FloatControl.Type.PAN) ? (FloatControl) sourceDataLine.getControl(FloatControl.Type.PAN) : null;
muteControl = sourceDataLine.isControlSupported(BooleanControl.Type.MUTE) ? (BooleanControl) sourceDataLine.getControl(BooleanControl.Type.MUTE) : null;
balanceControl = sourceDataLine.isControlSupported(FloatControl.Type.BALANCE) ? (FloatControl) sourceDataLine.getControl(FloatControl.Type.BALANCE) : null;
}
}
logger.info("Exited OpenLine()!:\n");
} | private void openLine() throws LineUnavailableException{
logger.info("Entered OpenLine()!:\n");
if (sourceDataLine != null) {
AudioFormat audioFormat = audioInputStream.getFormat();
int bufferSize = (bufferSize = lineBufferSize) >= 0 ? bufferSize : sourceDataLine.getBufferSize();
currentLineBufferSize = bufferSize;
sourceDataLine.open(audioFormat, currentLineBufferSize);
if (sourceDataLine.isOpen()) {
gainControl = sourceDataLine.isControlSupported(FloatControl.Type.MASTER_GAIN) ? (FloatControl) sourceDataLine.getControl(FloatControl.Type.MASTER_GAIN) : null;
panControl = sourceDataLine.isControlSupported(FloatControl.Type.PAN) ? (FloatControl) sourceDataLine.getControl(FloatControl.Type.PAN) : null;
muteControl = sourceDataLine.isControlSupported(BooleanControl.Type.MUTE) ? (BooleanControl) sourceDataLine.getControl(BooleanControl.Type.MUTE) : null;
balanceControl = sourceDataLine.isControlSupported(FloatControl.Type.BALANCE) ? (FloatControl) sourceDataLine.getControl(FloatControl.Type.BALANCE) : null;
}
}
logger.info("Exited OpenLine()!:\n");
} |
|
240 | public Result updateUdfFunc(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int udfFuncId, @RequestParam(value = "type") UdfType type, @RequestParam(value = "funcName") String funcName, @RequestParam(value = "className") String className, @RequestParam(value = "argTypes", required = false) String argTypes, @RequestParam(value = "database", required = false) String database, @RequestParam(value = "description", required = false) String description, @RequestParam(value = "resourceId") int resourceId){
logger.info("login user {}, updateProcessInstance udf function id: {},type: {}, funcName: {},argTypes: {} ,database: {},desc: {},resourceId: {}", loginUser.getUserName(), udfFuncId, type, funcName, argTypes, database, description, resourceId);
Map<String, Object> result = udfFuncService.updateUdfFunc(udfFuncId, funcName, className, argTypes, database, description, type, resourceId);
return returnDataList(result);
} | public Result<Void> updateUdfFunc(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int udfFuncId, @RequestParam(value = "type") UdfType type, @RequestParam(value = "funcName") String funcName, @RequestParam(value = "className") String className, @RequestParam(value = "argTypes", required = false) String argTypes, @RequestParam(value = "database", required = false) String database, @RequestParam(value = "description", required = false) String description, @RequestParam(value = "resourceId") int resourceId){
logger.info("login user {}, updateProcessInstance udf function id: {},type: {}, funcName: {},argTypes: {} ,database: {},desc: {},resourceId: {}", loginUser.getUserName(), udfFuncId, type, funcName, argTypes, database, description, resourceId);
return udfFuncService.updateUdfFunc(udfFuncId, funcName, className, argTypes, database, description, type, resourceId);
} |
|
241 | public String updateUserDay(Model model, WebRequest request){
User user = userService.getUserByName(request.getUserPrincipal().getName());
int id = Integer.parseInt(request.getParameter("id"));
UserDay userDay = userDayService.getUserDayById(id);
String shift = request.getParameter("shift");
if (shift.equals("day")) {
userDay.setShift(Shift.DAY);
} else if (shift.equals("late")) {
userDay.setShift(Shift.LATE);
} else {
userDay.setShift(Shift.ANY);
}
if (request.getParameterMap().containsKey("disponibility")) {
userDay.setDisponibility(request.getParameter("disponibility").equals("1") ? true : false);
}
model.addAttribute("member", true);
try {
userDayService.updateUserDay(userDay);
model.addAttribute("userDay", userDayService.getUserDayById(id));
model.addAttribute("day", userDay.getDay());
model.addAttribute("msg", "Changes Saved!");
} catch (Exception e) {
model.addAttribute("error", e.getMessage());
}
return "member-day-manager";
} | public String updateUserDay(Model model, WebRequest request){
int id = Integer.parseInt(request.getParameter("id"));
UserDay userDay = userDayService.getUserDayById(id);
String shift = request.getParameter("shift");
if (shift.equals("day")) {
userDay.setShift(Shift.DAY);
} else if (shift.equals("late")) {
userDay.setShift(Shift.LATE);
} else {
userDay.setShift(Shift.ANY);
}
if (request.getParameterMap().containsKey("disponibility")) {
userDay.setDisponibility(request.getParameter("disponibility").equals("1") ? true : false);
}
model.addAttribute("member", true);
try {
userDayService.updateUserDay(userDay);
model.addAttribute("userDay", userDayService.getUserDayById(id));
model.addAttribute("day", userDay.getDay());
model.addAttribute("msg", "Changes Saved!");
} catch (Exception e) {
model.addAttribute("error", e.getMessage());
}
return "member-day-manager";
} |
|
242 | public User sendVerificationCode(User user){
String code = UUID.randomUUID().toString();
user.setActivationCode(code);
emailService.sendVerificationEmailTo(user);
return user;
} | public User sendVerificationCode(final User user){
user.setActivationCode(UUID.randomUUID().toString());
emailService.sendVerificationEmailTo(user);
return user;
} |
|
243 | public void createNewString(ArrayCallback callback, int count, Encoding encoding){
loadRuntime();
ByteList startingDstr = new ByteList(StandardASMCompiler.STARTING_DSTR_SIZE);
if (encoding != null) {
startingDstr.setEncoding(encoding);
}
script.getCacheCompiler().cacheByteList(this, startingDstr);
method.invokevirtual(p(ByteList.class), "dup", sig(ByteList.class));
method.ldc(StringSupport.CR_7BIT);
method.invokestatic(p(RubyString.class), "newStringShared", sig(RubyString.class, Ruby.class, ByteList.class, int.class));
for (int i = 0; i < count; i++) {
callback.nextValue(this, null, i);
if (encoding != null) {
method.invokevirtual(p(RubyString.class), "append19", sig(RubyString.class, params(IRubyObject.class)));
} else {
method.invokevirtual(p(RubyString.class), "append", sig(RubyString.class, params(IRubyObject.class)));
}
}
} | public void createNewString(ArrayCallback callback, int count, Encoding encoding){
loadRuntime();
method.ldc(StandardASMCompiler.STARTING_DSTR_FACTOR * count);
if (encoding == null) {
method.invokestatic(p(RubyString.class), "newStringLight", sig(RubyString.class, Ruby.class, int.class));
} else {
script.getCacheCompiler().cacheEncoding(this, encoding);
method.invokestatic(p(RubyString.class), "newStringLight", sig(RubyString.class, Ruby.class, int.class, Encoding.class));
}
for (int i = 0; i < count; i++) {
callback.nextValue(this, null, i);
if (encoding != null) {
method.invokevirtual(p(RubyString.class), "append19", sig(RubyString.class, params(IRubyObject.class)));
} else {
method.invokevirtual(p(RubyString.class), "append", sig(RubyString.class, params(IRubyObject.class)));
}
}
} |
|
244 | private static void processQuickEl(String _el, AnalyzedTestConfiguration _cont){
String gl_ = _cont.getArgument().getStruct().getClassName(_cont.getContext());
_cont.getAnalyzing().setGlobalType(new AnaFormattedRootBlock(_cont.getAnalyzing(), gl_));
CustList<OperationNode> all_ = getQuickAnalyzed(_el, 0, _cont, _cont.getAnalyzingDoc());
ForwardInfos.generalForward(_cont.getAnalyzing(), _cont.getForwards(), _cont.getContext());
CustList<RendDynOperationNode> out_ = getExecutableNodes(_cont, all_);
assertTrue(_cont.isEmptyErrors());
out_ = CommonRender.getReducedNodes(out_.last());
ExecClassesUtil.forwardClassesMetaInfos(_cont.getContext());
ExecClassesUtil.tryInitStaticlyTypes(_cont.getContext(), _cont.getAnalyzing().getOptions());
_cont.getContext().setExiting(new NoExiting());
calculateReuse(_cont, out_);
assertTrue(_cont.isEmptyErrors());
assertNotNull(getException(_cont));
} | private static void processQuickEl(String _el, AnalyzedTestConfiguration _cont){
String gl_ = _cont.getArgument().getStruct().getClassName(_cont.getContext());
_cont.getAnalyzing().setGlobalType(new AnaFormattedRootBlock(_cont.getAnalyzing(), gl_));
CustList<OperationNode> all_ = getQuickAnalyzed(_el, 0, _cont, _cont.getAnalyzingDoc());
ForwardInfos.generalForward(_cont.getAnalyzing(), _cont.getForwards());
CustList<RendDynOperationNode> out_ = getExecutableNodes(_cont, all_);
assertTrue(_cont.isEmptyErrors());
ExecClassesUtil.forwardClassesMetaInfos(_cont.getContext());
ExecClassesUtil.tryInitStaticlyTypes(_cont.getContext(), _cont.getOpt());
_cont.getContext().setExiting(new NoExiting());
calculateReuse(_cont, out_);
assertTrue(_cont.isEmptyErrors());
assertNotNull(getException(_cont));
} |
|
245 | public void onChange(Game game, Player player, SignChangeEvent sign){
String thirdLine = ChatColor.stripColor(sign.getLine(2));
String fourthLine = ChatColor.stripColor(sign.getLine(3));
PerkType type = PerkType.DEADSHOT_DAIQ;
type = type.getPerkType(thirdLine);
if (type == null) {
sign.setLine(0, ChatColor.RED + "" + ChatColor.BOLD + "No such");
sign.setLine(1, ChatColor.RED + "" + ChatColor.BOLD + "perk!");
sign.setLine(2, "");
sign.setLine(3, "");
} else {
int cost;
if (fourthLine.matches("[0-9]{1,5}")) {
cost = Integer.parseInt(fourthLine);
} else {
cost = 2000;
CommandUtil.sendMessageToPlayer(player, fourthLine + " is not a valid amount!");
}
sign.setLine(0, ChatColor.RED + "[Zombies]");
sign.setLine(1, ChatColor.AQUA + "Perk Machine");
sign.setLine(2, type.toString().toLowerCase());
sign.setLine(3, Integer.toString(cost));
}
} | public void onChange(Game game, Player player, SignChangeEvent sign){
String thirdLine = ChatColor.stripColor(sign.getLine(2));
String fourthLine = ChatColor.stripColor(sign.getLine(3));
PerkType type = PerkType.getPerkType(thirdLine);
if (type == null) {
sign.setLine(0, ChatColor.RED + "" + ChatColor.BOLD + "No such");
sign.setLine(1, ChatColor.RED + "" + ChatColor.BOLD + "perk!");
sign.setLine(2, "");
sign.setLine(3, "");
} else {
int cost;
if (fourthLine.matches("[0-9]{1,5}")) {
cost = Integer.parseInt(fourthLine);
} else {
cost = 2000;
CommandUtil.sendMessageToPlayer(player, fourthLine + " is not a valid amount!");
}
sign.setLine(0, ChatColor.RED + "[Zombies]");
sign.setLine(1, ChatColor.AQUA + "Perk Machine");
sign.setLine(2, type.toString().toLowerCase());
sign.setLine(3, Integer.toString(cost));
}
} |
|
246 | private void checkInstalledApps(){
BrokerPool pool = null;
DBBroker broker = null;
try {
pool = BrokerPool.getInstance();
broker = pool.get(pool.getSecurityManager().getSystemSubject());
final XQuery xquery = pool.getXQueryService();
final Sequence pkgs = xquery.execute(broker, "repo:list()", null, AccessContext.INITIALIZE);
for (final SequenceIterator i = pkgs.iterate(); i.hasNext(); ) {
final ExistRepository.Notification notification = new ExistRepository.Notification(ExistRepository.Action.INSTALL, i.nextItem().getStringValue());
Optional<ExistRepository> expathRepo = pool.getExpathRepo();
if (expathRepo.isPresent()) {
update(expathRepo.get(), notification);
utilityPanel.update(expathRepo.get(), notification);
}
expathRepo.orElseThrow(() -> new XPathException("expath repository is not available."));
}
} catch (final EXistException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
} catch (final XPathException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
} catch (final PermissionDeniedException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
} finally {
if (pool != null) {
pool.release(broker);
}
}
} | private void checkInstalledApps(){
try {
final BrokerPool pool = BrokerPool.getInstance();
try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) {
final XQuery xquery = pool.getXQueryService();
final Sequence pkgs = xquery.execute(broker, "repo:list()", null, AccessContext.INITIALIZE);
for (final SequenceIterator i = pkgs.iterate(); i.hasNext(); ) {
final ExistRepository.Notification notification = new ExistRepository.Notification(ExistRepository.Action.INSTALL, i.nextItem().getStringValue());
Optional<ExistRepository> expathRepo = pool.getExpathRepo();
if (expathRepo.isPresent()) {
update(expathRepo.get(), notification);
utilityPanel.update(expathRepo.get(), notification);
}
expathRepo.orElseThrow(() -> new XPathException("expath repository is not available."));
}
}
} catch (final EXistException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
} catch (final XPathException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
} catch (final PermissionDeniedException e) {
System.err.println("Failed to check installed packages: " + e.getMessage());
e.printStackTrace();
}
} |
|
247 | public Result list(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser){
logger.info("login user {}, query all alertGroup", loginUser.getUserName());
Map<String, Object> result = alertGroupService.queryAlertgroup();
return returnDataList(result);
} | public Result<List<AlertGroup>> list(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser){
logger.info("login user {}, query all alertGroup", loginUser.getUserName());
return alertGroupService.queryAlertgroup();
} |
|
248 | public void testProducerSession_Invalided() throws Exception{
if (!JmsConfig.jmsTestsEnabled()) {
return;
}
EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
DefinedJmsProducer producer = createProducer(new ConfiguredProduceDestination(getName()));
StandaloneProducer standaloneProducer = new StandaloneProducer(activeMqBroker.getJmsConnection(), producer);
try {
activeMqBroker.start();
start(standaloneProducer);
AdaptrisMessage msg = createMessage();
standaloneProducer.doService(msg);
assertNotNull(producer.producerSession);
stop(standaloneProducer);
assertNull(producer.producerSession);
} finally {
stop(standaloneProducer);
activeMqBroker.destroy();
}
} | public void testProducerSession_Invalided() throws Exception{
EmbeddedActiveMq activeMqBroker = new EmbeddedActiveMq();
DefinedJmsProducer producer = createProducer(new ConfiguredProduceDestination(getName()));
StandaloneProducer standaloneProducer = new StandaloneProducer(activeMqBroker.getJmsConnection(), producer);
try {
activeMqBroker.start();
start(standaloneProducer);
AdaptrisMessage msg = createMessage();
standaloneProducer.doService(msg);
assertNotNull(producer.producerSession);
stop(standaloneProducer);
assertNull(producer.producerSession);
} finally {
stop(standaloneProducer);
activeMqBroker.destroy();
}
} |
|
249 | public void beforeConnection(){
Services.registerService(IReplenishForFutureQty.class, new ReplenishForFutureQty());
Services.registerService(IInvoiceBL.class, new InvoiceBL());
Services.registerService(IInvoiceDAO.class, new InvoiceDAO());
Services.registerService(IAddonService.class, new AddonService());
Services.registerService(IBPartnerBL.class, new BPartnerBL());
Services.registerService(IBPartnerDAO.class, new BPartnerDAO());
Services.registerService(IClientOrgPA.class, new ClientOrgPA());
Services.registerService(IDatabaseBL.class, new DatabaseBL());
Services.registerService(IDBService.class, new org.adempiere.db.impl.DBService());
Services.registerService(IPackageInfoService.class, new RoutingService());
Services.registerService(IOrderBL.class, new OrderBL());
Services.registerService(IParameterBL.class, new ParameterBL());
Services.registerService(ICalendarDAO.class, new CalendarDAO());
Services.registerService(IPOService.class, new POService());
Services.registerService(IPriceListDAO.class, new PriceListDAO());
Services.registerService(IPrintPA.class, new PrintPA());
Services.registerService(IProcessEventSupport.class, new ProcessEventSupport());
Services.registerService(IProcessingService.class, ProcessingService.get());
Services.registerService(IProcessPA.class, new ProcessPA());
Services.registerService(ISweepTableBL.class, new SweepTableBL());
Services.registerService(ITablePA.class, new TablePA());
Services.registerService(IGlobalLockSystem.class, new GlobalLockSystem());
Services.registerService(IAppDictionaryBL.class, new AppDictionaryBL());
Services.registerService(ITableColumnPathBL.class, new TableColumnPathBL());
Services.registerService(IPrinterRoutingBL.class, new PrinterRoutingBL());
} | public void beforeConnection(){
Services.registerService(IReplenishForFutureQty.class, new ReplenishForFutureQty());
Services.registerService(IInvoiceBL.class, new InvoiceBL());
Services.registerService(IInvoiceDAO.class, new InvoiceDAO());
Services.registerService(IAddonService.class, new AddonService());
Services.registerService(IClientOrgPA.class, new ClientOrgPA());
Services.registerService(IDatabaseBL.class, new DatabaseBL());
Services.registerService(IDBService.class, new org.adempiere.db.impl.DBService());
Services.registerService(IPackageInfoService.class, new RoutingService());
Services.registerService(IOrderBL.class, new OrderBL());
Services.registerService(IParameterBL.class, new ParameterBL());
Services.registerService(ICalendarDAO.class, new CalendarDAO());
Services.registerService(IPOService.class, new POService());
Services.registerService(IPriceListDAO.class, new PriceListDAO());
Services.registerService(IPrintPA.class, new PrintPA());
Services.registerService(IProcessEventSupport.class, new ProcessEventSupport());
Services.registerService(IProcessingService.class, ProcessingService.get());
Services.registerService(IProcessPA.class, new ProcessPA());
Services.registerService(ISweepTableBL.class, new SweepTableBL());
Services.registerService(ITablePA.class, new TablePA());
Services.registerService(IGlobalLockSystem.class, new GlobalLockSystem());
Services.registerService(IAppDictionaryBL.class, new AppDictionaryBL());
Services.registerService(ITableColumnPathBL.class, new TableColumnPathBL());
Services.registerService(IPrinterRoutingBL.class, new PrinterRoutingBL());
} |
|
250 | public void resetTest() throws IOException, NoSuchFieldException, IllegalAccessException{
FakeBattery.deleteEV3DevFakeSystemPath();
FakeBattery.createEV3DevFakeSystemPath();
System.setProperty(EV3DevFileSystem.EV3DEV_TESTING_KEY, FakeBattery.EV3DEV_FAKE_SYSTEM_PATH);
} | public void resetTest() throws IOException{
FakeBattery.resetEV3DevInfrastructure();
System.setProperty(EV3DevFileSystem.EV3DEV_TESTING_KEY, FakeBattery.EV3DEV_FAKE_SYSTEM_PATH);
} |
|
251 | public void setStudentInfo(Scanner scanner){
LOGGER.log(Level.INFO, "Name: ");
String name = scanner.next();
setName(name);
LOGGER.log(Level.INFO, "Class: ");
while (!scanner.hasNextInt()) {
LOGGER.log(Level.WARNING, "Please provide a number :");
scanner.next();
}
setStandard(scanner.nextInt());
LOGGER.log(Level.INFO, "Roll No: ");
while (!scanner.hasNextInt()) {
LOGGER.log(Level.WARNING, "Please provide a number :");
scanner.next();
}
setRoll(scanner.nextInt());
Grade.setSubjectMarks(scanner, this);
} | public void setStudentInfo(Scanner scanner){
LOGGER.log(Level.INFO, "Name: ");
setName(scanner.next());
LOGGER.log(Level.INFO, "Class: ");
while (!scanner.hasNextInt()) {
LOGGER.log(Level.WARNING, "Please provide a number :");
scanner.next();
}
setStandard(scanner.nextInt());
LOGGER.log(Level.INFO, "Roll No: ");
while (!scanner.hasNextInt()) {
LOGGER.log(Level.WARNING, "Please provide a number :");
scanner.next();
}
setRoll(scanner.nextInt());
Grade.setSubjectMarks(scanner, this);
} |
|
252 | public int[] readIntArray(String name, int[] defVal) throws IOException{
try {
Element tmpEl;
if (name != null) {
tmpEl = findChildElement(currentElem, name);
} else {
tmpEl = currentElem;
}
if (tmpEl == null) {
return defVal;
}
String sizeString = tmpEl.getAttribute("size");
String[] strings = parseTokens(tmpEl.getAttribute("data"));
if (sizeString.length() > 0) {
int requiredSize = Integer.parseInt(sizeString);
if (strings.length != requiredSize)
throw new IOException("Wrong number of ints for '" + name + "'. size says " + requiredSize + ", data contains " + strings.length);
}
int[] tmp = new int[strings.length];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = Integer.parseInt(strings[i]);
}
return tmp;
} catch (IOException ioe) {
throw ioe;
} catch (NumberFormatException nfe) {
IOException io = new IOException(nfe.toString());
io.initCause(nfe);
throw io;
} catch (DOMException de) {
IOException io = new IOException(de.toString());
io.initCause(de);
throw io;
}
} | public int[] readIntArray(String name, int[] defVal) throws IOException{
try {
Element tmpEl;
if (name != null) {
tmpEl = findChildElement(currentElem, name);
} else {
tmpEl = currentElem;
}
if (tmpEl == null) {
return defVal;
}
String sizeString = tmpEl.getAttribute("size");
String[] strings = parseTokens(tmpEl.getAttribute("data"));
if (sizeString.length() > 0) {
int requiredSize = Integer.parseInt(sizeString);
if (strings.length != requiredSize)
throw new IOException("Wrong number of ints for '" + name + "'. size says " + requiredSize + ", data contains " + strings.length);
}
int[] tmp = new int[strings.length];
for (int i = 0; i < tmp.length; i++) {
tmp[i] = Integer.parseInt(strings[i]);
}
return tmp;
} catch (IOException ioe) {
throw ioe;
} catch (NumberFormatException | DOMException nfe) {
IOException io = new IOException(nfe.toString());
io.initCause(nfe);
throw io;
}
} |
|
253 | public Result updateTenant(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id, @RequestParam(value = "tenantCode") String tenantCode, @RequestParam(value = "queueId") int queueId, @RequestParam(value = "description", required = false) String description) throws Exception{
String userReplace = RegexUtils.escapeNRT(loginUser.getUserName());
String tenantCodeReplace = RegexUtils.escapeNRT(tenantCode);
String descReplace = RegexUtils.escapeNRT(description);
logger.info("login user {}, create tenant, tenantCode: {}, queueId: {}, desc: {}", userReplace, tenantCodeReplace, queueId, descReplace);
Map<String, Object> result = tenantService.updateTenant(loginUser, id, tenantCode, queueId, description);
return returnDataList(result);
} | public Result<Void> updateTenant(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id, @RequestParam(value = "tenantCode") String tenantCode, @RequestParam(value = "queueId") int queueId, @RequestParam(value = "description", required = false) String description) throws Exception{
String userReplace = RegexUtils.escapeNRT(loginUser.getUserName());
String tenantCodeReplace = RegexUtils.escapeNRT(tenantCode);
String descReplace = RegexUtils.escapeNRT(description);
logger.info("login user {}, create tenant, tenantCode: {}, queueId: {}, desc: {}", userReplace, tenantCodeReplace, queueId, descReplace);
return tenantService.updateTenant(loginUser, id, tenantCode, queueId, description);
} |
|
254 | public void removeAll(CharID id, Object source){
Map<T, Set<Object>> componentMap = getCachedMap(id);
if (componentMap != null) {
List<T> removedKeys = new ArrayList<>();
for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) {
Entry<T, Set<Object>> me = it.next();
Set<Object> set = me.getValue();
if (set.remove(source) && set.isEmpty()) {
T obj = me.getKey();
it.remove();
removedKeys.add(obj);
}
}
if (componentMap.isEmpty()) {
removeCache(id);
}
for (T obj : removedKeys) {
fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED);
}
}
} | public void removeAll(CharID id, Object source){
Map<T, Set<Object>> componentMap = getCachedMap(id);
if (componentMap != null) {
Collection<T> removedKeys = new ArrayList<>();
for (Iterator<Map.Entry<T, Set<Object>>> it = componentMap.entrySet().iterator(); it.hasNext(); ) {
Entry<T, Set<Object>> me = it.next();
Set<Object> set = me.getValue();
if (set.remove(source) && set.isEmpty()) {
T obj = me.getKey();
it.remove();
removedKeys.add(obj);
}
}
if (componentMap.isEmpty()) {
removeCache(id);
}
removedKeys.forEach(obj -> fireDataFacetChangeEvent(id, obj, DataFacetChangeEvent.DATA_REMOVED));
}
} |
|
255 | private long moveBackwardsToFindAlternateRoute(){
this.isGoingBackwards = true;
while (reverseNodes.isEmpty()) {
nodeToGetTo = findFirstNodeWithUnusedNeighbour();
NodeImpl currentNode;
if (!nodesAlreadyAttempted.contains(nodeToGetTo)) {
if (nodeToGetTo != 0) {
unaccessableNodes.add(nodeToGetTo);
currentNode = allNodes.get(getIndexOfLocation(state.getCurrentLocation()));
} else {
nodeToGetTo = clearAllNodes();
currentNode = allNodes.get(getIndexOfLocation(state.getCurrentLocation()));
}
nodesAlreadyAttempted.add(nodeToGetTo);
} else {
nodeToGetTo = clearAllNodes();
currentNode = allNodes.get(getIndexOfLocation(state.getCurrentLocation()));
}
List<Long> nodesToVisit = new ArrayList<>();
List<Long> nodesVisited = new ArrayList<>();
recursiveFindPathToOrb(nodeToGetTo, currentNode, nodesToVisit, nodesVisited);
}
unaccessableNodes.clear();
if (reverseNodes.size() == 0) {
isGoingBackwards = false;
}
long returnLong = reverseNodes.get(0);
reverseNodes.remove(0);
return returnLong;
} | private long moveBackwardsToFindAlternateRoute(){
this.isGoingBackwards = true;
while (reverseNodes.isEmpty()) {
nodeToGetTo = findFirstNodeWithUnusedNeighbour();
NodeImpl currentNode;
if (!nodesAlreadyAttempted.contains(nodeToGetTo)) {
if (nodeToGetTo != 0) {
currentNode = allNodes.get(getIndexOfLocation(state.getCurrentLocation()));
} else {
nodeToGetTo = clearAllNodes();
currentNode = allNodes.get(getIndexOfLocation(state.getCurrentLocation()));
}
nodesAlreadyAttempted.add(nodeToGetTo);
List<Long> nodesToVisit = new ArrayList<>();
List<Long> nodesVisited = new ArrayList<>();
getLocation = 0;
recursiveFindPathToOrb(nodeToGetTo, currentNode, nodesToVisit, nodesVisited);
}
}
unaccessableNodes.clear();
if (reverseNodes.size() == 1) {
isGoingBackwards = false;
}
long returnLong = reverseNodes.get(0);
reverseNodes.remove(0);
return returnLong;
} |
|
256 | public void getUser_RetrieveFromRemoteFail_ThenRemoteFromDB(){
userDataRepositoryImpl.getUsers("", baseLoadDataCallback);
verify(userRemoteDataSource).getUsers(anyString(), loadRemoteDataCallbackArgumentCaptor.capture());
loadRemoteDataCallbackArgumentCaptor.getValue().onFail(new OperationJSONException());
verify(userDBDataSource).getUsers(loadDBDataCallbackArgumentCaptor.capture());
loadDBDataCallbackArgumentCaptor.getValue().onSucceed(Collections.singletonList(createUser()), new OperationSuccess());
assertEquals(USER_NAME, userDataRepositoryImpl.cacheUsers.get(USER_UUID).getUserName());
assertEquals(false, userDataRepositoryImpl.cacheDirty);
} | public void getUser_RetrieveFromRemoteFail_ThenRemoteFromDB(){
when(userDBDataSource.getUsers()).thenReturn(Collections.singletonList(createUser()));
userDataRepositoryImpl.getUsers("", baseLoadDataCallback);
verify(userRemoteDataSource).getUsers(anyString(), loadRemoteDataCallbackArgumentCaptor.capture());
loadRemoteDataCallbackArgumentCaptor.getValue().onFail(new OperationJSONException());
assertEquals(USER_NAME, userDataRepositoryImpl.cacheUsers.get(USER_UUID).getUserName());
assertEquals(false, userDataRepositoryImpl.cacheDirty);
} |
|
257 | public void onClick(View v){
recoveryButton.setEnabled(false);
mail = recoveryEmail.getText().toString().trim();
String url = "https://liborgs-1139.appspot.com/users/reset-password?";
RequestQueue queue = Volley.newRequestQueue(ForgotPassActivity.this);
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
Boolean status = jObject.getBoolean("status");
if (status) {
new AlertDialog.Builder(ForgotPassActivity.this).setTitle("Account Recovery").setMessage("Please check your email for further instructions").setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
}).show();
} else {
new AlertDialog.Builder(ForgotPassActivity.this).setTitle("Account Recovery").setMessage("Please enter valid email").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(KEY_EMAIL, mail);
return params;
}
};
queue.add(request);
} | public void onClick(View v){
recoveryButton.setEnabled(false);
mail = recoveryEmail.getText().toString().trim();
RequestQueue queue = Volley.newRequestQueue(ForgotPassActivity.this);
StringRequest request = new StringRequest(Request.Method.POST, Constants.PASSWORD_RESET_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jObject = new JSONObject(response);
Boolean status = jObject.getBoolean("status");
if (status) {
AppUtils.getInstance().alertMessage(ForgotPassActivity.this, "Account Recovery,", "Please check your email for further instructions");
} else {
AppUtils.getInstance().alertMessage(ForgotPassActivity.this, "Account Recovery", "Please enter correct email");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put(Constants.KEY_EMAIL, mail);
return params;
}
};
queue.add(request);
} |
|
258 | public ConfigFile save(MultipartFile file) throws IOException{
String fileName = file.getOriginalFilename();
String filePath = storagePath + fileName;
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
ConfigFile configFile = configFileRepository.findOneByFileName(fileName);
if (configFile != null) {
} else {
configFile = new ConfigFile();
configFile.setFileName(fileName);
configFile.setFilePath(filePath);
configFile.setCreated(new Timestamp(Calendar.getInstance().getTimeInMillis()));
}
configFile.setStatus("NULL");
configFile.setModified(new Timestamp(Calendar.getInstance().getTimeInMillis()));
configFile = configFileRepository.save(configFile);
return configFile;
} | public ConfigFile save(MultipartFile file) throws IOException{
String fileName = file.getOriginalFilename();
String filePath = storagePath + fileName;
FileUtils.copyInputStreamToFile(file.getInputStream(), new File(filePath));
ConfigFile configFile = configFileRepository.findOneByFileName(fileName);
if (configFile == null) {
configFile = new ConfigFile();
configFile.setFileName(fileName);
configFile.setFilePath(filePath);
configFile.setCreated(new Timestamp(Calendar.getInstance().getTimeInMillis()));
}
configFile.setStatus("NULL");
configFile.setModified(new Timestamp(Calendar.getInstance().getTimeInMillis()));
configFile = configFileRepository.save(configFile);
return configFile;
} |
|
259 | private void performLogOperationChecks(Collection<OperationWithCompletion> operations, DurableLog durableLog){
long lastSeqNo = -1;
Iterator<Operation> logIterator = durableLog.read(-1L, operations.size() + 1, TIMEOUT).join();
verifyFirstItemIsMetadataCheckpoint(logIterator);
OperationComparer comparer = new OperationComparer(true);
for (OperationWithCompletion oc : operations) {
if (oc.completion.isCompletedExceptionally()) {
continue;
}
if (!oc.operation.canSerialize()) {
continue;
}
Operation expectedOp = oc.operation;
long currentSeqNo = oc.completion.join();
Assert.assertEquals("Operation and its corresponding Completion Future have different Sequence Numbers.", currentSeqNo, expectedOp.getSequenceNumber());
AssertExtensions.assertGreaterThan("Operations were not assigned sequential Sequence Numbers.", lastSeqNo, currentSeqNo);
lastSeqNo = currentSeqNo;
Assert.assertTrue("No more items left to read from DurableLog. Expected: " + expectedOp, logIterator.hasNext());
comparer.assertEquals("Unexpected Operation in MemoryLog.", expectedOp, logIterator.next());
}
} | private void performLogOperationChecks(Collection<OperationWithCompletion> operations, DurableLog durableLog){
long lastSeqNo = -1;
Iterator<Operation> logIterator = durableLog.read(-1L, operations.size() + 1, TIMEOUT).join();
verifyFirstItemIsMetadataCheckpoint(logIterator);
OperationComparer comparer = new OperationComparer(true);
for (OperationWithCompletion oc : operations) {
if (oc.completion.isCompletedExceptionally()) {
continue;
}
if (!oc.operation.canSerialize()) {
continue;
}
Operation expectedOp = oc.operation;
AssertExtensions.assertGreaterThan("Operations were not assigned sequential Sequence Numbers.", lastSeqNo, expectedOp.getSequenceNumber());
lastSeqNo = expectedOp.getSequenceNumber();
Assert.assertTrue("No more items left to read from DurableLog. Expected: " + expectedOp, logIterator.hasNext());
comparer.assertEquals("Unexpected Operation in MemoryLog.", expectedOp, logIterator.next());
}
} |
|
260 | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){
if (key.equals(SharedPrefsKeys.IS_RUNNING_KEY)) {
boolean isRunning = SharedPrefsManager.getInstance(this).readBoolean(SharedPrefsKeys.IS_RUNNING_KEY);
Log.d(LOG_TAG, "isRunning: " + isRunning);
if (isRunning) {
String refKey = racesRef.push().getKey();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
SharedPrefsManager.getInstance(this).saveLong(SharedPrefsKeys.RACE_CURRENT_DISTANCE_KEY, 0);
buildLocationRequest();
buildLocationCallback(refKey);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
} else {
SharedPrefsManager.getInstance(this).saveLong(SharedPrefsKeys.RACE_CURRENT_DISTANCE_KEY, 0);
buildLocationRequest();
buildLocationCallback(refKey);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
} else {
if (fusedLocationProviderClient != null) {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
fusedLocationProviderClient = null;
}
}
}
} | public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){
if (key.equals(SharedPrefsKeys.IS_RUNNING_KEY)) {
boolean isRunning = SharedPrefsManager.getInstance(this).readBoolean(SharedPrefsKeys.IS_RUNNING_KEY);
Log.d(LOG_TAG, "isRunning: " + isRunning);
if (isRunning) {
String refKey = FirebaseRefs.getRacesRef().push().getKey();
LocationRequest locationRequest;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationRequest = LocationService.buildLocationRequest();
locationCallback = LocationService.buildLocationCallback(ContainerActivity.this, refKey);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
} else {
locationRequest = LocationService.buildLocationRequest();
locationCallback = LocationService.buildLocationCallback(ContainerActivity.this, refKey);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
} else {
if (fusedLocationProviderClient != null) {
fusedLocationProviderClient.removeLocationUpdates(locationCallback);
fusedLocationProviderClient = null;
}
}
}
} |
|
261 | private List<Map<String, String>> querySource(String query, int maxResults) throws InternalErrorException, FileNotFoundException, IOException{
List<Map<String, String>> subjects = new ArrayList<>();
int index = query.indexOf("=");
int indexContains = query.indexOf("contains");
if (index != -1) {
String queryType = query.substring(0, index);
String value = query.substring(index + 1);
switch(queryType) {
case "id":
subjects = executeQueryTypeID(value, maxResults);
break;
case "email":
subjects = executeQueryTypeEmail(value, maxResults);
break;
case "group":
subjects = executeQueryTypeGroupSubjects(value, maxResults);
break;
default:
throw new IllegalArgumentException("Word before '=' symbol can be 'id' or 'email' or 'group', nothing else.");
}
} else {
if (indexContains != -1) {
String queryType = query.substring(0, indexContains).trim();
String value = query.substring(indexContains + "contains".trim().length());
if (queryType.equals("email")) {
subjects = executeQueryTypeContains(value.trim());
} else {
throw new IllegalArgumentException("Search for substrings is possible only for 'email' attribute.");
}
} else {
throw new InternalErrorException("Wrong query!");
}
}
return subjects;
} | private void querySource(String query, int maxResults, List<Map<String, String>> subjects) throws InternalErrorException, FileNotFoundException, IOException{
int index = query.indexOf("=");
int indexContains = query.indexOf("contains");
if (index != -1) {
String queryType = query.substring(0, index);
String value = query.substring(index + 1);
switch(queryType) {
case "id":
executeQueryTypeID(value, maxResults, subjects);
break;
case "email":
executeQueryTypeEmail(value, maxResults, subjects);
break;
case "group":
executeQueryTypeGroupSubjects(value, maxResults, subjects);
break;
default:
throw new IllegalArgumentException("Word before '=' symbol can be 'id' or 'email' or 'group', nothing else.");
}
} else {
if (indexContains != -1) {
String queryType = query.substring(0, indexContains).trim();
String value = query.substring(indexContains + "contains".trim().length());
if (queryType.equals("email")) {
executeQueryTypeContains(value.trim(), subjects);
} else {
throw new IllegalArgumentException("Search for substrings is possible only for 'email' attribute.");
}
} else {
throw new InternalErrorException("Wrong query!");
}
}
} |
|
262 | public void end(boolean interrupted){
shooter.stopFlywheelMotor();
shooter.stopFeederMotor();
;
shooter.stopKickupMotor();
} | public void end(boolean interrupted){
shooter.stopFlywheelMotor();
} |
|
263 | public static void setType(ScreenType screenType){
Screen screen = null;
for (Screen s : screens) {
if (s.screenType == screenType) {
screen = s;
}
}
screens.remove(screen);
screens.add(0, screen);
} | public static void setType(ScreenType screenType){
Screen screen = null;
for (Screen s : screens) if (s.screenType == screenType)
screen = s;
screens.remove(screen);
screens.add(0, screen);
} |
|
264 | private boolean isAnyGatewayProcessingGroupId(int groupId){
Utilities.log.debug(getClass().getName() + ":: isAnyGatewayProcessingGroupId(" + groupId + ")");
if (gateways != null) {
for (int i = 0; i < gateways.size(); i++) {
DummyGateway gateway = gateways.get(i);
DummyMessage msg = gateway.getLastMessageSent();
if (msg != null) {
if (msg.getGroupId() == groupId) {
Utilities.log.debug(getClass().getName() + "::!!! true for-->" + gateway);
return true;
}
}
}
} else {
Utilities.log.error(getClass().getName() + ":: Error null gateways found...");
}
Utilities.log.debug(getClass().getName() + "::!!! false for all gateways");
return false;
} | private boolean isAnyGatewayProcessingGroupId(int groupId){
Utilities.log.debug(getClass().getName() + ":: isAnyGatewayProcessingGroupId(" + groupId + ")");
if (gateways != null) {
for (final DummyGateway dummyGateway : gateways) {
final DummyMessage msg = dummyGateway.getLastMessageSent();
if (msg != null) {
if (msg.getGroupId() == groupId) {
Utilities.log.debug(getClass().getName() + "::!!! true for-->" + dummyGateway);
return true;
}
}
}
} else {
Utilities.log.error(getClass().getName() + ":: Error null gateways found...");
}
Utilities.log.debug(getClass().getName() + "::!!! false for all gateways");
return false;
} |
|
265 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_main_list, container, false);
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
getDataFromApi(recyclerView);
}
return view;
} | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_main_list, container, false);
if (view instanceof RecyclerView) {
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
getDataFromApi(recyclerView);
}
return view;
} |
|
266 | public void testChangesOnStmts() throws ParseException{
String code = "public class Bar{\n public void foo() {\n String s = null;\n names.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());\n }\n}";
DefaultJavaParser parser = new DefaultJavaParser();
CompilationUnit cu = parser.parse(code, false);
CompilationUnit cu2 = parser.parse(code, false);
MethodDeclaration md = (MethodDeclaration) cu2.getTypes().get(0).getMembers().get(0);
List<Statement> stmts = md.getBody().getStmts();
stmts.remove(0);
ChangeLogVisitor visitor = new ChangeLogVisitor();
VisitorContext ctx = new VisitorContext();
ctx.put(ChangeLogVisitor.NODE_TO_COMPARE_KEY, cu2);
visitor.visit((CompilationUnit) cu, ctx);
List<Action> actions = visitor.getActionsToApply();
Assert.assertEquals(1, actions.size());
Assert.assertEquals(ActionType.REMOVE, actions.get(0).getType());
assertCode(actions, code, "public class Bar{\n public void foo() {\n names.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());\n }\n}");
} | public void testChangesOnStmts() throws ParseException{
String code = "public class Bar{\n public void foo() {\n String s = null;\n names.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());\n }\n}";
DefaultJavaParser parser = new DefaultJavaParser();
CompilationUnit cu = parser.parse(code, false);
CompilationUnit cu2 = parser.parse(code, false);
MethodDeclaration md = (MethodDeclaration) cu2.getTypes().get(0).getMembers().get(0);
List<Statement> stmts = md.getBody().getStmts();
stmts.remove(0);
List<Action> actions = getActions(cu2, cu);
Assert.assertEquals(1, actions.size());
Assert.assertEquals(ActionType.REMOVE, actions.get(0).getType());
assertCode(actions, code, "public class Bar{\n public void foo() {\n names.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());\n }\n}");
} |
|
267 | public void onResponse(Call<RawEpisodesServerResponse> call, Response<RawEpisodesServerResponse> response){
listEpisodes = response.body();
SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("APP_DATA", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("Episodes_List", gson.toJson(listEpisodes)).apply();
RecyclerViewAdapter adapter = new RecyclerViewAdapter(Fragment_Episodes.this, listEpisodes.getResults());
rv_episodes.setLayoutManager(new GridLayoutManager(view.getContext(), 3));
rv_episodes.setAdapter(adapter);
mSwipeRefreshLayout.setRefreshing(false);
} | public void onResponse(Call<RawEpisodesServerResponse> call, Response<RawEpisodesServerResponse> response){
listEpisodes = response.body();
SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("APP_DATA", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("Episodes_List", gson.toJson(listEpisodes)).apply();
adapter.setFilter(listEpisodes.getResults());
mSwipeRefreshLayout.setRefreshing(false);
} |
|
268 | protected void setSkin(Skin skin){
if (skin == null) {
throw new IllegalArgumentException("skin is null.");
}
if (this.skin != null) {
throw new IllegalStateException("Skin is already installed.");
}
this.skin = skin;
styles = new BeanAdapter(skin);
skin.install(this);
LinkedList<Class<?>> styleTypes = new LinkedList<>();
Class<?> type = getClass();
while (type != Object.class) {
styleTypes.insert(type, 0);
type = type.getSuperclass();
}
for (Class<?> styleType : styleTypes) {
Map<String, ?> stylesLocal = typedStyles.get((Class<? extends Component>) styleType);
if (stylesLocal != null) {
setStyles(stylesLocal);
}
}
invalidate();
repaint();
} | protected void setSkin(Skin skin){
Utils.checkNull(skin, "skin");
if (this.skin != null) {
throw new IllegalStateException("Skin is already installed.");
}
this.skin = skin;
styles = new BeanAdapter(skin);
skin.install(this);
LinkedList<Class<?>> styleTypes = new LinkedList<>();
Class<?> type = getClass();
while (type != Object.class) {
styleTypes.insert(type, 0);
type = type.getSuperclass();
}
for (Class<?> styleType : styleTypes) {
Map<String, ?> stylesLocal = typedStyles.get((Class<? extends Component>) styleType);
if (stylesLocal != null) {
setStyles(stylesLocal);
}
}
invalidate();
repaint();
} |
|
269 | public void setUp(){
mMainThread = new TestMainThread();
FakeDaoModule daoModule = new FakeDaoModule();
daoModule.setSeriesDao(mSeriesDao);
daoModule.setEpisodeDao(mEpisodeDao);
FakeNetworkRepositoryModule networkRepositoryModule = new FakeNetworkRepositoryModule();
InteractorComponent component = DaggerInteractorComponent.builder().spicioAppModule(new FakeAppModule(mApp)).daoModule(daoModule).networkRepositoryModule(networkRepositoryModule).build();
when(mApp.getInteractorComponent()).thenReturn(component);
} | public void setUp(){
FakeDaoModule daoModule = new FakeDaoModule();
daoModule.setSeriesDao(mSeriesDao);
daoModule.setEpisodeDao(mEpisodeDao);
FakeNetworkRepositoryModule networkRepositoryModule = new FakeNetworkRepositoryModule();
InteractorComponent component = DaggerInteractorComponent.builder().spicioAppModule(new FakeAppModule(mApp)).daoModule(daoModule).networkRepositoryModule(networkRepositoryModule).threadingModule(new FakeThreadingModule()).build();
when(mApp.getInteractorComponent()).thenReturn(component);
} |
|
270 | protected ApiRequest pkInit(){
Wrap<Long> pkWrap = new Wrap<Long>().var("pk").o(pk);
if (pk == null) {
_pk(pkWrap);
setPk(pkWrap.o);
}
pkWrap.o(null);
return (ApiRequest) this;
} | protected ApiRequest pkInit(){
Wrap<Long> pkWrap = new Wrap<Long>().var("pk");
if (pk == null) {
_pk(pkWrap);
setPk(pkWrap.o);
}
return (ApiRequest) this;
} |
|
271 | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mDrawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawer.addDrawerListener(mToggle);
mToggle.syncState();
mToggle.setToolbarNavigationClickListener(v -> onBackPressed());
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupWithNavController(navigationView, mNavController);
NavigationUI.setupActionBarWithNavController(this, mNavController, mDrawer);
if (savedInstanceState == null) {
implementInputIntent(getIntent());
}
mMainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mMainViewModel.initDbFromNetworkFile();
mMainViewModel.getRecipes().observe(this, recipeEntities -> {
});
mMainViewModel.getConnectionErrorData().observe(this, isError -> {
if (isError) {
showConnectionErrorSnackBar();
}
});
} | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
mDrawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawer.addDrawerListener(mToggle);
mToggle.syncState();
mToggle.setToolbarNavigationClickListener(v -> onBackPressed());
mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupWithNavController(navigationView, mNavController);
NavigationUI.setupActionBarWithNavController(this, mNavController, mDrawer);
if (savedInstanceState == null) {
implementInputIntent(getIntent());
}
mMainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mMainViewModel.initDbFromNetworkFile();
mMainViewModel.getConnectionErrorData().observe(this, isError -> {
if (isError) {
showConnectionErrorSnackBar();
}
});
} |
|
272 | public ResponseEntity<Object> getDocumentBinaryContent(UUID documentId){
try {
final HttpEntity requestEntity = new HttpEntity(getHttpHeaders());
String documentBinaryUrl = String.format("%s/documents/%s/binary", documentURL, documentId);
ResponseEntity<ByteArrayResource> response = restTemplate.exchange(documentBinaryUrl, GET, requestEntity, ByteArrayResource.class);
if (HttpStatus.OK.equals(response.getStatusCode())) {
return ResponseEntity.ok().headers(getHeaders(response)).body(response.getBody());
} else {
return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
}
} catch (HttpClientErrorException exception) {
if (HttpStatus.NOT_FOUND.equals(exception.getStatusCode())) {
LOG.error(ERROR_MESSAGE, documentId.toString(), HttpStatus.NOT_FOUND);
throw new ResourceNotFoundException(documentId.toString());
} else if (HttpStatus.FORBIDDEN.equals(exception.getStatusCode())) {
LOG.error(ERROR_MESSAGE, documentId.toString(), HttpStatus.FORBIDDEN);
throw new ForbiddenException(documentId.toString());
} else if (HttpStatus.BAD_REQUEST.equals(exception.getStatusCode())) {
LOG.error(ERROR_MESSAGE, documentId.toString(), HttpStatus.BAD_REQUEST);
throw new BadRequestException(documentId.toString());
} else {
LOG.error("Exception occurred while getting the document from Document store: {}", exception.getMessage());
throw new ServiceException(String.format("Problem fetching the document for document id: %s because of %s", documentId, exception.getMessage()));
}
}
} | public ResponseEntity<Object> getDocumentBinaryContent(UUID documentId){
try {
final HttpEntity requestEntity = new HttpEntity(getHttpHeaders());
String documentBinaryUrl = String.format("%s/documents/%s/binary", documentURL, documentId);
ResponseEntity<ByteArrayResource> response = restTemplate.exchange(documentBinaryUrl, GET, requestEntity, ByteArrayResource.class);
if (HttpStatus.OK.equals(response.getStatusCode())) {
return ResponseEntity.ok().headers(getHeaders(response)).body(response.getBody());
} else {
return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
}
} catch (HttpClientErrorException exception) {
catchException(exception, documentId.toString(), EXCEPTION_ERROR_ON_DOCUMENT_MESSAGE);
}
return new ResponseEntity<>(HttpStatus.OK);
} |
|
273 | public boolean onNavigationItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.nav_sign_out) {
viewModel.clearAccessTokens();
finish();
}
drawer.closeDrawer(GravityCompat.START);
return true;
} | public boolean onNavigationItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.nav_sign_out) {
viewModel.clearAccessTokens();
}
drawer.closeDrawer(GravityCompat.START);
return true;
} |
|
274 | public Expression optimize(ExpressionVisitor visitor, ItemType contextItemType) throws XPathException{
StaticContext env = visitor.getStaticContext();
Optimizer opt = visitor.getConfiguration().getOptimizer();
if (action instanceof VariableReference && ((VariableReference) action).getBinding() == this) {
Expression e2 = visitor.optimize(sequence, contextItemType);
return e2;
}
if (sequence instanceof DocumentInstr && ((DocumentInstr) sequence).isTextOnly()) {
if (allReferencesAreFlattened()) {
sequence = ((DocumentInstr) sequence).getStringValueExpression(env);
requiredType = SequenceType.SINGLE_UNTYPED_ATOMIC;
adoptChildExpression(sequence);
}
}
if (refCount == 0) {
Expression a = visitor.optimize(action, contextItemType);
ExpressionTool.copyLocationInfo(this, a);
return a;
}
int tries = 0;
while (tries++ < 5) {
Expression seq2 = visitor.optimize(sequence, contextItemType);
if (seq2 == sequence) {
break;
}
sequence = seq2;
adoptChildExpression(sequence);
visitor.resetStaticProperties();
}
tries = 0;
while (tries++ < 5) {
Expression act2 = visitor.optimize(action, contextItemType);
if (act2 == action) {
break;
}
action = act2;
adoptChildExpression(action);
visitor.resetStaticProperties();
}
evaluationMode = ExpressionTool.lazyEvaluationMode(sequence);
return this;
} | public Expression optimize(ExpressionVisitor visitor, ItemType contextItemType) throws XPathException{
StaticContext env = visitor.getStaticContext();
if (action instanceof VariableReference && ((VariableReference) action).getBinding() == this) {
return visitor.optimize(sequence, contextItemType);
}
if (sequence instanceof DocumentInstr && ((DocumentInstr) sequence).isTextOnly()) {
if (allReferencesAreFlattened()) {
sequence = ((DocumentInstr) sequence).getStringValueExpression(env);
requiredType = SequenceType.SINGLE_UNTYPED_ATOMIC;
adoptChildExpression(sequence);
}
}
if (refCount == 0) {
Expression a = visitor.optimize(action, contextItemType);
ExpressionTool.copyLocationInfo(this, a);
return a;
}
int tries = 0;
while (tries++ < 5) {
Expression seq2 = visitor.optimize(sequence, contextItemType);
if (seq2 == sequence) {
break;
}
sequence = seq2;
adoptChildExpression(sequence);
visitor.resetStaticProperties();
}
tries = 0;
while (tries++ < 5) {
Expression act2 = visitor.optimize(action, contextItemType);
if (act2 == action) {
break;
}
action = act2;
adoptChildExpression(action);
visitor.resetStaticProperties();
}
evaluationMode = ExpressionTool.lazyEvaluationMode(sequence);
return this;
} |
|
275 | private void updateList(){
if (!listFriends.isEmpty()) {
adapter = new FriendAdapter(FriendActivity.this, R.layout.friend_list_component, listFriends);
lvFriends.setAdapter(adapter);
}
} | private void updateList(){
adapter = new FriendAdapter(FriendActivity.this, R.layout.friend_list_component, listFriends);
lvFriends.setAdapter(adapter);
} |
|
276 | private int unlockTable(UnlockTableDesc unlockTbl) throws HiveException{
Context ctx = driverContext.getCtx();
HiveTxnManager txnManager = ctx.getHiveTxnManager();
if (!txnManager.supportsExplicitLock()) {
throw new HiveException(ErrorMsg.LOCK_REQUEST_UNSUPPORTED, conf.getVar(HiveConf.ConfVars.HIVE_TXN_MANAGER));
}
HiveLockManager lockMgr = txnManager.getLockManager();
if (lockMgr == null) {
throw new HiveException("unlock Table LockManager not specified");
}
String tabName = unlockTbl.getTableName();
HiveLockObject obj = getHiveObject(tabName, unlockTbl.getPartSpec());
List<HiveLock> locks = lockMgr.getLocks(obj, false, false);
if ((locks == null) || (locks.isEmpty())) {
throw new HiveException("Table " + tabName + " is not locked ");
}
Iterator<HiveLock> locksIter = locks.iterator();
while (locksIter.hasNext()) {
HiveLock lock = locksIter.next();
lockMgr.unlock(lock);
}
return 0;
} | private int unlockTable(UnlockTableDesc unlockTbl) throws HiveException{
Context ctx = driverContext.getCtx();
HiveTxnManager txnManager = ctx.getHiveTxnManager();
return txnManager.unlockTable(db, unlockTbl);
} |
|
277 | private LiveData<Message> getResultReading(){
return Transformations.map(mResultReader, input -> {
Message message = null;
if (input.data.getFields().getCode() != AudioTagger.SUCCESS) {
if (input.data.getFields().getError().getMessage() != null)
message = new Message(input.data.getFields().getError().getMessage());
else
message = new Message(R.string.could_not_read_file);
} else {
mTrack = input.data.getTrack();
mAudioFields = input.data.getFields();
if (mCorrectionMode == Constants.CorrectionActions.SEMI_AUTOMATIC && !mTriggered) {
mTriggered = true;
startIdentification(new IdentificationParams(IdentificationParams.ALL_TAGS));
}
setEditableInfo(mAudioFields);
setNoEditableInfo(mAudioFields);
setFixedInfo(mAudioFields);
}
return message;
});
} | private LiveData<Message> getResultReading(){
return Transformations.map(mResultReader, input -> {
Message message = null;
if (input.data.getFields().getCode() != AudioTagger.SUCCESS) {
if (input.data.getFields().getError().getMessage() != null)
message = new Message(input.data.getFields().getError().getMessage());
else
message = new Message(R.string.could_not_read_file);
} else {
mTrack = input.data.getTrack();
mAudioFields = input.data.getFields();
setEditableInfo(mAudioFields);
setNoEditableInfo(mAudioFields);
setFixedInfo(mAudioFields);
}
return message;
});
} |
|
278 | public Result batchDeleteProcessInstanceByIds(@RequestAttribute(value = Constants.SESSION_USER) User loginUser, @PathVariable String projectName, @RequestParam("processInstanceIds") String processInstanceIds){
logger.info("delete process instance by ids, login user:{}, project name:{}, process instance ids :{}", loginUser.getUserName(), projectName, processInstanceIds);
Map<String, Object> result = new HashMap<>();
List<String> deleteFailedIdList = new ArrayList<>();
if (StringUtils.isNotEmpty(processInstanceIds)) {
String[] processInstanceIdArray = processInstanceIds.split(",");
for (String strProcessInstanceId : processInstanceIdArray) {
int processInstanceId = Integer.parseInt(strProcessInstanceId);
try {
Map<String, Object> deleteResult = processInstanceService.deleteProcessInstanceById(loginUser, projectName, processInstanceId);
if (!Status.SUCCESS.equals(deleteResult.get(Constants.STATUS))) {
deleteFailedIdList.add(strProcessInstanceId);
logger.error((String) deleteResult.get(Constants.MSG));
}
} catch (Exception e) {
deleteFailedIdList.add(strProcessInstanceId);
}
}
}
if (!deleteFailedIdList.isEmpty()) {
putMsg(result, Status.BATCH_DELETE_PROCESS_INSTANCE_BY_IDS_ERROR, String.join(",", deleteFailedIdList));
} else {
putMsg(result, Status.SUCCESS);
}
return returnDataList(result);
} | public Result<Void> batchDeleteProcessInstanceByIds(@RequestAttribute(value = Constants.SESSION_USER) User loginUser, @PathVariable String projectName, @RequestParam("processInstanceIds") String processInstanceIds){
logger.info("delete process instance by ids, login user:{}, project name:{}, process instance ids :{}", loginUser.getUserName(), projectName, processInstanceIds);
List<String> deleteFailedIdList = new ArrayList<>();
if (StringUtils.isNotEmpty(processInstanceIds)) {
String[] processInstanceIdArray = processInstanceIds.split(",");
for (String strProcessInstanceId : processInstanceIdArray) {
int processInstanceId = Integer.parseInt(strProcessInstanceId);
try {
Result<Void> deleteResult = processInstanceService.deleteProcessInstanceById(loginUser, projectName, processInstanceId);
if (Status.SUCCESS.getCode() != (deleteResult.getCode())) {
deleteFailedIdList.add(strProcessInstanceId);
logger.error(deleteResult.getMsg());
}
} catch (Exception e) {
deleteFailedIdList.add(strProcessInstanceId);
}
}
}
if (!deleteFailedIdList.isEmpty()) {
return Result.errorWithArgs(Status.BATCH_DELETE_PROCESS_INSTANCE_BY_IDS_ERROR, String.join(",", deleteFailedIdList));
} else {
return Result.success(null);
}
} |
|
279 | public void testMapRowTo4() throws Exception{
ColumnMapper<SampleJavaBean> mapper = mock(ColumnMapper.class);
when(mapper.classTag()).thenReturn(JavaApiHelper.getClassTag(SampleJavaBean.class));
RowReaderFactory<SampleJavaBean> rrf = mapRowTo(mapper);
assertThat(rrf, instanceOf(ClassBasedRowReaderFactory.class));
assertThat(rrf.targetClass().getName(), is(SampleJavaBean.class.getName()));
} | public void testMapRowTo4() throws Exception{
ColumnMapper<SampleJavaBean> mapper = mock(ColumnMapper.class);
RowReaderFactory<SampleJavaBean> rrf = mapRowTo(SampleJavaBean.class, mapper);
assertThat(rrf, instanceOf(ClassBasedRowReaderFactory.class));
assertThat(rrf.targetClass().getName(), is(SampleJavaBean.class.getName()));
} |
|
280 | public VPStateBuilder<ACTION> createEmptyStateBuilder(){
final VPStateBuilder<ACTION> builder = new VPStateBuilder<>(mDomain);
for (final EqGraphNode<EqNode, IProgramVarOrConst> egn : builder.getAllEqGraphNodes()) {
egn.setupNode();
}
final Set<EqNode> literalSet = mDomain.getLiteralEqNodes();
final Set<VPDomainSymmetricPair<EqNode>> disEqualitySet = new HashSet<>();
for (final EqNode node1 : literalSet) {
for (final EqNode node2 : literalSet) {
if (!node1.equals(node2)) {
disEqualitySet.add(new VPDomainSymmetricPair<>(node1, node2));
}
}
}
builder.addDisEqualites(disEqualitySet);
final Set<IProgramVarOrConst> vars = new HashSet<>();
builder.addVars(vars);
builder.setIsTop(true);
return builder;
} | public VPStateBuilder<ACTION> createEmptyStateBuilder(){
final Set<EqNode> literalSet = mDomain.getLiteralEqNodes();
final Set<VPDomainSymmetricPair<EqNode>> disEqualitySet = new HashSet<>();
for (final EqNode node1 : literalSet) {
for (final EqNode node2 : literalSet) {
if (!node1.equals(node2)) {
disEqualitySet.add(new VPDomainSymmetricPair<>(node1, node2));
}
}
}
final VPStateBuilder<ACTION> builder = new VPStateBuilder<>(mDomain, disEqualitySet);
final Set<IProgramVarOrConst> vars = new HashSet<>();
builder.addVars(vars);
builder.setIsTop(true);
return builder;
} |
|
281 | public boolean contains(User user){
synchronized (this) {
for (KonThread thread : mMap.values()) {
Set<User> threadUser = thread.getUser();
if (threadUser.size() == 1 && threadUser.contains(user))
return true;
}
}
return false;
} | public boolean contains(User user){
return this.getOrNull(user) != null;
} |
|
282 | public Result delUserById(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id) throws Exception{
logger.info("login user {}, delete user, userId: {},", loginUser.getUserName(), id);
Map<String, Object> result = usersService.deleteUserById(loginUser, id);
return returnDataList(result);
} | public Result<Void> delUserById(@ApiIgnore @RequestAttribute(value = Constants.SESSION_USER) User loginUser, @RequestParam(value = "id") int id) throws Exception{
logger.info("login user {}, delete user, userId: {},", loginUser.getUserName(), id);
return usersService.deleteUserById(loginUser, id);
} |
|
283 | private List<Map<String, String>> executeQueryTypeGroupSubjects(String value, int maxResults) throws InternalErrorException{
List<Map<String, String>> subjects = new ArrayList<>();
if (value.contains("@" + this.domainName)) {
try {
Members result = service.members().list(value).execute();
List<Member> membersInGroup = result.getMembers();
for (Member member : membersInGroup) {
Map<String, String> map = new HashMap<>();
map = processGoogleMappingAttribute(member.getId());
if (!map.isEmpty()) {
subjects.add(map);
}
if (maxResults > 0) {
if (subjects.size() >= maxResults) {
break;
}
}
}
} catch (IOException ex) {
log.error("Problem with I/O operation while accesing Google Group API in ExtSourceGoogle class.", ex);
}
} else {
throw new IllegalArgumentException("You are trying to get users from nonexistin group, please check name if your group name is something like '[email protected]'.");
}
return subjects;
} | private void executeQueryTypeGroupSubjects(String value, int maxResults, List<Map<String, String>> subjects) throws InternalErrorException{
if (value.contains("@" + this.domainName)) {
try {
Members result = service.members().list(value).execute();
List<Member> membersInGroup = result.getMembers();
for (Member member : membersInGroup) {
Map<String, String> map;
map = processGoogleMappingAttribute(member.getId());
if (!map.isEmpty()) {
subjects.add(map);
}
if (maxResults > 0) {
if (subjects.size() >= maxResults) {
break;
}
}
}
} catch (IOException ex) {
log.error("Problem with I/O operation while accesing Google Group API in ExtSourceGoogle class.", ex);
}
} else {
throw new IllegalArgumentException("You are trying to get users from nonexistin group, please check name if your group name is something like '[email protected]'.");
}
} |
|
284 | private void updateModel(){
if (this.rocketModel == null) {
ModelResourceLocation modelResourceLocation = new ModelResourceLocation(Constants.TEXTURE_PREFIX + "electric_rocket", "inventory");
this.rocketModel = (ItemModelRocketElectricRocket) MCUtilities.getClient().getRenderItem().getItemModelMesher().getModelManager().getModel(modelResourceLocation);
}
} | private void updateModel(){
if (this.rocketModel == null) {
this.rocketModel = (ItemModelRocketElectricRocket) ModelUtilities.getModelFromRegistry(Constants.TEXTURE_PREFIX, "electric_rocket");
}
} |
|
285 | private EObject getEObjectFor(String string){
EClassifier eClassifier = Ifc4Package.eINSTANCE.getEClassifier(string);
EObject eObject = null;
if (eClassifier instanceof EClass) {
eObject = EcoreUtil.create((EClass) eClassifier);
}
this.toString(eClassifier);
return eObject;
} | private EObject getEObjectFor(String string){
EClassifier eClassifier = Ifc4Package.eINSTANCE.getEClassifier(string);
EObject eObject = null;
if (eClassifier instanceof EClass) {
eObject = EcoreUtil.create((EClass) eClassifier);
}
return eObject;
} |
|
286 | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mNoteIndex = getArguments().getString(ARG_PARAM1);
mTabPosition = getArguments().getString(ARG_PARAM2);
}
} | public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mNoteIndex = getArguments().getString(ARG_NOTE_INDEX);
}
} |
|
287 | public List<Permanent> getActivePermanents(FilterPermanent filter, UUID sourcePlayerId, UUID sourceId, Game game){
if (game.getRangeOfInfluence() == RangeOfInfluence.ALL) {
return field.values().stream().filter(perm -> perm.isPhasedIn() && filter.match(perm, sourceId, sourcePlayerId, game)).collect(Collectors.toList());
} else {
Player player = game.getPlayer(sourcePlayerId);
if (player == null) {
return Collections.emptyList();
}
Set<UUID> range = player.getInRange();
return field.values().stream().filter(perm -> perm.isPhasedIn() && range.contains(perm.getControllerId()) && filter.match(perm, sourceId, sourcePlayerId, game)).collect(Collectors.toList());
}
} | public List<Permanent> getActivePermanents(FilterPermanent filter, UUID sourcePlayerId, UUID sourceId, Game game){
if (game.getRangeOfInfluence() == RangeOfInfluence.ALL) {
return field.values().stream().filter(perm -> perm.isPhasedIn() && filter.match(perm, sourceId, sourcePlayerId, game)).collect(Collectors.toList());
} else {
List<UUID> range = game.getState().getPlayersInRange(sourcePlayerId, game);
return field.values().stream().filter(perm -> perm.isPhasedIn() && range.contains(perm.getControllerId()) && filter.match(perm, sourceId, sourcePlayerId, game)).collect(Collectors.toList());
}
} |
|
288 | public Map<String, Object> previewSchedule(User loginUser, String projectName, String schedule){
Map<String, Object> result = new HashMap<>();
CronExpression cronExpression;
ScheduleParam scheduleParam = JSONUtils.parseObject(schedule, ScheduleParam.class);
Date now = new Date();
Date startTime = now.after(scheduleParam.getStartTime()) ? now : scheduleParam.getStartTime();
Date endTime = scheduleParam.getEndTime();
try {
cronExpression = CronUtils.parse2CronExpression(scheduleParam.getCrontab());
} catch (ParseException e) {
logger.error(e.getMessage(), e);
putMsg(result, Status.PARSE_TO_CRON_EXPRESSION_ERROR);
return result;
}
List<Date> selfFireDateList = CronUtils.getSelfFireDateList(startTime, endTime, cronExpression, Constants.PREVIEW_SCHEDULE_EXECUTE_COUNT);
result.put(Constants.DATA_LIST, selfFireDateList.stream().map(DateUtils::dateToString));
putMsg(result, Status.SUCCESS);
return result;
} | public Result<List<String>> previewSchedule(User loginUser, String projectName, String schedule){
Map<String, Object> result = new HashMap<>();
CronExpression cronExpression;
ScheduleParam scheduleParam = JSONUtils.parseObject(schedule, ScheduleParam.class);
Date now = new Date();
Date startTime = now.after(scheduleParam.getStartTime()) ? now : scheduleParam.getStartTime();
Date endTime = scheduleParam.getEndTime();
try {
cronExpression = CronUtils.parse2CronExpression(scheduleParam.getCrontab());
} catch (ParseException e) {
logger.error(e.getMessage(), e);
return Result.error(Status.PARSE_TO_CRON_EXPRESSION_ERROR);
}
List<Date> selfFireDateList = CronUtils.getSelfFireDateList(startTime, endTime, cronExpression, Constants.PREVIEW_SCHEDULE_EXECUTE_COUNT);
return Result.success(selfFireDateList.stream().map(DateUtils::dateToString).collect(Collectors.toList()));
} |
|
289 | private Path generateTempFileFor(Path dest, Path video){
try {
return Files.createTempFile(dest.getParent(), dest.getFileName().toString(), "." + FilenameUtils.getExtension(video.getFileName().toString()));
} catch (IOException e) {
log.error("Error during generation of tmp file for {}", video.toAbsolutePath().toString());
throw new RuntimeException(e);
}
} | private Path generateTempFileFor(Path dest, Path video){
return Try.of(() -> Files.createTempFile(dest.getParent(), dest.getFileName().toString(), "." + FilenameUtils.getExtension(video.getFileName().toString()))).onFailure(e -> log.error("Error during generation of tmp file for {}", video.toAbsolutePath().toString())).getOrElseThrow(e -> new RuntimeException(e));
} |
|
290 | private List<Map<String, String>> executeQueryTypeEmail(String value, int maxResults) throws InternalErrorException{
List<Map<String, String>> subjects = new ArrayList<>();
try {
Members result = service.members().list(groupName).execute();
List<Member> membersInGroup = result.getMembers();
for (Member member : membersInGroup) {
Map<String, String> map = new HashMap<>();
if (member.getEmail().equals(value)) {
map = processGoogleMappingAttribute(member.getId());
}
if (!map.isEmpty()) {
subjects.add(map);
}
if (maxResults > 0) {
if (subjects.size() >= maxResults) {
break;
}
}
}
} catch (IOException ex) {
log.error("Problem with I/O operation while accesing Google Group API in ExtSourceGoogle class.", ex);
}
return subjects;
} | private void executeQueryTypeEmail(String value, int maxResults, List<Map<String, String>> subjects) throws InternalErrorException{
try {
Members result = service.members().list(groupName).execute();
List<Member> membersInGroup = result.getMembers();
for (Member member : membersInGroup) {
Map<String, String> map = new HashMap<>();
if (member.getEmail().equals(value)) {
map = processGoogleMappingAttribute(member.getId());
}
if (!map.isEmpty()) {
subjects.add(map);
}
if (maxResults > 0) {
if (subjects.size() >= maxResults) {
break;
}
}
}
} catch (IOException ex) {
log.error("Problem with I/O operation while accesing Google Group API in ExtSourceGoogle class.", ex);
}
} |
|
291 | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ctx = this;
mainActivityRunningInstance = this;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment, new MovieFragment());
transaction.commit();
}
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
MovieFragment.setSearchedLayout(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
searchView.setVisibility(View.VISIBLE);
}
@Override
public void onSearchViewClosed() {
searchView.setVisibility(View.GONE);
}
});
} | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ctx = this;
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
if (savedInstanceState == null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment, new MovieFragment());
transaction.commit();
}
searchView = (MaterialSearchView) findViewById(R.id.search_view);
searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
MovieFragment.setSearchedLayout(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
@Override
public void onSearchViewShown() {
searchView.setVisibility(View.VISIBLE);
}
@Override
public void onSearchViewClosed() {
searchView.setVisibility(View.GONE);
}
});
} |
|
292 | public Response registerResearcher(@PathParam("userId") Integer userId, NIHUserAccount nihAccount){
try {
;
return Response.status(Response.Status.OK).entity(nihAuthApi.authenticateNih(nihAccount, userId)).build();
} catch (Exception e) {
return createExceptionResponse(e);
}
} | public Response registerResearcher(@PathParam("userId") Integer userId, NIHUserAccount nihAccount){
try {
return Response.status(Response.Status.OK).entity(nihAuthApi.authenticateNih(nihAccount, userId)).build();
} catch (Exception e) {
return createExceptionResponse(e);
}
} |
|
293 | public static PinpointManager getPinpointManager(final Context applicationContext){
if (pinpointManager == null) {
final AWSConfiguration awsConfig = new AWSConfiguration(applicationContext);
AWSMobileClient.getInstance().initialize(applicationContext, awsConfig, new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails userStateDetails) {
Log.i("INIT", userStateDetails.getUserState().toString());
}
@Override
public void onError(Exception e) {
Log.e("INIT", "Initialization error.", e);
}
});
Log.e("awsconfig", awsConfig.toString());
PinpointConfiguration pinpointConfig = new PinpointConfiguration(applicationContext, AWSMobileClient.getInstance(), awsConfig).withChannelType(ChannelType.BAIDU);
pinpointManager = new PinpointManager(pinpointConfig);
}
return pinpointManager;
} | public static PinpointManager getPinpointManager(final Context applicationContext){
if (pinpointManager == null) {
final AWSConfiguration awsConfig = new AWSConfiguration(applicationContext);
AWSMobileClient.getInstance().initialize(applicationContext, awsConfig, new Callback<UserStateDetails>() {
@Override
public void onResult(UserStateDetails userStateDetails) {
Log.i("INIT", userStateDetails.getUserState().toString());
}
@Override
public void onError(Exception e) {
Log.e("INIT", "Initialization error.", e);
}
});
PinpointConfiguration pinpointConfig = new PinpointConfiguration(applicationContext, AWSMobileClient.getInstance(), awsConfig).withChannelType(ChannelType.BAIDU);
pinpointManager = new PinpointManager(pinpointConfig);
}
return pinpointManager;
} |
|
294 | public List<Map<String, Object>> items(@PathVariable String table){
LOGGER.info("Getting items for " + table);
List<Map<String, Object>> items = new ArrayList<>();
ScanRequest scanRequest = new ScanRequest().withTableName(table);
try {
List<Map<String, AttributeValue>> list = amazonDynamoDBClient.scan(scanRequest).getItems();
LOGGER.info("raw items ", list);
for (Map<String, AttributeValue> item : list) {
items.add(InternalUtils.toSimpleMapValue(item));
}
} catch (AmazonClientException ex) {
LOGGER.error(ex.getMessage());
}
return items;
} | public List<Map<String, Object>> items(@PathVariable String table){
LOGGER.info("Getting items for " + table);
List<Map<String, Object>> items = new ArrayList<>();
scanRequest.withTableName(table);
List<Map<String, AttributeValue>> list = amazonDynamoDBClient.scan(scanRequest).getItems();
LOGGER.info("raw items ", list);
for (Map<String, AttributeValue> item : list) {
items.add(InternalUtils.toSimpleMapValue(item));
}
return items;
} |
|
295 | public static void unZip(String zipFile, String outputFolder){
byte[] buffer = new byte[1024];
try {
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
System.out.println("file unzip : " + newFile.getAbsoluteFile());
new File(newFile.getParent()).mkdirs();
if (!newFile.exists()) {
if (newFile.isDirectory()) {
newFile.mkdir();
} else {
newFile.createNewFile();
}
}
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
} | public static void unZip(String zipFile, String outputFolder){
byte[] buffer = new byte[1024];
try {
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
new File(newFile.getParent()).mkdirs();
if (!newFile.exists()) {
if (newFile.isDirectory()) {
newFile.mkdir();
} else {
newFile.createNewFile();
}
}
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
} |
|
296 | public Bitmap GetBarcode(int width, int height){
Code39Writer writer = new Code39Writer();
BitMatrix bm = null;
Bitmap bitmap = null;
try {
bm = writer.encode(content, BarcodeFormat.CODE_39, width, height);
} catch (WriterException e) {
e.printStackTrace();
}
if (bm != null) {
bitmap = ProduceBarcode(bm, width, height);
}
return bitmap;
} | public Bitmap GetBarcode(int width, int height){
return ProduceBarcode(new Code39Writer(), BarcodeFormat.CODE_39, width, height);
} |
|
297 | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
stockAdapter = new StockAdapter(stockList, this);
recyclerView.setAdapter(stockAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
swiper = findViewById(R.id.swiper);
swiper.setOnRefreshListener(() -> {
doRefresh();
});
for (int i = 0; i < 20; i++) {
stockList.add(new Stock());
}
} | protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
stockAdapter = new StockAdapter(stockList, this);
recyclerView.setAdapter(stockAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
swiper = findViewById(R.id.swiper);
swiper.setOnRefreshListener(this::doRefresh);
for (int i = 0; i < 20; i++) {
stockList.add(new Stock());
}
} |
|
298 | public static void collectNestedProperties(T initial, NestedPropertyContext<T> context){
Queue<T> queue = new ArrayDeque<T>();
queue.add(initial);
while (!queue.isEmpty()) {
T nestedNode = queue.remove();
if (context.isIterable(nestedNode)) {
Iterators.addAll(queue, nestedNode.getIterator());
} else {
context.addNested(nestedNode);
}
}
} | public static void collectNestedProperties(T initial, NestedPropertyContext<T> context){
Queue<T> queue = new ArrayDeque<T>();
queue.add(initial);
while (!queue.isEmpty()) {
T nestedNode = queue.remove();
if (!(context.shouldUnpack(nestedNode) && nestedNode.unpackToQueue(queue))) {
context.addNested(nestedNode);
}
}
} |
|
299 | private void deleteGroups(){
Collection<Group> groups = getSelectedGroups();
for (Iterator<Group> iterator = groups.iterator(); iterator.hasNext(); ) {
Group group = iterator.next();
group = groupService.merge(group);
Set<User> users = new HashSet<>();
users.addAll(group.getUsers());
groupService.delete(group);
for (User user : users) {
if (user != null) {
getBus().post(new MainUIEvent.UserGroupsChangedEvent(user));
}
}
table.removeItem(group.getId());
}
} | private void deleteGroups(){
Collection<Group> groups = getSelectedGroups();
for (Group group : groups) {
group = groupService.merge(group);
Set<User> users = new HashSet<>();
users.addAll(group.getUsers());
groupService.delete(group);
for (User user : users) {
if (user != null) {
getBus().post(new MainUIEvent.UserGroupsChangedEvent(user));
}
}
table.removeItem(group.getId());
}
} |