text
stringlengths 10
2.72M
|
|---|
package com.github.dongchan.scheduler;
/**
* @author DongChan
* @date 2020/10/23
* @time 3:35 PM
*/
public interface SchedulerState {
boolean isShuttingDown();
boolean isStarted();
class SettableSchedulerState implements SchedulerState {
private boolean isShuttingDown;
private boolean isStarted;
@Override
public boolean isShuttingDown() {
return isShuttingDown;
}
public void setShuttingDown(boolean shuttingDown) {
isShuttingDown = shuttingDown;
}
@Override
public boolean isStarted() {
return isStarted;
}
public void setStarted(boolean started) {
isStarted = started;
}
}
}
|
package com.onightperson.hearken.datetime;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.onightperson.hearken.R;
import com.onightperson.hearken.base.BaseActivity;
import com.onightperson.hearken.util.ProblemUtils;
/**
* Created by liubaozhu on 17/7/9.
*/
public class DateTimeActivity extends BaseActivity implements View.OnClickListener {
private static int add = 0;
private Button mTestWeekBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date_time);
initViews();
}
private void initViews() {
mTestWeekBtn = (Button) findViewById(R.id.test_week);
mTestWeekBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == mTestWeekBtn) {
DateTimeUtils.testWeek(add++);
ProblemUtils.testArrayListCopy();
}
}
}
|
package chat.errors;
/**
*/
public interface GroovyErrorCodes {
public static final int CODE_CORE = 18000;
//Groovy related codes.
public static final int ERROR_GROOVY_CLASSNOTFOUND = CODE_CORE + 1;
public static final int ERROR_GROOY_NEWINSTANCE_FAILED = CODE_CORE + 2;
public static final int ERROR_GROOY_CLASSCAST = CODE_CORE + 3;
public static final int ERROR_GROOVY_INVOKE_FAILED = CODE_CORE + 4;
public static final int ERROR_GROOVYSERVLET_SERVLET_NOT_INITIALIZED = CODE_CORE + 5;
public static final int ERROR_URL_PARAMETER_NULL = CODE_CORE + 6;
public static final int ERROR_URL_VARIABLE_NULL = CODE_CORE + 7;
public static final int ERROR_GROOVY_PARSECLASS_FAILED = CODE_CORE + 8;
public static final int ERROR_GROOVY_UNKNOWN = CODE_CORE + 9;
public static final int ERROR_GROOVY_CLASSLOADERNOTFOUND = CODE_CORE + 10;
public static final int ERROR_JAVASCRIPT_LOADFILE_FAILED = CODE_CORE + 11;
public static final int ERROR_URL_HEADER_NULL = CODE_CORE + 12;
}
|
package forms;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.SafeHtml;
import org.hibernate.validator.constraints.SafeHtml.WhiteListType;
public class ManagerForm {
private String username;
private String password;
private String confirmPassword;
private String name;
private String surname;
private String email;
private String phoneNumber;
private String company;
private String vatNumber;
@Size(min = 5, max = 32)
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getUsername() {
return this.username;
}
public void setUsername(final String username) {
this.username = username;
}
@Size(min = 5, max = 32)
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getPassword() {
return this.password;
}
public void setPassword(final String password) {
this.password = password;
}
@Size(min = 5, max = 32)
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getConfirmPassword() {
return this.confirmPassword;
}
public void setConfirmPassword(final String confirmPassword) {
this.confirmPassword = confirmPassword;
}
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getSurname() {
return this.surname;
}
public void setSurname(final String surname) {
this.surname = surname;
}
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
@Email
public String getEmail() {
return this.email;
}
public void setEmail(final String email) {
this.email = email;
}
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
@Pattern(regexp = "(\\+\\d{1,3} )?(\\(\\d{1,3}\\) )?(\\w{4,})")
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getCompany() {
return this.company;
}
public void setCompany(final String company) {
this.company = company;
}
@Size(min = 2, max = 13)
@SafeHtml(whitelistType = WhiteListType.SIMPLE_TEXT)
@NotBlank
@NotNull
public String getVatNumber() {
return this.vatNumber;
}
public void setVatNumber(final String vatNumber) {
this.vatNumber = vatNumber;
}
}
|
package com.gxtc.huchuan.ui.live.foreshowlist;
import com.gxtc.commlibrary.BasePresenter;
import com.gxtc.commlibrary.BaseUiView;
import com.gxtc.commlibrary.data.BaseSource;
import com.gxtc.huchuan.bean.ChatInfosBean;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Gubr on 2017/3/30.
*/
public interface ForeshowListContract {
public interface View extends BaseUiView<Presenter> {
void showData(List<ChatInfosBean> datas);
void showLoMore(List<ChatInfosBean> datas);
void loadFinish();
}
public interface Presenter extends BasePresenter {
void getData(boolean isloadmroe, int start);
}
public interface Source extends BaseSource {
void getData(HashMap<String, String> map, ApiCallBack<ArrayList<ChatInfosBean>> callBack);
}
}
|
package script.javascript.runtime;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import chat.errors.ChatErrorCodes;
import chat.errors.CoreException;
import chat.utils.FileExtensionFilter;
import script.ScriptRuntime;
public class JavascriptRuntime extends ScriptRuntime {
private ScriptEngineManager scriptEngineManager;
private ScriptEngine currentScriptEngine;
@Override
public void init() throws CoreException {
scriptEngineManager = new ScriptEngineManager();
redeploy();
}
@Override
public void redeploy() throws CoreException {
final ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
final File file = new File(path);
FileExtensionFilter filter = new FileExtensionFilter().filter(file);
List<File> files = filter.getFiles();
for(File theFile : files) {
try {
FileReader reader = new FileReader(theFile.getAbsolutePath().replaceAll("\\\\", "/"));
if (scriptEngine instanceof Compilable) {
System.out.println("Compiling.... " + theFile);
Compilable compEngine = (Compilable) scriptEngine;
CompiledScript cs = compEngine.compile(reader);
cs.eval();
} else {
scriptEngine.eval(reader);
}
} catch (FileNotFoundException | ScriptException e) {
e.printStackTrace();
throw new CoreException(ChatErrorCodes.ERROR_JAVASCRIPT_LOADFILE_FAILED, "Load js file " + theFile + " failed, " + e.getMessage());
}
}
currentScriptEngine = scriptEngine;
}
@Override
public void close() {
}
public ScriptEngine getCurrentScriptEngine() {
return currentScriptEngine;
}
public void setCurrentScriptEngine(ScriptEngine currentScriptEngine) {
this.currentScriptEngine = currentScriptEngine;
}
}
|
package ch7;
class Shape{
String color = "black";
void draw() {
System.out.printf("[color=%s]%n", color);
}
}
class PointD{
int x;
int y;
PointD(int x, int y){
this.x = x;
this.y = y;
}
PointD() {
this(0, 0);
}
String getXY() {
return "("+x+","+y+")"; //x,y 문자열로 반환
}
String getLocation() {
return "x : "+x+" y : "+y;
}
}
class Circle extends Shape{
Point center; //원의 원점 좌표
int r; //반지름
Circle() {
this(new Point(0, 0), 100); // Circle(Point center, int r) 호출
}
Circle(Point center, int r){
this.center = center;
this.r = r;
}
void draw() {
System.out.printf("[center=(%d, %d), r=%d, color=%s]%n", center.x, center.y, r, color);
}
}
class Triangle extends Shape{
PointD[] p = new PointD[3];
Triangle(PointD[] p) {
this.p = p;
}
void draw() {
System.out.printf("[p1=%s, p2=%s, p3=%s, color=%s]%n",
p[0].getXY(), p[1].getXY(), p[2].getXY(), color);
}
}
public class DrawShape {
public static void main(String[] args) {
PointD[] p = {
new PointD(100, 100),
new PointD(140, 50),
new PointD(200, 100)
};
Triangle t = new Triangle(p);
//Circle c = new Circle(new Point(150, 150), 50);
Point p1 = new Point(150, 150);
Circle c = new Circle(p1, 50);
t.draw();
c.draw();
}
}
|
package com.enedis.ludovic;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Classe pour l'affichage des menus et les selections de jeu, mode et choix de fin de partie
*/
public class Menu {
private static final Logger logger = LogManager.getLogger();
private String devModeArgs;
public Menu(String devModeArgs) {
this.devModeArgs = devModeArgs;
}
/**
* Cette méthode est utilisé afin d'afficher les menus de selection, pour le choix du jeu ainsi que du mode
*/
public void gameChoice() {
Config config = new Config("config.properties");
int longNbAlea = config.getIntPropertiesByName("longNbAlea");
int nombreDeTour = config.getIntPropertiesByName("nombreDeTour");
int nombreChiffreUtilisables = config.getIntPropertiesByName("nombrePionPossible");
int devMode = config.getIntPropertiesByName("devMode");
if (devModeArgs.equals("dm"))
devMode = 1;
PlusOuMoins plusOuMoins = new PlusOuMoins(longNbAlea, nombreDeTour, devMode);
plusOuMoins.setMenu(this);
Mastermind mastermind = new Mastermind(longNbAlea, nombreDeTour, nombreChiffreUtilisables, devMode);
mastermind.setMenu(this);
String choixJeu ;
String choixMode ;
System.out.println("Veuillez choisir votre jeux");
System.out.println("1: Recherche +/-");
System.out.println("2: Mastermind");
choixJeu = Tools.saisieNumero(1, 1,3);
logger.info("Demande du choix du jeu");
switch (choixJeu) {
case "1":
logger.info("L'utilisateur choisit le Plus ou Moins");
Messages.plusOuMoins();
System.out.println("Veuilez choisir votre mode de jeu. 1 - Challenger, 2 - Défenseur, 3 - Duel");
choixMode = Tools.saisieNumero(1, 1,3);
logger.info("Demande du choix du mode (Plus ou Moins)");
switch (choixMode) {
case "1":
logger.info("L'utilisateur choisit le mode challenger");
System.out.println("Bienvenue dans le +/-, mode Challenger !");
plusOuMoins.plusOuMoinsChallenger();
break;
case "2":
logger.info("L'utilisateur choisit le mode défenseur");
System.out.println("Bienvenue dans le +/-, mode Défenseur !");
plusOuMoins.plusOuMoinsDefenseur();
break;
case "3":
logger.info("L'utilisateur choisit le mode duel");
System.out.println("Bievenue dans le +/-, mode duel !");
plusOuMoins.plusOuMoinsDuel();
break;
}
break;
case "2":
logger.info("L'utilisateur choisi le Mastermind");
Messages.mastermind();
System.out.println("Veuilez choisir votre mode de jeu. 1 - Challenger, 2 - Défenseur, 3 - Duel");
choixMode = Tools.saisieNumero(1, 1,3);
logger.info("Choix du mode (Mastermind)");
switch (choixMode) {
case "1":
logger.info("L'utilisateur choisit le mode challenger");
System.out.println("Bienvenue dans le Mastermind, mode Challenger !");
mastermind.mastermindChallenger();
break;
case "2":
logger.info("L'utilisateur choisit le mode défenseur");
System.out.println("Bienvenue dans le Mastermind, mode Défenseur !");
mastermind.mastermindDefenseur();
break;
case "3":
logger.info("L'utilisateur choisit le mode duel");
System.out.println("Bievenue dans le Mastermind, mode duel !");
mastermind.mastermindDuel();
break;
}
break;
}
}
/**
* Cette méthode affiche le menu de fin de partie
*
* @return retourne le boolean qui permet de refaire une nouvelle partie
*/
public boolean finDePArtie() {
String replay ;
System.out.println("Que souhaitez vous faire ? 1: Rejouer -- 2: Choisir un autre jeu --3: Quitter");
logger.info("Choix de fin de partie");
replay = Tools.saisieNumero(1, 1,3);
switch (replay) {
case "1":
logger.info("L'utilisateur choisi de rejouer");
return true;
case "2":
logger.info("L'utilisateur choisi de jouer un autre jeu");
gameChoice();
break;
case "3":
logger.info("L'utilisateur choisi de quitter");
System.out.println("Merci d'avoir joué, à bientot !");
break;
}
return false;
}
}
|
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import org.json.simple.*;
public class GameLogic extends HttpServlet
{
public static int players = 0;
public static boolean gameFull = false;
public static String[] AllCards = getCards();
public static String[] CurrentTrick = new String[4];
public static int trumpSuit;
public static int whoWonLast = 1;
public static int trickState = 0;
public static int trickSuit;
public static boolean trickStarted = false;
public static State state;
public static int[] scores = new int[4];
public static String[] names = new String[4];
public void init() throws ServletException
{
shuffle(AllCards);
state = State.WAIT; // wait state
}
/************************************************************************/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
if(players == 4)
trickStarted = true;
String resp = "";
response.setContentType("application/json");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
if(request.getParameter("type").equals("addPlayer")) // New player
{
if(state.toString() == "WAIT")
{
resp = addPlayer(request.getParameter("name"), session);
}
else // new player but full
resp = "Full!";
}
else if(request.getParameter("type").equals("update")) // update request from client
{
resp = update(session);
}
out.write(resp);
}
/***************************************************************************/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
}
/****************************************************************************/
public void destroy()
{
// do nothing.
}
/*****************************************************************************/
/*return suitable response to addPlayer request from client*/
public String addPlayer(String name, HttpSession session)
{
//add new player
names[players] = name.replace("\"","");
session.setAttribute("playerName", name);
players++;
session.setAttribute("playerId", players);
//setting up cards for player
String[] cards = new String[13];
JSONObject innerObject, mainObject;
JSONArray jArray = new JSONArray();
for(int i = 0; i<13; i++) // add cards to player
{
innerObject = new JSONObject();
innerObject.put("image",AllCards[13*(players-1)+i]);
jArray.add(innerObject);
cards[i] = AllCards[13*(players-1)+i];
}
mainObject = new JSONObject();
mainObject.put("cards",jArray); // add card list
mainObject.put("trumpSuit", Integer.parseInt(AllCards[AllCards.length-1].charAt(6)+"")); // add trumpsuit
//store player's cards in session data
session.setAttribute("cards", cards); // store user's card in session
if(players == 4)
{
gameFull = true;
state = state.eval("ready");
shuffle(AllCards);
}
return mainObject.toString().replace("\\","");
}
/********************************************************************************/
/*returns the suitable response to polling requests*/
public static String update(HttpSession session)
{
JSONObject innerObject, mainObject;
JSONArray jArray = new JSONArray();
JSONArray score = new JSONArray();
JSONArray name = new JSONArray();
String message = "";
mainObject = new JSONObject();
int max = 0, maxIndex = 0;
for(int i = 0; i<4; i++)
{
if(scores[i] > 9) // check if a player has won
{
trickStarted = false;
mainObject.put("won",true);
message = names[i]+" won the game!";
}
else if(Score.rounds == 13) // if all cards are played, player with max marks win
{
System.out.println(Score.rounds);
for(int j = 0; j<4; j++)
{
if(scores[j] >max)
{
maxIndex = j;
max = scores[j];
}
}
trickStarted = false;
mainObject.put("won",true);
message = names[maxIndex]+" won the game!";
}
else
mainObject.put("won",false);
}
if(!trickStarted) // trick not started yet
{
mainObject.put("cards",jArray);
mainObject.put("shouldShowHand", false);
mainObject.put("message", message);
return mainObject.toString().replace("\\","");
}
if(state.toString().equals("SCORING")) // calculate score
{
trickStarted = false;
whoWonLast = (new Score(GameLogic.CurrentTrick, GameLogic.trumpSuit)).winner();
scores[whoWonLast-1]++;
System.out.println(whoWonLast);
for(int i = 0; i<4; i++)
CurrentTrick[i] = null;
trickState = 0;
state = state.eval("ready");
trickStarted = true;
}
for(int i = 0; i<4; i++)//
{
if(i == (int)session.getAttribute("playerId")-1)
continue;
innerObject = new JSONObject();
if(CurrentTrick[i] != null)
innerObject.put("image",CurrentTrick[i]);
else
innerObject.put("image",null);
jArray.add(innerObject);//current cards
score.add(scores[i]); // add scores
name.add(names[i]); //add names
}
/*add my card last*/
innerObject = new JSONObject();
innerObject.put("image",CurrentTrick[(int)session.getAttribute("playerId")-1]);
jArray.add(innerObject); // add my cards
score.add(scores[(int)session.getAttribute("playerId")-1]); //add scores to json
name.add(names[(int)session.getAttribute("playerId")-1]); //add names to json
mainObject = new JSONObject();
mainObject.put("cards",jArray);
mainObject.put("shouldShowHand", true);
mainObject.put("scores",score);
mainObject.put("names",name);
if(state.toString().equals("SCORING") || state.toString().equals("WAIT"))
mainObject.put("message","Waiting!");
else
mainObject.put("message",names[Integer.parseInt(state.toString().charAt(8)+"")-1]+"'s chance");// chance
mainObject.put("won",false);
return mainObject.toString().replace("\\","");
}
/***********************************************************************************/
/*returns a string array of card names in order*/
public static String[] getCards()
{
int suit = 0;
int value = 1;
String[] cards = new String[52];
for(int i = 0; i<52; i++)
{
cards[i] = "cards/" + suit + "_" + value + ".png";
if(value == 13)
{
value = 0;
suit++;
}
value++;
}
return cards;
}
/******************************************************************************/
/*Shuffle a given string array*/
public static String[] shuffle(String[] cards)
{
String tmp;
int pos;
for(int i = 0; i<cards.length; i++)
{
pos = (int )(Math.random() * 52);;
tmp = cards[i];
cards[i] = cards[pos];
cards[pos] = tmp;
}
return cards;
}
}
|
package net.grandcentrix.tray;
/**
* Created by pascalwelsch on 5/13/15.
*/
public class TrayRuntimeException extends RuntimeException {
public TrayRuntimeException() {
}
public TrayRuntimeException(final String detailMessage) {
super(detailMessage);
}
public TrayRuntimeException(final String detailMessage, Object... args) {
super(String.format(detailMessage, args));
}
public TrayRuntimeException(final String detailMessage, final Throwable throwable) {
super(detailMessage, throwable);
}
public TrayRuntimeException(final Throwable throwable) {
super(throwable);
}
}
|
package GerenciadorSensores;
import java.util.ArrayList;
public class GerenciadorSensores {
private ArrayList<ISensorTemperatura> listaSensores;
public GerenciadorSensores(int quantidadeSensoresPSC, int quantidadeSensoresXSC, int quantidadeSensoresYSC){
int idSensor = 0;
listaSensores = new ArrayList<ISensorTemperatura>();
for(int contador = 0; contador < quantidadeSensoresPSC; contador++){
idSensor++;
listaSensores.add(new SensorPSC(idSensor));
}
for(int contador = 0; contador < quantidadeSensoresXSC; contador++){
idSensor++;
listaSensores.add(new SensorXSC(idSensor));
}
for(int contador = 0; contador < quantidadeSensoresYSC; contador++){
idSensor++;
listaSensores.add(new SensorYSC(idSensor));
}
}
public DadosSensor lerInformacoesSensor(int idSensor){
DadosSensor dadosSensor = new DadosSensor();
GerenciadorTemperatura gerenciadorTemperatura = new GerenciadorTemperatura();
for (ISensorTemperatura sensor : listaSensores) {
if(sensor.getIdSensor() == idSensor){
dadosSensor.idSensor = idSensor;
dadosSensor.nomeFabricanteSensor = sensor.getNomeFabricante();
dadosSensor.temperaturaSensor = sensor.getTemperatura();
dadosSensor.corTemperatura = gerenciadorTemperatura.getCorTemperatura(sensor.getTemperatura());
return dadosSensor;
}
}
return dadosSensor;
}
public ArrayList<DadosSensor> lerInformacoesTodosSensores(){
ArrayList<DadosSensor> dadosSensores = new ArrayList<DadosSensor>();
GerenciadorTemperatura gerenciadorTemperatura = new GerenciadorTemperatura();
for (ISensorTemperatura sensor : listaSensores) {
DadosSensor infoSensor = new DadosSensor();
infoSensor.idSensor = sensor.getIdSensor();
infoSensor.nomeFabricanteSensor = sensor.getNomeFabricante();
infoSensor.temperaturaSensor = sensor.getTemperatura();
infoSensor.corTemperatura = gerenciadorTemperatura.getCorTemperatura(sensor.getTemperatura());
dadosSensores.add(infoSensor);
}
return dadosSensores;
}
}
|
package com.sinodynamic.hkgta.dao.crm;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.dto.crm.UserPreferenceSettingDto;
import com.sinodynamic.hkgta.entity.crm.UserPreferenceSetting;
import com.sinodynamic.hkgta.entity.crm.UserPreferenceSettingPK;
@Repository
public class NotificationOnOffSettingDaoImpl extends GenericDao<UserPreferenceSetting> implements NotificationOnOffSettingDao{
public List<UserPreferenceSettingDto> getNotificationOnOffSetting(Long customerId) throws Exception{
String sql = "SELECT a.user_id AS userId, a.param_id AS paramId, " +
" ups.param_value AS paramValue, ups.update_date AS updateDate " +
" FROM (select m.user_id,gp.param_id " +
" from member m, global_parameter gp " +
" where gp.param_cat = 'NOTIFICATION' AND m.customer_id = ? ) a " +
" Left join user_preference_setting ups " +
" on a.user_id = ups.user_id and a.param_id = ups.param_id";
List param = new ArrayList();
param.add(customerId);
List<UserPreferenceSettingDto> settings = this.getDtoBySql(sql, param, UserPreferenceSettingDto.class);
return settings;
}
}
|
package net.cattaka.android.learngetaccount;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorDescription;
import android.accounts.AuthenticatorException;
import android.accounts.OperationCanceledException;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
static final String ACCOUNT_TYPE = "net.cattaka.android.learnaccount";
static Handler sHandler = new Handler();
ListView mAccountsList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAccountsList = (ListView) findViewById(R.id.list_accounts);
mAccountsList.setOnItemClickListener(this);
findViewById(R.id.button_update).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AccountManager am = AccountManager.get(MainActivity.this);
AuthenticatorDescription[] ads = am.getAuthenticatorTypes();
List<Account> accounts = new ArrayList<Account>();
for (AuthenticatorDescription ad : ads) {
accounts.addAll(Arrays.asList(am.getAccountsByType(ad.type)));
}
mAccountsList.setAdapter(new ArrayAdapter<Account>(MainActivity.this, android.R.layout.simple_list_item_1, accounts));
}
});
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (adapterView == mAccountsList) {
final Account account = (Account) adapterView.getItemAtPosition(position);
final AccountManager am = AccountManager.get(this);
AccountManagerFuture<Bundle> amf = am.getAuthToken(account, account.type, null, this, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
Bundle bundle = null;
try {
bundle = future.getResult();
String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
String authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
String password = am.getPassword(account);
String userData = am.getUserData(account, "test");
Toast.makeText(MainActivity.this, String.valueOf(bundle) + ":" + password + ":" + userData, Toast.LENGTH_SHORT).show();
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
}
}
}, sHandler);
}
}
}
|
/*
* Copyright 2019 Claire Fauch
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.code.fauch.hedwig;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.InetAddress;
/**
* This class describes a TFTP packet.
*
* @author c.fauch
*
*/
public abstract class AbsPacket {
/**
* The operation code associated with the TFTP packet.
*/
private final EOperation operation;
/**
* The host name:
* - destination host name if this packet is a request.
* - source host name if this packet is response.
*/
private final InetAddress host;
/**
* The port number:
* - destination port if this packet is a request
* - source port if this packet is a response.
*/
private final int port;
/**
* Constructor.
*
* @param op the operation code (not null)
* @param host the host name (not null)
* @param port the port number
*/
AbsPacket(final EOperation op, final InetAddress host, final int port) {
this.operation = op;
this.host = host;
this.port = port;
}
/**
* @return the operation
*/
public EOperation getOperation() {
return operation;
}
/**
* @return the host
*/
public InetAddress getHost() {
return host;
}
/**
* @return the port
*/
public int getPort() {
return port;
}
/**
* Build a datagram packet from this TFTP packet.
*
* @return the corresponding datagram packet ready to be sent.
* @throws UnsupportedEncodingException
*/
public DatagramPacket build() throws UnsupportedEncodingException {
final byte[] body = encode();
return new DatagramPacket(body, body.length, this.host, this.port);
}
/**
* Encode the payload this packet.
*
* @return the encoded payload
* @throws UnsupportedEncodingException
*/
abstract byte[] encode() throws UnsupportedEncodingException;
}
|
import java.util.HashMap;
public class JewelsandStones {
/**
* Return how many characters in String S are also in J.
* Input: J = "aA", S = "aAAbbbb"
Output: 3
*/
public int numJewelsInStones(String J, String S) {
HashMap<Character, Integer> save = new HashMap<Character, Integer>();
for(int i=0; i<J.length(); i++){
save.put(J.charAt(i), 0);
}
int count = 0;
for(int j=0; j<S.length(); j++){
if(save.containsKey(S.charAt(j))) count++;
}
return count;
}
/**
* Using contains of HashMap, nothing serious here.
*/
}
|
package com.git.cloud.resmgt.common.model.po;
import java.io.Serializable;
import com.git.cloud.common.model.base.BaseBO;
public class CmHostUsernamePasswordPo extends BaseBO implements Serializable{
/**
*
*/
private static final long serialVersionUID = 7264873956767654713L;
private String id;
private String username;
private String password;
private String primaryId;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
public String getPrimaryId() {
return primaryId;
}
public void setPrimaryId(String primaryId) {
this.primaryId = primaryId;
}
}
|
package com.globant.talent.utils;
/**
* Created by drobak on 19/11/14.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
public class CSVDataSource {
Iterator<String> ite;
String[] heads;
private boolean hasNext = true;
private int lineNumber;
private String currentLine = "";
private int totalLines = 0;
/*
* New CSV Data Source Constructor
*
* @param f file CSV file to read
*
* @author: Alejandro de la Viņa <a.delavina@globant.com>
*/
/*
* public CSVDataSource (File f) throws IOException { this.lines = FileUtils.readLines(f); ite =
* this.lines.iterator();
*
* heads = ite.next().split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)"); }
*/
public CSVDataSource(InputStream is) throws IOException {
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
String line;
List<String> lines = new ArrayList<String>();
while ((line = bis.readLine()) != null) {
lines.add(line);
}
totalLines = lines.size();
ite = lines.iterator();
heads = ite.next().split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
lineNumber = 1;
}
/*
* Method that retrieves a Map with the next data structure.<p> For this implementation a map that will always bring
* the same Keys and a set of Values per line
*
* @author Alejandro de la Viņa <a.delavina@globant.com>
*/
public HashMap<String, String> getNextRecord() {
int i;
while (ite.hasNext()) {
lineNumber++;
currentLine = ite.next();
if (StringUtils.isBlank(currentLine))
continue;
String[] line = currentLine.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
if (line.length != heads.length)
throw new IllegalStateException("Invalid number of columns in CSV in line:" + lineNumber
+ " - # of columns=" + line.length);
HashMap<String, String> hm = new HashMap<String, String>();
for (i = 0; i < line.length; i++)
hm.put(heads[i], line[i].replaceAll("^\"|\"$", ""));
if (!ite.hasNext())
this.hasNext = false;
return hm;
}
return null;
}
/*
* Informs whether there are following records to be processed.
*
* @author: Alejandro de la Viņa <a.delavina@globant.com>
*/
public boolean hasNext() {
return this.hasNext;
}
public String getCurrentLine() {
return currentLine;
}
public int getTotalLines() {
return totalLines;
}
public String[] getHeads() {
return this.heads;
}
}
|
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository("userRepository")
public interface UserRepository extends CrudRepository<User, String> {
User findByEmailIdIgnoreCase(String emailId);
}
|
package com.huruilei.designpattern.observer;
/**
* @author: huruilei
* @date: 2019/10/31
* @description:
* @return
*/
public interface DisplayElement {
void display();
}
|
package com.ylz.dto;
import java.util.Date;
/**
* 用户秒杀数据传输类型
* Created by liuburu on 2017/3/6.
*/
public class UserSucessKillsDTO {
private String userPhone;
private String skName;
private Date skTime;
private int status;
public UserSucessKillsDTO() {
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getSkName() {
return skName;
}
public void setSkName(String skName) {
this.skName = skName;
}
public Date getSkTime() {
return skTime;
}
public void setSkTime(Date skTime) {
this.skTime = skTime;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
|
package com.pibs.bo.impl;
import java.util.HashMap;
import java.util.Map;
import com.pibs.bo.RptPatientHistoryBo;
import com.pibs.dao.PatientDao;
public class RptPatientHistoryBoImpl implements RptPatientHistoryBo {
private PatientDao patientDao;
public PatientDao getPatientDao() {
return patientDao;
}
public void setPatientDao(PatientDao patientDao) {
this.patientDao = patientDao;
}
@Override
public Map<String, Object> search(HashMap<String, Object> criteriaMap)
throws Exception {
// TODO Auto-generated method stub
return patientDao.search(criteriaMap);
}
@Override
public Map<String, Object> getPatientHistory(
HashMap<String, Object> criteriaMap) throws Exception {
// TODO Auto-generated method stub
return patientDao.getPatientHistory(criteriaMap);
}
}
|
package br.com.hype.medan;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.jaredrummler.materialspinner.MaterialSpinner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.regex.Pattern;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by IQBAL on 9/1/2016.
*/
public class ProfilMember extends AppCompatActivity {
Button btnSubmit;
EditText edNamaDepan, edNamaBelakang, edPonsel;
String nama, nama_depan, nama_belakang, id_sosmed, fb_gplus, language, gender, tahun_lahir, koordinat, kodeVerifikasi;
//shared prefernces untuk data order dan harga
public static final String profilPREFERENCES = "profilPreference";
SharedPreferences profilSharedpreferences;
//This is our root url
public static final String ROOT_URL = "http://api.hypemedan.id";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profil_member);
//ambil koordinat gps
profilSharedpreferences = getSharedPreferences(profilPREFERENCES, Context.MODE_PRIVATE);
String getKoordinat = profilSharedpreferences.getString("koordinat", null);
koordinat = getKoordinat;
Log.e("Koordinatnya = ", "I shouldn't be " + getKoordinat);
//fb_gplus social network name
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String socialNetworkName = preferences.getString(LoginActivity.USER_SOCIAL, null);
fb_gplus = socialNetworkName;
nama = preferences.getString(LoginActivity.PROFILE_NAME, "");
id_sosmed = preferences.getString(LoginActivity.PROFILE_EMAIL, "");
Pattern p = Pattern.compile("[ ]");
String[] result = p.split(nama);
for (int i = 0; i < result.length; i++) {
if (i == 0) {
nama_depan = result[i];
}
if (i != 0) {
if (result[i] != null) {
nama_belakang += result[i] + " ";
}
}
}
nama_belakang = nama_belakang.replace("null", "");
int count = 2016-1979;
int total = 0;
String [] tahunlahir = new String[count];
for (int i=0; count>i; i++) {
tahunlahir[i] = String.valueOf(i+1979);
total += i+1;
}
btnSubmit = (Button) findViewById(R.id.btnSubmit);
edNamaDepan = (EditText) findViewById(R.id.edNamaDepan);
edNamaBelakang = (EditText) findViewById(R.id.edNamaBelakang);
edPonsel = (EditText) findViewById(R.id.edPhone);
edNamaDepan.setText(nama_depan);
edNamaBelakang.setText(nama_belakang);
language = "Bahasa Indonesia";
gender = "Pria";
tahun_lahir = "1979";
MaterialSpinner spinner = (MaterialSpinner) findViewById(R.id.spinner);
spinner.setItems("Bahasa Indonesia", "English");
MaterialSpinner spinnerJenisKelamin = (MaterialSpinner) findViewById(R.id.spinnerJenisKelamin);
spinnerJenisKelamin.setItems("Pria", "Wanita");
MaterialSpinner spinnerTahunLahir = (MaterialSpinner) findViewById(R.id.spinnerTahunLahir);
spinnerTahunLahir.setItems(tahunlahir);
spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
Snackbar.make(view, item + " Selected", Snackbar.LENGTH_LONG).show();
language = item;
}
});
spinnerJenisKelamin.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
Snackbar.make(view, item + " Selected", Snackbar.LENGTH_LONG).show();
gender = item;
}
});
spinnerTahunLahir.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
@Override
public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
Snackbar.make(view, item + " Selected", Snackbar.LENGTH_LONG).show();
tahun_lahir = item;
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Intent intent = new Intent(ProfilMember.this, DataInterest.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//startActivity(intent);
if(edPonsel.getText().toString().trim().length() > 0) {
insertUser();
}else {
Snackbar.make(v, "Harap Isi Nomor Ponsel Anda ", Snackbar.LENGTH_LONG).show();
}
//createVerivikasi();
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void createVerivikasi() {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
String kode = String.valueOf(randomInt);
kodeVerifikasi = kode;
//Here we will handle the http request to insert user to mysql db
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
CreateVerifikasiKodeAPI api = adapter.create(CreateVerifikasiKodeAPI.class);
//Defining the method insertuser of our interface
api.createVerifikasi(
edPonsel.getText().toString(),
kodeVerifikasi,
//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
/*
Untuk proses development berikutnya
programmer harus membuat apakah ada data yang di edit atau tidak
kemudian programmer harus membedakan apakah user baru pertamakali login
atau user ingin mengubah data dirinya
#Perlu struktur looping yang lebih baik
#HailHydra
- Jika user cuman edit profil maka dapat langsung di bypass ke
Activity DataInterest
*/
Toast.makeText(ProfilMember.this, output, Toast.LENGTH_LONG).show();
String Success = "sukses";
if (output.toLowerCase().contains(Success.toLowerCase())) {
String nmrhp = edPonsel.getText().toString();
Intent i = new Intent(ProfilMember.this, VerifikasiHP.class);
i.putExtra("nomor_hp", nmrhp);
i.putExtra("kode", kodeVerifikasi);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(ProfilMember.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
private void insertUser() {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100);
String id_user = String.valueOf(randomInt);
//Here we will handle the http request to insert user to mysql db
//Here we will handle the http request to insert user to mysql db
//Creating a RestAdapter
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ROOT_URL) //Setting the Root URL
.build(); //Finally building the adapter
//Creating object for our interface
RegisterAPI api = adapter.create(RegisterAPI.class);
//Defining the method insertuser of our interface
api.insertUser(
//Passing the values by getting it from editTexts
id_user,
id_sosmed,
fb_gplus,
koordinat,
edNamaDepan.getText().toString(),
edNamaBelakang.getText().toString(),
language,
edPonsel.getText().toString(),
gender,
tahun_lahir,
"",
"",
"",
"hold",
//Creating an anonymous callback
new Callback<Response>() {
@Override
public void success(Response result, Response response) {
//On success we will read the server's output using bufferedreader
//Creating a bufferedreader object
BufferedReader reader = null;
//An string to store output from the server
String output = "";
try {
//Initializing buffered reader
reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
//Reading the output in the string
output = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
//Displaying the output as a toast
Toast.makeText(ProfilMember.this, output, Toast.LENGTH_LONG).show();
String Success = "berhasil";
if (output.toLowerCase().contains(Success.toLowerCase())) {
createVerivikasi();
}
}
@Override
public void failure(RetrofitError error) {
//If any error occured displaying the error as toast
Toast.makeText(ProfilMember.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"ProfilMember Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://br.com.hype.medan/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"ProfilMember Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://br.com.hype.medan/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
}
|
//file: Zodiac.java
//author: Victoria Cameron
//course: CMPT 220
//assignment: Project 2
//due date: May, 2017
//version: 0.4
public class Zodiac{
int month = 1;
int day = 1;
int year = 1900;
String cZodiac = new String ("ERROR");
String wZodiac = new String ("ERROR");
//Constructor
public Zodiac(){
}
//created the western zodiac string that will be printed
public void western (int month, int day){
month = month + 1;
if ((month == 12 && day >= 22 && day <= 31) || (month == 1 && day >= 1 && day <= 19))
wZodiac = (" Your Western zodiac sign is Capricorn." +
"The sign of highly intelligent and knowlegable individuals.");
else if ((month == 1 && day >= 20 && day <= 31) || (month == 2 && day >= 1 && day <= 17))
wZodiac = (" Your Western zodiac sign is Aquarius." +
"The sign of unorthodox and loyal individuals.");
else if ((month == 2 && day >= 18 && day <= 29) || (month == 3 && day >= 1 && day <= 19))
wZodiac = (" Your Western zodiac sign is Pisces." +
"The sign of trust worthy and loyal individuals.");
else if ((month == 3 && day >= 20 && day <= 31) || (month == 4 && day >= 1 && day <= 19))
wZodiac = (" Your Western zodiac sign is Aries." +
"The sign of creative, and adaptable strong willed individuals.");
else if ((month == 4 && day >= 20 && day <= 30) || (month == 5 && day >= 1 && day <= 20))
wZodiac = (" Your Western zodiac sign is Taurus." +
"The sign of strong and stuborn individuals.");
else if ((month == 5 && day >= 21 && day <= 31) || (month == 6 && day >= 1 && day <= 20))
wZodiac = (" Your Western zodiac sign is Gemini." +
"The sign of flexible and balanced individuals.");
else if ((month == 6 && day >= 21 && day <= 30) || (month == 7 && day >= 1 && day <= 22))
wZodiac = (" Your Western zodiac sign is Cancer." +
"The sign of Loving and traditional individuals.");
else if ((month == 7 && day >= 23 && day <= 31) || (month == 8 && day >= 1 && day <= 22))
wZodiac = (" Your Western zodiac sign is Leo." +
"The sign of expansive and powerful individuals.");
else if ((month == 8 && day >= 23 && day <= 31) || (month == 9 && day >= 1 && day <= 22))
wZodiac = (" Your Western zodiac sign is Virgo." +
"The sign of charming and artful individuals.");
else if ((month == 9 && day >= 23 && day <= 30) || (month == 10 && day >= 1 && day <= 22))
wZodiac = (" Your Western zodiac sign is Libra." +
"The sign of lawful and stable individuals.");
else if ((month == 10 && day >= 23 && day <= 31) || (month == 11 && day >= 1 && day <= 21))
wZodiac = (" Your Western zodiac sign is Scorpio" +
"The sign of misunderstood, and bold individuals.");
else if ((month == 11 && day >= 22 && day <= 30) || (month == 12 && day >= 1 && day <= 21))
wZodiac = (" Your Western zodiac sign is Sagittarius." +
"The sign of intense and focused individuals.");
else
wZodiac = (" Your Western zodiac sign is Illegal date");
}
//creates the chinese zodiac string to be printed.
public void chinese (int year){
switch (year % 12) {
case 0: cZodiac = ("Your Chinese zodiac is a monkey." +
"You are quick- witted, adaptable, and a very charming conversationalist.");
break;
case 1: cZodiac = ("Your Chinese zodiac is a rooster." +
"You are honest, energetic, and can sometimes be a little flampoyant.");
break;
case 2: cZodiac = ("Your Chinese zodiac is a dog." +
"You are loyal, diligent, and lively.");
break;
case 3: cZodiac = ("Your Chinese zodiac is a pig." +
"You are honorable, determined, and optimistic.");
break;
case 4: cZodiac = ("Your Chinese zodiac is a rat." +
"You are intellegent, artistic and sociable.");
break;
case 5: cZodiac = ("Your Chinese zodiac is a ox." +
"You are loyal, thorough, and reliable.");
break;
case 6: cZodiac = ("Your Chinese zodiac is a tiger." +
"You are enthusiastic, confident, and a natural leader.");
break;
case 7: cZodiac = ("Your Chinese zodiac is a rabbit." +
"You are trustworthy, diplomatic, and empethetic.");
break;
case 8: cZodiac = ("Your Chinese zodiac is a dragon." +
"You are artistic, flexible, and very imaginative.");
break;
case 9: cZodiac = ("Your Chinese zodiac is a snake." +
"You are intuitive, organized, and attentive.");
break;
case 10: cZodiac = ("Your Chinese zodiac is a horse." +
"You are aldptable, loyal, and courageous.");
break;
case 11: cZodiac = ("Your Chinese zodiac is a sheep." +
"You are tasetful, warm, and sensitive.");
}
}
}
|
package com.mytaxi.controller;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.mytaxi.controller.mapper.CarMapper;
import com.mytaxi.datatransferobject.CarDTO;
import com.mytaxi.domainobject.CarDO;
import com.mytaxi.domainobject.ManufacturerDO;
import com.mytaxi.domainvalue.OnlineStatus;
import com.mytaxi.exception.ConstraintsViolationException;
import com.mytaxi.exception.EntityNotFoundException;
import com.mytaxi.service.car.CarService;
/**
* All operations with a car will be routed by this controller.
* <p/>
* @author rajkumar
*/
@RestController
@RequestMapping("v1/cars")
public class CarController
{
private static org.slf4j.Logger LOG = LoggerFactory.getLogger(CarController.class);
private final CarService carService;
@Autowired
public CarController(final CarService carService)
{
this.carService = carService;
}
@GetMapping("/{carId}")
public CarDTO getCar(@Valid @PathVariable long carId) throws EntityNotFoundException
{
return CarMapper.makeCarDTO(carService.find(carId));
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public CarDTO createCar(@Valid @RequestBody CarDTO carDTO) throws ConstraintsViolationException, EntityNotFoundException
{
ManufacturerDO manDO = carService.findManufacturer(carDTO.getManufacturerId());
CarDO carDO = CarMapper.makeCarDO(carDTO);
carDO.setManufacturer(manDO);
return CarMapper.makeCarDTO(carService.save(carDO));
}
@PutMapping("/{carId}")
public CarDTO updateCar(@Valid @PathVariable long carId, @Valid @RequestBody CarDTO carDTO) throws ConstraintsViolationException, EntityNotFoundException
{
ManufacturerDO manDO = carService.findManufacturer(carDTO.getManufacturerId());
CarDO carDO = CarMapper.makeCarDO(carDTO);
carDO.setManufacturer(manDO);
carDO.setId(carId);
return CarMapper.makeCarDTO(carService.save(carDO));
}
@DeleteMapping("/{carId}")
public void deleteDriver(@Valid @PathVariable long carId) throws EntityNotFoundException
{
carService.delete(carId);
}
@GetMapping()
public List<CarDTO> findCars(@RequestParam OnlineStatus onlineStatus)
throws ConstraintsViolationException, EntityNotFoundException
{
return CarMapper.makeCarDTOList(carService.find(onlineStatus));
}
}
|
/**
* Created by owen on 2017/6/13.
*/
public class MultiThreadSingleton {
/**
* 多线程模式下线程安全的单例模式
*/
private MultiThreadSingleton(){}
public static volatile MultiThreadSingleton INSATCNE;
public static MultiThreadSingleton getINSATCNE() {
if (INSATCNE == null)
synchronized (MultiThreadSingleton.class) {
if (INSATCNE == null)
INSATCNE = new MultiThreadSingleton();
}
return INSATCNE;
}
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.db.model;
import java.util.Arrays;
/**
* In DB representation of basic data which is present in the most of tables.
* @author K. Benedyczak
*/
public class BaseBean
{
private Long id;
private String name;
private byte[] contents;
public BaseBean()
{
}
public BaseBean(String name, byte[] contents)
{
this.name = name;
this.contents = contents;
}
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 byte[] getContents()
{
return contents;
}
public void setContents(byte[] contents)
{
this.contents = contents;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(contents);
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BaseBean other = (BaseBean) obj;
if (!Arrays.equals(contents, other.contents))
return false;
if (id == null)
{
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null)
{
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
|
/*
* 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 latihan;
/**
*
* @author Fifi Agustina
*/
public class hurufI {
public static void main(String[] args){
int a, b;
for(a=1; a<=4; a++){
for(b=1;b<=1;b++){
System.out.print("*");
}
System.out.println();
}
}
}
|
package com.psl.training;
import java.util.Scanner;
public class CalculateIntrest {
static Scanner scan = new Scanner (System.in);
static double calInterest(int amt) {
double percent,interest;
if(amt<=1000){
percent=4;
}
else if(amt>1000&&amt<=5000){
percent=4.5;
}
else{
percent=5;
}
interest = (amt*percent)/100.0;
return interest;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter Deposit :");
int deposit = scan.nextInt();
double interest = calInterest(deposit);
System.out.println("Interest is "+interest);
}
}
|
package com.gaoshin.onsalelocal.osl.resource;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import com.gaoshin.onsalelocal.api.Offer;
import com.gaoshin.onsalelocal.api.OfferDetailsList;
import com.gaoshin.onsalelocal.osl.entity.FavouriteOfferDetailsList;
import com.gaoshin.onsalelocal.osl.entity.OfferComment;
import com.gaoshin.onsalelocal.osl.entity.OfferCommentDetailsList;
import com.gaoshin.onsalelocal.osl.entity.User;
import com.gaoshin.onsalelocal.osl.entity.UserList;
import com.sun.jersey.api.client.UniformInterfaceException;
import common.util.web.ServiceError;
public class OfferResourceTest extends OslResourceTester {
@Before
public void setup() throws Exception {
super.setup();
}
@Test
public void testOffer() throws Exception {
try {
Offer offer = createOffer();
} catch (UniformInterfaceException e) {
Assert.assertEquals(ServiceError.NoGuest.getErrorCode(), e.getResponse().getStatus());
}
User user = registerNewUser();
Offer offer = createOffer();
Assert.assertNotNull(offer.getTitle());
String imgUrl = offer.getLargeImg();
InputStream stream = new URL(imgUrl).openStream();
byte[] images = IOUtils.toByteArray(stream);
stream.close();
File file = new File("./src/test/resources/coffee.png");
Assert.assertEquals(file.length(), (long)images.length);
getBuilder("/ws/v2/offer/like/" + offer.getId()).post();
FavouriteOfferDetailsList myfavs = getBuilder("/ws/user/my-fav-offers").get(FavouriteOfferDetailsList.class);
Assert.assertEquals(1, myfavs.getItems().size());
Assert.assertEquals(offer.getTitle(), myfavs.getItems().get(0).getOffer().getTitle());
OfferDetailsList myoffers = getBuilder("/ws/user/my-offers").get(OfferDetailsList.class);
Assert.assertEquals(1, myoffers.getItems().size());
Assert.assertEquals(offer.getTitle(), myoffers.getItems().get(0).getTitle());
Offer offer2 = createOffer();
getBuilder("/ws/v2/offer/like/" + offer2.getId()).post();
myfavs = getBuilder("/ws/user/my-fav-offers").get(FavouriteOfferDetailsList.class);
Assert.assertEquals(2, myfavs.getItems().size());
myoffers = getBuilder("/ws/user/my-offers").get(OfferDetailsList.class);
Assert.assertEquals(2, myoffers.getItems().size());
UserList userList = getBuilder("/ws/v2/offer/like/users", "offerId", offer.getId()).get(UserList.class);
Assert.assertEquals(1, userList.getItems().size());
Assert.assertEquals(user.getId(), userList.getItems().get(0).getId());
// second user
getBuilder("/ws/user/logout").post();
registerNewUser();
// second user likes offer 1
getBuilder("/ws/v2/offer/like/" + offer.getId()).post();
userList = getBuilder("/ws/v2/offer/like/users", "offerId", offer.getId()).get(UserList.class);
Assert.assertEquals(2, userList.getItems().size());
OfferComment comment = new OfferComment();
String content = getCurrentTimeMillisString();
comment.setContent(content);
comment.setOfferId(offer.getId());
getBuilder("/ws/v2/offer/comment").post(comment);
OfferCommentDetailsList commentList = getBuilder("/ws/v2/offer/comments", "offerId", offer.getId()).get(OfferCommentDetailsList.class);
Assert.assertEquals(1, commentList.getItems().size());
Assert.assertEquals(comment.getContent(), commentList.getItems().get(0).getContent());
}
}
|
package com.emg.projectsmanage.dao.comm;
import java.util.List;
import java.util.Map;
import com.emg.projectsmanage.pojo.SystemModel;
public interface SystemModelDao {
List<SystemModel> getSystemsByNames(Map<String, List<String>> map);
public List<SystemModel> getAllSystems();
}
|
package com.lotbyte.servlet;
import java.io.IOException;
import java.util.Optional;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lotbyte.inter.ThrowingFunction;
import com.lotbyte.inter.ThrowingSupplier;
import com.lotbyte.po.Note;
import com.lotbyte.po.User;
import com.lotbyte.service.NoteService;
import com.lotbyte.service.TypeService;
import com.lotbyte.util.StringUtil;
import com.lotbyte.vo.ResultInfo;
import org.apache.commons.lang3.StringUtils;
/**
* 云记管理
*/
@WebServlet("/note")
public class NoteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private NoteService noteService = new NoteService();
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 得到用户行为
String action = request.getParameter("action");
Optional<String> ap = Optional.ofNullable(action);
ap.filter(a -> StringUtils.isBlank(a) || a.equals("list")).map(ThrowingFunction.functionWrapper((a) -> {
System.out.println("列表查询页面。。。");
return null;
}, Exception.class))
.orElseGet(ThrowingSupplier.supplierWrapper(() -> {
return ap.filter((a) -> a.equals("view")).map(ThrowingFunction.functionWrapper((a) -> {
noteView(request, response);
return null;
}, Exception.class))
.orElseGet(() -> {
return ap.filter((a) -> a.equals("edit")).map(ThrowingFunction.functionWrapper((a) -> {
noteEdit(request, response);
return null;
}, Exception.class))
.orElseGet(() -> {
return ap.filter((a) -> a.equals("detail")).map(ThrowingFunction.functionWrapper((a) -> {
noteDetail(request, response);
return null;
}, Exception.class))
.orElseGet(() -> {
return ap.filter((a) -> a.equals("delete")).map(ThrowingFunction.functionWrapper((a) -> {
noteDelete(request, response);
return null;
}, Exception.class));
});
});
});
}));
}
/**
* 删除云记
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void noteDelete(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 接收参数
String noteId = request.getParameter("noteId");
// 调用Service层的删除方法,返回resultInfo对象
ResultInfo resultInfo = noteService.deleteNote(noteId);
// 判断是否删除成功
if (resultInfo.getCode() == 1) { // 成功
// 重定向到首页
response.sendRedirect("main");
} else {
// 将resultInfo存到request作用域中
request.setAttribute("resultInfo", resultInfo);
// 请求转发到云记详情页面
request.getRequestDispatcher("note?action=detail¬eId=" + noteId).forward(request, response);
}
}
/**
* 查询云记详情
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void noteDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 接收参数
String noteId = request.getParameter("noteId");
// 调用Service层的方法,通过noteId主键查询note对象
Note note = noteService.findNoteById(noteId);
ResultInfo resultInfo = new ResultInfo();
if (note != null) { // 如果查询到云记对象
resultInfo.setCode(1);
resultInfo.setResult(note);
} else {
resultInfo.setCode(0);
resultInfo.setMsg("未查询到云记详情!");
}
// 存到request作用域中
request.setAttribute("resultInfo", resultInfo);
// 设置动态页面值
request.setAttribute("changePage", "note/detail.jsp");
// 请求转发到首页
request.getRequestDispatcher("main.jsp").forward(request, response);
}
/**
* 添加或者修改操作
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void noteEdit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// 接收参数
String noteId = request.getParameter("noteId");
String title = request.getParameter("title");
String content = request.getParameter("content");
String typeId = request.getParameter("typeId");
// 调用Service的方法,返回resultInfo页面
ResultInfo resultInfo = noteService.noteEdit(noteId, title, content, typeId);
// 判断是否更新成功
if (resultInfo.getCode() == 1) { // 成功
response.sendRedirect("main");
} else {
// 存request作用域
request.setAttribute("noteInfo", resultInfo.getResult());
String url = "note?action=view"; // 添加操作
if (!StringUtil.isNullOrEmpty(noteId)) { //修改操作
url += "¬eId=" + Integer.parseInt(noteId);
}
// 请求转发到添加或修改页面
request.getRequestDispatcher(url).forward(request, response);
}
}
/**
* 进入发表云记
*
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void noteView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 如果noteId不为空,说明是进入修改页面
String noteId = request.getParameter("noteId");
if (!StringUtil.isNullOrEmpty(noteId)) {
// 调用Service查询方法,通过noteId主键查询note对象
Note note = noteService.findNoteById(noteId);
// 将note对象存放request作用域中
request.setAttribute("noteInfo", note);
}
// 得到用户ID
User user = (User) request.getSession().getAttribute("user");
Integer userId = user.getUserId();
// 查询当前用户的云记类型列表
ResultInfo resultInfo = new TypeService().findNoteTypeList(userId);
// 将resultInfo、存放到request域对象中
request.setAttribute("resultInfo", resultInfo);
// 设置动态页面值
request.setAttribute("changePage", "note/edit.jsp");
// 请求转发
request.getRequestDispatcher("main.jsp").forward(request, response);
}
}
|
package com.pmm.sdgc.model;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
*
* @author dreges
*/
@Entity
@Table(name = "userlogin")
public class UserLogin implements Serializable {
//VAR
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@Column(name = "login")
private String login;
@Column(name = "cpf")
private String cpf;
@Column(name = "nome")
private String nome;
@Column(name = "senha")
private String senha;
@Column(name = "chave")
private String chave;
@Column(name = "status")
@Enumerated(EnumType.STRING)
private StatusUserLogin status;
@Column(name = "datahora")
private LocalDateTime dataHora;
@Column(name = "trocasenha")
private Boolean trocaSenha;
@Override
public String toString() {
return "UserLogin{" + "id=" + id + ", login=" + login + ", cpf=" + cpf + ", nome=" + nome + ", senha=" + senha + ", chave=" + chave + ", status=" + status + ", dataHora=" + dataHora + ", trocaSenha=" + trocaSenha + '}';
}
//SET GET
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public String getChave() {
return chave;
}
public void setChave(String chave) {
this.chave = chave;
}
public StatusUserLogin getStatus() {
return status;
}
public void setStatus(StatusUserLogin status) {
this.status = status;
}
public LocalDateTime getDataHora() {
return dataHora;
}
public void setDataHora(LocalDateTime dataHora) {
this.dataHora = dataHora;
}
public void atualizarChaveAcesso() {
try {
LocalDateTime agora = LocalDateTime.now();
String codigo = this.getCpf() + this.getLogin() + this.getNome() + agora.toString();
MessageDigest m;
m = MessageDigest.getInstance("MD5");
m.update(codigo.getBytes(), 0, codigo.length());
this.chave = new BigInteger(1, m.digest()).toString(16);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(UserLogin.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static String encrypt(String passwd) {
String sign = passwd;
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
md.update(sign.getBytes());
byte[] hash = md.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
if ((0xff & hash[i]) < 0x10) {
hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
} else {
hexString.append(Integer.toHexString(0xFF & hash[i]));
}
}
sign = hexString.toString();
} catch (Exception nsae) {
nsae.printStackTrace();
}
return sign;
}
//COMPARACAO
@Override
public int hashCode() {
int hash = 5;
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UserLogin other = (UserLogin) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
return true;
}
public static boolean isCPF(String CPF) {
// considera-se erro CPF's formados por uma sequencia de numeros iguais
if (CPF.equals("00000000000") || CPF.equals("11111111111") || CPF.equals("22222222222")
|| CPF.equals("33333333333") || CPF.equals("44444444444") || CPF.equals("55555555555")
|| CPF.equals("66666666666") || CPF.equals("77777777777") || CPF.equals("88888888888")
|| CPF.equals("99999999999") || (CPF.length() != 11))
return (false);
char dig10, dig11;
int sm, i, r, num, peso;
// "try" - protege o codigo para eventuais erros de conversao de tipo (int)
try {
// Calculo do 1o. Digito Verificador
sm = 0;
peso = 10;
for (i = 0; i < 9; i++) {
// converte o i-esimo caractere do CPF em um numero:
// por exemplo, transforma o caractere '0' no inteiro 0
// (48 eh a posicao de '0' na tabela ASCII)
num = (int) (CPF.charAt(i) - 48);
sm = sm + (num * peso);
peso = peso - 1;
}
r = 11 - (sm % 11);
if ((r == 10) || (r == 11))
dig10 = '0';
else
dig10 = (char) (r + 48); // converte no respectivo caractere numerico
// Calculo do 2o. Digito Verificador
sm = 0;
peso = 11;
for (i = 0; i < 10; i++) {
num = (int) (CPF.charAt(i) - 48);
sm = sm + (num * peso);
peso = peso - 1;
}
r = 11 - (sm % 11);
if ((r == 10) || (r == 11))
dig11 = '0';
else
dig11 = (char) (r + 48);
// Verifica se os digitos calculados conferem com os digitos informados.
if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10)))
return (true);
else
return (false);
} catch (Exception erro) {
return (false);
}
}
public Boolean getTrocaSenha() {
return trocaSenha;
}
public void setTrocaSenha(Boolean trocaSenha) {
this.trocaSenha = trocaSenha;
}
}
|
package de.trispeedys.resourceplanning;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
import de.trispeedys.resourceplanning.entity.Domain;
import de.trispeedys.resourceplanning.entity.Event;
import de.trispeedys.resourceplanning.entity.EventTemplate;
import de.trispeedys.resourceplanning.entity.Helper;
import de.trispeedys.resourceplanning.entity.Position;
import de.trispeedys.resourceplanning.entity.misc.EventState;
import de.trispeedys.resourceplanning.entity.misc.HelperState;
import de.trispeedys.resourceplanning.entity.util.EntityFactory;
import de.trispeedys.resourceplanning.repository.HelperRepository;
import de.trispeedys.resourceplanning.repository.base.RepositoryProvider;
import de.trispeedys.resourceplanning.service.AssignmentService;
import de.trispeedys.resourceplanning.service.HelperService;
import de.trispeedys.resourceplanning.test.TestDataGenerator;
import de.trispeedys.resourceplanning.util.SpeedyRoutines;
public class HelperTest
{
@Test
public void testFirstAssignment()
{
HibernateUtil.clearAll();
Helper helper =
EntityFactory.buildHelper("Stefan", "Schulz", HelperAssignmentTest.TEST_MAIL_ADDRESS,
HelperState.ACTIVE, 13, 2, 1976).saveOrUpdate();
assertEquals(true, AssignmentService.isFirstAssignment(helper.getId()));
}
/**
* A helper can have two assignments in one event!!
*/
// @Test
public void testDuplicateAssignment()
{
// clear db
HibernateUtil.clearAll();
// create helper
Helper helper =
EntityFactory.buildHelper("Diana", "Schulz", "a@b.de", HelperState.ACTIVE, 4, 3, 1973)
.saveOrUpdate();
// create domain
Domain domain = EntityFactory.buildDomain("someDomain", 1).saveOrUpdate();
// create positions
Position pos1 = EntityFactory.buildPosition("Nudelparty", 12, domain, 0, true).saveOrUpdate();
Position pos2 = EntityFactory.buildPosition("Laufstrecke", 12, domain, 1, true).saveOrUpdate();
EventTemplate template = EntityFactory.buildEventTemplate("123").saveOrUpdate();
// create event
Event tri2014 =
EntityFactory.buildEvent("Triathlon 2014", "TRI-2014", 21, 6, 2014, EventState.PLANNED,
template, null).saveOrUpdate();
// assign positions to that event
SpeedyRoutines.relatePositionsToEvent(tri2014, pos1, pos2);
// assign helper to both positions
SpeedyRoutines.assignHelperToPositions(helper, tri2014, pos1, pos2);
}
@Test
public void testSelectActiveHelperIds()
{
HibernateUtil.clearAll();
TestDataGenerator.createSimpleEvent("TRI", "TRI", 1, 1, 1980, EventState.FINISHED, EventTemplate.TEMPLATE_TRI);
assertEquals(5, HelperService.queryActiveHelperIds().size());
}
@Test
public void testCreateHelperId()
{
assertEquals("PADE29051964", SpeedyRoutines.createHelperCode(EntityFactory.buildHelper("Päge", "Denny", "a@b.de",
HelperState.ACTIVE, 29, 5, 1964)));
assertEquals("KLWI13111964", SpeedyRoutines.createHelperCode(EntityFactory.buildHelper("Klopp", "Willi", "a@b.de",
HelperState.ACTIVE, 13, 11, 1964)));
assertEquals("BELA04041971", SpeedyRoutines.createHelperCode(EntityFactory.buildHelper("Beyer", "Lars", "a@b.de",
HelperState.ACTIVE, 4, 4, 1971)));
assertEquals("LULO04041971", SpeedyRoutines.createHelperCode(EntityFactory.buildHelper("Lüge", "Lothar", "a@b.de",
HelperState.ACTIVE, 4, 4, 1971)));
assertEquals("LOLE04041971", SpeedyRoutines.createHelperCode(EntityFactory.buildHelper("Löge", "Lennart", "a@b.de",
HelperState.ACTIVE, 4, 4, 1971)));
}
@Test
public void testHelperFitsPosition()
{
HibernateUtil.clearAll();
// helper turns 16 on 15.06.2016
EntityFactory.buildHelper("Schulz", "Stefan", "a@b.de", HelperState.ACTIVE, 15, 6, 2000).saveOrUpdate();
Domain domain = EntityFactory.buildDomain("D1", 787).saveOrUpdate();
Position pos = EntityFactory.buildPosition("P1", 16, domain, 53, true).saveOrUpdate();
Helper helper = RepositoryProvider.getRepository(HelperRepository.class).findAll().get(0);
assertFalse(helper.isAssignableTo(pos, makeDate(14, 6, 2014)));
assertFalse(helper.isAssignableTo(pos, makeDate(14, 6, 2016)));
assertTrue(helper.isAssignableTo(pos, makeDate(15, 6, 2016)));
assertTrue(helper.isAssignableTo(pos, makeDate(15, 6, 2018)));
}
@Test
public void testCreateUserTestEvent()
{
HibernateUtil.clearAll();
TestDataGenerator.createUserTestEvent("Test-Duathlon 2015", "DU-TEST-2015", 1, 3, 2015, EventState.FINISHED, EventTemplate.TEMPLATE_TRI);
}
private Date makeDate(int day, int month, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, day);
cal.set(Calendar.MONTH, (month-1));
cal.set(Calendar.YEAR, year);
Date result = cal.getTime();
return result;
}
}
|
package com.yc.education.service;
import com.yc.education.model.Permissions;
import java.util.List;
/**
* @ClassName PermissionsService
* @Description TODO
* @Author QuZhangJing
* @Date 2019/3/1 11:26
* @Version 1.0
*/
public interface PermissionsService extends IService<Permissions> {
/**
* 根据父级编号和分类查询权限
* @param parent
* @return
*/
List<Permissions> selectPermissionsByParent(long parent,int types);
boolean selectPermissionsByTitleAndParent(long parent,String title);
Permissions selectPermissionsByParentAndCodes(long parent,int status);
Permissions selectPermissionsByTitleAndCodes(String title ,int status);
}
|
/** @author : Panchami Rudrakshi
* Single linked List class which has methods to
* add elements to the list,
* print the elements of a list,
* perform multiunzip on a list of elements
*/
import java.util.Iterator;
import java.util.Scanner;
public class SinglyLinkedList<T> implements Iterable<T>{
//Each node in the list is a Entry type
public class Entry<T>{
T ele;
Entry<T> next;
Entry(T x,Entry<T> nxt){
ele=x;
next=nxt;
}
}
Entry<T> header,tail;
int size;
SinglyLinkedList(){
header=new Entry<>(null,null);
tail=header;
size=0;
}
public Iterator<T> iterator(){
return new SLLIterator<>(header);
}
private class SLLIterator<E> implements Iterator<E>{
Entry<E> cursor,prev;
SLLIterator(Entry<E> head){
cursor=head;
prev=null;
}
public boolean hasNext(){
return cursor.next!=null;
}
public E next(){
prev=cursor;
cursor=cursor.next;
return cursor.ele;
}
public void remove(){
if(cursor.next!=null){
prev.next=cursor.next;
cursor=cursor.next;
}
else
System.out.println("This is the last element, cannot perform next()operstion");
}
}
//add new elements to the list
public void add(T x){
tail.next=new Entry<>(x,null);
tail=tail.next;
size++;
}
//print the elements of a list
public void printList(){
Entry<T> x=header.next;
while(x!=null){
System.out.print(x.ele+" ");
x=x.next;
}
System.out.println();
}
public void multiUnzip(int k){
// Rearrange elements of a singly linked list by chaining
// together elements that are k apart.
// Invariant:
// tail[] is an array which holds k tails where each tail points to the list of elements in its chain
// head[] holds k-1 heads which is used to connect different chains formed
// curr is current element to be processed.
// state is the loop variable which decides to which tail should the current element be added.
Entry<T>[] tail = (Entry<T>[]) new Entry[k];
Entry<T>[] head = (Entry<T>[]) new Entry[k-1];
tail[0]=header.next;
for(int i=1;i<k;i++){
tail[i]=tail[i-1].next;
head[i-1]=tail[i];
}
Entry<T> curr=tail[k-1].next;
int state=0;
while(curr!=null){
tail[state].next=curr;
tail[state]=curr;
curr=curr.next;
state=(state+1)%k;
}
//merge the different chains formed by connecting tail[0] to head[0],....tail[k-2] to head[k-2]
for(int p=0;p<k-1;p++){
tail[p].next=head[p];
}
//connect null to the last element
tail[k-1].next=null;
}
public static void main(String[] args){
SinglyLinkedList<Integer> ls=new SinglyLinkedList<>();
Scanner in = new Scanner(System.in);
System.out.println("Please enter a list of numbers: ");
String [] values = in.nextLine().split("\\s");
for (int i = 0; i < values.length; i++)
ls.add(Integer.parseInt(values[i]));
Scanner s1=new Scanner(System.in);
System.out.println("enter k value:");
int k=s1.nextInt();
System.out.println("List Initially");
ls.printList();
ls.multiUnzip(k);
System.out.println("List After Multiunzip with k="+k);
ls.printList();
}
}
/* Sample output:
List Initially
1 2 3 4 5 6 7 8 9 10
List After Multiunzip with k=3
1 4 7 10 2 5 8 3 6 9
*/
|
package com.corejava.java8;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortingBasedOnTwoPropertyOnceUsingJava8 {
public static void main(String[] args) {
//List<Employee> employeeLists=new ArrayList<>();
Employee employee1=new Employee(101, "Ashutosh", "Pandey", 3000);
Employee employee2=new Employee(103, "Vibhor", "Tripathi", 4000);
Employee employee3=new Employee(102, "Manish", "Tiwari", 8000);
Employee employee4=new Employee(104, "Subhash", "Mishra", 7000);
List<Employee> employeeLists=Arrays.asList(employee2,employee3,employee1,employee4);
System.out.println("Before Sorting Employees Lists are::");
employeeLists.forEach(System.out::println);
//Sorting using FirstName
Collections.sort(employeeLists, Comparator.comparing(Employee::getFirstName).thenComparing(Employee::getLastName));
System.out.println("After Sorting Employees Based On First And Last Name Lists are::");
employeeLists.forEach(System.out::println);
}
}
|
package com.sshfortress.controller.system;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sshfortress.common.beans.LoginFormWeb;
import com.sshfortress.common.enums.UserStatus;
import com.sshfortress.common.enums.ViewShowEnums;
import com.sshfortress.common.util.ResponseObj;
import com.sshfortress.common.util.UserTypesUtil;
import com.sshfortress.controller.websocket.MyWebSocketHandler2;
import com.sshfortress.service.helper.LoginHelper;
@Controller
@RequestMapping("/userweb/")
public class LoginWeb {
@Autowired
LoginHelper loginHelper;
@Autowired
MyWebSocketHandler2 m;
@RequestMapping(value = "login.do", produces = { "application/json;charset=UTF-8" },method = RequestMethod.POST)
@ResponseBody
public ResponseObj login(LoginFormWeb loginFormWeb, BindingResult result,
HttpServletRequest request, HttpServletResponse response) throws IOException {
ResponseObj ajaxResponseObj =new ResponseObj(ViewShowEnums.INFO_SUCCESS.getStatus(), ViewShowEnums.INFO_SUCCESS.getDetail());
if (result.hasErrors()) {
ajaxResponseObj = new ResponseObj(ViewShowEnums.ERROR_FAILED.getStatus(),
result.getAllErrors().get(0).getDefaultMessage());
return ajaxResponseObj;
}
// if(!loginFormWeb.getSrand().toUpperCase().equals(request.getSession().getAttribute("piccode").toString().toUpperCase())){
// ajaxResponseObj.setStatus(ViewShowEnums.ERROR_FAILED.getStatus());
// ajaxResponseObj.setShowMessage("输入验证码不正确");
//
// return ajaxResponseObj;
// }
// m.sendMessage("登陆成功");
return loginHelper.loginWeb(loginFormWeb.getUserName(),loginFormWeb.getPassWord(), UserTypesUtil.getWebuserTypes(), UserStatus.OPEN.getCode(),request, response,ajaxResponseObj);
}
}
|
import java.util.Arrays;
public class StringArray {
private String[] string_array;
private int size;
public StringArray() {
string_array = new String[100];
size = 0;
}
public StringArray(StringArray a) {
int space = (int) (0.1 * a.string_array.length);
this.string_array = Arrays.copyOf(a.string_array, (a.string_array.length + space));
}
public int size() {
return this.size;
}
private void incrementSize() {
this.size++;
}
private void decrementSize() {
this.size--;
}
public boolean isEmpty() {
return this.size() == 0;
}
public String get(int index) {
if (index > this.size() - 1 || index < 0) return null;
else return string_array[index];
}
public void set(int index, String s) {
if (index < 0 || index > this.size() - 1) {
//do nothing
} else putString(index, s);
}
private void enlargeArray() {
StringArray array = new StringArray(this);
this.string_array = array.string_array;
}
private void putString(int i, String s){
string_array[i] = s;
}
public void add(String s) {
if (this.size() == string_array.length) {
enlargeArray();
}
incrementSize();
putString((this.size()-1), s);
}
public void insert(int index, String s) {
if (this.size() == string_array.length) {
enlargeArray();
}
if (this.isEmpty()) {
putString(0, s);
incrementSize();
}
//if index is not out of range
else if (!(index < 0 || index > this.size() - 1)) {
incrementSize();
shiftArrayToRight(index, s);
putString(index, s);
}
}
//make space for a string to be inserted
private void shiftArrayToRight(int indexOfinsert, String s) {
for (int i = this.size() - 1; i > indexOfinsert; i--) {
string_array[i] = string_array[i - 1]; //can use putstring here
}
}
private void shiftArrayToLeft(int removed) {
System.out.println("this is removed: " + removed);
for (int i = removed; i < this.size() - 1; i++) {
string_array[i] = string_array[i + 1];
}
string_array[this.size() - 1] = null;
}
//might add feature to decrease the array
public void remove(int index) {
if (this.size() == 1) {
string_array[0] = null;
}
else if (!(index < 0 || index > this.size() - 1)) {
shiftArrayToLeft(index);
}
decrementSize();
}
private String toLowerCase(String s) {
String result;
if (!(s == null)) {
result = s.toLowerCase();
} else result = s;
return result;
}
private boolean compare(String s1, String s2) {
return (s1 == null ? s2 == null : s1.equals(s2));
}
//can be done with binary search to make more efficient
public boolean contains(String s) {
int i;
int contains = 0;
for (i = 0; i < this.size(); i++) {
if (compare(toLowerCase(s), toLowerCase(string_array[i]))) {
contains = 1;
break;
}
}
return (contains == 1);
}
public boolean containsMatchingCase(String s) {
int i;
int contains = 0;
for (i = 0; i < this.size(); i++) {
if (compare(s, string_array[i])) {
contains = 1;
break;
}
}
return (contains == 1);
}
public int indexOf(String s) {
int result = 0;
if (!this.contains(toLowerCase(s))) result = -1;
else {
for (int i = 0; i < this.size(); i++) {
if (compare(toLowerCase(s), toLowerCase(string_array[i]))) {
result = i;
break;
}
}
}
return result;
}
public int indexOfMatchingCase(String s) {
int result = 0;
if (!this.containsMatchingCase(s)) result = -1;
else {
for (int i = 0; i < this.size(); i++) {
if (compare(s, string_array[i])) {
result = i;
break;
}
}
}
return result;
}
}
|
package cn.jpush.impl.applist;
public class ImeiPackageVO {
public String imei;
public String packageStr;
public void setImei(String imei) {
this.imei = imei;
}
public void setPackageStr(String packageStr) {
this.packageStr = packageStr;
}
public String getImei() {
return imei;
}
public String getPackageStr() {
return packageStr;
}
public ImeiPackageVO(String imei, String packageStr) {
this.imei = imei;
this.packageStr = packageStr;
}
}
|
package math;
public class Game {
public static void main(String[] args) {
Warrior warrior1 = new Warrior("Warrior 1", new Point(0, 0));
Warrior warrior2 = new Warrior("Warrior 2", new Point(5, 10));
System.out.println(warrior1);
System.out.println(warrior2);
int counter = 1;
while (warrior1.distance(warrior2) > 0) {
warrior1.move(warrior2);
warrior2.move(warrior1);
counter++;
System.out.println("\n" + counter + " kör mozgások: ");
System.out.println(warrior1);
System.out.println(warrior2);
}
System.out.println("Indul a harc:");
counter = 1;
while (warrior1.isAlive() && warrior2.isAlive()) {
warrior1.attack(warrior2);
warrior2.attack(warrior1);
counter++;
System.out.println("\n" + counter + " harc kör: ");
System.out.println(warrior1);
System.out.println(warrior2);
}
System.out.println("\nA gyöztes");
System.out.println((warrior1.isAlive() ? warrior1.toString() : warrior2.toString()) + " nyerte a játékot");
}
}
|
package com.android_dev.tatenuufrn.databases;
import com.raizlabs.android.dbflow.annotation.Database;
/**
* Created by adelinosegundo on 10/13/15.
*/
@Database(name = TatenUFRNDatabase.NAME, version = TatenUFRNDatabase.VERSION)
public class TatenUFRNDatabase {
public static final String NAME = "tatenufrn_db";
public static final int VERSION = 1;
}
|
package com.uit.huydaoduc.hieu.chi.hhapp.Main.Driver.RouteRequestManager;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uit.huydaoduc.hieu.chi.hhapp.ActivitiesAuth.PhoneAuthActivity;
import com.uit.huydaoduc.hieu.chi.hhapp.Define;
import com.uit.huydaoduc.hieu.chi.hhapp.Framework.DBManager;
import com.uit.huydaoduc.hieu.chi.hhapp.Framework.ImageUtils;
import com.uit.huydaoduc.hieu.chi.hhapp.Framework.TimeUtils;
import com.uit.huydaoduc.hieu.chi.hhapp.Main.AboutApp;
import com.uit.huydaoduc.hieu.chi.hhapp.Main.AboutUser;
import com.uit.huydaoduc.hieu.chi.hhapp.Main.CurUserInfo;
import com.uit.huydaoduc.hieu.chi.hhapp.Main.Driver.PassengerRequestInfoActivity;
import com.uit.huydaoduc.hieu.chi.hhapp.Main.MainActivity;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Passenger.PassengerRequest;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Passenger.PassengerRequestState;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.RouteRequest.RouteRequest;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.RouteRequest.RouteRequestState;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip.NotifyTrip;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip.Trip;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip.TripFareInfo;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip.TripState;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip.TripType;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.User.UserInfo;
import com.uit.huydaoduc.hieu.chi.hhapp.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import cn.bingoogolapple.titlebar.BGATitleBar;
public class WaitingPassengerListActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "WaitingPassengerListAct";
BGATitleBar titleBar;
RecyclerView rycv_route_request;
List<PassengerRequest> passengerRequests;
ValueEventListener passengerRequestListener;
DatabaseReference dbRefe;
private String getCurUid() {
return FirebaseAuth.getInstance().getCurrentUser().getUid();
}
@Override
public void onBackPressed() {
if (!drawer_layout.isDrawerOpen(GravityCompat.START)) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
WaitingPassengerListActivity.this.startActivity(intent);
WaitingPassengerListActivity.this.finish();
}
else {
drawer_layout.closeDrawer(GravityCompat.START);
}
}
@Override
protected void onPause() {
super.onPause();
if(passengerRequestListener != null)
dbRefe.child(Define.DB_PASSENGER_REQUESTS)
.removeEventListener(passengerRequestListener);
}
@Override
protected void onResume() {
super.onResume();
refreshList(false);
if(passengerRequestListener != null)
dbRefe.child(Define.DB_PASSENGER_REQUESTS)
.addValueEventListener(passengerRequestListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiting_passenger_list);
// init database
dbRefe = FirebaseDatabase.getInstance().getReference();
Init();
Event();
passengerRequestListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
refreshList(true);
Log.d(TAG, "passengerRequestListener - onDataChange");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
dbRefe.child(Define.DB_PASSENGER_REQUESTS)
.addValueEventListener(passengerRequestListener);
}
private void Init() {
//view
titleBar = (BGATitleBar) findViewById(R.id.titlebar);
initNavigation();
// recycler
initRecyclerView();
passengerRequests = new ArrayList<>();
initRefeshLayout();
}
private void Event() {
titleBar.setDelegate(new BGATitleBar.Delegate() {
@Override
public void onClickLeftCtv() {
drawer_layout.openDrawer(GravityCompat.START);
}
@Override
public void onClickTitleCtv() {
}
@Override
public void onClickRightCtv() {
}
@Override
public void onClickRightSecondaryCtv() {
}
});
((TextView) findViewById(R.id.tv_tab_passenger_list)).setOnClickListener(v -> {
Intent intent = new Intent(getApplicationContext(), RouteRequestManagerActivity.class);
WaitingPassengerListActivity.this.startActivity(intent);
WaitingPassengerListActivity.this.overridePendingTransition(R.anim.anim_activity_none, R.anim.anim_activity_none);
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
NavigationResultHandle(requestCode, resultCode, data);
}
//region -------------- Notify Passenger & show Passenger Request Info ----------------
private void showPassengerInfoActivityItem(PassengerRequest passengerRequest, Trip trip) {
showLoadingPassengerRequestInfo(getResources().getString(R.string.loading_passenger_info));
DBManager.getUserById(trip.getPassengerUId(), userInfo -> {
Intent intent = new Intent(WaitingPassengerListActivity.this, PassengerRequestInfoActivity.class);
intent.putExtra("trip", trip);
intent.putExtra("userInfo", userInfo);
intent.putExtra("passengerRequest", passengerRequest);
WaitingPassengerListActivity.this.startActivity(intent);
hideLoadingPassengerRequestInfo();
});
}
MaterialDialog loadingPassengerInfo;
private void showLoadingPassengerRequestInfo(String title) {
loadingPassengerInfo = new MaterialDialog.Builder(this)
.title(title)
.content(getResources().getString(R.string.please_wait))
.progress(true, 0)
.titleColor(getResources().getColor(R.color.title_bar_background_color_blue))
.widgetColorRes(R.color.title_bar_background_color_blue)
.buttonRippleColorRes(R.color.title_bar_background_color_blue).show();
}
private void hideLoadingPassengerRequestInfo() {
if (loadingPassengerInfo != null)
loadingPassengerInfo.dismiss();
}
//endregion
//region -------------- Accepting trip ----------------
private void acceptingPassengerRequest(PassengerRequest passengerRequest) {
// Create a same RouteRequest with PassengerRequest Info
String routeRequestUId = dbRefe.child(Define.DB_ROUTE_REQUESTS).child(getCurUid()).push().getKey();
String tripUId = dbRefe.child(Define.DB_TRIPS).push().getKey();
//todo: edit this
RouteRequest routeRequest = RouteRequest.Builder
.aRouteRequest(routeRequestUId)
.setDriverUId(getCurUid())
.setRouteRequestState(RouteRequestState.FOUND_PASSENGER)
.setCarType(passengerRequest.getTripFareInfo().getCarType())
.setStartPlace(passengerRequest.getPickUpSavePlace())
.setEndPlace(passengerRequest.getDropOffSavePlace())
.setStartTime(passengerRequest.getTripFareInfo().getStartTime())
.setSummary("Summary")
.setNotifyTrip(new NotifyTrip(tripUId, true))
.setPercentDiscount(0f)
.build();
dbRefe.child(Define.DB_ROUTE_REQUESTS)
.child(getCurUid())
.child(routeRequestUId)
.setValue(routeRequest);
// up trip to server
Trip trip = Trip.Builder.aTrip(tripUId)
.setDriverUId(getCurUid())
.setTripState(TripState.ACCEPTED)
.setTripType(TripType.HH)
.setRouteRequestUId(routeRequest.getRouteRequestUId())
.build();
trip.setRouteRequestUId(passengerRequest.getPassengerRequestUId());
trip.setTripState(TripState.ACCEPTED);
trip.setPassengerUId(passengerRequest.getPassengerUId());
trip.setPassengerRequestUId(passengerRequest.getPassengerRequestUId());
dbRefe.child(Define.DB_TRIPS)
.child(trip.getTripUId())
.setValue(trip);
// notify passenger and change passenger state
passengerRequest.setPassengerRequestState(PassengerRequestState.FOUND_DRIVER);
passengerRequest.setNotifyTrip(new NotifyTrip(trip.getTripUId(), false));
dbRefe.child(Define.DB_PASSENGER_REQUESTS)
.child(passengerRequest.getPassengerUId())
.child(passengerRequest.getPassengerRequestUId())
.setValue(passengerRequest);
// show Passenger Request Info
showPassengerInfoActivityItem(passengerRequest, trip);
refreshList(false);
}
//endregion
//region -------------- Recycle View & Route request Row click event----------------
private void initRecyclerView() {
rycv_route_request = findViewById(R.id.recycler_view_requests);
LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
llm.setOrientation(LinearLayoutManager.VERTICAL);
rycv_route_request.setLayoutManager(llm);
}
private void refreshList(boolean enableLoading) {
if (enableLoading)
startLoading();
FirebaseDatabase.getInstance().getReference()
.child(Define.DB_PASSENGER_REQUESTS)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
passengerRequests.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot requestSnapshot : postSnapshot.getChildren()) {
PassengerRequest request = requestSnapshot.getValue(PassengerRequest.class);
// Only get trip that finding driver
if (request.getPassengerRequestState() == PassengerRequestState.FINDING_DRIVER
&& !request.getPassengerUId().equals(getCurUid())) {
long passTime = TimeUtils.getPassTime(request.getTripFareInfo().getStartTime())/60;
int waitMin = request.getWaitMinute();
if (passTime < waitMin) {
passengerRequests.add(request);
}
}
}
}
Collections.reverse(passengerRequests);
// Route request Row click event
WaitingPassengerRequestAdapter adapter = new WaitingPassengerRequestAdapter(passengerRequests);
adapter.setOnItemChildClickListener((adapter1, view, position) -> {
if (view.getId() == R.id.btn_accept_trip) {
if ((loadingPassengerInfo != null && !loadingPassengerInfo.isShowing()) || loadingPassengerInfo == null) {
new MaterialDialog.Builder(WaitingPassengerListActivity.this)
.title(R.string.accept_trip_title)
.content(R.string.accept_trip_content)
.positiveText(R.string.confirm)
.negativeText(R.string.cancel)
.titleColor(getResources().getColor(R.color.title_bar_background_color))
.positiveColor(getResources().getColor(R.color.title_bar_background_color))
.widgetColorRes(R.color.title_bar_background_color)
.buttonRippleColorRes(R.color.title_bar_background_color)
.onPositive((dialog, which) -> {
acceptingPassengerRequest(passengerRequests.get(position));
})
.show();
}
}
});
rycv_route_request.setAdapter(adapter);
stopLoading();
if (passengerRequests.size() == 0) {
Toast.makeText(getApplicationContext(), R.string.cant_find_request_now, Toast.LENGTH_LONG)
.show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
//endregion
//region -------------- Smart Refresh Layout ----------------
SmartRefreshLayout smartRefreshLayout;
private void initRefeshLayout() {
smartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
smartRefreshLayout.setEnableLoadMore(false);
smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(RefreshLayout refreshlayout) {
refreshList(true);
}
});
}
private void startLoading() {
smartRefreshLayout.autoRefresh();
}
private void stopLoading() {
smartRefreshLayout.finishRefresh(500);
}
//endregion
//region Navigation Bar
private static final int ABOUT_USER_REQUEST_CODE = 70;
NavigationView navigationView;
DrawerLayout drawer_layout;
View headerLayout;
private void initNavigation() {
// Navigation bar
drawer_layout = findViewById(R.id.drawer_layout);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
headerLayout = navigationView.getHeaderView(0);
updateNavUserInfo();
RelativeLayout group_Avatar = headerLayout.findViewById(R.id.group_Avatar);
group_Avatar.setOnClickListener(v -> {
Intent i = new Intent(WaitingPassengerListActivity.this, AboutUser.class);
WaitingPassengerListActivity.this.startActivityForResult(i, ABOUT_USER_REQUEST_CODE);
});
}
public void updateNavUserInfo() {
UserInfo userInfo = CurUserInfo.getInstance().getUserInfo();
ImageView iv_Avatar = headerLayout.findViewById(R.id.iv_Avatar);
TextView txtName = headerLayout.findViewById(R.id.txtName);
TextView txtPhone = headerLayout.findViewById(R.id.txtPhone);
if (userInfo.getPhoto() != null) {
iv_Avatar.setImageBitmap(ImageUtils.base64ToBitmap(userInfo.getPhoto()));
}
txtName.setText(userInfo.getName());
txtPhone.setText(userInfo.getPhoneNumber());
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(android.view.MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_about) {
Intent i = new Intent(WaitingPassengerListActivity.this, AboutApp.class);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
WaitingPassengerListActivity.this.startActivity(i);
} else if (id == R.id.nav_logout) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(WaitingPassengerListActivity.this, PhoneAuthActivity.class);
startActivity(intent);
} else if (id == R.id.nav_share) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
String shareBody = "https://play.google.com/store/apps/details?id=com.example.huydaoduc.hieu.chi.hhapp";
String shareName = "SBike";
i.putExtra(Intent.EXTRA_TEXT, shareBody);
i.putExtra(Intent.EXTRA_SUBJECT, shareName);
startActivity(Intent.createChooser(i, "Sharing"));
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void NavigationResultHandle(int requestCode, int resultCode, Intent data) {
if (requestCode == ABOUT_USER_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
updateNavUserInfo();
}
}
}
//endregion
}
|
package com.online.hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Authors_Books")
public class Books {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="Book_Id")
int bookId;
@Column(name="Author")
String author;
@Column(name="Publication")
String publication;
@Column(name="Published_Year")
String publishedYear;
public Books() {
}
public Books(int bookId, String author, String publication, String publishedYear) {
this.bookId = bookId;
this.author = author;
this.publication = publication;
this.publishedYear = publishedYear;
}
public Books(String author, String publication, String publishedYear) {
this.author = author;
this.publication = publication;
this.publishedYear = publishedYear;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublication() {
return publication;
}
public void setPublication(String publication) {
this.publication = publication;
}
public String getPublishedYear() {
return publishedYear;
}
public void setPublishedYear(String publishedYear) {
this.publishedYear = publishedYear;
}
}
|
package progkomp.zad2;
public class SudokuBoardDaoFactory {
public static FileSudokuBoardDao getFileDao(final String fileName) {
return new FileSudokuBoardDao(fileName);
}
public static JdbcSudokuBoardDao getDbDao(final String dbName, final String user, final String password) throws Exception {
return new JdbcSudokuBoardDao(dbName, user, password);
}
}
|
import java.io.*;
class Sales
{
String name;
int qty;
long mobno;
float rate;
float amt;
float tax;
float total;
byte availableQty;
public void bill() throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the item name");
name=br.readLine();
System.out.println("Enter phone no :");
mobno= Long.parseLong(br.readLine());
System.out.println("Enter the quantity purchased");
qty=Integer.parseInt(br.readLine());
System.out.println("Enter the rate of each product");
rate=Float.valueOf(br.readLine());
amt=qty*rate;
System.out.println("Enter the tax rae");
tax=Float.valueOf(br.readLine());
System.out.println("The cost of the products:"+amt);
tax=amt*tax/100;
total=amt+tax;
System.out.println("The total bill amount is:"+total);
}
public overload(){
System.out.println("Hello");
name="bag";
amt=2100;
availableQty=56;
}
public overload(String a,Byte a1){
System.out.println("Hello");
name="laptop";
amt=50000;
availableQty=6;
}
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
Sales ob1= new Sales();
ob1.bill();
}
}
|
package com.lxl.beans.vo;
import com.lxl.beans.po.DfGroupItemPo;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Created by xiaolu on 15/5/7.
*/
public class DfGroupItem {
public DfGroupItem()
{
}
public DfGroupItem(DfGroupItemPo po)
{
this.id = po.getId();
this.groupid = po.getGroupid();
this.itemid = po.getItemid();
this.type = po.getType();
this.isRequire = po.getIsRequire();
this.showData = po.getShowData();
}
private Integer id;
private Integer groupid;
private Integer itemid;
private String type;
private Integer isRequire;
private String showData;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getGroupid() {
return groupid;
}
public void setGroupid(Integer groupid) {
this.groupid = groupid;
}
public Integer getItemid() {
return itemid;
}
public void setItemid(Integer itemid) {
this.itemid = itemid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Integer getIsRequire() {
return isRequire;
}
public void setIsRequire(Integer isRequire) {
this.isRequire = isRequire;
}
public String getShowData() {
return showData;
}
public void setShowData(String showData) {
this.showData = showData;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
package com.jzl;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ClearDriver {
public static void main(String[] args) throws Exception{
Configuration configuration = new Configuration();
//获得任务对象
Job job = Job.getInstance(configuration,"jzl-clear-job");
//设置驱动类
job.setJarByClass(ClearDriver.class);
//设置map阶段的类
job.setMapperClass(ClearMapper.class);
//设置最终的输出类型
job.setOutputKeyClass(Entity.class);
job.setOutputValueClass(NullWritable.class);
//设置输入 输出路径
// FileInputFormat.addInputPath(job,new Path( args[0]));
// FileOutputFormat.setOutputPath(job,new Path( args[1]));
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
//得到long类型当前时间
long l = System.currentTimeMillis();
//new日期对象
Date date = new Date(l);
//转换提日期输出格式
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String nyr = dateFormat.format(date);
// FileInputFormat.addInputPath(job,new Path("/flume/jzl-log/"+nyr));
FileInputFormat.addInputPath(job,new Path("/flume/jzl-log/"+nyr));
String newtime2 = calendar.get(Calendar.YEAR)+"-"
+(calendar.get(Calendar.MONTH)+1)+"-"
+calendar.get(Calendar.DAY_OF_MONTH);
FileOutputFormat.setOutputPath(job,new Path( "/jzl-clear/"+newtime2));
//提交任务
boolean result = job.waitForCompletion(true);
System.out.println(result?"成功":"失败!");
}
}
|
package lawscraper.server.entities.user;
import lawscraper.server.entities.legalresearch.LegalResearch;
import lawscraper.server.entities.superclasses.EntityBase;
import lawscraper.shared.UserRole;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
/**
* Created by erik, IT Bolaget Per & Per AB
* Date: 4/16/12
* Time: 6:43 PM
*/
@Entity
@Table(name = "user")
public class User extends EntityBase {
String userName;
String password;
String eMail;
Set<LegalResearch> legalResearchList = new HashSet<LegalResearch>();
private UserRole userRole;
private LegalResearch activeLegalResearch;
public User() {
}
public User(String userName, String password) {
setUserName(userName);
setPassword(password);
}
public User(UserRole userRole) {
this.setUserRole(userRole);
}
public User(String userName, String password, UserRole userRole) {
setUserName(userName);
setPassword(password);
setUserRole(userRole);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
public Set<LegalResearch> getLegalResearch() {
return legalResearchList;
}
public void setLegalResearch(Set<LegalResearch> legalResearchs) {
this.legalResearchList = legalResearchs;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public UserRole getUserRole() {
return userRole;
}
public void setUserRole(UserRole userRole) {
this.userRole = userRole;
}
public static User AnonymousUser() {
return new User(UserRole.Anonymous);
}
public static User AnonymousAdministratorUser() {
User user = new User(UserRole.Administrator);
user.setUserName("root");
return user;
}
public boolean addLegalResearch(LegalResearch legalResearch) {
for (LegalResearch research : legalResearchList) {
if (legalResearch.getId() == research.getId()) {
return false;
}
}
getLegalResearch().add(legalResearch);
legalResearch.setUser(this);
return true;
}
public void setLegalResearchList(Set<LegalResearch> legalResearchList) {
this.legalResearchList = legalResearchList;
}
@OneToOne
public LegalResearch getActiveLegalResearch() {
return activeLegalResearch;
}
public void setActiveLegalResearch(LegalResearch activeLegalResearch) {
this.activeLegalResearch = activeLegalResearch;
}
}
|
import java.util.Scanner;
/**
* @author zhang
*/
public class Work05 {
public static void main(String[] args) {
System.out.println("请输入一个正整数:");
Scanner sc =new Scanner(System.in);
int number = sc.nextInt();
System.out.println(number+"的因子有:");
for(int i =1 ;i<=number;i++){
if(number%i==0){
System.out.print(i+",");
}
}
}
}
|
package example.android.notepad.test;
import java.util.ArrayList;
import android.test.suitebuilder.annotation.Smoke;
import android.widget.TextView;
import com.example.android.notepad.NotesList;
import com.jayway.android.robotium.remotesolo.RemoteSolo;
import com.jayway.android.robotium.solo.Solo;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class NoteListTestCase extends TestCase {
static RemoteSolo solo;
public static Test suite() {
TestSetup setup = new TestSetup(new TestSuite(NoteListTestCase.class)) {
protected void setUp( ) throws Exception {
// Typical setup()
solo = new RemoteSolo(NotesList.class);
// emulators
solo.addDevice("emulator-5554", 6000, 6000);
solo.addDevice("emulator-5556", 5003, 5003);
solo.addDevice("emulator-5558", 5004, 5004);
solo.addDevice("emulator-5560", 5007, 5007);
solo.addDevice("emulator-5562", 5008, 5008);
// v1.6 device
//solo.addDevice("HT98YLZ00039", 6565, 6565);
// v2.2 device
//solo.addDevice("HT04TP800408", 5002, 5002);
solo.connect();
}
protected void tearDown() throws Exception {
solo.disconnect();
}
};
return setup;
}
@Smoke
public void testAddNote() throws Exception {
solo.clickOnMenuItem("Add note");
solo.assertCurrentActivity("Expected NoteEditor activity", "NoteEditor"); //Assert that NoteEditor activity is opened
solo.enterText(0, "Note 1"); //Add note
solo.goBack();
solo.clickOnMenuItem("Add note"); //Clicks on menu item
solo.enterText(0, "Note 2"); //Add note
solo.goBack();
boolean expected = true;
boolean actual = solo.searchText("Note 1") && solo.searchText("Note 2");
assertEquals("Note 1 and/or Note 2 are not found", expected, actual);
}
@Smoke
public void testNoteChange() throws Exception {
solo.clickInList(2); // Clicks on a list line
solo.setActivityOrientation(Solo.LANDSCAPE); // Change orientation of activity
solo.pressMenuItem(2); // Change title
solo.enterText(0, " test");
solo.goBack();
solo.goBack();
boolean expected = true;
boolean actual = solo.searchText("(?i).*?note 1 test"); // (Regexp) case insensitive // insensitive
assertEquals("Note 1 test is not found", expected, actual);
}
@Smoke
public void testNoteRemove() throws Exception {
solo.clickOnText("(?i).*?test.*"); //(Regexp) case insensitive/text that contains "test"
solo.pressMenuItem(1); //Delete Note 1 test
boolean expected = false; //Note 1 test & Note 2 should not be found
boolean actual = solo.searchText("Note 1 test");
assertEquals("Note 1 Test is found", expected, actual); //Assert that Note 1 test is not found
solo.clickLongOnText("Note 2");
solo.clickOnText("(?i).*?Delete.*"); //Clicks on Delete in the context menu
actual = solo.searchText("Note 2");
assertEquals("Note 2 is found", expected, actual); //Assert that Note 2 is not found
}
}
|
package by.belotserkovsky.pojos;
import javax.persistence.*;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Set;
/**
* Created by K.Belotserkovsky
*/
@Entity
@Table(name = "T_USER")
public class User implements Serializable{
private Long userId;
@Size(min = 3, message = "Name must be min 3 characters long.")
private String name;
@Size(min = 3, max = 20, message = "Username must be between 3 and 20 characters long.")
private String userName;
@Size(min = 3, message = "Password must be min 3 characters long.")
private String password;
@Pattern(regexp = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}", message="Incorrect email address! example@mail.com")
private String email;
private String role;
private Set<History> calcHistory;
public User() {
}
public User(String name, String userName, String password, String email, String role) {
this.name = name;
this.userName = userName;
this.password = password;
this.email = email;
this.role = role;
}
@Id
@Column (name = "F_USER_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getUserId() {
return userId;
}
@Column(name = "F_NAME")
public String getName() {
return name;
}
@Column(name = "F_USER_NAME", unique = true)
public String getUserName() {
return userName;
}
@Column (name = "F_PASSWORD")
public String getPassword() {
return password;
}
@Column(name = "F_EMAIL")
public String getEmail() {
return email;
}
@Column (name = "F_ROLE")
public String getRole() {
return role;
}
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
public Set<History> getCalcHistory() {
return calcHistory;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setName(String name) {
this.name = name;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setRole(String role) {
this.role = role;
}
public void setCalcHistory(Set<History> calcHistory) {
this.calcHistory = calcHistory;
}
}
|
package com.kawakawaryuryu.commandlinerunnersample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class JobLauncher implements CommandLineRunner {
private final String hogeValue;
public JobLauncher(
@Value("${hoge.value}") String hogeValue) {
this.hogeValue = hogeValue;
}
@Override
public void run(String... args) {
log.info("app started");
}
public String hoge() {
log.info(hogeValue);
return hogeValue;
}
}
|
package pt.utl.ist.bw.conditionsinterpreter.conditioncompiler;
import pt.utl.ist.bw.conditionsinterpreter.conditions.Condition;
import pt.utl.ist.bw.elements.DataModelInstanceID;
import pt.utl.ist.bw.elements.DataModelURI;
import pt.utl.ist.bw.exceptions.InvalidConditionException;
/**
* Creates and returns new conditions
* @author bernardoopinto
*
*/
public class ConditionFactory {
public static boolean isConditionValid(String rawCondition) {
//TODO parse the raw condition looking for errors
return true;
}
public static Condition createCondition(DataModelURI dataModelURI, String condInString, DataModelInstanceID instanceID) throws InvalidConditionException {
return new ConditionParser(condInString, dataModelURI, instanceID).parseCondition();
}
}
|
package classstructureconstructors;
import java.util.Scanner;
public class BookMain {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Book book = new Book("Teszt Elek", "Teszt könyv");
System.out.println("Kérem adja meg a " + book.getAuthor() + " szerzőtől a " + book.getTitle() + " című könyv regisztrációs számát:");
book.register(scanner.nextLine());
System.out.println("A könyv adatai:\n" +
"Szerző: " + book.getAuthor() +
"Cím: " + book.getTitle() +
"Regisztrációs szám: " + book.getRegNumber());
}
}
|
package de.scads.gradoop_service.server.helper.constructor;
import java.util.List;
import java.util.Map;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.operators.MapOperator;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.gradoop.common.model.impl.id.GradoopId;
import org.gradoop.common.model.impl.pojo.Vertex;
import org.gradoop.flink.model.api.epgm.LogicalGraph;
import org.gradoop.flink.util.GradoopFlinkConfig;
import org.uni_leipzig.biggr.builder.GradoopOperatorConstructor;
import org.uni_leipzig.biggr.builder.InvalidSettingsException;
import de.scads.gradoop_service.server.helper.linking.LinkingHelper;
public class LinkingConstructor implements GradoopOperatorConstructor{
public static final String LINKING_CONFIG = "linkingConfig";
/**
* {@inheritDoc}
*/
@SuppressWarnings("serial")
@Override
public Object construct(final GradoopFlinkConfig gfc, final Map<String, Object> arguments, final List<Object> dependencies) throws InvalidSettingsException {
String input = (String)arguments.get(LINKING_CONFIG);
JSONObject configObject;
try {
configObject = new JSONObject(input);
String linkingConfig = configObject.getString("linkingConfig");
System.out.println(linkingConfig);
// contains ordered list of names used to refer to graphs or subworkflows in the UI
JSONArray inputsArray = configObject.getJSONArray("inputsArray");
GradoopId gradoopId = new GradoopId();
LogicalGraph inputGraph = null;
for(int i = 0; i < inputsArray.length(); i++) {
System.out.println(inputsArray.getString(i));
final int j = i;
if(i == 0) {
inputGraph = (LogicalGraph)dependencies.get(i);
MapOperator<Vertex, Vertex> graphVertexTmp = inputGraph.getVertices().map(new MapFunction<Vertex, Vertex>() {
@Override
public Vertex map(Vertex arg0) throws Exception {
// use the name of the graph, that was used in the UI and was passed to linkingConfig
arg0.setProperty("graphLabel", inputsArray.getString(j));
arg0.resetGraphIds();
arg0.addGraphId(gradoopId);
return arg0;
}
});
inputGraph = inputGraph.getConfig().getLogicalGraphFactory().fromDataSets(graphVertexTmp, inputGraph.getEdges());
}
else{
LogicalGraph nextGraph = (LogicalGraph)dependencies.get(i);
MapOperator<Vertex, Vertex> graphVertexTmp = nextGraph.getVertices().map(new MapFunction<Vertex, Vertex>() {
@Override
public Vertex map(Vertex arg0) throws Exception {
arg0.setProperty("graphLabel", inputsArray.getString(j));
arg0.resetGraphIds();
arg0.addGraphId(gradoopId);
return arg0;
}
});
nextGraph = nextGraph.getConfig().getLogicalGraphFactory().fromDataSets(graphVertexTmp, nextGraph.getEdges());
inputGraph = inputGraph.combine(nextGraph);
}
}
return LinkingHelper.runLinking(inputGraph, linkingConfig);
} catch (Exception e) {
e.printStackTrace();
}
// should not happen during normal program execution
throw new RuntimeException();
}
}
|
/*
* 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 Controlador;
import Modelo.Login;
import Modelo.Empleado;
import Vista.FrmLogin;
import Vista.FrmMenuPrincipal;
import Vista.FrmMenuPrincipalAdmin;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* @author Percy
*/
public final class ControladorLogin implements ActionListener{
protected FrmLogin vista;
protected int contador = 0;
private Timer timer;
private TimerTask tarea;
private ImageIcon rutaImagenAmostrar;
ControladorLogin(FrmLogin vista){
this.vista=vista;
DeslizarImagenes();
ActionCerrar();
InsertarLogo();
this.vista.btnInciarSesion.addActionListener(this);
}
public void ActionCerrar(){
vista.jLabel1.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent me) {
timer.cancel();
vista.dispose();
// vista.setDefaultCloseOperation();
}
@Override
public void mousePressed(MouseEvent me) {
}
@Override
public void mouseReleased(MouseEvent me) {
}
@Override
public void mouseEntered(MouseEvent me) {
}
@Override
public void mouseExited(MouseEvent me) {
}
});
}
public void DeslizarImagenes(){
int tiempo= 1*1000; //1seg
tarea= new TimerTask(){
@Override
public void run(){
// Recogemos la imagen de la ruta
rutaImagenAmostrar = new ImageIcon("src/IMAGENES/LATERAL"+(contador+1)+".jpg");
Image Imagen= rutaImagenAmostrar.getImage();
//Remidencionamos
Image ImagenModificada= Imagen.getScaledInstance(561, 530, java.awt.Image.SCALE_SMOOTH);
//Mostramos
rutaImagenAmostrar= new ImageIcon(ImagenModificada);
vista.InsertarImagen.setIcon(rutaImagenAmostrar);
if(contador<6) contador++;
else contador=0;
}
};
timer = new Timer();
timer.scheduleAtFixedRate(tarea, 0, tiempo);
}
public void InsertarLogo(){
rutaImagenAmostrar = new ImageIcon("src/IMAGENES/logopng.png");
Image Imagen= rutaImagenAmostrar.getImage();
//Remidencionamos
Image ImagenModificada= Imagen.getScaledInstance(250, 250, java.awt.Image.SCALE_SMOOTH);
//Mostramos
rutaImagenAmostrar= new ImageIcon(ImagenModificada);
vista.lblLogo.setIcon(rutaImagenAmostrar);
}
@Override
public void actionPerformed(ActionEvent ae) {
Login login= new Login(vista.txtusuario.getText(), vista.txtcontrasena.getText());
Empleado activo= login.IniciarSesion();
if(activo.getIdRecepcionista()!=0){
if(activo.getIdRol()==1){
FrmMenuPrincipalAdmin vistaMPA = new FrmMenuPrincipalAdmin();
ControladorMenuPrincipalAdmin controMPA= new ControladorMenuPrincipalAdmin(vistaMPA, activo);
vistaMPA.setVisible(true);
vista.dispose();
}
else if(activo.getIdRol()==2){
//pasar al siguiente formulario
FrmMenuPrincipal vistaMP=new FrmMenuPrincipal();
ControladorMenuPrincipal contrMP= new ControladorMenuPrincipal(vistaMP,activo.getIdRecepcionista());
vistaMP.setVisible(true);
vista.dispose();
}
}
}
}
|
package com.algaworks.algamoney.api.logic.converter;
import com.algaworks.algamoney.api.data.entity.Address;
import com.algaworks.algamoney.api.data.entity.ClientEntity;
import com.algaworks.algamoney.api.logic.bean.AddressDTO;
import com.algaworks.algamoney.api.logic.bean.ClientDTO;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
@Component
public class ClientConverter implements Converter<ClientEntity, ClientDTO> {
@Override
public ClientDTO convert(ClientEntity clientEntity) {
AddressDTO addressDTO = null;
if(clientEntity.getAddress() != null) {
addressDTO = AddressDTO
.builder()
.street(clientEntity.getAddress().getStreet())
.number(clientEntity.getAddress().getNumber())
.complement(clientEntity.getAddress().getComplement())
.cp(clientEntity.getAddress().getCp())
.city(clientEntity.getAddress().getCity())
.state(clientEntity.getAddress().getState())
.build();
}
return ClientDTO
.builder()
.id(clientEntity.getId())
.name(clientEntity.getName())
.active(clientEntity.getActive())
.address(addressDTO)
.build();
}
public ClientEntity convert(ClientDTO clientDTO) {
Address address = null;
if(clientDTO.getAddress() != null) {
address = Address
.builder()
.street(clientDTO.getAddress().getStreet())
.number(clientDTO.getAddress().getNumber())
.complement(clientDTO.getAddress().getComplement())
.cp(clientDTO.getAddress().getCp())
.city(clientDTO.getAddress().getCity())
.state(clientDTO.getAddress().getState())
.build();
}
return ClientEntity
.builder()
.id(clientDTO.getId())
.name(clientDTO.getName())
.active(clientDTO.getActive())
.address(address)
.build();
}
}
|
package com.openfarmanager.android.utils;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
public class ParcelableWrapper<T> implements Parcelable, Serializable {
public T value;
public ParcelableWrapper(T object) {
value = object;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
try {
parcel.writeValue(value);
} catch (Exception ignore) {
}
}
public final Parcelable.Creator<ParcelableWrapper> CREATOR = new Parcelable.Creator<ParcelableWrapper>() {
public ParcelableWrapper createFromParcel(Parcel source) {
try {
//noinspection unchecked
return new ParcelableWrapper<T>((T) source.readValue(ClassLoader.getSystemClassLoader()));
} catch (Exception e) {
e.printStackTrace();
}
//noinspection unchecked
return new ParcelableWrapper<T>((T) new Object());
}
public ParcelableWrapper[] newArray(int size) {
throw new UnsupportedOperationException();
}
};
}
|
package com.spring.work1;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;
//指定单元测试环境
//@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件路径
@ContextConfiguration(locations={"/spring.xml"})
public class UserDaoTest {
@Autowired
private UserDao user;
@Test
public void test() {
user.insert();
}
}//
|
package com.cxc.appcontext;
import android.content.SharedPreferences;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button mBtn_get_to;
private Button mBtn_get_sh;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
}
private void initData(){
SharedPreferences.Editor editor = AppContext.getContext().getSharedPreferences("init_data",MODE_PRIVATE).edit();
editor.putString("context",AppContext.getContext().toString());
editor.commit();
}
private void initView(){
mBtn_get_to = (Button)findViewById(R.id.btn_get_to);
mBtn_get_to.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(AppContext.getContext(),AppContext.getContext().toString(),Toast.LENGTH_SHORT).show();
}
});
mBtn_get_sh = (Button)findViewById(R.id.btn_get_sh);
mBtn_get_sh.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences pref = AppContext.getContext().getSharedPreferences("init_data",MODE_PRIVATE);
String str = pref.getString("context","null");
Toast.makeText(AppContext.getContext(),str,Toast.LENGTH_SHORT).show();
}
});
}
}
|
package com.test.base;
/**
* You are given two linked lists representing two non-negative numbers.
* The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
*
* You may assume the two numbers do not contain any leading zero, except the number 0 itself
*
* 给定两个 非负数的 链表
* 每个链表中的节点,储存一个反顺序写成的数字,将两个链表求和
* 可以假设两个链表中,没有包含0
*
* Example:
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
* Explanation: 342 + 465 = 807.
* @author YLine
*
* 2016年12月22日 下午1:21:36
*/
public interface Solution
{
public ListNode addTwoNumbers(ListNode l1, ListNode l2);
}
|
package com.roundarch.entity;
public enum QuestionCategory {
SMART,
MOTIVATED,
GETS_ALONG,
GENERAL
}
|
package org.vincent.aop.dynamicproxy;
/**
* @Package: org.vincent.aop.dynamicproxy <br/>
* @Description: 定义切面接口,切面接口定义了两个切面方法,分别在切点接口方法执行前和执行后执行 <br/>
* @author: lenovo <br/>
* @Company: PLCC <br/>
* @Copyright: Copyright (c) 2019 <br/>
* @Version: 1.0 <br/>
* @Modified By: <br/>
* @Created by lenovo on 2018/12/26 <br/>
*/
public interface IAspect {
/**
* 在切点接口方法执行之前执行
* @param args 切点参数列表
* @return
*/
boolean startTransaction(Object... args);
/**
* 在切点接口方法执行之后执行
*/
void endTrasaction();
}
|
package com.vincent.algorithm.basic.btree;
/**
* Created by chenjun on 2020-04-15 21:09
*/
class BitMapIpList implements IpService{
private IpSet ipSet = null;
public static void main(String[] args) {
BitMapIpList bitMapIpList = new BitMapIpList();
System.out.println(bitMapIpList.ipToLong("192.168.1.1"));
}
public BitMapIpList() {
ipSet = new IpSet();
ipSet.set(ipToLong("192.168.1.1")); // 1100 0000 . 1010 1000 . 0000 0001 . 0000 0001
}
@Override
public boolean isInList(String ip) {
return ipSet.get(ipToLong(ip));
}
/**
* 将字符串形式的ip地址转换为整数
* 由于int会出现负数,所以返回long
* @param ip
* @return
*/
public long ipToLong(String ip) {
long ret = 0;
String[] ipStrArr = ip.split("\\.");
for (int i = 0; i < 4; i++) {
ret <<= 8;
ret += Long.valueOf(ipStrArr[i]);
}
return ret;
}
private class IpSet {
/**
* 一共有2^32个ip地址,即需要2^32个bit来保存,
* 那么我们一共需要(2^32)/64 == 2^26个long来保存。
*/
private long[] words;
public IpSet() {
words = new long[1 << 26];
}
public void set(long bitIndex) {
int arrIndex = (int)(bitIndex >> 6);
words[arrIndex] |= (1L << bitIndex);
}
public boolean get(long bitIndex) {
int arrIndex = (int)(bitIndex >> 6);
return (words[arrIndex] & (1L << bitIndex)) != 0;
}
}
}
|
package wholesalemarket_SMP;
import jade.core.AID;
import jade.core.Agent;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import personalassistant.PersonalAssistant;
public class SMP_Market_Controller {
private InputData_Agents window;
private Intraday_Time timeWindow;
private ArrayList<AgentData> buyers = new ArrayList<AgentData>();
private ArrayList<AgentData> sellers = new ArrayList<AgentData>();
public static int START_HOUR = 0;
public static int END_HOUR = 23;
private String[] sellerNames;
private String[] buyerNames;
private boolean isSeller = false;
public SMP_Market_Controller() {
buyers = new ArrayList<>();
sellers = new ArrayList<>();
}
public void start_InputData(PersonalAssistant market, boolean _isSeller, DefaultListModel _sellerNames, DefaultListModel _buyerNames) {
isSeller = _isSeller;
sellerNames = splitAgentTotalNames(_sellerNames.toString(), _sellerNames.getSize());
buyerNames = splitAgentTotalNames(_buyerNames.toString(), _buyerNames.getSize());
InputData_Window(market);
}
public void setSellerNames(String[] sellerNames) {
this.sellerNames = sellerNames;
}
public void setBuyerNames(String[] buyerNames) {
this.buyerNames = buyerNames;
}
public String[] getSellerNames() {
return sellerNames;
}
public String[] getBuyerNames() {
return buyerNames;
}
public String[] splitAgentTotalNames(String _names, int _num) {
String aux = _names.substring(_names.indexOf("[") + 1, _names.indexOf("]"));
String[] agentNames = aux.split(", ", _num);
return agentNames;
}
public void InputData_Window(Agent market) {
window = new InputData_Agents(market, this, isSeller, START_HOUR, END_HOUR);
window.setVisible(true);
}
public void SMPCaseStudy(String file) {
window.setCaseStudydata(file);
}
public int getStartHour() {
return START_HOUR;
}
public void setStartHour(int startHour) {
this.START_HOUR = startHour;
}
public int getEndHour() {
return END_HOUR;
}
public void setEndHour(int endHour) {
this.END_HOUR = endHour;
}
// Added PersonalAssistant agent as argument for run method. João de Sá <------------------
public void casetudy(boolean with_wind, PersonalAssistant market){
PersonalAssistant PA = market;
String agent;
int id;
int k;
int g;
File f;
Workbook wb;
System.out.println("entrou no run!!");
buyers = new ArrayList<AgentData>();
sellers = new ArrayList<AgentData>();
this.sellerNames = new String[99];
this.buyerNames = new String[99];
if(with_wind){
g = 39;
}else{
g = 36;
}
k=1;
for(int i = 2; i < g; i++){
try {
ArrayList<Float> price = new ArrayList<Float>();
ArrayList<Float> power = new ArrayList<Float>();
System.out.println("" + k);
agent = "Genco"+k;
System.out.println("" + agent);
f = new File("files\\case_study.xls");
wb = Workbook.getWorkbook(f);
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
Cell c;
c = s.getCell(0,1);
sellerNames[k-1] = agent;
id = k-1;
k++;
c = s.getCell(i,1);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,2);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,3);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,4);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,5);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,6);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,7);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,8);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,9);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,10);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,11);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,12);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,13);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,14);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,15);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,16);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,17);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,18);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,19);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,20);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,21);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,22);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,23);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,24);
price.add(Float.parseFloat(c.getContents()));
i=i+1;
c = s.getCell(i,1);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,2);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,3);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,4);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,5);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,6);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,7);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,8);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,9);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,10);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,11);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,12);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,13);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,14);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,15);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,16);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,17);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,18);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,19);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,20);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,21);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,22);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,23);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(i,24);
power.add(Float.parseFloat(c.getContents()));
AgentData newData = new AgentData(agent, id, price, power);
sellers.add(newData);
} catch (IOException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
} catch (BiffException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
ArrayList<Float> price = new ArrayList<Float>();
ArrayList<Float> power = new ArrayList<Float>();
f = new File("files\\case_study.xls");
wb = Workbook.getWorkbook(f);
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
Cell c;
agent = "Retailco";
buyerNames[0] = agent;
id = 0;
c = s.getCell(0,1);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,2);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,3);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,4);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,5);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,6);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,7);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,8);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,9);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,10);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,11);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,12);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,13);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,14);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,15);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,16);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,17);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,18);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,19);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,20);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,21);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,22);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,23);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(0,24);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,1);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,2);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,3);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,4);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,5);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,6);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,7);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,8);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,9);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,10);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,11);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,12);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,13);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,14);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,15);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,16);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,17);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,18);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,19);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,20);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,21);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,22);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,23);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(1,24);
power.add(Float.parseFloat(c.getContents()));
AgentData newData = new AgentData(agent, id, price, power);
buyers.add(newData);
} catch (IOException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
} catch (BiffException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Vai para a simulation!!");
Simulation sim = new Simulation(buyers, sellers, true);
sim.run(this.START_HOUR, this.END_HOUR, this.sellerNames, this.buyerNames);
}
public void run(boolean is_Sym, PersonalAssistant market) {
PersonalAssistant PA = market;
String agent;
int id;
int k;
int g;
File f;
Workbook wb;
System.out.println("entrou no run!!");
buyers = new ArrayList<AgentData>();
sellers = new ArrayList<AgentData>();
this.sellerNames = new String[14];
this.buyerNames = new String[1];
if(is_Sym){
g = 14;
}else{
g = 13;
}
for(int i = 0; i < g; i++){
try {
ArrayList<Float> price = new ArrayList<Float>();
ArrayList<Float> power = new ArrayList<Float>();
k = i+1;
System.out.println("" + i);
System.out.println("" + k);
agent = "GenCo"+k;
System.out.println("" + agent);
f = new File("files\\"+agent+"\\Standard_strat.xls");
wb = Workbook.getWorkbook(f);
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
Cell c;
c = s.getCell(0,1);
sellerNames[i] = agent;
id = i;
c = s.getCell(3,1);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,2);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,3);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,4);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,5);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,6);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,7);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,8);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,9);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,10);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,11);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,12);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,13);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,14);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,15);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,16);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,17);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,18);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,19);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,20);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,21);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,22);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,23);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,24);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,1);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,2);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,3);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,4);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,5);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,6);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,7);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,8);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,9);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,10);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,11);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,12);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,13);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,14);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,15);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,16);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,17);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,18);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,19);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,20);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,21);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,22);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,23);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,24);
power.add(Float.parseFloat(c.getContents()));
AgentData newData = new AgentData(agent, id, price, power);
sellers.add(newData);
} catch (IOException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
} catch (BiffException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
try {
ArrayList<Float> price = new ArrayList<Float>();
ArrayList<Float> power = new ArrayList<Float>();
f = new File("files\\RetailCo1\\Standard_strat.xls");
wb = Workbook.getWorkbook(f);
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
Cell c;
c = s.getCell(0,1);
agent = c.getContents();
buyerNames[0] = agent;
id = 0;
c = s.getCell(3,1);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,2);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,3);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,4);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,5);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,6);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,7);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,8);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,9);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,10);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,11);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,12);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,13);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,14);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,15);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,16);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,17);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,18);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,19);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,20);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,21);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,22);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,23);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(3,24);
price.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,1);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,2);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,3);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,4);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,5);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,6);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,7);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,8);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,9);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,10);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,11);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,12);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,13);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,14);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,15);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,16);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,17);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,18);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,19);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,20);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,21);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,22);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,23);
power.add(Float.parseFloat(c.getContents()));
c = s.getCell(2,24);
power.add(Float.parseFloat(c.getContents()));
AgentData newData = new AgentData(agent, id, price, power);
buyers.add(newData);
} catch (IOException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
} catch (BiffException ex) {
Logger.getLogger(SMP_Market_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Vai para a simulation!!");
Simulation sim = new Simulation(buyers, sellers, true);
sim.run(this.START_HOUR, this.END_HOUR, this.sellerNames, this.buyerNames);
}
public ArrayList<AgentData> getBuyers() {
return buyers;
}
public void setBuyers(ArrayList<AgentData> buyers) {
// setBuyers was not working as intended
// Whenever setBuyers was called the content of the array list was
// rewritten, making it so there was never more than one element in the
// list
// To correct this, setBuyers simply calls the addBuyers method
// Which correctly adds a new member to the list
// To return setBuyers to the previous state simply uncomment the
// commented line of code and delete the uncommented one
// João de Sá
//this.buyers = buyers;
addBuyers(buyers);
}
public void addBuyers(ArrayList<AgentData> buyer) {
for (int i=0; i<buyer.size();i++){
this.buyers.add(buyer.get(i));
}
}
public ArrayList<AgentData> getSellers() {
return sellers;
}
public void setSellers(ArrayList<AgentData> sellers) {
// setSellers was not working as intended
// Whenever setSellers was called the content of the array list was
// rewritten, making it so there was never more than one element in th
// list
// To correct this, setSellers simply calls the addSellers method
// Which correctly adds a new member to the list
// To return setSellers to the previous state simply uncomment the
// commented line of code and delete the uncommented one
// João de Sá
//this.sellers = sellers;
addSellers(sellers);
}
public void addSellers(ArrayList<AgentData> seller) {
for (int i=0; i<seller.size();i++){
this.sellers.add(seller.get(i));
}
}
}
|
package com.company.tax.role.action;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashSet;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import com.company.core.action.BaseAction;
import com.company.core.constant.Constant;
import com.company.core.util.QueryHelper;
import com.company.tax.role.entity.CompositeRolePrivilege;
import com.company.tax.role.entity.Role;
import com.company.tax.role.entity.RolePrivilege;
import com.company.tax.role.service.RoleService;
import com.opensymphony.xwork2.ActionContext;
/**
* @author Dongfuming
* @date 2016-5-11 下午3:49:08
*/
@SuppressWarnings("serial")
public class RoleAction extends BaseAction {
@Resource
private RoleService roleService;
private Role role; // 编辑、删除
private String[] privilegeIdArray; // 新增角色的权限数组
private String searchContent; // 暂存搜索内容
public String listRole() {
transferDataOfPrivilegaMap();
transferDataOfPageResult();
return "listRole";
}
public String toAddRolePage() {
transferDataOfPrivilegaMap();
return "toAddRolePage";
}
public String addRole() {
savePrivilegeInRole();
roleService.save(role);
return "addRoleSuccess";
}
// 传权限列表、角色、该角色选中的权限过去
public String toEditRolePage() {
searchContent = role.getName();
transferDataOfPrivilegaMap();
role = roleService.findObjectById(role.getId());
transferDataOfPrivilegaIdArray();
return "toEditRolePage";
}
public String editRole() {
savePrivilegeInRole();
roleService.update(role);
return "editRoleSuccess";
}
public String deleteRole() {
searchContent = role.getName();
roleService.delete(role.getId());
return "deleteRoleSuccess";
}
public String deleteSelectedRole() {
searchContent = role.getName();
for (String roleId : selectedRow) {
roleService.delete(roleId);
}
return "deleteSelectedRoleSuccess";
}
/***************** private method *****************/
private void savePrivilegeInRole() {
HashSet<RolePrivilege> set = new HashSet<RolePrivilege>();
for(int i = 0; i < privilegeIdArray.length; i++) {
CompositeRolePrivilege composition = new CompositeRolePrivilege(role, privilegeIdArray[i]);
RolePrivilege rolePrivilege = new RolePrivilege(composition);
set.add(rolePrivilege);
}
role.setRolePrivilegeSet(set);
}
private void transferDataOfPageResult() {
try {
QueryHelper queryHelper = new QueryHelper(Role.class, "r");
if(role != null && StringUtils.isNotBlank(role.getName())) { // 搜索
role.setName(URLDecoder.decode(role.getName(), "utf-8"));
queryHelper.addCondition("r.name LIKE ?", "%" + role.getName() + "%");
}
pageResult = roleService.getPageResult(queryHelper, getPageNo(), getPageSize());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
private void transferDataOfPrivilegaMap() {
ActionContext.getContext().getContextMap().put("privilegeMap", Constant.PRIVILEGE_MAP);
}
private void transferDataOfPrivilegaIdArray() {
privilegeIdArray = new String[role.getRolePrivilegeSet().size()];
int i = 0;
for(RolePrivilege privilege: role.getRolePrivilegeSet()){
privilegeIdArray[i++] = privilege.getCompositeRolePrivilege().getPrivilege();
}
}
/***************** setter / getter *****************/
public void setRole(Role role) {
this.role = role;
}
public Role getRole() {
return role;
}
public void setPrivilegeIdArray(String[] privilegeIdArray) {
this.privilegeIdArray = privilegeIdArray;
}
public String[] getPrivilegeIdArray() {
return privilegeIdArray;
}
public void setSearchContent(String searchContent) {
this.searchContent = searchContent;
}
public String getSearchContent() {
return searchContent;
}
}
|
package com.learn.leetcode.week3;
import com.learn.leetcode.Tool;
import com.learn.leetcode.week1.SolutionRemoveElement;
import com.learn.leetcode.week1.struct.ListNode;
import org.junit.Test;
public class TestSolution {
@Test
public void testGetIntersectionNode(){
}
@Test
public void testTwoSum(){
}
@Test
public void testConvertToTitle(){
System.out.println(SolutionConvertToTitle.convertToTitle(28));
}
@Test
public void testMajorElement(){
int[] nums = {2,2,1,1,1,2,2};
System.out.println(SolutionMajorityElement.majorityElement(nums));
}
@Test
public void testTitleToNumber(){
System.out.println(SolutionTitleToNumber.titleToNumber("AA"));
}
@Test
public void testTailingZeros(){
System.out.println(SolutionTailingZeros.trailingZeroes(10));
}
@Test
public void testRotateArray(){
int[] nums = {1,2,3,4,5,6,7,8};
SolutionRotateArray.rotate1(nums,3);
Tool.printArray(nums);
}
@Test
public void testReverseBits(){
System.out.println(SolutionReverseBits.reverseBits(43261596));
}
@Test
public void testHammingWeight(){
System.out.println(SolutionHammingWeight.hammingWeight(3));
}
@Test
public void testRob(){
int[] nums = {2,7,9,3,1};
System.out.println(SolutionRob.rob(nums));
}
@Test
public void testHappy(){
System.out.println(SolutionHappy.isHappy(19));
}
@Test
public void testRemoveElement(){
ListNode head = new ListNode(1,new ListNode(1));
ListNode node = SolutionRemoveElements.removeElements(head,1);
}
}
|
package com.kevin.cloud.service.limit;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.kevin.cloud.commons.platform.dto.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
/**
* @ProjectName: vue-blog-backend
* @Package: com.kevin.cloud.service.limit
* @ClassName: ArticleControllerLimit
* @Author: kevin
* @Description: 自定义sentinle 限流
* @Date: 2020/2/4 13:10
* @Version: 1.0
*/
public class ArticleControllerLimit {
private static final Logger logger = LoggerFactory.getLogger(ArticleControllerLimit.class);
/**
* 这里的参数 除了加一个 BlockException 其它的参数必须和 对应的Controller方法中的参数一模一样,不然会失效
*
* 并且方法必须是static的,不然也无效, 不过如果不使用 blockHandlerClass 这种方式,直接声明blockHandler 则方法不是static的
* @param esId
* @param request
* @param d
* @return
*/
public static ResponseResult doLikeLimit(String esId, HttpServletRequest request, BlockException d){
logger.info("{}点赞限流触发", esId);
return new ResponseResult(ResponseResult.CodeStatus.FAIL, "操作过于频繁", d);
}
}
|
package domain;
import repository.RoleRepository;
public class RestaurantManager extends Employee implements RoleRepository {
public String getjobDescription()
{
return "Manages the restaurant, makes sure everyone is working an dbusiness is running smoothly";
}
}
|
/*******************************************************************************
* Copyright 2012 Ivan Morgillo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.dronix.android.unisannio.activity;
import org.dronix.android.unisannio.NewsIng;
import org.dronix.android.unisannio.R;
import org.dronix.android.unisannio.R.id;
import org.dronix.android.unisannio.R.layout;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.widget.TextView;
public class NewsDetailActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_newsdetail);
Bundle b = getIntent().getExtras();
NewsIng news = b.getParcelable("newsing");
TextView title = (TextView) findViewById(R.id.title);
WebView description = (WebView) findViewById(R.id.description);
TextView pubDate = (TextView) findViewById(R.id.date);
pubDate.setText(news.getPubDate());
title.setText(news.getTitle());
description.loadData(news.getDescription(), "text/html", null);
}
}
|
package top.docstorm.documentstormcommon.domain;
import java.io.Serializable;
import java.util.Date;
/**
* file_info
* @author
*/
public class FileInfo implements Serializable {
/**
* 文件id
*/
private Integer fileId;
/**
* 文件唯一key,用于在硬盘中的文件名
*/
private String fileKey;
/**
* 原文件名
*/
private String fileName;
/**
* 创建时间
*/
private Date createTime;
/**
* 最近更新时间
*/
private Date updateLastTime;
/**
* 用户id
*/
private Integer userId;
/**
* 0为转换中,1为转换完成,2为过期文件
*/
private Byte fileStatus;
/**
* 文件格式转换的类型,0为word2pdf,1为pdf2word,2为markdown2pdf,3为markdown2html,4为word translate,5为html2pdf
*/
private Byte fileFormatChangeType;
private static final long serialVersionUID = 1L;
public Integer getFileId() {
return fileId;
}
public void setFileId(Integer fileId) {
this.fileId = fileId;
}
public String getFileKey() {
return fileKey;
}
public void setFileKey(String fileKey) {
this.fileKey = fileKey;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateLastTime() {
return updateLastTime;
}
public void setUpdateLastTime(Date updateLastTime) {
this.updateLastTime = updateLastTime;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Byte getFileStatus() {
return fileStatus;
}
public void setFileStatus(Byte fileStatus) {
this.fileStatus = fileStatus;
}
public Byte getFileFormatChangeType() {
return fileFormatChangeType;
}
public void setFileFormatChangeType(Byte fileFormatChangeType) {
this.fileFormatChangeType = fileFormatChangeType;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
FileInfo other = (FileInfo) that;
return (this.getFileId() == null ? other.getFileId() == null : this.getFileId().equals(other.getFileId()))
&& (this.getFileKey() == null ? other.getFileKey() == null : this.getFileKey().equals(other.getFileKey()))
&& (this.getFileName() == null ? other.getFileName() == null : this.getFileName().equals(other.getFileName()))
&& (this.getCreateTime() == null ? other.getCreateTime() == null : this.getCreateTime().equals(other.getCreateTime()))
&& (this.getUpdateLastTime() == null ? other.getUpdateLastTime() == null : this.getUpdateLastTime().equals(other.getUpdateLastTime()))
&& (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
&& (this.getFileStatus() == null ? other.getFileStatus() == null : this.getFileStatus().equals(other.getFileStatus()))
&& (this.getFileFormatChangeType() == null ? other.getFileFormatChangeType() == null : this.getFileFormatChangeType().equals(other.getFileFormatChangeType()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getFileId() == null) ? 0 : getFileId().hashCode());
result = prime * result + ((getFileKey() == null) ? 0 : getFileKey().hashCode());
result = prime * result + ((getFileName() == null) ? 0 : getFileName().hashCode());
result = prime * result + ((getCreateTime() == null) ? 0 : getCreateTime().hashCode());
result = prime * result + ((getUpdateLastTime() == null) ? 0 : getUpdateLastTime().hashCode());
result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode());
result = prime * result + ((getFileStatus() == null) ? 0 : getFileStatus().hashCode());
result = prime * result + ((getFileFormatChangeType() == null) ? 0 : getFileFormatChangeType().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", fileId=").append(fileId);
sb.append(", fileKey=").append(fileKey);
sb.append(", fileName=").append(fileName);
sb.append(", createTime=").append(createTime);
sb.append(", updateLastTime=").append(updateLastTime);
sb.append(", userId=").append(userId);
sb.append(", fileStatus=").append(fileStatus);
sb.append(", fileFormatChangeType=").append(fileFormatChangeType);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
package additional.greedy_algorithm;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
/**
* Книга Адитья Бхаргава.Грокаем алгоритмы. Aditya Bhargava.Grokking Algorithms.2017
* Глава 8. Жадные алгоритмы(Greedy algorithms) - это приближенные алгоритмы.
* Translated by Yuriy Litvinenko from Python to Java.
* Задача. "О радиостанциях".
* Вы открываете собственную авторскую программу на радио и хотите, чтобы вас слушали во всех
* 50 штатах. Нужно решить, на каких радиостанциях должна транслироваться ваша передача. Каждая
* u станция стоит денег, поэтому количество станции необходимо свести к минимуму.
* Имеется список станций со списком штатов покрытия для каждой.
* Формализованная задача.
* Выбрать минимальное количество радиостанций, чтобы покрыть всю территории вещания.
* Решение.
* 1 . Выбрать станцию, покрывающую наибольшее количество штатов, еще не входящих в покрытие.
* Если станция будет покрывать некоторые штаты, уже входящие в покрытие, это нормально.
* 2. Повторять, пока остаются штаты, не входящие в покрытие.
*/
public class MainGA {
public static void main(String[] args) {
//инициируем список радиостанций в виде хэш таблицы с ключами - их названиями и
// хэш таблиц с их покрытиями вещания
final HashMap<String, HashSet<String>> stations = new HashMap<>();
//инициируем список требуемых штатов покрытия вещанием в виде хэш набора
// с ключами - их названиями
final HashSet<String> statesNeeded = new HashSet<>();
//наполняем список станций
stations.put("kone", new HashSet<>());
stations.put("ktwo", new HashSet<>());
stations.put("kthree", new HashSet<>());
stations.put("kfour", new HashSet<>());
stations.put("kfive", new HashSet<>());
//наполняем покрытиями список станций
stations.get("kone").add("id");
stations.get("kone").add("nv");
stations.get("kone").add("ut");
stations.get("ktwo").add("wa");
stations.get("ktwo").add("id");
stations.get("ktwo").add("mt");
stations.get("kthree").add("or");
stations.get("kthree").add("nv");
stations.get("kthree").add("ca");
stations.get("kfour").add("nv");
stations.get("kfour").add("ut");
stations.get("kfive").add("ca");
stations.get("kfive").add("az");
//наполняем хэш множество штатов требующих радио покрытия
for (Map.Entry<String, HashSet<String>> s: stations.entrySet()) {
statesNeeded.addAll(s.getValue());
}
System.out.println("statesNeeded: " + statesNeeded);
//"mt" , "wa" , "or", "id", "nv", "ut", "са", "az"
GreedyA greedyA = new GreedyA(stations, statesNeeded);
System.out.println("Best stations list: " + greedyA.getResult());
//Best stations list: [kfour, ktwo, kthree, kfive]
}
}
// stations [ " kone " ] = set ( [ " id " , " nv " , " ut " ] )
// stations [ " ktwo " ] = set ( [ " wa " , " id " , " mt " ] )
// stations [ " kthree " ] = set ( [ " or " , " nv " , " са " ] )
// stations [ " kfour " ] = set ( [ " nv " , " ut " ] )
// stations [ " kfive " ] = set ( [ " ca " , " az " ] )
// System.out.println(stations);
// {kfour=[nv, ut], ktwo=[mt, wa, id], kone=[nv, id, ut], kthree=[or, nv, ca], kfive=[az, ca]}
// stations.put("kone", new HashSet<>());
// stations.get("kfour").add("ut");
// System.out.println(stations);
// {kfour=[nv, ut], ktwo=[mt, wa, id], kone=[], kthree=[or, nv, ca], kfive=[az, ca]}
|
/*
* SuperByteMatrixSingleTranspose
*/
package net.maizegenetics.util;
/**
*
* @author Terry Casstevens
*/
public class SuperByteMatrixTranspose implements SuperByteMatrix {
private final SuperByteMatrix myMatrix;
SuperByteMatrixTranspose(int rows, int columns) {
myMatrix = SuperByteMatrixBuilder.getInstance(columns, rows);
}
@Override
public int getNumRows() {
return myMatrix.getNumColumns();
}
@Override
public int getNumColumns() {
return myMatrix.getNumRows();
}
@Override
public void set(int row, int column, byte value) {
myMatrix.set(column, row, value);
}
@Override
public void setAll(byte value) {
myMatrix.setAll(value);
}
@Override
public byte get(int row, int column) {
return myMatrix.get(column, row);
}
@Override
public byte[] getAllColumns(int row) {
return myMatrix.getAllRows(row);
}
@Override
public byte[] getColumnRange(int row, int start, int end) {
int length = end - start;
byte[] result = new byte[length];
for (int i = 0; i < length; i++) {
result[i] = get(row, i);
}
return result;
}
@Override
public byte[] getAllRows(int column) {
return myMatrix.getAllColumns(column);
}
@Override
public boolean isColumnInnerLoop() {
return false;
}
@Override
public void reorderRows(int[] newIndices) {
myMatrix.reorderColumns(newIndices);
}
@Override
public void reorderColumns(int[] newIndices) {
myMatrix.reorderRows(newIndices);
}
}
|
package stock;
import java.util.HashMap;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import com.UBQGenericLib.BaseClassLoader;
import com.UBQGenericLib.ExcelLib;
/**
* @author Deepak
*
*/
@Listeners(com.UBQGenericLib.SampleListner.class)
public class stockmovement extends BaseClassLoader {
HashMap<String, String> input = new HashMap<String, String>();
@Test
public void printStockPositionview() throws Exception {
input.put("SBU", "AJEDIRAN OLATUNJI(1003379)");
// input.put("Packdate1", " 2020-02-01 ");
if (country.equalsIgnoreCase("Nigeria")) {
Thread.sleep(2000);
home.ClickonMenutype();
Thread.sleep(2000);
}
Thread.sleep(500);
home.ClickOnMenu();
Thread.sleep(500);
home.ClickOnSubMenuItem("Stk Movement");
logger.info("Clicked on sub menu item View Stock");
Thread.sleep(1000);
stm.selectTostore(input.get("SBU"));
if(stm.getAlertmsg().equalsIgnoreCase("Would you like to load last closing stock for the same store ? ")){
stm.dismissAlert();
}
java.util.List<WebElement> Details = driver.findElements(By.xpath("//thead[@class='sectionHeader']"));
for(WebElement Details1:Details){
System.out.println(Details1.getText());
}
}
}
|
package global.model;
/**
* 教学任务类
*
* @author zzt
*
*/
public class Teachingtask {
private int tt_id;
private String cou_id;
private int cou_theoryhour;
private int cou_experimentalhours;
private int cou_practicehour;
private String t_id;
private int sy_id;
private String multimedia;
private String m_id;
private String tt_grade;
private String Practicescheduling;
private int tt_state;
public Teachingtask(int tt_id, String cou_id, int cou_theoryhour,
int cou_experimentalhours, int cou_practicehour, String t_id,
int sy_id, String multimedia, String m_id, String tt_grade,
String practicescheduling, int tt_state) {
super();
this.tt_id = tt_id;
this.cou_id = cou_id;
this.cou_theoryhour = cou_theoryhour;
this.cou_experimentalhours = cou_experimentalhours;
this.cou_practicehour = cou_practicehour;
this.t_id = t_id;
this.sy_id = sy_id;
this.multimedia = multimedia;
this.m_id = m_id;
this.tt_grade = tt_grade;
Practicescheduling = practicescheduling;
this.tt_state = tt_state;
}
public Teachingtask(String cou_id, int cou_theoryhour,
int cou_experimentalhours, int cou_practicehour, String t_id,
int sy_id, String multimedia, String m_id, String tt_grade,
String experimentalenvironment, String practicescheduling,
int tt_state) {
super();
this.cou_id = cou_id;
this.cou_theoryhour = cou_theoryhour;
this.cou_experimentalhours = cou_experimentalhours;
this.cou_practicehour = cou_practicehour;
this.t_id = t_id;
this.sy_id = sy_id;
this.multimedia = multimedia;
this.m_id = m_id;
this.tt_grade = tt_grade;
this.Practicescheduling = practicescheduling;
this.tt_state = tt_state;
}
public int getTt_id() {
return tt_id;
}
public void setTt_id(int tt_id) {
this.tt_id = tt_id;
}
public String getCou_id() {
return cou_id;
}
public void setCou_id(String cou_id) {
this.cou_id = cou_id;
}
public int getCou_theoryhour() {
return cou_theoryhour;
}
public void setCou_theoryhour(int cou_theoryhour) {
this.cou_theoryhour = cou_theoryhour;
}
public int getCou_experimentalhours() {
return cou_experimentalhours;
}
public void setCou_experimentalhours(int cou_experimentalhours) {
this.cou_experimentalhours = cou_experimentalhours;
}
public int getCou_practicehour() {
return cou_practicehour;
}
public void setCou_practicehour(int cou_practicehour) {
this.cou_practicehour = cou_practicehour;
}
public String getT_id() {
return t_id;
}
public void setT_id(String t_id) {
this.t_id = t_id;
}
public int getSy_id() {
return sy_id;
}
public void setSy_id(int sy_id) {
this.sy_id = sy_id;
}
public String getMultimedia() {
return multimedia;
}
public void setMultimedia(String multimedia) {
this.multimedia = multimedia;
}
public String getM_id() {
return m_id;
}
public void setM_id(String m_id) {
this.m_id = m_id;
}
public String getTt_grade() {
return tt_grade;
}
public void setTt_grade(String tt_grade) {
this.tt_grade = tt_grade;
}
public String getPracticescheduling() {
return Practicescheduling;
}
public void setPracticescheduling(String practicescheduling) {
Practicescheduling = practicescheduling;
}
public int getTt_state() {
return tt_state;
}
public void setTt_state(int tt_state) {
this.tt_state = tt_state;
}
}
|
/**
*
*/
package br.com.rpires.application.entity;
import java.io.Serializable;
import java.util.Date;
import br.com.rpires.application.utils.DateUtils;
/**
* @author Rodrigo Pires
*
*/
public class Corrida implements Serializable, Comparable<Corrida> {
private static final long serialVersionUID = 12434346665L;
private DateUtils dateUtils;
private Date hora;
private String codigoPiloto;
private String piloto;
private int numeroVoltas;
private Date tempoVolta;
private double velocidadeMedia;
private long tempoTotalProva;
public Corrida() {
this.dateUtils = new DateUtils();
}
public Date getHora() {
return hora;
}
public void setHora(Date hora) {
this.hora = hora;
}
public String getPiloto() {
return piloto;
}
public void setPiloto(String piloto) {
this.piloto = piloto;
}
public int getNumeroVoltas() {
return numeroVoltas;
}
public void setNumeroVoltas(int numeroVoltas) {
this.numeroVoltas = numeroVoltas;
}
public Date getTempoVolta() {
return tempoVolta;
}
public void setTempoVolta(Date tempoVolta) {
this.tempoVolta = tempoVolta;
}
public double getVelocidadeMedia() {
return velocidadeMedia;
}
public void setVelocidadeMedia(double velocidadeMedia) {
this.velocidadeMedia = velocidadeMedia;
}
public String getCodigoPiloto() {
return codigoPiloto;
}
public void setCodigoPiloto(String codigoPiloto) {
this.codigoPiloto = codigoPiloto;
}
public long getTempoTotalProva() {
return tempoTotalProva;
}
public void setTempoTotalProva(long tempoTotalProva) {
this.tempoTotalProva = tempoTotalProva;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codigoPiloto == null) ? 0 : codigoPiloto.hashCode());
result = prime * result + ((hora == null) ? 0 : hora.hashCode());
result = prime * result + numeroVoltas;
result = prime * result + ((piloto == null) ? 0 : piloto.hashCode());
result = prime * result + ((tempoVolta == null) ? 0 : tempoVolta.hashCode());
long temp;
temp = Double.doubleToLongBits(velocidadeMedia);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Corrida other = (Corrida) obj;
if (codigoPiloto == null) {
if (other.codigoPiloto != null)
return false;
} else if (!codigoPiloto.equals(other.codigoPiloto))
return false;
if (hora == null) {
if (other.hora != null)
return false;
} else if (!hora.equals(other.hora))
return false;
if (numeroVoltas != other.numeroVoltas)
return false;
if (piloto == null) {
if (other.piloto != null)
return false;
} else if (!piloto.equals(other.piloto))
return false;
if (tempoVolta == null) {
if (other.tempoVolta != null)
return false;
} else if (!tempoVolta.equals(other.tempoVolta))
return false;
if (Double.doubleToLongBits(velocidadeMedia) != Double.doubleToLongBits(other.velocidadeMedia))
return false;
return true;
}
@Override
public int compareTo(Corrida p) {
if (this.numeroVoltas > p.getNumeroVoltas()) {
return 1;
}
return -1;
}
@Override
public String toString() {
return "Código Piloto=" + codigoPiloto + ", Nome Piloto=" + piloto + ", Qtde Voltas Completadas=" + numeroVoltas + ", "
+ "Tempo Total de Prova=" + dateUtils.converMillisecondToHour(tempoTotalProva);
}
}
|
package restAPI.clients;
import feign.Param;
import feign.RequestLine;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import restAPI.models.CourseStudents;
@Component
@FeignClient("CourseStudent")
public interface ICourseStudentClient {
@RequestLine("GET /{id}")
ResponseEntity getOneById(@Param("id") Long id);
}
|
package com.tt.rendezvous;
public interface SearchFacade {
public void getRelationsByTerms(String... terms);
public void getRelationsByQuery(String query);
public void getRealtionsByTermOrderBy(String orderBy, String...terms);
public void getRelationsByQueryOrderBy(String orderBy, String...terms);
}
|
package test;
import fello.controller.MemberManager;
import java.sql.SQLException;
public class test01 {
public static void main(String[] args) throws SQLException {
MemberManager memberManager = new MemberManager();
// memberManager.update();
}
}
|
package parameters;
import java.util.HashSet;
import java.util.Set;
/**
* Created by daniel on 8/12/14.
*/
public class RequestedTransfer {
int node_origin;
int node_destination;
int time_completion;
int data_amount;
Set<Rectangle> A;
public RequestedTransfer(int node_origin, int node_destination, int time_completion, int data_amount) {
this.node_origin = node_origin;
this.node_destination = node_destination;
this.time_completion = time_completion;
this.data_amount = data_amount;
}
public int getNode_origin() {
return node_origin;
}
public void setNode_origin(int node_origin) {
this.node_origin = node_origin;
}
public int getNode_destination() {
return node_destination;
}
public void setNode_destination(int node_destination) {
this.node_destination = node_destination;
}
public int getTime_completion() {
return time_completion;
}
public int getData_amount() {
return data_amount;
}
public Set<Rectangle> getA() {
return A;
}
public void computeRectanglesSet (int maxFreqSlices) {
A = getRectangles(0,time_completion,maxFreqSlices);
}
HashSet<Rectangle> getRectangles(int tStart, int tEnd, int maxFreqSlices){
HashSet<Rectangle>resultList =new HashSet<Rectangle>(maxFreqSlices*time_completion);
for (int time=1; time<=time_completion; time++){
for(int lowSlice=0;lowSlice<maxFreqSlices;lowSlice++){
for(int maxSlice=lowSlice; maxSlice<maxFreqSlices; maxSlice++){
Rectangle rectangle=new Rectangle(0,time,lowSlice,maxSlice);
if (rectangle.getArea()>data_amount) {
resultList.add(rectangle);
}
}
}
}
return resultList;
}
}
|
package jp.ac.hal.Model;
//個人注文クラス
public class IndividualOrder extends Order {
private String name; //氏名
private String phonetic; //フリガナ
private String postalCode; //郵便番号
private String address; //住所
private String phoneNumber; //電話番号
private String mailAddress; //メールアドレス
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhonetic() {
return phonetic;
}
public void setPhonetic(String phonetic) {
this.phonetic = phonetic;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getMailAddress() {
return mailAddress;
}
public void setMailAddress(String mailAddress) {
this.mailAddress = mailAddress;
}
}
|
import java.io.Serializable;
public class User implements Serializable {
transient String username;
String email;
transient int password;
public User(String username, String email, int password) {
this.username = username;
this.password = password;
this.email = email;
}
}
|
package se.kth.eh2745.moritzv.assigment1.exception;
public class InsertDataFailedException extends MysqlException {
private static final long serialVersionUID = 3588299366456202475L;
public InsertDataFailedException(Throwable cause){
super(cause);
}
}
|
package com.danielvizzini.util;
import java.lang.reflect.Constructor;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Kitchen sink of static methods with iterables as parameters to be used in multiple projects, kept in one place to avoid code drift.
*/
public class MiscUtil {
//hide default constructor
private MiscUtil() {}
/**
* Given a string, returns the MD5 hash
*
* @param s String whose MD5 hash value is required
* @return An MD5 hash string
* @throws java.security.NoSuchAlgorithmException if the MD5 hash algorithm is not found
*/
public static String getMd5(String s) throws NoSuchAlgorithmException {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update( s.getBytes(), 0, s.length() );
String md5 = new BigInteger(1, m.digest()).toString(16);
return md5;
}
/**
* Return the ordinal for an integer, e.g. getOrdinalFor(1) returns 1st
* @param value cardinal integer for which an ordinal will be returned
* @return ordinal of cardinal integer
*/
public static String getOrdinalFor(int value) {
int hundredRemainder = value % 100;
int tenRemainder = value % 10;
if (hundredRemainder - tenRemainder == 10) {
return value + "th";
}
switch (tenRemainder) {
case 1:
return value + "st";
case 2:
return value + "nd";
case 3:
return value + "rd";
default:
return value + "th";
}
}
/**
* Calculates distance in meters between two geographical points
* @param lat1 latitude of first point
* @param lon1 longitude of first point
* @param lat2 latitude of second point
* @param lon2 longitude of second point
* @return great circle distance between the two specified points
*/
public static double getDistanceFromLatLon(double lat1, double lon1, double lat2, double lon2) {
//validate
if (lat1 > 90 || lat1 < -90 || lat2 > 90 || lat2 < -90 || lon1 > 180 || lon1 < -180 || lon2 > 180 || lon2 < -180) {
throw new IllegalArgumentException("Cannot find distance between invalid coordinate(s)");
}
int R = 6371000; // meters
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) *
Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (R * c);
}
/**
* Returns the constructor of a class given its parameters. Used instead of getConstructor because of that will not handle parameters with generics.
* @param klass the class for the constructor sought
* @param parameterTypes parameter types of constructor returned
* @return constructor that constructs and instance of klass using the parameters specified
* @throws NoSuchMethodException if the constructor specified does not exist
*/
public static <T> Constructor<T> findConstructor(Class<T> klass, Class<?>... parameterTypes) throws NoSuchMethodException {
@SuppressWarnings("unchecked")
Constructor<T>[] constructors = (Constructor<T>[]) klass.getConstructors();
for (Constructor<T> constructor : constructors) {
Class<?>[] thisConstructorParameterTypes = constructor.getParameterTypes();
if (thisConstructorParameterTypes.length == parameterTypes.length) {
boolean match = true;
for (int i = 0; i < thisConstructorParameterTypes.length && match; i++) {
if (!thisConstructorParameterTypes[i].isAssignableFrom(parameterTypes[i]))
match = false;
}
if (match)
return constructor;
}
}
throw new NoSuchMethodException();
}
/**
* @param string that may or may not be parsable to double
* @return true if string parses to double, false otherwise
*/
public static boolean isDouble(String string) {
try {
Double.valueOf(string);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Returns an enum instance given the enum class and the name of the instance. Similar to Enum.valueOf() but case insensitive
* @param enumeration Enum class (e.g. DaysOfWeek.class)
* @param name name of enum instance, regardless of case (e.g. "MoNdAy")
* @return the enum instance (e.g. MONDAY)
*/
public static <T extends Enum<T>> T valueOfIgnoreCase(Class<T> enumeration, String name) {
for(T enumValue : enumeration.getEnumConstants()) {
if(enumValue.name().equalsIgnoreCase(name)) {
return enumValue;
}
}
throw new IllegalArgumentException("There is no value with name '" + name + "' in Enum " + enumeration.getClass().getName());
}
/**
* Calculates the greatest common divisor of an array using Euclid's method. Thank you Euclid.
* @param integers Iterable of integers, can be negative or positive and in any order
* @return the greatest common divisor of all elements of the array
* <p>
* If the array is all zeros the greatest common divisor will be zero, and not the more mathematically correct infinity
*/
public static int greatestCommonDivisor(Iterable<Integer> integers) {
int result = integers.iterator().next();
for(int integer : integers){
result = greatestCommonDivisor(result, integer);
}
return result;
}
/**
* Calculates the greatest common divisor of an array using Euclid's method. Thank you Euclid.
* @param integers array of integers, can be negative or positive and in any order
* @return the greatest common divisor of all elements of the array
* <p>
* If the array is all zeros the greatest common divisor will be zero, and not the more mathematically correct infinity
*/
public static int greatestCommonDivisor(int[] integers) {
int result = integers[0];
for(int integer : integers){
result = greatestCommonDivisor(result, integer);
}
return result;
}
/**
* Calculates the greatest common divisor using Euclid's method
* @param firstInteger any integer, can be negative or positive, greater or smaller than second
* @param secondInteger any integer, can be negative or positive, greater or smaller than first
* @return the greatest common divisor of firstInteger and secondInteger
* <p>
* If both parameters are zero the greatest common divisor will be zero, and not the more mathematically correct infinity
*/
public static int greatestCommonDivisor(int firstInteger, int secondInteger) {
//convert to positive numbers
firstInteger = Math.abs(firstInteger);
secondInteger = Math.abs(secondInteger);
//find biggest and smallest absolute values
int biggestPositiveInteger = Math.max(firstInteger, secondInteger);
int smallestPositiveInteger = Math.min(firstInteger, secondInteger);
//use Euclid's method (thank you Euclid)
return greatestCommonDivisorInternal(biggestPositiveInteger, smallestPositiveInteger);
}
/**
* Internal method to be used once parameters are cleaned.
*/
private static int greatestCommonDivisorInternal(int biggestPositiveInteger, int smallestPositiveInteger) {
//use Euclid's algorithm (thank you Euclid)
if (smallestPositiveInteger == 0) {
return biggestPositiveInteger;
}
return greatestCommonDivisorInternal(smallestPositiveInteger, biggestPositiveInteger % smallestPositiveInteger);
}
/**
* @param integer the integer that one is applying the modulus operator to
* @param modulus the base of the modulus operator
* @return integer % modulus, set to be positive<br/>
* Examples:<br/>
* modPositive(17, 5) == 2//true<br/>
* modPositive(17, -5) == 2//true<br/>
* modPositive(-17, 5) == 3//true<br/>
* modPositive(-17, -5) == 3//true<br/>
*/
public static int modPositive(int integer, int modulus) {
int mod = integer % modulus;
return mod + (mod < 0 ? Math.abs(modulus) : 0);
}
/**
* Mutates list by removing duplicates and maintains order.
* @param list to be mutated
*/
public static <T> void removeDuplicates(Collection<T> list) {
Set<T> set = new HashSet<T>();
List<T> newList = new ArrayList<T>();
for (Iterator<T> iter = list.iterator(); iter.hasNext();) {
T element = iter.next();
if (set.add(element)) {
newList.add(element);
}
}
list.clear();
list.addAll(newList);
}
/**
* Trims trailing zeros from string that represents a number
* @param numberString a string representing a number (e.g. "123.000")
* @return that string without its trailing zeros (e.g. "123")
*/
public static String trimTrailingZeros(String numberString) {
if (numberString.contains("E")) return numberString;
if (!numberString.contains(".")) return numberString;
int length = numberString.length();
while (numberString.charAt(length - 1) == '0') {
length--;
}
if (numberString.charAt(length - 1) == '.') length--;
return numberString.substring(0,length);
}
/**
* Converts number to String and trims it of trailing zeros
* @param number Number object to be trimmed (e.g. Double.valueOf(123))
* @return that string without its trailing zeros (e.g. "123")
*/
public static String trimTrailingZeros(Number number) {
return trimTrailingZeros(number.toString());
}
/**
* @param stringList list of strings
* @return longest string. If iterable is empty, "" is returned. If two strings are equally long, the first is returned.
*/
public static String getLongestString(Iterable<String> stringList) {
String forReturn = "";
for (String string : stringList) {
if (string.length() > forReturn.length()) {
forReturn = string;
}
}
return forReturn;
}
/**
* Capitalizes first letter of String
* @param string string to be capitalized
* @return Capitalized String. If string is "", "" is returned.
*/
public static String capitalize(String string) {
if (string.length() <= 1) return string.toUpperCase();
return string.substring(0,1).toUpperCase() + string.substring(1);
}
}
|
/*8. Implement a JAVA program to find the odd numbers between 0-100.*/
class OddNumbers{
public static void main(String args[]){
int i;
System.out.println("Odd numbers between 0-100 are: " );
for(i=0;i<=100;i++)
{
if(i%2!=0)
System.out.println(i);
}
}
}
|
/*
* Copyright (c) 2009, Julian Gosnell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dada.core;
import java.util.Collection;
import junit.framework.TestCase;
public class ViewTestCase extends TestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
Creator<BooleanDatum> booleanDatumCreator = new Creator<BooleanDatum>(){
@Override
public BooleanDatum create(Object... args) {
return new BooleanDatum((Integer)args[0], (Boolean)args[1]);
}
};
datumMetadata = new IntrospectiveMetadata<Integer, BooleanDatum>(BooleanDatum.class, booleanDatumCreator, "Id");
Creator<StringDatum> stringDatumCreator = new Creator<StringDatum>(){
@Override
public StringDatum create(Object... args) {
return new StringDatum((Integer)args[0], (Boolean)args[1], (String)args[2]);
}
};
stringDatumMetadata = new IntrospectiveMetadata<Integer, StringDatum>(StringDatum.class, stringDatumCreator, "Id");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
static class BooleanDatum extends IntegerDatum {
final boolean flag;
BooleanDatum(int id, boolean flag) {
super(id, 0);
this.flag = flag;
}
public boolean getFlag() {
return flag;
}
};
protected Metadata<Integer, BooleanDatum> datumMetadata;
protected Metadata<Integer, StringDatum> stringDatumMetadata;
static class Counter<V> implements View<V> {
int count;
@Override
public void update(Collection<Update<V>> insertions, Collection<Update<V>> alterations, Collection<Update<V>> deletions) {
count += insertions.size();
}
};
public void testEmpty() {
}
// TODO: split Query into Filter/Transformer/Strategy...
// TODO: how do we support modification/removal using this architecture ?
// TODO: modification will require exlusion/versioning
// TODO: removal will require a deleted flag/status
}
|
package utilities;
public final class StringUtils {
private StringUtils() {}
static String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String alphabet2 = alphabet.toLowerCase();
public static Boolean isPalindrome(String s) {
int n = s.length();
for (int i = 0; i < (n / 2); ++i) {
if (s.charAt(i) != s.charAt(n - i - 1)) {
return false;
}
}
return true;
}
public static String encodeCesar(String s, int delta) {
String result = "";
// bring delta to positive value
while (delta < 0) {
delta += 26;
}
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
char startLetter = 'A';
result += (char) ((c - startLetter + delta) % 26 + startLetter);
}
return result;
}
public static String decodeCesar(String s, int delta) {
return encodeCesar(s, -delta);
}
public static String capitalize(String name) {
return name.substring(0,1).toUpperCase() + name.substring(1);
}
}
|
package ar.edu.unlam.pb2.ea1;
public class Hipertenso extends Paciente{
private Integer prensionMinima;
private Integer presionMaxima;
@Override
public void agregarDietaDiaria(DietaDiaria dieta) {
// Control de dieta para un Hipertenso
}
}
|
package com.slack.bot.services;
import me.ramswaroop.jbot.core.slack.Bot;
import me.ramswaroop.jbot.core.slack.SlackService;
import me.ramswaroop.jbot.core.slack.models.Event;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.web.socket.WebSocketSession;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
@RunWith(MockitoJUnitRunner.Silent.class)
@SpringBootTest
public class BotAnswerServiceTest {
@Test
public void sendAnswersTest() {
BotAnswerService botAnswerService = mock(BotAnswerService.class);
doAnswer(invocation -> {
Object arg0 = invocation.getArgument(0);
Object arg1 = invocation.getArgument(1);
assertEquals(null, arg0);
assertEquals(null, arg1);
return null;
}).when(botAnswerService)
.sendAnswers(any(SlackService.class), any(Bot.class), any(WebSocketSession.class), any(Event.class));
botAnswerService.sendAnswers(null, null, null, null);
}
}
|
package ElevatorDesign;
/**
* Created by FLK on 2019-04-06.
*/
public class ExternalRequest extends Request {
private final Direction direction;
public ExternalRequest(final int levelNumber,final Direction direction) {
super(levelNumber);
this.direction = direction;
}
public Direction getDirection(){
return direction;
}
}
|
package com.aforo255.exam.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aforo255.exam.domain.Invoice;
import com.aforo255.exam.service.InvoiceService;
import lombok.extern.slf4j.Slf4j;
@RefreshScope
@RestController
@Slf4j
public class InvoiceController {
@Autowired
private InvoiceService invoiceService;
@GetMapping("/v1/load")
public List<Invoice> load() {
log.info("::load::");
return invoiceService.load();
}
}
|
package rocks.zipcode.io.assessment4.fundamentals;
import java.util.HashSet;
import java.util.Set;
/**
* @author leon on 09/12/2018.
*/
public class StringUtils {
public static String capitalizeNthCharacter(String str, Integer indexToCapitalize) {
String[] strArray = str.split("");
strArray[indexToCapitalize] = strArray[indexToCapitalize].toUpperCase();
return String.join("", strArray);
}
public static Boolean isCharacterAtIndex(String baseString, Character characterToCheckFor, Integer indexOfString) {
return baseString.charAt(indexOfString)==(characterToCheckFor);
}
public static String[] getAllSubStrings(String string) {
Set<String> result = new HashSet<String>();
for (int i = 0; i <= string.length(); i++) {
for (int j = i + 1; j <= string.length(); j++) {
result.add(string.substring(i, j));
}
}
String [] toReturn = new String[result.size()];
return result.toArray(toReturn);
}
public static Integer getNumberOfSubStrings(String input){
return getAllSubStrings(input).length;
}
}
|
package com.alibaba.druid.sql.parser;
import com.alibaba.druid.DbType;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import junit.framework.TestCase;
import org.junit.Assert;
/**
* @author gfChris
* @version 1.0
* @Description
* @date 2022/8/11 下午4:46
*/
public class OraclePivotCloneTest extends TestCase {
public void testCreateCharset() {
String sql = "SELECT DEPT_ID, M01, M02, M03, M04\n" +
"\t, M05, M06, M07, M08, M09\n" +
"\t, M10, M11, M12\n" +
"FROM (\n" +
"\tSELECT DEPT_ID, CMONTH, SUM(SO_TAXMONEY) AS SO_TAXMONEY\n" +
"\tFROM DW_SCM_DIM_SALEDATA\n" +
"\tGROUP BY DEPT_ID, CMONTH\n" +
")\n" +
"PIVOT (sum(SO_TAXMONEY) FOR CMONTH IN ('01' AS M01, '02' AS M02, '03' AS M03, '04' AS M04, '05' AS M05, '06' AS M06, '07' AS M07, '08' AS M08, '09' AS M09, '10' AS M10, '11' AS M11, '12' AS M12));";
SQLStatement sqlStatement = SQLUtils.parseSingleStatement(sql, DbType.oracle);
SQLStatement sqlStatement1 = sqlStatement.clone();
System.out.println(sqlStatement1.toString());
Assert.assertTrue(sqlStatement1.toString().equals(sql));
}
}
|
package com.huang.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Objects;
import java.util.Properties;
import com.huang.beans.FileBean;
import com.huang.common.Common;
import com.huang.server.Request;
import com.huang.server.Response;
public class Search implements Servlet {
@Override
public void init() {
System.out.println("init");
}
@Override
public void service(Request request, Response response) throws IOException {
System.out.println("from service");
PrintWriter out = response.getWriter();
String contentType = null;
String filePath = null;
String parma = FileBean.parma == null ? "" : FileBean.parma;
Properties prop = new Properties();
InputStream in = null;
try {
in = getClass().getResourceAsStream("/data.properties");
prop.load(in);
contentType = prop.getProperty("Search");
filePath = prop.getProperty("path");
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
StringBuilder sb = new StringBuilder();
Common.getPath(filePath.length(), sb, filePath, parma);
if (Objects.equals(sb, null)) {
return;
}
filePath = filePath.replace("/", "\\");
System.out.println("&&&&&&&&" + sb);
String result = new String(sb);
out.print("HTTP/1.1 200 OK\r\n" + contentType + "\r\n");
out.println("Access-Control-Allow-Origin:*\r\n");
out.print(result.replace("\\", "/"));
out.flush();
out.close();
}
public void destroy() {
System.out.println("destroy");
}
public String getServletInfo() {
return null;
}
}
|
package view.component.button;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.SwingConstants;
import view.aConstant.ButtonConstant;
@SuppressWarnings("serial")
public class SelectButton extends BasicButton {
// Constructor
public SelectButton(String text, String actionCommand, ActionListener actionListener) {
super(" "+text, actionCommand, actionListener);
this.setBackground(ButtonConstant.SelectButtonBackground_Normal);
this.setClickColor(ButtonConstant.SelectButtonBackground_Clicked);
this.setMouseOnColor(ButtonConstant.SelectButtonBackground_MouseOn);
this.setBorderPainted(true);
this.setBorder(BorderFactory.createLineBorder(ButtonConstant.SelectButtonBorderColor));
this.setForeground(ButtonConstant.SelectButtonForeground);
this.setHorizontalAlignment(SwingConstants.LEFT);
}
}
|
package com.Sanmina.BlackLabelWeb;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(BlackLabelWebApplication.class);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.globalcollect.infra2.landscapetool.model;
import org.neo4j.graphdb.RelationshipType;
/**
*
* @author cvugrine
*/
public class Neo4jTypes {
public static enum RelTypes implements RelationshipType {
IS_EEN,
DOCHTER_VAN,
VROUW_VAN,
FAMILIE_VAN
}
public static enum GcCMDBRelTypes implements RelationshipType {
PART_OF,
HAS_CHANNEL,
PROVIDES_SOLUTION,
IN_LOCATION,
IN_ENVIRONMENT,
HOSTS_APP,
USES_DB
}
public static enum NodeTypes {
DATACENTER,
SOLUTION,
CHANNEL,
ENVIRONMENT,
APP,
DB
}
}
|
package br.com.infoCenter.excecao;
public class CarrinhoException extends Exception {
private static final long serialVersionUID = 1L;
public CarrinhoException() {
super();
}
public CarrinhoException(String mensagem) {
super(mensagem);
}
}
|
package org.quickbundle.tools.support.cn2spell;
/**
* @(#)CnToSpellGUI.java
* kindani
* 2004-10-25??
* */
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
/**
* <pre></pre>
*
* <BR>
* <DL>
* <DT><B>JDK版本 </B></DT>
* <BR>
* <DD>1.4</DD>
* </DL>
*
* @author KIN
* @version 1.0
* @see
* @since 1.0
*/
public class Cn2Spell2GUI extends JFrame {
private Cn2Spell2GUI c = null;
public Cn2Spell2GUI() {
super("Cn to Spell");
setSize(800, 100);
getContentPane().setLayout(new FlowLayout());
// component layout
JTextArea from = new JTextArea(5, 20);
JTextArea to = new JTextArea(5, 20);
JButton b = new JButton("cn to pinyin");
getContentPane().add(new JLabel("From:"));
getContentPane().add(from);
getContentPane().add(b);
getContentPane().add(new JLabel("To:"));
getContentPane().add(to);
// action handle
b.addActionListener(new Cn2PinyinActionListener(from, to));
setVisible(true);
// set this for pack
c = this;
}
/**
* button action listener to convert text to pinyin from one textbox to
* another textbox
*/
class Cn2PinyinActionListener implements ActionListener {
private JTextArea from = null;
private JTextArea to = null;
public Cn2PinyinActionListener(JTextArea from, JTextArea to) {
this.from = from;
this.to = to;
}
public void actionPerformed(ActionEvent e) {
if (from.getText().length() == 0) {
JOptionPane.showMessageDialog(from, "From text is empty!",
"Warning", JOptionPane.WARNING_MESSAGE);
}
String text = from.getText();
to.setText(Cn2Spell.getFullSpell(text));
c.pack();
}
}
public static void main(String[] args) {
Cn2Spell2GUI g = new Cn2Spell2GUI();
System.out.println(g);
}
}
|
package com.example.demo.pojo;
import javax.persistence.*;
@Entity
@Table(name = "base_street")
public class BaseStreet{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String streetid;
private String street;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
private String father;
public String getStreetid() {
return streetid;
}
public void setStreetid(String streetid) {
this.streetid = streetid;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getFather() {
return father;
}
public void setFather(String father) {
this.father = father;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.