text
stringlengths 10
2.72M
|
|---|
package com.lupan.HeadFirstDesignMode.chapter4_factory.factoryMethod.pizza;
/**
* TODO
*
* @author lupan
* @version 2016/3/21 0021
*/
public class Pizza1 extends Pizza {
public Pizza1() {
this.name = "披萨1";
}
}
|
package org.qizuo.cm.modules.system.pojo;
import org.qizuo.cm.modules.base.pojo.BasePoJo;
/**
* @Author: fangl
* @Description: 日志
* @Date: 14:20 2018/10/29
*/
public class LogPoJo extends BasePoJo {
/**
* 日志内容
*/
private String content;
/**
* 日志类型
*/
private String typeCd;
private String typeNm;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTypeCd() {
return typeCd;
}
public void setTypeCd(String typeCd) {
this.typeCd = typeCd;
}
public String getTypeNm() {
return typeNm;
}
public void setTypeNm(String typeNm) {
this.typeNm = typeNm;
}
}
|
package communication.enums;
import communication.packets.Packet;
import communication.packets.ResponsePacket;
/**
* This enum contains all types of packets as String representation.
* This String is used on the server-side to identify a {@link Packet} before instantiating the corresponding class.
* However, for increased code flexibility the types includes those of {@link ResponsePacket}'.
*/
public enum PacketType {
LOGIN_REQUEST, LOGIN_RESPONSE, PERSONAL_DATA_REQUEST, PERSONAL_DATA_RESPONSE, GET_AGENDA_REQUEST, GET_AGENDA_RESPONSE, ADD_VOTE_REQUEST, ADD_VOTE_RESPONSE,
GET_ACTIVE_VOTING_REQUEST, GET_ACTIVE_VOTING_RESPONSE, INVALID_TOKEN, FAILURE, ADD_TOPIC_REQUEST, REMOVE_TOPIC_REQUEST,
RENAME_TOPIC_REQUEST, REORDER_TOPIC_REQUEST, VALID_RESPONSE, REQUEST_OF_CHANGE_REQUEST, REQUEST_OF_SPEECH_REQUEST, GET_ALL_REQUESTS_REQUEST,
GET_ALL_REQUESTS_RESPONSE, ADD_ATTENDEE_REQUEST, GET_ALL_ATTENDEES_REQUEST, GET_ALL_ATTENDEES_RESPONSE, EDIT_USER_REQUEST,
REMOVE_ATTENDEE_REQUEST, LOGOUT_ATTENDEE_REQUEST, GENERATE_NEW_ATTENDEE_PASSWORD, GENERATE_NEW_ATTENDEE_TOKEN,
GENERATE_MISSING_ATTENDEE_PASSWORDS, GET_ATTENDEE_PASSWORD_REQUEST, GET_ALL_ATTENDEE_PASSWORDS, LOGOUT_ALL_ATTENDEES, GET_ATTENDEE_DATA_REQUEST,
GET_VOTINGS_REQUEST, ADD_VOTING_REQUEST_PACKET, REMOVE_VOTING_REQUEST, SET_ATTENDEE_PRESENT_STATUS_REQUEST,
GET_ALL_ATTENDEE_PASSWORDS_RESPONSE, GET_ATTENDEE_PASSWORD_RESPONSE, CONFERENCE_DATA_REQUEST, CONFERENCE_DATA_RESPONSE, IS_ADMIN_REQUEST, IS_ADMIN_RESPONSE,
DOWNLOAD_FILE_RESPONSE, DOWNLOAD_FILE_REQUEST, GET_DOCUMENT_LIST_REQUEST, GET_DOCUMENT_LIST_RESPONSE, UPDATE_FILE_REQUEST, UPDATE_FILE_RESPONSE,
GET_VOTINGS_RESPONSE, START_VOTING_REQUEST, EDIT_VOTING_REQUEST, ADD_MULTIPLE_ATTENDEES_REQUEST, DELETE_FILE_REQUEST, SET_REQUEST_STATUS_REQUEST,
GET_EXISTING_GROUPS_REQUEST, GET_EXISTING_GROUPS_RESPONSE, ADD_FULL_AGENDA_REQUEST, DELETE_AGENDA_REQUEST, GET_PREVIOUS_VOTINGS_REQUEST,
DOWNLOAD_QR_REQUEST, DOWNLOAD_ALL_QR_REQUEST;
}
|
/*
* Node represent a node for Stack and Queue
*
* Author: Gilang Kusuma Jati (gilang.k@samsung.com), SRIN.
*
*/
package datastructurefromlib;
public class Node<E extends Comparable<E>>
{
E element;
Node<E> next;
public Node(E element, Node<E> next)
{
this.element = element;
this.next = next;
}
public Node(E element)
{
this(element, null);
}
public Node()
{
this(null);
}
}
|
/**
*
* ******************************************************************************
* MontiCAR Modeling Family, www.se-rwth.de
* Copyright (c) 2017, Software Engineering Group at RWTH Aachen,
* All rights reserved.
*
* This project is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this project. If not, see <http://www.gnu.org/licenses/>.
* *******************************************************************************
*/
package de.monticore.lang.monticar.cnnarch.cocos;
import de.monticore.lang.monticar.cnnarch._cocos.*;
import de.monticore.lang.monticar.cnnarch.helper.ErrorCodes;
import de.se_rwth.commons.logging.Log;
import org.junit.Before;
import org.junit.Test;
import static de.monticore.lang.monticar.cnnarch.ParserTest.ENABLE_FAIL_QUICK;
public class AllCoCoTest extends AbstractCoCoTest {
String baseDir="src/test/resources";
public AllCoCoTest() {
Log.enableFailQuick(false);
}
@Before
public void setUp() {
// ensure an empty log
Log.getFindings().clear();
Log.enableFailQuick(ENABLE_FAIL_QUICK);
}
@Test
public void testValidCoCos(){
checkValid("architectures", "ResNet152");
checkValid("architectures", "Alexnet");
checkValid("architectures", "ResNeXt50");
checkValid("architectures", "ResNet34");
checkValid("architectures", "SequentialAlexnet");
checkValid("architectures", "ThreeInputCNN_M14");
checkValid("architectures", "VGG16");
checkValid("valid_tests", "ArgumentSequenceTest");
checkValid("valid_tests", "Fixed_Alexnet");
checkValid("valid_tests", "Fixed_ThreeInputCNN_M14");
checkValid("valid_tests", "ThreeInputCNN_M14_alternative");
checkValid("valid_tests", "Alexnet_alt");
checkValid("valid_tests", "SimpleNetworkSoftmax");
checkValid("valid_tests", "SimpleNetworkSigmoid");
checkValid("valid_tests", "SimpleNetworkLinear");
checkValid("valid_tests", "SimpleNetworkRelu");
checkValid("valid_tests", "SimpleNetworkTanh");
checkValid("valid_tests", "ResNeXt50_alt");
checkValid("valid_tests", "Alexnet_alt2");
checkValid("valid_tests", "MultipleOutputs");
}
@Test
public void testIllegalIONames(){
checkInvalid(
new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOName()),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "IllegalIOName",
new ExpectedErrorInfo(2, ErrorCodes.ILLEGAL_NAME));
}
@Test
public void testUnknownMethod(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckLayer()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "UnknownMethod",
new ExpectedErrorInfo(1, ErrorCodes.UNKNOWN_LAYER));
}
@Test
public void testDuplicatedNames(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckVariableName()).addCoCo(new CheckLayerName()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "DuplicatedNames",
new ExpectedErrorInfo(2, ErrorCodes.DUPLICATED_NAME));
}
@Test
public void testDuplicatedIONames(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOName()),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "DuplicatedIONames",
new ExpectedErrorInfo(1, ErrorCodes.DUPLICATED_NAME));
}
@Test
public void testUnknownVariableName(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckExpressions()),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "UnknownVariableName",
new ExpectedErrorInfo(1, ErrorCodes.UNKNOWN_VARIABLE_NAME));
}
@Test
public void testUnknownIO(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOName()),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "UnknownIO",
new ExpectedErrorInfo(2, ErrorCodes.UNKNOWN_IO));
}
@Test
public void testDuplicatedArgument(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckLayer()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "DuplicatedArgument",
new ExpectedErrorInfo(1, ErrorCodes.DUPLICATED_ARG));
}
@Test
public void testWrongArgument(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckArgument()).addCoCo(new CheckLayer()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "WrongArgument",
new ExpectedErrorInfo(4, ErrorCodes.UNKNOWN_ARGUMENT, ErrorCodes.MISSING_ARGUMENT));
}
@Test
public void testInvalidRecursion(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckLayerRecursion()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "InvalidRecursion",
new ExpectedErrorInfo(1, ErrorCodes.RECURSION_ERROR));
}
@Test
public void testArgumentConstraintTest1(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "ArgumentConstraintTest1",
new ExpectedErrorInfo(1, ErrorCodes.ILLEGAL_ASSIGNMENT));
}
@Test
public void testArgumentConstraintTest2(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "ArgumentConstraintTest2",
new ExpectedErrorInfo(1, ErrorCodes.ILLEGAL_ASSIGNMENT));
}
@Test
public void testWrongRangeOperator(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckRangeOperators()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "WrongRangeOperator",
new ExpectedErrorInfo(2, ErrorCodes.DIFFERENT_RANGE_OPERATORS));
}
@Test
public void testArgumentConstraintTest3(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "ArgumentConstraintTest3",
new ExpectedErrorInfo(1, ErrorCodes.ILLEGAL_ASSIGNMENT));
}
@Test
public void testArgumentConstraintTest4(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "ArgumentConstraintTest4",
new ExpectedErrorInfo(1, ErrorCodes.ILLEGAL_ASSIGNMENT));
}
@Test
public void testArgumentConstraintTest5(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "ArgumentConstraintTest5",
new ExpectedErrorInfo(1, ErrorCodes.ILLEGAL_ASSIGNMENT));
}
@Test
public void testArgumentConstraintTest6(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "ArgumentConstraintTest6",
new ExpectedErrorInfo(1, ErrorCodes.ILLEGAL_ASSIGNMENT));
}
@Test
public void testMissingArgument(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckLayer()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "MissingArgument",
new ExpectedErrorInfo(3, ErrorCodes.MISSING_ARGUMENT));
}
@Test
public void testIllegalName(){
checkInvalid(new CNNArchCoCoChecker().addCoCo(new CheckVariableName()).addCoCo(new CheckLayerName()),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
"invalid_tests", "IllegalName",
new ExpectedErrorInfo(2, ErrorCodes.ILLEGAL_NAME));
}
@Test
public void testUnfinishedArchitecture(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckArchitectureFinished()),
"invalid_tests", "UnfinishedArchitecture",
new ExpectedErrorInfo(1, ErrorCodes.UNFINISHED_ARCHITECTURE));
}
@Test
public void testInvalidInputShape(){
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckElementInputs()),
"invalid_tests", "InvalidInputShape",
new ExpectedErrorInfo(2, ErrorCodes.INVALID_ELEMENT_INPUT_SHAPE));
}
@Test
public void testWrongIOType() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckElementInputs()),
"invalid_tests", "WrongIOType",
new ExpectedErrorInfo(1, ErrorCodes.INVALID_ELEMENT_INPUT_DOMAIN));
}
@Test
public void testInvalidIOShape1() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOType()),
"invalid_tests", "InvalidIOShape1",
new ExpectedErrorInfo(2, ErrorCodes.INVALID_IO_TYPE));
}
@Test
public void testInvalidIOShape2() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOType()),
"invalid_tests", "InvalidIOShape2",
new ExpectedErrorInfo(2, ErrorCodes.INVALID_IO_TYPE));
}
@Test
public void testNotIOArray() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOAccessAndIOMissing()),
"invalid_tests", "NotIOArray",
new ExpectedErrorInfo(2, ErrorCodes.INVALID_ARRAY_ACCESS));
}
@Test
public void testMissingIO2() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOAccessAndIOMissing()),
"invalid_tests", "MissingIO2",
new ExpectedErrorInfo(2, ErrorCodes.MISSING_IO));
}
@Test
public void testInvalidArrayAccessValue() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckIOAccessAndIOMissing()),
"invalid_tests", "InvalidArrayAccessValue",
new ExpectedErrorInfo(1, ErrorCodes.INVALID_ARRAY_ACCESS));
}
@Test
public void testMissingMerge() {
checkInvalid(new CNNArchCoCoChecker(),
new CNNArchSymbolCoCoChecker(),
new CNNArchSymbolCoCoChecker().addCoCo(new CheckElementInputs()),
"invalid_tests", "MissingMerge",
new ExpectedErrorInfo(2, ErrorCodes.MISSING_MERGE));
}
}
|
package Kamil_zerg.astar;
import java.util.*;
import battlecode.common.MapLocation;
/**
* A path determined by some path finding algorithm. A series of steps from
* the starting location to the target location. This includes a step for the
* initial location.
*
* @author Kevin Glass
*/
public class Path {
/** The list of steps building up this path */
private List<Step> steps = new ArrayList<Step>();
/**
* Create an empty path
*/
public Path() {
}
/**
* Get the length of the path, i.e. the number of steps
*
* @return The number of steps in this path
*/
public int getLength() {
return steps.size();
}
/**
* Get the step at a given index in the path
*
* @param index The index of the step to retrieve. Note this should
* be >= 0 and < getLength();
* @return The step information, the position on the map.
*/
public Step getStep(int index) {
return steps.get(index);
}
/**
* Get the x coordinate for the step at the given index
*
* @param index The index of the step whose x coordinate should be retrieved
* @return The x coordinate at the step
*/
public MapLocation getLoc(int index) {
return getStep(index).loc;
}
/**
* Append a step to the path.
*
* @param x The x coordinate of the new step
* @param y The y coordinate of the new step
*/
public void appendStep(MapLocation loc) {
steps.add(new Step(loc));
}
/**
* Prepend a step to the path.
*
* @param x The x coordinate of the new step
* @param y The y coordinate of the new step
*/
public void prependStep(MapLocation loc) {
steps.add(0, new Step(loc));
}
/**
* Check if this path contains the given step
*
* @param x The x coordinate of the step to check for
* @param y The y coordinate of the step to check for
* @return True if the path contains the given step
*/
public boolean contains(MapLocation loc) {
return steps.contains(new Step(loc));
}
public List<MapLocation> toMapLocationList() {
List<MapLocation> result = new ArrayList<MapLocation>();
for (Step step : this.steps) {
result.add(step.loc);
}
return result;
}
/**
* A single step within the path
*
* @author Kevin Glass
*/
public class Step {
/** The x coordinate at the given step */
private MapLocation loc;
/**
* Create a new step
*
* @param x The x coordinate of the new step
* @param y The y coordinate of the new step
*/
public Step(MapLocation loc) {
this.loc = loc;
}
/**
* Get the x coordinate of the new step
*
* @return The x coodindate of the new step
*/
public MapLocation getLoc() {
return loc;
}
/**
* @see Object#hashCode()
*/
public int hashCode() {
return loc.getX()*loc.getY();
}
/**
* @see Object#equals(Object)
*/
public boolean equals(Object other) {
if (other instanceof Step) {
Step o = (Step) other;
return this.loc.equals(o.loc);
}
return false;
}
}
}
|
package com.flutterwave.raveandroid.rave_presentation.di.francmobilemoney;
import com.flutterwave.raveandroid.rave_presentation.francmobilemoney.FrancMobileMoneyContract;
import javax.inject.Inject;
import dagger.Module;
import dagger.Provides;
@Module
public class FrancophoneModule {
private FrancMobileMoneyContract.Interactor interactor;
@Inject
public FrancophoneModule(FrancMobileMoneyContract.Interactor interactor) {
this.interactor = interactor;
}
@Provides
public FrancMobileMoneyContract.Interactor providesContract() {
return interactor;
}
}
|
package net.youzule.spring.chapter02.BeanInherit;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @description:
* @company:
* @author:Sean
* @date:2018/7/3 10:04
**/
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("/net/youzule/spring/chapter02/BeanInherit/Beans.xml");
Parent parent = (Parent) context.getBean("parent");
System.out.println(parent);
Son son = (Son) context.getBean("son");
System.out.println(son);
}
}
|
package LongestCommonPrefix;
/**
* 题目内容 寻找数组公共的前缀字符串
*
* Write a function to find the longest common prefix string amongst an array of strings.
* If there is no common prefix, return an empty string "".
* Example 1:
* Input: ["flower","flow","flight"]
* Output: "fl"
* Example 2:
* Input: ["dog","racecar","car"]
* Output: ""
* Explanation: There is no common prefix among the input strings.
* Note:
* All given inputs are in lowercase letters a-z.
*
* @author zhangmiao
*
* email:1006299425@qq.com
*
*/
public class Solution {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strs1 = new String[]{"dog","racecar","car"};
String[] strs2 = new String[]{"flower","flow","flight"};
String[] strs3 = new String[]{"ca","a"};
String[] strs4 = new String[]{"a","a"};
System.out.println("strs1 longestCommonPrefix:"+longestCommonPrefix(strs1));
System.out.println("strs2 longestCommonPrefix:"+longestCommonPrefix(strs2));
System.out.println("strs3 longestCommonPrefix:"+longestCommonPrefix(strs3));
System.out.println("strs4 longestCommonPrefix:"+longestCommonPrefix(strs4));
}
public static String longestCommonPrefix(String[] strs) {
String result = "";
if (strs.length == 0) {
return "";
}
if (strs.length == 1) {
return strs[0];
}
String lestString = strs[0];
for (int n =1;n<strs.length;n++) {
String str = strs[n];
if (str.length() < lestString.length()) {
lestString = str;
}
}
int length = lestString.length();
for (int i = length; i> 0;i--){
String sub = lestString.substring(0,i);
boolean isContains = true;
for (int n = 0; n<strs.length;n++){
String str = strs[n];
if (!str.startsWith(sub)) {
isContains = false;
break;
}
}
if (isContains){
if (sub.length() > result.length()) {
result = sub;
}
}
}
return result;
}
}
|
package Tienda;
public class Producto {
private double codigo;
private float IVA;
private float precio;
private String nombreProducto;
public Producto() {}
public void setPrecio(float precio) {
this.precio = precio;
}
public float getPrecio() {
return precio;
}
public void setIVA(float IVA) {
this.IVA = IVA;
}
public float getIVA() {
return IVA;
}
public String getNombreProducto() {
return nombreProducto;
}
public void setNombreProducto(String nombreProducto) {
this.nombreProducto = nombreProducto;
}
public double codigoProducto(){
codigo = (double)Math.floor(Math.random()*10000000);
return codigo;
}
public float precioTotal(){
float total = ((getPrecio()*getIVA())+getPrecio());
return total;
}
}
|
package com.malf.service.impl;
import com.malf.mapper.RolePermissionMapper;
import com.malf.mapper.UserRoleMapper;
import com.malf.pojo.*;
import com.malf.service.RolePermissionService;
import com.malf.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author malf
* @description 用户角色服务类
* @project shiroSpringBoot
* @since 2020/11/9
*/
@Service
public class RolePermissionServiceImpl implements RolePermissionService {
@Autowired
RolePermissionMapper rolePermissionMapper;
@Override
public void setPermissions(Role role, long[] permissionIds) {
// 删除当前角色所有权限
RolePermissionExample example = new RolePermissionExample();
example.createCriteria().andRidEqualTo(role.getId());
List<RolePermission> rolePermissions = rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rolePermissions) {
rolePermissionMapper.deleteByPrimaryKey(rolePermission.getRid());
}
// 设置新的权限关系
if (null != permissionIds) {
for (Long pid : permissionIds) {
RolePermission rolePermission = new RolePermission();
rolePermission.setPid(pid);
rolePermission.setRid(role.getId());
rolePermissionMapper.insert(rolePermission);
}
}
}
@Override
public void deleteByRole(long roleId) {
RolePermissionExample example = new RolePermissionExample();
example.createCriteria().andRidEqualTo(roleId);
List<RolePermission> rolePermissions = rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rolePermissions)
rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
}
@Override
public void deleteByPermission(long permissionId) {
RolePermissionExample example = new RolePermissionExample();
example.createCriteria().andPidEqualTo(permissionId);
List<RolePermission> rolePermissions = rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rolePermissions)
rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
}
}
|
package com.example.xiaox.goline2.extension.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
import java.util.ArrayList;
public class TextCircle extends android.support.v7.widget.AppCompatTextView {
public TextCircle(Context context){
super(context);
init();
}
public TextCircle(Context context, AttributeSet attrs){
super(context, attrs);
init();
}
public TextCircle(Context context, AttributeSet attrs, int defStyle){
super(context, attrs, defStyle);
init();
}
private int cx = 0;
private int cy = 0;
private int maxRadius = 0;
private int fillWidth = 0;
private int strokeWidth = 0;
private int fillColor;
private int strokeColor;
private Paint fillPaint = null;
private Paint strokePaint = null;
private static final int DEFAULT_FILL = Color.GRAY;
private static final int DEFAULT_STROKE_FILL = Color.WHITE;
private static final int DEFAULT_VIEW_SIZE = 128;
private void init(){
this.fillColor = DEFAULT_FILL;
this.strokeColor = DEFAULT_STROKE_FILL;
fillPaint = new Paint();
strokePaint = new Paint();
fillPaint.setColor(this.fillColor);
fillPaint.setStyle(Paint.Style.FILL);
fillPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
fillPaint.setAntiAlias(true);
strokePaint.setStrokeWidth(strokeWidth);
strokePaint.setColor(this.strokeColor);
strokePaint.setStyle(Paint.Style.STROKE);
strokePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
strokePaint.setAntiAlias(true);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
int width = resolveSize(DEFAULT_VIEW_SIZE, widthMeasureSpec);
int height = resolveSize(DEFAULT_VIEW_SIZE, heightMeasureSpec);
updateRadius(width, height);
setMeasuredDimension(width, height);
}
private void updateRadius(int width, int height){
if(height > width){
this.maxRadius = width / 2;
this.cx = this.maxRadius;
this.cy = (height - width) / 2 + this.maxRadius;
}else{
this.maxRadius = height / 2;
this.cx = (width - height) / 2 + this.maxRadius;
this.cy = this.maxRadius;
}
this.fillWidth = this.maxRadius - this.strokeWidth;
}
public void setStroke(int stroke){
this.strokeWidth = stroke;
this.strokePaint.setStrokeWidth(stroke);
this.invalidate();
}
public int getStroke(){
return this.strokeWidth;
}
public void setFill(int color){
this.fillColor = color;
fillPaint.setColor(color);
invalidate();
}
private int getFill(){return this.fillColor;}
public void setStrokeFill(int color){
this.strokeColor = color;
this.strokePaint.setColor(color);
invalidate();
}
private int getStrokeFill(){return this.strokeColor;}
@Override
protected void onDraw(Canvas canvas){
canvas.drawCircle(cx, cy, this.fillWidth, fillPaint);
canvas.drawCircle(cx, cy, this.fillWidth, strokePaint);
super.onDraw(canvas);
}
}
|
package demo.kanban.contract.moscow.repository;
import demo.kanban.contract.moscow.resource.column.Column;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ColumnRepository extends MongoRepository<Column, String>{
}
|
package se.tobijoh.onkyocontroller.communication.serversearcher;
import java.util.ArrayList;
import java.util.List;
import se.tobijoh.onkyocontroller.communication.Receiver;
public class ReceiverSearcherManager implements ReceiverSearcherListener {
private List<ReceiverSearcherListener> listeners;
private static ReceiverSearcherManager manager;
private boolean isSearching;
public static ReceiverSearcherManager getSharedInstance() {
return manager == null ? manager = new ReceiverSearcherManager() : manager;
}
public void addReceiverSearcherListener(ReceiverSearcherListener listener) {
if (listeners == null) listeners = new ArrayList<>();
listeners.add(listener);
}
public void searchForReceivers() {
if (!isSearching) {
isSearching = true;
new ReceiverSearcherTask(this).execute();
} else {
onNewReceiverFound(null, true);
}
}
@Override
public void onNewReceiverFound(Receiver newReceiver, boolean taskFinished) {
isSearching = !taskFinished;
for (ReceiverSearcherListener listener : listeners) {
listener.onNewReceiverFound(newReceiver, taskFinished);
}
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.ui.config.cluster;
import static edu.tsinghua.lumaqq.resource.Messages.button_modify;
import static edu.tsinghua.lumaqq.resource.Messages.button_update;
import static edu.tsinghua.lumaqq.resource.Messages.cluster_info_title_modify;
import static edu.tsinghua.lumaqq.resource.Messages.cluster_info_title_view;
import static edu.tsinghua.lumaqq.resource.Messages.message_box_cluster_message_option_modified;
import static edu.tsinghua.lumaqq.resource.Messages.message_box_common_fail_title;
import static edu.tsinghua.lumaqq.resource.Messages.message_box_common_info_title;
import static edu.tsinghua.lumaqq.resource.Messages.message_box_common_timeout;
import static edu.tsinghua.lumaqq.resource.Messages.success_modify_info;
import edu.tsinghua.lumaqq.models.Cluster;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.events.QQEvent;
import edu.tsinghua.lumaqq.qq.packets.in.ClusterCommandReplyPacket;
import edu.tsinghua.lumaqq.qq.packets.out.ClusterCommandPacket;
import edu.tsinghua.lumaqq.resource.Resources;
import edu.tsinghua.lumaqq.ui.MainShell;
import edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
/**
* @author luma
*/
public class ClusterInfoWindow extends AbstractConfigurationWindow {
private MainShell main;
private Cluster model;
// style
/** 我是创建者 */
public static final int EDITABLE_CREATOR = 1;
/** 群资料只读,对应于查看群资料窗口 */
public static final int READ_ONLY = 2;
/** 我是管理员,管理员不能设置管理员,不能转让身份 */
public static final int EDITABLE_ADMIN = 3;
// 页ID
private static final int CLUSTER_INFO = 0;
private static final int MEMBERS = 1;
private static final int MESSAGE_OPTION = 2;
// 修改成员列表时的包序号,检查这些序号判断回复包是否属于这个窗口
// 这里也用来判断修改是否完成,如果三者都为0,表示修改已经完成
private char removeMemberSequence;
private char addMemberSequence;
private char modifyInfoSequence;
/**
* Create a cluster info window
*
* @param main
* MainShell
* @param c
* Cluster model
* @param style
* window style
*/
public ClusterInfoWindow(MainShell main, Cluster c, int style) {
super(main.getShell(), style);
this.main = main;
this.model = c;
setPageListWidth(90);
if(style == READ_ONLY)
setOKButtonText(button_update);
else
setOKButtonText(button_modify);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#initializeVariables()
*/
@Override
protected void initializeVariables() {
super.initializeVariables();
addMemberSequence = removeMemberSequence = modifyInfoSequence = 0;
}
/**
* @return
* true表示修改已经完成
*/
private boolean isFinished() {
return addMemberSequence == 0 && removeMemberSequence == 0 && modifyInfoSequence == 0;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#initialPages()
*/
@Override
protected void initialPages() {
addPage(new ClusterPage(getPageContainer(), main, model, style));
addPage(new MemberPage(getPageContainer(), main, model, style));
addPage(new MessagePage(getPageContainer(), model));
main.getClient().addQQListener(this);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#configureShellSize()
*/
@Override
protected void configureShellSize() {
shell.pack();
Point size = shell.getSize();
if(size.x > 800)
size.x = 800;
if(size.y > 600)
size.y = 600;
shell.setSize(size);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#onShellClose()
*/
@Override
protected void onShellClose() {
saveAll();
main.getShellRegistry().removeClusterInfoWindow(model);
main.getClient().removeQQListener(this);
}
/**
* 设置cluster model
*
* @param c
*/
public void setClusterModel(Cluster c) {
this.model = c;
refreshPageModels(model);
refreshPageValues();
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#onOK()
*/
@Override
protected void onOK() {
if(getCurrentPageId() == MESSAGE_OPTION) {
((MessagePage)getPage(MESSAGE_OPTION)).doSave();
MessageDialog.openInformation(getShell(), message_box_common_info_title, message_box_cluster_message_option_modified);
} else {
setOKButtonEnabled(false);
if(style == READ_ONLY)
getClusterInfo();
else
modifyCluster();
}
}
/**
* 发送修改群信息的请求包
*/
private void modifyCluster() {
modifyInfoSequence = ((ClusterPage)getPage(CLUSTER_INFO)).doModifyClusterInfo();
MemberPage page = (MemberPage)getPage(MEMBERS);
removeMemberSequence = page.doRemoveMember();
addMemberSequence = page.doAddMember();
}
/**
* 请求得到群信息
*/
private void getClusterInfo() {
main.getClient().cluster_GetInfo(model.clusterId);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#pageChanged()
*/
@Override
protected void pageChanged() {
if(style == READ_ONLY) {
if(getCurrentPageId() == MESSAGE_OPTION)
setOKButtonText(button_modify);
else
setOKButtonText(button_update);
}
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#getTitle()
*/
@Override
protected String getTitle() {
return (style == READ_ONLY) ? cluster_info_title_view : cluster_info_title_modify;
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.ui.config.AbstractConfigurationWindow#getImage()
*/
@Override
protected Image getImage() {
return Resources.getInstance().getImage(Resources.icoCluster);
}
/**
* 如果修改已经完成,关闭窗口
*/
private void checkFinish() {
if(isFinished()) {
getClusterInfo();
MessageDialog.openInformation(main.getShell(), message_box_common_info_title, success_modify_info);
close();
}
}
@Override
protected void OnQQEvent(QQEvent e) {
switch(e.type) {
case QQEvent.CLUSTER_GET_INFO_FAIL:
case QQEvent.CLUSTER_GET_TEMP_INFO_FAIL:
case QQEvent.CLUSTER_MODIFY_INFO_FAIL:
processClusterCommandFail(e);
break;
case QQEvent.CLUSTER_GET_TEMP_INFO_OK:
case QQEvent.CLUSTER_GET_INFO_OK:
processGetClusterInfoSuccess(e);
break;
case QQEvent.CLUSTER_MODIFY_INFO_OK:
processModifyClusterInfoSuccess(e);
break;
case QQEvent.CLUSTER_MODIFY_MEMBER_OK:
processModifyClusterMemberSuccess(e);
break;
case QQEvent.SYS_TIMEOUT:
if(e.operation == QQ.QQ_CMD_CLUSTER_CMD)
processClusterCommandTimeout(e);
break;
}
}
/**
* @param e
*/
private void processModifyClusterMemberSuccess(QQEvent e) {
ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource();
if(packet.getSequence() == addMemberSequence)
addMemberSequence = 0;
else if(packet.getSequence() == removeMemberSequence)
removeMemberSequence = 0;
checkFinish();
}
/**
* @param e
*/
private void processClusterCommandTimeout(QQEvent e) {
ClusterCommandPacket packet = (ClusterCommandPacket)e.getSource();
if(packet.getClusterId() == model.clusterId) {
MessageDialog.openError(main.getShell(), message_box_common_fail_title, message_box_common_timeout);
close();
}
}
/**
* @param e
*/
private void processModifyClusterInfoSuccess(QQEvent e) {
ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource();
if(packet.getSequence() != modifyInfoSequence)
return;
modifyInfoSequence = 0;
checkFinish();
}
/**
* 处理得到临时群信息成功事件
*
* @param e
*/
private void processGetClusterInfoSuccess(QQEvent e) {
ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource();
if(packet.clusterId == model.clusterId)
setOKButtonEnabled(true);
}
/**
* 处理群命令失败事件,如果错误信息表示自己已经不是群成员,则删除这个群
*
* @param e
*/
private void processClusterCommandFail(QQEvent e) {
ClusterCommandReplyPacket packet = (ClusterCommandReplyPacket)e.getSource();
if(packet.clusterId == model.clusterId)
MessageDialog.openError(main.getShell(), message_box_common_fail_title, packet.errorMessage);
}
}
|
package Tasks.LessonSix.Converters;
public abstract class BaseConverter {
public double convert() {
return 0;
}
}
|
package com.ttps.gestortareas.dao.impl;
import org.springframework.stereotype.Repository;
import com.ttps.gestortareas.dao.IGenericDAO;
import com.ttps.gestortareas.domain.Board;
@Repository
public class BoardDao extends AbstractDao<Board> implements IGenericDAO<Board> {
public BoardDao() {
super();
this.persistenClass = Board.class;
}
}
|
package cn.ehanmy.hospital.mvp.model.entity.order;
import java.util.List;
import cn.ehanmy.hospital.mvp.model.entity.response.BaseResponse;
public class GetBuyInfoResponse extends BaseResponse {
private int nextPageIndex;
private List<GoodsOrderBean> goodsList;
@Override
public String toString() {
return "GetBuyInfoResponse{" +
"nextPageIndex=" + nextPageIndex +
", goodsList=" + goodsList +
'}';
}
public int getNextPageIndex() {
return nextPageIndex;
}
public void setNextPageIndex(int nextPageIndex) {
this.nextPageIndex = nextPageIndex;
}
public List<GoodsOrderBean> getGoodsList() {
return goodsList;
}
public void setGoodsList(List<GoodsOrderBean> goodsList) {
this.goodsList = goodsList;
}
}
|
package rendering;
import org.lwjgl.opengl.GL11;
import org.lwjgl.util.vector.Vector4f;
import terrains.Terrain;
/**
* A simple renderer that renders terrains.
*
* @author Karl
*
*/
public class TerrainRenderer {
private final TerrainShader shader;
private final boolean hasIndices;
/**
* @param shader
* - The shader program used for rendering this terrain.
* @param usesIndices
* - Indicates whether the terrain will be rendered with an index
* buffer or not.
*/
public TerrainRenderer(TerrainShader shader, boolean usesIndices) {
this.shader = shader;
this.hasIndices = usesIndices;
}
/**
* Renders a terrain to the screen. If the terrain has an index buffer the
* glDrawElements is used. Otherwise glDrawArrays is used.
*
* @param terrain
* - The terrain to be rendered.
* @param camera
* - The camera being used for rendering the terrain.
* @param light
* - The light being used to iluminate the terrain.
*
* @param clipPlane
* - The equation of the clipping plane to be used when rendering
* the terrain. The clipping planes cut off anything in the scene
* that is rendered outside of the plane.
*/
public void render(Terrain terrain, ICamera camera, Light light, Vector4f clipPlane) {
prepare(terrain, camera, light, clipPlane);
if (hasIndices) {
GL11.glDrawElements(GL11.GL_TRIANGLES, terrain.getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
} else {
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, terrain.getVertexCount());
}
finish(terrain);
}
/**
* Used when the program closes. Deletes the shader program.
*/
public void cleanUp() {
shader.cleanUp();
}
/**
* Starts the shader program and loads up any necessary uniform variables.
*
* @param terrain
* - The terrain to be rendered.
* @param camera
* - The camera being used to render the scene.
* @param light
* - The light in the scene.
* @param clipPlane
* - The equation of the clipping plane to be used when rendering
* the terrain. The clipping planes cut off anything in the scene
* that is rendered outside of the plane.
*/
private void prepare(Terrain terrain, ICamera camera, Light light, Vector4f clipPlane) {
terrain.getVao().bind();
shader.start();
shader.plane.loadVec4(clipPlane);
shader.lightBias.loadVec2(light.getLightBias());
shader.lightDirection.loadVec3(light.getDirection());
shader.lightColour.loadVec3(light.getColour().getVector());
shader.projectionViewMatrix.loadMatrix(camera.getProjectionViewMatrix());
}
/**
* End the rendering process by unbinding the VAO and stopping the shader
* program.
*
* @param terrain
*/
private void finish(Terrain terrain) {
terrain.getVao().unbind();
shader.stop();
}
}
|
package com.tencent.mm.plugin.appbrand.ui.autofill;
import android.view.MenuItem;
import com.tencent.mm.plugin.appbrand.ui.autofill.b.2;
import com.tencent.mm.protocal.c.ej;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.n.d;
class b$2$2 implements d {
final /* synthetic */ 2 gxJ;
b$2$2(2 2) {
this.gxJ = 2;
}
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
ej ejVar = (ej) this.gxJ.gxI.gxx.reO.get(menuItem.getItemId());
if (ejVar == null) {
x.e("MicroMsg.AppBrandIDCardVerifyPwdFrag", "not find phone_id, menuItem id :%d", new Object[]{Integer.valueOf(menuItem.getItemId())});
return;
}
x.i("MicroMsg.AppBrandIDCardVerifyPwdFrag", "select menuItem id:%d, phone_id:%s, show_phone:%s, bank_type:%s", new Object[]{Integer.valueOf(menuItem.getItemId()), ejVar.reM, ejVar.reN, ejVar.lMV});
this.gxJ.gxI.gxF = ejVar;
this.gxJ.gxI.gxG.setText(ejVar.reN);
}
}
|
package ctci.chap2;
import ctci.ctciLibrary.*;
public class Partition{
// Assuming doublely linked list (though it would easy to extend to single linked list, just track the previous node)
// This is a little funky since I imagined that we wanted to keep the head the head (this function would be void)
// Clearly the Author of CtCI was not thinking this way and the method signature shows that.
public static LinkedListNode partition(LinkedListNode head, int val){
LinkedListNode currNode = head.next;
while(currNode != null){
LinkedListNode nextEval = currNode.next;
if(currNode.data < val){
if (head.data >= val){
// A little hacky, but there's not much you can do if the head in right partition
int temp = head.data;
head.data = currNode.data;
currNode.data = temp;
}else{
// Remove currNode from current location
currNode.prev.setNext(currNode.next);
if(currNode.next != null){
currNode.next.setPrevious(currNode.prev);
}
// Put currNode in place directly after head
currNode.setNext(head.next);
head.next.setPrevious(currNode);
head.setNext(currNode);
currNode.setPrevious(head);
}
}
currNode = nextEval;
}
return head;
}
public static LinkedListNode createLinkedList() {
/* Create linked list */
int[] vals = AssortedMethods.randomArray(15,0,30);
LinkedListNode head = new LinkedListNode(vals[0], null, null);
LinkedListNode current = head;
for (int i = 1; i < vals.length; i++) {
current = new LinkedListNode(vals[i], null, current);
}
return head;
}
public static void main(String[] args) {
System.out.println(createLinkedList().printForward());
/* Partition */
LinkedListNode hA = partition(createLinkedList(), 15);
LinkedListNode hB = partition(createLinkedList(), 15);
LinkedListNode hC = partition(createLinkedList(), 15);
/* Print Result */
System.out.println(hA.printForward());
System.out.println(hB.printForward());
System.out.println(hC.printForward());
}
}
|
package jp.personal.server.data.message;
import java.util.Date;
import jp.personal.server.data.BaseDto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@NoArgsConstructor
@Data
public class SaveMessageDto extends BaseDto {
private static final long serialVersionUID = 1L;
private Long messageId;
private Date lastMessageDate;
private Long count;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.govt.controller;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.logging.LoggingFeature;
import org.govt.model.Activity;
import org.govt.model.AuthenticatedCommittee;
import org.govt.model.Grievance;
import org.govt.model.Keyword;
import org.govt.others.DBConfig;
import java.util.ArrayList;
import javax.ws.rs.client.Entity;
import org.govt.model.Committee;
import org.govt.model.Course;
import org.govt.model.NameById;
import org.govt.model.Status;
import org.govt.model.Student;
import org.govt.model.ComplaintResponse;
import org.govt.model.Email;
/**
*
* @author Pravesh Ganwani
*/
@WebServlet("/SolveGrievanceController")
public class SolveGrievanceController extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp); //To change body of generated methods, choose Tools | Templates.
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Client client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
WebTarget webTarget = client.target(DBConfig.getApiHost()).path("activities/activity/"+req.getParameter("complaintId")+"/ASC");
Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
Response response = invocationBuilder.get();
List<Activity> listOfActivities = response.readEntity(new GenericType<List<Activity>>(){});
webTarget = client.target(DBConfig.getApiHost()).path("responses/response/"+req.getParameter("complaintId")+"/ASC");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
List<ComplaintResponse> listOfResponses = response.readEntity(new GenericType<List<ComplaintResponse>>(){});
try {
String complaintId = req.getParameter("complaintId");
String type = req.getParameter("complaintType");
HttpSession hs = req.getSession();
AuthenticatedCommittee ac = (AuthenticatedCommittee)hs.getAttribute("user");
if(type.equals("pending")) {
int flag = 0;
int index = -1;
Grievance grievance = null;
Keyword k = null;
List<Grievance> listOfCommitteeGrievances = (List<Grievance>)hs.getAttribute("pendingGrievances");
List<Keyword> listOfCommitteeKeywords = (List<Keyword>)hs.getAttribute("pendingKeywords");
List<Activity> listOfComplaintActivities = new ArrayList<Activity>();
List<NameById> listOfActivitiesFrom = new ArrayList<NameById>();
List<NameById> listOfActivitiesTo = new ArrayList<NameById>();
List<ComplaintResponse> listOfComplaintResponses = new ArrayList<ComplaintResponse>();
List<NameById> listOfResponsesFrom = new ArrayList<NameById>();
List<NameById> listOfResponsesTo = new ArrayList<NameById>();
for (Iterator<Grievance> g = listOfCommitteeGrievances.iterator(); g.hasNext();) {
index++;
grievance = g.next();
if(grievance.getComplaintId().equals(complaintId)) {
flag = 1;
k = listOfCommitteeKeywords.get(index);
if(grievance.getComplaintIsAnonymous() != 1)
{
webTarget = client.target(DBConfig.getApiHost()).path("students/student/"+grievance.getComplaintStudentId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Student s = response.readEntity(Student.class);
List<Course> committeeCourses = (List<Course>)hs.getAttribute("courses");
for (Iterator<Course> c = committeeCourses.iterator(); c.hasNext();) {
Course course = c.next();
if(s.getCourseId() == course.getCourseId()) {
hs.setAttribute("courseName", course.getCourseName());
break;
}
}
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+s.getInstituteId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiInstituteName = response.readEntity(NameById.class);
hs.setAttribute("instituteName", nbiInstituteName);
hs.setAttribute("studentDetails", s);
}
if(grievance.getLastActivity() == null || grievance.getLastActivity().equals("")) {
Activity viewActivity = new Activity();
viewActivity.setComplaintId(complaintId);
viewActivity.setActivityFrom(ac.getCommitteeDetails().getCommitteeId());
viewActivity.setActivityTo(grievance.getComplaintStudentId());
viewActivity.setActivityType("view");
webTarget = client.target(DBConfig.getApiHost()).path("activities/activity");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(viewActivity, MediaType.APPLICATION_JSON));
grievance.setLastActivity("view");
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("grievances/activity");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(grievance, MediaType.APPLICATION_JSON));
Status st = response.readEntity(Status.class);
webTarget = client.target(DBConfig.getApiHost()).path("students/student/"+grievance.getComplaintStudentId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Student s = response.readEntity(Student.class);
Email e = new Email();
e.setActivityFrom(ac.getCommitteeDetails().getCommitteeName());
e.setG(grievance);
e.setSubject("Complaint Viewed");
e.setTitle("Your Complaint Was Viewed");
e.setTo(s.getStudentEmail().toLowerCase());
webTarget = client.target(DBConfig.getApiHost()).path("additional/email");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(e, MediaType.APPLICATION_JSON));
}
for (Iterator<Activity> a = listOfActivities.iterator(); a.hasNext();) {
Activity activity = a.next();
if(activity.getComplaintId().equals(complaintId)) {
listOfComplaintActivities.add(activity);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiFrom = response.readEntity(NameById.class);
listOfActivitiesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfActivitiesTo.add(nbiTo);
}
}
for (Iterator<ComplaintResponse> a = listOfResponses.iterator(); a.hasNext();) {
ComplaintResponse comResp = a.next();
if(comResp.getComplaintId().equals(complaintId)) {
listOfComplaintResponses.add(comResp);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
NameById nbiFrom = null;
if(grievance.getComplaintIsAnonymous() == 1) {
if(comResp.getResponseFrom().startsWith("STUD")) {
nbiFrom = new NameById();
nbiFrom.setName("Anonymous");
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
listOfResponsesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfResponsesTo.add(nbiTo);
}
}
break;
}
}
List<Committee> forwardsAvailable = new ArrayList<Committee>();
if(ac.getCommitteeDetails().getCommitteeType().equals("inst")) {
webTarget = client.target(DBConfig.getApiHost()).path("committees/committee/"+ac.getCommitteeDetails().getParentId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Committee c = response.readEntity(Committee.class);
forwardsAvailable.add(c);
}
else if(ac.getCommitteeDetails().getCommitteeType().equals("univ")) {
webTarget = client.target(DBConfig.getApiHost()).path("committees");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
List<Committee> availableCommittees = response.readEntity(new GenericType<List<Committee>>(){});
for (Iterator<Committee> c = availableCommittees.iterator(); c.hasNext();) {
Committee com = c.next();
if(com.getParentId().equals(ac.getCommitteeDetails().getCommitteeId())) {
forwardsAvailable.add(com);
}
}
}
if(flag == 1) {
hs.setAttribute("complaintDetails", grievance);
hs.setAttribute("complaintKeywords", k);
hs.setAttribute("complaintActivities", listOfComplaintActivities);
hs.setAttribute("activitiesFrom", listOfActivitiesFrom);
hs.setAttribute("activitiesTo", listOfActivitiesTo);
hs.setAttribute("complaintResponses", listOfComplaintResponses);
hs.setAttribute("responsesFrom", listOfResponsesFrom);
hs.setAttribute("responsesTo", listOfResponsesTo);
hs.setAttribute("forwardsAvailable", forwardsAvailable);
}
}
else if(type.equals("received")) {
List<Grievance> listOfReceivedGrievances = (List<Grievance>)hs.getAttribute("forwardedGrievances");
List<Keyword> listOfReceivedKeywords = (List<Keyword>)hs.getAttribute("forwardedKeywords");
List<Activity> listOfComplaintActivities = new ArrayList<Activity>();
List<NameById> listOfActivitiesFrom = new ArrayList<NameById>();
List<NameById> listOfActivitiesTo = new ArrayList<NameById>();
List<ComplaintResponse> listOfComplaintResponses = new ArrayList<ComplaintResponse>();
List<NameById> listOfResponsesFrom = new ArrayList<NameById>();
List<NameById> listOfResponsesTo = new ArrayList<NameById>();
int flag = 0;
int index = -1;
Grievance grievance = null;
Keyword k = null;
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
for (Iterator<Grievance> g = listOfReceivedGrievances.iterator(); g.hasNext();) {
index++;
grievance = g.next();
if(grievance.getComplaintId().equals(complaintId)) {
flag = 1;
k = listOfReceivedKeywords.get(index);
if(grievance.getComplaintIsAnonymous() != 1)
{
webTarget = client.target(DBConfig.getApiHost()).path("students/student/"+grievance.getComplaintStudentId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Student s = response.readEntity(Student.class);
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+s.getInstituteId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiInstituteName = response.readEntity(NameById.class);
hs.setAttribute("instituteName", nbiInstituteName);
hs.setAttribute("studentDetails", s);
}
int activityFlag = 0;
for (Iterator<Activity> a = listOfActivities.iterator(); a.hasNext();) {
Activity activity = a.next();
if(activity.getComplaintId().equals(grievance.getComplaintId()) && activity.getActivityType().equals("view") && activity.getActivityFrom().equals(ac.getCommitteeDetails().getCommitteeId()) && activity.getActivityTo().equals(grievance.getComplaintStudentId())) {
activityFlag = 1;
break;
}
}
if(activityFlag == 0) {
Activity viewActivity = new Activity();
viewActivity.setComplaintId(complaintId);
viewActivity.setActivityFrom(ac.getCommitteeDetails().getCommitteeId());
viewActivity.setActivityTo(grievance.getComplaintStudentId());
viewActivity.setActivityType("view");
webTarget = client.target(DBConfig.getApiHost()).path("activities/activity");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(viewActivity, MediaType.APPLICATION_JSON));
grievance.setLastActivity("view");
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("grievances/activity");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(grievance, MediaType.APPLICATION_JSON));
Status st = response.readEntity(Status.class);
webTarget = client.target(DBConfig.getApiHost()).path("students/student/"+grievance.getComplaintStudentId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Student s = response.readEntity(Student.class);
Email e = new Email();
e.setActivityFrom(ac.getCommitteeDetails().getCommitteeName());
e.setG(grievance);
e.setSubject("Complaint Viewed");
e.setTitle("Your Complaint Was Viewed");
e.setTo(s.getStudentEmail().toLowerCase());
webTarget = client.target(DBConfig.getApiHost()).path("additional/email");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(e, MediaType.APPLICATION_JSON));
}
for (Iterator<Activity> a = listOfActivities.iterator(); a.hasNext();) {
Activity activity = a.next();
if(activity.getComplaintId().equals(complaintId)) {
listOfComplaintActivities.add(activity);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiFrom = response.readEntity(NameById.class);
listOfActivitiesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfActivitiesTo.add(nbiTo);
}
}
for (Iterator<ComplaintResponse> a = listOfResponses.iterator(); a.hasNext();) {
ComplaintResponse comResp = a.next();
if(comResp.getComplaintId().equals(complaintId)) {
listOfComplaintResponses.add(comResp);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
NameById nbiFrom = null;
if(grievance.getComplaintIsAnonymous() == 1) {
if(comResp.getResponseFrom().startsWith("STUD")) {
nbiFrom = new NameById();
nbiFrom.setName("Anonymous");
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
listOfResponsesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfResponsesTo.add(nbiTo);
}
}
break;
}
}
if(flag == 1) {
hs.setAttribute("complaintDetails", grievance);
hs.setAttribute("complaintKeywords", k);
hs.setAttribute("complaintActivities", listOfComplaintActivities);
hs.setAttribute("activitiesFrom", listOfActivitiesFrom);
hs.setAttribute("activitiesTo", listOfActivitiesTo);
hs.setAttribute("complaintResponses", listOfComplaintResponses);
hs.setAttribute("responsesFrom", listOfResponsesFrom);
hs.setAttribute("responsesTo", listOfResponsesTo);
}
}
else if(type.equals("solved")) {
webTarget = client.target(DBConfig.getApiHost()).path("grievances/grievance/"+complaintId);
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Grievance grievance = response.readEntity(Grievance.class);
List<Activity> listOfComplaintActivities = new ArrayList<Activity>();
List<NameById> listOfActivitiesFrom = new ArrayList<NameById>();
List<NameById> listOfActivitiesTo = new ArrayList<NameById>();
List<ComplaintResponse> listOfComplaintResponses = new ArrayList<ComplaintResponse>();
List<NameById> listOfResponsesFrom = new ArrayList<NameById>();
List<NameById> listOfResponsesTo = new ArrayList<NameById>();
for (Iterator<Activity> a = listOfActivities.iterator(); a.hasNext();) {
Activity activity = a.next();
if(activity.getComplaintId().equals(complaintId)) {
listOfComplaintActivities.add(activity);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiFrom = response.readEntity(NameById.class);
listOfActivitiesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfActivitiesTo.add(nbiTo);
}
}
for (Iterator<ComplaintResponse> a = listOfResponses.iterator(); a.hasNext();) {
ComplaintResponse comResp = a.next();
if(comResp.getComplaintId().equals(complaintId)) {
listOfComplaintResponses.add(comResp);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
NameById nbiFrom = null;
if(grievance.getComplaintIsAnonymous() == 1) {
if(comResp.getResponseFrom().startsWith("STUD")) {
nbiFrom = new NameById();
nbiFrom.setName("Anonymous");
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
listOfResponsesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfResponsesTo.add(nbiTo);
}
}
hs.setAttribute("complaintDetails", grievance);
hs.setAttribute("complaintActivities", listOfComplaintActivities);
hs.setAttribute("activitiesFrom", listOfActivitiesFrom);
hs.setAttribute("activitiesTo", listOfActivitiesTo);
hs.setAttribute("complaintResponses", listOfComplaintResponses);
hs.setAttribute("responsesFrom", listOfResponsesFrom);
hs.setAttribute("responsesTo", listOfResponsesTo);
}
else if(type.equals("escalated")) {
List<Grievance> listOfReceivedGrievances = (List<Grievance>)hs.getAttribute("escalatedGrievances");
List<Keyword> listOfReceivedKeywords = (List<Keyword>)hs.getAttribute("escalatedKeywords");
List<Activity> listOfComplaintActivities = new ArrayList<Activity>();
List<NameById> listOfActivitiesFrom = new ArrayList<NameById>();
List<NameById> listOfActivitiesTo = new ArrayList<NameById>();
List<ComplaintResponse> listOfComplaintResponses = new ArrayList<ComplaintResponse>();
List<NameById> listOfResponsesFrom = new ArrayList<NameById>();
List<NameById> listOfResponsesTo = new ArrayList<NameById>();
int flag = 0;
int index = -1;
Grievance grievance = null;
Keyword k = null;
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
for (Iterator<Grievance> g = listOfReceivedGrievances.iterator(); g.hasNext();) {
index++;
grievance = g.next();
if(grievance.getComplaintId().equals(complaintId)) {
flag = 1;
k = listOfReceivedKeywords.get(index);
if(grievance.getComplaintIsAnonymous() != 1)
{
webTarget = client.target(DBConfig.getApiHost()).path("students/student/"+grievance.getComplaintStudentId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
Student s = response.readEntity(Student.class);
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+s.getInstituteId());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiInstituteName = response.readEntity(NameById.class);
hs.setAttribute("instituteName", nbiInstituteName);
hs.setAttribute("studentDetails", s);
}
int activityFlag = 0;
for (Iterator<Activity> a = listOfActivities.iterator(); a.hasNext();) {
Activity activity = a.next();
if(activity.getComplaintId().equals(grievance.getComplaintId()) && activity.getActivityType().equals("view") && activity.getActivityFrom().equals(ac.getCommitteeDetails().getCommitteeId()) && activity.getActivityTo().equals(grievance.getComplaintStudentId())) {
activityFlag = 1;
break;
}
}
if(activityFlag == 0) {
Activity viewActivity = new Activity();
viewActivity.setComplaintId(complaintId);
viewActivity.setActivityFrom(ac.getCommitteeDetails().getCommitteeId());
viewActivity.setActivityTo(grievance.getComplaintStudentId());
viewActivity.setActivityType("view");
webTarget = client.target(DBConfig.getApiHost()).path("activities/activity");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(viewActivity, MediaType.APPLICATION_JSON));
grievance.setLastActivity("view");
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("grievances/activity");
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.post(Entity.entity(grievance, MediaType.APPLICATION_JSON));
Status st = response.readEntity(Status.class);
}
for (Iterator<Activity> a = listOfActivities.iterator(); a.hasNext();) {
Activity activity = a.next();
if(activity.getComplaintId().equals(complaintId)) {
listOfComplaintActivities.add(activity);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiFrom = response.readEntity(NameById.class);
listOfActivitiesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+activity.getActivityTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfActivitiesTo.add(nbiTo);
}
}
for (Iterator<ComplaintResponse> a = listOfResponses.iterator(); a.hasNext();) {
ComplaintResponse comResp = a.next();
if(comResp.getComplaintId().equals(complaintId)) {
listOfComplaintResponses.add(comResp);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
NameById nbiFrom = null;
if(grievance.getComplaintIsAnonymous() == 1) {
if(comResp.getResponseFrom().startsWith("STUD")) {
nbiFrom = new NameById();
nbiFrom.setName("Anonymous");
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
}
else {
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseFrom());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
nbiFrom = response.readEntity(NameById.class);
}
listOfResponsesFrom.add(nbiFrom);
client = ClientBuilder.newClient( new ClientConfig().register( LoggingFeature.class ) );
webTarget = client.target(DBConfig.getApiHost()).path("additional/"+comResp.getResponseTo());
invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
response = invocationBuilder.get();
NameById nbiTo = response.readEntity(NameById.class);
listOfResponsesTo.add(nbiTo);
}
}
break;
}
}
if(flag == 1) {
hs.setAttribute("complaintDetails", grievance);
hs.setAttribute("complaintKeywords", k);
hs.setAttribute("complaintActivities", listOfComplaintActivities);
hs.setAttribute("activitiesFrom", listOfActivitiesFrom);
hs.setAttribute("activitiesTo", listOfActivitiesTo);
hs.setAttribute("complaintResponses", listOfComplaintResponses);
hs.setAttribute("responsesFrom", listOfResponsesFrom);
hs.setAttribute("responsesTo", listOfResponsesTo);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
}
|
package pizzaml.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import org.springframework.stereotype.Repository;
import pizzaml.entity.Item;
import pizzaml.entity.ItemSizeCost;
@Repository
public class ItemDAOImpl implements ItemDAO {
@PersistenceContext
EntityManager em;
@Override
public Item getItem(int id) {
return em.find(Item.class, id);
}
@Override
public void createItem(Item item) {
em.persist(item);
}
@Override
public void updateItem(Item item) {
em.merge(item);
}
@Override
public void deleteItem(int id) {
Item itemFromPC = getItem(id);
if( itemFromPC != null ) {
em.remove(itemFromPC);
}
}
@Override
public List<ItemSizeCost> getItemItemSizeCost(int id) {
TypedQuery<ItemSizeCost> tq = em.createQuery(
"select isc from ItemSizeCost isc"
+" join fetch isc.size"
+" join fetch isc.item"
+" where isc.item.id = :itemId",
ItemSizeCost.class);
tq.setParameter("itemId", id);
List<ItemSizeCost> itemSizeCostList = tq.getResultList();
return itemSizeCostList;
}
}
|
package com.supconit.kqfx.web.fxzf.warn.daos;
import hc.base.domains.Pageable;
import hc.orm.BasicDao;
import java.util.List;
import com.supconit.kqfx.web.fxzf.search.entities.Fxzf;
import com.supconit.kqfx.web.fxzf.warn.entities.WarnHistory;
public interface WarnHistoryDao extends BasicDao<WarnHistory, String>{
/**
* 分页查询信息列表
* @param pager
* @param condition
* @return
*/
Pageable<WarnHistory> findByPager(Pageable<WarnHistory> pager, WarnHistory condition);
/**
* 分页查询信息列表
* @param pager
* @param condition
* @return
*/
Pageable<WarnHistory> findByPagerExport(Pageable<WarnHistory> pager, WarnHistory condition);
/**
* 根据车牌号、车牌颜色、间隔时间查询已发布的告警信息
* @param license
* @param plateColor
* @param againTime
* @return
*/
List<WarnHistory> findAgainTimeData(String license, String plateColor,
Double againTime);
List<WarnHistory> AnalysisDayWarnByCondition(WarnHistory condition);
List<WarnHistory> getWarnByFxzfId(String fxzfid);
WarnHistory getWarnHistoryQbb(Fxzf warn);
}
|
package marcio.tcc.estacionamento.negocio;
/**
* Representa dados de valores a serem cobrados pelo periodo de estacionamento, bem como os intervalos de tempo envolvidos no calculo
* @author Marcio
*
*/
public class Tarifario {
public static int VALOR_HORA = 1;
public static int VALOR_INCREMENTAL = 1;
public static int INCREMENTO_MINUTOS = 15;
}
|
package cn.vector.esdemo;
import cn.vector.esdemo.entity.Book;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.ParsedAvg;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import java.math.BigDecimal;
/**
* ElasticsearchRestTemplate的简单使用
* Create By ahrenJ
* Date: 2020-08-01
*/
@SpringBootTest
public class EsRestTemplateTest {
//自动注入即可使用
@Autowired
private ElasticsearchRestTemplate esRestTemplate;
//按id查询
@Test
void testQueryBookById() {
Book book = esRestTemplate.get("1", Book.class);
Assertions.assertNotNull(book);
System.out.println(book.toString());
}
//按书名查询
@Test
void testQueryBookByTitle() {
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("title", "Java"))
.build();
SearchHits<Book> searchHits = esRestTemplate.search(searchQuery, Book.class);
//SearchHits就是查询的结果集
searchHits.get().forEach(hit -> {
System.out.println(hit.getContent());
});
}
//按价格区间查询
@Test
void testQueryBookByPriceInternal() {
BigDecimal min = new BigDecimal("15.00");
BigDecimal max = new BigDecimal("30.00");
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.rangeQuery("price")
.gte(min)
.lte(max))
.build();
SearchHits<Book> searchHits = esRestTemplate.search(searchQuery, Book.class);
searchHits.get().forEach(hit -> {
System.out.println(hit.getContent());
});
}
//按标签匹配查询
@Test
void testQueryBookByTag() {
//查询标签中含有Java和数据库的书籍
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.termsQuery("tag", "Java", "数据库"))
.build();
SearchHits<Book> searchHits = esRestTemplate.search(searchQuery, Book.class);
searchHits.get().forEach(hit -> {
System.out.println(hit.getContent());
});
}
//聚合操作-计算所有书籍的平均价格
@Test
void testAggregationBookAvgPrice() {
//聚合名为avg_price,对price字段进行聚合,计算平均值
NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
.addAggregation(AggregationBuilders.avg("avg_price").field("price"))
.build();
SearchHits<Book> searchHits = esRestTemplate.search(searchQuery, Book.class);
searchHits.get().forEach(hit -> {
System.out.println(hit.getContent());
});
//获取聚合结果
if (searchHits.hasAggregations()) {
ParsedAvg parsedAvg = searchHits.getAggregations().get("avg_price");
Assertions.assertNotNull(parsedAvg, "无聚合结果");
System.out.println(parsedAvg.getValue());
}
}
}
|
/*
* Copyright 2018 Ameer Antar.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.antfarmer.ejce.test.util;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.antfarmer.ejce.util.ObjectUtil;
import org.junit.Test;
/**
* @author Ameer Antar
*/
public class ObjectUtilTest {
@Test
public void testEquals() {
final String a = "same";
final String b = "same";
final String c = "not";
assertTrue(ObjectUtil.equals(null, null));
assertFalse(ObjectUtil.equals(a, null));
assertFalse(ObjectUtil.equals(null, a));
assertTrue(ObjectUtil.equals(a, b));
assertTrue(ObjectUtil.equals(b, a));
assertFalse(ObjectUtil.equals(a, c));
assertFalse(ObjectUtil.equals(c, a));
}
}
|
package com.example.andreasbergman.appadmin2;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
/**
* Created by andreasbergman on 23/11/16.
*/
public class EventAdapter extends ArrayAdapter<Event> {
private Activity activity;
private ArrayList<Event> lEvent;
private LayoutInflater inflater = null;
/* public EventAdapter (Activity activity, int textViewResourceId, ArrayList<Event> lEvent){
super(activity,textViewResourceId, lEvent);
try{
this.activity = activity;
this.lEvent = lEvent;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}catch (Exception e){
e.printStackTrace();
}
}
public int getCount(){
return lEvent.size();
}
public static class ViewHolder{
public TextView display_name;
}
public View getView(int position, View convertView, ViewGroup parent){
View vi = convertView;
final ViewHolder holder;
try{
if(convertView == null){
vi = inflater.inflate(R.layout.activity_event_list,null);
holder = new ViewHolder();
}
}catch (Exception e){
}
return vi;
}*/
public EventAdapter(Context context, ArrayList<Event> events){
super(context, 0, events);
}
public View getView(int position, View conertView, ViewGroup parent){
Event event = getItem(position);
if(conertView == null){
conertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_event_list, parent, false);
}
//ListView e = (ListView)conertView.findViewById(R.id.listview1);
//e.setTextAlignment(event.name);
TextView test = (TextView)conertView.findViewById(R.id.textView);
test.setText(event.getName());
return conertView;
}
}
|
package PracticeTest;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.*;
import io.github.bonigarcia.wdm.WebDriverManager;
public class FirstTestCase_Firefox {
public static WebDriver firefox_driver;
@BeforeMethod
public static void SetupChrome() {
WebDriverManager.firefoxdriver().setup();
firefox_driver = new FirefoxDriver();
firefox_driver.manage().window().maximize();
}
@Test
public void FirstTest() {
firefox_driver.get("https://google.com");
System.out.println("The Title of the Page is:" + firefox_driver.getTitle());
}
@AfterMethod
public void CloseBrowser() {
firefox_driver.close();
}
}
|
package carlos.talavera.com.project;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import static carlos.talavera.com.project.MainActivity.intentContent;
import static carlos.talavera.com.project.MainActivity.webView;
public class MediaDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Elige video o audio");
builder.setPositiveButton("Descarga video", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
intentContent = intentContent.substring("https://youtu.be/".length());
System.out.println("Vamos a buscar la canción con ID: " + intentContent);
webView.loadUrl("https://youtubemp3api.com/es/@api/button/videos/"+intentContent);
}
});
builder.setNegativeButton("Descarga audio", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
intentContent = intentContent.substring("https://youtu.be/".length());
System.out.println("Vamos a buscar la canción con ID: " + intentContent);
webView.loadUrl("https://youtubemp3api.com/es/@api/button/mp3/" + intentContent);
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
|
package com.wlc.ds.string;
import java.util.Arrays;
import org.junit.Test;
public class KmperTest {
@Test
public void testGetIndexKMP() {
String ss = "aabcbabcaabcaababc";
String tt = "abcaabcabc";
int[] next = new int[tt.length()+1];
Kmper.getNext(tt.toCharArray(), next);
System.out.println(Arrays.toString(next));
//System.out.println(Kmper.getIndexKMP(ss.toCharArray(), tt.toCharArray(), next));
}
}
|
package com.example.shreyansh.layouts;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyCustomAdapter extends BaseAdapter {
List<Student> studentList;
Activity activity;
public MyCustomAdapter(ArrayList<Student> arrayList, Activity activity) {
studentList = arrayList;
this.activity = activity;
}
public int getCount() {
return studentList.size();
}
@Override
public Object getItem(int position) {
return studentList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder viewHolder;
//Logger.log("Position : " + position + " convertView is null : " + (convertView == null));
if(convertView == null) {
LayoutInflater inflater = activity.getLayoutInflater();
//for list view
//convertView = inflater.inflate(R.layout.clock_text_include, parent, false);
//for grid view
convertView = inflater.inflate(R.layout.clock_text_grid, parent, false);
viewHolder = new MyViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (MyViewHolder) convertView.getTag();
}
viewHolder.tv1.setText(studentList.get(position).name);
viewHolder.tv2.setText(studentList.get(position).fatherName);
viewHolder.tv3.setText(studentList.get(position).motherName);
if(position%3 == 0) viewHolder.image.setImageResource(R.drawable.clock);
else if (position%3 == 1) viewHolder.image.setImageResource(R.drawable.virat);
else viewHolder.image.setImageResource(R.drawable.spiderman);
return convertView;
}
private class MyViewHolder {
private ImageView image;
private TextView tv1,tv2,tv3;
public MyViewHolder(View view){
image = (ImageView) view.findViewById(R.id.image1);
tv1 = (TextView) view.findViewById(R.id.tv1);
tv2 = (TextView) view.findViewById(R.id.tv2);
tv3 = (TextView) view.findViewById(R.id.tv3);
}
}
}
|
package com.cazimir.attendancetest.ui.dashboard;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.cazimir.attendancetest.R;
import com.cazimir.attendancetest.event.QrCodeResultReady;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
public class DashboardFragment extends Fragment {
private static final String TAG = "DashboardFragment";
private DashboardViewModel dashboardViewModel;
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel = ViewModelProviders.of(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
final TextView textView = root.findViewById(R.id.text_dashboard);
dashboardViewModel
.getText()
.observe(
this,
new Observer<String>() {
@Override
public void onChanged(@Nullable String s) {
textView.setText(s);
}
});
return root;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
Log.d(TAG, "onAttach: registering EventBus");
if (!EventBus.getDefault().isRegistered(this)) {
Log.d(TAG, "onAttach: called");
EventBus.getDefault().register(this);
}
}
@Override
public void onDetach() {
EventBus.getDefault().unregister(this);
super.onDetach();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onQrScanResultReady(QrCodeResultReady resultReady) {
Log.d(TAG, "onQrScanResultReady: resultReady: " + resultReady.getQRCode().getText());
dashboardViewModel.setText(resultReady.getQRCode().getText());
dashboardViewModel.sendToFirebase(resultReady.getQRCode());
}
}
|
package test;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.Test;
import edu.uci.ics.sdcl.firefly.Answer;
import edu.uci.ics.sdcl.firefly.report.predictive.AcrossQuestionsConsensus;
import edu.uci.ics.sdcl.firefly.report.predictive.AnswerData;
import edu.uci.ics.sdcl.firefly.report.predictive.WithinQuestionConsensus;
public class MajorityVotingTest {
HashMap<String, ArrayList<String>> answerMap = new HashMap<String, ArrayList<String>>();
HashMap<String,String> bugCoveringMap = new HashMap<String,String>();
AnswerData data;
public void setup1(){
bugCoveringMap.put("1","1");//1 yes
bugCoveringMap.put("3","3");//4 yes's
ArrayList<String> answerList = new ArrayList<String>();//2 yes's False Positive
answerList.add(Answer.YES);
answerList.add(Answer.NO);
answerList.add("IDK");
answerList.add(Answer.YES);
answerMap.put("0",answerList);
answerList = new ArrayList<String>();//1 yes False Negative
answerList.add(Answer.YES);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerMap.put("1",answerList);
answerList = new ArrayList<String>();//2 yes's True Negative
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerMap.put("2",answerList);
answerList = new ArrayList<String>();//4 yes's True positive
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerMap.put("3",answerList);
String hitFileName = "HIT00_0";
data = new AnswerData(hitFileName,answerMap,bugCoveringMap,4,4);
}
@Test
public void testComputeSignal_FirstThreshold() {
this.setup1();
WithinQuestionConsensus predictor = new WithinQuestionConsensus();
assertTrue(predictor.computeSignal(this.data));
assertEquals(1, predictor.getFalsePositives().intValue());
assertEquals(1, predictor.getTruePositives().intValue());
assertEquals(1, predictor.getFalseNegatives().intValue());
assertEquals(1, predictor.getTrueNegatives().intValue());
double extraVote = 3;
double rateOfTP =0.5;
double expectedSignalStrength = extraVote* rateOfTP;
System.out.println(predictor.computeSignalStrength(data).doubleValue());
assertEquals("Signal Strength", expectedSignalStrength, predictor.computeSignalStrength(data).doubleValue(),0.0);
//Test for number of workers
assertEquals("Workers", 4, predictor.computeNumberOfWorkers(data).intValue());
}
public void setup2(){
bugCoveringMap.put("0","0");//2 yes's
bugCoveringMap.put("1","1");//1 yes
ArrayList<String> answerList = new ArrayList<String>();//2 yes's True Positive
answerList.add(Answer.YES);
answerList.add(Answer.NO);
answerList.add("IDK");
answerList.add(Answer.YES);
answerMap.put("0",answerList);
answerList = new ArrayList<String>();//1 yes False Negative
answerList.add(Answer.YES);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerMap.put("1",answerList);
answerList = new ArrayList<String>();//2 yes's True Negative
answerList.add(Answer.YES);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerList.add(Answer.NO);
answerMap.put("2",answerList);
answerList = new ArrayList<String>();//4 yes's False Positive
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerList.add(Answer.YES);
answerMap.put("3",answerList);
String hitFileName = "HIT00_0";
data = new AnswerData(hitFileName,answerMap,bugCoveringMap,4,4);
}
@Test
public void testComputeSignal_SecondThreshold() {
this.setup2();
WithinQuestionConsensus predictor = new WithinQuestionConsensus();
assertTrue(predictor.computeSignal(this.data));
assertEquals(1, predictor.getFalsePositives().intValue());
assertEquals(1, predictor.getTruePositives().intValue());
assertEquals(1, predictor.getFalseNegatives().intValue());
assertEquals(1, predictor.getTrueNegatives().intValue());
double extraVote = 0.0;
double rateOfTP = 0.5;
double expectedSignalStrength = extraVote* rateOfTP;
assertEquals("Signal Strength",expectedSignalStrength, predictor.computeSignalStrength(data).doubleValue(),0.0);
//Test for number of workers
assertEquals("Workers", 4, predictor.computeNumberOfWorkers(data).intValue());
}
}
|
import java.util.Scanner;
class consorcio {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
float valor_prest, total_pago, saldo_devedor;
int total_prest, qtd_prest_pagas;
System.out.println("Digite o total das prestacoes");
total_prest = sc.nextInt();
System.out.println("Digite a quantidade das prestacoes pagas");
qtd_prest_pagas = sc.nextInt();
System.out.println("Digite o valor de cada prestacao");
valor_prest = sc.nextFloat();
total_pago = qtd_prest_pagas * valor_prest;
saldo_devedor = valor_prest * (total_prest - qtd_prest_pagas);
System.out.println("O total pago = " + total_pago + "\nO saldo devedor = " + saldo_devedor);
sc.close();
}
}
|
package net.trejj.talk.adapters;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import net.trejj.talk.Function;
import net.trejj.talk.R;
import net.trejj.talk.activities.main.MainActivity;
import net.trejj.talk.model.ContactInfo;
import net.trejj.talk.model.realms.User;
import net.trejj.talk.utils.RealmHelper;
import net.trejj.talk.utils.glide.GlideApp;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
/** Created by AwsmCreators * */
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.MyViewHolder>
implements Filterable {
private Context context;
private List<ContactInfo> contactList;
private List<ContactInfo> contactListFiltered;
private List<User> usersList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name, phone, invite;
RelativeLayout itemclick;
CircleImageView image;
public MyViewHolder(View view) {
super(view);
name = view.findViewById(R.id.displayName);
phone = view.findViewById(R.id.phoneNumber);
invite = view.findViewById(R.id.invite);
itemclick = view.findViewById(R.id.item_click);
image = view.findViewById(R.id.image);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// send selected contact in callback
//listener.onContactSelected(contactListFiltered.get(getAdapterPosition()));
}
});
}
}
public ContactAdapter(Context context, List<ContactInfo> contactList) {
this.context = context;
this.contactList = contactList;
this.contactListFiltered = contactList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
usersList = RealmHelper.getInstance().getListOfUsers();
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.contact_info, parent, false);
return new MyViewHolder(itemView);
}
public ExistsResult doesItExist(ContactInfo contact)
{
Boolean exists = false;
String image = "";
for(int i =0; i<usersList.size(); i++)
{
if(usersList.get(i).getPhone().equals(contact.getNumber()))
{
exists = true;
image = usersList.get(i).getThumbImg();
break;
}
}
return new ExistsResult(exists, image);
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final ContactInfo contact = contactListFiltered.get(position);
holder.name.setText(contact.getName());
holder.phone.setText(contact.getNumber());
ExistsResult exists = doesItExist(contact);
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.Q){
holder.invite.setBackgroundColor(context.getResources().getColor(R.color.white));
holder.invite.setTextColor(context.getResources().getColor(R.color.black));
holder.name.setTextColor(context.getResources().getColor(R.color.white));
holder.phone.setTextColor(context.getResources().getColor(R.color.white));
holder.itemclick.setBackgroundColor(context.getResources().getColor(R.color.black));
}
if(exists.getExists()) {
holder.invite.setVisibility(View.GONE);
GlideApp.with(context).load(exists.getImage()).into(holder.image);
}else{
holder.invite.setVisibility(View.VISIBLE);
holder.image.setImageResource(R.drawable.profile_avatar);
}
holder.itemclick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(contact.getName(),contact.getNumber());
}
});
holder.invite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
Uri uri = Uri.parse("smsto:"+contact.getNumber());
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", context.getString(R.string.msg_body)+" "+"https://play.google.com/store/apps/details?id=" + context.getPackageName());
context.startActivity(it);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
@Override
public int getItemCount() {
return contactListFiltered.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = contactList;
} else {
List<ContactInfo> filteredList = new ArrayList<>();
for (ContactInfo row : contactList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getNumber().contains(charSequence)) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<ContactInfo>) filterResults.values;
notifyDataSetChanged();
}
};
}
private void showDialog(String Contactname, String Contactnumber) {
Dialog callOptionDialog = new Dialog(context);
callOptionDialog.setContentView(R.layout.call_option_dialog);
callOptionDialog.getWindow().setBackgroundDrawable(new ColorDrawable
(Color.TRANSPARENT));
ImageView call, back, chat;
TextView name, number, charges;
call = (ImageView) callOptionDialog.findViewById
(R.id.call);
back = (ImageView) callOptionDialog.findViewById(R.id.back);
chat = callOptionDialog.findViewById(R.id.chat);
name = callOptionDialog.findViewById(R.id.contact_name);
number = callOptionDialog.findViewById(R.id.contact_number);
charges = callOptionDialog.findViewById(R.id.charges);
name.setText(Contactname);
number.setText(Contactnumber);
String callrate = Function.checkCountry(Contactnumber);
if (Contactnumber.startsWith("+")){
charges.setText("Call charges: "+callrate+" credits/min");
}else {
charges.setText("Call charges: Unknown/min");
}
call.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity)context).CallNumber(Contactnumber,Contactname);
callOptionDialog.dismiss();
}
});
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callOptionDialog.dismiss();
}
});
callOptionDialog.setCancelable(false);
callOptionDialog.show();
}
}
final class ExistsResult {
private final Boolean exists;
private final String image;
public ExistsResult(Boolean exists, String image) {
this.exists = exists;
this.image = image;
}
public String getImage() {
return image;
}
public Boolean getExists() {
return exists;
}
}
|
package algo_basic.day1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class SWEA_6808_D3_규영이와_인영이의_카드게임 {
private static int cnt;
private static int[] cardK; // 규영이
private static int[] cardI; // 인영이
private static boolean[] visited; // 방문 기록
private static int kW, iW; // 규영이와 인영이의 승리수
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int TC = Integer.parseInt(br.readLine());
for (int i = 1; i <= TC; i++) {
sb.append("#").append(i).append(" ");
st =new StringTokenizer(br.readLine());
cardK = new int[9];
cardI = new int[9];
for (int j = 0; j < 9; j++) {
//cardK.add(Integer.parseInt(st.nextToken()));
cardK[j] =Integer.parseInt(st.nextToken());
}
int count =0;
for (int j = 1; j <= 18; j++) { // 인영이 카드 생성
int c = 1;
for (int k = 0; k < 9; k++) {
if(cardK[k]== j) {
c =0;
break;
}
}
if(c==1) {
//cardI.add(c);
cardI[count] = j;
count++;
}
}
kW=0; // 초기화
iW=0;
visited = new boolean[9];
dfs(new int[9], 0); // dfs로 확인
sb.append(kW +" ").append(iW).append("\n");
}
System.out.println(sb);
System.out.println(cnt);
}
public static void dfs(int[] tmp , int r) {
if(r == 9) { // 만약 규영이의 카드가 임의의 순서로 9장이 모였다면
int ky = 0, in=0; // 규영이, 인영이 점수
for (int i = 0; i < 9; i++) {
if(tmp[i] < cardK[i]) { // 규영이와 인영이의 i번째 비교
ky+=(cardK[i]+tmp[i]); // 점수 배정
}else {
in+=(cardK[i]+tmp[i]);
}
}
if(ky > in) { // 규영이가 인영이보다 점수 가 높으면
kW++;
}else if(ky < in){ // " 낮으면 -> 비겻을 경우를 대비하여 else if 로 표현
iW++;
}
}else {
for (int i = 0; i < 9; i++) { // 방문한 적이 있는 지 없는지로 인영이 카드를 순열 한다
if(!visited[i]) {
visited[i] =true;
tmp[r] = cardI[i];
cnt++;
dfs(tmp, r+1);
visited[i] =false;
}
}
}
}
}
|
package model;
import com.opencsv.bean.ColumnPositionMappingStrategy;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
private String[] header;
private static final String[] HEADER = new String[]{"name", "surname", "age"};
@Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
super.generateHeader(bean);
return header;
}
}
|
package com.schneider.tsm.library;
import com.schneider.tsm.maillotus.MailLotus;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
/**
*
* @author SESA385697 Carlos Gonzalez Alonso @ Schneider-Electric, MDIC, TSM
* Team.
*/
public class ReadLibraryAndSend {
String emailTo;
String emailCC;
String emailBCC;
String emailSubject;
String emailBody;
String emailAttachment;
String scriptName;
public void CheckFilesAndSend() //lista los Archivos xls en la Carpeta de Output y los guarda en un string array
{
File dir = new File("C:\\softwaretest\\FileOutput"); //Directorio a listar
String[] ficheros = dir.list(); //Arreglo que guarda la lista de archivos
if (ficheros == null) //Si la lista esta vacia entonces no existen archivos
System.out.println("No hay ficheros en el directorio especificado"); //Imprime falta de Archivos
else { //Si existen entonces
for (int x=0;x<ficheros.length;x++) //Envia el nombre de Cada archivo listado en el arreglo uno por uno
{
ifexist(ficheros[x]); //Se envia la lista de Archivos a la funcion ifexist para su busqueda en
} // el xls de relaciones entre TSE y Managers
}
File dirTSEMan = new File("C:\\softwaretest\\FileOutput\\TSE_Manager");
}
public void ifexist(String idnumber)
{
try {
String cellvalue=""; //String se usara para asignar el valor de las celdas
FileInputStream file = new FileInputStream(new File("C:\\softwaretest\\LibraryTest.xls")); // xls de relaciones entre TSE y Managers
HSSFWorkbook workbook = new HSSFWorkbook(file); //declara el libro de trabajo
HSSFSheet sheet = workbook.getSheetAt(0); //declara la hoja de trabajo
Cell cell = null; //declara la celda
int sheetsize = sheet.getPhysicalNumberOfRows() ; //obtiene el numero desde 1 hasta N de Rows
for (int i = 1; i < sheetsize; i++) { //Recorre cada row
cell = sheet.getRow(i).getCell(0); //se posiciona en la celda deseada (TSE SESA)
cellvalue=cell.getStringCellValue(); //se asigna el valor del texto de la celda a cellvalue
scriptName=cellvalue;
if (idnumber.endsWith(cellvalue + ".xls")) { //verifica si el Valor de la celda(SESA) es igual al nombre del archivo
emailAttachment="C:\\softwaretest\\FileOutput\\"+idnumber;
MailLotus createscript = new MailLotus();
cell = sheet.getRow(i).getCell(1);
emailTo=cell.getStringCellValue();
cell = sheet.getRow(i).getCell(3);
emailCC=cell.getStringCellValue();
cell = sheet.getRow(i).getCell(5);
emailBCC=cell.getStringCellValue();
emailSubject="TSE "+ scriptName +" Notification: Timeout CPR & NPR Status";
emailBody="You have one or more CPR/NPR timeout items. Please find below attachment the listed items";
createscript.setMailData(emailTo, emailCC, emailBCC, emailSubject, emailBody, emailAttachment, scriptName);
createscript.createScript();
System.out.println(emailTo +", "+ emailCC +", " +emailBCC +", "+ emailSubject +", "+ emailBody +", "+ emailAttachment +", "+ scriptName);
// System.out.println("ok for:" + cellvalue);
}
}
file.close();
FileOutputStream outFile =new FileOutputStream(new File("C:\\softwaretest\\LibraryTest.xls"));
workbook.write(outFile);
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* RRuleGroup generated by hbm2java
*/
public class RRuleGroup implements java.io.Serializable {
private RRuleGroupId id;
public RRuleGroup() {
}
public RRuleGroup(RRuleGroupId id) {
this.id = id;
}
public RRuleGroupId getId() {
return this.id;
}
public void setId(RRuleGroupId id) {
this.id = id;
}
}
|
package com.MQ.www;
public class PrimeNum1To100 {
public static void main(String[] args) {
System.out.println("PrimeNumbers are:");
for(int i=4;i<=100;i++)
{
boolean flag=true;
for(int j=2;j<=i/2;++j)
{
if(i%j==0)
{
flag=false;
break;
}
}
if(flag==true)
{
System.out.println(i);
}
}
}
}
|
package Items;
import java.util.Scanner;
import java.util.Vector;
import java.io.*;
import java.util.Collections;
public class NewItems extends Vector<Item> {
Scanner sc= new Scanner(System.in);
Vector <String> storedCodes= new Vector<String>();
public NewItems() {super();}
public void loadStoredCodes(String fName) {
if(storedCodes.size()>0)storedCodes.clear();
try {
File f= new File(fName);
if(!f.exists()) return;
FileReader fr= new FileReader(f);
BufferedReader bf= new BufferedReader(fr);
String code,name, priceStr;
while((code=bf.readLine())!=null &&
(name=bf.readLine())!=null &&
(priceStr=bf.readLine())!=null )
storedCodes.add(code);
bf.close();fr.close();
}
catch(Exception e) {
System.out.println(e);
}
}
private boolean valid(String aCode) {
int i;
for(i=0;i<storedCodes.size();i++)
if(aCode.equals(storedCodes.get(i))) return false;
for(i=0;i<this.size();i++)
if(aCode.equals(this.get(i).getCode())) return false;
return true;
}
private int find (String aCode) {
for (int i=0;i<this.size();i++)
if(this.get(i).getCode().equals(aCode)) return i;
return -1;
}
public void appendToFile(String fName){
if (this.size()==0) {
System.out.println("Empty List.");
return;
}
try {
boolean append= true;
File f=new File(fName);
FileWriter fw= new FileWriter(f,append);
PrintWriter pw= new PrintWriter(fw);
for(Item x:this) {
pw.println(x.getCode());
pw.println(x.getName());
pw.println(x.getPrice());
pw.flush();
}
pw.close();fw.close();
this.loadStoredCodes(fName);
this.clear();
}
catch(Exception e) {
System.out.println(e);
}
}
public void addNewItem() {
String newCode,newName;
int price;
boolean duplicated = false, matched= true;
System.out.println("Enter new Item Details.");
do {
System.out.print(" code(format I000): ");
newCode= sc.nextLine().toUpperCase();
duplicated= !valid(newCode);
matched= newCode.matches("^I\\d{3}$");
if(duplicated) System.out.println(" The code is duplicated.");
if(!matched) System.out.println(" The code: I and 3 digits.");
}
while(duplicated ||(!matched));
System.out.print(" name: ");
newName= sc.nextLine().toUpperCase();
System.out.print(" price: ");
price = Integer.parseInt(sc.nextLine());
this.add(new Item(newCode, newName, price));
this.loadStoredCodes(newName);
System.out.println("New Item has beed added");
}
public void removeItem() {
String code;
System.out.print("Enter the code of removed Item: ");
code= sc.nextLine().toUpperCase();
int pos =find(code);
if(pos<0) System.out.println("This code does not exist.");
else {
this.remove(pos);
System.out.println("The Item" + code + "has beed removed.");
}
}
public void updatePrice() {
String code;
System.out.print("Enter the code of promoved item.");
code = sc.nextLine().toUpperCase();
int pos =find(code);
if(pos<0) System.out.println("This code does not exist.");
else {
int oldPrice= this.get(pos).getPrice();
int newPrice;
do {
System.out.print("Old Price:" + oldPrice + ", new Price: ");
newPrice= Integer.parseInt(sc.nextLine());
}
while(newPrice<oldPrice);
this.get(pos).setPrice(newPrice);
System.out.println("The Item" + code +"has beed updated. ");
}
}
public void print() {
if(this.size()==0) {
System.out.println("Empty List. ");
return;
}
System.out.println("\nITEM LIST");
System.out.println("----------------------------");
System.out.println("CODE\t"+"NAME\t"+"PRICE");
for(Item x: this)
System.out.println(x.toString());
}
}
|
package com.example.demo.dao;
import com.example.demo.pojo.User;
import java.util.List;
/**
* Created by admin on 2017/7/12.
*/
public interface UserDao {
List<User> findAll();
User findbyId(Integer id);
}
|
package com.gligor.hypnosis;
import com.gligor.hypnosis.services.TroupeDescService;
import com.gligor.hypnosis.services.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
@Service
public class DatabaseInit implements CommandLineRunner {
@Autowired
private UserService userService;
@Autowired
private TroupeDescService troupeDescService;
@Override
public void run(String... args) throws Exception {
// User user1 = new User("abc", bc.encode("123"));
// userService.createUser("abc", "123");
troupeDescService.editDescription("token", "token");
}
}
|
/**
*
*/
package com.cnk.travelogix.orgstructure.core.interceptors;
import de.hybris.platform.servicelayer.interceptor.InterceptorContext;
import de.hybris.platform.servicelayer.interceptor.InterceptorException;
import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor;
import de.hybris.platform.servicelayer.keygenerator.KeyGenerator;
import com.cnk.travelogix.orgstructure.core.model.AbstractOrganizationModel;
/**
*
*/
public class AbstractOrganizationPrepareInterceptor implements PrepareInterceptor<AbstractOrganizationModel>
{
private KeyGenerator keyGenerator;
/*
* (non-Javadoc)
*
* @see de.hybris.platform.servicelayer.interceptor.PrepareInterceptor#onPrepare(java.lang.Object,
* de.hybris.platform.servicelayer.interceptor.InterceptorContext)
*/
@Override
public void onPrepare(final AbstractOrganizationModel organization, final InterceptorContext context)
throws InterceptorException
{
organization.setUid((String) keyGenerator.generate());
}
/**
* @param keyGenerator
* the keyGenerator to set
*/
public void setKeyGenerator(final KeyGenerator keyGenerator)
{
this.keyGenerator = keyGenerator;
}
}
|
package com.li.xiaomi.xiaomi_core.app;
/**
* 作者:dell or Xiaomi Li
* 时间: 2018/3/8
* 内容:
* 最后修改:
*/
public enum ConfigType {
SHARED_PREFERENCES,
HOST_API,//网络请求的地址
CONFIGREADY,//是否完成初始化的标志位
APPLICATIO_CONTEXT,//全局上下文
ICON,
INTERCEPTOR,//okhttp的拦截器
DBNAME//数据库名
}
|
import java.util.*;
class SkipList {
private Random random;
private int size;
private int height;
private SkipListEntry head;
private SkipListEntry tail;
public SkipList() {
this.random = new Random();
this.size = 0;
this.height = 0;
this.head = new SkipListEntry(SkipListEntry.negInf, null);
this.tail = new SkipListEntry(SkipListEntry.posInf, null);
head.right = tail;
tail.left = head;
}
public int size() {
return size;
}
private int height() {
return height;
}
public SkipListEntry find(String key) {
SkipListEntry pointer = head;
while (true) {
while (!SkipListEntry.negInf.equals(pointer.right.getKey()) && pointer.right.getKey().compareTo(key) <= 0) {
pointer = pointer.right;
}
if (pointer.down != null) {
pointer = pointer.down;
} else {
break;
}
}
return pointer;
}
public Integer get(String key) {
SkipListEntry entry = find(key);
if (entry.getKey().equals(key)) {
return entry.getValue();
} else {
return null;
}
}
public void put(String key, Integer value) {
SkipListEntry pointer = find(key);
if (key.equals(pointer.getKey())) {
pointer.setValue(value);
return;
}
SkipListEntry newEntry = new SkipListEntry(key, value);
newEntry.left = pointer;
pointer.right.left = newEntry;
newEntry.right = pointer.right;
pointer.right = newEntry;
int level = 0;
while (random.nextDouble() < 0.5) {
if (level >= height) {
createNewLayer();
}
while (pointer.up == null) {
pointer = pointer.left;
}
pointer = pointer.up;
SkipListEntry e = new SkipListEntry(key, null);
e.right = pointer.right;
e.left = pointer;
e.down = newEntry;
newEntry.up = e;
pointer.right.left = e;
pointer.right = e;
newEntry = e;
level++;
}
size++;
}
public void remove(String key) {
SkipListEntry pointer = find(key);
if (!pointer.getKey().equals(key)) {
return;
}
while (pointer != null) {
SkipListEntry left = pointer.left;
SkipListEntry right = pointer.right;
left.right = right;
right.left = left;
pointer = pointer.up;
}
}
private void createNewLayer() {
SkipListEntry p1 = new SkipListEntry(SkipListEntry.negInf, null);
SkipListEntry p2 = new SkipListEntry(SkipListEntry.posInf, null);
p1.down = head;
p2.down = tail;
p1.right = p2;
p2.left = p1;
head.up = p1;
tail.up = p2;
head = p1;
tail = p2;
height++;
}
//
// public void printHorizontal()
// {
// String s = "";
// int i;
//
// SkipListEntry p;
//
// /* ----------------------------------
// Record the position of each entry
// ---------------------------------- */
// p = head;
//
// while ( p.down != null )
// {
// p = p.down;
// }
//
// i = 0;
// while ( p != null )
// {
// p.pos = i++;
// p = p.right;
// }
//
// /* -------------------
// Print...
// ------------------- */
// p = head;
//
// while ( p != null )
// {
// s = getOneRow( p );
// System.out.println(s);
//
// p = p.down;
// }
// }
//
// public String getOneRow( SkipListEntry p )
// {
// String s;
// int a, b, i;
//
// a = 0;
//
// s = "" + p.key;
// p = p.right;
//
//
// while ( p != null )
// {
// SkipListEntry q;
//
// q = p;
// while (q.down != null)
// q = q.down;
// b = q.pos;
//
// s = s + " <-";
//
//
// for (i = a+1; i < b; i++)
// s = s + "--------";
//
// s = s + "> " + p.key;
//
// a = b;
//
// p = p.right;
// }
//
// return(s);
// }
//
// public void printVertical()
// {
// String s = "";
//
// SkipListEntry p;
//
// p = head;
//
// while ( p.down != null )
// p = p.down;
//
// while ( p != null )
// {
// s = getOneColumn( p );
// System.out.println(s);
//
// p = p.right;
// }
// }
//
//
// public String getOneColumn( SkipListEntry p )
// {
// String s = "";
//
// while ( p != null )
// {
// s = s + " " + p.key;
//
// p = p.up;
// }
//
// return(s);
// }
}
|
package com.lingjuli.validatePhone;
/**
* Created by Administrator on 2016/3/3 0003.
*/
//生成手机验证码的工具类
public class validateCode {
//获取四位手机验证码的方法
public static String getValidateCode() {
String v1 = String.valueOf((int) (Math.random() * 10));
String v2 = String.valueOf((int) (Math.random() * 10));
String v3 = String.valueOf((int) (Math.random() * 10));
String v4 = String.valueOf((int) (Math.random() * 10));
String vCode = v1 + v2 + v3 + v4;
return vCode;
}
//此为测试方法,虽然不规范,但是我喜欢
public static void main(String[] args) {
System.out.printf(getValidateCode());
}
}
|
package com.pzhu.topicsys.common.mybatis.mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.RowBounds;
import com.github.pagehelper.Page;
import com.pzhu.topicsys.common.mybatis.entity.Teacher;
public interface TeacherMapper {
int deleteByPrimaryKey(String teacherId);
int insert(Teacher record);
int insertSelective(Teacher record);
Teacher selectByPrimaryKey(String teacherId);
int updateByPrimaryKeySelective(Teacher record);
int updateByPrimaryKey(Teacher record);
/**
* Desc:根据UserId获取导师
*
* @param userId
* @return
*/
Teacher selectByUserId(@Param("userId") String userId);
/**
* Desc:查询导师列表
*
* @param name
* @param rowBounds
* @return
*/
Page<Teacher> findTeachers(@Param("name") String name, RowBounds rowBounds);
}
|
package InterviewTasks_Saim_Numbers;
public class NumberOfBinary {
public static void main(String[] args) {
System.out.println(getCountOfOnes(10));
}
public static int getCountOfOnes(int n) {
String s = "";
boolean result = n > 0;
while (result) {
s = ((n % 2) == 0 ? "0" : "1") + s;
n = n / 2;
result = n > 0;
}
int count = 0;
for (char each : s.toCharArray()) {
if (each == '1') {
count++;
}
}
return count;
}
}
|
package com.open.proxy.aop;
/**
* proxy接口
*
* @author jinming.wu
* @date 2014-4-7
*/
public interface Proxy {
Object getProxy();
}
|
package com.ibiscus.myster.repository.shopper;
import org.springframework.data.repository.CrudRepository;
import com.ibiscus.myster.model.shopper.Shopper;
public interface ShopperRepository extends CrudRepository<Shopper, Long> {
Shopper getByUserId(long userId);
}
|
package com.es.phoneshop.web;
import com.es.phoneshop.model.product.Cart.Cart;
import com.es.phoneshop.model.product.Cart.CartService;
import com.es.phoneshop.model.product.Cart.HttpSessionCartService;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CartItemDeleteServlet extends HttpServlet {
private CartService cartService;
@Override
public void init() {
this.cartService = HttpSessionCartService.getInstance();
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
Cart cart = cartService.getCart(request.getSession());
Long productId = getProductIdFromPath(request);
cartService.delete(cart, productId);
response.sendRedirect(request.getContextPath() + "/cart");
}
protected Long getProductIdFromPath(HttpServletRequest request) {
return Long.valueOf(request.getPathInfo().substring(1));
}
}
|
package com.project.bookingrest;
import lombok.Data;
@Data
public class BookingStatistic {
private int booking_count;
BookingStatistic(){
}
}
|
import static java.lang.System.out;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.MenuItem;
import java.awt.Panel;
import java.awt.Point;
import java.awt.ScrollPane;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Area;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.text.html.Option;
import org.omg.CORBA.PRIVATE_MEMBER;
public class Management extends JFrame{ //繼承 JFrame的類別
/**
* @param args這裡為管理者類別
*/
/*** Fields ***/
private JMenuBar menuBar; //宣告menuBar
private JMenu fileMenu; //宣告fileMenu
private JMenu operateMenu;//宣告operateMenu
private JMenu displayMenu;//宣告displayMenu
private JMenu aboutMenu; //宣告aboutMenu
private JMenuItem menuOpen; //宣告menuOpen
private JMenuItem menuSave; //宣告menuSave
private JMenuItem menuSaveAs; //宣告menuSaveAs
private JMenuItem menuClose; //宣告menuClose
private JMenuItem menuInsert; //宣告menuInsert
private JMenuItem menuQuiry; //宣告menuQuiry
private JMenuItem menuDelete; //宣告menuDelete
private JMenuItem menuChange; //宣告menuChange
private JMenuItem menuShow; //宣告menuShow
private JMenuItem menuList; //宣告menuList
private JMenuItem menuAbout; //宣告menuAbout
private JTextArea textArea; //宣告textArea
private JLabel stateBar; //宣告stateBar
private Container contenPane;
private JFileChooser fileChooser;
public Management() {
// TODO Auto-generated constructor stub
super("pyschology academic"); //呼叫富類別建構子順便定義title
initComponents(); //初始元件外觀
initEventListeners(); //初始元件傾聽器
}
private void initComponents() {
// TODO Auto-generated method stub
setSize(400, 300); //設定視窗大小
//set選單
fileMenu = new JMenu("檔案");
operateMenu = new JMenu("操作");
displayMenu = new JMenu("顯示");
aboutMenu = new JMenu("關於");
//set選單項目
menuOpen = new JMenuItem("開啟就資料庫");
menuSave = new JMenuItem("儲存資料庫");
menuSaveAs = new JMenuItem("另存資料庫");
menuClose = new JMenuItem("離開");
menuInsert = new JMenuItem("新增");
menuQuiry = new JMenuItem("查詢");
menuDelete = new JMenuItem("刪除");
menuChange = new JMenuItem("修改");
menuShow = new JMenuItem("單筆資料顯示");
menuList = new JMenuItem("顯示全部資料");
menuAbout = new JMenuItem("關於");
menuBar = new JMenuBar(); //建立選單列
stateBar = new JLabel("未修改");
stateBar.setHorizontalAlignment(SwingConstants.CENTER); //設定文字顯示在中間
stateBar.setBorder(BorderFactory.createEtchedBorder());
textArea = new JTextArea();
textArea.setFont(new Font("細明體", Font.PLAIN, 12));
textArea.setLineWrap(true);
JScrollPane panel = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, //設定垂直拉軸有需要時就出現可以拉
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); //設定水平軸不出現
contenPane = getContentPane();
contenPane.add(stateBar,BorderLayout.SOUTH); //設定bar 在下方
contenPane.add(panel,BorderLayout.CENTER);
//add選單項目
fileMenu.add(menuOpen);
fileMenu.addSeparator(); //分隔線
fileMenu.add(menuSave);
fileMenu.add(menuSaveAs);
fileMenu.addSeparator(); //分隔線
fileMenu.add(menuClose);
operateMenu.add(menuInsert);
operateMenu.add(menuQuiry);
operateMenu.add(menuDelete);
operateMenu.add(menuChange);
displayMenu.add(menuShow);
displayMenu.add(menuList);
aboutMenu.add(menuAbout);
//add選單列
menuBar.add(fileMenu); //將檔案的選單列加入選單列
menuBar.add(operateMenu); //將操作的選單加入選單列
menuBar.add(displayMenu); //將顯示的選單加入選單列
menuBar.add(aboutMenu); //將關於的選單加入選單列
// set選單列
setJMenuBar(menuBar); //使用JFrame的setMenuBar()設置選單列
fileChooser = new JFileChooser();
}
private void initEventListeners() {
// TODO Auto-generated method stub
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //按下右上X按鈕的預設行為
menuOpen.setAccelerator( //選單項目中的開啟舊資料庫設定快捷鍵
KeyStroke.getKeyStroke(KeyEvent.VK_O, //快捷鍵為ctrl+o
InputEvent.CTRL_MASK));
menuSave.setAccelerator( //選單項目中的儲存新資料庫設定快捷鍵
KeyStroke.getKeyStroke(KeyEvent.VK_S, //設定快捷鍵為ctrl+s
InputEvent.CTRL_DOWN_MASK));
menuClose.setAccelerator( //選單項目中的離開設定快捷鍵
KeyStroke.getKeyStroke(KeyEvent.VK_Q, //設定快捷鍵為ctrl+s
InputEvent.CTRL_DOWN_MASK));
addWindowListener(new WindowAdapter() { //按下是窗關閉按鈕事件處理
public void windowCloding(WindowEvent e){
closeFile();
}
});
menuOpen.addActionListener(new ActionListener() { //選單 - 開啟舊資料庫事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
openFile();
}
});
menuSave.addActionListener(new ActionListener() { //選單 - 儲存資料庫事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
saveFile();
}
});
menuSaveAs.addActionListener(new ActionListener() { //選單 - 另存資料庫事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
saveAsFile();
}
});
menuClose.addActionListener(new ActionListener() { //選單 - 離開事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
closeFile();
}
});
menuInsert.addActionListener(new ActionListener() { //選單 - 新增的事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
insertOperate();
}
});
menuQuiry.addActionListener(new ActionListener() { //選單 - 查詢的事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
quiryOperate();
}
});
menuDelete.addActionListener(new ActionListener() { //選單 - 刪除的事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
deleteOperate();
}
});
menuChange.addActionListener(new ActionListener() { //選單 - 修改的事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
changeOperate();
}
});
menuShow.addActionListener(new ActionListener() { //選單 - 單筆顯示的事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
showDisplay();
}
});
menuList.addActionListener(new ActionListener() { //選單 - 顯示全部的事件傾聽
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
listDisplay();
}
});
menuAbout.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String msg = String.format("%25s\n來自於java程式設計實習(二)",
"pyschology database"); //編輯顯示訊息
String title = String.format("關於 pyshology database"); //編輯顯示title
// TODO Auto-generated method stub
JOptionPane.showOptionDialog(null, //設定彈出視窗
msg,title, JOptionPane.DEFAULT_OPTION, //設定彈出視窗的title和msg(內容)
JOptionPane.INFORMATION_MESSAGE,
null, null, null);
}
});
}
static Academic[] pyschologyAcademic = new Academic[100];
public static void main(String[] args) {
System.out.print(Academic.getAmount());
pyschologyAcademic[Academic.getAmount()]=new Academic("John William Atkinson"
, 1923, "2.04", 2003, "2.04","研究成就動機","美國");
// TODO Auto-generated method stub
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new Management().setVisible(true);
}
});
System.out.print(Academic.getAmount());
}
private static String show(Academic data) {
//利用String中的format方法整理字串,並將整個字串回傳
return String.format("姓名 : %-30s\n國籍 : %-12s\n生卒年 : %d %4.2f ~ %d %4.2f\n貢獻 : %s\n",
data.getName(),data.getNatiomality(),data.getBirth(),data.getBirthMathDay(),
data.getDeath(),data.getBirthMathDay(),data.getDedication()
);
}
private void openFile(){
if(stateBar.getText().equals("未修改"))
showFileDialog();
else{
int option = JOptionPane.showConfirmDialog(null,"檔案已修改,是否儲存?", "儲存檔案?",
JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE,null);
switch (option) {
case JOptionPane.YES_OPTION: saveFile();
break;
case JOptionPane.NO_OPTION: showFileDialog();
break;
}
}
}
private void saveFile() {
Path path = Paths.get(getTitle());
try{
if (Files.notExists(path)) {
saveAsFile();
} else {
//儲存檔案
try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(path.toString()),
Charset.forName(System.getProperty("fuke.encoding")));
writer.write(textArea.getText());
stateBar.setText("未修改");
} catch(IOException e) {
// TODO: handle exception
JOptionPane.showMessageDialog(null,e.toString(), "寫入檔案失敗",
JOptionPane.ERROR_MESSAGE);
}
stateBar.setText("未修改");
}
}catch(Throwable e){
JOptionPane.showMessageDialog(null, e.toString(),"寫入檔案失敗",JOptionPane.ERROR_MESSAGE);
}
}
private void saveAsFile() {
int option = fileChooser.showDialog(null, null);
if(option==JFileChooser.APPROVE_OPTION){
setTitle(fileChooser.getSelectedFile().toString());
try {
Files.createFile(Paths.get(fileChooser.getSelectedFile().toString()));
} catch(IOException e) {
// TODO: handle exception
Logger.getLogger(Management.class.getName()).log(Level.SEVERE,null,e);
}
}
}
private void closeFile() {
if (stateBar.getText().equals("未修改")) {
dispose();
} else {
int option = JOptionPane.showConfirmDialog(null,
"檔案已修改,是否儲存?","儲存檔案?",JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE,null);
switch (option) {
case JOptionPane.YES_OPTION:
saveFile();
break;
case JOptionPane.NO_OPTION:
dispose();
break;
}
}
}
private void insertOperate(){
contenPane.removeAll();
/***宣告使用變數***/
JLabel labName = new JLabel("姓 名 : ");
final JTextField texName = new JTextField(22); //建構且直接給寬度
JLabel labNationality = new JLabel("國 籍 : ");
final JTextField texNationality = new JTextField(22);
JLabel labBrith = new JLabel(" 生年:");
final JTextField texBrith = new JTextField(10);
JLabel labBrithMathDay = new JLabel("月份");
final JTextField texBrithMathDay = new JTextField(12);
JLabel labDeath = new JLabel(" 卒年:");
final JTextField texDeath = new JTextField(10);
JLabel labDeathMathDay = new JLabel("月份 ");
final JTextField texDeathMathDay = new JTextField(12);
JLabel labDedication = new JLabel("貢 獻 : ");
final JTextField texDedication = new JTextField(22);
JButton btnDetermine= new JButton("確定");
JPanel panel = new JPanel(new FlowLayout()); //宣告JPanel的容器
labName.setFont(new Font("標楷體",Font.PLAIN,16));
labNationality.setFont(new Font("標楷體",Font.PLAIN,16));
labBrith.setFont(new Font("標楷體",Font.PLAIN,16));
labBrithMathDay.setFont(new Font("標楷體",Font.PLAIN,16));
labDeath.setFont(new Font("標楷體",Font.PLAIN,16));
labBrithMathDay.setFont(new Font("標楷體",Font.PLAIN,16));
labDedication.setFont(new Font("標楷體",Font.PLAIN,16));
btnDetermine.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
String name = texName.getText(); //獲得使用者輸入的名稱
String nationality = texNationality.getText(); //獲得使用者輸入的國籍
String birth = texBrith.getText(); //獲得使用者輸入的生年
String birthMathDay = texBrithMathDay.getText(); //獲得使用者輸入的出生月份
String death = texDeath.getText(); //獲得使用者輸入的卒年
String deathMathDay = texBrithMathDay.getText(); //獲得使用者輸入的卒月
String dedication = texDedication.getText(); //獲得使用者輸入的貢獻
int birthForData = Integer.parseInt(birth);
int deathForData = Integer.parseInt(death);
pyschologyAcademic[Academic.getAmount()] = new Academic(name,
birthForData, birthMathDay, deathForData, deathMathDay, dedication, nationality);
JOptionPane.showMessageDialog(null, "新建完成");
}
});
panel.add(labName);
panel.add(texName);
panel.add(labNationality);
panel.add(texNationality);
panel.add(labDedication);
panel.add(texDedication);
panel.add(labBrith);
panel.add(texBrith);
panel.add(labBrithMathDay);
panel.add(texBrithMathDay);
panel.add(labDeath);
panel.add(texDeath);
panel.add(labDeathMathDay);
panel.add(texDeathMathDay);
panel.add(btnDetermine);
contenPane.add(panel,BorderLayout.CENTER);
}
private void quiryOperate(){
contenPane.removeAll();
JLabel labQuiryName = new JLabel("請輸入預查詢名稱:");
final JTextField texQuiryName = new JTextField(30);
JButton btnDetermine= new JButton("確定");
labQuiryName.setFont(new Font("標楷體",Font.PLAIN,16));
final Panel panel = new Panel(new FlowLayout());
panel.add(labQuiryName);
panel.add(texQuiryName);
panel.add(btnDetermine);
contenPane.add(panel,BorderLayout.CENTER);
btnDetermine.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
boolean flag=false;
String name = texQuiryName.getText();
panel.removeAll();
panel.add(textArea,BorderLayout.CENTER);
contenPane.add(panel);
textArea.setText("112");
for(int i=0;i<Academic.getAmount();i++){
if (pyschologyAcademic[i].equals(name)) { //如果相同
String msg = String.format("尋找到的資料為\n%s", show(pyschologyAcademic[i]));
textArea.setText(msg);
flag = true; //有找到
}
}
if(!flag){
textArea.setText("找不到資料");
}
}
});
}
private void deleteOperate(){
if(Academic.getAmount()>0){
pyschologyAcademic[Academic.getAmount()-1].delete();
}else {
textArea.setText("無資料可刪");
}
}
private void changeOperate(){
contenPane.removeAll();
contenPane.add(textArea);
textArea.setText("");
String msg;
if (!(Academic.getAmount()>0)) {
textArea.setText("沒有資料");
}
for(int i=0;i<Academic.getAmount();i++){
msg = String.format("第%d筆資料:%s\n",i+1,pyschologyAcademic[i].getName());
textArea.append(msg);
}
}
private void showDisplay(){
contenPane.removeAll();
textArea = new JTextArea();
textArea.setFont(new Font("細明體", Font.PLAIN, 12));
textArea.setLineWrap(true);
JScrollPane panel = new JScrollPane(textArea,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, //設定垂直拉軸有需要時就出現可以拉
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); //設定水平軸不出現
contenPane.add(textArea,BorderLayout.CENTER);
if(Academic.getAmount()==0){
textArea.setText("沒有資料");
}else {
String msg = String.format("顯示第%d筆資料\n%s",Academic.getAmount(),
show(pyschologyAcademic[Academic.getAmount()-1]));
textArea.setText(msg);
}
}
private void listDisplay(){
contenPane.removeAll();
contenPane.add(textArea);
textArea.setText(""); //清空畫面
int i=0;
JButton btnExit = new JButton("離開");
JButton btnNext = new JButton("下一頁");
JButton btnPrev = new JButton("上一頁");
boolean exit=false;
if(!(Academic.getAmount()>0)){ //判斷是否有資料,如果沒有資料
textArea.setText("沒有資料");
}else{ //如果有資料
do{
do{
System.out.println(i);
textArea.append(show(pyschologyAcademic[i])+"\n");
i++;
}while(((i<Academic.getAmount())&&((i%3)!=0)));
if ((i<=3)&&(i==Academic.getAmount())){ //只有一頁
} else if((i<=3)&&(i!=Academic.getAmount())){ //位於第一頁
} else if ((i>3)&&(i!=Academic.getAmount())){ //位於中間頁
} else { //最後一頁
}
String msg=String.format("\n。-。-。-。-。-。-。-。-。-。-。-。-。-。-。-。\n");
textArea.append(msg);
exit=true;
}while(!exit);
}
}
private void showFileDialog(){
int option = fileChooser.showDialog(null,null);
// int option=0;
//使用者按下確認按鍵
if(option == JFileChooser.APPROVE_OPTION){
try{
setTitle(fileChooser.getSelectedFile().toString());
textArea.setText("");
stateBar.setText("未修改");
String text = Readable(fileChooser.getSelectedFile().toString());
textArea.setText(text);
}catch(Throwable e){
JOptionPane.showMessageDialog(null,e.toString(),"開檔失敗",JOptionPane.ERROR_MESSAGE);
}
}
}
private String Readable(String file){
byte[] datas = null;
try {
datas = Files.readAllBytes(Paths.get(file));
} catch(IOException e) {
// TODO: handle exception
Logger.getLogger(Management.class.getName()).log(Level.SEVERE,null,e);
}
return new String(datas);
}
private void create(String file) {
// TODO Auto-generated method stub
try {
Files.createFile(Paths.get(file));
} catch(IOException e) {
// TODO: handle exception
Logger.getLogger(Management.class.getName()).log(Level.SEVERE,null,e);
}
}
private void save(String file, String text) {
// TODO Auto-generated method stub
try {
BufferedWriter writer = Files.newBufferedWriter(Paths.get(file),
Charset.forName(System.getProperty("file.encoding")));
} catch(IOException e) {
// TODO: handle exception
Logger.getLogger(Management.class.getName()).log(Level.SEVERE,null,e);
}
}
}
|
package com.SkyBlue.hr.pm.to;
import com.SkyBlue.common.annotation.Dataset;
import com.SkyBlue.common.to.BaseBean;
import lombok.Getter;
import lombok.Setter;
@Dataset(name="dsWorkInfo")
public class WorkInfoBean extends BaseBean {
@Setter
@Getter
private String hireDate,retireDate,employeementTypeCode,retireCause,probationStatus,probationExpireDate;
@Setter
@Getter
private String projectCode,jikjongCode,empCode,empName;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vpl;
import java.util.Map;
/**
*
* @author Przemysław Czuj
*/
class VplExperimentSnapshot {
private Map<String, VplObjectState> objectStates;
private Map<String, VplForce> forces;
private VplGravity gravity;
}
|
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class AdminGUI extends Menu{
public void adminGui() {
userTypeFrame = new JFrame("Administrator Menu");
userTypeFrame.setSize(400, 400);
userTypeFrame.setLocation(200, 200);
closeWindow();
userTypeFrame.setVisible(true);
deleteCustomerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
deleteCustomer = new JButton("Delete Customer");
deleteCustomer.setPreferredSize(new Dimension(250, 20));
deleteCustomerPanel.add(deleteCustomer);
deleteAccountPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
deleteAccount = new JButton("Delete Account");
deleteAccount.setPreferredSize(new Dimension(250, 20));
deleteAccountPanel.add(deleteAccount);
bankChargesPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
bankChargesButton = new JButton("Apply Bank Charges");
bankChargesButton.setPreferredSize(new Dimension(250, 20));
bankChargesPanel.add(bankChargesButton);
interestPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
interestButton = new JButton("Apply Interest");
interestPanel.add(interestButton);
interestButton.setPreferredSize(new Dimension(250, 20));
editCustomerPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
editCustomerButton = new JButton("Edit existing Customer");
editCustomerPanel.add(editCustomerButton);
editCustomerButton.setPreferredSize(new Dimension(250, 20));
navigatePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
navigateButton = new JButton("Navigate Customer Collection");
navigatePanel.add(navigateButton);
navigateButton.setPreferredSize(new Dimension(250, 20));
summaryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
summaryButton = new JButton("Display Summary Of All Accounts");
summaryPanel.add(summaryButton);
summaryButton.setPreferredSize(new Dimension(250, 20));
accountPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
accountButton = new JButton("Add an Account to a Customer");
accountPanel.add(accountButton);
accountButton.setPreferredSize(new Dimension(250, 20));
returnPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
returnButton = new JButton("Exit Admin Menu");
returnPanel.add(returnButton);
}
}
|
package ca.mohawk.jdw.shifty.server.database.activity;
/*
I, Josh Maione, 000320309 certify that this material is my original work.
No other person's work has been used without due acknowledgement.
I have not made my work available to anyone else.
Module: server
Developed By: Josh Maione (000320309)
*/
import ca.mohawk.jdw.shifty.server.model.activity.ActivityLog;
import ca.mohawk.jdw.shifty.server.utils.Utils;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.skife.jdbi.v2.StatementContext;
import org.skife.jdbi.v2.tweak.ResultSetMapper;
import static ca.mohawk.jdw.shifty.server.Shifty.company;
public class ActivityLogMapper implements ResultSetMapper<ActivityLog> {
@Override
public ActivityLog map(final int index, final ResultSet rs, final StatementContext ctx) throws SQLException{
return new ActivityLog(
company.employees().forId(rs.getLong("employee_id")),
Utils.timestamp(rs.getString("timestamp")),
rs.getString("message")
);
}
}
|
package com.mybatis.interceptor.service;
import com.mybatis.interceptor.entity.Player;
import java.util.List;
import java.util.Map;
public interface PlayerService {
List<Player> getList(Map<String,Object> params);
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.commerceservices.order.exceptions;
import de.hybris.platform.commerceservices.enums.QuoteAction;
import de.hybris.platform.core.enums.QuoteState;
/**
* Exception thrown when an action cannot be performed for a quote. Encapsulates basic quote information.
*/
public class IllegalQuoteStateException extends RuntimeException
{
private static final String EXCEPTION_MSG_FORMAT = "Action [%s] is not allowed for quote code [%s] in quote state [%s] having version [%s].";
private final QuoteAction quoteAction;
private final String quoteCode;
private final QuoteState quoteState;
private final Integer quoteVersion;
public IllegalQuoteStateException(final QuoteAction quoteAction, final String quoteCode, final QuoteState quoteState,
final Integer quoteVersion)
{
super(String.format(EXCEPTION_MSG_FORMAT, quoteAction, quoteCode, quoteState, quoteVersion));
this.quoteAction = quoteAction;
this.quoteCode = quoteCode;
this.quoteState = quoteState;
this.quoteVersion = quoteVersion;
}
public IllegalQuoteStateException(final QuoteAction quoteAction, final String quoteCode, final QuoteState quoteState,
final Integer quoteVersion, final Throwable cause)
{
super(String.format(EXCEPTION_MSG_FORMAT, quoteAction, quoteCode, quoteState, quoteVersion), cause);
this.quoteAction = quoteAction;
this.quoteCode = quoteCode;
this.quoteState = quoteState;
this.quoteVersion = quoteVersion;
}
public IllegalQuoteStateException(final QuoteAction quoteAction, final String quoteCode, final QuoteState quoteState,
final Integer quoteVersion, final String message)
{
super(message);
this.quoteAction = quoteAction;
this.quoteCode = quoteCode;
this.quoteState = quoteState;
this.quoteVersion = quoteVersion;
}
public IllegalQuoteStateException(final QuoteAction quoteAction, final String quoteCode, final QuoteState quoteState,
final Integer quoteVersion, final String message, final Throwable cause)
{
super(message, cause);
this.quoteAction = quoteAction;
this.quoteCode = quoteCode;
this.quoteState = quoteState;
this.quoteVersion = quoteVersion;
}
public QuoteAction getQuoteAction()
{
return quoteAction;
}
public String getQuoteCode()
{
return quoteCode;
}
public QuoteState getQuoteState()
{
return quoteState;
}
public Integer getQuoteVersion()
{
return quoteVersion;
}
}
|
package com.tencent.mm.plugin.monitor;
import com.tencent.mm.kernel.b.f;
import com.tencent.mm.kernel.b.g;
import com.tencent.mm.model.p;
import com.tencent.mm.plugin.monitor.a.a;
import com.tencent.mm.sdk.platformtools.x;
public class PluginMonitor extends f implements a {
public void installed() {
super.installed();
alias(a.class);
}
public void execute(g gVar) {
if (gVar.ES()) {
x.i("MicroMsg.PluginMonitor", "PluginMonitor execute PluginMonitor new SubCoreBaseMonitor");
pin(new p(b.class));
}
}
public String name() {
return "plugin-monitor";
}
}
|
package com.mirth.tools.header.builders;
public class HeaderBuilderFactory {
public static HeaderBuilder createHeaderBuilder(String extension) {
if ("jsp".equalsIgnoreCase(extension)) {
return new JspHeaderBuilder();
} else if ("java".equalsIgnoreCase(extension) || "js".equalsIgnoreCase(extension)) {
return new JavaHeaderBuilder();
} else {
return new NoOpHeaderBuilder();
}
}
}
|
package App;
import model.GameMemento;
import model.SaveState;
import resources.Constants;
import java.io.*;
import java.util.EmptyStackException;
import java.util.Stack;
import static resources.Constants.SAVE_PATH;
//Caretaker class for Memento Pattern
public class SaveStateManager {
public static Stack<GameMemento> gameHistory = new Stack<GameMemento>();
//serialise and save our game state to .txt
public static boolean SaveState(GameMemento memento){
SaveState state = memento.getState();
System.out.println("Saving...");
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(SAVE_PATH,false);
out = new ObjectOutputStream(fos);
out.writeObject(state);
out.close();
System.out.println("Saved.");
return true;
} catch (IOException ex) {
System.out.println("Error: " + ex.getMessage());
}
return false;
};
//Deserialise from the .txt and return the loaded SaveState
public static SaveState LoadState (){
SaveState loadState = new SaveState(null, null, 0, 0);
System.out.println("Loading...");
try {
FileInputStream fileInputStream = new FileInputStream(SAVE_PATH);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
loadState = (SaveState)objectInputStream.readObject();
objectInputStream.close();
fileInputStream.close();
System.out.println("Loaded.");
}
catch(FileNotFoundException ex) {
System.out.println("Save file not found: " + ex.getLocalizedMessage());
}
catch(IOException ex) {
System.out.println("IOException occurred: " + ex.getLocalizedMessage());
}
catch(ClassNotFoundException ex) {
System.out.println("ClassNotFoundException occurred: " + ex.getLocalizedMessage());
}
return loadState;
};
public static void SaveGameMemento(GameMemento memento){
//only keep stack to a size that we actually need.
if (gameHistory.size() > Constants.GAME_HISTORY_MAX_SIZE)
{
gameHistory.removeElement(gameHistory.firstElement());
}
gameHistory.push(memento);
//For debug
System.out.println("STACK: ");
PrintStack();
}
public static GameMemento Undo(int numberOfUndo){
try {
if (!canGameHistoryUndo(numberOfUndo))
{
throw new EmptyStackException();
}
for (int i = 0; i < numberOfUndo ; i++) {
gameHistory.pop();
}
return gameHistory.pop();
} catch (EmptyStackException ex)
{
throw new EmptyStackException();
}
}
private static boolean canGameHistoryUndo(int numberOfUndo){
return gameHistory.size() > numberOfUndo;
}
private static void PrintStack()
{
for (GameMemento i : gameHistory) {
System.out.println("Tile: " + i.getState().getGameBoard().getBoard() + "Board: " + i.getState().getGameBoard());
}
}
}
|
package vamk.java.assignment5;
import java.util.Arrays;
public class Customer {
private static int lastId = 0;
private int id;
private String name;
private String phone;
private Purchase[] purchases;
public Customer(String name, String phone, Purchase[] purchases) {
this.id = lastId;
this.name = name;
this.phone = phone;
this.purchases = purchases;
}
public Customer getCustomer(int id) {
return this.id == id ? this : null;
}
public Purchase[] getPurchases() {
return purchases;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", phone=" + phone
+ ", purchases=" + Arrays.toString(purchases) + "]";
}
}
|
package com.example.recuperacion2;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroup;
private RadioButton uno, dos, tres;
private EditText nombre;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup = (RadioGroup) findViewById(R.id.rGroup);
uno = (RadioButton) findViewById(R.id.rbUno);
dos = (RadioButton) findViewById(R.id.rbDos);
tres = (RadioButton) findViewById(R.id.rbTres);
nombre = (EditText) findViewById(R.id.etNombre);
}
public void Siguiente(View view){
String datosNombre = nombre.getText().toString();
String numero = "";
if(uno.isChecked()){
numero = "uno";
}
else if(dos.isChecked()){
numero = "dos";
}
else if(tres.isChecked()){
numero = "tres";
}
else{
Toast.makeText(getApplicationContext(), "Error, tienes que seleccionar un boton para mandar datos",Toast.LENGTH_LONG).show();
}
Intent i = new Intent(this, Pantalla2.class);
i.putExtra("nombre", datosNombre);
i.putExtra("numero", numero);
startActivity(i);
}
}
|
package org.shadow.dao;
import org.apache.ibatis.annotations.Param;
public interface LoginMapper {
public int verify(@Param("name")String name, @Param("password")String password);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.rajesh.mavenproject.core.dao.impl;
import com.rajesh.mavenproject.core.dao.SkillDao;
import com.rajesh.mavenproject.core.entity.Skill;
import org.springframework.stereotype.Repository;
/**
*
* @author Dell
*/
@Repository
public class SkillDaoImpl extends GenricDaoImpl<Skill>implements SkillDao{
// @Autowired
// private SessionFactory sessionFactory;
// private Session session;
// private Transaction transaction;
//
// private void startSession(){
// session=sessionFactory.openSession();
// }
// @Override
// public List<Skill> getAll() {
// startSession();
// return session.createCriteria(Skill.class).list();
// }
//
// @Override
// public void save(Skill model) {
//
// startSession();
// transaction=session.beginTransaction();
// session.saveOrUpdate(model);
// transaction.commit();
// }
//
// @Override
// public boolean delete(int id) {
//
// startSession();
// Skill skill=getById(id);
// if(skill!=null){
// transaction=session.beginTransaction();
// session.delete(skill);
// transaction.commit();
// return true;
// }
// return false;
// }
//
// @Override
// public Skill getById(int id) {
// startSession();
// return (Skill) session.get(Skill.class, id);
// }
//
}
|
package itsmap.khaledsaied.handin2;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmReceiver extends BroadcastReceiver{
private final static String TAG = "AlarmReceiver";
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.d(TAG, "onReceive");
Intent i = new Intent();
i.setClassName("itsmap.khaledsaied.handin2", "itsmap.khaledsaied.handin2.Activity_B");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
arg0.startActivity(i);
}
}
|
package models;
import dao.ResourceDao;
import play.data.validation.Constraints;
import utilities.Dependencies;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
@Entity
public final class Resource extends BaseModel<ResourceDao>{
@Constraints.Required(message = "my.required.message")
@Column(nullable = false)
public String name;
@ManyToMany(cascade= CascadeType.ALL)
public Set<Category> categories;
@Column(columnDefinition = "TEXT")
public String description;
public String fileUrl;
public String url;
public String owner;
@ManyToOne(fetch=FetchType.EAGER)
public User user;
@OneToMany(mappedBy = "parResource", cascade = CascadeType.ALL)
public List<Comment> comments;
@OneToMany(mappedBy = "resource", cascade = CascadeType.ALL)
public Set<RateResource> rates;
@Column(nullable = false)
public Date date;
public double rating;
public ResourceType resourceType;
public Resource(){}
/**
* @return A list of comments given to the resource
*/
public List<Comment> getComments() {
List<Comment> ret = new ArrayList<>();
for(Comment comment: comments)
ret.add(Dependencies.getCommentDao().findById(comment.id));
return ret;
}
/**
* @return The average rating given to the resource by users
*/
public double getRate(){
double sum = 0;
for(RateResource rateResource: rates)
sum += rateResource.rate;
double rating = sum/Math.max(rates.size(), 1);
if (this.rating != rating) {
this.rating = rating;
Dependencies.getResourceDao().update(this);
}
return rating;
}
@Override
public boolean equals(Object o) {
if (o instanceof Resource) {
Resource r = (Resource)o;
return id == r.id;
}
return false;
}
}
|
package boj1316;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int testcase = Integer.parseInt(br.readLine());
int nGroupWord = 0;
for(int i=0; i<testcase;i++) {
String str = br.readLine();
char currentChar =0;
int nChar = 0;
HashSet<Character> usedChar = new HashSet<Character>();
for(int j=0; j<str.length();j++) {
if(currentChar != str.charAt(j)) {
currentChar = str.charAt(j);
nChar++;
usedChar.add(str.charAt(j));
}
}
if(nChar == usedChar.size()) nGroupWord++;
}
bw.write(nGroupWord+"");
bw.flush();
bw.close();
br.close();
}
}
|
package com.tencent.xweb.xwalk;
import android.webkit.ValueCallback;
class g$3 implements Runnable {
final /* synthetic */ String vEI;
final /* synthetic */ ValueCallback vEJ;
final /* synthetic */ g vEV;
g$3(g gVar, String str, ValueCallback valueCallback) {
this.vEV = gVar;
this.vEI = str;
this.vEJ = valueCallback;
}
public final void run() {
if (this.vEV.vET != null) {
this.vEV.vET.evaluateJavascript(this.vEI, this.vEJ);
}
}
}
|
package it.dstech.film.service;
import java.util.List;
import it.dstech.film.model.Role;
public interface RoleService {
List<Role> findAllRoles();
List<Role> findAllAdmin(String type);
List<Role> findAllDba(String type);
Role findByType(String type);
Role findById(int id);
}
|
package com.neuedu.util;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class JdbcUtil {
private static final String URL = "jdbc:mysql://localhost:3306/zyyb?useUnicode=true&characterEncoding=utf8";
private static final String USER = "root";
private static final String PWD = "123456";
static{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
static Connection getConnetion(){
Connection conn = null;
try {
conn = DriverManager.getConnection(URL,USER,PWD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static int executeUpdata(String sql,Object[] obj){
int result = 0;
Connection conn = getConnetion();
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
if(obj != null){
for (int i = 0;i < obj.length;i++){
ps.setObject(i+1,obj[i]);
}
}
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close(conn, ps);
}
return result;
}
public static <T> List<T> executeQuery(String sql, Class<T> clz , Object... obj){
List<T> list = new ArrayList<>();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = getConnetion();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()){
T t = clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field f : fields){
String column = f.getName();
if (f.isAnnotationPresent(Column.class)){
Column c = f.getAnnotation(Column.class);
column = c.value();
}
Object value = rs.getObject(column);
f.setAccessible(true);
f.set(t,value);
}
list.add(t);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} finally {
close(conn,ps,rs);
}
return list;
}
public static <T> T executeQueryOne(String sql,RowMap<T> rowMap,Object... obj){
List<T> list = new ArrayList<>();
Connection conn = getConnetion();
PreparedStatement ps = null;
T t = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()){
t = rowMap.rowMapping(rs);
return t;
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
}
return t;
}
static void close(Connection conn,PreparedStatement ps){
try {
if (ps != null)
ps.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
static void close(Connection conn, PreparedStatement ps, ResultSet rs){
try {
if (rs != null)
rs.close();
close(conn,ps);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
package com.salesianos.dam.apirest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController // Equivalente a @Controller + @ResponseBody
@RequestMapping("task")
@RequiredArgsConstructor
public class TaskController {
private final TaskRepository repository;
@GetMapping("/")
public List<Task> findAll(){
return repository.findAll();
}
@PostMapping("/")
public ResponseEntity<Task> create(@RequestBody Task task) {
return ResponseEntity
.status(HttpStatus.CREATED)
.body((repository.save(task)));
}
// @GetMapping(/{id})
// public{
//
// }
@DeleteMapping("/{id}")
public ResponseEntity<?> DELETE(@PathVariable("id") Long id) {
repository.deleteById();
return ResponseEntity.noContent().build();
}
@PutMapping("/{id}")
public Task edit (@RequestBody Task task, @PathVariable Long id) {
Task antigua = repository.findById(id).orElse(task);
antigua.setText(task.getText());
antigua.setTitle(task.getTitle());
}
}
|
package org.globsframework.sqlstreams.annotations.typed;
import org.globsframework.metamodel.GlobType;
import org.globsframework.sqlstreams.annotations.DbFieldIsNullable;
import org.globsframework.sqlstreams.annotations.IsBigDecimal;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Retention(RUNTIME)
@Target({ElementType.FIELD})
public @interface TypedIsNullable {
GlobType TYPE = DbFieldIsNullable.TYPE;
}
|
package mazes.generators.base;
import datastructures.concrete.ChainedHashSet;
import datastructures.interfaces.IList;
import datastructures.interfaces.ISet;
import mazes.entities.Maze;
import mazes.entities.Room;
import mazes.entities.Wall;
import mazes.entities.LineSegment;
import java.awt.*;
/**
* Generates a grid-like maze, where every room is a rectangle connected to
* up to four adjacent rooms.
*/
public class GridGenerator extends BaseMazeGenerator {
private int numRows;
private int numColumns;
/**
* Accepts the number of rows and columns the grid ought to have.
*/
public GridGenerator(int numRows, int numColumns) {
this.numRows = numRows;
this.numColumns = numColumns;
}
public Maze generateBaseMaze(Rectangle boundingBox) {
Room[][] grid = this.buildRooms(boundingBox);
return new Maze(
this.extractRooms(grid),
this.extractWalls(grid),
new ChainedHashSet<>());
}
private Room[][] buildRooms(Rectangle boundingBox) {
Room[][] grid = new Room[this.numColumns][this.numRows];
double yDelta = 1.0 * boundingBox.height / this.numRows;
double xDelta = 1.0 * boundingBox.width / this.numColumns;
for (int i = 0; i < numRows; i++) {
int yMin = round(i * yDelta + boundingBox.y);
int yMax = round((i + 1) * yDelta + boundingBox.y);
for (int j = 0; j < numColumns; j++) {
int xMin = round(j * xDelta + boundingBox.x);
int xMax = round((j + 1) * xDelta + boundingBox.x);
Point center = new Point(
round((xMin + xMax) / 2.0),
round((yMin + yMax) / 2.0));
Polygon polygon = new Polygon(
new int[]{xMin, xMax, xMax, xMin},
new int[]{yMin, yMin, yMax, yMax},
4);
grid[j][i] = new Room(center, polygon);
}
}
return grid;
}
private ISet<Room> extractRooms(Room[][] grid) {
ISet<Room> rooms = new ChainedHashSet<>();
for (int x = 0; x < this.numColumns; x++) {
for (int y = 0; y < this.numRows; y++) {
rooms.add(grid[x][y]);
}
}
return rooms;
}
private ISet<Wall> extractWalls(Room[][] grid) {
ISet<Wall> walls = new ChainedHashSet<>();
for (int x = 0; x < this.numColumns; x++) {
for (int y = 0; y < this.numRows; y++) {
Room room = grid[x][y];
IList<LineSegment> segments = this.polygonToLineSegment(room.getPolygon());
if (x > 0) {
walls.add(new Wall(room, grid[x - 1][y], segments.get(3)));
}
if (y > 0) {
walls.add(new Wall(room, grid[x][y - 1], segments.get(0)));
}
}
}
return walls;
}
}
|
package fi.lassemaatta.temporaljooq.config;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;
import javax.annotation.Nonnull;
import javax.sql.DataSource;
@Configuration
public class LiquibaseConfig {
private static final String CHANGELOG_LOCATION = "classpath:migrations/db.changelog.xml";
@Bean
public SpringLiquibase liquibase(@Nonnull @Qualifier("dataSource") final DataSource dataSource,
@Nonnull final ResourceLoader resourceLoader) {
final SpringLiquibase liquibase = new SpringLiquibase();
liquibase.setChangeLog(CHANGELOG_LOCATION);
liquibase.setResourceLoader(resourceLoader);
liquibase.setDataSource(dataSource);
return liquibase;
}
}
|
package com.tencent.mm.plugin.voip.model.a;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.appbrand.jsapi.share.d;
import com.tencent.mm.protocal.c.byy;
import com.tencent.mm.protocal.c.cai;
import com.tencent.mm.protocal.c.caj;
import com.tencent.mm.protocal.c.cal;
import com.tencent.mm.sdk.platformtools.x;
public final class h extends n<cai, caj> {
public h(int i, long j, int i2, int i3, int i4, int[] iArr) {
int i5 = 0;
a aVar = new a();
aVar.dIG = new cai();
aVar.dIH = new caj();
aVar.uri = "/cgi-bin/micromsg-bin/voipRedirect";
aVar.dIF = 678;
aVar.dII = d.CTRL_INDEX;
aVar.dIJ = 1000000240;
this.diG = aVar.KT();
cai cai = (cai) this.diG.dID.dIL;
cai.rxG = i;
cai.rxH = j;
cai.seq = i2;
cai.swG = i3;
cai.swH = i4;
int i6 = 0;
for (int i7 = 0; i7 < i4; i7++) {
cal cal = new cal();
int i8 = i6 + 1;
cal.swR = iArr[i6];
i6 = i8 + 1;
cal.swS = iArr[i8];
i8 = i6 + 1;
cal.swT = iArr[i6];
int i9 = i8 + 1;
cal.swU = iArr[i8];
i6 = i9 + 1;
cal.swV = iArr[i9];
cai.swI.add(cal);
}
if (this.oKs.oJX.oPS.oLr != 0) {
i5 = (int) ((System.currentTimeMillis() - this.oKs.oJX.oPS.oLr) / 1000);
}
cai.swJ = i5;
}
public final int getType() {
return 678;
}
public final void dP(int i, int i2) {
if (i == 0 && i2 == 0) {
if (((caj) this.diG.dIE.dIL) != null) {
x.i("MicroMsg.Voip.Redirect", "roomId:%d, roomKey:%s, member:%d", new Object[]{Integer.valueOf(((caj) this.diG.dIE.dIL).rxG), Long.valueOf(((caj) this.diG.dIE.dIL).rxH), Integer.valueOf(((caj) this.diG.dIE.dIL).seq)});
return;
}
return;
}
x.i("MicroMsg.Voip.Redirect", "Redirect error");
}
public final e bLm() {
return new e() {
public final void a(int i, int i2, String str, l lVar) {
com.tencent.mm.plugin.voip.b.a.eU("MicroMsg.Voip.Redirect", "Redirect response:" + i + " errCode:" + i2 + " status:" + h.this.oKs.mStatus);
if (i2 != 0) {
com.tencent.mm.plugin.voip.b.a.eT("MicroMsg.Voip.Redirect", " redirect response with error code:" + i2);
return;
}
caj caj = (caj) h.this.bLq();
com.tencent.mm.plugin.voip.b.a.eU("MicroMsg.Voip.Redirect", "room " + caj.rxG + " member " + caj.seq + " key " + caj.rxH + " relay addr cnt " + caj.swK + " RedirectThreshold " + caj.swP + " RedirectDecision " + caj.swQ);
byy byy = new byy();
byy byy2 = new byy();
byy byy3 = new byy();
byy.suW = caj.swK;
byy.suX = caj.swL;
byy2.suW = caj.swM;
byy2.suX = caj.swN;
byy3.suW = caj.swO;
byy3.suX = caj.svB;
h.this.oKs.oJX.a(byy, byy2, byy3, caj.swP, caj.swQ);
}
};
}
}
|
package com.anexa.livechat.configuration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.val;
@Configuration
public class OdooConfiguration {
@Bean
@ConfigurationProperties(prefix = "odoo.livechat")
public OdooProperties odooProperties() {
val result = new OdooProperties();
return result;
}
}
|
package persistence;
//eq
import static com.mongodb.client.model.Filters.eq;
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import adapter.ClienteAdapter;
import entity.Cliente;
public class ClienteDao extends Dao {
public static final String CLIENTE = "cliente";
public void save(Cliente c) throws Exception {
try {
MongoCollection<Document> coll = getDB().getCollection(CLIENTE);
coll.insertOne(ClienteAdapter.toDBObject(c));
} finally {
close();
}
}
public List<Cliente> findAll() throws Exception {
MongoCursor<Document> doc = null;
try {
MongoCollection<Document> coll = getDB().getCollection(CLIENTE);
doc = coll.find().iterator();
List<Cliente> lista = new ArrayList<>();
lista.clear();
while (doc.hasNext()) {
lista.add(ClienteAdapter.getFromClienteDoc(doc.next()));
}
return lista;
} finally {
doc.close();
close();
}
}
public Cliente findByCode(Double id) throws Exception {
MongoCursor<Document> doc = null;
Cliente c = null;
try {
MongoCollection<Document> coll = getDB().getCollection(CLIENTE);
doc = coll.find(eq("_id", id)).iterator();
if(doc.hasNext()) {
c = ClienteAdapter.getFromClienteDoc(doc.next());
}
return c;
} finally {
doc.close();
close();
}
}
public void edit(Cliente c) throws Exception {
try {
MongoCollection<Document> coll = getDB().getCollection(CLIENTE);
coll.updateOne(eq("_id", c.getId()),
new Document("$set", ClienteAdapter.toDBObject(c)));
} finally {
close();
}
}
public void delete(Cliente c) throws Exception{
try {
MongoCollection<Document> coll = getDB().getCollection(CLIENTE);
coll.findOneAndDelete(eq("_id", c.getId()));
} finally {
close();
}
}
}
|
package com.tencent.mm.bg;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.x;
class d$9 implements a {
final /* synthetic */ String qVb;
final /* synthetic */ String qVg;
final /* synthetic */ Bundle rQ;
final /* synthetic */ Context val$context;
final /* synthetic */ Intent val$intent;
d$9(String str, Intent intent, String str2, Context context, Bundle bundle) {
this.qVb = str;
this.val$intent = intent;
this.qVg = str2;
this.val$context = context;
this.rQ = bundle;
}
public final void onDone() {
x.d("MicroMsg.PluginHelper", "[DEBUG] onDone Load %s", new Object[]{this.qVb});
try {
Intent intent = this.val$intent == null ? new Intent() : this.val$intent;
String str = this.qVg.startsWith(".") ? (ad.chX() + ".plugin." + this.qVb) + this.qVg : this.qVg;
intent.setClassName(ad.getPackageName(), str);
Class.forName(str, false, this.val$context.getClassLoader());
if (this.val$context instanceof Activity) {
this.val$context.startActivity(intent, this.rQ);
return;
}
intent.addFlags(268435456);
this.val$context.startActivity(intent, this.rQ);
} catch (ClassNotFoundException e) {
x.e("MicroMsg.PluginHelper", "Class Not Found when startActivity %s", new Object[]{e});
}
}
}
|
package com.mei.tododemo.tools;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import com.mei.tododemo.R;
/**
* created by meishenbo
* 2018/12/12
*/
public class VerticalView extends FrameLayout{
private final static String TAG="VerticalView";
private ViewGroup.LayoutParams layoutParams ;
public VerticalView(Context context) {
this(context,null);
}
public VerticalView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public VerticalView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
private void init(Context context, AttributeSet attrs) {
View view = LayoutInflater.from(context).inflate(R.layout.vertical_layuot, this,false);
addView(view);
View topView = view.findViewById(R.id.top_liner);
View bottomView = view.findViewById(R.id.bottom_liner);
View content_view = view.findViewById(R.id.content_liner);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.vertical_view);
float topWH = typedArray.getDimension(R.styleable.vertical_view_top_wh, 0);
if (topWH>0){
layoutParams = topView.getLayoutParams();
layoutParams.height = (int) topWH;
layoutParams.width = (int) topWH;
topView.setLayoutParams(layoutParams);
}
float bottomWH = typedArray.getDimension(R.styleable.vertical_view_bottom_wh, 0);
Log.d(TAG, "init: "+bottomWH);
if (bottomWH>0) {
layoutParams = bottomView.getLayoutParams();
layoutParams.height = (int) bottomWH;
layoutParams.width = (int) bottomWH;
bottomView.setLayoutParams(layoutParams);
}
float contentW = typedArray.getDimension(R.styleable.vertical_view_content_width, 0);
if (contentW>0) {
layoutParams = content_view.getLayoutParams();
layoutParams.width = (int)contentW;
content_view.setLayoutParams(layoutParams);
}
float contentH = typedArray.getDimension(R.styleable.vertical_view_content_height, 0);
if (contentH>0) {
layoutParams = content_view.getLayoutParams();
layoutParams.height =(int) contentW;
content_view.setLayoutParams(layoutParams);
}
int topColor = typedArray.getColor(R.styleable.vertical_view_top_color, Color.BLUE);
topView.setBackgroundColor(topColor);
int bottomColor = typedArray.getColor(R.styleable.vertical_view_bottom_color, Color.BLUE);
bottomView.setBackgroundColor(bottomColor);
int contentColor = typedArray.getColor(R.styleable.vertical_view_content_color, Color.BLUE);
content_view.setBackgroundColor(contentColor);
int topVisibility = typedArray.getInt(R.styleable.vertical_view_topVisibility, -1);
if (topVisibility!=-1) {
topView.setVisibility(VISIBLE);
}
int bottomVisibility = typedArray.getInt(R.styleable.vertical_view_bottomVisibility, -1);
if (bottomVisibility!=-1) {
bottomView.setVisibility(VISIBLE);
}
}
}
|
package com.tencent.mm.plugin.emoji.ui;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ak.a.c.d;
import com.tencent.mm.ak.a.c.l;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.emoji.e.n;
import com.tencent.mm.plugin.emoji.model.i;
import com.tencent.mm.plugin.emoji.sync.BKGLoaderManager;
import com.tencent.mm.plugin.emoji.sync.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.e.j.a;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.ao;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import com.tencent.mm.storage.emotion.EmojiGroupInfo;
import com.tencent.mm.storage.emotion.EmojiInfo;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.HeaderGridView;
import com.tencent.mm.ui.base.HeaderGridView.b;
import com.tencent.mm.ui.base.s;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
public class EmojiCustomUI extends MMActivity implements OnItemClickListener, e {
private l dYr = new 16(this);
private ProgressDialog eEX;
private OnClickListener ilA = new 11(this);
private OnClickListener ilB = new 12(this);
private final a ilC = new 13(this);
private final c ilD = new 14(this);
private d ilE = new d() {
public final byte[] h(Object... objArr) {
if (objArr != null && objArr.length > 0) {
Object obj = objArr[0];
if (obj != null && (obj instanceof EmojiInfo)) {
return com.tencent.mm.plugin.emoji.e.e.aDM().a((EmojiInfo) obj);
}
}
return null;
}
};
private EmojiInfo ilF;
private int ilk = c.ilR;
private b ill;
private HeaderGridView ilm;
private View iln;
private Button ilo;
private Button ilp;
private com.tencent.mm.plugin.emoji.sync.a.a ilq = com.tencent.mm.plugin.emoji.sync.a.a.ijf;
private View ilr;
private TextView ils;
private Button ilt;
private boolean ilu = false;
private boolean ilv = false;
private boolean ilw = false;
private a ilx = a.ilN;
private ArrayList<String> ily = new ArrayList();
private OnClickListener ilz = new 1(this);
private ag mHandler = new 17(this);
static /* synthetic */ void d(EmojiCustomUI emojiCustomUI) {
String str = "MicroMsg.emoji.EmojiCustomUI";
String str2 = "topCustom mSelectedList size:%d";
Object[] objArr = new Object[1];
objArr[0] = Integer.valueOf(emojiCustomUI.ily == null ? 0 : emojiCustomUI.ily.size());
x.i(str, str2, objArr);
if (emojiCustomUI.ily == null || emojiCustomUI.ily.size() <= 0) {
x.w("MicroMsg.emoji.EmojiCustomUI", "empty seleted list");
return;
}
emojiCustomUI.zM(emojiCustomUI.getString(R.l.emoji_top_loading));
ArrayList arrayList = emojiCustomUI.ily;
str2 = "MicroMsg.emoji.EmojiCustomUI";
String str3 = "topSyncEmoji list size:%d";
Object[] objArr2 = new Object[1];
objArr2[0] = Integer.valueOf(arrayList == null ? 0 : arrayList.size());
x.i(str2, str3, objArr2);
if (arrayList == null || arrayList.size() <= 0) {
x.i("MicroMsg.emoji.EmojiCustomUI", "empty size.");
} else {
au.DF().a(new com.tencent.mm.plugin.emoji.f.c(3, emojiCustomUI.ily), 0);
}
}
static /* synthetic */ void g(EmojiCustomUI emojiCustomUI) {
x.i("MicroMsg.emoji.EmojiCustomUI", "dz[updateSyncView status:%s]", new Object[]{emojiCustomUI.ilq.toString()});
if (emojiCustomUI.ilk != c.ilS && !emojiCustomUI.ilv) {
switch (10.ilJ[emojiCustomUI.ilq.ordinal()]) {
case 1:
emojiCustomUI.ilw = false;
emojiCustomUI.enableOptionMenu(0, true);
emojiCustomUI.aFH();
emojiCustomUI.oN(c.ilR);
return;
case 2:
emojiCustomUI.enableOptionMenu(0, false);
i.aEx();
if (BKGLoaderManager.aDK()) {
emojiCustomUI.ilw = false;
emojiCustomUI.ilr.setVisibility(0);
emojiCustomUI.a(a.ilM);
emojiCustomUI.ek(true);
} else {
i.aEx();
if (BKGLoaderManager.aEY() && !emojiCustomUI.ilw) {
emojiCustomUI.ilw = true;
emojiCustomUI.aFH();
emojiCustomUI.a(a.ilN);
}
}
if (emojiCustomUI.ilk != c.ilT) {
emojiCustomUI.oN(c.ilT);
return;
}
return;
case 3:
emojiCustomUI.ilw = false;
emojiCustomUI.enableOptionMenu(0, false);
if (emojiCustomUI.mHandler != null) {
emojiCustomUI.mHandler.removeMessages(1003);
}
emojiCustomUI.ilr.setVisibility(0);
emojiCustomUI.ek(false);
emojiCustomUI.a(a.ilL);
emojiCustomUI.oN(c.ilU);
return;
case 4:
emojiCustomUI.ilw = false;
emojiCustomUI.enableOptionMenu(0, false);
emojiCustomUI.aFH();
emojiCustomUI.oN(c.ilU);
return;
case 5:
emojiCustomUI.ilw = false;
emojiCustomUI.enableOptionMenu(0, true);
emojiCustomUI.ilr.setVisibility(0);
int cnK = i.aEA().igx.cnK();
int i = i.aEx().ije.ijp;
emojiCustomUI.ils.setText(R.l.emoji_sync_sdcard_full);
emojiCustomUI.ils.setText(String.format(emojiCustomUI.getString(R.l.emoji_sync_sdcard_full), new Object[]{Integer.valueOf(i - cnK), Integer.valueOf(i)}));
emojiCustomUI.ilt.setVisibility(4);
emojiCustomUI.oN(c.ilU);
return;
case 6:
emojiCustomUI.ilw = false;
emojiCustomUI.enableOptionMenu(0, true);
emojiCustomUI.aFH();
emojiCustomUI.oN(c.ilR);
return;
default:
return;
}
}
}
static /* synthetic */ void j(EmojiCustomUI emojiCustomUI) {
String str = "MicroMsg.emoji.EmojiCustomUI";
String str2 = "deleteEmoji mSelectedList size:%d";
Object[] objArr = new Object[1];
objArr[0] = Integer.valueOf(emojiCustomUI.ily == null ? 0 : emojiCustomUI.ily.size());
x.i(str, str2, objArr);
if (emojiCustomUI.ily == null || emojiCustomUI.ily.size() <= 0) {
x.w("MicroMsg.emoji.EmojiCustomUI", "empty seleted list");
return;
}
emojiCustomUI.zM(emojiCustomUI.getString(R.l.emoji_delete_loading));
ArrayList arrayList = emojiCustomUI.ily;
str2 = "MicroMsg.emoji.EmojiCustomUI";
String str3 = "deleteSyncEmoji list size:%d";
Object[] objArr2 = new Object[1];
objArr2[0] = Integer.valueOf(arrayList == null ? 0 : arrayList.size());
x.i(str2, str3, objArr2);
if (arrayList == null || arrayList.size() <= 0) {
x.i("MicroMsg.emoji.EmojiCustomUI", "empty size.");
} else {
au.DF().a(new com.tencent.mm.plugin.emoji.f.c(2, emojiCustomUI.ily), 0);
}
x.i("MicroMsg.emoji.EmojiCustomUI", "touchBatchEmojiBackup over emoji size. need touch :%b", new Object[]{Boolean.valueOf(emojiCustomUI.ilu)});
if (emojiCustomUI.ilu) {
emojiCustomUI.ilu = false;
au.HU();
com.tencent.mm.model.c.DT().set(348162, Boolean.valueOf(true));
com.tencent.mm.plugin.emoji.c.a.aDH();
}
emojiCustomUI.aFI();
}
private void a(a aVar) {
x.i("MicroMsg.emoji.EmojiCustomUI", "dz[updateButtonType,button type:%s]", new Object[]{aVar.toString()});
this.ilx = aVar;
switch (10.ilI[aVar.ordinal()]) {
case 1:
this.ilt.setVisibility(4);
return;
case 2:
this.ilt.setVisibility(0);
this.ilt.setText(R.l.emoji_sync_start_sync);
return;
case 3:
this.ilt.setVisibility(0);
this.ilt.setText(R.l.emoji_sync_stop_sync);
return;
default:
return;
}
}
private void ek(boolean z) {
int cnK = i.aEA().igx.cnK();
int i = i.aEx().ije.ijp;
if (cnK != i || z) {
int i2;
if (i == 0) {
i2 = cnK;
} else {
i2 = 0;
}
i += i2;
this.ils.setText(String.format(getString(z ? R.l.emoji_sync_syncing_not_in_wifi : R.l.emoji_sync_pause_not_in_wifi), new Object[]{Integer.valueOf(i - cnK), Integer.valueOf(i)}));
return;
}
this.ils.setText(R.l.emoji_sync_sync_start_not_in_wifi);
}
public void onCreate(Bundle bundle) {
long currentTimeMillis = System.currentTimeMillis();
super.onCreate(bundle);
this.ill = new b(this);
this.ill.aFM();
initView();
i.aEx().ej(true);
oN(c.ilR);
au.HU();
x.i("MicroMsg.emoji.EmojiCustomUI", "[cpan] touch batch emoji download from EmojiCustomUI needDownload:%b", new Object[]{Boolean.valueOf(((Boolean) com.tencent.mm.model.c.DT().get(aa.a.sOY, Boolean.valueOf(true))).booleanValue())});
if (((Boolean) com.tencent.mm.model.c.DT().get(aa.a.sOY, Boolean.valueOf(true))).booleanValue()) {
au.DF().a(new com.tencent.mm.plugin.emoji.f.e(), 0);
}
i.aEA().igx.c(this.ilC);
h.mEJ.a(406, 9, 1, false);
h.mEJ.a(406, 11, System.currentTimeMillis() - currentTimeMillis, false);
}
protected void onResume() {
super.onResume();
com.tencent.mm.plugin.emoji.sync.a aEx = i.aEx();
c cVar = this.ilD;
BKGLoaderManager bKGLoaderManager = aEx.ije;
if (bKGLoaderManager.ijD == null) {
bKGLoaderManager.ijD = new HashSet();
}
if (!bKGLoaderManager.ijD.contains(cVar)) {
bKGLoaderManager.ijD.add(cVar);
}
aFI();
au.DF().a(698, this);
}
protected void onPause() {
super.onPause();
com.tencent.mm.plugin.emoji.sync.a aEx = i.aEx();
c cVar = this.ilD;
BKGLoaderManager bKGLoaderManager = aEx.ije;
if (bKGLoaderManager.ijD == null) {
bKGLoaderManager.ijD = new HashSet();
}
if (bKGLoaderManager.ijD.contains(cVar)) {
bKGLoaderManager.ijD.remove(cVar);
}
au.DF().b(698, this);
}
protected void onDestroy() {
super.onDestroy();
i.aEA().igx.d(this.ilC);
i.aEx().ej(false);
BKGLoaderManager bKGLoaderManager = i.aEx().ije;
if (bKGLoaderManager.ijv) {
bKGLoaderManager.ijv = false;
}
}
protected final int getLayoutId() {
return R.i.emoji_custom;
}
protected final int getForceOrientation() {
return 1;
}
protected final void initView() {
this.ilr = getLayoutInflater().inflate(R.i.emoji_custom_header, null);
this.ils = (TextView) this.ilr.findViewById(R.h.sync_status);
this.ilt = (Button) this.ilr.findViewById(R.h.sync_action_btn);
this.ilt.setOnClickListener(this.ilz);
this.ilm = (HeaderGridView) findViewById(R.h.settings_emoticons_custom_grid);
HeaderGridView headerGridView = this.ilm;
View view = this.ilr;
ListAdapter adapter = headerGridView.getAdapter();
if (adapter == null || (adapter instanceof HeaderGridView$c)) {
HeaderGridView.a aVar = new HeaderGridView.a((byte) 0);
b bVar = new b(headerGridView, headerGridView.getContext());
bVar.addView(view);
aVar.view = view;
aVar.tsv = bVar;
aVar.data = null;
aVar.isSelectable = false;
headerGridView.tsu.add(aVar);
if (adapter != null) {
((HeaderGridView$c) adapter).mDataSetObservable.notifyChanged();
}
this.ilm.setAdapter$159aa965(this.ill);
this.ilm.setOnItemClickListener(this);
this.ilm.setFocusableInTouchMode(false);
this.iln = findViewById(R.h.settings_emoticons_custom_footer);
this.ilo = (Button) findViewById(R.h.settings_emoticons_delete);
this.ilo.setOnClickListener(this.ilA);
this.ilp = (Button) findViewById(R.h.settings_emoticons_top);
this.ilp.setOnClickListener(this.ilB);
return;
}
throw new IllegalStateException("Cannot add header view to grid -- setAdapter has already been called.");
}
public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
if (this.ill != null) {
int headerViewCount = i - (this.ilm.getHeaderViewCount() * 5);
if (this.ilk == c.ilR && headerViewCount == this.ill.aFL()) {
au.HU();
if (com.tencent.mm.model.c.isSDCardAvailable()) {
if (this.ill.aFL() >= n.aEj()) {
com.tencent.mm.ui.base.h.a(this, getString(R.l.emoji_upper_limit_warning), "", new 18(this));
} else {
com.tencent.mm.pluginsdk.ui.tools.l.P(this);
}
h.mEJ.h(11596, new Object[]{Integer.valueOf(0)});
} else {
s.gH(this);
return;
}
}
if (this.ilk == c.ilS && headerViewCount < this.ill.aFL()) {
EmojiInfo oO = this.ill.oO(headerViewCount);
d dVar = null;
if (view != null) {
dVar = (d) view.getTag();
}
String Xh;
if (oO.field_catalog == EmojiGroupInfo.tcz) {
com.tencent.mm.ui.base.h.i(this.mController.tml, R.l.chatting_can_not_del_sys_smiley, R.l.chatting_can_not_del_sys_smiley).show();
} else if (this.ily.contains(oO.Xh())) {
Xh = oO.Xh();
if (this.ily != null) {
this.ily.remove(Xh);
}
if (dVar != null) {
dVar.ilY.setChecked(false);
this.ill.notifyDataSetChanged();
}
x.i("MicroMsg.emoji.EmojiCustomUI", "unselected md5:%s", new Object[]{oO.Xh()});
} else {
Xh = oO.Xh();
if (this.ily != null) {
this.ily.add(Xh);
}
if (dVar != null) {
dVar.ilY.setChecked(true);
}
x.i("MicroMsg.emoji.EmojiCustomUI", "selected md5:%s", new Object[]{oO.Xh()});
}
aFG();
if (dVar == null) {
this.ill.notifyDataSetChanged();
}
}
}
}
protected void onActivityResult(int i, int i2, Intent intent) {
x.d("MicroMsg.emoji.EmojiCustomUI", "onActivityResult: requestCode[%d],resultCode:[%d]", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
if (i2 == -1) {
switch (i) {
case 205:
if (intent != null) {
Intent intent2 = new Intent();
intent2.putExtra("CropImageMode", 3);
au.HU();
intent2.putExtra("CropImage_OutputPath", com.tencent.mm.model.c.Gg());
com.tencent.mm.plugin.emoji.b.ezn.a(intent2, 206, this, intent);
return;
}
return;
case 206:
if (intent == null) {
x.e("MicroMsg.emoji.EmojiCustomUI", "onActivityResult MAT_IMAGE_IN_CROP_ACTIVITY return null.");
return;
}
String stringExtra = intent.getStringExtra("CropImage_OutputPath");
int intExtra = intent.getIntExtra("emoji_type", 0);
if (stringExtra != null && stringExtra.length() > 0) {
stringExtra = stringExtra.substring(stringExtra.lastIndexOf(47) + 1);
StringBuilder stringBuilder = new StringBuilder();
au.HU();
String stringBuilder2 = stringBuilder.append(com.tencent.mm.model.c.Gg()).append(stringExtra).toString();
this.ilF = i.aEA().igx.Zy(stringExtra);
com.tencent.mm.ui.tools.a.b abg = com.tencent.mm.ui.tools.a.b.abg(stringBuilder2);
abg.fi = com.tencent.mm.k.b.Ay();
abg.Gh(com.tencent.mm.k.b.Az()).a(new 2(this, intExtra, stringExtra));
return;
}
return;
case 214:
if (this.ill != null) {
this.ill.aFM();
this.ill.notifyDataSetChanged();
return;
}
return;
default:
x.e("MicroMsg.emoji.EmojiCustomUI", "onActivityResult: not found this requestCode");
return;
}
}
}
public void onBackPressed() {
if (this.ilk == c.ilS) {
oN(c.ilR);
} else {
super.onBackPressed();
}
}
private void oN(int i) {
long currentTimeMillis = System.currentTimeMillis();
this.ilk = i;
switch (10.ilK[i - 1]) {
case 1:
setBackBtn(new 3(this));
enableBackMenu(true);
addTextOptionMenu(0, getString(R.l.emoji_store_custom_mgr), new 4(this));
this.iln.setVisibility(8);
aFI();
aFE();
break;
case 2:
setBackBtn(new 5(this));
addTextOptionMenu(0, getString(R.l.app_finish), new 6(this));
this.iln.setVisibility(0);
aFH();
aFG();
break;
case 3:
aFF();
break;
case 4:
break;
}
aFF();
if (this.ill != null) {
this.ill.aFM();
this.ill.notifyDataSetChanged();
}
x.d("MicroMsg.emoji.EmojiCustomUI", "updateMode use time:%d", new Object[]{Long.valueOf(System.currentTimeMillis() - currentTimeMillis)});
}
private void aFE() {
if (this.ily != null) {
this.ily.clear();
}
x.i("MicroMsg.emoji.EmojiCustomUI", "clear md5 list. updateMode NORMAL");
}
private void aFF() {
this.iln.setVisibility(this.ilk == c.ilS ? 0 : 8);
}
private void aFG() {
if (this.ilk == c.ilS) {
if ((this.ily == null ? 0 : this.ily.size()) > 0) {
this.ilo.setText(getResources().getString(R.l.app_delete));
this.ilo.setEnabled(true);
this.ilp.setEnabled(true);
} else {
this.ilo.setText(getResources().getString(R.l.app_delete));
this.ilo.setEnabled(false);
this.ilp.setEnabled(false);
}
setMMTitle(getResources().getString(R.l.emoji_select_count, new Object[]{Integer.valueOf(r0)}));
}
}
private boolean zL(String str) {
String str2 = str;
com.tencent.mm.ui.base.h.a(this.mController.tml, str2, "", "", getString(R.l.i_know_it), null, null);
return true;
}
private void aFH() {
if (this.mHandler != null) {
this.mHandler.sendEmptyMessageDelayed(1003, 0);
}
}
private void aFI() {
boolean z = true;
i.aEx();
if (ao.isConnected(ad.getContext())) {
if (this.ill == null || this.ill.aFL() <= n.aEj()) {
z = false;
} else {
this.ilu = true;
this.ilr.setVisibility(0);
int i = R.l.emoji_sync_delete_emoji;
this.ils.setTextColor(getResources().getColor(R.e.red));
this.ils.setText(getString(i, new Object[]{Integer.valueOf(n.aEj())}));
this.ilt.setVisibility(8);
this.ill.notifyDataSetChanged();
enableOptionMenu(0, true);
this.ilv = true;
}
if (!z) {
this.ilv = false;
return;
}
return;
}
aFH();
}
public final void a(int i, int i2, String str, com.tencent.mm.ab.l lVar) {
x.i("MicroMsg.emoji.EmojiCustomUI", "errType:%d, errCode:%d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
if (lVar instanceof com.tencent.mm.plugin.emoji.f.c) {
switch (((com.tencent.mm.plugin.emoji.f.c) lVar).eKI) {
case 2:
aFs();
if (i == 0 && i2 == 0) {
int i3 = 0;
while (true) {
int i4 = i3;
if (i4 < this.ily.size()) {
x.i("MicroMsg.emoji.EmojiCustomUI", "mSelectedList md5:%s", new Object[]{this.ily.get(i4)});
h.mEJ.k(10613, (String) this.ily.get(i4));
i3 = i4 + 1;
} else {
com.tencent.mm.plugin.emoji.sync.a aEx = i.aEx();
ArrayList arrayList = this.ily;
BKGLoaderManager bKGLoaderManager = aEx.ije;
String str2 = "MicroMsg.BKGLoader.BKGLoaderManager";
String str3 = "cleanUploadTasks size%s";
Object[] objArr = new Object[1];
objArr[0] = Integer.valueOf(arrayList == null ? 0 : arrayList.size());
x.i(str2, str3, objArr);
if (bKGLoaderManager.ijB != null && arrayList != null && bKGLoaderManager.ijB.size() > 0 && arrayList.size() > 0) {
com.tencent.mm.plugin.emoji.sync.d dVar;
ArrayList arrayList2 = new ArrayList();
Iterator it = arrayList.iterator();
while (it.hasNext()) {
String str4 = (String) it.next();
if (!bi.oW(str4)) {
Iterator it2 = bKGLoaderManager.ijB.iterator();
while (it2.hasNext()) {
dVar = (com.tencent.mm.plugin.emoji.sync.d) it2.next();
if (!bi.oW(dVar.getKey()) && dVar.getKey().equalsIgnoreCase(str4)) {
arrayList2.add(dVar);
}
}
}
}
if (bKGLoaderManager.ijB != null && bKGLoaderManager.ijB.size() > 0 && arrayList2.size() > 0) {
Iterator it3 = arrayList2.iterator();
while (it3.hasNext()) {
bKGLoaderManager.ijB.remove((com.tencent.mm.plugin.emoji.sync.d) it3.next());
x.i("MicroMsg.BKGLoader.BKGLoaderManager", "clean upload task :%s", new Object[]{dVar.getKey()});
}
}
arrayList2.clear();
}
i.aEA().igx.dt(this.ily);
aFE();
aFG();
this.mHandler.sendEmptyMessageDelayed(1004, 100);
return;
}
}
}
x.i("MicroMsg.emoji.EmojiCustomUI", "delete failed");
zL(getString(R.l.emoji_top_failed));
return;
break;
case 3:
aFs();
if (i == 0 && i2 == 0) {
i.aEA().igx.du(this.ily);
aFE();
aFG();
this.mHandler.sendEmptyMessageDelayed(1004, 100);
return;
}
zL(getString(R.l.emoji_top_failed));
return;
default:
return;
}
}
x.w("MicroMsg.emoji.EmojiCustomUI", "no emoji operate");
}
private void zM(String str) {
getString(R.l.app_tip);
this.eEX = com.tencent.mm.ui.base.h.a(this, str, true, new 9(this));
}
private void aFs() {
if (this.eEX != null && this.eEX.isShowing()) {
this.eEX.dismiss();
}
}
}
|
package vegoo.stockcommon.db.redis.jgcc;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.google.common.base.Strings;
import vegoo.commons.DateUtil;
import vegoo.commons.redis.RedisService;
import vegoo.stockcommon.bo.JgccService;
import vegoo.stockcommon.dao.JgccDao;
import vegoo.stockcommon.db.redis.RedisBoServiceImpl;
@Component (immediate = true)
public class JgccServiceImpl extends RedisBoServiceImpl implements JgccService, ManagedService {
@Reference protected RedisService redis;
static String key4Jgcc(String stockCode, Date rDate) {
return key4Jgcc(stockCode, DateUtil.formatDate(rDate));
}
static String key4Jgcc(String stockCode, String rDate) {
return getKey(TBL_JGCC, stockCode, rDate);
}
@Override
public void updated(Dictionary<String, ?> properties) throws ConfigurationException {
// TODO Auto-generated method stub
}
@Override
public boolean isNewJgcc(JgccDao dao, boolean deleteOld) {
String oldTag = redis.hget(key4Jgcc(dao.getScode(), dao.getReportDate()), "DTAG"+dao.getJglx());
return oldTag ==null || !oldTag.equals(dao.getDataTag()+"");
}
@Override
public boolean existJgcc(String scode, Date reportDate) {
String key = key4Jgcc(scode, reportDate);
return redis.exists(key);
}
@Override
public void insertJgcc(JgccDao dao) {
if(Strings.isNullOrEmpty(dao.getScode())||dao.getReportDate()==null) {
return;
}
Map<String, String> props = new HashMap<>();
int i = dao.getJglx();
props.put("CNT"+i, String.valueOf(dao.getCount()));
props.put("HN"+i, String.valueOf(dao.getShareHDNum()));
props.put("VP"+i, String.valueOf(dao.getvPosition()));
props.put("ZZB"+i, String.valueOf(dao.getTabRate()));
props.put("LTZB"+i, String.valueOf(dao.getLtzb()));
props.put("DTAG"+i, String.valueOf(dao.getDataTag()));
redis.hmset(key4Jgcc(dao.getScode(), dao.getReportDate()), props);
}
@Override
public double getLtzb(String stockCode, Date rdate, int jglx) {
return getFieldValue(stockCode, rdate, jglx,"LTZB");
}
@Override
public double getLtzb(String stockCode, Date rdate, int[] jglxs) {
return sumFieldValues(stockCode, rdate, jglxs, "LTZB");
}
@Override
public double getZzb(String stkcode, Date rDate, int[] jglxs) {
return sumFieldValues(stkcode, rDate, jglxs, "ZZB");
}
@Override
public double getZzb(String stkcode, Date rDate, int jglx) {
return getFieldValue(stkcode, rDate, jglx, "ZZB");
}
public double getCount(String stockCode, Date rdate, int jglx) {
return getFieldValue(stockCode, rdate, jglx,"CNT");
}
@Override
public double getAmount(String stockCode, Date rdate, int jglx) {
return getFieldValue(stockCode, rdate, jglx,"VP");
}
@Override
public double getVolume(String stockCode, Date rdate, int jglx) {
return getFieldValue(stockCode, rdate, jglx,"HN");
}
@Override
public void settleJgcc(boolean reset) {
// TODO Auto-generated method stub
}
protected double getFieldValue(String stockCode, Date rdate, int jglx, String field) {
String key = key4Jgcc(stockCode, rdate);
return redis.getDoubleValue(key, field+jglx);
}
protected double sumFieldValues(String stockCode, Date rdate, int[] jglxs, String field) {
double result = 0;
for(int lx : jglxs) {
result += getFieldValue(stockCode, rdate, lx, field);
}
return result;
}
}
|
package com.example.demo.quartz;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* 描述:定时器类
* @author Ay
* @date 2017/11/18
*/
public class TestTask {
//日志对象
private static final Logger logger = LogManager.getLogger(TestTask.class);
public void run() {
logger.info("定时器运行了!!!");
}
}
|
package com.example.homework.app;
import com.example.homework.model.*;
import java.util.SortedMap;
public class Test {
public static void main(String[] args) {
ShapeCalculator shapeCalculator = new ShapeCalculator();
Line2D line2D = new Line2D(2.1, 2.2, 1.5, -1.8);
LineCalc lineCalc = new LineCalc();
System.out.println(line2D.toString() + lineCalc.lineLength(line2D));
Circle circle = new Circle(2.5);
System.out.println(circle.toString() + shapeCalculator.circleArea(circle));
Rectangle rectangle = new Rectangle(4,5);
System.out.println(rectangle.toString() + shapeCalculator.rectangleArea(rectangle));
Ball ball = new Ball(6);
System.out.println(ball.toString() + shapeCalculator.ballVolume(ball));
Cube cube = new Cube(5);
System.out.println(cube.toString() + shapeCalculator.cubeVolume(cube));
}
}
|
package com.example.codebind.linkingactivities;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class deleteAMove extends AppCompatActivity {
DatabaseHelper myDb;
EditText deleteMoveName;
Button btnDeleteMove;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_amove);
myDb = new DatabaseHelper(this);
deleteMoveName = (EditText)findViewById(R.id.txtMoveToDelete);
btnDeleteMove = (Button)findViewById(R.id.btnDeleteThisMove);
DeleteData();
}
public void DeleteData() {
btnDeleteMove.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
String deletedMove;
Integer deletedRows = myDb.deleteData(deleteMoveName.getText().toString());
deletedMove=deleteMoveName.getText().toString();
if(deletedRows > 0)
Toast.makeText(deleteAMove.this,"Goodbye, '"+deletedMove+"'!",Toast.LENGTH_LONG).show();
else
Toast.makeText(deleteAMove.this,"Oops! '"+deletedMove+"' Not Deleted",Toast.LENGTH_LONG).show();
}
}
);
}
}
|
package com.cyz.staticsystem.finance.controller;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.cyz.staticsystem.common.excel.ExcelExpUtils;
import com.cyz.staticsystem.common.excel.ExpParamBean;
import com.cyz.staticsystem.common.page.Page;
import com.cyz.staticsystem.common.util.AjaxUtils;
import com.cyz.staticsystem.common.util.Utils;
import com.cyz.staticsystem.finance.model.AccountOperaTotal;
import com.cyz.staticsystem.finance.model.OperaDate;
import com.cyz.staticsystem.finance.service.AccountOperaTotalService;
import com.cyz.staticsystem.store.model.Store;
import com.cyz.staticsystem.store.service.StoreService;
/**
* 描述:运营合计模块controller类,负责页面分发与跳转
*
* @author maggie
* @version 1.0 2017-03-26
*/
@Controller
@RequestMapping("accountOperaTotal")
public class AccountOperaTotalController{
@Resource
private AccountOperaTotalService accountOperaTotalService;
@Resource
private StoreService storeService;
/**
* 进入运营数据汇总列表页面
* @return ModelAndView
*/
@RequestMapping("/toListAccountOperaTotal")
public ModelAndView toList(HttpServletRequest request){
ModelAndView mv = new ModelAndView("WEB-INF/jsp/finance/accountOperaTotal/listAccountOperaTotal");
Store store = new Store();
store.setIsDelete(0);
boolean isAdmin = true;
if(!Utils.isSuperAdmin(request)){
store.setOwnerUserId(Utils.getLoginUserInfoId(request));
isAdmin = false;
}
mv.addObject("store",storeService.listByCondition(store));
mv.addObject("isAdmin",isAdmin);
return mv;
}
/**
* 修改方法
* @param accountOperaTotal AccountOperaTotal:实体对象
* @param response HttpServletResponse
* @return: ajax输入json字符串
* */
@RequestMapping("/updateAccountOperaTotal")
public void updateTotal(AccountOperaTotal accountOperaTotal,String type,HttpServletRequest request,HttpServletResponse response){
//修改深运营表
AjaxUtils.sendAjaxForObjectStr(
response,accountOperaTotalService.updateDeepTotal(accountOperaTotal));
}
/**
* 根据条件查找列表方法
* @param operaDate OperaDate:实体对象(查询条件)
* @param request HttpServletRequest
* @param response HttpServletResponse
* @param page Page:分页对象
* @return: ajax输入json字符串
*/
@RequestMapping("/listAccountOperaTotal")
public void listByCondition(AccountOperaTotal accountOperaTotal,String type,HttpServletRequest request,
HttpServletResponse response, Page page){
accountOperaTotal.setPage(page);
if(accountOperaTotal.getStoreId()!=""&&accountOperaTotal.getStoreId()!=null){
Store s = storeService.getByPrimaryKey(accountOperaTotal.getStoreId());
accountOperaTotal.setStoreELMId(StringUtils.defaultIfEmpty(
s.getElmId(), "0"));
accountOperaTotal.setStoreMTId(StringUtils.defaultIfEmpty(
s.getMeituanId(), "0"));
accountOperaTotal.setStoreBDId(StringUtils.defaultIfEmpty(
s.getBaiduId(), "0"));
}
List<AccountOperaTotal> list = accountOperaTotalService.listDeepTotalByCondition(accountOperaTotal);
AjaxUtils.sendAjaxForPage(request, response, page, list);
}
//导出数据方法
@RequestMapping("/exportExcel")
public void exportExcel(AccountOperaTotal accountOperaTotal, ExpParamBean epb,
HttpServletRequest request, HttpServletResponse response, Page page)
throws Exception {
if(accountOperaTotal.getStoreId()!=""&&accountOperaTotal.getStoreId()!=null){
Store s = storeService.getByPrimaryKey(accountOperaTotal.getStoreId());
accountOperaTotal.setStoreELMId(StringUtils.defaultIfEmpty(
s.getElmId(), "0"));
accountOperaTotal.setStoreMTId(StringUtils.defaultIfEmpty(
s.getMeituanId(), "0"));
accountOperaTotal.setStoreBDId(StringUtils.defaultIfEmpty(
s.getBaiduId(), "0"));
}
int expType = Integer.parseInt(request.getParameter("expType"));
if (expType == 1) {
accountOperaTotal.setPage(page);
}
List<AccountOperaTotal> list = null;
try{
String filename = "";
String title = "";
list = accountOperaTotalService.listDeepTotalByCondition(accountOperaTotal);
filename = "深运营汇总表";
title = "深运营汇总表";
ExcelExpUtils.exportListToExcel(list, response, epb.getFieldlist(),
filename, title);
}catch(Exception e){
e.printStackTrace();
}
}
}
|
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.JScrollPane;
public class HorarioGUI {
private JFrame Ventana;
private JTextField tfNombreClase;
private JTextField tfSalon;
private Horario horario;
private JComboBox cbDiaSemana;
private JComboBox cbPeriodo;
private JButton btnIngresarClase;
private JButton btnMostrarMatriz;
private JPanel pHorario;
private JTable tblHorario;
private DefaultTableModel tblModel;
private JScrollPane spTabla;
private JButton btnExisteAsignatura;
private JButton btnHorarioAsig;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HorarioGUI window = new HorarioGUI();
window.Ventana.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HorarioGUI() {
initialize();
horario = new Horario(7, 5);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Ventana = new JFrame();
Ventana.setBounds(100, 100, 450, 300);
Ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Ventana.getContentPane().setLayout(new GridLayout(0, 1, 0, 0));
JPanel pAddDatos = new JPanel();
Ventana.getContentPane().add(pAddDatos);
pAddDatos.setLayout(new GridLayout(0, 2, 0, 0));
JLabel lblNombreClase = new JLabel("Nombre de la Clase:");
pAddDatos.add(lblNombreClase);
tfNombreClase = new JTextField();
pAddDatos.add(tfNombreClase);
tfNombreClase.setColumns(10);
JLabel lblSalon = new JLabel("Sal\u00F3n: ");
pAddDatos.add(lblSalon);
tfSalon = new JTextField();
pAddDatos.add(tfSalon);
tfSalon.setColumns(10);
JLabel lblDiaSemana = new JLabel("Dia de la semana");
pAddDatos.add(lblDiaSemana);
cbDiaSemana = new JComboBox();
cbDiaSemana.setModel(new DefaultComboBoxModel(new String[] {"Lunes", "Martes", "Mi\u00E9rcoles", "Jueves", "Viernes"}));
pAddDatos.add(cbDiaSemana);
JLabel lblHora = new JLabel("Hora del per\u00EDodo:");
pAddDatos.add(lblHora);
cbPeriodo = new JComboBox();
cbPeriodo.setModel(new DefaultComboBoxModel(new String[] {"7:00 - 7:45", "7:50 - 8:35", "8:40 - 9:25", "9:30 -10:15", "10:15 - 10:40", "10:40 - 11:25", "11:30 - 12:15", "12:20 - 13:05"}));
pAddDatos.add(cbPeriodo);
btnIngresarClase = new JButton("IngresarClase");
pAddDatos.add(btnIngresarClase);
btnIngresarClase.addActionListener(new MiListener());
btnMostrarMatriz = new JButton("Mostrar Matriz");
pAddDatos.add(btnMostrarMatriz);
btnExisteAsignatura = new JButton("\u00BFExiste Asignatura?");
btnExisteAsignatura.addActionListener(new MiListener());
pAddDatos.add(btnExisteAsignatura);
btnHorarioAsig = new JButton("Horario Asignatura");
btnHorarioAsig.addActionListener(new MiListener());
pAddDatos.add(btnHorarioAsig);
btnMostrarMatriz.addActionListener(new MiListener());
pHorario = new JPanel();
Ventana.getContentPane().add(pHorario);
tblHorario = new JTable();
String[] header = {"Lunes", "Martes", "Miércoles", "Jueves", "Viernes"};
tblModel = new DefaultTableModel(header, 7);
pHorario.setLayout(new GridLayout(0, 1, 0, 0));
spTabla = new JScrollPane(tblHorario);
pHorario.add(spTabla);
tblHorario.setModel(tblModel);
spTabla.setViewportView(tblHorario);
}
private class MiListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() == btnIngresarClase) {
int periodo = cbPeriodo.getSelectedIndex();
int dia = cbDiaSemana.getSelectedIndex();
horario.reservarPeriodo(tfNombreClase.getText(), tfSalon.getText(), periodo, dia);
tblModel.setValueAt(horario.obtenerAsignatura(periodo, dia), periodo, dia);
}
if (e.getSource() == btnMostrarMatriz) {
String[][] matriz = horario.devolverHorario();
for (int i = 0; i<horario.getFilas(); i++) {
for (int j=0; j<horario.getColumnas(); j++)
System.out.print(matriz[i][j]);
System.out.println();
}
}
if (e.getSource() == btnExisteAsignatura) {
boolean existe = horario.buscarAsignatura(tfNombreClase.getText(), tfSalon.getText());
String msg = "";
if (existe)
msg = "Si existe en el horario";
else
msg = "No existe en el horario";
JOptionPane.showMessageDialog(Ventana, msg);
}
if (e.getSource() == btnHorarioAsig) {
String msg = "";
ArrayList<Integer> indices = horario.asignaturaIndex(tfNombreClase.getText(), tfSalon.getText());
if (indices.isEmpty())
JOptionPane.showMessageDialog(Ventana, "La clase no está en el horario");
else {
int i = 0;
while (i<indices.size()) {
msg = msg + "periodo: "+cbPeriodo.getItemAt(indices.get(i))+" Día: "+cbDiaSemana.getItemAt(indices.get(i+1))+"\n";
i = i+2;
}
JOptionPane.showMessageDialog(Ventana, msg, "La asignatura "+tfNombreClase.getText()+" está: ",JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
}
|
package com.utknl.katas;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
public class DeadFishTest {
@org.junit.Test
public void exampleTests() {
assertArrayEquals(new int[]{8, 64}, DeadFish.parse("iiisdoso"));
assertArrayEquals(new int[]{8, 64, 3600}, DeadFish.parse("iiisdosodddddiso"));
}
@Test
public void seeOutput() {
System.out.println(Arrays.toString(DeadFish.parse("iiisdoso")));
}
}
|
import java.io.*;
import java.util.*;
public class PyramidMessageScheme {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// String [] temp = in.readLine().split(" ");
int times = Integer.parseInt(in.readLine());
for (int x =0; x< times; x++)
{
int lines = Integer.parseInt(in.readLine());
String [] places = new String [lines+1];
int distance = 0;
int count = 0;
places [0] = "temp";
for (int i = 1; i <= lines; i++)
{
places[i] = in.readLine();
}
places[0] = places[lines];
String [] hold = new String [lines+1];
hold[0] = "";
hold[1] = places[0];
count = 1;
for (int i =lines-1; i >= 0; i--)
{
if (places[i].equals(hold[count-1]))
{
count--;
}
else
{
hold[count+1] = places[i];
count++;
distance = Math.max(count, distance);
}
}
distance--;
System.out.println((lines-distance*2)*10);
}
}
}
|
package ru.dias.springdatainterview;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDataInterviewApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDataInterviewApplication.class, args);
}
}
|
package com.mssngvwls.service.bootstrap;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.mssngvwls.model.Category;
import com.mssngvwls.model.builder.CategoryBuilder;
import com.mssngvwls.service.repository.CategoryRepository;
@Service
public class DataBootstrapping implements InitializingBean {
private static final Logger LOGGER = LoggerFactory.getLogger(DataBootstrapping.class);
private final boolean shouldBootstrapData;
private final CategoryRepository categoryRepository;
public DataBootstrapping(@Value("${bootstrapData}") final boolean shouldBootstrapData, final CategoryRepository categoryRepository) {
this.shouldBootstrapData = shouldBootstrapData;
this.categoryRepository = categoryRepository;
}
@Override
@Transactional
public void afterPropertiesSet() throws Exception {
LOGGER.info("Checking if we need to bootstrap data");
if (!shouldBootstrapData) {
LOGGER.info("Not bootstrapping data");
return;
}
LOGGER.info("Bootstrapping data");
createCategoriesAndPhrases();
LOGGER.info("Finished bootstrapping data");
}
private void createCategoriesAndPhrases() {
final List<Category> categories = new ArrayList<>();
categories.add(new CategoryBuilder()
.withCategoryName("English Football Teams")
.withPhrases("Manchester United", "Arsenal", "Liverpool", "Chelsea", "Everton", "Swansea", "Hartlepool United", "Torquay United",
"Manchester City", "Bournemouth", "West Bromwich Albion", "Queens Park Rangers", "Ipswich Town", "Burton Albion", "Oldham Athletic",
"Peterborough United")
.build());
categories.add(new CategoryBuilder()
.withCategoryName("Cars")
.withPhrases("Toyota Prius", "Toyota Yaris", "Toyota Corolla", "Nissan QASHQAI", "Ford Fiesta", "Ford Focus", "Ford Mondeo", "Ford Edge",
"Alfa Romeo 4C")
.build());
categories.add(new CategoryBuilder()
.withCategoryName("Formula One Teams")
.withPhrases("McLaren", "Williams", "Force India", "Benetton", "Minardi", "Spyker", "Red Bull Racing", "Toro Rosso", "Sauber", "Haas",
"Andrea Moda", "Caterham", "Honda", "Jordan", "Lotus", "Marussia", "Super Aguri")
.build());
categories.add(new CategoryBuilder()
.withCategoryName("Greetings and their language")
.withPhrases("Hello in English", "Bonjour in French", "Hola in Spanish", "Guten Tag in German", "Ciao in Italian", "Namaste in Hindi",
"Salaam in Persian")
.build());
categories.add(new CategoryBuilder()
.withCategoryName("Rupaul contestants")
.withPhrases("Tammie Brown", "Akashia", "Ongina", "BeBe Zahara Benet", "Sonique", "Tatianna", "Jujubee", "Mimi Imfurst", "Carmen Carrera",
"Raja", "Madame LaQueer", "Latrice Royale", "Sharon Needles", "Jade Jolie", "Alaska", "Adore Delano", "Miss Fame", "Aja")
.build());
categories.add(new CategoryBuilder()
.withCategoryName("Historic Counties of England")
.withPhrases("Essex", "Bedfordshire", "Derbyshire", "Yorkshire", "Kent", "Leicestershire", "Devon", "Dorset", "Gloucestershire", "Middlesex",
"Somerset", "Northumberland", "Rutland", "Shropshire", "Surrey", "Worcestershire", "Oxfordshire", "Northamptonshire")
.build());
categoryRepository.save(categories);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package noinheritance;
import java.util.ArrayList;
import java.lang.Math;
/**
*
* @author user
*/
public class Triangle {
ArrayList<Integer> sides = new ArrayList<Integer>();
int s1,s2,s3;
int Perimeter;
double Area;
public Triangle(int s1, int s2, int s3){
sides.add(s1);
sides.add(s2);
sides.add(s2);
}
public void getside(){
this.sides = sides;
}
public void isEquilateral(){
if(s1 == s2 && s1 == s3 && s2 == s3){
System.out.println("It is Equilateral");
}
}
public void calculatePerimeter(int s1, int s2, int s3){
Perimeter = s1 + s2 + s3;
System.out.printf("Perimeter is %d",Perimeter);
}
public void claculateArea(int s1, int s2, int s3){
Perimeter = s1 + s2 + s3;
int s = Perimeter/2;
double a;
a = s*(s-s1)*(s-s2)*(s-s3);
Area = Math.sqrt(a);
System.out.printf("Area is %f",Area);
}
public String draw(){
System.out.println("Shape is Triangle");
System.out.printf("Perimeter is %d:",Perimeter);
System.out.printf("Area is %f:",Area);
return null;
}
public void equals(Circle c,Triangle t,Rectangle r){
if(t.equals(c) || t.equals(r)){
System.out.println("They are equals.");
}
}
public String toString(){
System.out.println(sides.toString());
System.out.println(Triangle.class.toString());
return null;
}
}
|
package apa7.bitcoin.data;
/**
* Created by apa7 on 2019/7/17.
* Maintainer:
*/
public enum CategoryEnum {
send,
receive,
generate;
}
|
package member.desktop.pages.account;
import base.PageObject;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class Member_Reset_PassWord_Page extends PageObject {
@FindBy(css = ".mod-input-newPassword input") private WebElement newPass_txtField;
@FindBy(css = ".mod-input-re-newPassword input") private WebElement reNewPass_txtField;
@FindBy(css = ".next-btn-primary") private WebElement submit_btn;
public void resetPassword(String newPass) {
waitUntilPageReady();
waitUntilVisible(newPass_txtField);
this.newPass_txtField.sendKeys(newPass);
this.reNewPass_txtField.sendKeys(newPass);
this.submit_btn.click();
}
}
|
package com.justeat.app.deeplinks.links;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import com.justeat.app.deeplinks.intents.IntentHelper;
public class UriToIntentMapper {
private Context mContext;
private IntentHelper mIntents;
public UriToIntentMapper(Context context, IntentHelper intentHelper) {
mContext = context;
mIntents = intentHelper;
}
public void dispatchIntent(Intent intent) {
final Uri uri = intent.getData();
Intent dispatchIntent = null;
if (uri == null) throw new IllegalArgumentException("Uri cannot be null");
final String scheme = uri.getScheme().toLowerCase();
final String host = uri.getHost().toLowerCase();
if ("example-scheme".equals(scheme)) {
dispatchIntent = mapAppLink(uri);
} else if (("http".equals(scheme) || "https".equals(scheme)) &&
("www.example.co.uk".equals(host) || "example.co.uk".equals(host))) {
dispatchIntent = mapWebLink(uri);
}
if (dispatchIntent != null) {
mContext.startActivity(dispatchIntent);
}
}
private Intent mapAppLink(Uri uri) {
final String host = uri.getHost().toLowerCase();
switch (host) {
case "activitya":
return mIntents.newAActivityIntent(mContext);
case "activityb":
String bQuery = uri.getQueryParameter("query");
return mIntents.newBActivityIntent(mContext, bQuery);
case "activityc":
String cQuery = uri.getQueryParameter("query");
int choice = Integer.parseInt(uri.getQueryParameter("choice"));
return mIntents.newCActivityIntent(mContext, cQuery, choice);
}
return null;
}
private Intent mapWebLink(Uri uri) {
final String path = uri.getPath();
switch (path) {
case "/a":
return mIntents.newAActivityIntent(mContext);
case "/c":
String cQuery = uri.getQueryParameter("query");
int choice = Integer.parseInt(uri.getQueryParameter("choice"));
return mIntents.newCActivityIntent(mContext, cQuery, choice);
}
return null;
}
}
|
package froggame;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;
import java.util.TreeSet;
/**
* Frog game with StringBuilder
* @author ngadzheva
*/
public class FrogGame {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
makeInitialState();
}
/**
* Retrieve user input
* Make the initial state
* Start search
*/
private static void makeInitialState(){
System.out.print("Enter the number of frogs: ");
Scanner input = new Scanner(System.in);
int frogsCount = input.nextInt();
input.close();
int emptyPosition = frogsCount;
int length = 2 * frogsCount + 1;
/*StringBuilder initialState = new StringBuilder(String.join("", Collections.nCopies(frogsCount, ">")) +
"_" + String.join("", Collections.nCopies(frogsCount, "<")));*/
char[] initialState = new char[length];
for (int i = 0; i < frogsCount; ++i) {
initialState[i] = '>';
}
initialState[frogsCount] = '_';
for (int i = frogsCount + 1; i < length; ++i) {
initialState[i] = '<';
}
dfs(initialState, emptyPosition, initialState.length);
}
/**
* Implementation of DFS
* @param frogs - the initial state
* @param emptyPosition - the index of the empty position
* @param length - the number of all frogs + empty position
*/
private static void dfs(char[] frogs, int emptyPosition, int length){
/**
* Stack which stores next possible moves
*/
Stack<char[]> moves = new Stack<>();
/**
* List which stores the visited moves
*/
List<char[]> visited = new ArrayList<>();
/**
* List which stores the correct moves
*/
List<char[]> result = new ArrayList<>();
/**
* Add the initial state to the list with correct moves
*/
result.add(frogs);
/**
* Make next possible moves
*/
makeMoves(frogs, moves, emptyPosition, length);
/**
* While there are available moves in the stack
* get the move on the top of the stack,
* check whether it is the wanted move
* If the current move is the wanted move,
* add it to the list with the correct moves, break and print the result
* Else make next possible moves from the current moves
* If there are such moves,
* add them to the stack with possible moves
*/
while(!moves.isEmpty()){
char[] currentMove = moves.peek();
if(visited.contains(currentMove)){
moves.pop();
if(result.contains(currentMove)){
result.remove(currentMove);
}
} else {
visited.add(currentMove);
emptyPosition = getEmptyPosition(currentMove, length);
if(emptyPosition == currentMove.length / 2 &&
isAllLeftRight(currentMove, emptyPosition)){
result.add(currentMove);
break;
}
int currentSize = moves.size();
makeMoves(currentMove, moves, emptyPosition, length);
if(moves.size() > currentSize){
result.add(currentMove);
} else {
moves.pop();
}
}
}
printResult(result);
}
/**
* Make next possible move
* @param frogs - the current move
* @param moves - the stack with the possible moves
* @param emptyPosition - the index of the empty position
* @param length - the number of all frogs + the empty position
*/
private static void makeMoves(char[] frogs, Stack<char[]> moves, int emptyPosition, int length){
/**
* emptyPosition + 2
* right frog jumps over one frog
*/
if(emptyPosition + 2 < length && frogs[emptyPosition + 2] == '<'){
char[] current = makeCopy(frogs, length);
current[emptyPosition + 2] = '_';
current[emptyPosition] = '<';
moves.add(current);
}
/**
* emptyPosition + 1
* right frog jumps on the empty position
*/
if(emptyPosition + 1 < length && frogs[emptyPosition + 1] == '<'){
char[] current = makeCopy(frogs, length);
current[emptyPosition + 1] = '_';
current[emptyPosition] = '<';
moves.add(current);
}
/**
* emptyPosition - 1
* left frog jumps over one frog
*/
if(emptyPosition - 1 >= 0 && frogs[emptyPosition - 1] == '>'){
char[] current = makeCopy(frogs, length);
current[emptyPosition - 1] = '_';
current[emptyPosition] = '>';
moves.add(current);
}
/**
* emptyPosition - 2
* left frog jumps on the empty position
*/
if(emptyPosition - 2 >= 0 && frogs[emptyPosition - 2] == '>'){
char[] current = makeCopy(frogs, length);
current[emptyPosition - 2] = '_';
current[emptyPosition] = '>';
moves.add(current);
}
}
/**
* Make copy of the current move
* @param move - the current move
* @param length - the number of frogs and the empty position
* @return copy of the current move
*/
private static char[] makeCopy(char[] move, int length){
char[] newMove = new char[length];
for (int i = 0; i < length; ++i) {
newMove[i] = move[i];
}
return newMove;
}
/**
* Get the index of the empty position
* @param move - current move
* @return the index of the empty position
*/
private static int getEmptyPosition(char[] move, int length){
int index = 0;
for (int i = 0; i < length; ++i) {
if(move[i] == '_'){
return i;
}
}
return index;
}
/**
* Print the correct moves
* @param result - the list with the correct moves
*/
private static void printResult(List<char[]> result){
for (char[] res : result) {
System.out.println(new String(res));
}
}
/**
* Check whether all left frogs are right frogs
* @param move - current move
* @param length - the number of all frogs + the empty position
* @return true if the frogs to the right are ordered properly, else
* return false
*/
private static boolean isAllLeftRight(char[] move, int emptyPosition){
for (int i = 0; i < emptyPosition; ++i) {
if(move[i] != '<'){
return false;
}
}
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.