text
stringlengths 10
2.72M
|
|---|
package com.programapprentice.app;
/**
* User: program-apprentice
* Date: 8/4/15
* Time: 10:01 PM
*/
import java.util.Stack;
/**
* Reverse digits of an integer.
* Example1: x = 123, return 321
* Example2: x = -123, return -321
* */
public class ReverseInteger_7 {
public int reverse_v1(int x) {
if(x == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
boolean isNegative = false;
if(x < 0) {
isNegative = true;
}
while(x != 0) {
stack.push(x % 10);
x /= 10;
}
int result = 0;
int step = 1;
int length = 1;
while(!stack.isEmpty()) {
if(length == 10) {
// judge for overflow
if(stack.peek() > 2 || stack.peek() < -2) {
return 0;
} else {
if(isNegative) {
if(Integer.MIN_VALUE - stack.peek() * step > result) {
return 0;
}
} else {
if(Integer.MAX_VALUE - stack.peek() * step < result) {
return 0;
}
}
}
}
length ++;
result += stack.pop() * step;
step *= 10;
}
return result;
}
public int reverse_v2(int x) {
if(x == 0) {
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
boolean isNegative = false;
if(x < 0) {
isNegative = true;
}
while(x != 0) {
stack.push(x % 10);
x /= 10;
}
int result = 0;
int step = 1;
int tmpValue = 0;
int maxThreshold = Integer.MAX_VALUE / 10;
int minThreshold = Integer.MIN_VALUE / 10;
while(!stack.isEmpty()) {
tmpValue = stack.peek() * (step / 10);
if(isNegative) {
if(tmpValue < minThreshold || Integer.MIN_VALUE - tmpValue * 10 > result) {
return 0;
}
} else {
if(tmpValue > maxThreshold || Integer.MAX_VALUE - tmpValue * 10 < result) {
return 0;
}
}
result += stack.pop() * step;
step *= 10;
}
return result;
}
public int reverse(int x) {
int val = 0;
int num = x;
while(num != 0) {
if(Math.abs(val) > Integer.MAX_VALUE /10) {
return 0;
}
val = val * 10 + num % 10;
num /= 10;
}
return val;
}
}
|
package p08;
import java.util.Random;
public class Lotto {
private int[] lottoNums;
private Random r;
private int lottoTemp;
private int lotooMax;
private int[] checkLottoNums;
public Lotto() {
this(6, 45);
}
public Lotto(int rNumsLength, int lotooMax) {
lottoNums = new int[rNumsLength];
r = new Random();
this.lotooMax = lotooMax;
}
void printLotoo() {
String str = "";
for (int i = 0; i < lottoNums.length; i++) {
str += lottoNums[i] + ", ";
}
System.out.println("로또 당첨번호 입니다\n" + str.substring(0, str.length() - 2));
}
private boolean isDupl() {
for (int i = 0; i < lottoNums.length; i++) {
if (lottoNums[i] == lottoTemp) {
return true;
}
}
return false;
}
void getLottoNums() {
for (int i = 0; i < lottoNums.length; i++) {
lottoTemp = r.nextInt(lotooMax) + 1;
if (isDupl()) {
i--;
continue;
}
lottoNums[i] = lottoTemp;
}
}
void setCheckLottoNums(int[] checkLottoNums) {
this.checkLottoNums = checkLottoNums;
String str = "";
for (int i = 0; i < this.checkLottoNums.length; i++) {
str += this.checkLottoNums[i] + ", ";
}
System.out.println("당신의 숫자\n" + str.substring(0, str.length() - 2));
}
void checkLottoNums() {
int cnt = 0;
for (int i = 0; i < lottoNums.length; i++) {
for (int j = 0; j < lottoNums.length; j++) {
if (checkLottoNums[i] == lottoNums[j]) {
cnt++;
System.out.println(checkLottoNums[i] + "==" + lottoNums[j] + ":" + (checkLottoNums[i] == lottoNums[j]));
}
}
}
System.out.println(cnt + "개 맞았습니다");
}
public static void main(String[] args) {
Lotto lt = new Lotto(6, 45);
lt.getLottoNums();
lt.printLotoo();
int[] nums = { 10, 15, 23, 4, 24, 33 };
lt.setCheckLottoNums(nums);
lt.checkLottoNums();
}
}
|
package codejam1;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class creep {
public static void main(String[] args) {
Scanner sc = null;
try {
sc = new Scanner(new File("C:/Users/Aloy Aditya Sen/workspace/Thought/src/input/inStream"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int i=sc.nextInt();
String nan=sc.nextLine();
String in=sc.nextLine();
for (int j = 0; j < in.length(); j++) {
System.out.println(Integer.parseInt(in.));
}
}
}
|
package com.proyectofinal.game.objects.trops;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.math.Rectangle;
import com.proyectofinal.game.helpers.AssetManager;
/**
* Created by ALUMNEDAM on 09/05/2017.
*/
public class Ninja extends Tropas {
public Ninja(float x, float y, int desviacionX, int desviacionY, int vida, int danyo, int velocidad) {
super(x, y, desviacionX, desviacionY, vida, danyo, velocidad);
}
@Override
public void act(float delta) {
setCollisionRect(new Rectangle(getPosition().x, getPosition().y, 78, 90)); //Rectangulo de posiciones del Ninja
}
@Override
public void draw(Batch batch, float parentAlpha) {
this.setName("Ninjas");
if (isanimacionCaminar()) {
batch.draw(AssetManager.ninjaRun.getKeyFrame(getTiempoDeEstado()), getX(), getY(), 0, 0, 77, 88, 1f, 1f, 0);
} else {
batch.draw(AssetManager.ninjaAttack.getKeyFrame(getTiempoDeEstado()), getX(), getY(), 0, 0, 110, 100, 1f, 1f, 0);
}
}
}
|
package com.kamak.katalogfilmuiux;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.kamak.katalogfilmuiux.NowPlaying.NowPlaying;
import com.kamak.katalogfilmuiux.Upcoming.Upcoming;
/**
* A simple {@link Fragment} subclass.
*/
public class TabMenuFilm extends Fragment {
public static TabLayout tabLayout;
public static int items=2;
public static ViewPager viewPager;
public TabMenuFilm() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v=inflater.inflate(R.layout.fragment_tab_menu_film, container, false);
tabLayout=v.findViewById(R.id.tabs);
viewPager=v.findViewById(R.id.viewpager);
viewPager.setAdapter(new GrafikTabAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return v;
}
class GrafikTabAdapter extends FragmentPagerAdapter {
public GrafikTabAdapter(FragmentManager childFragmentManager) {
super(childFragmentManager);
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new NowPlaying();
case 1:
return new Upcoming();
}
return null;
}
@Override
public int getCount() {
return items;
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Now Playing";
case 1:
return "Upcoming";
}
return null;
}
}
}
|
package sample.mybatis;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class Main {
public static void main(String[] args) throws Exception {
// ★ルートとなる設定ファイルを読み込む
try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
// ★設定ファイルを元に、 SqlSessionFactory を作成する
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// ★SqlSessionFactory から SqlSession を生成する
try (SqlSession session = factory.openSession()) {
// ★SqlSession を使って SQL を実行する
List<Map<String, Object>> result = session.selectList("sample.mybatis.selectTest");
result.forEach(row -> {
System.out.println("---------------");
row.forEach((columnName, value) -> {
System.out.printf("columnName=%s, value=%s%n", columnName, value);
});
});
}
}
}
private void printResult(List<Map<String, Object>> result) {
for (Map<String, Object> map : result) {
}
}
}
|
package com.javaee.ebook1.service.impl;
import com.javaee.ebook1.mybatis.vo.BookListVO;
import com.javaee.ebook1.service.BookListService;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.servlet.ModelAndView;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class BookListServiceImplTest {
@Autowired
BookListService bls;
@AfterAll
static void end(){
System.out.println("All Book List Service Test Done.");
}
@Test
void getBookList() {
ModelAndView mav = bls.getBookList();
assertEquals(mav.getViewName(), "booksList");
System.out.println("getBookList() Done.");
}
@Test
void testGetBookList() {
BookListVO booklist = new BookListVO("1","1",1,0);
ModelAndView mav = bls.getBookList(booklist);
assertEquals(mav.getViewName(), "booksList");
System.out.println("getBookList(BookListVO) Done.");
}
}
|
/*
* Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.datumbox.framework.machinelearning.common.bases.basemodels;
import com.datumbox.common.dataobjects.AssociativeArray;
import com.datumbox.common.dataobjects.Dataset;
import com.datumbox.common.dataobjects.Record;
import com.datumbox.common.persistentstorage.factories.BigDataStructureFactory;
import com.datumbox.common.persistentstorage.interfaces.BigDataStructureMarker;
import com.datumbox.common.utilities.MapFunctions;
import com.datumbox.common.utilities.PHPfunctions;
import com.datumbox.configuration.GeneralConfiguration;
import com.datumbox.configuration.MemoryConfiguration;
import com.datumbox.framework.machinelearning.common.bases.mlmodels.BaseMLclusterer;
import com.datumbox.framework.statistics.descriptivestatistics.Descriptives;
import com.datumbox.framework.statistics.sampling.SRS;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.mongodb.morphia.annotations.Transient;
/**
*
* @author Vasilis Vryniotis <bbriniotis at datumbox.com>
* @param <CL>
* @param <MP>
* @param <TP>
* @param <VM>
*/
public abstract class BaseDPMM<CL extends BaseDPMM.Cluster, MP extends BaseDPMM.ModelParameters, TP extends BaseDPMM.TrainingParameters, VM extends BaseDPMM.ValidationMetrics> extends BaseMLclusterer<CL, MP, TP, VM> {
public static abstract class Cluster extends BaseMLclusterer.Cluster {
@Transient
protected transient Map<Object, Integer> featureIds; //This is only a reference to the real Map. It is used to convert the Records to Arrays
public Cluster(Integer clusterId) {
super(clusterId);
}
protected void setClusterId(Integer clusterId) {
this.clusterId = clusterId;
}
protected abstract void updateClusterParameters();
protected abstract void initializeClusterParameters();
/**
* Returns the log posterior PDF of a particular point xi, to belong to this
* cluster.
*
* @param r The point for which we want to estimate the PDF.
* @return The log posterior PDF
*/
public abstract double posteriorLogPdf(Record r);
}
public static abstract class ModelParameters<CL extends BaseDPMM.Cluster> extends BaseMLclusterer.ModelParameters<CL> {
private int totalIterations;
/**
* Feature set
*/
@BigDataStructureMarker
@Transient
private Map<Object, Integer> featureIds; //list of all the supported features
@Override
public void bigDataStructureInitializer(BigDataStructureFactory bdsf, MemoryConfiguration memoryConfiguration) {
super.bigDataStructureInitializer(bdsf, memoryConfiguration);
BigDataStructureFactory.MapType mapType = memoryConfiguration.getMapType();
int LRUsize = memoryConfiguration.getLRUsize();
featureIds = bdsf.getMap("featureIds", mapType, LRUsize);
}
public int getTotalIterations() {
return totalIterations;
}
public void setTotalIterations(int totalIterations) {
this.totalIterations = totalIterations;
}
public Map<Object, Integer> getFeatureIds() {
return featureIds;
}
public void setFeatureIds(Map<Object, Integer> featureIds) {
this.featureIds = featureIds;
}
}
public static abstract class TrainingParameters extends BaseMLclusterer.TrainingParameters {
/**
* Alpha value of Dirichlet process
*/
private double alpha;
private int maxIterations = 1000;
public enum Initialization {
ONE_CLUSTER_PER_RECORD,
RANDOM_ASSIGNMENT
}
//My optimization: it controls whether the algorithm will be initialized with every observation
//being a separate cluster. If this is turned off, then alpha*log(n) clusters
//are generated and the observations are assigned randomly in it.
private Initialization initializationMethod = Initialization.ONE_CLUSTER_PER_RECORD;
public double getAlpha() {
return alpha;
}
public void setAlpha(double alpha) {
this.alpha = alpha;
}
public int getMaxIterations() {
return maxIterations;
}
public void setMaxIterations(int maxIterations) {
this.maxIterations = maxIterations;
}
public Initialization getInitializationMethod() {
return initializationMethod;
}
public void setInitializationMethod(Initialization initializationMethod) {
this.initializationMethod = initializationMethod;
}
}
public static abstract class ValidationMetrics extends BaseMLclusterer.ValidationMetrics {
}
protected BaseDPMM(String dbName, Class<MP> mpClass, Class<TP> tpClass, Class<VM> vmClass) {
super(dbName, mpClass, tpClass, vmClass);
}
@Override
@SuppressWarnings("unchecked")
protected void estimateModelParameters(Dataset trainingData) {
int n = trainingData.size();
int d = trainingData.getColumnSize();
ModelParameters modelParameters = knowledgeBase.getModelParameters();
Map<Integer, CL> clusterList = modelParameters.getClusterList();
//initialization
modelParameters.setN(n);
modelParameters.setD(d);
Set<Object> goldStandardClasses = modelParameters.getGoldStandardClasses();
Map<Object, Integer> featureIds = modelParameters.getFeatureIds();
//check if there are any gold standard classes and buld the featureIds maps
int previousFeatureId = 0;
for(Record r : trainingData) {
Object theClass=r.getY();
if(theClass!=null) {
goldStandardClasses.add(theClass);
}
for(Map.Entry<Object, Object> entry : r.getX().entrySet()) {
Object feature = entry.getKey();
if(!featureIds.containsKey(feature)) {
featureIds.put(feature, previousFeatureId++);
}
}
}
//perform Gibbs Sampling and calculate the clusters
int totalIterations = collapsedGibbsSampling(trainingData);
//set the actual iterations performed
modelParameters.setTotalIterations(totalIterations);
//update the number of clusters
modelParameters.setC(clusterList.size());
//clear dataclusters
for(CL c : clusterList.values()) {
c.clear();
}
}
/**
* Implementation of Collapsed Gibbs Sampling algorithm.
*
* @param dataset The list of points that we want to cluster
* @param maxIterations The maximum number of iterations
*/
private int collapsedGibbsSampling(Dataset dataset) {
ModelParameters modelParameters = knowledgeBase.getModelParameters();
Map<Integer, CL> tempClusterMap = new HashMap<>(modelParameters.getClusterList());
TrainingParameters trainingParameters = knowledgeBase.getTrainingParameters();
double alpha = trainingParameters.getAlpha();
//Initialize clusters, create a cluster for every xi
Integer newClusterId = tempClusterMap.size(); //start counting the Ids based on clusters in the list
if(trainingParameters.getInitializationMethod()==TrainingParameters.Initialization.ONE_CLUSTER_PER_RECORD) {
for(Record r : dataset) {
//generate a new cluster
CL cluster = createNewCluster(newClusterId);
//add the record in the new cluster
r.setYPredicted(newClusterId);
cluster.add(r);
//add the cluster in clusterList
tempClusterMap.put(newClusterId, cluster);
++newClusterId;
}
}
else {
int numberOfNewClusters = (int)(Math.max(alpha, 1)*Math.log(dataset.size())); //a*log(n) clusters on average
if(numberOfNewClusters<=0) {
numberOfNewClusters=1;
}
//generate new clusters
for(int i=0;i<numberOfNewClusters;++i) {
//generate a new cluster
CL cluster = createNewCluster(newClusterId);
//add the cluster in clusterList
tempClusterMap.put(newClusterId, cluster);
++newClusterId;
}
int clusterMapSize = newClusterId;
for(Record r : dataset) {
int assignedClusterId = PHPfunctions.mt_rand(0, clusterMapSize-1);
r.setYPredicted(assignedClusterId);
tempClusterMap.get((Integer)assignedClusterId).add(r);
}
}
int n = tempClusterMap.size();
int maxIterations = trainingParameters.getMaxIterations();
boolean noChangeMade=false;
int iteration=0;
while(iteration<maxIterations && noChangeMade==false) {
if(GeneralConfiguration.DEBUG) {
System.out.println("Iteration "+iteration);
}
noChangeMade=true;
for(Record r : dataset) {
Integer pointClusterId = (Integer) r.getYPredicted();
CL ci = tempClusterMap.get(pointClusterId);
//remove the point from the cluster
ci.remove(r);
//if empty cluster remove it
if(ci.size()==0) {
tempClusterMap.remove(pointClusterId);
}
AssociativeArray condProbCiGivenXiAndOtherCi = clusterProbabilities(r, n, tempClusterMap);
//Calculate the probabilities of assigning the point to a new cluster
//compute P*(X[i]) = P(X[i]|λ)
CL cNew = createNewCluster(newClusterId);
double priorLogPredictive = cNew.posteriorLogPdf(r);
//compute P(z[i] = * | z[-i], Data) = α/(α+N-1)
double probNewCluster = alpha/(alpha+n-1.0);
condProbCiGivenXiAndOtherCi.put(newClusterId, priorLogPredictive+Math.log(probNewCluster));
//normalize probabilities P(z[i])
Descriptives.normalizeExp(condProbCiGivenXiAndOtherCi);
Integer sampledClusterId = (Integer)SRS.weightedProbabilitySampling(condProbCiGivenXiAndOtherCi, 1, true).iterator().next();
condProbCiGivenXiAndOtherCi=null;
//Add Xi back to the sampled Cluster
if(sampledClusterId==newClusterId) { //if new cluster
//add the record in the new cluster
r.setYPredicted(newClusterId);
cNew.add(r);
//add the cluster in clusterList
tempClusterMap.put(newClusterId, cNew);
noChangeMade=false;
++newClusterId;
}
else {
r.setYPredicted(sampledClusterId);
tempClusterMap.get(sampledClusterId).add(r);
if(noChangeMade && pointClusterId!=sampledClusterId) {
noChangeMade=false;
}
}
}
++iteration;
}
//copy the values in the map and update the cluster ids
Map<Integer, CL> clusterList = modelParameters.getClusterList();
newClusterId = clusterList.size();
for(CL cluster : tempClusterMap.values()) {
cluster.setClusterId(newClusterId);
clusterList.put(newClusterId, cluster);
++newClusterId;
}
tempClusterMap = null;
return iteration;
}
public AssociativeArray clusterProbabilities(Record r, int n, Map<Integer, CL> clusterMap) {
AssociativeArray condProbCiGivenXiAndOtherCi = new AssociativeArray();
double alpha = knowledgeBase.getTrainingParameters().getAlpha();
//Probabilities that appear on https://www.cs.cmu.edu/~kbe/dp_tutorial.posteriorLogPdf
//Calculate the probabilities of assigning the point for every cluster
for(CL ck : clusterMap.values()) {
//compute P_k(X[i]) = P(X[i] | X[-i] = k)
double marginalLogLikelihoodXi = ck.posteriorLogPdf(r);
//set N_{k,-i} = dim({X[-i] = k})
//compute P(z[i] = k | z[-i], Data) = N_{k,-i}/(a+N-1)
double mixingXi = ck.size()/(alpha+n-1.0);
condProbCiGivenXiAndOtherCi.put(ck.getClusterId(), marginalLogLikelihoodXi+Math.log(mixingXi));
}
return condProbCiGivenXiAndOtherCi;
}
@Override
protected void predictDataset(Dataset newData) {
if(newData.isEmpty()) {
return;
}
ModelParameters modelParameters = knowledgeBase.getModelParameters();
Map<Integer, Cluster> clusterList = modelParameters.getClusterList();
for(Record r : newData) {
AssociativeArray clusterScores = new AssociativeArray();
for(Cluster c : clusterList.values()) {
double probability = c.posteriorLogPdf(r);
clusterScores.put(c.getClusterId(), probability);
}
r.setYPredicted(getSelectedClusterFromScores(clusterScores));
Descriptives.normalizeExp(clusterScores);
r.setYPredictedProbabilities(clusterScores);
}
}
private Object getSelectedClusterFromScores(AssociativeArray clusterScores) {
Map.Entry<Object, Object> maxEntry = MapFunctions.selectMaxKeyValue(clusterScores);
return maxEntry.getKey();
}
//create new cluster, set the ID, initialize it and pass to it the featureIds
//DO NOT add it on the clusterList
protected abstract CL createNewCluster(Integer clusterId);
}
|
package hashcode_and_equal_method_using_hashset;
// as we know hashset does not contain duplicate elements.
// but if we create two user defined object with same values then it contains both objects because both two objects have different hash code
import java.util.HashSet;
import java.util.Objects;
class Student2 {
private int id;
private String name;
public Student2(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
@Override
public String toString() {
return "Student2{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class without_override_equal_method_of_object_using_hashset {
public static void main(String[] args) {
HashSet<Student2> hashSet = new HashSet<>();
Student2 obj1=new Student2(1,"ankit");
Student2 obj2=new Student2(2,"arpit");
Student2 obj3=new Student2(1,"ankit");
System.out.println("HashCode of obj1 :"+obj1.hashCode());
System.out.println("HashCode of obj2 :"+obj2.hashCode());
System.out.println("HashCode of obj3 :"+obj3.hashCode());
//we can see that obj1 and obj2 have same values but hashset contains both because they have different hash code
hashSet.add(obj1);
hashSet.add(obj2);
hashSet.add(obj3);
obj1.equals(obj2);
System.out.println(hashSet);
//but according to business needs, if we want hash code does not contain other object with same values
//so first we have to override hashcode method to make their hash code same
//if hash codes are same then jvm calls (equal(object secondobj) method of object(ex- firstobj)) to check whether firstobj is equal to secondobj or not
//default implementation of equal method is :
//public boolean equals(Object secondobj) {
// return (this == secondobj); //here "this" means firstobj
// }
//
// if firstobj is equal to the secondobj then jvm does not add new object in hashset.
//so we have to override equal method also to tell when two object are equal
//see next example
}
}
|
package org.oatesonline.yaffle.services.impl;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.oatesonline.yaffle.entities.dao.DAOFactory;
import org.oatesonline.yaffle.entities.dao.DAOPlayer;
import org.oatesonline.yaffle.entities.impl.Player;
import org.restlet.data.CookieSetting;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.restlet.util.Series;
public class LoginService extends YaffleService {
Logger log = Logger.getLogger(LoginService.class.getName());
@Post
public void doOptions(){
super.doOptions();
}
@Post
public String login(Representation rep)
throws ResourceException {
DAOPlayer daoP = DAOFactory.getDAOPlayerInstance();
String pin= null;
String email= null;
String jsonData = null;
String ret = "";
try {
jsonData = rep.getText();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
}
Player p = null;
if (jsonData != null){
JSONParser parser=new JSONParser();
Object obj = null;
Map pData = null;
try {
obj=parser.parse(jsonData);
pData = (Map) obj;
if (null != pData){
email = (String) pData.get("email");
pin = (String) pData.get("password");
p = (Player) daoP.findPlayer(email);
if (null != p){
String password = p.getPassword();
if (password != null){
if (password.equals(pin)){
getResponse().setStatus(Status.SUCCESS_OK);
getResponse().getCookieSettings().set(YAFFLE_UID, p.getId().toString());
ret= p.toJSONString();
} else {
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return "Login Failed";
}
}
} else {
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return "Login Failed";
}
}
} catch(ParseException pEx){
log.log(Level.SEVERE, pEx.getMessage());
getResponse().setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
return "Login Failed";
}
} else {
getResponse().setStatus(Status.CLIENT_ERROR_UNPROCESSABLE_ENTITY);
ret = "No login data was received by the server";
}
return ret;
}
@Get
public void logout(){
Player p= validateUser(null);
if (p != null){
Series<CookieSetting> cs = getResponse().getCookieSettings();
cs.removeFirst(YAFFLE_UID);
cs.add(YAFFLE_UID, "");
}
}
}
|
package section3;
public class ByteShortIntLong {
public static void main(String[] args) {
System.out.println("Integer Range");
int myMin = Integer.MIN_VALUE;
System.out.println("Minimum: " + myMin);
int myMax = Integer.MAX_VALUE;
System.out.println("Maximum: " + myMax);
// overflow
int myBustedMax = Integer.MAX_VALUE + 1;
System.out.println("Busted Maximum Value: " + myBustedMax);
// underflow
int myBustedMin = Integer.MIN_VALUE - 1;
System.out.println("Busted Maximum Value: " + myBustedMin);
// throws error, number is out of range
// int myMaxTest = 2147483648;
byte myMinByte = Byte.MIN_VALUE;
byte myMaxByte = Byte.MAX_VALUE;
System.out.println("Byte Min: " + myMinByte);
System.out.println("Byte Max: " + myMaxByte);
short myMinShort = Short.MIN_VALUE;
short myMaxShort = Short.MAX_VALUE;
System.out.println("Short Min: " + myMinShort);
System.out.println("Short Max: " + myMaxShort);
long myLong = 100L;
long myMinLong = Long.MIN_VALUE;
long myMaxLong = Long.MAX_VALUE;
System.out.println("Long Min: " + myMinLong);
System.out.println("Long Max: " + myMaxLong);
// need "L" to specify it's a long, otherwise
// ide thinks it's an int value
long bigLongLiteralValue = 2147483647234L;
System.out.println(bigLongLiteralValue);
short bigShortLiteralValue = 32767;
System.out.println(bigShortLiteralValue);
// Casting //
System.out.println("************ Casting ****************");
int myTotal = (myMin / 2);
System.out.println(myTotal);
byte myNewByteValue = (byte)(myMinByte / 2);
System.out.println(myNewByteValue);
short myNewShortValue = (short)(myMinShort / 2 );
System.out.println(myNewShortValue);
// Primitives Types Challenge
System.out.println("\nPrimitives Types Challenge");
byte byteVar = 125;
short shortVar = 30;
int intVar = 14327;
// no casting needed
long longSum = (50000) + ((byteVar + shortVar + intVar) * 10);
System.out.println("Long Sum: " + longSum);
short shortTotal = (short)(1000 + 10 *
(byteVar + shortVar + intVar));
System.out.println("Short Total: " + shortTotal);
}
}
|
package com.qac.nbg_app.messenging.messages;
public class Address {
}
|
package simplefactory2;
public interface Hair {
public void drawHair();
}
|
package com.turios.modules.core;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import android.util.Log;
@Singleton
public class ExpirationCoreModule {
private static final String TAG = "ExpirationCoreModule";
public interface ExpirationCoreModuleCallback {
void expiresIn(int days);
}
private ExpirationCoreModuleCallback expirationCoreModuleCallback;
public void setExpirationListener(
ExpirationCoreModuleCallback expirationCoreModuleCallback) {
this.expirationCoreModuleCallback = expirationCoreModuleCallback;
}
private static final int TRIAL_PERIOD_DAYS = 30;
private final ParseCoreModule parse;
@Inject
public ExpirationCoreModule(ParseCoreModule parse) {
this.parse = parse;
}
public void checkExpiration() {
if (expirationCoreModuleCallback != null)
expirationCoreModuleCallback.expiresIn(getDaysUntilExpiration());
}
private long getExpiresAndTodayDiff(Date installDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(installDate);
cal.add(Calendar.DATE, TRIAL_PERIOD_DAYS);
return cal.getTime().getTime() - System.currentTimeMillis();
}
public boolean isExpired() {
return getDaysUntilExpiration() == 0;
}
private int getDaysUntilExpiration() {
if (parse.isLoggedIn()) {
Date installDate = parse.getParseInstallation().getCreatedAt();
int days = (int) TimeUnit.DAYS.convert(
getExpiresAndTodayDiff(installDate), TimeUnit.MILLISECONDS);
return (days >= 0) ? days : 0;
}
return 0;
}
}
|
/**
* Created by jeffbrinkley on 3/2/17.
*/
public class User {
int id;
String user_name;
public User(int id, String user_name) {
this.id = id;
this.user_name = user_name;
}
}
|
class Solution {
public int thirdMax(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < nums.length; i++){
set.add(nums[i]);
}
if(set.size() == 1) {
for(Integer i:set) return i;
}
if(set.size() == 2){
int max = Integer.MIN_VALUE;
for(Integer i:set) {
if(i > max) max = i;
}
return max;
}
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;
for(Integer i:set){
if(i >= first) {
third = second;
second = first;
first = i;
}
if(i < first && i >= second) {
third = second;
second = i;
}
if(i < second && i >= third) third = i;
}
return third;
}
}
|
package com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.createtopic;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUserView;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.bean.CreateLiveTopicBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.HashMap;
/**
* Describe:
* Created by ALing on 2017/3/20 .
*/
public class CreateTopicContract {
public interface View extends BaseUserView<CreateTopicContract.Presenter> {
void createLiveResult(CreateLiveTopicBean bean);
}
public interface Presenter extends BasePresenter {
void createLiveTopic(HashMap<String,String> map);
}
public interface Source extends BaseSource {
void createLiveTopic(HashMap<String,String> map, ApiCallBack<CreateLiveTopicBean> callBack);
}
}
|
package com.mars.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Date;
/**
* Created by mars on 2015/8/24.
*/
@Data
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class LeaveRequestMail implements HrMail{
private String type;
private String empId;
private String username;
private String depName;
private String url;
private String documentNo;
private String leaveType;
private String subType;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd")
private Date startDate;
private String startTime;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy/MM/dd")
private Date endDate;
private String endTime;
private String sum;
private String sumUnit;
private String memo;
}
|
package main.java.com.example.projekt_jee_liga.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/about")
public class AboutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h2>Your data</h2>" +
"<p>id pilkarza: " + request.getParameter("playerId") + "<br />" +
"<p>id klubu: " + request.getParameter("clubId") + "<br />" +
"<p>First name: " + request.getParameter("firstName") + "<br />" +
"<p>Last name: " + request.getParameter("lastName") + "<br />" +
"<p>position: " + request.getParameter("position") + "<br />" +
"<p>number: " + request.getParameter("number") + "<br />" +
"</body></html>");
out.close();
}
}
|
package com.tpg.microservices.test1.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.tpg.microservices.test1.bean.Item;
@RepositoryRestResource
public interface ItemRepository extends CrudRepository<Item, Integer> {
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Loading {
public void read(int level) {
try {
File lev = new File("levels.txt");
Scanner scan = new Scanner(lev);
// Поиск нужного уровня
String s = "";
while(scan.hasNextLine()) {
s = scan.nextLine();
if (s.indexOf("Maze: "+level) > -1) break;
}
// Загрузка ширины и высоты
scan.nextLine();
Main.fieldWidth = Integer.parseInt(scan.nextLine().substring(8));
Main.fieldHeight = Integer.parseInt(scan.nextLine().substring(8));
Main.WIDTH = Main.fieldWidth*Main.cellWidth;
Main.HEIGHT = Main.fieldHeight*Main.cellHeight+30;
Main.fieldClass.init(Main.fieldWidth, Main.fieldHeight);
// Парсер уровня
for (int i = 0; i < 3; i++) scan.nextLine();
for (int i = 0; i < Main.fieldHeight; i++) {
s = scan.nextLine();
for (int j = 0; j < Main.fieldWidth; j++) {
if (s.charAt(j) == 'X') Main.field[j][i] = 1;
if (s.charAt(j) == '*') Main.field[j][i] = 2;
if (s.charAt(j) == '.') {
Main.countTarget++;
Main.targetX.add(j);
Main.targetY.add(i);
}
if (s.charAt(j) == '@') {
Main.hero.x = j;
Main.hero.y = i;
}
}
}
scan.close();
} catch(FileNotFoundException e) {System.out.println("FileNotFound");}
}
}
|
package com.wdl.webapp.controller.login;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.wdl.base.pojo.AjaxResult;
import com.wdl.entity.rbac.UserEntity;
import com.wdl.service.rbac.MenuService;
import com.wdl.service.rbac.RoleService;
import com.wdl.service.rbac.UserService;
import com.wdl.util.EncoderHandler;
import com.wdl.webapp.filter.SystemAuthorizingRealm;
/**
* @ClassName: userLoginController
* @Description: TODO
* @author sunfengle
* @date 2016年3月22日
*/
@Controller
@RequestMapping("/userLogin")
public class UserLoginController{
private final static Logger logger=Logger.getLogger(UserLoginController.class);
@Resource
private UserService userService;
@Resource
RoleService roleService;
@Resource
private SystemAuthorizingRealm systemAuthorizingRealm;
@RequestMapping("/userLogin")
public String userLogin() {
return "login/userLogin";
}
@RequestMapping("/change_password")
public String userPassword() {
return "login/change_password";
}
@RequestMapping(method=RequestMethod.POST,value="/selectUser")
@ResponseBody
public AjaxResult selectUser(String username, String password, String vcode, ServletRequest request,
ServletResponse response) {
logger.info("用户登录 用户:"+username);
AjaxResult result = new AjaxResult();
try {
UserEntity entity = userService.findUserByloginName(username);
if (entity != null) {
result.setCode(UsetLogin(username, password, vcode, request, response));
}
} catch (AuthenticationException ex) {
logger.error("",ex);
}
return result;
}
@Resource
MenuService menuService;
private int UsetLogin(String username, String password, String vcode, ServletRequest request,
ServletResponse response) {
int result = 0;
UserEntity user = new UserEntity();
user.setLoginName(username);
user.setPassWord(EncoderHandler.encode("SHA1", password));
user.setIsdel(0);
List<UserEntity> userList = userService.findByExample(user);
if (userList.size() > 0) {
user = userList.get(0);
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
session.setAttribute("loginName", user.getLoginName());
session.setAttribute("userName", user.getUserName());
session.setAttribute("id", user.getId());
session.setAttribute("userId", user.getId());
subject.login(new UsernamePasswordToken(username, EncoderHandler.encode("SHA1", password)));
/*
* try { onAccessDenied(request, response); } catch (Exception e) {
* // TODO Auto-generated catch block e.printStackTrace(); }
*/
if (subject.isAuthenticated()) {
result = 1;
}
} else {
result = 3;
}
return result;
}
@RequestMapping("/userLogout")
public String userLogout() {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
if (session != null) {
session.removeAttribute("id");
session.removeAttribute("loginName");
session.removeAttribute("userName");
session.removeAttribute("userId");
}
subject.logout();
return "login/userLogin";
}
@RequestMapping(value ="/update_password")
@ResponseBody
public AjaxResult updatePassword(String password, String verifyCode) {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
Long userId = Long.valueOf(session.getAttribute("updatePasswordUserId").toString());
AjaxResult result = new AjaxResult();
UserEntity userEntity = userService.get(UserEntity.class, userId);
if (userEntity != null) {
if (verifyCode != null) {
if (verifyCode.equals(userEntity.getValidataCode())) {
if (password != null && password.length() > 0) {
if (!userEntity.getPassWord().equals(EncoderHandler.encode("SHA1", password))) {
long outTime = new Date().getTime() - userEntity.getOutDate().getTime();
if (outTime <= 30 * 60 * 1000) {
userEntity.setPassWord(EncoderHandler.encode("SHA1", password));
userService.update(userEntity);
subject.logout();
result.setCode(3);
} else {
result.setCode(2); // 超时
}
} else {
result.setCode(5);// 相同的密码
}
} else {
result.setCode(4);// 没有输入密码
}
} else {
result.setCode(7);// 验证码错误
}
} else {
result.setCode(6);// 验证码不能为空
}
} else {
result.setCode(1);// key 错误
}
return result;
}
@RequestMapping(value ="/into_update_password")
public String update_password(HttpServletRequest request) {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
if (session != null) {
return "user/update_password";
} else {
return "login/userLogin";
}
}
@RequestMapping(value ="/user_update_password")
@ResponseBody
public AjaxResult userUpdatePassword(String password, String oldPassword) {
AjaxResult result = new AjaxResult();
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
if (session != null) {
UserEntity userEntity = userService.get(UserEntity.class,
Long.valueOf(session.getAttribute("id").toString()));
if (userEntity != null) {
if (password != null && password.length() > 0) {
if (userEntity.getPassWord().equals(EncoderHandler.encode("SHA1", oldPassword))) {
if (!userEntity.getPassWord().equals(EncoderHandler.encode("SHA1", password))) {
userEntity.setPassWord(EncoderHandler.encode("SHA1", password));
userService.update(userEntity);
result.setCode(3);
} else {
result.setCode(5);// 相同的密码
}
} else {
result.setCode(6);// 原密码错误
}
} else {
result.setCode(4);// 没有输入密码
}
} else {
result.setCode(1);// 没找到
}
}
return result;
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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.springframework.http.client;
import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import io.netty.channel.ChannelOption;
import reactor.netty.http.client.HttpClient;
import org.springframework.http.HttpMethod;
import org.springframework.util.Assert;
/**
* Reactor-Netty implementation of {@link ClientHttpRequestFactory}.
*
* @author Arjen Poutsma
* @since 6.1
*/
public class ReactorNettyClientRequestFactory implements ClientHttpRequestFactory {
private final HttpClient httpClient;
private Duration exchangeTimeout = Duration.ofSeconds(5);
private Duration readTimeout = Duration.ofSeconds(10);
/**
* Create a new instance of the {@code ReactorNettyClientRequestFactory}
* with a default {@link HttpClient} that has compression enabled.
*/
public ReactorNettyClientRequestFactory() {
this(HttpClient.create().compress(true));
}
/**
* Create a new instance of the {@code ReactorNettyClientRequestFactory}
* based on the given {@link HttpClient}.
* @param httpClient the client to base on
*/
public ReactorNettyClientRequestFactory(HttpClient httpClient) {
Assert.notNull(httpClient, "HttpClient must not be null");
this.httpClient = httpClient;
}
/**
* Set the underlying connect timeout in milliseconds.
* A value of 0 specifies an infinite timeout.
* <p>Default is 30 seconds.
* @see HttpClient#option(ChannelOption, Object)
* @see ChannelOption#CONNECT_TIMEOUT_MILLIS
*/
public void setConnectTimeout(int connectTimeout) {
Assert.isTrue(connectTimeout >= 0, "Timeout must be a non-negative value");
this.httpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
}
/**
* Set the underlying connect timeout in milliseconds.
* A value of 0 specifies an infinite timeout.
* <p>Default is 30 seconds.
* @see HttpClient#option(ChannelOption, Object)
* @see ChannelOption#CONNECT_TIMEOUT_MILLIS
*/
public void setConnectTimeout(Duration connectTimeout) {
Assert.notNull(connectTimeout, "ConnectTimeout must not be null");
Assert.isTrue(!connectTimeout.isNegative(), "Timeout must be a non-negative value");
this.httpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int)connectTimeout.toMillis());
}
/**
* Set the underlying read timeout in milliseconds.
* <p>Default is 10 seconds.
*/
public void setReadTimeout(long readTimeout) {
Assert.isTrue(readTimeout > 0, "Timeout must be a positive value");
this.readTimeout = Duration.ofMillis(readTimeout);
}
/**
* Set the underlying read timeout as {@code Duration}.
* <p>Default is 10 seconds.
*/
public void setReadTimeout(Duration readTimeout) {
Assert.notNull(readTimeout, "ReadTimeout must not be null");
Assert.isTrue(!readTimeout.isNegative(), "Timeout must be a non-negative value");
this.readTimeout = readTimeout;
}
/**
* Set the timeout for the HTTP exchange in milliseconds.
* <p>Default is 30 seconds.
*/
public void setExchangeTimeout(long exchangeTimeout) {
Assert.isTrue(exchangeTimeout > 0, "Timeout must be a positive value");
this.exchangeTimeout = Duration.ofMillis(exchangeTimeout);
}
/**
* Set the timeout for the HTTP exchange.
* <p>Default is 30 seconds.
*/
public void setExchangeTimeout(Duration exchangeTimeout) {
Assert.notNull(exchangeTimeout, "ExchangeTimeout must not be null");
Assert.isTrue(!exchangeTimeout.isNegative(), "Timeout must be a non-negative value");
this.exchangeTimeout = exchangeTimeout;
}
@Override
public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) throws IOException {
return new ReactorNettyClientRequest(this.httpClient, uri, httpMethod, this.exchangeTimeout, this.readTimeout);
}
}
|
/*
* /*
* * Copyright (C) Henryk Timur Domagalski
* *
* * 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 net.henryco.opalette.api.utils.views.widgets;
import android.widget.SeekBar;
/**
* Created by HenryCo on 18/03/17.
*/
public class OPallSeekBarListener implements SeekBar.OnSeekBarChangeListener {
public interface progress {
void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser);
}
public interface start {
void onStartTrackingTouch(SeekBar seekBar);
}
public interface stop {
void onStopTrackingTouch(SeekBar seekBar);
}
private progress p = null;
private start str = null;
private stop stp = null;
public OPallSeekBarListener onProgress(progress p) {
this.p = p;
return this;
}
public OPallSeekBarListener
onProgress(OPallSeekBarListener bar) {
return onProgress(bar.p);
}
public OPallSeekBarListener onStart(start str) {
this.str = str;
return this;
}
public OPallSeekBarListener onStart(OPallSeekBarListener bar) {
return onStart(bar.str);
}
public OPallSeekBarListener onStop(stop stp) {
this.stp = stp;
return this;
}
public OPallSeekBarListener onStop(OPallSeekBarListener bar) {
return onStop(bar.stp);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (p != null) p.onProgressChanged(seekBar, progress, fromUser);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
if (str != null) str.onStartTrackingTouch(seekBar);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (stp != null) stp.onStopTrackingTouch(seekBar);
}
}
|
package com.wellsfargo.SBA3.its.exceptions;
public class UserException extends Exception {
public UserException(String errMsg){
super(errMsg);
}
}
|
package com.itfacesystem.domain.org;
import com.itfacesystem.domain.common.BaseDomain;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
/**
* Created by wangrongtao on 15/10/13.
*/
public class User extends BaseDomain implements Comparable<User>{
private long id;
@NotBlank
@Length(max=100)
private String name;
/**
* 手机号
*/
@NotBlank
@Length(max=100)
private String userid;
private String pwd;
/**
* 帐号状态,预留,1是正常,-1锁定
*/
private int status;
private long orgid;
private long lastlogintime;
private String lastlogintimestr;
private int loginfailcount;
/**
* 0代表密码验证,1代码短信验证
*/
private int logintype;
private String wechatopenid;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public long getOrgid() {
return orgid;
}
public void setOrgid(long orgid) {
this.orgid = orgid;
}
public int getLoginfailcount() {
return loginfailcount;
}
public void setLoginfailcount(int loginfailcount) {
this.loginfailcount = loginfailcount;
}
public long getLastlogintime() {
return lastlogintime;
}
public void setLastlogintime(long lastlogintime) {
this.lastlogintime = lastlogintime;
}
public String getLastlogintimestr() {
return lastlogintimestr;
}
public void setLastlogintimestr(String lastlogintimestr) {
this.lastlogintimestr = lastlogintimestr;
}
public int getLogintype() {
return logintype;
}
public void setLogintype(int logintype) {
this.logintype = logintype;
}
public String getWechatopenid() {
return wechatopenid;
}
public void setWechatopenid(String wechatopenid) {
this.wechatopenid = wechatopenid;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return userid.equals(user.userid);
}
@Override
public int hashCode() {
return userid.hashCode();
}
@Override
public int compareTo(User o) {
if (o != null) {
return id > o.getId()?1:-1;
}
return 0;
}
}
|
// https://java.keicode.com/lang/operators.php
// javac -encoding utf-8 OpTest4.java
package operator;
public class OpTest4 {
public static void main(String[] args) {
boolean a;
a = ( 1 == 2 );
System.out.println( a );
a = ( 1 < 2 );
System.out.println( a );
}
}
|
package br.com.huegroup.salao.json;
import java.io.IOException;
import org.joda.time.LocalTime;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
public class LocalTimeDeserializer extends StdDeserializer<LocalTime> {
protected LocalTimeDeserializer() {
this(LocalTime.class);
}
protected LocalTimeDeserializer(Class<LocalTime> t) {
super(t);
}
private static final long serialVersionUID = 1L;
@Override
public LocalTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
TreeNode node = p.getCodec().readTree(p);
return new LocalTime(node.get("hora"));
}
}
|
package com.sherry.epaydigital.bussiness.domain;
import com.sherry.epaydigital.data.model.Card;
import java.util.List;
import java.util.Set;
public class CustomerDomain {
private long id;
private String first_name;
private String last_name;
private String email;
private String password;
private String re_password;
private String city;
private String country;
private String address_line1;
private String address_line2;
private String postal_code;
private String state;
private String image;
private String phone_number;
private Set<Card> cardSet;
public Set<Card> getCardSet() {
return cardSet;
}
public void setCardSet(Set<Card> cardSet) {
this.cardSet = cardSet;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return first_name;
}
public void setFirstName(String firstName) {
this.first_name = firstName;
}
public String getLastName() {
return last_name;
}
public void setLastName(String lastName) {
this.last_name = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRePassword() {
return re_password;
}
public void setRePassword(String rePassword) {
this.re_password = rePassword;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAddressLine1() {
return address_line1;
}
public void setAddressLine1(String addressLine1) {
this.address_line1 = addressLine1;
}
public String getAddressLine2() {
return address_line2;
}
public void setAddressLine2(String addressLine2) {
this.address_line2 = addressLine2;
}
public String getPostalCode() {
return postal_code;
}
public void setPostalCode(String postalCode) {
this.postal_code = postalCode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPhoneNumber() {
return phone_number;
}
public String getImage() {
return image;
}
public void setImage(String image) {
if (image == null)
this.image = null;
else
this.image = "/uploads/userPhotos/" + image;
}
public void setPhoneNumber(String phoneNumber) {
this.phone_number = phoneNumber;
}
}
|
package com.T_Y.controller;
import com.T_Y.model.User;
import java.io.IOException;
import java.sql.SQLException;
public class UserManagement {
// public String[] showFavorites(User tempUser) throws SQLException, IOException, ClassNotFoundException {
// return tempUser.getFavoritesArr();
// }
}
|
/*
* 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 pl.polsl.aei.io.turnieje.model.datamodel;
/**
* Id datatype pattern
*
* @author Piotr Uhl
*/
public abstract class Id {
public final int id;
public Id(int id) {
this.id = id;
}
public Id(String id) throws NumberFormatException {
this(Integer.parseInt(id));
}
}
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(Sensorcate)传感器类型
//generate by redcloud,2020-07-24 19:59:20
public class Sensorcate implements Serializable {
private static final long serialVersionUID = 59L;
// 自增ID
private Long id ;
// 名称
private String title ;
// 图标
private String url ;
// 设备数量
private String sensornum ;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url ;
}
public void setUrl(String url) {
this.url = url;
}
public String getSensornum() {
return sensornum ;
}
public void setSensornum(String sensornum) {
this.sensornum = sensornum;
}
}
|
package com.Hellel.PSoloid.homework7.MyLinkedList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;
/**
* Created by otk_prog on 14.07.2015.
*/
public class MyLinkedListApp<T> {
public static void main(String[] args) {
Node elem1 = new Node("11");
Node elem2 = new Node("22");
Node elem3 = new Node("33");
Node elem4 = new Node("44");
Node elem5 = new Node("55");
MyLinkedList myList = new MyLinkedList();
myList.add(elem1);
myList.add(elem2);
myList.add(elem3);
myList.add(elem4);
myList.add(elem5);
myList.print();
System.out.println("\nReverse print\n");
myList.reversePrint();
if (myList.isEmpty()) {
System.out.println("MyLinkedList is empty");
} else {
System.out.println("MyLinkedList is not empty");
}
if (myList.contains(elem2)) {
System.out.println("MyLinkedList contains elem2");
} else {
System.out.println("MyLinkedList does not contains elem2");
}
if (myList.remove(elem2)) {
System.out.println("elem2 removed");
} else {
System.out.println("elem2 didn't remove");
}
myList.print();
List list = Arrays.asList(1, 2, 3, 4, 5);
if (myList.addAll(list)) {
System.out.println("stringList added");
} else {
System.out.println("stringList did not add");
}
myList.print();
// MyCollection group1 = new MyCollection();
//
// Student student7 = new Student(7, "Fedya");
// Student student8 = new Student(8, "Vasya");
//
// group1.add(student3);
// group1.add(student4);
// group1.add(student7);
// group1.add(student8);
//
//
// group1.print();
if (myList.containsAll(list)) {
System.out.println("group1 contained");
} else {
System.out.println("group1 did not contain");
}
myList.print();
if (myList.retainAll(list)) {
System.out.println("group1 retained");
} else {
System.out.println("group1 did not retain");
}
myList.print();
// myList.add(student1);
// myList.add(student2);
// myList.add(student5);
// myList.add(student6);
// myList.add(student7);
// myList.add(student8);
//
// myList.print();
if (myList.removeAll(list)) {
System.out.println("removed All");
} else {
System.out.println("did not remove All");
}
myList.print();
myList.clear();
System.out.println("MyLinkedList is clear");
myList.print();
try {
myList.reversePrint();
} catch (NoSuchElementException e) {
System.out.println("List is empty");
e.printStackTrace();
}
}
}
|
package be.mxs.common.util.pdf.general.oc.examinations;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import be.mxs.common.util.pdf.general.PDFGeneralBasic;
public class PDFNeuropsyOutpatientSummary extends PDFGeneralBasic {
//--- ADD CONTENT ------------------------------------------------------------------------------
protected void addContent(){
try{
if(transactionVO.getItems().size() >= minNumberOfItems){
/*
//*** DIAGNOSTICS *********************************************
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_CONTEXT_ENCOUNTERUID");
if(itemValue.length() > 0){
table = new PdfPTable(5);
addEncounterDiagnosticsRow(table, itemValue);
tranTable.addCell(createContentCell(table));
}
*/
//*** MEDICAL SUMMARY *****************************************
table = new PdfPTable(5);
table.setWidthPercentage(100);
cell = createHeaderCell(getTran("web","medicalsummary"),5);
table.addCell(cell);
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_NPOS_REASONFORENCOUNTER");
if(itemValue.length() > 0){
addItemRow(table,getTran("web","reason.for.encounter"),itemValue);
}
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_NPOS_COMPLEMENTARYEXAMS");
if(itemValue.length() > 0){
addItemRow(table,getTran("web","complentary.exams"),itemValue);
}
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_NPOS_MEASURESTAKEN");
if(itemValue.length() > 0){
addItemRow(table,getTran("web","disease.evolution"),itemValue);
}
itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_NPOS_RECCOMMENDATIONS");
if(itemValue.length() > 0){
addItemRow(table,getTran("web","specific.reccommendations"),itemValue);
}
// add table
if(table.size() > 0){
tranTable.addCell(createContentCell(table));
}
// add transaction to doc
addTransactionToDoc();
// diagnoses
addDiagnosisEncoding(true,true,true);
addTransactionToDoc();
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
|
package com.hlx.view.play;
import com.hlx.model.Score;
import com.hlx.view.common.PositionUtil;
import com.hlx.view.common.TipLabel;
import com.hlx.view.common.TranslucentPanel;
import java.util.*;
/**
* The rank view of play frame
* @author hlx
* @version 2018-3-20
*/
public class RankPanel extends TranslucentPanel implements Observer{
private DataService dataService;
private List<ScorePanel> scorePanelList;
public RankPanel(float transparency,DataService dataService) {
super();
this.setTransparency(transparency);
this.setSize(260, 250);
this.dataService = dataService;
dataService.attach(this);
initTitleLabel();
initScoreLabel();
}
private void initTitleLabel() {
TipLabel titleLabel = new TipLabel("积分榜", 20);
titleLabel.setSize(60, 20);
titleLabel.setLocation(-1, 15);
PositionUtil.setMiddle(titleLabel,this);
}
private void initScoreLabel() {
scorePanelList = new ArrayList<>(Arrays.asList(
new ScorePanel(5),
new ScorePanel(4),
new ScorePanel(3),
new ScorePanel(2),
new ScorePanel(1)
));
int y = 45;
for (ScorePanel scorePanel : scorePanelList) {
scorePanel.setLocation(40, y);
y = y + 35;
this.add(scorePanel);
}
}
public void clear() {
for (ScorePanel scorePanel : scorePanelList) {
scorePanel.clear();
}
}
public void update() {
List<Score> scoreSet = dataService.getScoreList();
int i = scoreSet.size()-1;
for (Score score : scoreSet) {
scorePanelList.get(i).setScore(score);
i = i - 1;
}
}
}
|
package com.citibank.ods.modules.product.prodriskcatprvt.functionality.valueobject;
import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO;
import com.citibank.ods.entity.pl.BaseTplProdRiskCatPrvtEntity;
/**
* @author leonardo.nakada
*
*
* Preferences - Java - Code Style - Code Templates
*/
public class BaseProdRiskCatPrvtDetailFncVO extends BaseODSFncVO
{
/**
* Constante do nome do elemento Código
*/
public static final String C_PROD_RISK_CAT_CODE_DESCRIPTION = "Código da Categoria de Risco";
/**
* Constante da descricao da categoria de risco
*/
public static final String C_PROD_RISK_CAT_TEXT_DESCRIPTION = "Descrição da Categoria de Risco";
/**
* Entity
*/
protected BaseTplProdRiskCatPrvtEntity m_baseTplProdRiskCatPrvtEntity;
/**
* @return Returns the baseTplProdRiskCatPrvtEntity.
*/
public BaseTplProdRiskCatPrvtEntity getBaseTplProdRiskCatPrvtEntity()
{
return m_baseTplProdRiskCatPrvtEntity;
}
/**
* @param baseTplProdRiskCatPrvtEntity_ The baseTplProdRiskCatPrvtEntity to
* set.
*/
public void setBaseTplProdRiskCatPrvtEntity(
BaseTplProdRiskCatPrvtEntity baseTplProdRiskCatPrvtEntity_ )
{
m_baseTplProdRiskCatPrvtEntity = baseTplProdRiskCatPrvtEntity_;
}
}
|
package au.gov.nsw.records.digitalarchive.search;
public class OpenGovFacet {
private String dataPublished;
private String type;
private String coverage;
private String rights;
private String agencyName;
private String content_type;
public String getDataPublished() {
return dataPublished;
}
public void setDataPublished(String dataPublished) {
this.dataPublished = dataPublished;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCoverage() {
return coverage;
}
public void setCoverage(String coverage) {
this.coverage = coverage;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
public String getAgencyName() {
return agencyName;
}
public void setAgencyName(String agencyName) {
this.agencyName = agencyName;
}
public String getContent_type() {
return content_type;
}
public void setContent_type(String content_type) {
this.content_type = content_type;
}
}
|
package com.twair;
/**
* Created by sangeeth on 02-04-2016.
*/
public enum SeatTypes {
BUSINESSCLASS("Business Class"), FIRSTCLASS("First Class"), ECONOMYCLASS("Economy Class");
private final String className;
private SeatTypes(String className)
{
this.className = className;
}
public String getClassName() {
return className;
}
}
|
package com.gxtc.huchuan.ui.mine.classroom.directseedingbackground.livebgsetting;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.gxtc.commlibrary.base.BaseTitleActivity;
import com.gxtc.commlibrary.utils.ToastUtil;
import com.gxtc.huchuan.Constant;
import com.gxtc.huchuan.R;
import com.gxtc.huchuan.bean.ChatInviteUrlBean;
import com.gxtc.huchuan.bean.event.EventSelectFriendBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.handler.CircleShareHandler;
import com.gxtc.huchuan.helper.RxTaskHelper;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.MineApi;
import com.gxtc.huchuan.im.ui.ConversationActivity;
import com.gxtc.huchuan.im.ui.ConversationListActivity;
import com.gxtc.huchuan.ui.circle.homePage.CircleInviteActivity;
import com.gxtc.huchuan.ui.mine.focus.FocusActivity;
import com.gxtc.huchuan.utils.ImMessageUtils;
import com.gxtc.huchuan.utils.LoginErrorCodeUtil;
import com.gxtc.huchuan.utils.RIMErrorCodeUtil;
import com.gxtc.huchuan.utils.RongIMTextUtil;
import com.gxtc.huchuan.utils.UMShareUtils;
import com.umeng.socialize.bean.SHARE_MEDIA;
import java.util.HashMap;
import butterknife.BindView;
import butterknife.OnClick;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Message;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Describe:邀请(管理员,主持人,普通成员)嘉宾
* Created by ALing on 2017/3/22.
*/
public class InvitedGuestsActivity extends BaseTitleActivity implements View.OnClickListener {
private static final String TAG = InvitedGuestsActivity.class.getSimpleName();
@BindView(R.id.btn_send_to_webchat) Button btnSendToWebchat;
@BindView(R.id.text1) TextView text1;
@BindView(R.id.text2) TextView text2;
@BindView(R.id.text3) TextView text3;
@BindView(R.id.text4) TextView text4;
@BindView(R.id.text5) TextView text5;
private UMShareUtils shareUtils;
private String shareUrl;
private String facePic;
private String Type;
private String name;
private String id;
private String freeSign;
private String rolerType;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_invite_guests);
}
@Override
public void initView() {
getBaseHeadView().showBackButton(this);
Type = getIntent().getStringExtra("Type");
name = getIntent().getStringExtra("name");
id = getIntent().getStringExtra("id");
facePic = getIntent().getStringExtra("facePic");
if ("1".equals(Type)) {
rolerType = CircleShareHandler.SHARE_CLASS_ADMIN + "";
ConversationListActivity.CAN_SHARE_INVITE = 9;
getBaseHeadView().showTitle("邀请管理员");
setAdminInfo();
} else if ("2".equals(Type)) {
rolerType = CircleShareHandler.SHARE_TEACHER;
ConversationListActivity.CAN_SHARE_INVITE = 8;
getBaseHeadView().showTitle("邀请讲师");
setSpeakerInfo();
//免费邀请课堂
} else if("3".equals(Type)){
rolerType = CircleShareHandler.SHARE_FREE_CLASS;
ConversationListActivity.CAN_SHARE_INVITE = 10;
getBaseHeadView().showTitle("邀请学员");
setStudentInfo();
//免费邀请系列课
}else{
rolerType = CircleShareHandler.SHARE_FREE_SERIES;
ConversationListActivity.CAN_SHARE_INVITE = 11;
getBaseHeadView().showTitle("邀请学员");
setStudentInfo();
}
getInviteUrl();
}
private void setAdminInfo() {
text1.setText("邀请管理员说明:");
text2.setText("管理员可以协助创建者管理课堂间");
text3.setText("管理员权限跟创建者一致,但不能添加和删除管理员,不能操作课堂间提现功能");
text4.setText("课堂创建者可以删除管理员");
text5.setText("邀请管理员的链接已复制,点击下方按钮发送给好友,好友点击后即可成为管理员");
}
private void setSpeakerInfo() {
text1.setText("邀请讲师说明:");
text2.setText("讲师可以在当次课堂课程发言");
text3.setText("创建新的课堂课程后,需要重新邀请讲师");
text4.setText("课堂创建者可以删除讲师");
text5.setText("点击下方按钮发送给好友,好友点击后即可成为讲师,每次发送只能邀请1位");
}
private void setStudentInfo() {
text1.setText("邀请学员说明:");
text2.setText("邀请的学员可以免费报名进入本次课程");
text3.setText("课程创建者与管理员可以禁言、删除学员");
text4.setText("");
text5.setText("邀请学员免费加入课程的链接已复制,点击下方按钮发送给好友,好友点击后即可免费加入课程");
}
private void setSeriersInfo() {
text1.setText("邀请学员说明:");
text2.setText("邀请的学员可以免费报名进入本次系列课");
text3.setText("课程创建者与管理员可以禁言、删除学员");
text4.setText("");
text5.setText("邀请学员免费加入系列课的链接已复制,点击下方按钮发送给好友,好友点击后即可免费加入系列课");
}
@OnClick({R.id.btn_send_to_webchat, R.id.btn_send_to_xinmt})
public void onClick(View view) {
switch (view.getId()) {
//返回
case R.id.headBackButton:
finish();
break;
//发送给微信好友
case R.id.btn_send_to_webchat:
if(!TextUtils.isEmpty(shareUrl)){
share(SHARE_MEDIA.WEIXIN);
}
break;
case R.id.btn_send_to_xinmt:
if(!TextUtils.isEmpty(freeSign)){
ConversationListActivity.startActivity(InvitedGuestsActivity.this, ConversationActivity.REQUEST_SHARE_INVITE,Constant.SELECT_TYPE_SHARE,ConversationListActivity.CAN_SHARE_INVITE);
}
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ConversationActivity.REQUEST_SHARE_INVITE && resultCode == RESULT_OK) {
EventSelectFriendBean bean = data.getParcelableExtra(Constant.INTENT_DATA);
sendRongIm(bean);
}
}
@Override
protected void onDestroy() {
RxTaskHelper.getInstance().cancelTask(this);
super.onDestroy();
}
/**
* 获取免费邀请的的 邀请url 以及 邀请码
* 1、邀请管理员 2、邀请讲师 3、免费邀请学员进课堂 4、免费邀请学员进系列课
*/
private void getInviteUrl() {
getBaseLoadingView().showLoading(true);
HashMap<String,String> map = new HashMap<>();
map.put("token", UserManager.getInstance().getToken());
map.put("chatInfoId",id);
map.put("joinType",Type);
Subscription sub =
MineApi.getInstance().getChatInviteUrl(map).subscribeOn(Schedulers.io()).observeOn(
AndroidSchedulers.mainThread()).subscribe(
new ApiObserver<ApiResponseBean<ChatInviteUrlBean>>(new ApiCallBack<ChatInviteUrlBean>() {
@Override
public void onSuccess(ChatInviteUrlBean data) {
if(getBaseLoadingView() == null) return;
getBaseLoadingView().hideLoading();
shareUrl = data.getUrl();
freeSign = data.getFreeSign();
}
@Override
public void onError(String errorCode, String message) {
if(getBaseLoadingView() == null) return;
getBaseLoadingView().hideLoading();
LoginErrorCodeUtil.showHaveTokenError(InvitedGuestsActivity.this, errorCode, message);
}
}));
RxTaskHelper.getInstance().addTask(this, sub);
}
private void share(final SHARE_MEDIA shareMedia) {
String title = "";
switch (Type){
case "1":
title = "管理员";
break;
case "2":
title = "讲师";
break;
case "3":
title = "学员";
break;
default:
title = "嘉宾";
break;
}
new UMShareUtils(InvitedGuestsActivity.this).shareOne(shareMedia,
UserManager.getInstance().getUser().getHeadPic(), "新媒之家"+title+"邀请链接", "向你发出"+title+"邀请链接",
shareUrl);
}
private void sendRongIm(final EventSelectFriendBean bean) {
String title = "";
if ("1".equals(Type)) {
title = UserManager.getInstance().getUserName() + "邀请你成为" + name + "管理员";
} else if ("2".equals(Type)) {
title = UserManager.getInstance().getUserName() + "邀请你成为" + name + "讲师";
}else if ("3".equals(Type)) {
title = UserManager.getInstance().getUserName() + "邀请你免费加入" + name;
}else if ("4".equals(Type)) {
title = UserManager.getInstance().getUserName() + "邀请你免费加入" + name;
}
String TitleId = id + "&" + freeSign;
ImMessageUtils.shareMessage(bean.targetId, bean.mType, TitleId, title, facePic, rolerType,
new IRongCallback.ISendMessageCallback() {
@Override
public void onAttached(Message message) {}
@Override
public void onSuccess(Message message) {
ToastUtil.showShort(InvitedGuestsActivity.this, "分享成功");
if(!TextUtils.isEmpty(bean.liuyan)){
RongIMTextUtil.INSTANCE.relayMessage
(bean.liuyan,bean.targetId,bean.mType);
}
}
@Override
public void onError(Message message, RongIMClient.ErrorCode errorCode) {
ToastUtil.showShort(InvitedGuestsActivity.this, "分享失败: " + RIMErrorCodeUtil.handleErrorCode(errorCode));
}
});
}
/**
* @param Type 1、邀请管理员 2、邀请讲师 3、免费邀请学员进课堂 4、免费邀请学员进系列课
*/
public static void startActivity(Context context, String Id, String Type, String name, String facePic) {
Intent intent = new Intent(context, InvitedGuestsActivity.class);
intent.putExtra("Type", Type);
intent.putExtra("name", name);
intent.putExtra("id", Id);
intent.putExtra("facePic", facePic);
context.startActivity(intent);
}
public static void startActivity(Context context, String shareUrl) {
Intent intent = new Intent(context, InvitedGuestsActivity.class);
intent.putExtra("shareUrl", shareUrl);
context.startActivity(intent);
}
}
|
package com.mpls.v2.dto;
import java.util.List;
public class IndustriesFullDto extends IndustriesShortDto {
List<BlogShortDto> blogsList;
public List<BlogShortDto> getBlogsList() {
return blogsList;
}
public IndustriesFullDto setBlogsList(List<BlogShortDto> blogsList) {
this.blogsList = blogsList;
return this;
}
@Override
public String toString() {
return "IndustriesFullDto{" +
"blogsList=" + blogsList +
", id=" + id +
", name='" + name + '\'' +
", description='" + description + '\'' +
", image='" + image + '\'' +
'}';
}
}
|
package mydomain.needit;
/**
* Created by Michal on 08/03/2016.
*/
public class Response {
UserLocation userLocation;
private final String responseToUser;
public String getResponseToaccessToken() {
return responseToaccessToken;
}
private final String responseToaccessToken;
public UserLocation getUserLocation() {
return userLocation;
}
public String getResponseToUser() {
return responseToUser;
}
public Response(UserLocation userLocation, String responseToUser, String responseToaccessToken) {
this.userLocation = userLocation;
this.responseToUser = responseToUser;
this.responseToaccessToken = responseToaccessToken;
}
@Override
public boolean equals(Object o) {
if (o instanceof Response) {
Response r = (Response) o;
return r.getUserLocation().getUserID().equals(this.getUserLocation().getUserID()) && r.getUserLocation().getLocation().equals(this.getUserLocation().getLocation()) && r.getResponseToUser().equals(this.getResponseToUser());
}
return false;
}
}
|
package com.xld.common.bean.ENUM;
/**
* 业务码
* @author xld
*/
public interface BusinessCode {
/**
* 获取业务错误码
* @return 错误码
*/
int getCode();
/**
* 获取业务错误信息
* @return 业务错误信息
*/
String getMessage();
}
|
package com.ak.texasholdem.winconditions;
public enum HandTypes {
HIGH_CARD(1), PAIR(2), TWO_PAIRS(3), TRIPLE(4), STRAIGHT(5), FLUSH(6), FULL_HOUSE(7), FOUR_OF_A_KIND(8),
STRAIGHT_FLUSH(9), ROYAL_FLUSH(10);
private int value;
private HandTypes(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
|
package com.junzhao.shanfen.pws;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import com.junzhao.shanfen.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
/**
* Created by Administrator on 2018/4/23 0023.
*/
public class SelectorPhotoPopWindow extends PopupWindow {
private View view;
private Context context;
private View.OnClickListener onClickListener;
public void setOnClickListener(View.OnClickListener onClickListener){
this.onClickListener = onClickListener;
}
public SelectorPhotoPopWindow(Context context){
super(context);
this.context = context;
view = LayoutInflater.from(context).inflate(R.layout.dialog_selector_photo,null,false);
ViewUtils.inject(this,view);
setContentView(view);
setOutsideTouchable(false);
// 设置PopupWindow是否能响应点击事件
setTouchable(true);
setWidth(LinearLayout.LayoutParams.WRAP_CONTENT);
setBackgroundDrawable(new ColorDrawable(Color.WHITE));
}
@OnClick({R.id.tv_photo,R.id.tv_video})
public void onClick(View view){
if (onClickListener != null){
onClickListener.onClick(view);
dismiss();
}
}
}
|
package ru.aggregator.object.response;
import ru.aggregator.model.Gene;
/**
* Created by user on 03.01.2015.
*/
public class GeneResponse extends AbstractResponse {
public static GeneResponse create(Gene entity) {
GeneResponse response = new GeneResponse();
response.setId(entity.getId());
response.setName(entity.getName());
return response;
}
}
|
package br.com.ifpb.observer;
import java.util.Objects;
public class User implements Subscriber {
private String email;
public User(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public void update(User u, User u2, String message) {
System.out.printf("O usuario %s recebeu a mensagem: %s \nenviada por %s recebeu.\n", getEmail(), message, u);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return email.equals(user.email);
}
@Override
public int hashCode() {
return Objects.hash(email);
}
@Override
public String toString() {
return "Usuario = " + "email: [" + email + "]";
}
}
|
package Teatrus.persistence;
import Teatrus.model.Spectacol;
public interface IRepositorySpectacol extends IRepository<Integer, Spectacol> {
}
|
/**
* Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT
* Copyright (c) 2006-2018, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Commercial License
* ================================================================================
* This version of Sencha GXT is licensed commercially and is the appropriate
* option for the vast majority of use cases.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.window;
import static com.sencha.gxt.core.client.Style.Anchor.CENTER;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.Style.AnchorAlignment;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.client.resources.ThemeStyles;
import com.sencha.gxt.data.shared.IconProvider;
import com.sencha.gxt.data.shared.TreeStore;
import com.sencha.gxt.examples.resources.client.ExampleStyles;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.examples.resources.client.Utils;
import com.sencha.gxt.examples.resources.client.Utils.Theme;
import com.sencha.gxt.examples.resources.client.images.ExampleImages;
import com.sencha.gxt.examples.resources.client.model.NameImageModel;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.container.AccordionLayoutContainer;
import com.sencha.gxt.widget.core.client.container.AccordionLayoutContainer.AccordionLayoutAppearance;
import com.sencha.gxt.widget.core.client.container.AccordionLayoutContainer.ExpandMode;
import com.sencha.gxt.widget.core.client.container.SimpleContainer;
import com.sencha.gxt.widget.core.client.tree.Tree;
@Detail(
name = "Accordion Window",
category = "Windows",
icon = "accordionwindow",
preferredWidth = AccordionWindowExample.PREFERRED_WIDTH,
preferredHeight = AccordionWindowExample.PREFERRED_HEIGHT,
preferredMargin = AccordionWindowExample.PREFERRED_MARGIN,
classes = { Utils.class, TestData.class }
)
public class AccordionWindowExample implements IsWidget, EntryPoint {
protected static final int PREFERRED_WIDTH = 1;
protected static final int PREFERRED_HEIGHT = 1;
// keep margins for window shadow
protected static final int PREFERRED_MARGIN = 2;
private SimpleContainer container;
private Window window;
@Override
public Widget asWidget() {
if (container == null) {
AccordionLayoutAppearance appearance = GWT.<AccordionLayoutAppearance> create(AccordionLayoutAppearance.class);
final NameImageModel modelFamily = newItem("Family", null);
final NameImageModel modelFriends = newItem("Friends", null);
TreeStore<NameImageModel> store = new TreeStore<NameImageModel>(NameImageModel.KP);
store.add(modelFamily);
store.add(modelFamily, newItem("John", "user"));
store.add(modelFamily, newItem("Olivia", "user-girl"));
store.add(modelFamily, newItem("Noah", "user-kid"));
store.add(modelFamily, newItem("Emma", "user-kid"));
store.add(modelFamily, newItem("Liam", "user-kid"));
store.add(modelFriends);
store.add(modelFriends, newItem("Mason", "user"));
store.add(modelFriends, newItem("Sophia", "user-girl"));
store.add(modelFriends, newItem("Isabella", "user-girl"));
store.add(modelFriends, newItem("Jacob", "user"));
Tree<NameImageModel, String> tree = new Tree<NameImageModel, String>(store,
new ValueProvider<NameImageModel, String>() {
@Override
public String getValue(NameImageModel object) {
return object.getName();
}
@Override
public void setValue(NameImageModel object, String value) {
}
@Override
public String getPath() {
return "name";
}
}) {
@Override
protected void onAfterFirstAttach() {
super.onAfterFirstAttach();
setExpanded(modelFamily, true);
setExpanded(modelFriends, true);
}
};
tree.setIconProvider(new IconProvider<NameImageModel>() {
public ImageResource getIcon(NameImageModel model) {
if (null == model.getImage()) {
return null;
} else if ("user-girl" == model.getImage()) {
return ExampleImages.INSTANCE.userFemale();
} else if ("user-kid" == model.getImage()) {
return ExampleImages.INSTANCE.userKid();
} else {
return ExampleImages.INSTANCE.user();
}
}
});
ContentPanel cp1 = new ContentPanel(appearance);
cp1.setHeading("Online Users");
cp1.add(tree);
if (Theme.BLUE.isActive() || Theme.GRAY.isActive()) {
cp1.getHeader().addStyleName(ThemeStyles.get().style().borderTop());
}
ContentPanel cp2 = new ContentPanel(appearance);
cp2.setBodyStyleName(ExampleStyles.get().paddedText());
cp2.setHeading("Settings");
cp2.add(new Label(TestData.DUMMY_TEXT_SHORT));
ContentPanel cp3 = new ContentPanel(appearance);
cp3.setBodyStyleName(ExampleStyles.get().paddedText());
cp3.setHeading("Stuff");
cp3.add(new Label(TestData.DUMMY_TEXT_SHORT));
ContentPanel cp4 = new ContentPanel(appearance);
cp4.setBodyStyleName(ExampleStyles.get().paddedText());
cp4.setHeading("More Stuff");
cp4.add(new Label(TestData.DUMMY_TEXT_SHORT));
AccordionLayoutContainer accordion = new AccordionLayoutContainer();
accordion.setExpandMode(ExpandMode.SINGLE_FILL);
accordion.add(cp1);
accordion.add(cp2);
accordion.add(cp3);
accordion.add(cp4);
accordion.setActiveWidget(cp1);
container = new SimpleContainer() {
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
window.show();
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
// since this is deferred, check that window is actually visible
if (window.isVisible()) {
window.alignTo(container.getElement(), new AnchorAlignment(CENTER, CENTER), 0, 0);
}
}
});
} else {
window.hide();
}
}
};
window = new Window();
window.setResizable(false);
window.setHeading("Accordion Window");
window.setWidth(275);
window.setHeight(350);
window.add(accordion);
window.setClosable(false);
window.getDraggable().setContainer(container);
}
return container;
}
private NameImageModel newItem(String text, String iconStyle) {
return new NameImageModel(text, iconStyle);
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setPreferredWidth(PREFERRED_WIDTH)
.setPreferredHeight(PREFERRED_HEIGHT)
.setPreferredMargin(PREFERRED_MARGIN)
.doStandalone();
}
}
|
package BinaryTree;
/*
相同节点值的最大路径长度
687. Longest Univalue Path (Easy)
1
/ \
4 5
/ \ \
4 4 5
Output : 2
*/
public class LongestUnivaluePath {
private int path = 0;
public int longestUnivaluePath(TreeNode root) {
dfs(root);
return path;
}
public int dfs(TreeNode root) {
if(root == null) return 0;
int left = dfs(root.leftChild);
int right = dfs(root.rightChild);
int leftPath = root.leftChild != null && root.leftChild.data == root.data ? left + 1 : 0;
int rightPath = root.rightChild != null && root.rightChild.data == root.data ? right + 1 : 0;
path = Math.max(path, leftPath+rightPath);
return Math.max(leftPath, rightPath);
}
}
|
package vnfoss2010.smartshop.serverside.services.comment;
import java.util.List;
import java.util.Map;
import vnfoss2010.smartshop.serverside.Global;
import vnfoss2010.smartshop.serverside.database.CommentServiceImpl;
import vnfoss2010.smartshop.serverside.database.ServiceResult;
import vnfoss2010.smartshop.serverside.database.entity.Comment;
import vnfoss2010.smartshop.serverside.services.BaseRestfulService;
import vnfoss2010.smartshop.serverside.services.exception.MissingParameterException;
import vnfoss2010.smartshop.serverside.services.exception.RestfulException;
import com.google.appengine.repackaged.org.json.JSONObject;
import com.google.gson.JsonObject;
public class GetCommentService extends BaseRestfulService {
private static CommentServiceImpl dbComment = CommentServiceImpl.getInstance();
public GetCommentService(String serviceName) {
super(serviceName);
}
@Override
public String process(Map<String, String[]> params, String content)
throws Exception, RestfulException {
JSONObject json = null;
JsonObject jsonReturn = new JsonObject();
try {
json = new JSONObject(content);
} catch (Exception e) {
}
String commentType = getParameterWithThrow("type", params, json);
Long typeID = Long.parseLong(getParameterWithThrow("type_id", params,
json));
ServiceResult<List<Comment>> result = dbComment.getComment(typeID,
commentType);
if (result.isOK()) {
jsonReturn.addProperty("errCode", 0);
jsonReturn.add("comments", Global.gsonWithDate.toJsonTree(result
.getResult()));
} else {
jsonReturn.addProperty("errCode", 1);
}
jsonReturn.addProperty("message", result.getMessage());
return jsonReturn.toString();
}
}
|
package com.keega.weixin.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* 我的薪酬控制器
* Created by zun.wei on 2016/12/12.
* To change this template use File|Default Setting
* |Editor|File and Code Templates|Includes|File Header
*/
@Controller
@RequestMapping(value = "/self/salary")
public class MySalaryController {
@RequestMapping(value = "/home",method = RequestMethod.GET)
public String selfSalaryHome() {
return "/views/salary";
}
}
|
public class Productos{
protected String fc;
protected String nl;
}
|
package com.atguigu.java;
/**
* @author shuning
* @date 2019/7/29-17:55
*/
public class Test2 {
public static final int INT = 10;
public static void main(String[] args) {
System.out.println("ss");
}
//test
public void test(){
}
/**
*
*/
private int age = 15;
}
|
package com.gsccs.sme.api.domain.base;
public class CtreeGrid {
private String id;
private String text;
private String iconCls;
private String state;
private String parentId;
private String type;
private String url;
private String permission;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getIconCls() {
return iconCls;
}
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
}
|
package com.freddy.mpesa.stkpush.model;
import android.util.Base64;
import com.freddy.mpesa.stkpush.Mode;
import com.freddy.mpesa.stkpush.api.RetroClient;
import com.freddy.mpesa.stkpush.api.response.STKPushResponse;
import com.freddy.mpesa.stkpush.interfaces.STKListener;
import com.freddy.mpesa.stkpush.interfaces.STKQueryListener;
import com.freddy.mpesa.stkpush.interfaces.TokenListener;
import java.io.UnsupportedEncodingException;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
public class Mpesa {
private static final String TAG = Mpesa.class.getSimpleName();
private CompositeSubscription mCompositeSubscription;
private String consumerKey;
private String consumerSecret;
private Mode mode;
public Mpesa(String consumerKey, String consumerSecret, Mode mode) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.mode = mode;
this.mCompositeSubscription = new CompositeSubscription();
}
/**
* returns mpesa access token
*
* @param tokenListener - callback listener
*/
public void getToken(final TokenListener tokenListener) throws UnsupportedEncodingException {
if (tokenListener == null) {
throw new RuntimeException("Activity must implement TokenListener");
}
mCompositeSubscription.add(RetroClient.getApiService(mode).generateAccessToken(getAuth())
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<Token>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
tokenListener.OnTokenError(e);
}
@Override
public void onNext(Token token) {
tokenListener.onTokenSuccess(token);
}
}));
}
/**
* generate mpesa bearer key
*
* @return - encoded auth string
* @throws UnsupportedEncodingException - exception
*/
private String getAuth() throws UnsupportedEncodingException {
if (consumerKey.isEmpty()) {
throw new RuntimeException("Consumer key cannot be empty");
}
if (consumerSecret.isEmpty()) {
throw new RuntimeException("Consumer secret cannot be empty");
}
String consumerKeySecret = consumerKey + ":" + consumerSecret;
byte[] bytes = consumerKeySecret.getBytes("ISO-8859-1");
return "Basic " + Base64.encodeToString(bytes, Base64.NO_WRAP);
}
/**
* start mpesa push stk
*
* @param token - access token from mpesa
* @param stkPush - stk push object
* @param stkListener - callback method
*/
public void startStkPush(Token token, STKPush stkPush, final STKListener stkListener) {
if (token == null) {
throw new RuntimeException("Token cannot be null");
}
if (stkPush == null) {
throw new RuntimeException("STKPush cannot be null");
}
if (stkListener == null) {
throw new RuntimeException("Activity must implement TokenListener");
}
if (stkPush.getCallBackURL() == null) {
throw new RuntimeException("Callback URL cannot be null");
}
if (stkPush.getCallBackURL().isEmpty()) {
throw new RuntimeException("Callback URL is required");
}
if (stkPush.getPassword() == null) {
throw new RuntimeException("Password can not be null");
}
if (stkPush.getPassword().isEmpty()) {
throw new RuntimeException("Password is required");
}
mCompositeSubscription.add(RetroClient.getApiService(mode).stkPush(getAuthorization(token.getAccessToken()), stkPush)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<STKPushResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable throwable) {
stkListener.onError(throwable);
}
@Override
public void onNext(STKPushResponse stkPushResponse) {
stkListener.onResponse(stkPushResponse);
}
}));
}
private String getAuthorization(String accessToken) {
return "Bearer " + accessToken;
}
public void stkPushQuery(Token token, STKQuery stkQuery, final STKQueryListener stkQueryListener) {
if (token == null) {
throw new RuntimeException("Token cannot be null");
}
if (stkQuery == null) {
throw new RuntimeException("STKQuery cannot be null");
}
if (stkQueryListener == null) {
throw new RuntimeException("Activity must implement STKQueryListener");
}
mCompositeSubscription.add(RetroClient.getApiService(mode).stkPushQuery(getAuthorization(token.getAccessToken()), stkQuery)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new Subscriber<STKPushResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
stkQueryListener.onError(e);
}
@Override
public void onNext(STKPushResponse stkPushResponse) {
stkQueryListener.onResponse(stkPushResponse);
}
}));
}
}
|
package net.su.controller;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import net.su.service.HomeService;
import net.su.vo.Homevo;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
@Resource
private HomeService homeService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
return "home";
}
@RequestMapping(value ="/insertInfo.do", method = {RequestMethod.GET,RequestMethod.POST})
public String insertInfo(Homevo vo) throws Exception{
System.out.println("작동완료");
homeService.select();
return "home";
}
@RequestMapping(value ="/start.do", method = {RequestMethod.GET,RequestMethod.POST})
public String start() throws Exception{
System.out.println("작동완료2");
homeService.select2();
return "home";
}
@RequestMapping(value ="/test.do", method = {RequestMethod.GET,RequestMethod.POST})
public String test() throws Exception{
System.out.println("작동완료3");
homeService.test(true);
return "home";
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.core.test.tools;
/**
* Exception thrown when code cannot compile.
*
* @author Phillip Webb
* @since 6.0
*/
@SuppressWarnings("serial")
public class CompilationException extends RuntimeException {
CompilationException(String errors, SourceFiles sourceFiles, ResourceFiles resourceFiles) {
super(buildMessage(errors, sourceFiles, resourceFiles));
}
private static String buildMessage(String errors, SourceFiles sourceFiles,
ResourceFiles resourceFiles) {
StringBuilder message = new StringBuilder();
message.append("Unable to compile source\n\n");
message.append(errors);
message.append("\n\n");
for (SourceFile sourceFile : sourceFiles) {
message.append("---- source: ").append(sourceFile.getPath()).append("\n\n");
message.append(sourceFile.getContent());
message.append("\n\n");
}
for (ResourceFile resourceFile : resourceFiles) {
message.append("---- resource: ").append(resourceFile.getPath()).append("\n\n");
message.append(resourceFile.getContent());
message.append("\n\n");
}
return message.toString();
}
}
|
package org.rs.utils;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RsaUtils {
private static final Logger logger = LoggerFactory.getLogger(RsaUtils.class);
public static String publicKey = "";
public static String privateKey = "";
static {
Security.addProvider(new BouncyCastleProvider());
KeyPair keyPair = generateKeyPair(1024);
publicKey = Base64.encodeBase64String(keyPair.getPublic().getEncoded());
privateKey = Base64.encodeBase64String(keyPair.getPrivate().getEncoded());
}
public static KeyPair generateKeyPair(int keySize) {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
keyPairGen.initialize(keySize, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;
} catch (NoSuchAlgorithmException var3) {
var3.printStackTrace();
} catch (NoSuchProviderException var4) {
var4.printStackTrace();
}
return null;
}
public static RSAPublicKey generateRSAPublicKey(String key ) throws Exception {
byte[] decoded = Base64.decodeBase64(key);
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(decoded);
KeyFactory keyFac = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
return (RSAPublicKey) keyFac.generatePublic(x509EncodedKeySpec);
}
public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {
KeyFactory keyFac = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
return (RSAPublicKey) keyFac.generatePublic(publicKeySpec);
}
public static RSAPrivateKey generateRSAPrivateKey( String key ) {
byte[] decoded = Base64.decodeBase64(key);
try {
KeyFactory keyFac = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(decoded);
return (RSAPrivateKey) keyFac.generatePrivate(privateKeySpec);
}catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {
KeyFactory keyFac = KeyFactory.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus),
new BigInteger(privateExponent));
return (RSAPrivateKey) keyFac.generatePrivate(privateKeySpec);
}
public static byte[] encrypt(PublicKey pk, byte[] data ) throws Exception {
return encrypt(pk,data,data.length);
}
public static byte[] encrypt(PublicKey pk, byte[] data, int inputLen ) throws Exception {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.ENCRYPT_MODE, pk);
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(inputLen);
int leaveSize = inputLen % blockSize;
int blocksSize = leaveSize != 0 ? inputLen / blockSize + 1 : inputLen / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
for (int i = 0; inputLen - i * blockSize > 0; ++i) {
if (inputLen - i * blockSize > blockSize) {
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
} else {
cipher.doFinal(data, i * blockSize, inputLen - i * blockSize, raw, i * outputSize);
}
}
return raw;
}
public static byte[] decrypt(PrivateKey key, byte[] raw ) {
return decrypt(key,raw,raw.length);
}
public static byte[] decrypt(PrivateKey key, byte[] data, int inputLen ) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
cipher.init(Cipher.DECRYPT_MODE, key);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(blockSize);
int offset = 0;
while (inputLen - offset > 0) {
if ( inputLen - offset > blockSize ) {
bout.write(cipher.doFinal(data, offset, blockSize));
offset += blockSize;
} else {
bout.write(cipher.doFinal(data, offset, inputLen - offset));
offset += (inputLen - offset);
}
}
return bout.toByteArray();
}catch(Exception ex) {
logger.error("decrypt error : {}", StringTools.getAllExceptionMessage(ex));
}
return null;
}
}
|
package net.dark.entreprise.international.adhess.savedata.DataBase;
/**
* Created by adhess on 31/05/2018.
*/
public class Modification {
private long id;
private String url;
private String last_modification;
public Modification(long id, String url, String last_modification) {
this.id = id;
this.url = url;
this.last_modification = last_modification;
}
public long getId() {
return id;
}
public String getUrl() {
return url;
}
public String getLast_modification() {
return last_modification;
}
public void setId(long id) {
this.id = id;
}
public void setUrl(String url) {
this.url = url;
}
public void setLast_modification(String last_modification) {
this.last_modification = last_modification;
}
}
|
package com.hqzmss.strategy;
public class ConcreteStrategyTwo implements Strategy{
public void print() {
System.out.println("打印两行");
}
}
|
import java.util.*;
public interface Expression
{
public SymbolTable.TypeDesignator type (SymbolTable table);
public boolean referenceable (SymbolTable table);
interface Designator extends Expression
{
public class Variable implements Designator
{
String name;
Variable (String n)
{
name = n;
}
public SymbolTable.TypeDesignator type (SymbolTable table)
{
SymbolTable.Symbol symbol = table.getBinding (name, "VAR");
if (symbol == null) symbol = table.getBinding (name, "CONST");
if (symbol == null) return null;
else return symbol.type ();
}
public boolean referenceable (SymbolTable table)
{
return table.getBinding (name, "VAR") != null;
}
}
public class ArrayReference implements Designator
{
Designator baseDesignator;
Expression index;
ArrayReference (Designator bd, Expression i)
{
baseDesignator = bd;
index = i;
}
public SymbolTable.TypeDesignator type (SymbolTable table)
{
SymbolTable.TypeDesignator type = baseDesignator.type (table);
if (type == null) return null;
else return type.dereferencedType ();
}
public boolean referenceable (SymbolTable table) { return true; }
}
}
public class Number implements Expression
{
short value;
Number (short v) { value = v; }
public SymbolTable.TypeDesignator type (SymbolTable table) { return SymbolTable.TypeDesignator.SHORT; }
public boolean referenceable (SymbolTable table) { return false; }
}
public class ProcedureCall implements Expression
{
String name;
List <Expression> arguments;
ProcedureCall (String n, List <Expression> a)
{
name = n;
arguments = a;
}
public SymbolTable.TypeDesignator type (SymbolTable table)
{
SymbolTable.Symbol symbol = table.getBinding (name, "PROCEDURE");
if (symbol == null) return null;
else return symbol.type ();
}
public boolean referenceable (SymbolTable table) { return false; }
}
abstract class BinaryOperation implements Expression
{
Expression expression0, expression1;
BinaryOperation (Expression e0, Expression e1)
{
expression0 = e0;
expression1 = e1;
}
public SymbolTable.TypeDesignator type (SymbolTable table)
{
return SymbolTable.TypeDesignator.Combine.symmetrically (expression0.type (table), expression1.type (table));
}
public static class Addition extends BinaryOperation
{
Addition (Expression e0, Expression e1) { super (e0, e1); }
}
public static class Subtraction extends BinaryOperation
{
Subtraction (Expression e0, Expression e1) { super (e0, e1); }
}
public static class Multiplication extends BinaryOperation
{
Multiplication (Expression e0, Expression e1) { super (e0, e1); }
}
public static class Division extends BinaryOperation
{
Division (Expression e0, Expression e1) { super (e0, e1); }
}
public boolean referenceable (SymbolTable table) { return false; }
}
}
|
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.web.servlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
/**
* Interface for web-based theme resolution strategies that allows for
* both theme resolution via the request and theme modification via
* request and response.
*
* <p>This interface allows for implementations based on session,
* cookies, etc. The default implementation is
* {@link org.springframework.web.servlet.theme.FixedThemeResolver},
* simply using a configured default theme.
*
* <p>Note that this resolver is only responsible for determining the
* current theme name. The Theme instance for the resolved theme name
* gets looked up by DispatcherServlet via the respective ThemeSource,
* i.e. the current WebApplicationContext.
*
* <p>Use {@link org.springframework.web.servlet.support.RequestContext#getTheme()}
* to retrieve the current theme in controllers or views, independent
* of the actual resolution strategy.
*
* @author Jean-Pierre Pawlak
* @author Juergen Hoeller
* @since 17.06.2003
* @see org.springframework.ui.context.Theme
* @see org.springframework.ui.context.ThemeSource
* @deprecated as of 6.0 in favor of using CSS, without direct replacement
*/
@Deprecated(since = "6.0")
public interface ThemeResolver {
/**
* Resolve the current theme name via the given request.
* Should return a default theme as fallback in any case.
* @param request the request to be used for resolution
* @return the current theme name
*/
String resolveThemeName(HttpServletRequest request);
/**
* Set the current theme name to the given one.
* @param request the request to be used for theme name modification
* @param response the response to be used for theme name modification
* @param themeName the new theme name ({@code null} or empty to reset it)
* @throws UnsupportedOperationException if the ThemeResolver implementation
* does not support dynamic changing of the theme
*/
void setThemeName(HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable String themeName);
}
|
package com.cs240.server.service;
import dao.*;
import model.Person;
import request.PersonsRequest;
import result.PersonsResult;
import service.shared.Relatives;
import java.sql.Connection;
import java.util.ArrayList;
/***
* Uses a recursive function to get all persons who are related to said person.
*/
public class PersonsService {
private Database db;
private PersonDAO pDAO;
/***
* Sets up Database Connection, and initialize needed DAO's.
*
* @throws DataAccessException - Database Connection errors
*/
private void setUp() throws DataAccessException, ClassNotFoundException {
db = new Database();
Connection c = db.getConnection();
pDAO = new PersonDAO(c);
}
/***
* Description: Returns the single Person object with the specified ID.
* @param r getAllEventsRequest
* @return getAllEventsResult object
*/
public PersonsResult getAllPersons (PersonsRequest r){
PersonsResult result;
try{
try{
//Setup and get relatives
setUp();
Person person = pDAO.fetchPerson(r.getPersonID());
Relatives get = new Relatives();
ArrayList<Person> relatives = get.getRelatives(person, pDAO);
result = new PersonsResult(relatives,true);
//Close Connection
db.closeConnection(true);
}
//Persons Failed
catch (ClassNotFoundException | DataAccessException e) {
//Rollback changes
db.closeConnection(false);
result = new PersonsResult(("Error: " + e.getMessage()),false);
e.printStackTrace();
}
}
//Connection close failed
catch(DataAccessException e){
result = new PersonsResult(("Error: " + e.getMessage()), false);
e.printStackTrace();
}
return result;
}
}
|
package com.programapprentice.app;
/**
* User: program-apprentice
* Date: 8/16/15
* Time: 7:04 PM
*/
/**
* 1. divident is Integer.MIN_VALUE
* 2. divisor is Integer.MIN_VALUE
* Find N such that
* divisor * 2 ^ N < dividend < divisor * 2 ^ (N + 1)
* Then
* result += 2 ^ N
* divendd -= divisor * 2 ^ N
* */
public class DivideTwoIntegers_29 {
public long posDivide(long dividend, long divisor) {
// dividend and divisor are both positive.
if(dividend < divisor) {
return 0;
}
int result = 0;
long base = divisor;
int tResult = 1;
while(dividend >= base) { // Don's miss equal sign.
dividend -= base;
result += tResult;
tResult = tResult << 1;
base = base << 1;
}
result += posDivide(dividend, divisor);
return result;
}
public int divide(int dividend, int divisor) {
if(divisor == 0 || dividend == 0) {
return 0;
}
if(divisor == 1) {
return dividend;
}
if(divisor == -1) {
return (dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend);
}
boolean isNegative = false;
if((dividend < 0 && divisor < 0) || (dividend > 0 && divisor > 0)) {
isNegative = false;
} else {
isNegative = true;
}
long p = (long)dividend;
long q = (long)divisor;
long result = posDivide((long)Math.abs(p), (long)Math.abs(q));
if(isNegative) {
result = 0 - result;
}
if(result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
}
if(result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int)result;
}
}
|
package com.xwj.entity;
public enum Color {
RED(1,"红"),
YELLOW(2,"黄"),
BLUE(3,"蓝");
private int code;
private String name;
Color(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static Color getByCode(int code){
for (Color color : Color.values()) {
if(color.code==code){
return color;
}
}
return null;
}
}
|
package com.tindertone.tinder.dao.jdbc.mapper;
import com.tindertone.tinder.entity.*;
public class DisplayUserRowMapper {
public DisplayUser mapRow(User user, Photo photo){
DisplayUser displayUser = new DisplayUser();
displayUser.setUserId(user.getId());
displayUser.setUserDescription(user.getDescription());
displayUser.setUserNickname(user.getNickName());
displayUser.setPhotoLink(photo.getLink());
return displayUser;
}
public DisplayUser mapRow(User user, Photo photo, Couple couple, Message lastMessage) {
DisplayUser displayUser = mapRow(user, photo);
displayUser.setCoupleId(couple.getId());
displayUser.setLastMessage(lastMessage);
return displayUser;
}
}
|
package boletin75;
import javax.swing.JOptionPane;
/**
*
* @author miglezlor
*/
public class Comparacion {
public int pedirNumero(){
int num;
String res=JOptionPane.showInputDialog("Introduce un número");
num=Integer.parseInt(res);
return num;
}
public void compararNumeros (int num1, int num2, int num3){
if (num1>num2 & num1>num3)
System.out.println("O primeiro número é o maior ("+num1+")");
else if (num2>num1 & num2>num3)
System.out.println("O segundo número é o maior ("+num2+")");
else
System.out.println("O terceiro número é o maior ("+num3+")");
}
}
|
package com.example.tecomca.mylogin_seccion05.Activities;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Parcel;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.tecomca.mylogin_seccion05.Fragments.InstructionsFragment.AlertFragment;
import com.example.tecomca.mylogin_seccion05.Fragments.categorisFragment.CatergorisFragment;
import com.example.tecomca.mylogin_seccion05.Fragments.EstadisticoFragment.InforFragment;
import com.example.tecomca.mylogin_seccion05.R;
import com.example.tecomca.mylogin_seccion05.Utils.ComunViews;
import com.example.tecomca.mylogin_seccion05.Utils.Util;
import java.util.ArrayList;
import java.util.List;
@SuppressLint("ParcelCreator")
public class MainActivity extends AppCompatActivity implements ComunViews {
private SharedPreferences prefs;
private DrawerLayout drawerLayout;
private NavigationView navigationView;
private List<String> fragments;
private ComunViews comunViews = this;
Toolbar toolbar;
private String nameFromIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setToolbar();
prefs = getSharedPreferences("Preferences", Context.MODE_PRIVATE);
nameFromIntent = getIntent().getStringExtra("EMAIL");
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
navigationView = (NavigationView) findViewById(R.id.navview);
this.fragments = new ArrayList<>();
setFragmentByDefault();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, this.drawerLayout, this.toolbar, 0, 0);
this.drawerLayout.addDrawerListener(toggle);
toggle.syncState();
chargeNavView();
// con este listener controlamos el navigation drawer
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
boolean fragmentTransaction = false;
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.menu_mail:
fragments.clear();
fragment = CatergorisFragment.newInstance(comunViews);
fragmentTransaction = true;
break;
case R.id.menu_alert:
fragments.clear();
fragment = AlertFragment.newInstance(comunViews);
fragmentTransaction = true;
break;
case R.id.menu_information:
fragments.clear();
fragment = InforFragment.newInstance(comunViews);
fragmentTransaction = true;
break;
case R.id.menu_registrar:
fragments.clear();
Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(intent);
// fragment = new RegistrarFragment();
// fragmentTransaction = true;
break;
case R.id.menu_logout:
fragments.clear();
logOut();
break;
case R.id.menu_forget_logout:
fragments.clear();
removeSharedPreferences();
logOut();
break;
}
if (fragmentTransaction) {
item.setChecked(true);
getSupportActionBar().setTitle(item.getTitle());
changeFragment(fragment);
drawerLayout.closeDrawers();
}
return true;
}
});
}
public void chargeNavView() {
View view = this.navigationView.getHeaderView(0);
TextView tv_name = view.findViewById(R.id.tv_name);
tv_name.setText(Util.getSessionName(this.prefs));
switch (Util.getSessionType(this.prefs)) {
case 1: {
this.navigationView.inflateMenu(R.menu.nav_options);
break;
}
case 2: {
// algo raro
this.navigationView.inflateMenu(R.menu.menu_guest);
break;
}
}
}
// parte de navigation drawer
private void setToolbar() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void setFragmentByDefault() {
changeFragment(CatergorisFragment.newInstance(comunViews));
}
@Override
public void changeFragment(Fragment fragment) {
getSupportActionBar().setSubtitle(" ");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
if (!this.fragments.isEmpty()) {
ft.addToBackStack(fragment.getClass().getName());
}
this.fragments.add(fragment.getClass().getName());
ft.commit();
Log.e("asda", "Tamaño lista: " + getSupportFragmentManager().getBackStackEntryCount());
// getSupportFragmentManager()
// .beginTransaction()
// .replace(R.id.content_frame, fragment)
// .addToBackStack(fragment.getClass().getName())
// .commit();
// this.fragments.add(fragment.getClass().getName());
}
@Override
public void onBackPressed() {
getSupportActionBar().setSubtitle(" ");
if (this.drawerLayout.isDrawerOpen(GravityCompat.START)) {
this.drawerLayout.closeDrawer(GravityCompat.START);
} else {
if (this.fragments.size() > 0) {
this.fragments.remove(this.fragments.size() - 1);
}
super.onBackPressed();
}
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu, menu);
// return super.onCreateOptionsMenu(menu);
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
//
// switch (item.getItemId()) {
// case android.R.id.home:
// // abrir el menu lateral
// drawerLayout.openDrawer(GravityCompat.START);
// return true;
// case R.id.menu_logout:
// logOut();
// return true;
// case R.id.menu_forget_logout:
// removeSharedPreferences();
// logOut();
// return true;
// default:
// return super.onOptionsItemSelected(item);
// }
// }
private void logOut() {
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void removeSharedPreferences() {
prefs.edit().clear().apply();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
}
}
|
package com.kic.app;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import dao.myDAO;
@Controller
public class MyDeptController {
@Autowired
private myDAO mydao;
@RequestMapping("/view/{deptno}")
public String view(@PathVariable(value="deptno") int deptno, Model model)
{
model.addAttribute("count", mydao.dataCount());
model.addAttribute("dname",mydao.getDeptName(deptno));
model.addAttribute("dto", mydao.getData(deptno));
model.addAttribute("list" , mydao.getList());
return "view";
}
}
|
package ru.mcfr.oxygen.framework.operations;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;
import ro.sync.ecss.extensions.api.node.AuthorNode;
import javax.swing.text.BadLocationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: ws
* Date: 4/18/11
* Time: 4:33 PM
* To change this template use File | Settings | File Templates.
*/
public class DeleteAllIdOperation implements AuthorOperation{
private AuthorDocumentController controller = null;
private void RemoveAllID(Element element){
if (element.getNodeType() == Node.ELEMENT_NODE){
element.removeAttribute("id");
NodeList childs = element.getChildNodes();
for (int i = 0; i < childs.getLength(); i++){
if (childs.item(i).getNodeType() == Node.ELEMENT_NODE)
RemoveAllID((Element) childs.item(i));
}
}
}
public void doOperation(AuthorAccess authorAccess, ArgumentsMap argumentsMap) throws IllegalArgumentException, AuthorOperationException {
controller = authorAccess.getDocumentController();
ArrayList<String> lostElements = new ArrayList<String>();
lostElements.add("метаданные");
lostElements.add("редакции");
lostElements.add("ссылки");
List<AuthorNode> nodes = controller.getAuthorDocumentNode().getContentNodes();
for (AuthorNode node : nodes){
if (!lostElements.contains(node.getName())){
AuthorDocumentFragment fragment = null;
try {
fragment = controller.createDocumentFragment(node, true);
String xmlFragment = controller.serializeFragmentToXML(fragment);
Document XMLDoc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
XMLDoc = db.parse(new ByteArrayInputStream(xmlFragment.getBytes("UTF-8")));
RemoveAllID(XMLDoc.getDocumentElement());
OutputFormat opfrmt = new OutputFormat(XMLDoc, "UTF-8", false);
opfrmt.setPreserveSpace(false);
opfrmt.setOmitDocumentType(true);
opfrmt.setOmitXMLDeclaration(true);
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut, opfrmt);
try {
serial.asDOMSerializer();
serial.serialize(XMLDoc);
String xmlString = stringOut.toString();
authorAccess.getWorkspaceAccess().showErrorMessage(xmlString);
int pos = node.getStartOffset();
if (!xmlString.isEmpty()) {
try {
controller.beginCompoundEdit();
controller.deleteNode(node);
controller.insertXMLFragment(xmlString, pos);
} finally {
controller.endCompoundEdit();
}
}
} catch (java.io.IOException ioe) {
authorAccess.getWorkspaceAccess().showErrorMessage(ioe.getLocalizedMessage());
}
} catch (Exception e) {
authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage());
}
} catch (BadLocationException e) {
authorAccess.getWorkspaceAccess().showErrorMessage(e.getLocalizedMessage());
}
}
}
}
public ArgumentDescriptor[] getArguments() {
return new ArgumentDescriptor[0]; //To change body of implemented methods use File | Settings | File Templates.
}
public String getDescription() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
}
|
package com.regentzu.untitledgame.bodypart.guidepart;
import com.regentzu.untitledgame.bodypart.BodyPart;
/**
* Created on 12/16/13.
*/
public abstract class Balls extends BodyPart{
protected Float width;
@Override
protected void partSetup() {
this.width = 1f;
}
public Float getWidth() {
return width;
}
public void setWidth(Float width) {
this.width = width;
}
}
|
package com.szhrnet.taoqiapp.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.Uri;
import android.os.Environment;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.szhrnet.taoqiapp.R;
import java.io.File;
/**
* <pre>
* author: MakeCodeFly
* desc : 照片选择类
* email:15695947865@139.com
* </pre>
*/
public class PhotoSelectUtils {
public static void showDialog(final int limit, final TakePhoto takePhoto, final Context context, final boolean isCrop, final boolean isShowCompressDialog,
final int cropWidth, final int cropHeight) {
final String items[] = {context.getResources().getString(R.string.pz), context.getResources().getString(R.string.xzzp)};
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.ts));
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (items[which].equals(context.getResources().getString(R.string.pz))) {
takePhotos(takePhoto, isCrop,cropWidth,cropHeight,isShowCompressDialog);
} else if (items[which].equals(context.getResources().getString(R.string.xzzp))) {
selectPicture(limit, takePhoto, isCrop,cropWidth,cropHeight,isShowCompressDialog);
}
}
});
builder.setPositiveButton(context.getResources().getString(R.string.qx), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
public static void takePhotos(TakePhoto takePhoto, boolean isCrop, int cropWidth, int cropHeight,boolean isShowCompressDialog) {
File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
Uri imageUri = Uri.fromFile(file);
configCompress(takePhoto,isShowCompressDialog);
if (isCrop)
takePhoto.onPickFromCaptureWithCrop(imageUri, getCropOptions(cropWidth,cropHeight));
else
takePhoto.onPickFromCapture(imageUri);
}
public static void configCompress(TakePhoto takePhoto,boolean isShowCompressDialog) {
int maxSize = (int) (0.5 * 1024);
int width = 800;
int height = 800;
CompressConfig config;
config = new CompressConfig.Builder()
.setMaxSize(maxSize)
.setMaxPixel(width >= height ? width : height)
.enableReserveRaw(true)
.create();
takePhoto.onEnableCompress(config, isShowCompressDialog);//是否显示压缩进度条
}
public static CropOptions getCropOptions(int cropWidth, int cropHeight) {
CropOptions.Builder builder = new CropOptions.Builder();
builder.setAspectX(cropWidth).setAspectY(cropHeight);
builder.setWithOwnCrop(false);//是否使用自带剪切工具
return builder.create();
}
public static void selectPicture(int limit, TakePhoto takePhoto, boolean isCrop, int cropWidth, int cropHeight,boolean isShowCompressDialog) {
configCompress(takePhoto,isShowCompressDialog);
if (isCrop)
takePhoto.onPickMultipleWithCrop(limit, getCropOptions(cropWidth,cropHeight));
else
takePhoto.onPickMultiple(limit);
}
}
|
package com.wizered67.game.Entities;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;
import com.wizered67.game.Collisions.ContactData;
import com.wizered67.game.Constants;
import com.wizered67.game.EntityManager;
import com.wizered67.game.Enums.Direction;
import com.wizered67.game.GameManager;
import com.wizered67.game.Screens.GameScreen;
import com.wizered67.game.WorldManager;
import java.util.ArrayList;
import java.util.Comparator;
/**
* Created by Adam on 8/24/2016.
*/
public class HomingProjectileEntity extends Entity{
private float x, y, radius;
private double angle;
private double targetAngle;
private int deathTimer;
private Entity creator;
private Direction direction;
private Comparator<Entity> distanceComparator = new Comparator<Entity>() {
@Override
public int compare(Entity e1, Entity e2) {
double distance1 = Math.pow(e1.getX() - getX(), 2) + Math.pow(e1.getY() - getY(), 2);
double distance2 = Math.pow(e2.getX() - getX(), 2) + Math.pow(e2.getY() - getY(), 2);
return (int) (distance1 - distance2);
}
};
public HomingProjectileEntity(Entity creator, float x, float y, float radius, double angle, Direction direction){
this.creator = creator;
this.x = x;
this.y = y;
this.radius = radius;
this.angle = angle;
this.targetAngle = angle;
this.direction = direction;
deathTimer = 0;
WorldManager.addNewObjectBody(this);
}
public void makeBody(){
BodyDef bdef = new BodyDef();
bdef.type = BodyDef.BodyType.DynamicBody;
bdef.position.set(x, y);
bdef.angle = (float) angle;
bdef.bullet = true;
bdef.fixedRotation = true;
body = WorldManager.world.createBody(bdef);
body.setUserData(this);
CircleShape circle = new CircleShape();
circle.setPosition(new Vector2(0, 0));
circle.setRadius(radius);
FixtureDef mb = new FixtureDef();
mb.isSensor = true;
mb.shape = circle;
mb.density = 0.5f;
mb.friction = 0f;
mb.restitution = 0;
mb.filter.categoryBits = Constants.CATEGORY_PLAYER_ATTACK;
mb.filter.maskBits = Constants.MASK_PLAYER_ATTACK;
body.createFixture(mb);
super.makeBody();
}
@Override
public void beginContact(ContactData c) {
if (c.getOther().getFilterData().categoryBits == Constants.CATEGORY_SCENERY) {
EntityManager.removeEntity(this);
}
}
@Override
public void endContact(ContactData c) {
}
@Override
public void preSolveCollision(ContactData c, Manifold m) {
}
@Override
public void postSolveCollision(ContactData c, ContactImpulse impulse) {
}
@Override
public void updatePhysics(float delta) {
Screen currentScreen = GameManager.game.getScreen();
if (currentScreen instanceof GameScreen){
GameScreen screen = (GameScreen) currentScreen;
if (!screen.inWorld(Constants.toPixels(body.getPosition())))
EntityManager.removeEntity(this);
}
homeOnTagged();
if (targetAngle != angle){
angle = MathUtils.lerpAngle((float)angle, (float)targetAngle, 0.15f);
}
body.setTransform(body.getPosition(), (float) angle);
float speed = 6f;
body.setLinearVelocity((float)Math.cos(Constants.toBox2DAngle(angle)) * speed, (float)Math.sin(Constants.toBox2DAngle(angle)) * speed);
}
private void homeOnTagged(){
if (creator instanceof PlayerEntity){
final PlayerEntity player = (PlayerEntity) creator;
final ArrayList<Entity> nearby = new ArrayList<Entity>();
QueryCallback callback = new QueryCallback() {
@Override
public boolean reportFixture(Fixture fixture) {
Object other = fixture.getBody().getUserData();
if (other instanceof EnemyEntity){
if (player.getTaggedEntities().contains(other))
nearby.add((Entity) other);
}
return true;
}
};
float width = Constants.toMeters(96);
float height = Constants.toMeters(96);
WorldManager.world.QueryAABB(callback, getX() - width / 2, getY() - height / 2, getX() + width / 2, getY() + height / 2);
nearby.sort(distanceComparator);
if (!nearby.isEmpty()){
Entity closest = nearby.get(0);
targetAngle = Constants.toBox2DAngle(Math.atan2(getY() - closest.getY(), getX() - closest.getX()));
}
}
}
@Override
public void updateTimers() {
deathTimer = Math.max(deathTimer - 1, 0);
}
@Override
public void destroy() {
}
}
|
package edu.asu.commons.event;
import java.io.Serializable;
import edu.asu.commons.net.Identifier;
/**
* $Id$
*
* Event marker interface, tags all semantic messages used locally within
* the event channel or transmit remotely via the Dispatcher.
*
* @author <a href='alllee@cs.indiana.edu'>Allen Lee</a>
* @version $Revision$
*/
public interface Event extends Serializable {
public Identifier getId();
// FIXME: use TimePoints instead.
public long getCreationTime();
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* 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
*
* https://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.springframework.core.io;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* {@link Resource} implementation for {@link java.lang.Module} resolution,
* performing {@link #getInputStream()} access via {@link Module#getResourceAsStream}.
*
* <p>Alternatively, consider accessing resources in a module path layout via
* {@link ClassPathResource} for exported resources, or specifically relative to
* a {@code Class} via {@link ClassPathResource#ClassPathResource(String, Class)}
* for local resolution within the containing module of that specific class.
* In common scenarios, module resources will simply be transparently visible as
* classpath resources and therefore do not need any special treatment at all.
*
* @author Juergen Hoeller
* @author Sam Brannen
* @since 6.1
* @see Module#getResourceAsStream
* @see ClassPathResource
*/
public class ModuleResource extends AbstractResource {
private final Module module;
private final String path;
/**
* Create a new {@code ModuleResource} for the given {@link Module}
* and the given resource path.
* @param module the runtime module to search within
* @param path the resource path within the module
*/
public ModuleResource(Module module, String path) {
Assert.notNull(module, "Module must not be null");
Assert.notNull(path, "Path must not be null");
this.module = module;
this.path = path;
}
/**
* Return the {@link Module} for this resource.
*/
public final Module getModule() {
return this.module;
}
/**
* Return the path for this resource.
*/
public final String getPath() {
return this.path;
}
@Override
public InputStream getInputStream() throws IOException {
InputStream is = this.module.getResourceAsStream(this.path);
if (is == null) {
throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
}
return is;
}
@Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(this.path, relativePath);
return new ModuleResource(this.module, pathToUse);
}
@Override
@Nullable
public String getFilename() {
return StringUtils.getFilename(this.path);
}
@Override
public String getDescription() {
return "module resource [" + this.path + "]" +
(this.module.isNamed() ? " from module [" + this.module.getName() + "]" : "");
}
@Override
public boolean equals(@Nullable Object obj) {
return (this == obj || (obj instanceof ModuleResource that &&
this.module.equals(that.module) && this.path.equals(that.path)));
}
@Override
public int hashCode() {
return this.module.hashCode() * 31 + this.path.hashCode();
}
}
|
package com.ut.healthelink.model;
import com.ut.healthelink.validator.NoHtml;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "USERS")
public class User {
@Transient
private List<Integer> sectionList;
@Transient
private String orgName, password;
@Transient
private Date dateOrgWasCreated = null;
@Transient
private Integer orgType;
@Transient
private boolean connectionAssociated = false, sendSentEmail = false, sendReceivedEmail = false;
@Transient
private List<siteSections> userAllowedModules = null;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private int id;
@Column(name = "STATUS", nullable = false)
private boolean status = false;
@Column(name = "ORGID", nullable = false)
private int orgId;
@NotEmpty
@NoHtml
@Column(name = "FIRSTNAME", nullable = false)
private String firstName;
@NotEmpty
@NoHtml
@Column(name = "LASTNAME", nullable = true)
private String lastName;
/**
* @NotEmpty @NoHtml @Column(name = "PASSWORD", nullable = false) private String password;
*
*/
@NotEmpty
@NoHtml
@Size(min = 4, max = 15)
@Column(name = "USERNAME", nullable = false)
private String username;
@Column(name = "ROLEID", nullable = false)
private int roleId = 2;
@Column(name = "MAINCONTACT", nullable = false)
private int mainContact = 0;
@Column(name = "SENDEMAILALERT", nullable = true)
private boolean sendEmailAlert = false;
@Column(name = "RECEIVEEMAILALERT", nullable = true)
private boolean receiveEmailAlert = false;
@Email
@NoHtml
@Column(name = "EMAIL", nullable = false)
private String email;
@DateTimeFormat(pattern = "dd/MM/yyyy hh:mm:ss")
@Column(name = "DATECREATED", nullable = true)
private Date dateCreated = new Date();
@Column(name = "USERTYPE", nullable = false)
private int userType = 1;
@Column(name = "DELIVERAUTHORITY", nullable = false)
private boolean deliverAuthority = false;
@Column(name = "EDITAUTHORITY", nullable = false)
private boolean editAuthority = false;
@Column(name = "CREATEAUTHORITY", nullable = false)
private boolean createAuthority = false;
@Column(name = "CANCELAUTHORITY", nullable = false)
private boolean cancelAuthority = false;
@NoHtml
@Column(name = "RESETCODE", nullable = true)
private String resetCode = null;
@Column(name = "randomSalt", nullable = true)
private byte[] randomSalt;
@Column(name = "encryptedPw", nullable = true)
private byte[] encryptedPw;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public int getMainContact() {
return mainContact;
}
public void setMainContact(int mainContact) {
this.mainContact = mainContact;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public boolean getStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public List<Integer> getsectionList() {
return this.sectionList;
}
public void setsectionList(List<Integer> sectionList) {
this.sectionList = sectionList;
}
public int getuserType() {
return userType;
}
public void setuserType(int userType) {
this.userType = userType;
}
public boolean getdeliverAuthority() {
return deliverAuthority;
}
public void setdeliverAuthority(boolean deliverAuthority) {
this.deliverAuthority = deliverAuthority;
}
public boolean geteditAuthority() {
return editAuthority;
}
public void seteditAuthority(boolean editAuthority) {
this.editAuthority = editAuthority;
}
public boolean getcreateAuthority() {
return createAuthority;
}
public void setcreateAuthority(boolean createAuthority) {
this.createAuthority = createAuthority;
}
public boolean getcancelAuthority() {
return cancelAuthority;
}
public void setcancelAuthority(boolean cancelAuthority) {
this.cancelAuthority = cancelAuthority;
}
public Date getdateOrgWasCreated() {
return dateOrgWasCreated;
}
public void setdateOrgWasCreated(Date dateOrgWasCreated) {
this.dateOrgWasCreated = dateOrgWasCreated;
}
public String getresetCode() {
return resetCode;
}
public void setresetCode(String resetCode) {
this.resetCode = resetCode;
}
public String getOrgName() {
return orgName;
}
public void setOrgName(String orgName) {
this.orgName = orgName;
}
public byte[] getRandomSalt() {
return randomSalt;
}
public void setRandomSalt(byte[] randomSalt) {
this.randomSalt = randomSalt;
}
public byte[] getEncryptedPw() {
return encryptedPw;
}
public void setEncryptedPw(byte[] encryptedPw) {
this.encryptedPw = encryptedPw;
}
public Integer getOrgType() {
return orgType;
}
public void setOrgType(Integer orgType) {
this.orgType = orgType;
}
public boolean isConnectionAssociated() {
return connectionAssociated;
}
public void setConnectionAssociated(boolean connectionAssociated) {
this.connectionAssociated = connectionAssociated;
}
public boolean isSendSentEmail() {
return sendSentEmail;
}
public void setSendSentEmail(boolean sendSentEmail) {
this.sendSentEmail = sendSentEmail;
}
public boolean isSendReceivedEmail() {
return sendReceivedEmail;
}
public void setSendReceivedEmail(boolean sendReceivedEmail) {
this.sendReceivedEmail = sendReceivedEmail;
}
public List<siteSections> getUserAllowedModules() {
return userAllowedModules;
}
public void setUserAllowedModules(List<siteSections> userAllowedModules) {
this.userAllowedModules = userAllowedModules;
}
public List<Integer> getSectionList() {
return sectionList;
}
public void setSectionList(List<Integer> sectionList) {
this.sectionList = sectionList;
}
public Date getDateOrgWasCreated() {
return dateOrgWasCreated;
}
public void setDateOrgWasCreated(Date dateOrgWasCreated) {
this.dateOrgWasCreated = dateOrgWasCreated;
}
public boolean isSendEmailAlert() {
return sendEmailAlert;
}
public void setSendEmailAlert(boolean sendEmailAlert) {
this.sendEmailAlert = sendEmailAlert;
}
public boolean isReceiveEmailAlert() {
return receiveEmailAlert;
}
public void setReceiveEmailAlert(boolean receiveEmailAlert) {
this.receiveEmailAlert = receiveEmailAlert;
}
public int getUserType() {
return userType;
}
public void setUserType(int userType) {
this.userType = userType;
}
public boolean isDeliverAuthority() {
return deliverAuthority;
}
public void setDeliverAuthority(boolean deliverAuthority) {
this.deliverAuthority = deliverAuthority;
}
public boolean isEditAuthority() {
return editAuthority;
}
public void setEditAuthority(boolean editAuthority) {
this.editAuthority = editAuthority;
}
public boolean isCreateAuthority() {
return createAuthority;
}
public void setCreateAuthority(boolean createAuthority) {
this.createAuthority = createAuthority;
}
public boolean isCancelAuthority() {
return cancelAuthority;
}
public void setCancelAuthority(boolean cancelAuthority) {
this.cancelAuthority = cancelAuthority;
}
public String getResetCode() {
return resetCode;
}
public void setResetCode(String resetCode) {
this.resetCode = resetCode;
}
}
|
package delivery;
/**
* @메쏘드명 : DeliveryInfo
* @작성자 : jwt1029
* @작성일자 : 2019-01-30
* @설명 :
*/
public class DeliveryInfo {
private String carrierId;
private String trackId;
private Integer progressCount;
public String getCarrierId() {
return carrierId;
}
public void setCarrierId(String carrierId) {
this.carrierId = carrierId;
}
public String getTrackId() {
return trackId;
}
public void setTrackId(String trackId) {
this.trackId = trackId;
}
public Integer getProgressCount() {
return progressCount;
}
public void setProgressCount(Integer progressCount) {
this.progressCount = progressCount;
}
}
|
package com.cskaoyan.bean.film;
import java.io.Serializable;
/**
* @Author: Qiu
* @Date: 2019/6/7 22:18
*/
public class FilmConditionVo implements Serializable {
private Integer catId=99;
private Integer sourceId=99;
private Integer yearId=99;
public FilmConditionVo() {
}
public FilmConditionVo(Integer catId, Integer sourceId, Integer yearId) {
this.catId = catId;
this.sourceId = sourceId;
this.yearId = yearId;
}
public Integer getCatId() {
return catId;
}
public void setCatId(Integer catId) {
this.catId = catId;
}
public Integer getSourceId() {
return sourceId;
}
public void setSourceId(Integer sourceId) {
this.sourceId = sourceId;
}
public Integer getYearId() {
return yearId;
}
public void setYearId(Integer yearId) {
this.yearId = yearId;
}
}
|
// Samuel Bermuez sa167851
// COP 3503 Summer 2018
import java.io.*;
import java.util.*;
import java.lang.Object;
import java.util.HashMap;
class knights
{
HashMap<Integer, Integer> square;
public knights (HashMap<Integer,Integer> square)
{
this.square = square;
}
public HashMap<Integer, Integer> getSquare()
{
return square;
}
}
public class SneakyKnights
{
public static boolean allTheKnightsAreSafe(ArrayList<String> coordinateStrings, int boardSize)
{
int size = coordinateStrings.size();
int i, j;
int Rval = 0;
int Cval = 0;
int length;
knights tempKnight;
HashMap<Integer, Integer> newKnight;
knights []board = new knights[size];
for(i = 0; i < size; i++)
{
if(coordinateStrings.get(i).length() != 0)
{
Rval = Integer.parseInt(coordinateStrings.get(i).replaceAll("[^\\d]","")) - 1;
String temp = coordinateStrings.get(i).replaceAll("[\\d]", "");
length = temp.length();
Cval = 0;
for(j = 0; j < length; j++)
Cval += (int)(temp.charAt(j)- 96)*Math.pow( 26, length - j - 1);
Cval--;
System.out.println("Rval: " + Rval);
if(board[Rval] == null)
{ newKnight = new HashMap<Integer,Integer>();
newKnight.put(Cval,1);
board[Rval] = new knights(newKnight);
}
else
board[Rval].getSquare().put(Cval,1);
if(Rval + 1 < boardSize && (Cval + 2 < boardSize || Cval - 2 >= 0))
{
if(board[Rval + 1] != null)
{
if(Cval + 2 < boardSize && board[Rval+1].getSquare().containsKey(Cval + 2))
return false;
if(Cval - 2 >= 0 && board[Rval + 1 ].getSquare().containsKey(Cval - 2))
return false;
}
}
if(Rval - 1 >= 0 && (Cval + 2 < boardSize || Cval - 2 >= 0))
{
if(board[Rval - 1] != null)
{
if(Cval + 2 < boardSize && board[Rval - 1].getSquare().containsKey(Cval + 2))
return false;
if(Cval - 2 >= 0 && board[Rval - 1].getSquare().containsKey(Cval - 2))
return false;
}
}
if(Rval + 2 < boardSize && (Cval + 1 < boardSize || Cval - 1 >= 0))
{
if(board[Rval + 2] != null)
{
if(Cval + 1 < boardSize && board[Rval + 2].getSquare().containsKey(Cval + 1))
return false;
if(Cval - 1 >= 0 && board[Rval + 2].getSquare().containsKey(Cval - 1))
return false;
}
}
if(Rval - 2 >= 0 && (Cval + 1 < boardSize || Cval - 1 >= 0))
{
if(board[Rval - 2] != null)
{
if(Cval + 1 < boardSize && board[Rval - 2].getSquare().containsKey(Cval + 1))
return false;
if(Cval - 1 >= 0 && board[Rval - 2].getSquare().containsKey(Cval - 1))
return false;
}
}
}
}
return true;
}
public static double difficultyRating()
{
return 5.0;
}
public static double hoursSpent()
{
return 5.0;
}
}
|
package com.davivienda.sara.tablas.tareasadminaccesousuario.servicio;
import com.davivienda.sara.base.AdministracionTablasInterface;
import com.davivienda.sara.base.BaseEntityServicio;
import com.davivienda.sara.entitys.TareasadminAccesoUsuario;
import javax.persistence.EntityManager;
/**
* EdcMultifuncionalServicio Versión : 1.0
*
* @author P-MDRUIZ Davivienda 2011
*/
public class TareasadminAccesoUsuarioServicio extends BaseEntityServicio<TareasadminAccesoUsuario> implements AdministracionTablasInterface<TareasadminAccesoUsuario> {
public TareasadminAccesoUsuarioServicio(EntityManager em) {
super(em, TareasadminAccesoUsuario.class);
}
public TareasadminAccesoUsuario obtenerTareaAdmAccesoUsuarioByMax() {
Long maxValue = 0L;
em = this.getEm();
maxValue = (Long) em.createNamedQuery("TareasadminAccesoUsuario.findMax").getSingleResult();
TareasadminAccesoUsuario tareasadminAccesoUsuario = (TareasadminAccesoUsuario) em.createNamedQuery("TareasadminAccesoUsuario.findByIdtareaaccesusu")
.setParameter("idtareaaccesusu", maxValue).getSingleResult();
return tareasadminAccesoUsuario;
}
}
|
package eCommerceDemos.business.concretes;
import eCommerceDemos.business.abstracts.UserInfoCheckService;
import eCommerceDemos.business.abstracts.UserService;
import eCommerceDemos.business.abstracts.ValidityCheckService;
import eCommerceDemos.core.abstracts.OuterService;
import eCommerceDemos.dataAccess.abstracts.UserDao;
import eCommerceDemos.entities.concretes.User;
public class UserManager implements UserService {
UserInfoCheckService checkService;
UserDao userDao;
OuterService outerService;
public UserManager(UserInfoCheckService checkService, UserDao userDao, OuterService outerService) {
super();
this.checkService = checkService;
this.userDao = userDao;
this.outerService = outerService;
}
@Override
public void userRegister(User user) {
ValidityCheckService validityCheckService = new ValidtyManager(userDao);
if (validityCheckService.isUsed(user.geteMail()) && checkService.checkEMail(user.geteMail())
&& checkService.checkFirstName(user.getFirstName()) && checkService.checkLastName(user.getLastName())
&& checkService.checkPassword(user.getPassword())
) {
userDao.addToDatabase(user);
outerService.registerWOS();
System.out.println("Dogrulama maili gonderildi: " + user.geteMail());
String allname = user.getFirstName() + " " + user.getLastName();
System.out.println("Kayit islemi tamamlanmisdir: " + allname);
} else {
System.out.println("Kayit ishlemi tamamlanmadi");
}
}
@Override
public void userLogIn(String eMail, String password) {
for (int i = 0; i < userDao.getAll().size(); i++) {
if (userDao.getAll().get(i).geteMail().equals(eMail)
&& userDao.getAll().get(i).getPassword().equals(password)) {
System.out.println("Giriş Başarılı!");
return;
} else {
System.out.println("Sifre ve ya Email yanlish");
return;
}
}
}
}
|
package net.mv.grub;
import net.mv.flatware.Plate;
public class Steak implements Food {
private Plate paperPlate;
private int size;
public Steak(int size){
this.size = size;
}
public void setPaperPlate(Plate paperPlate){
this.paperPlate = paperPlate;
}
@Override
public void getEaten() {
System.out.println("You ate me!!!");
}
@Override
public void rot() {
System.out.println("I'm decaying!");
}
@Override
public void tasteDelicious() {
System.out.println("I taste delicious when eaten rare");
}
@Override
public void setPlate() {
paperPlate.disintegrate();
}
@Override
public void printSize() {
System.out.println(this.size);
}
}
|
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class ERSimulator {
private PriorityQueue patientList1;
private PriorityQueue patientList2;
private PriorityQueue roomList;
private LocalDateTime endTime;
public ERSimulator(){
patientList1 = new PriorityQueue<Patient>();
patientList2 = new PriorityQueue<Patient>();
roomList = new PriorityQueue<TreatRoom>();
}
/**
* treat patient emulator
*/
public void emulator2(){//get enter time
patientList2.insert(patientList1.front());
LocalDateTime enterTime = LocalDateTime.now();
Patient patientEnter = (Patient) patientList1.remove();//the patient in the patient queue get into treat room
roomList.remove();//the first room in the treat room queue is occupied now
}
public void departure(){
while(LocalDateTime.now().isBefore(endTime)){
if(LocalDateTime.now().isEqual(this.emulator2().plusMinutes())){
}
}
}
}
|
package com.share.myview2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private String[] mVale = new String[]{"hello", "android", "button", "nihoa", "hello", "android",
"buttdfon", "nidsfdshoa", "helsdsalo", "anSSFDSdroid", "butsdasdfton", "nihohihiua"};
private FlowLayout mFlowLayout;
private RecyclerView mRecyclerView;
private List<String> mList;
private simpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDats();
initViews();
/*mFlowLayout = (FlowLayout) findViewById(R.id.flow_Id);
initData();*/
}
private void initViews() {
mRecyclerView = (RecyclerView) findViewById(R.id.recy);
adapter = new simpleAdapter(this, mList);
mRecyclerView.setAdapter(adapter);
//设置 它的布局管理
RecyclerView.LayoutManager linLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//设置分割线 item 之间的
/* mRecyclerView.addItemDecoration(new
DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
*/
}
private void initDats() {
mList = new ArrayList<>();
for (int i = 'A'; i < 'z'; i++) {
mList.add("" + (char) i);
}
}
//动态添加元素
public void initData() {
/* for (int i = 0; i < mVale.length; i++) {
Button button = new Button(this);
MarginLayoutParams lParams = new MarginLayoutParams(MarginLayoutParams.WRAP_CONTENT,
MarginLayoutParams.WRAP_CONTENT);
button.setText(mVale[i]);
mFlowLayout.addView(button,lParams);
}*/
LayoutInflater mInflater = LayoutInflater.from(this);
for (int i = 0; i < mVale.length; i++) {
TextView tView = (TextView) mInflater.inflate(R.layout.txt, mFlowLayout, false);
tView.setText(mVale[i]);
mFlowLayout.addView(tView);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_listView:
//设置 它的布局管理
RecyclerView.LayoutManager linLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRecyclerView.setLayoutManager(linLayoutManager);
break;
case R.id.action_gridView:
mRecyclerView.setLayoutManager(new GridLayoutManager(this,3));
break;
case R.id.action_hor_gridview:
//水平的时候设置 item大小
mRecyclerView.setLayoutManager(new AutoGridLayoutManager(this,5,LinearLayoutManager.HORIZONTAL,false));
break;
case R.id.action_stagger:
break;
case R.id.action_add:
adapter.addData(1);
break;
case R.id.action_delete:
adapter.deleteDate(1);
break;
}
return super.onOptionsItemSelected(item);
}
}
|
package com.trump.auction.cust.controller;
import com.trump.auction.cust.model.UserInfoModel;
import com.trump.auction.cust.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisCluster;
@RestController
public class TestController {
private final static Logger logger = LoggerFactory
.getLogger(TestController.class);
@Autowired
private JedisCluster jedisCluster;
@Autowired
private UserInfoService userInfoService;
// @RequestMapping(value = { "/", "/index" })
@RequestMapping(value = "/tttt", method = RequestMethod.GET)
public String getccc() {
String userPhone = "123123";
Integer id = 1;
UserInfoModel user = userInfoService.findUserIndexInfoById(id);
Integer sun = userInfoService.updateUserPhoneById(userPhone,id);
return String.valueOf(sun);
}
}
|
package org.study.schedule;
import java.util.List;
import org.study.admin.ScheduleVO;
public interface ScheduleService {
public List<ScheduleVO> reserveSelectDay() throws Exception;
public List<ScheduleVO> reserveSelectTime(String movie_code, String cinema_code, String day) throws Exception;
public ScheduleVO reserveSelectSchedule(String schedule_code) throws Exception;
public List<ScheduleVO> selectSchedule_date() throws Exception;
}
|
package syifa.app.portalti16.entity;
import java.io.Serializable;
/**
* Created by USER on 26/11/2018.
*/
public class Mahasiswa implements Serializable {
private int id;
private String name;
private String nim;
public Mahasiswa(String name, String nim) {
this.name = name;
this.nim = nim;
}
public String getName() {
return name;
}
public String getNim() {
return nim;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public void setNim(String nim) {
this.nim = nim;
}
}
|
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
private static HashMap<String,Integer> makeHash(String str)
{
HashMap<String, Integer> hashMap = new HashMap<>();
String[] split = str.split("|");
for (String s:split)
{
if (!hashMap.containsKey(s))
{
hashMap.put(s,1);
}else {
hashMap.put(s,hashMap.get(s)+1);
}
}
return hashMap;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String sale = scanner.nextLine();
String red = scanner.nextLine();
HashMap<String, Integer> saleHash = makeHash(sale);
HashMap<String, Integer> redHash = makeHash(red);
boolean isOkey = true;
int plus = 0; // 剩余的珠子
int minus = 0; // 缺的珠子
for(Map.Entry<String,Integer> entry:redHash.entrySet())
{
String key = entry.getKey();
Integer value = entry.getValue();
Integer saleValue = saleHash.get(key);
// System.out.println("key:"+key+";value:"+value+";saleValue:"+saleValue);
if (!saleHash.containsKey(key))
{
// 不存在key
isOkey = false;
minus += (value);
}else if(value>saleValue) {
// 缺珠子
minus += (value - saleValue);
// System.out.println("!!!!!key:"+key+";value:"+value+";saleValue:"+saleValue);
// System.out.println(minus);
isOkey = false;
}else {
plus += (saleValue - value);
}
}
if (isOkey)
{
for (Map.Entry<String,Integer> entry:saleHash.entrySet())
{
// 把剩下的珠子数量加上去
String key = entry.getKey();
if (!redHash.containsKey(key))
{
plus += entry.getValue();
}
}
System.out.println("Yes "+plus);
}else {
System.out.println("No "+minus);
}
}
}
|
package tal.com.orders.converters;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import tal.com.orders.entities.PaymentMethod;
@Converter(autoApply = true)
public class PaymentMethodConverter implements AttributeConverter<PaymentMethod , String > {
@Override
public String convertToDatabaseColumn(PaymentMethod method) {
switch(method){
case CREDIT:
return "CRE";
case CHEQUE:
return "CHE";
case CASH:
return "CAS";
case TRANSFER:
return "TRA";
default:
throw new IllegalArgumentException("Unknown method: " + method);
}
}
@Override
public PaymentMethod convertToEntityAttribute(String dbData) {
switch(dbData){
case "CRE":
return PaymentMethod.CREDIT;
case "CHE":
return PaymentMethod.CHEQUE;
case "CAS":
return PaymentMethod.CASH;
case "TRA":
return PaymentMethod.TRANSFER;
default:
throw new IllegalArgumentException("Unknown value: " + dbData);
}
}
}
|
package hu.gyabraham.wlspringboot;
import hu.gyorgyabraham.RequestStructure;
import hu.gyorgyabraham.ResponseStructure;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
@Endpoint
public class MockEndpoint {
@PayloadRoot(namespace = "http://gyorgyabraham.hu", localPart = "RequestStructure")
@ResponsePayload
public ResponseStructure responseStructure(@RequestPayload RequestStructure request) {
return new ResponseStructure() {{
setRsuid(request.getRquid());
setMessage("Hello from example app!");
}};
}
}
|
public class DishTest {
// Create another class called DishTest
// Add a main method and inside the method...
// 1) instantiate a Dish object and assign to a variable called dish1
// 2) assign creative values for each of the properties
// 3) test the printSummary() method by invoking it and checking if all instance values are correctly printed
public static void main(String[] args){
// Dish shakshuka = new Dish();
// shakshuka.nameOfDish = "Shakshuka";
// shakshuka.costInCents = 1100;
// shakshuka.wouldRecommend = true;
// shakshuka.vegetarian = true;
// shakshuka.courseType = "Entree";
// shakshuka.origin = "North Africa, Middle East";
//
// Dish bananasFoster = new Dish();
// bananasFoster.nameOfDish = "Bananas Foster";
// bananasFoster.costInCents = 899;
// bananasFoster.wouldRecommend = false;
// bananasFoster.vegetarian = true;
// bananasFoster.courseType = "Dessert";
// bananasFoster.origin = "New Orleans";
//
// Dish maqluba = new Dish();
// maqluba.nameOfDish = "Maqluba";
// maqluba.costInCents = 1200;
// maqluba.wouldRecommend = true;
// maqluba.vegetarian = false;
// maqluba.courseType = "Entree";
// maqluba.origin = "Middle East, Eastern Mediterranean";
//
// Dish chickenMarsala = new Dish();
// chickenMarsala.nameOfDish = "Chicken Marsala";
// chickenMarsala.costInCents = 1350;
// chickenMarsala.wouldRecommend = true;
// chickenMarsala.vegetarian = false;
// chickenMarsala.courseType = "Entree";
// chickenMarsala.origin = "Italy";
//
// Dish doroWat = new Dish();
// doroWat.nameOfDish = "Doro Wat";
// doroWat.costInCents = 1000;
// doroWat.wouldRecommend = true;
// doroWat.vegetarian = false;
// doroWat.courseType = "Entree";
// doroWat.origin = "Ethiopia";
//
// Dish lambBiryani = new Dish();
// lambBiryani.nameOfDish = "Lamb Biryani";
// lambBiryani.costInCents = 1200;
// lambBiryani.wouldRecommend = true;
// lambBiryani.vegetarian = false;
// lambBiryani.courseType = "Entree";
// lambBiryani.origin = "Middle East, India";
//
// Dish cobbSalad = new Dish();
// cobbSalad.nameOfDish = "Cobb Salad with Gorgonzola";
// cobbSalad.costInCents = 699;
// cobbSalad.wouldRecommend = false;
// cobbSalad.vegetarian = false;
// cobbSalad.courseType = "Appetizer";
// cobbSalad.origin = "United States";
// shakshuka.printSummary();
// bananasFoster.printSummary();
// maqluba.printSummary();
// chickenMarsala.printSummary();
// doroWat.printSummary();
// lambBiryani.printSummary();
// cobbSalad.printSummary();
// DishTools.shoutDishName(shakshuka);
// DishTools.shoutDishName(cobbSalad);
//
// DishTools.analyzeDishCost(maqluba);
// DishTools.analyzeDishCost(chickenMarsala);
// System.out.println(DishTools.flipRecommendation(cobbSalad));
// System.out.println(DishTools.flipRecommendation(chickenMarsala));
//
// cobbSalad.printSummary();
// chickenMarsala.printSummary();
//Refactor to use constructors and get/set=========================
Dish d1 = new Dish(1000, "Doro Wat", true, false, "Entree", "Ethiopia");
Dish d2 = new Dish(1200, "Lamb Biryani", true, false, "Entree", "Middle East, India");
// d1.printSummary();
// d2.printSummary();
System.out.println(d1.getCostInCents()); //1000
d1.setCostInCents(1550);
d1.printSummary(); //cost is now 1550
DishTools.shoutDishName(d1);
System.out.println(DishTools.flipRecommendation(d1));
DishTools.analyzeDishCost(d1);
}
}
|
package br.com.douglastuiuiu.biometricengine.integration.creddefense.dto.response.pooling;
import java.io.Serializable;
/**
* @author douglas
* @since 31/03/2017
*/
public class PoolingCol1CreditRequestDTO implements Serializable {
private static final long serialVersionUID = -3557139308923109045L;
private String photo;
private String identification;
private String similarity;
private String name;
private String identifier_code;
private String birth_date;
private String insert_date;
private Integer place_id;
private String place;
private String status;
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getIdentification() {
return identification;
}
public void setIdentification(String identification) {
this.identification = identification;
}
public String getSimilarity() {
return similarity;
}
public void setSimilarity(String similarity) {
this.similarity = similarity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdentifier_code() {
return identifier_code;
}
public void setIdentifier_code(String identifier_code) {
this.identifier_code = identifier_code;
}
public String getBirth_date() {
return birth_date;
}
public void setBirth_date(String birth_date) {
this.birth_date = birth_date;
}
public String getInsert_date() {
return insert_date;
}
public void setInsert_date(String insert_date) {
this.insert_date = insert_date;
}
public Integer getPlace_id() {
return place_id;
}
public void setPlace_id(Integer place_id) {
this.place_id = place_id;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package chatClient.ListOnlineUI;
import dependencies.lib.UserBean;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ListOnlineController {
ListOnlineModel model;
ListOnlineView view;
private UserBean user;
public ListOnlineController(UserBean user) {
this.user = user;
view = new ListOnlineView();
model = new ListOnlineModel(view, this.user.getUserHandle());
view.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
int index = view.getList().getSelectedIndex();
UserBean selectedValue = view.getList().getSelectedValue();
selectedValue.resetMessage();
view.getListModel().setElementAt(selectedValue, index);
view.setMessageBox(selectedValue.getUserHandle());
} catch (Exception e1) {
System.err.println("List Empty");
}
}
});
}
public ListOnlineModel getModel() {
return model;
}
}
|
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
class Demo extends JFrame
{
public Demo(Object row[][])
{
Container c=getContentPane();
c.setLayout(new BorderLayout()) ;
Object cols[]={"Prodid","Product","CP","Discount","SP"};
JTable tab=new JTable(row,cols);
tab.setFont(new Font("Arial",Font.BOLD,10));
tab.setRowHeight(20);
tab.setGridColor(Color.blue);
tab.setBackground(Color.white);
tab.setEnabled(false);
JTableHeader head=tab.getTableHeader();
head.setBackground(Color.orange);
head.setFont(new Font("Arial",Font.BOLD,20));
c.add("North",head);
c.add("Center",tab);
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* 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
*
* https://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.springframework.context.annotation;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.lang.Nullable;
/**
* A variation of {@link ImportSelector} that runs after all {@code @Configuration} beans
* have been processed. This type of selector can be particularly useful when the selected
* imports are {@code @Conditional}.
*
* <p>Implementations can also extend the {@link org.springframework.core.Ordered}
* interface or use the {@link org.springframework.core.annotation.Order} annotation to
* indicate a precedence against other {@link DeferredImportSelector DeferredImportSelectors}.
*
* <p>Implementations may also provide an {@link #getImportGroup() import group} which
* can provide additional sorting and filtering logic across different selectors.
*
* @author Phillip Webb
* @author Stephane Nicoll
* @since 4.0
*/
public interface DeferredImportSelector extends ImportSelector {
/**
* Return a specific import group.
* <p>The default implementations return {@code null} for no grouping required.
* @return the import group class, or {@code null} if none
* @since 5.0
*/
@Nullable
default Class<? extends Group> getImportGroup() {
return null;
}
/**
* Interface used to group results from different import selectors.
* @since 5.0
*/
interface Group {
/**
* Process the {@link AnnotationMetadata} of the importing @{@link Configuration}
* class using the specified {@link DeferredImportSelector}.
*/
void process(AnnotationMetadata metadata, DeferredImportSelector selector);
/**
* Return the {@link Entry entries} of which class(es) should be imported
* for this group.
*/
Iterable<Entry> selectImports();
/**
* An entry that holds the {@link AnnotationMetadata} of the importing
* {@link Configuration} class and the class name to import.
*/
class Entry {
private final AnnotationMetadata metadata;
private final String importClassName;
public Entry(AnnotationMetadata metadata, String importClassName) {
this.metadata = metadata;
this.importClassName = importClassName;
}
/**
* Return the {@link AnnotationMetadata} of the importing
* {@link Configuration} class.
*/
public AnnotationMetadata getMetadata() {
return this.metadata;
}
/**
* Return the fully qualified name of the class to import.
*/
public String getImportClassName() {
return this.importClassName;
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
Entry entry = (Entry) other;
return (this.metadata.equals(entry.metadata) && this.importClassName.equals(entry.importClassName));
}
@Override
public int hashCode() {
return (this.metadata.hashCode() * 31 + this.importClassName.hashCode());
}
@Override
public String toString() {
return this.importClassName;
}
}
}
}
|
package com.pronix.android.apssaataudit;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pronix.android.apssaataudit.Dal.DalUserMaster;
import com.pronix.android.apssaataudit.common.Constants;
/**
* Created by ravi on 1/2/2018.
*/
public class SSAATScheme extends BaseActivity implements View.OnClickListener{
RelativeLayout rl_MGNREGA;
TextView tv_ProfileName;
TextView tv_MGNREGA;
DalUserMaster dalUserMaster;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_ssaatscheme, frame_base);
dalUserMaster = new DalUserMaster();
dalUserMaster.getUserDetails(Constants.PIN, Constants.USERORMOBILE);
initializeControls();
setLaunguageTexts();
}
public void initializeControls()
{
rl_MGNREGA = (RelativeLayout) findViewById(R.id.rl_MGNREGA);
rl_MGNREGA.setOnClickListener(this);
tv_MGNREGA = (TextView) findViewById(R.id.tv_MGNREGA);
tv_ProfileName = (TextView) findViewById(R.id.tv_ProfileName);
tv_ProfileName.setText(Constants.userMasterDO.designation + " : " + Constants.userMasterDO.userName);
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.rl_MGNREGA:
Intent in = new Intent();
in.setClass(this, MainActivity.class);
startActivity(in);
break;
}
}
public void setLaunguageTexts()
{
// tv_MGNREGA.setText(R.string.MGNREGA);
}
@Override
public void onBackPressed() {
logout();
}
public void logout()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("SSAAT");
alertDialog.setMessage("Do you want to Logout Now.. ?");
alertDialog.setIcon(R.mipmap.ic_launcher);
alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
sessionManager.logoutUser();
Intent intent = new Intent(SSAATScheme.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
|
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package edu.psu.cse.siis.ic3;
import edu.psu.cse.siis.coal.arguments.Argument;
import edu.psu.cse.siis.coal.arguments.ArgumentValueAnalysis;
import edu.psu.cse.siis.coal.arguments.ArgumentValueManager;
import edu.psu.cse.siis.ic3.DataAuthority;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import soot.Unit;
import soot.Value;
import soot.jimple.InvokeExpr;
import soot.jimple.Stmt;
public class AuthorityValueAnalysis extends ArgumentValueAnalysis {
private static final Object TOP_VALUE = new DataAuthority("(.*)", "(.*)");
public AuthorityValueAnalysis() {
}
public Set<Object> computeArgumentValues(Argument argument, Unit callSite) {
ArgumentValueAnalysis stringAnalysis = ArgumentValueManager.v().getArgumentValueAnalysis("String");
Stmt stmt = (Stmt)callSite;
if(!stmt.containsInvokeExpr()) {
throw new RuntimeException("Statement " + stmt + " does not contain an invoke expression");
} else {
InvokeExpr invokeExpr = stmt.getInvokeExpr();
Set hosts = stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[0]), stmt);
Set ports = stringAnalysis.computeVariableValues(invokeExpr.getArg(argument.getArgnum()[1]), stmt);
HashSet result = new HashSet();
Iterator var9 = hosts.iterator();
while(var9.hasNext()) {
Object host = var9.next();
Iterator var11 = ports.iterator();
while(var11.hasNext()) {
Object port = var11.next();
result.add(new DataAuthority((String)host, (String)port));
}
}
return result;
}
}
public Set<Object> computeInlineArgumentValues(String[] inlineValue) {
return new HashSet(Arrays.asList(inlineValue));
}
public Object getTopValue() {
return TOP_VALUE;
}
public Set<Object> computeVariableValues(Value value, Stmt callSite) {
throw new RuntimeException("Should not be reached.");
}
}
|
package templateMethod;
/**
* Date: 2019/3/4
* Created by LiuJian
*
* @author LiuJian
*/
class WindowsComputer extends Computer {
@Override
protected void computeWithSoft() {
System.out.println("compute with soft B");
}
@Override
protected void loadOperateSystem() {
System.out.println("load operate system Windows");
}
@Override
protected boolean shouldDisplay() {
return false;
}
}
|
package de.varylab.discreteconformal.functional.node;
import de.jtem.halfedge.Face;
public class ConformalFace <
V extends ConformalVertex<V, E, F>,
E extends ConformalEdge<V, E, F>,
F extends ConformalFace<V, E, F>
> extends Face<V, E, F> {
private double
initialEnergy = 0.0;
public double getInitialEnergy() {
return initialEnergy;
}
public void setInitialEnergy(double energy) {
this.initialEnergy = energy;
}
}
|
package br.edu.ifpb.tsi.pdm.pdmproject.model;
import android.annotation.SuppressLint;
import java.text.SimpleDateFormat;
import java.util.Calendar;
@SuppressLint("SimpleDateFormat")
public class Tarefa {
private int id;
private Atividade atividade;
private Disciplina disciplina;
private Calendar dataHora;
private Calendar dataHoraNotificacao;
public Tarefa(Atividade atividade, Disciplina disciplina,
Calendar dataHora, Calendar dataHoraNotificacao) {
super();
this.atividade = atividade;
this.disciplina = disciplina;
this.dataHora = dataHora;
this.dataHoraNotificacao = dataHoraNotificacao;
}
public Tarefa() {
}
public Calendar getDataHoraNotificacao() {
return dataHoraNotificacao;
}
public void setDataHoraNotificacao(Calendar dataHoraNotificacao) {
this.dataHoraNotificacao = dataHoraNotificacao;
}
public void setDataHoraNotificacao(long dataHoraNotificacao) {
this.dataHoraNotificacao = Calendar.getInstance();
this.dataHoraNotificacao.setTimeInMillis(dataHoraNotificacao);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Atividade getAtividade() {
return atividade;
}
public void setAtividade(Atividade atividade) {
this.atividade = atividade;
}
public Disciplina getDisciplina() {
return disciplina;
}
public void setDisciplina(Disciplina disciplina) {
this.disciplina = disciplina;
}
public Calendar getDataHora() {
return dataHora;
}
public void setDataHora(Calendar dataHora) {
this.dataHora = dataHora;
}
public void setDataHora(long dataHora) {
this.dataHora = Calendar.getInstance();
this.dataHora.setTimeInMillis(dataHora);
}
public String toString(){
StringBuilder string = new StringBuilder();
string.append(getAtividade().toString() + " de ");
string.append(this.disciplina + ". \n");
string.append("Data: " + new SimpleDateFormat("dd/MM/yyyy.").format(this.dataHora.getTime()));
return string.toString();
}
public String toStringComNotificacao() {
if(this.dataHoraNotificacao != null && this.dataHoraNotificacao.getTimeInMillis() != 0){
return new StringBuilder().
append(this.toString()).
append("\nNotificação: ").
append(new SimpleDateFormat("dd/MM/yyyy HH:mm.").
format(this.dataHoraNotificacao.getTime())).toString();
} else
return this.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.