text
stringlengths 10
2.72M
|
|---|
package com.spbsu.flamestream.example.bl.index;
import com.expleague.commons.text.stem.Stemmer;
import com.spbsu.flamestream.example.bl.index.model.WikipediaPage;
import com.spbsu.flamestream.example.bl.index.model.WordBase;
import com.spbsu.flamestream.example.bl.index.model.WordIndexAdd;
import com.spbsu.flamestream.example.bl.index.ranking.Document;
import com.spbsu.flamestream.example.bl.index.ranking.RankingStorage;
import com.spbsu.flamestream.example.bl.index.ranking.impl.InMemRankingStorage;
import com.spbsu.flamestream.example.bl.index.utils.IndexItemInLong;
import java.util.stream.Stream;
/**
* User: Artem
* Date: 28.09.2017
*/
public interface InvertedIndexValidator {
Stream<WikipediaPage> input();
void assertCorrect(Stream<WordBase> output);
int expectedOutputSize();
abstract class Stub implements InvertedIndexValidator {
protected static String stem(String term) {
//noinspection deprecation
final Stemmer stemmer = Stemmer.getInstance();
return stemmer.stem(term).toString();
}
protected static RankingStorage rankingStorage(Stream<WordBase> output) {
final RankingStorage rankingStorage = new InMemRankingStorage();
output.forEach(container -> {
if (container instanceof WordIndexAdd) {
final WordIndexAdd indexAdd = (WordIndexAdd) container;
final int docId = IndexItemInLong.pageId(indexAdd.positions()[0]);
final int docVersion = IndexItemInLong.version(indexAdd.positions()[0]);
rankingStorage.add(indexAdd.word(), indexAdd.positions().length, new Document(docId, docVersion));
}
});
return rankingStorage;
}
}
}
|
package com.smxknife.java2.thread.yield;
/**
* @author smxknife
* 2019/9/26
*/
public class _Run {
public static void main(String[] args) {
// yield()从未导致线程转到等待/睡眠/阻塞状态。
// 在大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果。
Runnable runnable = () -> {
for (int i = 0; i < 100; i++) {
System.out.println("index = " + i + " name = " + Thread.currentThread().getName());
if ("t1".equals(Thread.currentThread().getName()) && i == 5) {
System.out.println(Thread.currentThread().getName() + " yield at index = " + i);
Thread.yield();
}
}
};
new Thread(runnable, "t1").start();
new Thread(runnable, "t2").start();
}
}
|
package com.example.utils;
import com.example.model.SysUser;
/**
* 把用户信息保存到本地线程
* @author leo
*
*/
public class UserThreadLocal {
private static final ThreadLocal<SysUser> THREAD_LOCAL = new ThreadLocal<SysUser>();
public static void set(SysUser user) {
THREAD_LOCAL.set(user);
}
public static SysUser get() {
return THREAD_LOCAL.get();
}
}
|
//Exercícios no link: https://www.slideshare.net/loianeg/curso-java-basico-exercicios-aulas-14-15
package exerciciosAulas14e15;
import java.util.Scanner;
public class Exercicio_09_OrdemDecrescente {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
System.out.println("Informe três números distintos:");
double n1 = scan.nextDouble();
double n2 = scan.nextDouble();
double n3 = scan.nextDouble();
if(n1 == n2 || n1 == n3 || n2 == n3) {
System.out.println("Existem números iguais!");
}
else if(n1 > n2 && n1 >n3 && n2 > n3) {
System.out.println("Ordem descrescente: " + n1 + ", " + n2 + ", " + n3);
System.out.println("primeira validação");
}
else if(n1 > n2 && n1 >n3 && n3 > n2) {
System.out.println("Ordem descrescente: " + n1 + ", " + n3 + ", " + n2);
System.out.println("segunda validação");
}
else if(n2 > n1 && n2 >n3 && n1 > n3) {
System.out.println("Ordem descrescente: " + n2 + ", " + n1 + ", " + n3);
System.out.println("terceira validação");
}
else if(n2 > n1 && n2 >n3 && n3 > n1) {
System.out.println("Ordem descrescente: " + n2 + ", " + n3 + ", " + n1);
System.out.println("quarta validação");
}
else if(n3 > n1 && n3 >n2 && n2 > n1) {
System.out.println("Ordem descrescente: " + n3 + ", " + n2 + ", " + n1);
System.out.println("quinta validação");
}
else if(n3 > n1 && n3 >n2 && n1 > n2) {
System.out.println("Ordem descrescente: " + n3 + ", " + n1 + ", " + n2);
System.out.println("sexta validação");
}
scan.close();
}
}
|
package com.chuxin.family.main;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chuxin.family.R;
import com.chuxin.family.net.AccountApi;
import com.chuxin.family.net.ConnectionManager.JSONCaller;
import com.chuxin.family.parse.been.CxParseBasic;
import com.chuxin.family.utils.CxLog;
import com.chuxin.family.utils.DialogUtil;
import com.chuxin.family.utils.ToastUtil;
import com.chuxin.family.views.login.CxThirdAccessToken;
import com.chuxin.family.views.login.CxThirdAccessTokenKeeper;
public class CxRegisterByFamily extends Activity {
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.cx_fa_activity_main_register_by_family);
initTitle();
init();
}
private void init() {
accountEdit = (EditText) findViewById(R.id.cx_fa_main_register_email_account);
tokenEdit = (EditText) findViewById(R.id.cx_fa_main_register_email_token);
tokenTooEdit = (EditText) findViewById(R.id.cx_fa_main_register_email_token_too);
LinearLayout registerLayout = (LinearLayout) findViewById(R.id.cx_fa_main_register_btn_layout);
registerLayout.setOnClickListener(listener);
}
private void initTitle() {
Button backBtn = (Button) findViewById(R.id.cx_fa_activity_title_back);
TextView titleText = (TextView) findViewById(R.id.cx_fa_activity_title_info);
titleText.setText("小家帐号注册");
backBtn.setText(getString(R.string.cx_fa_navi_back));
backBtn.setOnClickListener(listener);
}
OnClickListener listener=new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cx_fa_activity_title_back:
back();
break;
case R.id.cx_fa_main_register_btn_layout:
registerAccount();
break;
default:
break;
}
}
};
private EditText accountEdit;
private EditText tokenEdit;
private EditText tokenTooEdit;
private void registerAccount() {
account = accountEdit.getText().toString().trim();
token = tokenEdit.getText().toString().trim();
tokenToo = tokenTooEdit.getText().toString().trim();
if(TextUtils.isEmpty(account) || TextUtils.isEmpty(token) || TextUtils.isEmpty(tokenToo)){
ToastUtil.getSimpleToast(this, -3, "请输入帐号密码", 1).show();
return ;
}
String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
Pattern regex = Pattern.compile(check);
Matcher matcher = regex.matcher(account);
boolean flag = matcher.matches();
if(!flag){
ToastUtil.getSimpleToast(this, -3, "邮箱名格式有误", 1).show();
return ;
}
String check2 = "^[a-z0-9A-Z]+$";
Pattern regex2 = Pattern.compile(check2);
Matcher matcher2 = regex2.matcher(token);
boolean flag2 = matcher2.matches();
if(!flag2){
ToastUtil.getSimpleToast(this, -3, "只能输入英文或数字", 1).show();
return ;
}
if(token.length()<6){
ToastUtil.getSimpleToast(this, -3, "请输入6位以上密码", 1).show();
return ;
}
if(!token.equals(tokenToo)){
ToastUtil.getSimpleToast(this, -3, "两次密码输入不一致", 1).show();
return ;
}
if(account.length()>30){
ToastUtil.getSimpleToast(this, -3, "帐号输入过长", 1).show();
return ;
}
if(token.length()>30){
ToastUtil.getSimpleToast(this, -3, "密码输入过长", 1).show();
return ;
}
try {
DialogUtil.getInstance().getLoadingDialogShow(CxRegisterByFamily.this, -1);
AccountApi.getInstance().doRegister("email", account,token,null, -1+"", //0:男性 1:女性 -1:未设置
null/*sina微博没有生日这个字段返回*/,
null/*暂时没有client_version*/,
"zh_cn",
null, regiseCallback);
} catch (Exception e) {
e.printStackTrace();
DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000);
showResponseToast("注册失败", 0);
}
}
JSONCaller regiseCallback=new JSONCaller() {
@Override
public int call(Object result) {
DialogUtil.getInstance().setLoadingDialogDismiss(null, -1, 1000);
if (null == result) { //注册失败给予提示
showResponseToast("注册失败", 0);
return -1;
}
CxLog.i("", "ready to get user chuxin profile:"+result.toString());
CxParseBasic loginResult = null;
try {
loginResult = (CxParseBasic)result;
} catch (Exception e) {
e.printStackTrace();
}
if (null == loginResult){ //注意此处把uid放在msg字段
showResponseToast("注册失败", 0);
return -1;
}
if(408==loginResult.getRc()){
showResponseToast(getString(R.string.cx_fa_net_response_code_null), 0);
return -1;
}
if(3001 ==loginResult.getRc()){
String str="该账号已被注册";
if(!TextUtils.isEmpty(loginResult.getMsg())){
str=loginResult.getMsg();
}
showResponseToast(str, 0);
return -1;
}
if(0!=loginResult.getRc()){
showResponseToast(getString(R.string.cx_fa_net_response_code_fail), 0);
return -1;
}
CxThirdAccessToken localToken = new CxThirdAccessToken(token, account, "", "email");
CxThirdAccessTokenKeeper.keepAccessToken(CxRegisterByFamily.this, localToken);
try {
CxAuthenNew.mAuthenHandler.sendEmptyMessage(CxAuthenNew.AutoLogin);
finish();
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
} catch (Exception e) {
e.printStackTrace();
showResponseToast("登录失败", 0);
}
CxLog.i("", "registed uid is:"+loginResult.getMsg());
return 0;
}
};
private String account;
private String token;
private String tokenToo;
protected void back() {
Intent intent=new Intent(this, CxLoginByFamily.class);
startActivity(intent);
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
finish();
}
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if (keyCode == android.view.KeyEvent.KEYCODE_BACK) {
back();
return false;
}
return super.onKeyDown(keyCode, event);
};
/**
*
* @param info
* @param number 0 失败;1 成功;2 不要图。
*/
private void showResponseToast(String info,int number) {
Message msg = new Message();
msg.obj = info;
msg.arg1=number;
new Handler(CxRegisterByFamily.this.getMainLooper()) {
public void handleMessage(Message msg) {
if ((null == msg) || (null == msg.obj)) {
return;
}
int id=-1;
if(msg.arg1==0){
id= R.drawable.chatbg_update_error;
}else if(msg.arg1==1){
id=R.drawable.chatbg_update_success;
}
ToastUtil.getSimpleToast(CxRegisterByFamily.this, id,
msg.obj.toString(), 1).show();
};
}.sendMessage(msg);
}
}
|
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.PatternSyntaxException;
public class FileReader {
// --------------------------------------------------------------------------------------------------------------------
/*
* The method is used to read the grid information from a file, then returns 2D
* aaray of char elements each element is either '-' or 'x' at the begining
* Note: This methos was used for the first version of the project
*/
public static char[][] readFile(String fileName) {
int gridSize = 0;
char[][] grid = null;
try {
File file = new File("src/" + fileName + ".txt");
Scanner scanner = new Scanner(file);
if (scanner.hasNextLine()) {
// the first line of the text file contains the grid size
gridSize = Integer.parseInt(scanner.nextLine());
System.out.println("The grid size is " + gridSize + " x " + gridSize);
// creating the grid
grid = new char[gridSize][gridSize];
// assigning '-' for all elements of the grid
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
grid[row][col] = '-';
}
}
/*
* Now, we have a grid with '-' for all its elements So, continue looping to
* read all lines in the Each line represents the index of an obstacle => 'x'
*/
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
int i = Integer.parseInt(line.substring(0, line.indexOf(' '))) - 1;
int j = Integer.parseInt(line.substring(line.indexOf(' ') + 1)) - 1;
grid[i][j] = 'x';
}
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("There is an error while reading the " + fileName + " file !");
e.printStackTrace();
} catch (NumberFormatException e) {
System.out.println("The read input is not a number!");
e.printStackTrace();
}
return grid;
}
// --------------------------------------------------------------------------------------------------------------------
/*
* The method is used to read the tree elements from a file, then returns an
* aaray of characters elements each element is either '0' or null at the
* begining Note: This methos was used for the second version of the project
*/
public static Character[] fromFileToCharacterArray(String fileName) {
String[] floorString = null;
try {
File file = new File("src/" + fileName + ".txt");
Scanner scanner = new Scanner(file);
if (scanner.hasNextLine()) {
String str = scanner.nextLine();
String floorMapString = str.substring(1, str.length() - 1);
floorString = floorMapString.split(",");
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("The file " + fileName + " was not found !");
}catch(PatternSyntaxException e){
System.out.println("Please make sure that the " + fileName + " file is correctly written");
}
Character[] floor = new Character[floorString.length];
for (int i = 0; i < floor.length; i++) {
if (floorString[i].equals("0")) {
floor[i] = floorString[i].charAt(0);
} else {
floor[i] = null;
}
}
return floor;
}
}
|
package fr.pederobien.uhc.game.blockedexgame;
import org.bukkit.Material;
import fr.pederobien.uhc.game.blockedexgame.object.BlocksToFind;
import fr.pederobien.uhc.managers.BaseManager;
import fr.pederobien.uhc.managers.TeamsManager;
import fr.pederobien.uhc.managers.WorldManager;
public class StartState extends AbstractBlockedexState {
public StartState(IBlockedexGame game) {
super(game);
}
@Override
public void start() {
onStart();
WorldManager.createCrossUnderSpawn(Material.BEDROCK);
BaseManager.launchBlockedexBases();
TeamsManager.teleporteRandomlyAllTeams(getConfiguration(), getConfiguration().getDiameterAreaOnPlayerRespawn());
BlocksToFind.initialize();
taskLauncher.run(0, 20L);
scoreboardLauncher.run(0, getConfiguration().getScoreboardRefresh());
game.setCurrentState(game.getStarted());
}
}
|
package mapper;
import dto.InventoryDetailsDto;
import entity.Inventory;
public class InventoryToInventoryDetailsDto {
public static InventoryDetailsDto convert(Inventory inventory) {
if(inventory == null) return null;
return new InventoryDetailsDto(inventory.getId(), inventory.getBookDetails().getId(), inventory.getBookDetails().getTitle(), inventory.getQuantity());
}
}
|
/**
* @ClassName: WechatMsgService
* @Description: TODO
* @author: cc
* @date: 2018年8月18日 下午1:27:05
*
*/
package cc.feefox.wechat.message.service.interfaces;
import java.util.Map;
import cc.feefox.wechat.common.result.WeChatResult;
import cc.feefox.wechat.message.model.BaseMessage;
/**
* @Package: cc.feefox.wechat.message.service
* @author: cc
* @date: 2018年8月18日 下午1:27:05
*/
public interface WechatMsgService {
/**
* 用户发送的为文本消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return 返回需要该消息回复的xml格式类型的字符串
*/
WeChatResult textMsgInfo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户发送的为图片消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult imageMsgInfo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户发送的为链接消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult linkMsgInfo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户发送的为地理位置消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult locationMsgInfo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户发送的为音频消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult voiceMsgInfo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户发送的为短视频消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult shortVideo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户发送的为视频消息
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult videoMsgInfo(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户关注事件
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult subscribe(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户取消关注事件
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult unsubscribe(Map<String, String> params, BaseMessage msgInfo);
/**
* 用户已关注时的事件推送
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult scan(Map<String, String> params, BaseMessage msgInfo);
/**
* 上报地理位置事件
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult eventLocation(Map<String, String> params, BaseMessage msgInfo);
/**
* 点击菜单拉取消息时的事件推送 (自定义菜单的click在这里做响应)
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult eventClick(Map<String, String> params, BaseMessage msgInfo);
/**
* 点击菜单跳转链接时的事件推送 (自定义菜单的view在这里做响应)
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult eventView(Map<String, String> params, BaseMessage msgInfo);
/**
* 客服创建会话事件
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult kfCreateSession(Map<String, String> params, BaseMessage msgInfo);
/**
* 客服关闭会话事件
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult kfCloseSession(Map<String, String> params, BaseMessage msgInfo);
/**
* 客服转接会话事件
* WechatMsgService.java
* @param params
* @param msgInfo
* @return
*/
WeChatResult kfSwitchSession(Map<String, String> params, BaseMessage msgInfo);
/**
* 事件类型默认返回
* WechatMsgService.java
* @param params
* @param msgInfo
*/
void eventDefaultReply(Map<String, String> params, BaseMessage msgInfo);
/**
* 默认执行的消息
* WechatMsgService.java
* @param params
* @param msgInfo
*/
void defaultMsgInfo(Map<String, String> params, BaseMessage msgInfo);
}
|
package com.jim.multipos.ui.settings.currency;
import android.content.Context;
import android.support.v4.app.Fragment;
import com.jim.multipos.R;
import com.jim.multipos.config.scope.PerFragment;
import javax.inject.Named;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
@Module(includes = CurrencyPresenterModule.class)
public abstract class CurrencySettingsFragmentModule {
@Binds
@PerFragment
abstract Fragment provideFragment(CurrencySettingsFragment currencySettingsFragment);
@Binds
@PerFragment
abstract CurrencyView provideCurrencyView(CurrencySettingsFragment currencySettingsFragment);
@PerFragment
@Provides
@Named(value = "currency_name")
static String[] provideCurrencyName(Context context) {
return context.getResources().getStringArray(R.array.currency_title);
}
@PerFragment
@Provides
@Named(value = "currency_abbr")
static String[] provideCurrencyAbbr(Context context) {
return context.getResources().getStringArray(R.array.currency_abbrs);
}
}
|
package com.acme.dao;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.acme.model.evenement.Evenement;
public interface EvenementDao extends JpaRepository < Evenement, Long > {
/**
* Rechercher les evenenments d'un utilisateur.
*
* @param username
* @return liste des evenements
*/
List < Evenement > findByCreatedBy(String username);
@Query("SELECT e FROM com.acme.model.evenement.Evenement e where e.estPublie=true")
Page < Evenement > getPublies(Pageable page);
@Query("SELECT e FROM com.acme.model.evenement.Evenement e where e.estPublie=false")
Page < Evenement > getNonPublies(Pageable page);
}
|
package com.slort.struts.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.hibernate.HibernateException;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import com.bdb.model.TwoObjects;
import com.bdb.util.DateUtils;
import com.slort.model.Calculoubicacion;
import com.slort.model.CalculoubicacionDAO;
import com.slort.model.Cliente;
import com.slort.model.ClienteDAO;
import com.slort.model.Flota;
import com.slort.model.FlotaDAO;
import com.slort.model.Historicoubicaciondetalle;
import com.slort.model.HistoricoubicaciondetalleDAO;
import com.slort.model.Hotel;
import com.slort.model.HotelDAO;
import com.slort.model.OpcionmenuPerfil;
import com.slort.model.Reserva;
import com.slort.model.ReservaDAO;
import com.slort.model.OpcionmenuDAO;
import com.slort.model.Perfil;
import com.slort.model.PerfilDAO;
import com.slort.model.Usuario;
import com.slort.model.UsuarioDAO;
import com.slort.struts.action.SlortDispatchAction;
import com.slort.struts.form.ReporteHistoricoForm;
import com.slort.struts.form.ReporteReservaForm;
import com.slort.struts.form.security.FlotaForm;
import com.slort.struts.form.security.ReservaForm;
import com.slort.struts.form.security.PerfilForm;
import com.slort.struts.form.security.UsuarioForm;
import com.slort.util.FileCopy;
import com.slort.util.JExcel;
import com.slort.util.Numbers;
import fr.improve.struts.taglib.layout.util.FormUtils;
public class ReporteHistoricoAction extends SlortDispatchAction {
private static final Logger log;
private String error;
static {
log = Logger.getLogger(com.slort.struts.action.security.UsuarioAction.class);
}
public ReporteHistoricoAction() {
}
public ActionForward find(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
if (response.equals(new String("A"))) {}
log.debug("Procesando find action");
ReporteHistoricoForm currentForm = (ReporteHistoricoForm)form;
currentForm.reset(mapping, request);
log.debug("Seteando en modo EDIT");
currentForm.setReqCode("find");
FormUtils.setFormDisplayMode(request, form, FormUtils.EDIT_MODE);
return mapping.findForward("findPage");
}
public ActionForward findData(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
log.debug("findData++");
ReporteHistoricoForm currentForm = (ReporteHistoricoForm)form;
Historicoubicaciondetalle object = new Historicoubicaciondetalle();
HistoricoubicaciondetalleDAO HistoricoubicaciondetalleDAO = (HistoricoubicaciondetalleDAO) this.getBean(request,"HistoricoubicaciondetalleDAO");
UsuarioDAO un_UsuarioDAO = (UsuarioDAO) this.getBean(request,"UsuarioDAO");
request.setAttribute("usuarios", un_UsuarioDAO.findAll());
Calculoubicacion calculoubicacion = new Calculoubicacion();
Reserva reserva = new Reserva();
reserva.setUsuario(currentForm.getUsuario());
calculoubicacion.setReserva(reserva);
object.setCalculoubicacion(calculoubicacion);
Flota flota = new Flota();
flota.setLicencia(currentForm.getLicencia());
object.setFlota(flota);
Date fechadesde=null;
Date fechahasta=null;
if (currentForm.getFechadesde()!=null)
fechadesde = DateUtils.getFechaFormateada(currentForm.getFechadesde(),"dd-MM-yyyy");
if (currentForm.getFechahasta()!=null)
fechahasta = DateUtils.getFechaFormateada(currentForm.getFechahasta(),"dd-MM-yyyy");
currentForm.setListaResultado(HistoricoubicaciondetalleDAO.findByGUIPosibilitiesReporte(object, fechadesde , fechahasta ));
request.setAttribute("foundResults", currentForm.getListaResultado());
currentForm.setReqCode("findData");
//currentForm.reset(mapping, request);
FormUtils.setFormDisplayMode(request, form, FormUtils.EDIT_MODE);
log.debug("findData--");
return mapping.findForward("success");
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
@SuppressWarnings("unchecked")
public ActionForward reporte_excel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
log.debug("reporte_excel++");
ReporteHistoricoForm currentForm = (ReporteHistoricoForm)form;
JExcel excel=new JExcel();
String nombrePantillaHistoricoUbicacionDetalle = "Plantilla_Reporte_Historico_Ubicacion_Detalle.xls";
String nombreArchivo = "Reporte_Historico_"+ DateUtils.getFechaActual()+"_" + DateUtils.getHoraActual() +".xls";
String filePath = getServlet().getServletContext().getRealPath("/") +"view\\templates";
filePath = filePath + "\\";
try {
FileCopy.copy(filePath + nombrePantillaHistoricoUbicacionDetalle,
filePath + nombreArchivo);
} catch (IOException e) {e.printStackTrace();}
excel.exportarArrayList(toArraydeArray(currentForm.getListaResultado()) ,
response,
nombreArchivo,
filePath + nombreArchivo,
1,
6);
log.debug("reporte_excel--");
return null;
}
@SuppressWarnings("unchecked")
private ArrayList toArraydeArray(List<Historicoubicaciondetalle> listaResultado) {
ArrayList listaArray = new ArrayList();
ArrayList unArrayH = new ArrayList();
unArrayH.add(new TwoObjects("Texto", "ID"));
unArrayH.add(new TwoObjects("Texto", "Flota"));
unArrayH.add(new TwoObjects("Texto", "Fecha"));
unArrayH.add(new TwoObjects("Texto", "Hora"));
unArrayH.add(new TwoObjects("Texto", "Ranking"));
unArrayH.add(new TwoObjects("Texto", "Distancia"));
unArrayH.add(new TwoObjects("Texto", "Tiempo"));
unArrayH.add(new TwoObjects("Texto", "Motivo"));
//listaArray.add(unArrayH);
ArrayList unArray;
for (Historicoubicaciondetalle object : listaResultado) {
error = "AdmCostos.Resultado.ExistenDatos";
unArray = new ArrayList();
unArray.add(new TwoObjects("Numerico", object.getId().toString() ));
unArray.add(new TwoObjects("Numerico", object.getFlota().getCodUnidad().toString() ));
unArray.add(new TwoObjects("Fecha", object.getFecha()));
unArray.add(new TwoObjects("Hora", object.getHora()));
unArray.add(new TwoObjects("Numerico", object.getRanking()));
unArray.add(new TwoObjects("Texto", object.getDistanciaObjetivo().toString()));
unArray.add(new TwoObjects("Texto", object.getTiempoObjetivo().toString() ));
unArray.add(new TwoObjects("Texto", object.getMotivoNoAsignado()));
listaArray.add(unArray);
}
return listaArray;
}
}
|
package com.project.linkedindatabase.domain.post;
import com.project.linkedindatabase.annotations.Table;
import com.project.linkedindatabase.domain.BaseEntity;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@Table(tableName = "like_comment")
public class LikeComment extends BaseEntity {
private Long commentId;// foreign key to comment table
private Long profileId;
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$ch extends g {
public c$ch() {
super("getRouteUrl", "getRouteUrl", 235, false);
}
}
|
package com.johnadamsacademy.mentor.technologydevelopment.jaalaga;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.util.adt.pool.GenericPool;
public class RocketPool extends GenericPool<Sprite> {
private ITextureRegion textureRegion;
private VertexBufferObjectManager vertexBufferObjectManager;
public RocketPool(int maxCount, ITextureRegion newTextureRegion, VertexBufferObjectManager newVertexBufferObjectManager) {
super(0, 1, maxCount);
if(newTextureRegion != null) {
this.textureRegion = newTextureRegion;
} else {
throw new IllegalArgumentException("The texture region must not be NULL");
}
if(newVertexBufferObjectManager != null) {
this.vertexBufferObjectManager = newVertexBufferObjectManager;
} else {
throw new IllegalArgumentException("The texture region must not be NULL");
}
}
@Override
protected Sprite onAllocatePoolItem() {
return new Sprite(0, 0, this.textureRegion, this.vertexBufferObjectManager);
}
@Override
protected void onHandleRecycleItem(final Sprite sprite) {
sprite.setIgnoreUpdate(true);
sprite.setVisible(false);
}
@Override
protected void onHandleObtainItem(final Sprite sprite) {
sprite.reset();
}
}
|
import javax.swing.JOptionPane;
/** This program demonstrates a nested if statement.
*/
public class LoanQualifier
{
public static void main(String[] args)
{
String inputSalary; //Annual salary
String inputYears;
double salary;
double yearsOnJob;
//Get the user's annual salary.
inputSalary = JOptionPane.showInputDialog("Enter your annual salary: ");
salary = Double.parseDouble(inputSalary);
//Get the number of years at the current job.
inputYears = JOptionPane.showInputDialog ("Enter the number of years " + "at your current job: ");
yearsOnJob = Double.parseDouble(inputYears);
//Determin whether the user qualifies for the loan.
if (salary>= 50000)
{
if (yearsOnJob >= 2)
{
System.out.println("You qualify for the loan. ");
}
else
{
System.out.println("You must have been on your " + "current job for at least " + "two years to qualify. ");
}
}
else
{
System.out.println("You must earn at least " + "$50,000 per year to qualify.");
}
System.exit(0);
}
}
|
package com.google.android.exoplayer2.c.c;
public final class u$a {
public final String aem;
public final byte[] aph;
public final int type;
public u$a(String str, int i, byte[] bArr) {
this.aem = str;
this.type = i;
this.aph = bArr;
}
}
|
//*********************************************************
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
// OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language
// governing permissions and limitations under the License.
//*********************************************************
package com.example.onenoteservicecreatepageexample;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
import com.microsoft.live.LiveAuthClient;
import com.microsoft.live.LiveAuthException;
import com.microsoft.live.LiveAuthListener;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveConnectSession;
import com.microsoft.live.LiveStatus;
public class MainActivity extends Activity implements LiveAuthListener, AsyncResponse {
private LiveAuthClient mAuthClient;
private LiveConnectClient mLiveConnectClient;
private TextView resultTextView;
private String mAccessToken = null;
private final String CLIENT_ID_MESSAGE = "Insert Your Client Id Here";
private final Iterable<String> scopes = Arrays.asList("office.onenote_create" /*Create pages*/, "office.onenote_update_by_app" /*Edit pages created by the app*/, "wl.signin" /*WL Sign in access*/, "wl.offline_access" /*Refresh token access*/);
private Date accessTokenExpiration = null;
private String refreshToken = null;
private EditText sectionNameTextBox = null;
private String sectionName = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sectionName = "";
setContentView(R.layout.activity_main);
resultTextView = (TextView) findViewById(R.id.txtView_Auth);
mAuthClient = new LiveAuthClient(this, Constants.CLIENTID);
if(Constants.CLIENTID.equals(CLIENT_ID_MESSAGE))
{
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
/**
* Please enter your client ID for field Constants#CLIENTID
*/
dialogBuilder.setMessage("Visit http://go.microsoft.com/fwlink/?LinkId=392537 for instructions on getting a Client Id. Please specify your client ID at field Constants.CLIENTID and rebuild the application.");
dialogBuilder.setTitle("Please add a client Id to your code.");
dialogBuilder.setNeutralButton("OK", null);
AlertDialog dialog = dialogBuilder.create();
dialog.show();
}
setCreatePageButtonsVisibility(false);
Button signoutButton = (Button) findViewById(R.id.btn_signout);
signoutButton.setEnabled(false);
sectionNameTextBox = (EditText) findViewById(R.id.sectionName);
sectionNameTextBox.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable sectionNameField) {
sectionName = sectionNameTextBox.getText().toString();
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
//No handling done by this sample here
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//No handling done by this sample here
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void setCreatePageButtonsVisibility(boolean visibility) {
Button simplePageButton = (Button) findViewById(R.id.btn_sendHTML);
simplePageButton.setEnabled(visibility);
Button imagePageButton = (Button) findViewById(R.id.btn_sendImg);
imagePageButton.setEnabled(visibility);
Button urlPageButton = (Button) findViewById(R.id.btn_sendURL);
urlPageButton.setEnabled(visibility);
Button embeddedHTMLPageButton = (Button) findViewById(R.id.btn_sendEmbeddedHTML);
embeddedHTMLPageButton.setEnabled(visibility);
Button attachmentPageButton = (Button) findViewById(R.id.btn_createPageWithAttachmentAndPdfRendering);
attachmentPageButton.setEnabled(visibility);
}
public void onAuthComplete(LiveStatus status, LiveConnectSession session, Object userState) {
if(status == LiveStatus.CONNECTED) {
Button authenticateButton = (Button) findViewById(R.id.btn_auth);
authenticateButton.setEnabled(false);
resultTextView.setText(R.string.auth_yes);
mAccessToken = session.getAccessToken();
accessTokenExpiration = session.getExpiresIn();
refreshToken = session.getRefreshToken();
mLiveConnectClient = new LiveConnectClient(session);
setCreatePageButtonsVisibility(true);
Button signoutButton = (Button) findViewById(R.id.btn_signout);
signoutButton.setEnabled(true);
}
else {
resultTextView.setText(R.string.auth_no);
mLiveConnectClient = null;
}
}
public void onAuthError(LiveAuthException exception, Object userState) {
exception.printStackTrace();
resultTextView.setText(getResources().getString(R.string.auth_err) + exception.getMessage());
mLiveConnectClient = null;
}
public void btn_signout_onClick(View view) {
setCreatePageButtonsVisibility(false);
mAuthClient.logout(this);
mLiveConnectClient = null;
/**
* Since the user requested to sign out, we first logout on the LiveAuthClient instance
* Then, we restart the activity because we want to finish with and release the current activity and start a new activity based on the same intent (MainActivity)
* This results into the user seeing the start page with Authenticate enabled and all create page buttons disabled, which means that we signed out and must Authenticate again
*/
Intent intent = getIntent();
finish();
startActivity(intent);
}
/** Called when the user clicks the Authenticate Button */
public void callOAuth(View vew) {
mAuthClient.login(this, scopes, this);
}
@Override
protected void onStart() {
super.onStart();
mAuthClient.initialize(scopes, this);
}
/** Called when the user clicks the HTML Button */
public void btn_sendHTML_onClick(View view)
{
boolean success = StartRequest();
if(success)
{
SendPageCreateAsyncTask task = new SendPageCreateAsyncTask();
task.delegate = this;
task.execute("Simple", mAccessToken, sectionName);
}
else
{
//Disabling the create page buttons
setCreatePageButtonsVisibility(false);
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("An error was encountered when trying to refresh the access token.");
}
}
/**
* Called when the user clicks the attachment request button
*/
public void btn_sendAttachmentWithPdfRendering_onClick(View view) {
boolean success = StartRequest();
if(success)
{
SendPageCreateAsyncTask task = new SendPageCreateAsyncTask();
task.delegate = this;
AssetManager assetManager = getResources().getAssets();
task.assetManager = assetManager;
task.execute("AttachmentWithPdfRendering", mAccessToken, sectionName);
}
else
{
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("An error was encountered when trying to process this request.");
}
}
/** Called when the user clicks the Img Button */
/** Creates a page with an image on it
* @throws MalformedURLException */
public void btn_sendImg_onClick(View view) {
boolean success = StartRequest();
if(success)
{
SendPageCreateAsyncTask task = new SendPageCreateAsyncTask();
task.delegate = this;
AssetManager assetManager = getResources().getAssets();
task.assetManager = assetManager;
task.execute("Image", mAccessToken, sectionName);
}
else
{
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("A failure was encountered when trying to process this request.");
}
}
private boolean requestRefreshToken(String refreshToken) throws InterruptedException, ExecutionException
{
SendRefreshTokenAsyncTask task = new SendRefreshTokenAsyncTask();
Object[] refreshTokenResult = task.execute(refreshToken).get();
if(refreshTokenResult != null) {
mAccessToken = (String) refreshTokenResult[0];
refreshToken = (String) refreshTokenResult[1];
/**
* The value at refreshTokenResult[2] denotes the number of seconds since the time of the request in which the new access token will expire
* We add this value to keep the accessTokenExpiration property updated.
* This property is used to check if the access token has expired every time we attempt to use the access token for a new request.
* If yes, then we issue a new request for refreshing the token.
*/
accessTokenExpiration.setTime(accessTokenExpiration.getTime() + 1000 * (Integer)refreshTokenResult[2]);
return true;
}
return false;
}
private boolean StartRequest() {
//Check whether the access token has expired and if yes then attempt to refresh
Date now = new Date();
if(accessTokenExpiration.compareTo(now) <= 0) {
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("Status: Waiting for token refresh");
try {
if(requestRefreshToken(refreshToken))
{
return true;
}
else {
tvStatus.setText("Status: Token refresh failed. Attempting to restart the application.");
/**
* Since the token refresh failed, we restart the activity because we want to finish with and release the current activity which could not get the token refreshed
* We start a new activity based on the same intent (MainActivity)
* Then, clicking Authenticate will lead to a new login request to the LiveAuthClient which would attempt to get a new token
*/
Intent intent = getIntent();
finish();
startActivity(intent);
return false;
}
}
catch (Exception e) {
e.printStackTrace();
tvStatus.setText("Status: Token refresh failed. Attempting to restart the application.");
/**
* Since the token refresh failed even on retry, we restart the activity because we want to finish with and release the current activity which could not get the token refreshed
* We start a new activity based on the same intent (MainActivity)
* Then, clicking Authenticate will lead to a new login request to the LiveAuthClient which would attempt to get a new token
*/
Intent intent = getIntent();
finish();
startActivity(intent);
return false;
}
}
else {
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("Status: Sending request...");
return true;
}
}
/** Called when the user clicks the EmbeddedHTML Button */
public void btn_sendEmbeddedHTML_onClick(View view) {
boolean success = StartRequest();
if(success)
{
SendPageCreateAsyncTask task = new SendPageCreateAsyncTask();
task.delegate = this;
task.execute("HTML", mAccessToken, sectionName);
}
else
{
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("A failure was encountered when trying to process this request.");
}
}
/** Called when the user clicks the URL Button */
public void btn_sendURL_onClick(View view) {
boolean success = StartRequest();
if(success)
{
SendPageCreateAsyncTask task = new SendPageCreateAsyncTask();
task.delegate = this;
task.execute("URL", mAccessToken, sectionName);
}
else
{
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
tvStatus.setText("A failure was encountered when trying to process this request.");
}
}
@Override
public void processFinish(ApiResponse response) {
showResponse(response);
}
public void showResponse(ApiResponse response)
{
TextView tvStatus = (TextView)findViewById(R.id.tvStatus);
if (response.getReseponseCode() == 201) {
tvStatus.setText("Status: page created successfully.");
Intent intent = new Intent(this, ResultsActivity.class);
String message = response.getResponseMessage();
String clientUrl = response.getOneNoteClientUrl();
String webUrl = response.getOneNoteWebUrl();
intent.putExtra(Constants.RESPONSE, message);
intent.putExtra(Constants.CLIENT_URL, clientUrl);
intent.putExtra(Constants.WEB_URL, webUrl);
startActivity(intent);
} else {
tvStatus.setText("Status: page creation failed with error code " + response.getReseponseCode());
}
}
}
|
package com.edu.miusched.dao;
import com.edu.miusched.domain.Course;
import com.edu.miusched.domain.Faculty;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import javax.transaction.Transactional;
import java.time.LocalDate;
@Repository
public interface FacultyDao extends JpaRepository<Faculty ,Long> {
// to mark delete or update query
@Transactional
@Modifying
@Query(
value = "DELETE FROM faculty_block_preference u WHERE u.block_preference_blockid =:id ",
nativeQuery = true)
void deleteBlockByID(@Param("id")Long id);
@Transactional
@Modifying
@Query(
value = "DELETE FROM faculty_course_preference u WHERE u.course_preference_id =:id AND u.faculty_id=1",
nativeQuery = true)
void deleteCourseById(@Param("id") Long id);
// "insert into Logger (redirect,user_id) VALUES (:insertLink,:id)"
@Transactional
@Modifying
@Query(
value = "INSERT INTO faculty_course_preference VALUES (1,:courseid)",
nativeQuery = true)
void addCourse(@Param("courseid") Long id);
@Transactional
@Modifying
@Query(
value = "INSERT INTO faculty_block_preference VALUES (1,:blockid)",
nativeQuery = true)
void addBlock(@Param("blockid") Long id);
@Transactional
@Modifying
@Query(
value = "UPDATE Faculty set interval_between_blocks = :intr,start_date=:start WHERE id = :facid",
nativeQuery = true)
void UpdateFaculty(@Param("facid") Long id,
@Param("intr") Integer val,
@Param("start")LocalDate date);
@Transactional
@Query(
value = "SELECT * FROM faculty_course_preference WHERE faculty_id = 1 AND course_preference_id = :courid ",
nativeQuery = true)
Integer getOneCourse(@Param("courid") Long id
);
}
//"update Customer c set c.name = :name WHERE c.id = :customerId"
|
package uo.sdi.presentation;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import uo.sdi.business.exception.BusinessException;
import uo.sdi.infrastructure.Factories;
import uo.sdi.model.Task;
import alb.util.date.DateUtil;
import alb.util.log.Log;
public class BeanCreateTask {
@ManagedProperty(value = "userBean")
private UserBean userBean;
private String categoryNameToChange;
private String title;// Titulo de la nueva tarea
private Date planned;// Fecha planeada de la nueva tarea
private String comment;// Comentario de la nueva tarea;
@PostConstruct
public void init() {
userBean = (UserBean) FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap()
.get(new String("userBean"));
}
public String getCategoryNameToChange() {
return categoryNameToChange;
}
public void setCategoryNameToChange(String categoryNameToChange) {
this.categoryNameToChange = categoryNameToChange;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getPlanned() {
return planned;
}
public void setPlanned(Date planned) {
this.planned = planned;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
/**
* Crea una nueva tarea con los datos editTitle, editComments, editPlanned
* and editFinished.
*
* @return exito, si la tarea se guarda correctamente. fracaso si hay algun
* error al guardar la tarea
*/
public String createTask() {
String resultado = "exito";
try {
Task nuevaTarea = new Task();
nuevaTarea.setUser(userBean.getUser());
nuevaTarea.setTitle(title);
nuevaTarea.setComments(comment);
nuevaTarea.setCreated(DateUtil.today());
if (planned != null)
nuevaTarea.setPlanned(planned);
else
nuevaTarea.setPlanned(DateUtil.today());
if (this.categoryNameToChange != null)
nuevaTarea.setCategory(userBean
.getCategoryFromName(this.categoryNameToChange));
Factories.services.getTaskService().createTask(nuevaTarea);
Log.debug("Se ha creado una nueva tarea [%s] correctamente", title);
if (nuevaTarea.getCategory() == null) {
userBean.listarInbox();
resultado = "inbox";
} else {
if (nuevaTarea.getPlanned().equals(DateUtil.today())) {
userBean.listarHoy();
resultado = "hoy";
} else {
userBean.listarSemana();
resultado = "semana";
}
}
} catch (BusinessException e) {
resultado = "fracaso";
Log.debug("Ha ocurrido un error creando la tarea [%s]: %s", title,
e.getMessage());
}
return resultado;
}
}
|
package com.facebook.yoga;
public enum YogaDimension {
HEIGHT,
WIDTH(0);
private final int mIntValue;
static {
HEIGHT = new YogaDimension("HEIGHT", 1, 1);
$VALUES = new YogaDimension[] { WIDTH, HEIGHT };
}
YogaDimension(int paramInt1) {
this.mIntValue = paramInt1;
}
public static YogaDimension fromInt(int paramInt) {
if (paramInt != 0) {
if (paramInt == 1)
return HEIGHT;
StringBuilder stringBuilder = new StringBuilder("Unknown enum value: ");
stringBuilder.append(paramInt);
throw new IllegalArgumentException(stringBuilder.toString());
}
return WIDTH;
}
public final int intValue() {
return this.mIntValue;
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\yoga\YogaDimension.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.sushichet.sushichet.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class UserModel {
@SerializedName("value")
@Expose
private Integer value;
@SerializedName("data")
@Expose
private String data;
@SerializedName("user_details")
@Expose
private UserDetails userDetails;
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
static public class UserDetails {
public UserDetails(String id, String name, String email, String password, String role, String phone, List<String> address) {
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.role = role;
this.phone = phone;
this.address = address;
}
@SerializedName("id")
@Expose
private String id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("email")
@Expose
private String email;
@SerializedName("password")
@Expose
private String password;
@SerializedName("role")
@Expose
private String role;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("address")
@Expose
private List<String> address = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public List<String> getAddress() {
return address;
}
public void setAddress(List<String> address) {
this.address = address;
}
}
public UserModel(Integer value, UserDetails userDetails) {
this.value = value;
this.userDetails = userDetails;
}
}
|
package com.mohjacksi.snapdemo;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import java.io.IOException;
/**
* A simple {@link Fragment} subclass.
*/
public class EmptyFragment extends Fragment implements SurfaceHolder.Callback{
Camera camera;
SurfaceView mSurfaceView;
SurfaceHolder mSurfaceHolder;
public EmptyFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_empty, container, false);
mSurfaceView = view.findViewById(R.id.surfaceView);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
return view;
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
camera = Camera.open();
camera.setDisplayOrientation(90);
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewFrameRate(30);
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
camera.setParameters(parameters);
try {
camera.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
camera.startPreview();
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
}
|
package com.mega.mvc07.test;
public class Controller {
// 이 메서드에 정의된 기능을 처리하고 싶으면 우리는 어떻게 사용해야하나
public void call() {
System.out.println("내가 호출됨 일반메서드임");
}
}
|
package com.open.proxy.aop;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import com.google.common.base.Preconditions;
import com.open.proxy.aop.advisor.Advisor;
import com.open.proxy.aop.invocation.CglibMethodInvocation;
import com.open.proxy.aop.pointcut.MethodMatcher;
import com.open.proxy.aop.pointcut.PointCut;
/**
* @author jinming.wu
* @date 2014-4-7
*/
public class CgibProxy extends AbstractProxy implements MethodInterceptor {
public CgibProxy(TargetSource targetSource, Advisor advisor) {
super(targetSource, advisor);
}
@Override
public Object getProxy() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(targetSource.getTargetClazz());
enhancer.setInterfaces(targetSource.getInterfaces());
enhancer.setCallback(this);
Object enhanced = enhancer.create();
return enhanced;
}
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Preconditions.checkNotNull(targetSource);
Preconditions.checkNotNull(advisor);
com.open.proxy.aop.advice.MethodInterceptor methodInterceptor = (com.open.proxy.aop.advice.MethodInterceptor) advisor.getAdvice();
PointCut pointCut = advisor.getPointCut();
MethodMatcher methodMatcher = pointCut.getMethodMatcher();
if (methodMatcher != null && methodMatcher.matches(method, targetSource.getTargetClazz())) {
return methodInterceptor.invoke(new CglibMethodInvocation(targetSource.getTarget(), method, args,
methodProxy));
} else {
return methodProxy.invoke(targetSource.getTarget(), args);
}
}
}
|
package com.ovi.prescription.payload.response;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
@AllArgsConstructor
public class JWTLoginSuccessResponse {
private String email;
private boolean success;
private String token;
}
|
package com.zhuangjinxin.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
/**
* 使用配置文件中的单个属性
* 访问:http://localhost:8080/singleConfig
* 返回:My name is zhuangjinxin.
*/
@Controller
public class UseSingleConfigController {
//@Value("${name}")
//private String name;
@RequestMapping("/singleConfig")
@ResponseBody
public String printConfiguration(){
//return "My name is " + name +".";
return "My name is " + "zhuangjinxin" +".";
}
}
|
package potaskun.enot.math123teachv20;
public class Global {
public static String NAME_TECH ;
public static String ID_TECH ;
public static String HESH_KEY;
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import com.tencent.mm.plugin.setting.ui.setting.UnfamiliarContactDetailUI.d;
class UnfamiliarContactDetailUI$d$1 implements Runnable {
final /* synthetic */ d mVn;
UnfamiliarContactDetailUI$d$1(d dVar) {
this.mVn = dVar;
}
public final void run() {
if (this.mVn.mVi != null) {
this.mVn.mVi.ds(this.mVn.mUT.mUN.size(), this.mVn.mVk);
this.mVn.mUT.mUN.clear();
}
}
}
|
package com.jbk.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
public class RegistrationPage {
WebDriver driver=null;
public RegistrationPage(WebDriver driver) {
PageFactory.initElements(driver, this);
this.driver = driver;
}
}
|
package com.thinker.vdongthinker.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by zt on 2018/3/20.
*/
public abstract class BasePresenterFragment<T extends BaseFragmentPresenter> extends BaseFragment {
public T mPresenter ;
public abstract void initPresenter() ;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initPresenter();
}
}
|
package ro.pub.cs.systems.eim.practicaltest01var02;
import android.content.Intent;
public interface Constants {
String[] actionType = {Intent.ACTION_ANSWER,Intent.ACTION_DEFAULT};
}
|
package pa1;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import api.Graph;
import api.TaggedVertex;
/**
* An implementation of the graph interface.
* @author Matthew Smith and Mitchell Knoth
*
* @param <E>
*/
public class GraphService<E> implements Graph<E>{
private Map<Integer, List<Integer>> adjList = new HashMap<Integer, List<Integer>>();
private ArrayList<E> vertexList = new ArrayList<E>();
/**
* Allows us to add a vertex to our graph.
* @param vert
*/
public void addVertex(E vert) {
vertexList.add(vert);
adjList.put(vertexList.size() - 1, new ArrayList<Integer>());
}
/**
* Allows us to add an edge to our graph with a
* given source and destination vertex.
* @param source
* @param destination
*/
public void addEdge(E source, E destination) {
if(!vertexList.contains(source)) return;
if(!vertexList.contains(destination)) return;
Integer srcIdx = vertexList.indexOf(source);
Integer destIdx = vertexList.indexOf(destination);
if(adjList.get(srcIdx).contains(destIdx)) return;
else adjList.get(srcIdx).add(destIdx);
}
/**
* Returns an ArrayList of the actual objects constituting the vertices
* of this graph.
* @return
* ArrayList of objects in the graph
*/
@Override
public ArrayList<E> vertexData() {
return this.vertexList;
}
/**
* Returns an ArrayList that is identical to that returned by vertexData(), except
* that each vertex is associated with its incoming edge count.
* @return
* ArrayList of objects in the graph, each associated with its incoming edge count
*/
@Override
public ArrayList<TaggedVertex<E>> vertexDataWithIncomingCounts() {
ArrayList<TaggedVertex<E>> list = new ArrayList<TaggedVertex<E>>();
for(E vertex: vertexList) {
TaggedVertex taggedVertex = new TaggedVertex(vertex, getIncoming(vertexList.indexOf(vertex)).size());
list.add(taggedVertex);
}
return list;
}
/**
* Returns a list of outgoing edges, that is, a list of indices for neighbors
* of the vertex with given index.
* This method may throw ArrayIndexOutOfBoundsException if the index
* is invalid.
* @param index
* index of the given vertex according to vertexData()
* @return
* list of outgoing edges
*/
@Override
public List<Integer> getNeighbors(int index) {
return new ArrayList<Integer>(adjList.get(index));
}
/**
* Returns a list of incoming edges, that is, a list of indices for vertices
* having the given vertex as a neighbor.
* This method may throw ArrayIndexOutOfBoundsException if the index
* is invalid.
* @param index
* index of the given vertex according to vertexData()
* @return
* list of incoming edges
*/
@Override
public List<Integer> getIncoming(int index) {
List<Integer> inc = new ArrayList<>();
for(Integer i : adjList.keySet()) {
if (adjList.get(i).contains(index)) {
inc.add(i);
}
}
return inc;
}
}
|
package facing;
/**
* @author renyujie518
* @version 1.0.0
* @ClassName changGe.java
* @Description
* CC里面有一个土豪很喜欢一位女直播Kiki唱歌, 平时就经常给她点赞、 送礼、 私聊。
* 最近CC直播平台在举行 中秋之星主播唱歌比赛,
* 假设一开始该女主播的初始人气值为start, 能够晋升下一轮人气需要刚好达到end, 土豪给主播增加人气的可以采取的方法有:
* a. 点赞 花费x C币, 人气 + 2
* b. 送礼 花费y C币, 人气 * 2
* c. 私聊 花费z C币, 人气 - 2
* 其中 end 远大于start且start,end为偶数,
* 请写一个程序帮助土豪计算一下, 最少花费多少C币就能帮助该主播 Ki将人气刚好达到end(精确到达), 从而能够晋级下一轮?
* 输入描述: 第一行输入5个数据, 分别为: x y z start end, 每项数据以空格分开。
* 其中: 0<x, y, z<=10000, 0<start, end<=1000000
* 输出描述: 需要花费的最少C币。
* 示例1: 输入 3 100 1 2 6 输出 6
*
* 这是个纯code问题 最主要的就是递归+考虑边界
* 如果是单纯的递归会导致递归不完(偶数的问题+有-)所以要设置好basecase
* 限制1:点赞可以看做平凡解,效果还不如平凡解的的可以在递归中停止
* 限制2:成长的人气增长的幅度没有必要超过2*end
* @createTime 2021年08月12日 18:48:00
*/
public class changGe {
public static int minCoins1(int x, int y, int z, int start, int end) {
if (start > end) {
return -1;
}
//这里要解释下limitCoin 点赞 花费x C币, 人气 + 2的方式代价大,看做平凡解,假设全都要一步步加上去,共需要的代价是((end - start) / 2) * x
return process(0, end, x, y, z, start, end * 2, ((end - start) / 2) * x);
}
//preMoney 之前花了多少钱 可变
//aim 目标 固定
// jia chen jian 固定(对应x,y,z)
//curr当前来到的人气
//limitAim 人气大到什么程度不需要再尝试了 固定
//limitCoin 使用的币大到什么程度了不用再尝试了 固定
//返回最小币数
public static int process(int preMoney, int aim, int jia, int chen, int jian, int curr, int limitAim, int limitCoin) {
if (preMoney > limitCoin) {
return Integer.MAX_VALUE;
}
if (aim < 0) {
return Integer.MAX_VALUE;
}
if (aim == curr) {
return preMoney;
}
int result = Integer.MAX_VALUE;
//人气+2的方式
int p1 = process(preMoney + jia, aim, jia, chen, jian, curr + 2, limitAim, limitCoin);
if (p1 != Integer.MAX_VALUE) {
result = p1;
}
//人气*2
int p2 = process(preMoney + chen, aim, jia, chen, jian, curr *2, limitAim, limitCoin);
if (p2 != Integer.MAX_VALUE) {
result = Math.min(result, p2);
}
//人气-2
int p3 = process(preMoney + jian, aim, jia, chen, jian, curr -2, limitAim, limitCoin);
if (p3 != Integer.MAX_VALUE) {
result = Math.min(result, p3);
}
return result;
}
//二维动态的改动态规划
public static int minCoins2(int jia, int chen, int jian, int start, int end) {
if (start > end) {
return -1;
}
int limitCoin = ((end - start) / 2) * jia;
int limitAim = end * 2;
int[][] dp = new int[limitCoin + 1][limitAim + 1];//这个就是思路中的限制,把最终解限制在这么个矩阵中
//basecase
for (int preMonney = 0; preMonney <= limitCoin; preMonney++) {
for (int aim = 0; aim <= limitAim; aim++) {
if (aim == start) {
//初始的时候aim == start 疑问 ???为什么这里不设置为0即开始的时候所花的钱为0
dp[preMonney][aim] = preMonney;
} else {
dp[preMonney][aim] = Integer.MAX_VALUE;
}
}
}
for (int preMoney = limitCoin; preMoney >= 0; preMoney--) {
for (int aim = 0; aim <= limitAim; aim++) {
if (aim - 2 >= 0 && preMoney + jia <= limitCoin) {
dp[preMoney][aim] = Math.min(dp[preMoney][aim], dp[preMoney + jia][aim - 2]);
}
if (aim + 2 <= limitAim && preMoney + jian <= limitCoin) {
dp[preMoney][aim] = Math.min(dp[preMoney][aim], dp[preMoney + jian][aim + 2]);
}
if ((aim & 1) == 0) {
if (aim / 2 >= 0 && preMoney + chen <= limitCoin) {
dp[preMoney][aim] = Math.min(dp[preMoney][aim], dp[preMoney + chen][aim / 2]);
}
}
}
}
//上面的两层for循环是从右上到左下 行的含义是limitCoin,越小越好
//limitAim = end * 2 end一定在limitAim中
return dp[0][end];
}
public static void main(String[] args) {
int x = 6;
int y = 5;
int z = 1;
int start = 10;
int end = 30;
System.out.println(minCoins1(x, y, z, start, end));
System.out.println(minCoins2(x, y, z, start, end));
}
}
|
import java.util.Scanner;
public class ArquivoJava {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int x , y;
System.out.println("Digite um número com base em X ");
x = sc.nextInt(); // numero
System.out.println("Digite um número com base em Y ");
y = sc.nextInt(); // numero
if (x == 0 && y == 0) {
System.out.println("PONTO ORIGEM" );
} else if (x == 0 ) {
System.out.println("EIXO X" );
} else if (y == 0) {
System.out.println("EIXO Y" );
} else if (x > 0 && y > 0) {
System.out.println("Q1" );
} else if (x < 0 && y > 0) {
System.out.println("Q2" );
} else if (x < 0 && y < 0) {
System.out.println("Q3" );
} else {
System.out.println("Q4" );
}
sc.close();
}
}
|
package com.comm.test;
public class divideTest {
public static void main(String[] args) {
int a = 2;
int b = 2;
long c = 100l;
System.out.println((a*b)*100/c);
}
}
|
package com.choryan.spannabletextpacket.interf;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* Created by zhaolei on 2017/9/18.
*/
public interface LineDrawer {
void draw(Canvas c, Paint p, float left, int top, float right, int bottom, int baseLine);
}
|
package com.mrice.txl.appthree.ui;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.StaggeredGridLayoutManager;
import com.mrice.txl.appthree.R;
import com.mrice.txl.appthree.adapter.RebackAdapter;
import com.mrice.txl.appthree.base.BaseActivity;
import com.mrice.txl.appthree.databinding.LayoutRebackBinding;
import com.mrice.txl.appthree.ui.me.RebackItem;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by app on 2017/10/12.
*/
public class RebackActivity extends BaseActivity<LayoutRebackBinding> {
private RebackAdapter rebackAdapter;
private int type = -1;
private List<RebackItem> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_reback);
showContentView();
type = getIntent().getIntExtra("type", type);
setTitle("往期回顾");
bindingView.lv.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
// 需加,不然滑动不流畅
bindingView.lv.setNestedScrollingEnabled(false);
bindingView.lv.setHasFixedSize(false);
bindingView.lv.setItemAnimator(new DefaultItemAnimator());
rebackAdapter = new RebackAdapter(this);
bindingView.lv.setAdapter(rebackAdapter);
switch (type) {
case 1:
list = createListDLT();
bindingView.title.setText("大乐透");
break;
case 2:
list = createListSSQ();
bindingView.title.setText("双色球");
break;
case 3:
list = createList7LC();
bindingView.title.setText("七乐彩");
break;
case 4:
list = createList7XC();
bindingView.title.setText("七星彩");
break;
}
rebackAdapter.addAll(list);
rebackAdapter.notifyDataSetChanged();
}
private List<RebackItem> createListDLT() {
List<RebackItem> l = new ArrayList<>();
RebackItem r = new RebackItem();
r.setQq("17118");
r.setBall1("05");
r.setBall2("07");
r.setBall3("13");
r.setBall4("29");
r.setBall5("35");
r.setBall6("03");
r.setBall7("08");
r.setType(1);
l.add(r);
RebackItem rr;
for (int i = 17117; i > 17080; i--) {
int[] s = randomCommon(1, 33, 7);
rr = new RebackItem();
rr.setQq("" + i);
rr.setBall1(exchange(s[0]));
rr.setBall2(exchange(s[1]));
rr.setBall3(exchange(s[2]));
rr.setBall4(exchange(s[3]));
rr.setBall5(exchange(s[4]));
rr.setBall6(exchange(s[5]));
rr.setBall7(exchange(s[6]));
rr.setType(1);
l.add(rr);
}
return l;
}
private List<RebackItem> createListSSQ() {
List<RebackItem> l = new ArrayList<>();
RebackItem r = new RebackItem();
r.setQq("17119");
r.setBall1("09");
r.setBall2("16");
r.setBall3("21");
r.setBall4("25");
r.setBall5("26");
r.setBall6("31");
r.setBall7("14");
r.setType(2);
l.add(r);
RebackItem r2 = new RebackItem();
r2.setQq("17118");
r2.setBall1("08");
r2.setBall2("09");
r2.setBall3("15");
r2.setBall4("22");
r2.setBall5("30");
r2.setBall6("33");
r2.setBall7("16");
r2.setType(2);
l.add(r2);
RebackItem r3 = new RebackItem();
r3.setQq("17117");
r3.setBall1("01");
r3.setBall2("02");
r3.setBall3("08");
r3.setBall4("11");
r3.setBall5("14");
r3.setBall6("21");
r3.setBall7("09");
r3.setType(2);
l.add(r3);
RebackItem r4 = new RebackItem();
r4.setQq("17116");
r4.setBall1("05");
r4.setBall2("07");
r4.setBall3("13");
r4.setBall4("29");
r4.setBall5("35");
r4.setBall6("03");
r4.setBall7("08");
r4.setType(2);
l.add(r4);
RebackItem r5 = new RebackItem();
r5.setQq("17115");
r5.setBall1("04");
r5.setBall2("10");
r5.setBall3("11");
r5.setBall4("25");
r5.setBall5("30");
r5.setBall6("31");
r5.setBall7("01");
r5.setType(2);
l.add(r5);
RebackItem r6 = new RebackItem();
r6.setQq("17114");
r6.setBall1("06");
r6.setBall2("12");
r6.setBall3("13");
r6.setBall4("15");
r6.setBall5("18");
r6.setBall6("26");
r6.setBall7("13");
r6.setType(2);
l.add(r6);
RebackItem rr;
for (int i = 17113; i > 17080; i--) {
int[] s = randomCommon(1, 33, 7);
rr = new RebackItem();
rr.setQq("" + i);
rr.setBall1(exchange(s[0]));
rr.setBall2(exchange(s[1]));
rr.setBall3(exchange(s[2]));
rr.setBall4(exchange(s[3]));
rr.setBall5(exchange(s[4]));
rr.setBall6(exchange(s[5]));
rr.setBall7(exchange(s[6]));
rr.setType(2);
l.add(rr);
}
return l;
}
private List<RebackItem> createList7LC() {
List<RebackItem> l = new ArrayList<>();
RebackItem r = new RebackItem();
r.setQq("17118");
r.setBall1("05");
r.setBall2("07");
r.setBall3("13");
r.setBall4("29");
r.setBall5("35");
r.setBall6("03");
r.setBall7("08");
r.setType(3);
l.add(r);
RebackItem rr;
for (int i = 17117; i > 17080; i--) {
int[] s = randomCommon(1, 33, 7);
rr = new RebackItem();
rr.setQq("" + i);
rr.setBall1(exchange(s[0]));
rr.setBall2(exchange(s[1]));
rr.setBall3(exchange(s[2]));
rr.setBall4(exchange(s[3]));
rr.setBall5(exchange(s[4]));
rr.setBall6(exchange(s[5]));
rr.setBall7(exchange(s[6]));
rr.setType(3);
l.add(rr);
}
return l;
}
private List<RebackItem> createList7XC() {
List<RebackItem> l = new ArrayList<>();
RebackItem r = new RebackItem();
r.setQq("17119");
r.setBall1("2");
r.setBall2("6");
r.setBall3("6");
r.setBall4("5");
r.setBall5("0");
r.setBall6("3");
r.setBall7("6");
r.setType(4);
l.add(r);
RebackItem rr;
for (int i = 17118; i > 17080; i--) {
int[] s = randomCommon(0, 9, 7);
rr = new RebackItem();
rr.setQq("" + i);
rr.setBall1(s[0] + "");
rr.setBall2(s[1] + "");
rr.setBall3(s[2] + "");
rr.setBall4(s[3] + "");
rr.setBall5(s[4] + "");
rr.setBall6(s[5] + "");
rr.setBall7(s[6] + "");
rr.setType(4);
l.add(rr);
}
return l;
}
private String exchange(int n) {
String s = String.valueOf(n);
if (s.length() == 1) {
return "0" + s;
}
return s;
}
public static int[] randomCommon(int min, int max, int n) {
if (n > (max - min + 1) || max < min) {
return null;
}
int[] result = new int[n];
int count = 0;
while (count < n) {
int num = (int) (Math.random() * (max - min)) + min;
boolean flag = true;
for (int j = 0; j < n; j++) {
if (num == result[j]) {
flag = false;
break;
}
}
if (flag) {
result[count] = num;
count++;
}
}
Arrays.sort(result);
return result;
}
}
|
/*******************************************************************************
* QBiC Project qNavigator enables users to manage their projects.
* Copyright (C) "2016” Christopher Mohr, David Wojnar, Andreas Friedrich
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************/
package life.qbic.xml.manager;
import java.io.File;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.transform.stream.StreamSource;
import life.qbic.xml.notes.Notes;
public class HistoryReader {
/**
* returns a {@link historybeans.Notes} instance.
*
* @param notes a xml file that contains notes.
* @return historybeans.Notes which is a bean representation of the notes saved in openbis
* @throws JAXBException
*/
public static JAXBElement<Notes> parseNotes(File notes)
throws JAXBException {
JAXBContext jaxbContext;
jaxbContext = JAXBContext.newInstance("lif.qbic.xml.notes");
javax.xml.bind.Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StreamSource source = new StreamSource(notes);
JAXBElement<Notes> customerElement =
unmarshaller.unmarshal(source, Notes.class);
return customerElement;
}
/**
* returns a {@link historybeans.Notes} instance.
*
* @param notes a xml string that contains notes.
* @return historybeans.Notes which is a bean representation of the notes saved in openbis
* @throws JAXBException
*/
public static JAXBElement<Notes> parseNotes(String notes)
throws JAXBException {
JAXBContext jaxbContext;
jaxbContext = JAXBContext.newInstance("life.qbic.xml.notes");
javax.xml.bind.Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StreamSource source = new StreamSource(new StringReader(notes));
JAXBElement<Notes> customerElement =
unmarshaller.unmarshal(source, Notes.class);
return customerElement;
}
/**
* Write the jaxbelem (contains the notes as beans) back as xml into the outputstream
* @param jaxbelem
* @param os
* @throws JAXBException
*/
public static void writeNotes(JAXBElement<Notes> jaxbelem, OutputStream os) throws JAXBException{
JAXBContext jaxbContext;
jaxbContext = JAXBContext.newInstance("life.qbic.xml.notes");
javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(jaxbelem, os);
}
/**
* writes notes as a xml into the stringwriter. After that method the string can be retrieved with stringwriter.tostring
* @param jaxbelem
* @param sw
* @throws JAXBException
*/
public static void writeNotes(JAXBElement<Notes> jaxbelem, StringWriter sw) throws JAXBException{
JAXBContext jaxbContext;
jaxbContext = JAXBContext.newInstance("life.qbic.xml.notes");
javax.xml.bind.Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(jaxbelem, sw);
}
}
|
package com.chuxin.family.settings;
import com.chuxin.family.app.CxRootActivity;
import com.chuxin.family.global.CxGlobalParams;
import com.chuxin.family.net.UserApi;
import com.chuxin.family.net.ConnectionManager.JSONCaller;
import com.chuxin.family.parse.been.CxUserProfile;
import com.chuxin.family.resource.CxResourceRaw;
import com.chuxin.family.resource.CxResourceString;
import com.chuxin.androidpush.sdk.push.RKPush;
import com.chuxin.family.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CxSetPushSound extends CxRootActivity {
private ImageView firstImgView, secondImgView, thirdImgView;
private LinearLayout firstSetLayout, secondSetLayout, thirdSetLayout;
// private int mSetSoundType = 0; //默认是第一种(调皮:老公版; 三弦音:老婆),依次加1,分别为:1--老婆/老公,2--系统通知声音
private Button mSaveReturnBtn;
private SoundPool mSoundPlayer/*, mNotificationPlayer*/;
private int firstSound, secondSound, thirdSound;
boolean tempSelected = false;
String soundStr = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cx_fa_activity_set_push_sound);
new RkInitPlayer().execute(); //位置调节,确保初始化SoundPool成功
TextView mFirstSoundText = (TextView) findViewById(R.id.cx_fa_setting_sound_first_tv);
TextView mSecondSoundText = (TextView) findViewById(R.id.cx_fa_setting_sound_second_tv);
mFirstSoundText.setText(CxResourceString.getInstance().str_setting_sound_push_first_sound);
mSecondSoundText.setText(CxResourceString.getInstance().str_setting_sound_push_second_sound);
mSaveReturnBtn = (Button)findViewById(R.id.cx_fa_activity_title_back);
mSaveReturnBtn.setText(getString(R.string.cx_fa_save_and_back_text));
mSaveReturnBtn.setGravity(Gravity.CENTER);
firstSetLayout = (LinearLayout)findViewById(R.id.cx_fa_push_sound_first_set_btn);
secondSetLayout = (LinearLayout)findViewById(R.id.cx_fa_push_sound_second_set_btn);
thirdSetLayout = (LinearLayout)findViewById(R.id.cx_fa_push_sound_third_set_btn);
firstImgView = (ImageView)findViewById(R.id.cx_fa_first_sound_selected);
secondImgView = (ImageView)findViewById(R.id.cx_fa_second_sound_selected);
thirdImgView = (ImageView)findViewById(R.id.cx_fa_third_sound_selected);
int tempPushType = CxGlobalParams.getInstance().getPushSoundType();
if (0 == tempPushType) {
firstImgView.setVisibility(View.VISIBLE);
}else if(1 == tempPushType){
secondImgView.setVisibility(View.VISIBLE);
}else{
thirdImgView.setVisibility(View.VISIBLE);
}
firstSetLayout.setOnClickListener(pushSoundSetListener);
secondSetLayout.setOnClickListener(pushSoundSetListener);
thirdSetLayout.setOnClickListener(pushSoundSetListener);
mSaveReturnBtn.setOnClickListener(pushSoundSetListener);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (tempSelected) {
try {
UserApi.getInstance().updateUserProfile(null, null, soundStr, null, null, setPushSoundCaller);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
if (null != mSoundPlayer) {
mSoundPlayer.release();
}
super.onDestroy();
}
class RkInitPlayer extends AsyncTask<Object, Integer, Integer>{
@Override
protected Integer doInBackground(Object... params) {
mSoundPlayer = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
firstSound = mSoundPlayer.load(CxSetPushSound.this, CxResourceRaw.getInstance().raw_push_first, 1);
secondSound = mSoundPlayer.load(CxSetPushSound.this, CxResourceRaw.getInstance().raw_push, 1);
// mNotificationPlayer = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100);
// thirdSound = mNotificationPlayer.load(RkSetPushSound.this, RingtoneManager.TYPE_NOTIFICATION, 1);
return null;
}
}
OnClickListener pushSoundSetListener = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cx_fa_push_sound_first_set_btn:
firstImgView.setVisibility(View.VISIBLE);
secondImgView.setVisibility(View.INVISIBLE);
thirdImgView.setVisibility(View.INVISIBLE);
tempSelected = true;
CxGlobalParams.getInstance().setPushSoundType(0);
if(CxGlobalParams.getInstance().getVersion()==0){
soundStr = "w_rk_naughty_push.caf";
RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://"
+ getPackageName() + "/raw/" + "rk_fa_role_push_first_s");
}else{
soundStr = "h_rk_naughty_push.caf";
RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://"
+ getPackageName() + "/raw/" + "rk_fa_role_push_first");
}
try {
mSoundPlayer.play(firstSound, 0.5f, 0.5f, 1, 1, 1.0f);
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case R.id.cx_fa_push_sound_second_set_btn:
firstImgView.setVisibility(View.INVISIBLE);
secondImgView.setVisibility(View.VISIBLE);
thirdImgView.setVisibility(View.INVISIBLE);
tempSelected = true;
CxGlobalParams.getInstance().setPushSoundType(1);
if(CxGlobalParams.getInstance().getVersion()==0){
soundStr = "w_rk_fa_role_push.caf";
RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://"
+ getPackageName() + "/raw/" + "rk_fa_role_push_s");
}else{
soundStr = "h_rk_fa_role_push.caf";
RKPush.S_NOTIFY_SOUND_URI = Uri.parse("android.resource://"
+ getPackageName() + "/raw/" + "rk_fa_role_push");
}
try {
mSoundPlayer.play(secondSound, 0.5f, 0.5f, 1, 1, 1.0f);
} catch (Exception e1) {
e1.printStackTrace();
}
break;
case R.id.cx_fa_push_sound_third_set_btn:
firstImgView.setVisibility(View.INVISIBLE);
secondImgView.setVisibility(View.INVISIBLE);
thirdImgView.setVisibility(View.VISIBLE);
soundStr = "default";
tempSelected = true;
CxGlobalParams.getInstance().setPushSoundType(2);
RKPush.S_NOTIFY_SOUND_URI = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.cx_fa_activity_title_back:
if (tempSelected) {
try {
UserApi.getInstance().updateUserProfile(null, null, soundStr, null, null, setPushSoundCaller);
} catch (Exception e) {
e.printStackTrace();
}
}
CxSetPushSound.this.finish();
break;
default:
tempSelected = false;
break;
}
}
};
protected void onPause() {
super.onPause();
overridePendingTransition(R.anim.tran_pre_in, R.anim.tran_pre_out);
};
JSONCaller setPushSoundCaller = new JSONCaller() {
@Override
public int call(Object result) {
if (null == result) {
return -1;
}
CxUserProfile userProfile = null;
try {
userProfile = (CxUserProfile)result;
} catch (Exception e) {
e.printStackTrace();
}
if (null == userProfile) {
return -2;
}
if (0 != userProfile.getRc()) {
return userProfile.getRc();
}
if (null == userProfile.getData()){
return -4;
}
if (null == userProfile.getData().getPush_sound()) {
return -3;
}
return 0;
}
};
}
|
package GUI_Components;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Segment;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Objects;
/**
* Cette classe est customisée et permet d'accueillir un meilleur {@link JPasswordField}.
*
* Le texte entré est centré, on peut choisir le type d'input, et si l'input doit être caché ou non.
*
* Cette classe hérite de {@link JPasswordField}
*
* @author Hugues
*/
public class BEGEOT_BUNOUF_CustomJTextField extends JPasswordField
{
// "NUMERIC",
// "DECIMAL",
// "LOWER_ALPHABET",
// "UPPER_ALPHABET",
// "ALPHABET",
// "ALPHA_NUMERIC",
// "ALL"
private final String type;
private final boolean password;
public BEGEOT_BUNOUF_CustomJTextField(String type, boolean password, int maxChar)
{
this.type = type;
this.password = password;
if(0 < maxChar) setDocument(new BEGEOT_BUNOUF_Limit_JTextField(maxChar));
setHorizontalAlignment(JTextField.CENTER);
validInput();
// Pour cacher si mot de passe
if(password) setEchoChar('*');
else setEchoChar((char)0);
}
/**
* Verifies if the currently typed characted is valid or not.
* If it isn't, or if the maximum size of the field is reached, we edit the character out.
*/
private void validInput()
{
addKeyListener(new KeyAdapter()
{
public void keyTyped(KeyEvent e)
{
char ch = e.getKeyChar();
if (!isCorrect(ch) && ch != '\b') e.consume();
}
});
}
/**
* Verifies if the currently typed characted is valid or not.
* @return true if the currently typed characted is valid or not, false otherwise.
*/
private boolean isCorrect(char ch)
{
boolean numeric = ch >= '0' && ch <= '9';
boolean decimal = numeric || ch == '.';
boolean lowLetter = ch >= 'a' && ch <= 'z';
boolean upLetter = ch >= 'A' && ch <= 'Z';
if(type.equals("NUMERIC")) return numeric;
if(type.equals("DECIMAL")) return decimal;
if(type.equals("LOWER_ALPHABET")) return lowLetter;
if(type.equals("UPPER_ALPHABET")) return upLetter;
if(type.equals("ALPHABET")) return lowLetter || upLetter;
if(type.equals("ALPHA_NUMERIC")) return numeric || lowLetter || upLetter;
return true; // in case of all accepted
}
/**
* Returns the text contained in this <code>TextComponent</code>.
* @return the text
*/
private String Field()
{
Document doc = getDocument();
Segment txt = new Segment();
try { doc.getText(0, doc.getLength(), txt); /* use the non-String API */}
catch ( BadLocationException e) { return null; }
char[] retValue = new char[txt.count];
System.arraycopy(txt.array, txt.offset, retValue, 0, txt.count);
return new String(retValue);
}
/**
* Returns the length of the input.
* @return the length of the input
*/
public int length() { return Objects.requireNonNull(Field()).length(); }
/**
* This function is to be associated to a button.
* If the password attribute is true,
* then the password will be reveal if it is currently hidden,
* or hidden it it is currently displayed.
*/
public void hideOrReveal()
{
if(password)
{
if(echoCharIsSet())
setEchoChar((char)0);
else
setEchoChar('*');
}
}
}
|
package spring.cloud.samples.role.hierarchy.yml.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.SecurityExpressionHandler;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler;
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password("{noop}111").roles("ADMIN")
.and()
.withUser("user").password("{noop}111").roles("USER");
}
@Bean
public RoleHierarchiesMap roleHierarchiesMap() {
return new RoleHierarchiesMap();
}
@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
roleHierarchy.setHierarchy(roleHierarchiesMap().toString());
return roleHierarchy;
}
@Bean
public SecurityExpressionHandler<FilterInvocation> expressionHandler() {
DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
webSecurityExpressionHandler.setRoleHierarchy(roleHierarchy());
return webSecurityExpressionHandler;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated().expressionHandler(expressionHandler())
.and()
.httpBasic();
}
}
|
package com.simpson.kisen.fan.controller;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.simpson.kisen.fan.model.service.FanService;
import com.simpson.kisen.fan.model.vo.Fan;
import com.simpson.kisen.payment.model.service.PaymentService;
import com.simpson.kisen.payment.model.vo.Payment;
import com.simpson.kisen.unofficial.model.vo.UnofficialDemand;
import lombok.extern.slf4j.Slf4j;
@Controller
@Slf4j
@RequestMapping("/mypage")
@SessionAttributes({"loginMember", "principal"})
public class MyPageController {
@Autowired
private BCryptPasswordEncoder bcryptPasswordEncoder;
@Autowired
private PaymentService paymentService;
@Autowired
private FanService fanService;
@GetMapping("/mypagePay.do")
public void mypage(Authentication authentication, Model model){
try {
Fan principal = (Fan) authentication.getPrincipal();
List<Payment> payList = paymentService.selectAllList(principal.getFanNo());
model.addAttribute("loginMember", principal);
model.addAttribute("payList", payList);
log.info("payList = {}", payList);
log.info("authentication = {}", authentication);
// authentication = org.springframework.security.authentication.UsernamePasswordAuthenticationToken@23abe407: Principal: Member(id=honggd, password=$2a$10$qHHeJGgQ9teamJyIJFXbyOBtl7nIsQ37VP2jrz89dnDA7LgzS.nYi, name=카길동, gender=M, birthday=2021-05-04, email=honggd@naver.com, phone=01012341234, address=서울시 강남구, hobby=[운동, 등산], enrollDate=2021-05-20, authorities=[ROLE_USER], enabled=true); Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: B95C1041773474D93729781512D4490A; Granted Authorities: ROLE_USER
log.info("principal = {}", principal);
} catch (Exception e) {
log.error("결제내역 불러오기 오류!", e);
throw e;
}
}
@GetMapping("/mypageform.do")
public void mypageform(Authentication authentication, Model model){
try {
Fan principal = (Fan) authentication.getPrincipal();
List<UnofficialDemand > udList = paymentService.selectUdList(principal.getFanNo());
model.addAttribute("loginMember", principal);
model.addAttribute("udList",udList );
log.info("udList = {}", udList);
log.info("authentication = {}", authentication);
// authentication = org.springframework.security.authentication.UsernamePasswordAuthenticationToken@23abe407: Principal: Member(id=honggd, password=$2a$10$qHHeJGgQ9teamJyIJFXbyOBtl7nIsQ37VP2jrz89dnDA7LgzS.nYi, name=카길동, gender=M, birthday=2021-05-04, email=honggd@naver.com, phone=01012341234, address=서울시 강남구, hobby=[운동, 등산], enrollDate=2021-05-20, authorities=[ROLE_USER], enabled=true); Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: B95C1041773474D93729781512D4490A; Granted Authorities: ROLE_USER
log.info("principal = {}", principal);
} catch (Exception e) {
log.error("결제내역 불러오기 오류!", e);
throw e;
}
}
@GetMapping("/mypageMember.do")
public void mypageMember(Authentication authentication, Model model){
try {
Fan principal = (Fan) authentication.getPrincipal();
model.addAttribute("loginMember", principal);
log.debug("authentication = {}", authentication);
log.debug("principal = {}", principal);
} catch (Exception e) {
log.error("회원 불러오기 오류!", e);
throw e;
}
}
@PostMapping("/updateMypage.do")
public String updateMypgae (@ModelAttribute Fan updateFan, @RequestParam String addressExt1,
@RequestParam String addressExt2, @RequestParam String addressExt3,Authentication oldAuthentication,
RedirectAttributes redirectAttr, @RequestParam String fanNo) {
log.info("수정요청 fan = {}", updateFan);
try {
String rawPassword = updateFan.getPassword();
String encodedPassword = bcryptPasswordEncoder.encode(rawPassword);
// member에 암호화된 비밀번호 다시 세팅
updateFan.setPassword(encodedPassword);
updateFan.setAddress(updateFan.getAddress() + "-" + addressExt1 + "-" + addressExt2 + "-" + addressExt3);
updateFan.setFanNo(fanNo);
Collection<? extends GrantedAuthority> oldAuthorities =
oldAuthentication.getAuthorities();
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
for(GrantedAuthority auth : oldAuthorities) {
SimpleGrantedAuthority simpleAuth =
new SimpleGrantedAuthority(auth.getAuthority());
// 문자열을 인자로 auth객체생성
authorities.add(simpleAuth);
}
updateFan.setAuthorities(authorities);
log.info("담긴내용 -fan = {}", updateFan);
int result = fanService.updateFan(updateFan);
//새로운 authentication객체 생성
Authentication newAuthentication =
new UsernamePasswordAuthenticationToken(
updateFan,
oldAuthentication.getCredentials(),
oldAuthentication.getAuthorities()
);
log.info("담긴내용 -Authentication = {}", newAuthentication);
//SecurityContextHolder - SecurityContext 하위에 설정
SecurityContextHolder.getContext().setAuthentication(newAuthentication);
} catch(Exception e) {
log.error("회원 정보 수정 오류!", e);
throw e;
}
return "redirect:/mypage/mypageMember.do";
}
@PostMapping("/deleteFan.do")
public String deleteFan(@RequestParam String fanId, RedirectAttributes redirectAttr) {
try {
log.info("fanId={}",fanId);
//1. 업무로직
int result = fanService.deleteFan(fanId);
//2. 사용자피드백
redirectAttr.addFlashAttribute("msg", "회원 탈퇴 성공!");
} catch(Exception e) {
log.error("회원 탈퇴 오류!", e);
throw e;
}
return "redirect:/member/logout.do";
}
}
|
package rs.code9.taster.service;
import java.util.List;
import rs.code9.taster.model.Category;
/**
* Service for category management.
*
* @author d.gajic
*
*/
public interface CategoryService {
/**
* Find and return category with passed id.
*
* @param id of the {@link Category} to return
* @return {@link Category} with passed id or null if not found
*/
Category findOne(Long id);
/**
* Return back all existing categories.
*
* @return list of existing categories, empty list if there are no categories
*/
List<Category> findAll();
/**
* Saved {@link Category} and return saved instance (with id set).
*
* @param category to be saved
* @return saved instance
*/
Category save(Category category);
/**
* Remove category with passed id.
*
* @param id of the category to be removed
* @throws IllegalArgumentException if there is no {@link Category} with passed id
*/
void remove(Long id) throws IllegalArgumentException;
}
|
/*
* 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 javapractice;
/**
*
* @author Dilruba Showkat
*/
public class Circle implements FactoryShape{
public void shape(int param)
{
double area = Math.PI*param*param;
System.out.println("Drawing a with param "+ "with param " + param +"Area "+area);
}
}
|
package com.qswy.app.adapter;
import android.content.Context;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.qswy.app.R;
import com.qswy.app.model.AngelShops;
import com.qswy.app.model.TempAngel;
import com.qswy.app.utils.Contents;
import com.qswy.app.utils.ImageLoaderController;
import java.util.ArrayList;
/**
* Created by ryl on 2016/11/24.
*/
public class AngelStoreAdapter extends MyBaseAdapter<AngelShops> {
public AngelStoreAdapter(Context context, int itemLayoutResId, ArrayList<AngelShops> list) {
super(context, itemLayoutResId, list);
}
@Override
public void convert(ViewHolder viewHolder, AngelShops item, int position) {
ImageView headImage = viewHolder.getView(R.id.iv_aasi_head);
TextView nameTv = viewHolder.getView(R.id.tv_aasi_name);
TextView ageTv = viewHolder.getView(R.id.tv_aasi_age);
TextView contentTv = viewHolder.getView(R.id.tv_aasi_content);
TextView addressTv = viewHolder.getView(R.id.tv_aasi_address);
ImageLoader.getInstance().displayImage(Contents.URL+item.getImgUrl(),headImage, ImageLoaderController.getOptions(R.mipmap.icon_grandma));
nameTv.setText(item.getName());
// ageTv.setText();
contentTv.setText(item.getRemark());
addressTv.setText("住址:"+item.getAddress());
}
}
|
package com.libedi.jpa.onetoone.target;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import lombok.Getter;
import lombok.Setter;
/**
* Member
* : 일대일 대상 테이블에 외래키. 대상테이블은 LOCKER.
* : 연관관계의 주인은 locker이므로 mappedBy를 선언했다.
*
* @author Sang-jun, Park
* @since 2019. 04. 29
*/
@Entity(name = "Member_target")
@Table(name = "MEMBER_TARGET")
@Getter @Setter
public class Member {
@Id
@GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
private String username;
/*
* 외래키가 대상 테이블에 있을 경우, 단방향인 경우에는 주 테이블의 엔티티에서
* 대상 테이블로 매핑할 수 있는 방법이 없다. (당연하지... 알 수가 없잖아...)
* 그래서 양방향만 허용한다.
*/
@OneToOne(mappedBy = "member")
private Locker locker;
}
|
package bif3.swe1.seb;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class MainServer implements Runnable {
private static ServerSocket _listener = null;
//arena für Kampfaustragung
private static final bif3.swe1.seb.BattleGrounds arena = new bif3.swe1.seb.BattleGrounds();
//todo user logedin for Auth-Token
private static final bif3.swe1.seb.LoginHandler loginHandler = new bif3.swe1.seb.LoginHandler();
public MainServer() {
}
public static void main(String[] args) {
System.out.println("start server");
try {
_listener = new ServerSocket(10001, 5);
} catch (IOException e) {
e.printStackTrace();
return;
}
Runtime.getRuntime().addShutdownHook(new Thread(new MainServer()));
try {
while (true) {
Socket client = _listener.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
RequestContext requestHeader = new RequestContext();
String message;
StringBuilder header = new StringBuilder();
do {
//find method, path and keypairs
message = reader.readLine().trim();
//KeyPairs zwischenspeichern
header.append(message).append("\n");
System.out.println("srv: received: " + message);
} while (!message.isEmpty());
String response = "";
if (requestHeader.setHeaderLines(header.toString())) {
StringBuilder content = new StringBuilder();
while (reader.ready()) {
content.append((char) reader.read());
}
System.out.println("Content:\n" + content + "\ncontent end");
RequestHandler requestHandler = new RequestHandler(requestHeader.getMethod(),
requestHeader.getPath(), content.toString(), arena, loginHandler);
if (requestHeader.getKeyMap().containsKey("authorization")) {
requestHandler.setAuthorisation(requestHeader.getKeyMap().get("authorization"));
}
if (requestHeader.getKeyMap().containsKey("content-type")) {
requestHandler.setContentType(requestHeader.getKeyMap().get("content-type"));
}
response = requestHandler.work();
//
} else
response = MessageHandler.createHttpResponseMessage("400 BAD REQUEST");
System.out.println("responding:");
System.out.println(response);
System.out.println("");
writer.write(response);
writer.flush();
reader.close();
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
_listener.close();
} catch (IOException e) {
e.printStackTrace();
}
_listener = null;
System.out.println("close server");
}
}
|
package com.frank.dagger2demo.component;
import com.frank.dagger2demo.activity.MainActivity;
import com.frank.dagger2demo.enity.ZhaiNan;
import com.frank.dagger2demo.module.ActivityModule;
import com.frank.dagger2demo.module.ShangjiaAModule;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by Frank on 2017/7/18.
*/
@Singleton
@Component(modules = {ShangjiaAModule.class,ActivityModule.class})
public interface WaimaiPingTai {
ZhaiNan waimai();
void zhuru(ZhaiNan zhaiNan);
void inject(MainActivity mainActivity);
}
|
package jang.hyun.mapper;
public interface TimeMapper {
public String getTime2();
}
|
package com.udacity.jdnd.course3.critter.pet;
import com.udacity.jdnd.course3.critter.user.CustomerService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Transactional
@Service
public class PetService {
@Autowired
ModelMapper mapper;
PetRepository petRepository;
CustomerService customerService;
public PetService(PetRepository petRepository, CustomerService customerService) {
this.petRepository = petRepository;
this.customerService = customerService;
}
public Pet savePet(Pet pet) {
pet = petRepository.save(pet);
if(pet.getCustomer() != null) {
customerService.addPetToOwner(pet, pet.getCustomer());
};
return pet;
}
public Pet getPet(long petId) {
Pet pet = petRepository.getPetById(petId);
return pet;
}
public List<Pet> getPets() {
return petRepository.findAll();
}
public List<Pet> getPetsByOwner(Long ownerId) {
return petRepository.getPetsByCustomerId(ownerId);
}
}
|
//
// GCALDaemon is an OS-independent Java program that offers two-way
// synchronization between Google Calendar and various iCalalendar (RFC 2445)
// compatible calendar applications (Sunbird, Rainlendar, iCal, Lightning, etc).
//
// Apache License
// Version 2.0, January 2004
// http://www.apache.org/licenses/
//
// Project home:
// http://gcaldaemon.sourceforge.net
//
package org.gcaldaemon.gui.editors;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import org.gcaldaemon.core.PasswordEncoder;
import org.gcaldaemon.gui.ConfigEditor;
import org.gcaldaemon.gui.Messages;
import org.gcaldaemon.gui.config.MainConfig;
/**
* Password property editor.
*
* Created: May 25, 2007 20:00:00 PM
*
* @author Andras Berkes
*/
public final class PasswordEditor extends AbstractEditor implements KeyListener {
// --- SERIALVERSION ---
private static final long serialVersionUID = 542716571632242103L;
// --- GUI ---
private final JLabel label = new JLabel();
private final JPasswordField password = new JPasswordField();
// --- CONSTRUCTOR ---
public PasswordEditor(MainConfig config, ConfigEditor editor, String key)
throws Exception {
super(config, editor, key);
BorderLayout borderLayout = new BorderLayout();
borderLayout.setHgap(5);
setLayout(borderLayout);
add(label, BorderLayout.WEST);
add(password, BorderLayout.CENTER);
label.setText(Messages.getString(key) + ':');
try {
password.setText(config.getPasswordProperty(key));
} catch (Exception ignored) {
password.setText("XXXXX");
password.setForeground(Color.RED);
}
password.addKeyListener(this);
label.setPreferredSize(LABEL_SIZE);
}
// --- VALUE CHANGED ---
public final void keyReleased(KeyEvent evt) {
String pass = new String(password.getPassword());
try {
if (pass.length() > 0) {
pass = PasswordEncoder.encodePassword(pass);
}
config.setConfigProperty(key, pass);
editor.status(key, pass);
password.setForeground(Color.BLACK);
} catch (Exception ignored) {
password.setForeground(Color.RED);
return;
}
}
public final void keyPressed(KeyEvent evt) {
}
public final void keyTyped(KeyEvent evt) {
}
}
|
package solution;
/**
* User: jieyu
* Date: 12/19/16.
*/
public class LargestNumber179 {
public String largestNumber(int[] nums) {
quickSort(nums, 0, nums.length - 1);
StringBuilder sb = new StringBuilder();
boolean isZero = true;
for (int num : nums) {
if (num != 0) isZero = false;
sb.insert(0, num);
}
return (isZero) ? "0" : sb.toString();
}
private void quickSort(int[] nums, int left, int right) {
if (right > left) {
int pivotIndex = left + (right - left) / 2;
int newPivotIndex = partition(nums, left, right, pivotIndex);
quickSort(nums, left, newPivotIndex - 1);
quickSort(nums, newPivotIndex + 1, right);
}
}
private int partition(int[] nums, int left, int right, int pivotIndex) {
int temp = nums[right];
nums[right] = nums[pivotIndex];
nums[pivotIndex] = temp;
int storeIndex = left;
for (int i = left; i <= right; ++i) {
String a = String.valueOf(nums[i]) + String.valueOf(nums[right]);
String b = String.valueOf(nums[right]) + String.valueOf(nums[i]);
if (Long.parseLong(a) <= Long.parseLong(b)) {
if (storeIndex != i) {
temp = nums[storeIndex];
nums[storeIndex] = nums[i];
nums[i] = temp;
}
storeIndex++;
}
}
return storeIndex - 1;
}
}
|
package com.shopify.shipment.popup;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@JsonIgnoreProperties(ignoreUnknown = true) //JSON 스트링에는 resultCode, resultMessage name이 존재하지만 ConstraintData 클래스에는 해당 멤버 변수가 존재하지 않아도 처리
@Data
public class LocalDeliveryPaymentData {
private int idx;
private String id;
private String code;
private String zone;
private int weight;
private int price;
private String startDate;
private String endDate;
private String useYn;
private String codeKname;
private String codeEname;
private String codeName;
private String regDate;
private String locale;
private String nowDate;
}
|
package com.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.Entity.CandidateEntity;
import com.Entity.ResponseEntity;
import com.Repository.CandidateRepo;
@RestController
@RequestMapping("/superadmin")
public class SuperAdminController {
@Autowired
CandidateRepo crepo;
@GetMapping("/candidates")
public ResponseEntity<List<CandidateEntity>> getAllCandidates(){
ResponseEntity<List<CandidateEntity>> res = new ResponseEntity<>();
List<CandidateEntity> candidateList = crepo.findAll();
res.setMessage("All Candidates are retrieved...");
res.setStatus(200);
res.setData(candidateList);
return res;
}
@GetMapping("/candidates/{candidateId}")
public ResponseEntity<CandidateEntity> getCandidateById(@PathVariable("candidateId") int candidateId){
ResponseEntity<CandidateEntity> res = new ResponseEntity<>();
CandidateEntity candidate = crepo.findById(candidateId);
res.setMessage("The candidate is retrieved successfully...");
res.setStatus(200);
res.setData(candidate);
return res;
}
@DeleteMapping("/deleteCandidate/{candidateId}")
public ResponseEntity<CandidateEntity> deleteCandidateById(@PathVariable("candidateId") int candidateId){
ResponseEntity<CandidateEntity> res = new ResponseEntity<>();
CandidateEntity candidate = crepo.findById(candidateId);
crepo.delete(candidate);
res.setMessage("The candidate is removed successfully...");
res.setStatus(200);
res.setData(candidate);
return res;
}
@PutMapping("/updateCandidate")
public ResponseEntity<CandidateEntity> updateCandidate(@RequestBody CandidateEntity candidate){
ResponseEntity<CandidateEntity> res = new ResponseEntity<>();
return res;
}
}
|
package com.xiaohe.eurekaserver.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* @author Gmq
* @since 2019-05-20 16:16
**/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
super.configure(http);
}
}
|
package uk.co.mobsoc.MobsGames.Player;
import java.util.ArrayList;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockIgniteEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityTargetEvent;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.event.painting.PaintingBreakByEntityEvent;
import org.bukkit.event.painting.PaintingPlaceEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerBucketFillEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerShearEntityEvent;
import org.bukkit.event.vehicle.VehicleDamageEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import uk.co.mobsoc.MobsGames.MobsGames;
public class GhostClass extends AbstractPlayerClass{
int indexOf=0;
public GhostClass(String player) {
super(player);
}
@Override
public void onEnable(){
teleToSpawn();
if(getPlayer()!=null){ getPlayer().sendMessage("You are now in spectator mode. Left and Right click to teleport to players"); }
for(AbstractPlayerClass apc : MobsGames.getGame().getParticipants()){
Player p= apc.getPlayer();
if(p!=null){
p.hidePlayer(getPlayer());
}
}
}
@Override
public void onDisable(){
for(AbstractPlayerClass apc : MobsGames.getGame().getParticipants()){
Player p= apc.getPlayer();
if(p!=null){
p.showPlayer(getPlayer());
}
}
}
@Override
public void onEvent(Event event){
if(event instanceof PlayerDropItemEvent){
((PlayerDropItemEvent) event).setCancelled(true);
}else if(event instanceof PlayerInteractEntityEvent){
((PlayerInteractEntityEvent) event).setCancelled(true);
}else if(event instanceof PlayerPickupItemEvent){
((PlayerPickupItemEvent) event).setCancelled(true);
}else if(event instanceof PlayerShearEntityEvent){
((PlayerShearEntityEvent) event).setCancelled(true);
}else if(event instanceof PlayerBucketFillEvent){
((PlayerBucketFillEvent) event).setCancelled(true);
}else if(event instanceof PlayerBucketEmptyEvent){
((PlayerBucketEmptyEvent) event).setCancelled(true);
}else if(event instanceof BlockBreakEvent){
((BlockBreakEvent) event).setCancelled(true);
}else if(event instanceof BlockPlaceEvent){
((BlockPlaceEvent) event).setCancelled(true);
}else if(event instanceof PlayerInteractEvent){
PlayerInteractEvent e = (PlayerInteractEvent) event;
e.setCancelled(true);
ArrayList<AbstractPlayerClass> playersLeft = MobsGames.getGame().getNonGhosts();
if(playersLeft.size()==0){ return; }
if(e.getAction() == Action.LEFT_CLICK_AIR || e.getAction()== Action.LEFT_CLICK_BLOCK){
indexOf--;
if(indexOf<0 || indexOf>= playersLeft.size()){
indexOf = playersLeft.size()-1;
}
Player p = playersLeft.get(indexOf).getPlayer();
if(p!=null){
teleportTo(p.getLocation());
}
}else if(e.getAction() == Action.RIGHT_CLICK_AIR || e.getAction() == Action.RIGHT_CLICK_BLOCK){
indexOf++;
if(indexOf>= playersLeft.size()){
indexOf = 0;
}
Player p = playersLeft.get(indexOf).getPlayer();
if(p!=null){
teleportTo(p.getLocation());
}
}
}else if(event instanceof BlockIgniteEvent){
((BlockIgniteEvent) event).setCancelled(true);
}else if(event instanceof EntityDamageByEntityEvent){
((EntityDamageByEntityEvent) event).setCancelled(true);
}else if(event instanceof EntityDamageEvent){
((EntityDamageEvent) event).setCancelled(true);
}else if(event instanceof VehicleDamageEvent){
((VehicleDamageEvent) event).setCancelled(true);
}else if(event instanceof VehicleEnterEvent){
((VehicleEnterEvent) event).setCancelled(true);
}else if(event instanceof PaintingBreakByEntityEvent){
((PaintingBreakByEntityEvent) event).setCancelled(true);
}else if(event instanceof PaintingPlaceEvent){
((PaintingPlaceEvent) event).setCancelled(true);
}else if(event instanceof EntityTargetEvent){
((EntityTargetEvent) event).setCancelled(true);
}else if(event instanceof ProjectileLaunchEvent){
((ProjectileLaunchEvent) event).setCancelled(true);
}else if(event instanceof PlayerJoinEvent){
Player p = ((PlayerJoinEvent) event).getPlayer();
p.hidePlayer(this.getPlayer());
}
}
}
|
package ProgramaLeitura;
import java.util.Scanner;
public class Main2 {
public static void main(String[] args) {
String nome, cidade, estado, idade;
Scanner in = new Scanner(System.in);
System.out.println("Insira seu nome: ");
nome = in.nextLine();
System.out.println("Insira sua idade: ");
idade = in.nextLine();
System.out.println("Insira seu estado: ");
estado = in.nextLine();
System.out.println("Insira sua cidade: ");
cidade = in.nextLine();
if(cidade.equals("Joinville"))
System.out.println("Niice");
System.out.println("_____________________");
System.out.println("Dados: \n"+
"Nome: "+nome+"\n"+
"Idade: "+idade+"\n"+
"Estado: "+estado+"\n"+
"Cidade: "+cidade+"\n");
}
}
|
package net.xndk.proxygen;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class MethodProperties {
private String name;
private String httpMethod;
private List<PathFragment> pathFragments = new LinkedList<PathFragment>();
private String responseContentType;
private String requestContentType;
private Boolean requiresAuthentication = false;
public MethodProperties(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public String getResponseContentType() {
return responseContentType;
}
public void setResponseContentType(String responseContentType) {
this.responseContentType = responseContentType;
}
public Boolean requiresAuthentication() {
return requiresAuthentication;
}
public void setRequiresAuthentication(Boolean requiresAuthentication) {
this.requiresAuthentication = requiresAuthentication;
}
public String getRequestContentType() {
return requestContentType;
}
public void setRequestContentType(String requestContentType) {
this.requestContentType = requestContentType;
}
public Boolean getRequiresAuthentication() {
return requiresAuthentication;
}
public List<String> getParameters() {
List<String> result = new ArrayList<String>(pathFragments.size());
for (PathFragment pathFragment : pathFragments) {
if (pathFragment.isParameter) {
result.add(pathFragment.contents);
}
}
if (this.requestContentType != null) {
result.add("_data");
}
return result;
}
public List<PathFragment> getPathFragments() {
return pathFragments;
}
}
|
package com.espendwise.manta.util;
public interface PropertyStatusCode {
public String getStatusCode();
}
|
package am.main.api;
import am.main.common.ConfigParam;
import am.main.common.ConfigUtils;
import am.main.data.dto.logger.AMFunLogData;
import am.main.data.enums.impl.AMQ;
import am.main.data.enums.logger.LogConfigProp;
import am.main.data.jaxb.am.logger.*;
import am.main.data.jaxb.log4jData.Configuration;
import am.main.data.jaxb.log4jData.RollingFile;
import am.main.exception.GeneralException;
import am.main.session.AppSession;
import am.main.spi.AMCode;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static am.main.common.ConfigParam.APP_NAME;
import static am.main.common.ConfigParam.COMPONENT;
import static am.main.data.enums.Interface.INITIALIZING_COMPONENT;
import static am.main.data.enums.impl.AME.*;
import static am.main.data.enums.impl.AMI.*;
import static am.main.data.enums.impl.AMP.AM_INITIALIZATION;
import static am.main.data.enums.impl.AMP.JMS_MANAGER;
import static am.main.data.enums.impl.AMS.AM;
import static am.main.data.enums.impl.AMS.AM_LOGGER;
import static am.main.data.enums.impl.AMW.W_LOG_7;
import static am.main.data.enums.impl.AMW.W_LOG_8;
import static am.main.data.enums.logger.LogConfigProp.*;
import static am.main.data.enums.logger.LoggerLevels.*;
import static java.nio.charset.StandardCharsets.UTF_8;
@Singleton
public class AppLogger implements Serializable{
private static final String CLASS = AppLogger.class.getSimpleName();
public Logger FAILURE_LOGGER = LogManager.getLogger("Failure");
private Logger INITIAL_LOGGER = LogManager.getLogger("Initial");
private Logger JMS_LOGGER = LogManager.getLogger("JMS-Msg");
private Map<String, Logger> loggers = new HashMap<>();
private static final String LOG4J2_FILE_NAME = "/log4j2.xml";
private static final String TEMPLATE = "Template";
@Inject private Provider<JMSManager> jmsManager;
private Boolean USE_AM_LOGGER_APP = false;
private Boolean USE_PERFORMANCE_LOGGER = false;
private static AppLogger instance;
public AppLogger() {
}
public static AppLogger getInstance(){
if (instance == null){
synchronized(AppLogger.class){
if (instance == null){
instance = new AppLogger();
instance.load();
}
}
}
return instance;
}
@PostConstruct
private void load() {
String METHOD = "load";
AppSession session = new AppSession(AM, INITIALIZING_COMPONENT, AM_INITIALIZATION, CLASS, METHOD);
String componentName = COMPONENT.APP_LOGGER;
try {
this.info(session, I_SYS_1, componentName);
AMLogger externalConfig = null;
try {
externalConfig = ConfigUtils.readRemoteXMLFile(session, this, AMLogger.class, ConfigParam.LOGGER_CONFIG.FN_PATH);
this.info(session, I_LOG_2);
}catch (GeneralException exc){
if(exc.getErrorCode().equals(E_IO_3)) {
// this.warn(session, W_LOG_1);
throw new GeneralException(session, E_LOG_6);
}else
throw exc;
}
// if(externalConfig == null)
// throw new GeneralException(session, E_LOG_6);
AMLoggerConfig loggerConfig = checkLoggerConfig(session, externalConfig.getAMLoggerConfig());
List<LoggerProperty> loggerPropertyList = loggerConfig.getLoggerProperty();
String globalLogLevel = "";
for (LoggerProperty property :loggerPropertyList) {
if (property.getName().equals(USE_AM_LOGGER.getName())) {
if (!property.getValue().toLowerCase().trim().equals(USE_AM_LOGGER.getDefaultValue()))
USE_AM_LOGGER_APP = true;
}else if(property.getName().equals(LOG_LEVEL_FOR_ALL.getName())){
if (!property.getValue().toLowerCase().trim().equals(LOG_LEVEL_FOR_ALL.getDefaultValue()))
globalLogLevel = property.getValue().trim().toLowerCase();
}else if(property.getName().equals(LOG_PERFORMANCE.getName())){
if (!property.getValue().toLowerCase().trim().equals(LOG_PERFORMANCE.getDefaultValue()))
USE_PERFORMANCE_LOGGER = true;
}
}
List<AMApplication> applicationList = new ArrayList<>();
if(APP_NAME.equals(AM_LOGGER.getName()) && USE_AM_LOGGER_APP){
applicationList = externalConfig.getAMApplications().getAMApplication();
}else if(!USE_AM_LOGGER_APP){
applicationList = externalConfig.getAMApplications().getAMApplication();
}
if(applicationList.size() != 0){
Configuration log4j2 = ConfigUtils.readResourceXMLFile(session, this, Configuration.class, "/TemplateLog4j2.xml");
this.info(session, I_LOG_1);
RollingFile templateRolling = new RollingFile();
for (RollingFile rollingFile :log4j2.getAppenders().getRollingFile())
if(rollingFile.getName().equals(TEMPLATE))
templateRolling = rollingFile;
am.main.data.jaxb.log4jData.Logger templateLogger = new am.main.data.jaxb.log4jData.Logger();
for (am.main.data.jaxb.log4jData.Logger logger : log4j2.getLoggers().getLogger())
if (logger.getName().equals(TEMPLATE))
templateLogger = logger;
for (AMApplication application :applicationList)
log4j2.addNewLogger(session, this, application, loggerConfig, templateLogger,
templateRolling, globalLogLevel);
log4j2.removeTemplate(TEMPLATE);
writeLog4J2File(session, log4j2);
this.info(session, I_LOG_5);
//To Reload the Log4j2.xml
((org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false)).reconfigure();
this.info(session, I_LOG_6);
for (AMApplication application : applicationList) {
for (LoggerGroup group : application.getLoggerGroup())
for (LoggerData loggerData : group.getLoggerData()) {
loggers.put(loggerData.getName(), LogManager.getLogger(loggerData.getName()));
this.info(session, I_LOG_7, loggerData.getName());
}
}
loggers.remove(TEMPLATE);
this.info(session, I_LOG_8);
}
this.info(session, I_SYS_2, componentName);
} catch (Exception ex) {
this.error(session, ex, E_SYS_1, componentName, ex.getMessage());
throw new IllegalStateException(session + E_SYS_1.getFullMsg(componentName, ex.getMessage()));
}
}
private AMLoggerConfig checkLoggerConfig(AppSession appSession, AMLoggerConfig externalLogConfig) throws Exception{
String METHOD = "checkLoggerConfig";
AppSession session = appSession.updateSession(CLASS, METHOD);
try {
this.startDebug(session);
this.info(session, I_LOG_12);
for (LogConfigProp internalProp : LogConfigProp.values()) {
boolean found = false;
for (LoggerProperty externalProp : externalLogConfig.getLoggerProperty()) {
if(internalProp.getName().equals(externalProp.getName())){
found = true;
if(!externalProp.getValue().matches(internalProp.getRegex())) {
this.warn(session, W_LOG_8, externalProp.getValue(), externalProp.getName(), internalProp.getDefaultValue());
externalProp.setValue(internalProp.getDefaultValue());
}
break;
}
}
if(!found) {
this.warn(session, W_LOG_7, internalProp.getName(), internalProp.getDefaultValue());
externalLogConfig.getLoggerProperty().add(new LoggerProperty(internalProp.getName(), internalProp.getDefaultValue()));
}
}
this.info(session, I_LOG_13);
this.endDebug(session, externalLogConfig);
return externalLogConfig;
}catch (Exception ex){
if(ex instanceof GeneralException)
throw ex;
else
throw new GeneralException(session, ex, E_LOG_2);
}
}
private void writeLog4J2File(AppSession appSession, Configuration log4j2) throws Exception{
String METHOD = "writeLog4J2File";
AppSession session = appSession.updateSession(CLASS, METHOD);
try {
this.startDebug(session, log4j2);
this.info(session, I_IO_5, LOG4J2_FILE_NAME);
String xml = XMLHandler.compose(session, this, log4j2, Configuration.class);
try {
PrintWriter writer = new PrintWriter(AppLogger.class.getResource(LOG4J2_FILE_NAME).getPath(), UTF_8.displayName());
writer.write(xml);
writer.flush();
}catch (FileNotFoundException | NullPointerException e){
throw new GeneralException(session, e, E_IO_3, LOG4J2_FILE_NAME);
} catch (SecurityException e) {
throw new GeneralException(session, e, E_IO_6, LOG4J2_FILE_NAME);
}
this.info(session, I_IO_6, LOG4J2_FILE_NAME);
this.endDebug(session);
}catch (Exception ex){
if(ex instanceof GeneralException)
throw ex;
else
throw new GeneralException(session, ex, E_IO_7, LOG4J2_FILE_NAME);
}
}
public void error(AppSession session, Exception ex) {
AMFunLogData logData = new AMFunLogData(session, ERROR_EX, ex);
log(session, logData);
}
public void error(AppSession session, AMCode amCode, Object ... args) {
AMFunLogData logData = new AMFunLogData(session, ERROR_MSG, amCode, args);
log(session, logData);
}
public void error(AppSession session, Exception ex, AMCode ec, Object ... args) {
AMFunLogData logData = new AMFunLogData(session, ERROR_MSG_EX, ex, ec, args);
log(session, logData);
}
public void info(AppSession session, AMCode amCode, Object ... args){
AMFunLogData logData = new AMFunLogData(session, INFO, amCode, args);
log(session, logData);
}
public void warn(AppSession session, AMCode amCode, Object ... args){
AMFunLogData logData = new AMFunLogData(session, WARN, amCode, args);
log(session, logData);
}
public void startDebug(AppSession session, Object ... args){
AMFunLogData logData = new AMFunLogData(session, args);
log(session, logData);
}
public void endDebug(AppSession session){
AMFunLogData logData = new AMFunLogData(session);
log(session, logData);
}
public void endDebug(AppSession session, Object result){
AMFunLogData logData = new AMFunLogData(session, result);
log(session, logData);
}
public void log(AppSession session, AMFunLogData logData){
if(session == null || session.getPHASE() == null || session.getSOURCE() == null)
logData.logMsg(null, this, FAILURE_LOGGER);
else{
if(session.getINTERFACE().value().equals(INITIALIZING_COMPONENT.value()))
logData.logMsg(session.getMessageHandler(), this, INITIAL_LOGGER);
else if(session.getPHASE().equals(JMS_MANAGER))
logData.logMsg(session.getMessageHandler(), this, JMS_LOGGER);
else if(session.getSOURCE().equals(AM_LOGGER)) {
Logger logger = loggers.get(logData.getPHASE());
logger = (logger == null) ? loggers.get(APP_NAME) : logger;
logData.logMsg(session.getMessageHandler(), this,
(logger != null ? logger : FAILURE_LOGGER));
if(logger == null)
throw new IllegalStateException("Invalid Logger Selected");
}else {
try {
jmsManager.get().sendObjMessage(session, AMQ.FILE_LOG, logData);
} catch (Exception exc) {
logData.logMsg(session.getMessageHandler(), this, FAILURE_LOGGER);
FAILURE_LOGGER.error(exc);
}
}
}
}
public Boolean getUsePerformanceLogger() {
return USE_PERFORMANCE_LOGGER;
}
public void setUsePerformanceLogger(Boolean USE_PERFORMANCE_LOGGER) {
this.USE_PERFORMANCE_LOGGER = USE_PERFORMANCE_LOGGER;
}
}
|
package com.tkb.elearning.action.admin;
import java.io.IOException;
import java.util.List;
import com.tkb.elearning.model.AllAssociation;
import com.tkb.elearning.model.Zone;
import com.tkb.elearning.service.AllAssociationService;
import com.tkb.elearning.service.ZoneService;
import com.tkb.elearning.util.VerifyBaseAction;
public class ZoneAction extends VerifyBaseAction {
private static final long serialVersionUID = 1L;
private ZoneService zoneService; //地區管理服務
private AllAssociationService allAssociationService; //各區協會服務
private List<Zone> zoneList; //地區管理清單
private List<AllAssociation> allAssociationList; //各區協會清單
private Zone zone; //地區管理資料
private AllAssociation allAssociation; //各區協會
private int pageNo; //頁碼
private int[] deleteList; //刪除的ID清單
/**
* 清單頁面
* @return
*/
public String index() {
if(zone == null) {
zone = new Zone();
}
pageTotalCount = zoneService.getCount(zone);
pageNo = super.pageSetting(pageNo);
zoneList = zoneService.getList(pageCount, pageStart, zone);
return "list";
}
/**
* 新增頁面
* @return
*/
public String add() {
zone = new Zone();
return "form";
}
/**
* 新增資料
* @return
* @throws IOException
*/
public String addSubmit() throws IOException {
zoneService.add(zone);
return "index";
}
/**
* 修改頁面
* @return
*/
public String update() {
zone = zoneService.getData(zone);
return "form";
}
/**
* 修改排序
* @return
*/
public String updateSort() {
zoneService.updateSort(zone);
return "index";
}
/**
* 修改地區管理資料
* @return
* @throws IOException
*/
public String updateSubmit() throws IOException {
zoneService.update(zone);
return "index";
}
/**
* 刪除最新消息
* @return
*/
public String delete() throws IOException {
for(int id : deleteList) {
zone.setId(id);
zone = zoneService.getData(zone);
zoneService.delete(id);
}
return "index";
}
/**
* 瀏覽頁面
* @return
*/
public String view(){
zone = zoneService.getData(zone);
return "view";
}
/**
* 修改排序最新消息
* @return
*/
// public String updateSort() {
// zoneService.updateSort();
// return "index";
// }
/**
* 檢查重複學校名稱
* @return
* @throws IOException
*/
public void checkZonename() throws IOException {
String zone_name = request.getParameter("zone_name");
String msg = "";
Zone zone = new Zone();
zone.setZone_name(zone_name);
String returnZonename = zoneService.checkZonename(zone);
if(returnZonename == null) {
msg = "true";
} else {
msg = "false";
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(msg);
}
public void checkUsingZone() throws IOException {
int zone_name = Integer.parseInt(request.getParameter("zone_name"));
String checkmsg = "";
Zone zone = new Zone();
zone.setId(zone_name);
zone=zoneService.getData(zone);
AllAssociation allAssociation = new AllAssociation();
allAssociation.setZone_name(zone.getZone_name());
int returnZonename = allAssociationService.checkUsingZone(allAssociation);
if(returnZonename == 0) {
checkmsg = "true";
} else {
checkmsg = "false";
}
response.setContentType("text/json;charset=UTF-8");
response.getWriter().write(checkmsg);
}
public ZoneService getZoneService() {
return zoneService;
}
public void setZoneService(ZoneService zoneService) {
this.zoneService = zoneService;
}
public AllAssociationService getAllAssociationService() {
return allAssociationService;
}
public void setAllAssociationService(AllAssociationService allAssociationService) {
this.allAssociationService = allAssociationService;
}
public List<Zone> getZoneList() {
return zoneList;
}
public void setZoneList(List<Zone> zoneList) {
this.zoneList = zoneList;
}
public List<AllAssociation> getAllAssociationList() {
return allAssociationList;
}
public void setAllAssociationList(List<AllAssociation> allAssociationList) {
this.allAssociationList = allAssociationList;
}
public Zone getZone() {
return zone;
}
public void setZone(Zone zone) {
this.zone = zone;
}
public AllAssociation getAllAssociation() {
return allAssociation;
}
public void setAllAssociation(AllAssociation allAssociation) {
this.allAssociation = allAssociation;
}
public int getPageNo() {
return pageNo;
}
public void setPageNo(int pageNo) {
this.pageNo = pageNo;
}
public int[] getDeleteList() {
return deleteList;
}
public void setDeleteList(int[] deleteList) {
this.deleteList = deleteList;
}
}
|
package com.codecow.common.vo.req;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.List;
/**
* @author codecow
* @version 1.0 UPMS
* @date 2021/6/23 15:47
**/
@Data
public class UserOwnRoleReqVO {
@ApiModelProperty(value = "用户id")
@NotBlank(message = "用户id不能为空")
private String userId;
@ApiModelProperty(value = "赋予用户的角色id集合")
private List<String>roleIds;
}
|
package com.wv.web.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import com.wv.domain.User;
import com.wv.service.UserService;
import com.wv.utils.CommonUtils;
import com.wv.utils.MailUtils;
/**
* Servlet implementation class RegisterServlet
*/
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
// 获得表单数据
Map<String, String[]> properties = request.getParameterMap();
User user = new User();
try {
ConvertUtils.register(new Converter() {
public Object convert(Class clazz, Object value) {
// 将value转换成Date类型
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); // 指定日期格式
Date parse = null;
try {
parse = format.parse(value.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return parse;
}
}, Date.class);
BeanUtils.populate(user, properties);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// user中还有缺一些数据uid, telephone, state, code
user.setUid(CommonUtils.getUUID());
user.setTelephone(null);
String activeCode = CommonUtils.getUUID();
user.setCode(activeCode);
// 将user转给下一层
UserService service = new UserService();
boolean isRegisterSuccess = service.regist(user);
if (isRegisterSuccess) {
//注册时给用户发送激活邮件
String emailMsg = "恭喜您注册成功,请点击下面的连接进行激活账户"
+ "<a href='http://localhost:8080/WebShop/active?activeCode="+activeCode+"'>"
+ "http://localhost:8080/WebShop/active?activeCode="+activeCode+"</a>";
try {
MailUtils.sendMail(user.getEmail(), emailMsg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
//跳转到注册成功页面,重定向
response.sendRedirect(request.getContextPath() + "/registerSuccess.jsp");
} else {
//跳转到注册失败页面
response.sendRedirect(request.getContextPath() + "/registerFail.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
|
package com.company.look;
/**
* Created by Администратор on 27.01.2016.
*/
public interface Salable {
int price();
String name();
String description();
}
|
package com.team11.demoangrybird;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
public class Bird extends Vat_the
{
public Bird(float x, float y, ITextureRegion texture,
VertexBufferObjectManager Ver, Scene mScene) {
super(x, y, texture, Ver, mScene);
// TODO Auto-generated constructor stub
mSprite = new Sprite(x,y, texture, Ver);
position = new Vector2(x,y);
mSprite.setZIndex(2);
mScene.attachChild(mSprite);
mScene.sortChildren();
}
float timeLife = 500; //thời gian sống
int status = 1; //trạng thái
public void Shoot(Vector2 SLINGSHOT_CENTER, Vector2 Touch)
{
}
public void Collision(float force)
{
}
public boolean UseSkill()
{
return false;
}
}
|
package com.mochasoft.fk.security.entity;
public class Permission {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column MOCHA_SECU_PERMISSION.ID
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
private String id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column MOCHA_SECU_PERMISSION.NAME
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
private String name;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column MOCHA_SECU_PERMISSION.CREATE_TIME
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
private Long createTime;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column MOCHA_SECU_PERMISSION.DESCN
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
private String descn;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column MOCHA_SECU_PERMISSION.ID
*
* @return the value of MOCHA_SECU_PERMISSION.ID
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public String getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column MOCHA_SECU_PERMISSION.ID
*
* @param id the value for MOCHA_SECU_PERMISSION.ID
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column MOCHA_SECU_PERMISSION.NAME
*
* @return the value of MOCHA_SECU_PERMISSION.NAME
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public String getName() {
return name;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column MOCHA_SECU_PERMISSION.NAME
*
* @param name the value for MOCHA_SECU_PERMISSION.NAME
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column MOCHA_SECU_PERMISSION.CREATE_TIME
*
* @return the value of MOCHA_SECU_PERMISSION.CREATE_TIME
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public Long getCreateTime() {
return createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column MOCHA_SECU_PERMISSION.CREATE_TIME
*
* @param createTime the value for MOCHA_SECU_PERMISSION.CREATE_TIME
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column MOCHA_SECU_PERMISSION.DESCN
*
* @return the value of MOCHA_SECU_PERMISSION.DESCN
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public String getDescn() {
return descn;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column MOCHA_SECU_PERMISSION.DESCN
*
* @param descn the value for MOCHA_SECU_PERMISSION.DESCN
*
* @mbggenerated Wed Feb 20 16:25:27 CST 2013
*/
public void setDescn(String descn) {
this.descn = descn == null ? null : descn.trim();
}
}
|
package com.outofmemory.entertainment.dissemination.game.text;
import com.outofmemory.entertainment.dissemination.engine.*;
public class StartGameText extends AbstractGameObject {
private final Camera camera;
public StartGameText(Camera camera, Animation animation) {
super(animation, null, new TextBody());
this.camera = camera;
}
@Override
public void update(GameContext context) {
position = calculatePosition();
}
private Position calculatePosition() {
Position cameraPosition = camera.getPosition();
Position position = PositionCalculator.calculateRelativePosition(
animation.current().getSize(), camera.getSize(), cameraPosition, new PositionProps() {{
verticalAlign = VerticalAlign.Center;
horizontalAlign = HorizontalAlign.Center;
}}
);
position.setZ(10);
return position;
}
}
|
package cn.rongcloud.im.message.provider;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.text.ClipboardManager;
import android.text.Selection;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import cn.rongcloud.im.App;
import cn.rongcloud.im.R;
import cn.rongcloud.im.utils.SPUtils;
import cn.rongcloud.im.utils.TextTranslateTask;
import io.rong.common.RLog;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.emoticon.AndroidEmoji;
import io.rong.imkit.model.ProviderTag;
import io.rong.imkit.model.UIMessage;
import io.rong.imkit.utilities.OptionsPopupDialog;
import io.rong.imkit.widget.AutoLinkTextView;
import io.rong.imkit.widget.ILinkClickListener;
import io.rong.imkit.widget.LinkTextViewMovementMethod;
import io.rong.imkit.widget.provider.IContainerItemProvider;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
/**
* Created by DELL on 2017/5/27.
*/
@ProviderTag(
messageContent = TextMessage.class,
showReadState = true
)
public class MyTextMessageItemProvider extends IContainerItemProvider.MessageProvider<TextMessage> {
private static final String TAG = "MyTextMessageItemProvider";
public MyTextMessageItemProvider() {
}
public View newView(Context context, ViewGroup group) {
View view = LayoutInflater.from(context).inflate(R.layout.rc_item_text_message, (ViewGroup) null);
ViewHolder holder = new ViewHolder();
holder.message = (AutoLinkTextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
return view;
}
public Spannable getContentSummary(TextMessage data) {
if (data == null) {
return null;
} else {
String content = data.getContent();
if (content != null) {
if (content.length() > 100) {
content = content.substring(0, 100);
}
return new SpannableString(AndroidEmoji.ensure(content));
} else {
return null;
}
}
}
public void onItemClick(View view, int position, TextMessage content, UIMessage message) {
}
public void onItemLongClick(final View view, int position, final TextMessage content, final UIMessage message) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.longClick = true;
if (view instanceof TextView) {
CharSequence items = ((TextView) view).getText();
if (items != null && items instanceof Spannable) {
Selection.removeSelection((Spannable) items);
}
}
long deltaTime = RongIM.getInstance().getDeltaTime();
long normalTime = System.currentTimeMillis() - deltaTime;
boolean enableMessageRecall = false;
int messageRecallInterval = -1;
boolean hasSent = !message.getSentStatus().equals(Message.SentStatus.SENDING) && !message.getSentStatus().equals(Message.SentStatus.FAILED);
try {
enableMessageRecall = RongContext.getInstance().getResources().getBoolean(io.rong.imkit.R.bool.rc_enable_message_recall);
messageRecallInterval = RongContext.getInstance().getResources().getInteger(io.rong.imkit.R.integer.rc_message_recall_interval);
} catch (Resources.NotFoundException var15) {
RLog.e("TextMessageItemProvider", "rc_message_recall_interval not configure in rc_config.xml");
var15.printStackTrace();
}
String[] items1;
if (hasSent && enableMessageRecall && normalTime - message.getSentTime() <= (long) (messageRecallInterval * 1000) && message.getSenderUserId().equals(RongIM.getInstance().getCurrentUserId()) && !message.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.APP_PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.PUBLIC_SERVICE) && !message.getConversationType().equals(Conversation.ConversationType.SYSTEM) && !message.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
items1 = new String[]{view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_copy), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_delete), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_recall)};
} else {
items1 = new String[]{view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_copy), view.getContext().getResources().getString(io.rong.imkit.R.string.rc_dialog_item_message_delete)};
}
OptionsPopupDialog.newInstance(view.getContext(), items1).setOptionsPopupDialogListener(new OptionsPopupDialog.OnOptionsItemClickedListener() {
public void onOptionsItemClicked(int which) {
if (which == 0) {
ClipboardManager clipboard = (ClipboardManager) view.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(content.getContent());
} else if (which == 1) {
RongIM.getInstance().deleteMessages(new int[]{message.getMessageId()}, (RongIMClient.ResultCallback) null);
} else if (which == 2) {
RongIM.getInstance().recallMessage(message.getMessage(), MyTextMessageItemProvider.this.getPushContent(view.getContext(), message));
}
}
}).show();
}
public void bindView(final View v, int position, TextMessage content, final UIMessage data) {
Log.e("123", "MyTextMessageItemProvider——bindView " + data.getTextMessageContent() + " position= " + position);
ViewHolder holder = (ViewHolder) v.getTag();
if (data.getMessageDirection() == Message.MessageDirection.SEND) {
holder.message.setBackgroundResource(io.rong.imkit.R.drawable.rc_ic_bubble_right);
} else {
holder.message.setBackgroundResource(io.rong.imkit.R.drawable.rc_ic_bubble_left);
}
final AutoLinkTextView textView = holder.message;
textView.setTag(R.id.tag_second, position);
if (data.getTextMessageContent() != null) {
textView.setText(data.getTextMessageContent().toString());
String var = App.content.get(data.getTextMessageContent().toString());
if (!TextUtils.isEmpty(var)) {
setText(v,textView,var,data.getTextMessageContent().toString());
}else{
new TextTranslateTask(v,textView, position, new TextTranslateTask.OnTranslateListener() {
@Override
public void setData(View viewGroup, AutoLinkTextView tv, int position, String translateVar, String src) {
int tag = (Integer) tv.getTag(R.id.tag_second);
Log.e("123", "tag= " + tag + " position=" + position);
if (tag != position) return;
setText(viewGroup, tv, translateVar,src);
}
}).execute(data.getTextMessageContent().toString());
}
}
holder.message.setMovementMethod(new LinkTextViewMovementMethod(new ILinkClickListener() {
public boolean onLinkClick(String link) {
RongIM.ConversationBehaviorListener listener = RongContext.getInstance().getConversationBehaviorListener();
boolean result = false;
if (listener != null) {
result = listener.onMessageLinkClick(v.getContext(), link);
}
if (listener == null || !result) {
String str = link.toLowerCase();
if (str.startsWith("http") || str.startsWith("https")) {
Intent intent = new Intent("io.rong.imkit.intent.action.webview");
intent.setPackage(v.getContext().getPackageName());
intent.putExtra("url", link);
v.getContext().startActivity(intent);
result = true;
}
}
return result;
}
}));
}
private void setText(final View v, final AutoLinkTextView tv, final String translateVar,String src) {
final String show=getShowText(src,translateVar);
int len = show.length();
if (v.getHandler() != null && len > 500) {
v.getHandler().postDelayed(new Runnable() {
public void run() {
tv.setText(show);
}
}, 50L);
} else {
tv.setText(show);
}
}
private String getShowText(String src,String translate){
boolean flag= SPUtils.findBoolean("showModel");
StringBuilder sb=new StringBuilder();
if(flag){
sb.append("原文: "+src);
sb.append("\r\n");
sb.append("译文: ");
}
sb.append(translate);
return sb.toString();
}
private static class ViewHolder {
AutoLinkTextView message;
boolean longClick;
private ViewHolder() {
}
}
}
|
package test.main;
import java.io.File;
public class MainClass10 {
public static void main(String[] args) {
//특정 폴더 100개를 반복문 돌면서 만들기
for(int i=0; i<100; i++) {
File tmp=new File("c:/myFolder/gura"+i);
tmp.mkdir();
}
System.out.println("오예~");
}
}
|
package com.kukri.demo.moviecatalog.service.impl;
import com.kukri.demo.moviecatalog.dao.DirectorRepository;
import com.kukri.demo.moviecatalog.dao.MoviesRepository;
import com.kukri.demo.moviecatalog.exception.ResourceNotFoundException;
import com.kukri.demo.moviecatalog.model.Movie;
import com.kukri.demo.moviecatalog.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Component
public class MovieServiceImpl implements MovieService {
@Autowired
private MoviesRepository moviesRepository;
@Autowired
private DirectorRepository directorRepository;
@Override
public List<Movie> getMovies() {
return moviesRepository.findAll();
}
@Override
public Movie createMovie(Movie movie) {
return moviesRepository.save(movie);
}
@Override
public Movie getMovieById(Long movieId) throws ResourceNotFoundException {
Movie movie =
moviesRepository
.findById(movieId)
.orElseThrow(() -> new ResourceNotFoundException("User not found on :: " + movieId));
return movie;
}
@Override
public Movie updateMovie(Movie movieDetails, Long movieId) throws ResourceNotFoundException {
moviesRepository
.findById(movieId)
.orElseThrow(() -> new ResourceNotFoundException("Movie not found on :: " + movieId));
final Movie updatedMovie = moviesRepository.save(movieDetails);
return updatedMovie;
}
@Override
public Map<String, Boolean> deleteMovie(Long MovieId) throws ResourceNotFoundException {
Movie Movie =
moviesRepository
.findById(MovieId)
.orElseThrow(() -> new ResourceNotFoundException("Movie not found on :: " + MovieId));
moviesRepository.delete(Movie);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
@Override
public List<Movie> findMoviesByDirector(Optional<String> directorFirstName, Optional<String> directorLastName) throws ResourceNotFoundException {
Long directorID;
try {
directorID = directorRepository.findDirectorByFirstNameAndLastName(directorFirstName, directorLastName);
} catch (Exception e) {
throw new ResourceNotFoundException("No movies found " + directorFirstName + directorLastName);
}
List<Movie> movies = moviesRepository.findMoviesByDirectorName(directorID);
if(movies.isEmpty()) {
throw new ResourceNotFoundException("No movies found " + directorFirstName + directorLastName);
}
return movies;
}
@Override
public List<Movie> findMoviesByRating(Optional<Double> rating) throws ResourceNotFoundException {
List<Movie> movies = moviesRepository.findMoviesByMovieRating(rating);
if (movies.isEmpty()) {
throw new ResourceNotFoundException("No Movies Found");
}
return movies;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lappa.smsbanking.Langue;
/**
*
* @author lappa
*/
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class ChangeLocale implements Serializable {
// la locale des pages
private String locale = "fr";
public ChangeLocale() {
}
public String setFrenchLocale() {
locale = "fr";
return null;
}
public String setEnglishLocale() {
locale = "en";
return null;
}
public String getLocale() {
return locale;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package legaltime.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import legaltime.AppPrefs;
import legaltime.LegalTimeApp;
import legaltime.cache.ClientCache;
import legaltime.model.ClientBean;
import legaltime.model.PaymentLogBean;
import legaltime.model.PaymentLogManager;
import legaltime.model.exception.DAOException;
import legaltime.modelsafe.EasyLog;
import legaltime.view.PaymentLogView;
import legaltime.view.PostPaymentHelper;
import legaltime.view.model.ClientComboBoxModel;
import legaltime.view.model.PaymentLogTableModel;
import legaltime.view.renderer.ClientComboBoxRenderer;
/**
*
* @author bmartin
*/
public class PaymentLogController implements TableModelListener, ActionListener{
private static PaymentLogController instance;
private PaymentLogView paymentLogView;
private PostPaymentHelper postPaymentHelper;
private LegalTimeApp mainController;
private EasyLog easyLog;
private AppPrefs appPrefs;
private PaymentLogTableModel paymentLogTableModel;
private ClientComboBoxModel clientComboBoxModel;
private PaymentLogBean[] paymentLogBeans;
private PaymentLogManager paymentLogManager;
private ClientComboBoxRenderer clientComboBoxRenderer;
ProcessControllerAccounting processControllerAccounting;
protected PaymentLogController(LegalTimeApp mainController_){
mainController = mainController_;
processControllerAccounting = ProcessControllerAccounting.getInstance();
paymentLogView = new PaymentLogView(this);
postPaymentHelper = new PostPaymentHelper(mainController.getMainFrame());
mainController.getDesktop().add(paymentLogView);
easyLog = EasyLog.getInstance();
appPrefs = AppPrefs.getInstance();
//paymentLogBeans = new paymentLogBean[];
paymentLogManager = PaymentLogManager.getInstance();
paymentLogTableModel = new PaymentLogTableModel();
paymentLogView.getTblPaymentLog().setModel(paymentLogTableModel);
paymentLogTableModel.addTableModelListener(this);
paymentLogView.formatTblPaymentLog();
clientComboBoxModel = new ClientComboBoxModel();
clientComboBoxRenderer = new ClientComboBoxRenderer();
//clientComboBoxModel.setList(ClientCache.getInstance().getCache());
paymentLogView.getCboClient().setModel(clientComboBoxModel);
paymentLogView.getCboClient().setRenderer(clientComboBoxRenderer );
paymentLogView.getCboClient().setActionCommand("CLIENT_CHANGED");
paymentLogView.getCboClient().addActionListener(this);
paymentLogView.getCboClient().setMaximumRowCount(Integer.parseInt(appPrefs.getValue(AppPrefs.CLIENTCBO_DISPLAY_ROWS)));
paymentLogView.getTblPaymentLog().addMouseListener(new PopupListener());
paymentLogView.getCmdAddPayment().addActionListener(this);
paymentLogView.getCmdAddPayment().setActionCommand("POST_PAYMENT");
//==================
}
public static PaymentLogController getInstance(LegalTimeApp mainController_){
if (instance == null){
instance = new PaymentLogController(mainController_);
}
return instance;
}
public void tableChanged(TableModelEvent e) {
}
public void refreshTblPaymentLog(int clientId_){
paymentLogBeans = new PaymentLogBean[0];
try {
paymentLogBeans = paymentLogManager.loadByWhere("where client_id = " + clientId_);
} catch (DAOException ex) {
Logger.getLogger(PaymentLogController.class.getName()).log(Level.SEVERE, null, ex);
easyLog.addEntry(EasyLog.INFO, "Error Loading Payment Log beans by where"
, getClass().getName(), ex);
}
paymentLogTableModel.setList(paymentLogBeans);
paymentLogView.getTblPaymentLog().updateUI();
paymentLogView.scrollRowTblPaymentLog(paymentLogTableModel.getRowCount()-1);
}
public int getPaymentLogCboClientId(){
int clientId;
try{
clientId= ((ClientBean) paymentLogView.getCboClient().getSelectedItem()).getClientId();
}catch(NullPointerException ex){
clientId=0;
easyLog.addEntry(EasyLog.INFO, "Client Line indeterminate"
, getClass().getName(), ex);
}
return clientId;
}
public void refreshTblPaymentLog(){
refreshTblPaymentLog(getPaymentLogCboClientId());
}
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("REVERSE_SELECTED_TRAN")){
reverseSelectedTran();
}else if(e.getActionCommand().equals("POST_PAYMENT")){
postPaymentHelper.showDialog((ClientBean)paymentLogView.getCboClient().getSelectedItem());
if (postPaymentHelper.isSelectionConfirmed()){
addPayment(postPaymentHelper.getCboClientId()
,postPaymentHelper.getDtcEffectiveDate().getDate()
,postPaymentHelper.getPaymentAmount()
);
}
}else if(e.getActionCommand().equals("CLIENT_CHANGED")){
refreshTblPaymentLog();
}
}
public void showPaymentLogView() {
clientComboBoxModel.setList(ClientCache.getInstance().getCache());
paymentLogView.getCboClient().updateUI();
paymentLogView.setVisible(true);
try {
paymentLogView.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
easyLog.addEntry(EasyLog.INFO, "Show Payment Log View Vetoed"
, getClass().getName(), e);
}
}
private void reverseSelectedTran() {
int selectedRow = paymentLogView.getTblPaymentLog().getSelectedRow();
processControllerAccounting.reversePaymentLogById(paymentLogTableModel.
getPaymentLogId(selectedRow));
refreshTblPaymentLog();
}
private void addPayment(int clientId_, java.util.Date effectiveDate_, Double amount_) {
//paymentLogTableModel.addRow(clientId, "Payment Received", 0D, new java.util.Date());
PaymentLogBean paymentLogBean;
paymentLogBean = paymentLogManager.createPaymentLogBean();
paymentLogBean.setClientId(clientId_);
paymentLogBean.setAmount(amount_);
paymentLogBean.setDescription("Payment Received");
paymentLogBean.setEffectiveDate( effectiveDate_);
processControllerAccounting.addPaymentLogBean(paymentLogBean);
refreshTblPaymentLog();
}
class PopupListener extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
@Override
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
paymentLogView.getTableMenu().show(e.getComponent(),
e.getX(), e.getY());
}
}
}
}
|
package hr.tvz.seminar.handlers;
import hr.tvz.seminar.database.DataBaseUtils;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
public class SearchHandler implements ActionListener,KeyListener{
private JPanel bookPane;
private JTextField text;
private JComboBox cBox;
public SearchHandler(JPanel panel,JTextField text,JComboBox cBox){
this.bookPane = panel;
this.text = text;
this.cBox = cBox;
}
@Override
public void actionPerformed(ActionEvent arg0) {
if (text.getText().length() > 0) {
bookPane.removeAll();
bookPane.repaint();
bookPane.revalidate();
DataBaseUtils.connectToDataBase();
String pageNumbers="";
ResultSet rs;
if(text.getText().equals("*")){
rs = DataBaseUtils.returnResults();
}
else{
rs = DataBaseUtils.returnResultsCategory(cBox.getSelectedIndex(), text.getText());
}
try {
while (rs.next()) {
String naslov = rs.getString("naslov");
String ekstenzija = rs.getString("ekstenzija");
ImageIcon bookIcon = new ImageIcon(
"slike/book.png");
JLabel bookLabel = new JLabel(naslov + "." + ekstenzija,
bookIcon, JLabel.TRAILING);
JPanel singleBookPane = new JPanel();
singleBookPane.setLayout(new GridBagLayout());
singleBookPane.setMaximumSize(new Dimension(2000, 80));
ImageIcon readBookIcon = new ImageIcon(
"slike/book.jpg");
ImageIcon editBookIcon = new ImageIcon(
"slike/Book_edit.png");
JButton editBookButton = new JButton("Edit Book",
editBookIcon);
JButton readBookButton = new JButton("Read Book",
readBookIcon);
ImageIcon deleteBookIcon = new ImageIcon(
"slike/book_delete.png");
JButton deleteBookButton = new JButton("Delete Book",
deleteBookIcon);
JSeparator separator = new JSeparator();
separator.setMaximumSize(new Dimension(6000, 2));
DeleteBookHandler deleteBookHandler = new DeleteBookHandler(
bookPane, naslov, singleBookPane, separator);
deleteBookButton.addActionListener(deleteBookHandler);
ReadBookHandler readBookHandler = new ReadBookHandler(
naslov, ekstenzija);
readBookButton.addActionListener(readBookHandler);
EditBookHandler editBookHandler = new EditBookHandler(
naslov);
editBookButton.addActionListener(editBookHandler);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 3;
c.weightx = 1.0;
singleBookPane.add(bookLabel, c);
c.weightx = 0.0;
c.gridwidth = 1;
c.gridx = 4;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 10);
singleBookPane.add(readBookButton, c);
c.gridx = 5;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 10);
singleBookPane.add(deleteBookButton, c);
c.gridx = 6;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 10);
singleBookPane.add(editBookButton, c);
singleBookPane.setAlignmentX(JFrame.LEFT_ALIGNMENT);
bookPane.add(singleBookPane);
if(cBox.getSelectedIndex() == 0 && !text.getText().equals("*")){
ResultSet rs2 = DataBaseUtils.pageNumbers(text.getText());
String naslovTemp;
int pageNumber;
while(rs2.next()){
naslovTemp = rs2.getString("naslov");
if(naslovTemp.equals(naslov)){
pageNumber = rs2.getInt("stranica");
pageNumbers += Integer.toString(pageNumber)+",";
}
}
pageNumbers = pageNumbers.substring(0, pageNumbers.length()-1);
JLabel pageLabel = new JLabel("Pages:");
JLabel pageNumbersLabel = new JLabel(pageNumbers);
pageNumbersLabel.setForeground(Color.red);
bookPane.add(pageLabel);
bookPane.add(pageNumbersLabel);
bookPane.add(Box.createRigidArea(new Dimension(0, 10)));
pageNumbers = "";
}
bookPane.add(separator);
}
bookPane.repaint();
bookPane.revalidate();
DataBaseUtils.closeConnection();
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
actionPerformed(null);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
}
}
|
package com.qw.springboot.pojo;
public class Information {
public int id;
public String name;
public String age;
public String position;
public String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id=id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age=age;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position=position;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone=phone;
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.logger;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import javassist.bytecode.stackmap.TypeData.ClassName;
public class CarInfoLogger {
static boolean append = true;
public final static Logger carInfoLogger = Logger.getLogger(ClassName.class.getName(), null);
public final static String path = "C:\\EJ-Projects\\Web-Applications\\DeGUzmanFamilyAPI-Backend\\log\\car-info-logs\\car-info.log";
public static FileHandler carInfoFileHandler;
public static void createLog() throws SecurityException, IOException {
File logDirectory = new File("C:\\\\EJ-Projects\\\\Web-Applications\\\\DeGUzmanFamilyAPI-Backend\\\\log\\\\car-info-logs");
if (!logDirectory.exists()) {
logDirectory.mkdirs();
System.out.println("Created directory: " + logDirectory);
}
carInfoFileHandler = new FileHandler(path,append);
carInfoLogger.addHandler(carInfoFileHandler);
System.out.println("Created log directory " + logDirectory);
}
}
|
package workstarter.repository;
import workstarter.domain.Jobadvertisment;
import org.springframework.data.jpa.repository.*;
import java.util.List;
/**
* Spring Data JPA repository for the Jobadvertisment entity.
*/
@SuppressWarnings("unused")
public interface JobadvertismentRepository extends JpaRepository<Jobadvertisment,Long> {
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* SGroup generated by hbm2java
*/
public class SGroup implements java.io.Serializable {
private long groupid;
private String groupname;
private String notes;
private String groupdescription;
public SGroup() {
}
public SGroup(long groupid) {
this.groupid = groupid;
}
public SGroup(long groupid, String groupname, String notes, String groupdescription) {
this.groupid = groupid;
this.groupname = groupname;
this.notes = notes;
this.groupdescription = groupdescription;
}
public long getGroupid() {
return this.groupid;
}
public void setGroupid(long groupid) {
this.groupid = groupid;
}
public String getGroupname() {
return this.groupname;
}
public void setGroupname(String groupname) {
this.groupname = groupname;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public String getGroupdescription() {
return this.groupdescription;
}
public void setGroupdescription(String groupdescription) {
this.groupdescription = groupdescription;
}
}
|
package com.example.demo;
public class ChildCC extends ParentC{
public ChildCC(boolean sOS, String color, String power, double price) {
super(sOS, color, power, price);
}
}
|
package io.kuoche.share.data.db.jpa.entity;
import io.kuoche.share.core.domain.Participator;
import io.kuoche.share.data.db.jpa.entity.pk.ParticipatorDataPk;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
@Entity
@Table(name = "participator")
@IdClass(ParticipatorDataPk.class)
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ParticipatorData {
@Id
private String name;
@Id
private Long activityId;
}
|
package com.lecture.spring.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ModelEvalutation {
private int evalutationNo ;
private int pamphletNo ;
private int userCode ;
private float design ;
private float creativity ;
private float content ;
public ModelEvalutation() {
super();
}
public ModelEvalutation(int evalutationNo, int pamphletNo, int userCode,
float design, float creativity, float content) {
super();
this.evalutationNo = evalutationNo;
this.pamphletNo = pamphletNo;
this.userCode = userCode;
this.design = design;
this.creativity = creativity;
this.content = content;
}
public int getEvalutationNo() {
return evalutationNo;
}
public void setEvalutationNo(int evalutationNo) {
this.evalutationNo = evalutationNo;
}
public int getPamphletNo() {
return pamphletNo;
}
public void setPamphletNo(int pamphletNo) {
this.pamphletNo = pamphletNo;
}
public int getUserCode() {
return userCode;
}
public void setUserCode(int userCode) {
this.userCode = userCode;
}
public float getDesign() {
return design;
}
public void setDesign(float design) {
this.design = design;
}
public float getCreativity() {
return creativity;
}
public void setCreativity(float creativity) {
this.creativity = creativity;
}
public float getContent() {
return content;
}
public void setContent(float content) {
this.content = content;
}
@Override
public String toString() {
return "ModelEvalutation [evalutationNo=" + evalutationNo
+ ", pamphletNo=" + pamphletNo + ", userCode=" + userCode
+ ", design=" + design + ", creativity=" + creativity
+ ", content=" + content + "]";
}
}
|
package com.mochasoft.fk.security.entity;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
/**
* <strong>Title : IUserDetails </strong>. <br>
* <strong>Description : UserDetails.</strong> <br>
* <strong>Create on : 2013-1-30 上午9:05:01 </strong>. <br>
* <p>
* <strong>Copyright (C) Mocha Software Co.,Ltd.</strong> <br>
* </p>
*
* @author wanghe wanghe@mochasoft.com.cn <br>
* @version <strong>FrameWork v0.8</strong> <br>
* <br>
* <strong>修改历史: .</strong> <br>
* 修改人 修改日期 修改描述<br>
* -------------------------------------------<br>
* <br>
* <br>
*/
public interface IUserDetails extends UserDetails {
void setName(String name);
String getName();
String getUserId();
void setPassword(String password);
String getPassword();
Collection<GrantedAuthority> getAuthorities();
}
|
import java.io.*;
public class CountCharacterTypes {
private static final String FILE_PATH = "res/words.txt";
private static final String SAVE_PATH = "res/count-chars.txt";
public static void main(String[] args) {
File file = new File(FILE_PATH);
File outputFile = new File(SAVE_PATH);
try (
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pr = new PrintWriter(new FileWriter(outputFile, true), true)
) {
String line = br.readLine();
int vowelsCount = 0;
int consonantsCount = 0;
int punctMarksCount = 0;
while (line != null) {
line = line.replaceAll("\\s","");
for (int i = 0; i < line.length(); i++) {
boolean vowelSymbol = (line.charAt(i) == 'a' || line.charAt(i) == 'e' || line.charAt(i) == 'i'
|| line.charAt(i) == 'o' || line.charAt(i) == 'u');
boolean punctuationMark = (line.charAt(i) == '.' || line.charAt(i) == ',' || line.charAt(i) == '?'
|| line.charAt(i) == '!');
if (vowelSymbol) {
vowelsCount++;
} else if (punctuationMark) {
punctMarksCount++;
} else {
consonantsCount++;
}
}
pr.printf("Vowels: %d\nConsonants: %d\nPunctuation: %d\n", vowelsCount, consonantsCount, punctMarksCount);
line = br.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package com.emp.auction;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
import java.util.List;
import static java.util.Locale.getDefault;
public class ShopMapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
GoogleMap GMap;
Geocoder geocoder;
List<Address> addresses;
TextView _shopaddress;
private ArrayList<Shopmain> mShops;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
geocoder = new Geocoder(this, getDefault());
// Retrieve the content view that renders the map.
setContentView(R.layout.activity_shop_map);
_shopaddress = (TextView) findViewById(R.id.shop_address);
mShops = Common.getInstance().getmShops();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
// Get the SupportMapFragment and request notification
// when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(final GoogleMap googleMap) {
//
Marker mMaker;
GMap = googleMap;
for(Shopmain shop : mShops){
String pos_location = shop.getmLocation();
String[] separated = pos_location.split(",");
String pos_latitude= separated[0];
String pos_longtitude= separated[1];
LatLng position = new LatLng(Double.parseDouble(pos_latitude),Double.parseDouble(pos_longtitude));
mMaker = GMap.addMarker(new MarkerOptions().position(position).title(shop.getmName()).snippet(shop.getmId()));
mMaker.setTag(0);
}
GMap.setOnMarkerClickListener(this);
}
@Override
public boolean onMarkerClick(Marker marker) {
String shop_id=marker.getSnippet();
Common.getInstance().setShopid(shop_id);
Intent intent = new Intent(getApplicationContext(), OneShopActivity.class);
startActivity(intent);
return false;
}
}
|
package jp.co.tau.web7.admin.supplier.dao.mappers;
import static org.assertj.core.api.Assertions.fail;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import jp.co.tau.web7.admin.supplier.entity.TDepDepSlipBsEntity;
import jp.co.tau.web7.admin.supplier.mappers.TDepDepSlipBMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TDepDepSlipBMapperTest extends MapperBaseTest {
@Autowired
TDepDepSlipBMapper tDepDepSlipBMapper;
/**
* {@link TDepDepSlipBMapper#findMaxSalesDepSlipNo()}のテスト
* <p>
* パターン:正常系
* </p>
*/
@Test
public void testFindMaxSalesDepSlipNo_001() {
try {
// 対象メソッドを呼び出し、テストを行う
int insertCount = tDepDepSlipBMapper.findMaxSalesDepSlipNo();
assert(compareObj(1, insertCount));
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage(), e);
}
}
}
|
package eu.dons.struggle.doctor.bprot.bedarfemodel;
import eu.dons.struggle.doctor.ergebnis2docmodel.FachFilter;
import eu.dons.struggle.ergebnis.Relevanz;
public class BedarfeFilter {
public static final FachFilter<BedarfBProtInfo> NUR_ERMITTLUNGSRELEVANT = new FachFilter<BedarfBProtInfo>() {
@Override
public boolean apply(BedarfBProtInfo type) {
if(Relevanz.E == type.getRelevanz()){
return true;
}
return false;
}
};
public static final FachFilter<BedarfBProtInfo> ERMITTLUNGS_ODER_ZAHLUNGSRELEVANT = new FachFilter<BedarfBProtInfo>() {
@Override
public boolean apply(BedarfBProtInfo type) {
if(type.getRelevanz() == Relevanz.E || type.getRelevanz() == Relevanz.Z){
return true;
}
return false;
}
};
}
|
package testFb;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import util.Commons;
/**
For scroll use the JavascriptExecutor
How to get the JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor) driver;
How to perform scroll?
js.executeScript("scrollBy(0, 4500)");
*/
public class TestScroll {
public static void main(String[] args) throws InterruptedException {
// Scroll down the webpage by 4500 pixels
WebDriver driver = Commons.getDriver();
driver.get("https://www.youtube.com");
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("scrollBy(0, 4500)");
js.executeScript("scrollBy(0, 4500)");
Thread.sleep(3);
js.executeScript("scrollBy(0, 4500)");
Thread.sleep(3);
}
}
|
package com.tencent.mm.plugin.nearby.ui;
import com.tencent.mm.protocal.c.aqp;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.applet.b.b;
class NearbyFriendsUI$b$2 implements b {
final /* synthetic */ NearbyFriendsUI.b lCj;
NearbyFriendsUI$b$2(NearbyFriendsUI.b bVar) {
this.lCj = bVar;
}
public final String jd(int i) {
if (i < 0 || i >= this.lCj.getCount()) {
x.e("MicroMsg.NearbyFriend", "pos is invalid");
return null;
}
aqp tQ = this.lCj.tQ(i);
if (tQ != null) {
return tQ.hbL;
}
return null;
}
public final int Xy() {
return this.lCj.getCount();
}
}
|
package app.integro.sjbhs.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import app.integro.sjbhs.R;
import app.integro.sjbhs.models.Alumni;
public class AlumniViewPagerAdapter extends PagerAdapter {
private static final String TAG = "AlumniViewPagerAdapter";
private final Context context;
private final ArrayList<Alumni> alumniArrayList;
public AlumniViewPagerAdapter(Context context, ArrayList<Alumni> alumniArrayList) {
this.context = context;
this.alumniArrayList = alumniArrayList;
}
@Override
public int getCount() {
return alumniArrayList.size();
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return (view == (RelativeLayout) object);
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
ImageView ivImage;
TextView tvTitle;
TextView tvDesignation;
View view = LayoutInflater.from(context).inflate(R.layout.card_alumni2, container, false);
ivImage = view.findViewById(R.id.ivImage);
tvTitle = view.findViewById(R.id.tvTitle);
tvDesignation = view.findViewById(R.id.tvDesignation);
tvTitle.setText(alumniArrayList.get(position).getName());
tvDesignation.setText(alumniArrayList.get(position).getDesignation());
Log.d(TAG, "instantiateItem: " + alumniArrayList.get(0).getImage());
Glide.with(context)
.load(alumniArrayList.get(position).getImage())
.placeholder(R.drawable.bg_placeholder)
.into(ivImage);
((ViewPager) container).addView(view);
return view;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
|
package com.conglomerate.dev.integration.messages;
import com.conglomerate.dev.integration.TestingUtils;
import com.conglomerate.dev.models.domain.GetMessageDomain;
import org.junit.Test;
import java.util.List;
public class TestLikeMessage {
@Test
public void likeMessageSuccess() throws Exception {
// CREATE USER AND LOGIN
String authToken = TestingUtils.createUserAndLoginSuccess("likeMessageSuccess",
"likeMessageSuccess@email.com",
"likeMessageSuccess");
// CREATE GROUP
int groupingId = TestingUtils.createGroupingAndExpect(authToken, "Like Message Success", 201);
// SEND MESSAGE
int messageId = TestingUtils.sendMessageAndExpect(authToken, "Test Message", groupingId, 201);
// LIKE MESSAGE
TestingUtils.likeMessageAndExpect(authToken, messageId, 200);
}
@Test
public void likeMessageIncrements() throws Exception {
// CREATE USER AND LOGIN
String authToken = TestingUtils.createUserAndLoginSuccess("likeMessageIncrements",
"likeMessageIncrements@email.com",
"likeMessageIncrements");
// CREATE GROUP
int groupingId = TestingUtils.createGroupingAndExpect(authToken, "Like Message Increments", 201);
// SEND MESSAGE
int messageId = TestingUtils.sendMessageAndExpect(authToken, "Test Message", groupingId, 201);
// ASSERT THE MESSAGE DOES NOT START OUT AS LIKED
List<GetMessageDomain> messages = TestingUtils.getLatestMessagesAndExpect(authToken, groupingId, 200);
assert(messages.size() == 1);
assert(!messages.get(0).isLiked());
// LIKE MESSAGE
TestingUtils.likeMessageAndExpect(authToken, messageId, 200);
// ASSERT THE MESSAGE GETS LIKED
messages = TestingUtils.getLatestMessagesAndExpect(authToken, groupingId, 200);
assert(messages.size() == 1);
assert(messages.get(0).isLiked());
}
@Test
public void likeMessageBadAuth() throws Exception {
// CREATE USER AND LOGIN
String authToken = TestingUtils.createUserAndLoginSuccess("likeMessageBadAuth",
"likeMessageBadAuth@email.com",
"likeMessageBadAuth");
// CREATE GROUP
int groupingId = TestingUtils.createGroupingAndExpect(authToken, "Like Message Bad Auth", 201);
// SEND MESSAGE
int messageId = TestingUtils.sendMessageAndExpect(authToken, "Test Message", groupingId, 201);
// LIKE MESSAGE
TestingUtils.likeMessageAndExpect("BAD AUTH TOKEN", messageId, 400);
}
@Test
public void likeMessageNoMessage() throws Exception {
// CREATE USER AND LOGIN
String authToken = TestingUtils.createUserAndLoginSuccess("likeMessageNoMessage",
"likeMessageNoMessage@email.com",
"likeMessageNoMessage");
// CREATE GROUP
int groupingId = TestingUtils.createGroupingAndExpect(authToken, "Like Message No Message", 201);
// SEND MESSAGE
int messageId = TestingUtils.sendMessageAndExpect(authToken, "Test Message", groupingId, 201);
// LIKE MESSAGE
TestingUtils.likeMessageAndExpect(authToken, -1, 400);
}
@Test
public void likeMessageNotMember() throws Exception {
// CREATE USER AND LOGIN
String authToken = TestingUtils.createUserAndLoginSuccess("likeMessageNotMember1",
"likeMessageNotMember1@email.com",
"likeMessageNotMember1");
// CREATE GROUP
int groupingId = TestingUtils.createGroupingAndExpect(authToken, "Like Message No Message", 201);
// SEND MESSAGE
int messageId = TestingUtils.sendMessageAndExpect(authToken, "Test Message", groupingId, 201);
// CREATE OTHER USER AND LOGIN
authToken = TestingUtils.createUserAndLoginSuccess("likeMessageNotMember2",
"likeMessageNotMember2@email.com",
"likeMessageNotMember2");
// LIKE MESSAGE
TestingUtils.likeMessageAndExpect(authToken, messageId, 400);
}
}
|
package com.example.school_news.dao;
import com.example.school_news.pojo.New;
import com.example.school_news.pojo.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
public interface NewDAO extends JpaRepository<New, Integer> {
// 按审核状态查询结果
Page<New> findByState(String state, Pageable pageable);
/*模糊查询同时对审核人员进行模糊查询*/
@Query("select n from New n where (" +
"n.user_write.realname like ?1 or " +
// "n.refer_time like ?1 or " +
"n.note_title like ?1 or " +
"n.note like ?1 or " +
"n.note_type.name like ?1 or " +
"n.user_read.realname like ?1 ) and (" +
"n.state=?2)")
Page<New> findByAllLikeByConfirmed(String keyword, String state, Pageable pageable);
/*因为未审核过所以区别于上个查询,不能对审核人进行模糊查询*/
@Query("select n from New n where (" +
"n.user_write.realname like ?1 or " +
// "n.refer_time like ?1 or " +
"n.note_title like ?1 or " +
"n.note like ?1 or " +
"n.note_type.name like ?1 ) and (" +
"n.state=?2)")
Page<New> findByAllLikeByNoConfirmed(String keyword, String state, Pageable pageable);
@Query("select n from New n where n.user_write.id=?1")
Page<New> findByUserwrite(int user_write_id, Pageable pageable);
@Query("select n from New n where (n.user_write.realname like ?1 or n.note_title like ?1 or " +
"n.note like ?1 or n.note_type.name like ?1 ) and (" +
"n.user_write.id=?2 )")
Page<New> findByAllLikeAndUser(String keyword, int user_write_id, Pageable pageable);
@Query("select n from New n where n.user_read.id=?1")
Page<New> findByUserReadId(int user_read_id, Pageable pageable);
// Page<New> findByUser_writeLikeAndAndNoteLike(User user,String note,Pageable pageable);
}
|
package com.blackjack.domain;
import lombok.EqualsAndHashCode;
/**
* Card holds suit and rank to identify any card
*/
@EqualsAndHashCode
public class Card {
private Suit suit;
private Rank rank;
/**
* Card constructor needs both suit and rank and is public to be created from command line as well
*
* @param suit Suit of card
* @param rank Rank of card
*/
public Card(Suit suit, Rank rank) {
if (suit == null || rank == null) {
throw new IllegalArgumentException("Suit and Rank is required to form a card, please provide");
}
this.suit = suit;
this.rank = rank;
}
/**
* @return the face value of card
*/
int getScore() {
return rank.getValue();
}
/**
* @return card representation in form Suit and Rank representation Names
*/
@Override
public String toString() {
return this.suit.getRepresentation() + this.rank.getRepresentation();
}
}
|
package com.quizcore.quizapp.model.entity;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.util.UUID;
@Entity
public class Category {
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
@Column(name = "id", updatable = false, nullable = false)
@Type(type="uuid-char")
public UUID id;
@Column
@Type(type="uuid-char")
UUID categoryId;
@Column
@Type(type="uuid-char")
UUID productId;
@Column
String categoryName;
public Category() { super(); }
public Category(String categoryId) {
}
public Category(UUID productId, String categoryName) {
this.productId = productId;
this.categoryName = categoryName;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public UUID getCategoryId() {
return categoryId;
}
public void setCategoryId(UUID categoryId) {
this.categoryId = categoryId;
}
public UUID getProductId() {
return productId;
}
public void setProductId(UUID productId) {
this.productId = productId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", categoryId=" + categoryId +
", productId=" + productId +
", categoryName='" + categoryName + '\'' +
'}';
}
}
|
package com.mfm_app.entities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Users")
public class User {
@Id
@Column(name = "username", length = 50)
private String username;
@Column(name = "password", length = 50, nullable = false)
private String password;
@Column(name = "total_workouts")
private int total_workouts = 0;
@Column(name = "total_weight_lifted")
private Double total_weight_lifted =0.0;
@OneToMany(targetEntity = Workout.class, fetch= FetchType.EAGER)
private List<Workout> workouts_completed = new ArrayList<>();
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String username, String password, int total_workouts, Double total_weight_lifted) {
super();
this.username = username;
this.password = password;
this.total_workouts = total_workouts;
this.total_weight_lifted = total_weight_lifted;
}
public List<Workout> getWorkouts_completed() {
return workouts_completed;
}
public void setWorkouts_completed(List<Workout> workouts_completed) {
this.workouts_completed = workouts_completed;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getTotal_workouts() {
return total_workouts;
}
public void setTotal_workouts(int total_workouts) {
this.total_workouts = total_workouts;
}
public void increase_total_workouts() {
this.total_workouts++;
}
public void decrease_total_workouts() {
this.total_workouts--;
}
public Double getTotal_weight_lifted() {
return total_weight_lifted;
}
public void setTotal_weight_lifted(Double total_weight_lifted) {
this.total_weight_lifted = total_weight_lifted;
}
public void increase_total_weight_lifted(Double increase_amount) {
this.total_weight_lifted = total_weight_lifted + increase_amount;
}
public void decrease_total_weight_lifted(Double decrease_amount) {
this.total_weight_lifted = total_weight_lifted - decrease_amount;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((total_weight_lifted == null) ? 0 : total_weight_lifted.hashCode());
result = prime * result + total_workouts;
result = prime * result + ((username == null) ? 0 : username.hashCode());
result = prime * result + ((workouts_completed == null) ? 0 : workouts_completed.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;
User other = (User) obj;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (total_weight_lifted == null) {
if (other.total_weight_lifted != null)
return false;
} else if (!total_weight_lifted.equals(other.total_weight_lifted))
return false;
if (total_workouts != other.total_workouts)
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
if (workouts_completed == null) {
if (other.workouts_completed != null)
return false;
} else if (!workouts_completed.equals(other.workouts_completed))
return false;
return true;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", total_workouts=" + total_workouts
+ ", total_weight_lifted=" + total_weight_lifted + ", workouts_completed=" + workouts_completed + "]";
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import java.util.ArrayList;
class gu$4 extends ThreadLocal<ArrayList<gu>> {
gu$4() {
}
/* renamed from: a */
protected final ArrayList<gu> initialValue() {
return new ArrayList();
}
}
|
package com.example.landmark;
//How to use ======================================================
// RequestItem item = new RequestItem("restaurant", lat, lon, 500);
// RequestItem temp = new RequestItem().setItem(name, id, lat, lng);
//=================================================================
public class RequestItem {
public String name;
public String type;
public double lat;
public double lng;
public int radius;
public String id;
public double rating;
public String address;
public String error = "success";
public RequestItem(){}
// 어떤 지점(lat, lng) 근처(radius)의 특정 장소(type) 요청할때 아이템
// sendRequest()에 정보전달할때 쓰임
public RequestItem(String type, double lat, double lng, int radius) {
this.type = type;
this.lat = lat;
this.lng = lng;
this.radius = radius;
}
public RequestItem requestDetailsItem(String id){
RequestItem result = new RequestItem();
result.id = id;
return result;
}
public RequestItem setItem(String name, String id, double lat, double lng){
RequestItem result = new RequestItem();
result.name = name;
result.id = id;
result.lat = lat;
result.lng = lng;
return result;
}
public RequestItem setDetailsItem(double rating, String address){
RequestItem result = new RequestItem();
result.rating = rating;
result.address = address;
return result;
}
public RequestItem setError(){
RequestItem result = new RequestItem();
result.error = "error";
return result;
}
}
|
package com.example.legia.mobileweb.DTO;
public class themSanPhamMua {
private int idgio_hang;
private int iduser;
private int ma_san_pham;
public themSanPhamMua() {
super();
}
public int getIdgio_hang() {
return idgio_hang;
}
public void setIdgio_hang(int idgio_hang) {
this.idgio_hang = idgio_hang;
}
public int getIduser() {
return iduser;
}
public void setIduser(int iduser) {
this.iduser = iduser;
}
public int getMa_san_pham() {
return ma_san_pham;
}
public void setMa_san_pham(int ma_san_pham) {
this.ma_san_pham = ma_san_pham;
}
}
|
public class HexandOct {
static String convertString(String str){
if (str.length() >= 2){
String beginning = str.substring(0,2);
int integer = 0 ;
if (beginning.toLowerCase().contains("0x")){
//convert to hexadecimal
String str1 = str.substring(2);
//System.out.println(" " + Integer.parseInt(str1,16));
integer = Integer.parseInt(str1,16);
}else if (beginning.substring(0,1).toLowerCase().contains("0")){
String str1 = str.substring(1);
//System.out.println(" asfsdfasdf" + Integer.parseInt(str1,8));
integer = Integer.parseInt(str1,8);
}else{
//System.out.println(" " + Integer.parseInt(str,10));
integer = Integer.parseInt(str,10);
}
return Integer.toString(integer);
}else
return str;
}
}
|
package easy;
/* Sample code to read in test cases:*/
import java.io.*;
public class RollerCoaster {
public static void main (String[] args) throws IOException {
File file = new File(args[0]);
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line = " To be, or not to be: that is the question.";
while ((line = buffer.readLine()) != null) {
line = line.trim();
boolean cap = true;
StringBuffer sb = new StringBuffer();
char ch;
for(int i=0;i<line.length();i++){
ch = line.charAt(i);
if(Character.isAlphabetic(ch)){
if(cap){
ch = Character.toUpperCase(ch);
cap = false;
}else{
ch = Character.toLowerCase(ch);
cap = true;
}
}
sb.append(ch);
}
System.out.println(sb.toString());
sb = new StringBuffer();
}
}
}
|
import java.util.*;
/**
* N-Gram Problem - Lab 2
*
* @author Mayank Jariwala
* @version 0.1.0
*/
public class NGram {
private int nGramValue;
private List<String> nGramWords = new ArrayList<>();
private List<String> maxOccurrenceWords = new ArrayList<>();
private String[] nGramsWordsInput;
private List<Integer> nGramCount = new ArrayList<>();
// Driver Function
public static void main(String[] args) {
NGram nGram = new NGram();
Scanner scanner = new Scanner(System.in);
int noOfLines = scanner.nextInt();
// Initialize Array Size
nGram.nGramsWordsInput = new String[noOfLines];
scanner.nextLine();
String singleLineInp;
for (int i = 0; i <= noOfLines; i++) {
singleLineInp = scanner.nextLine();
if (i == noOfLines)
nGram.nGramValue = Integer.parseInt(singleLineInp);
else
nGram.nGramsWordsInput[i] = singleLineInp;
}
Arrays.asList(nGram.nGramsWordsInput).forEach(nGram::process);
int maxValue = Collections.max(nGram.nGramCount);
for (int k = 0; k < nGram.nGramWords.size(); k++) {
if (nGram.nGramCount.get(k).equals(maxValue)) {
nGram.maxOccurrenceWords.add(nGram.nGramWords.get(k));
}
}
nGram.maxOccurrenceWords.sort(null);
System.out.print(nGram.getNGramString() + " " + nGram.maxOccurrenceWords.get(0));
}
/**
* @return String with NGram - UniGram,BiGram,Trigram
*/
private String getNGramString() {
String gramText = "";
switch (nGramValue) {
case 1:
gramText = "Unigram";
break;
case 2:
gramText = "Bigram";
break;
case 3:
gramText = "Trigram";
break;
default:
break;
}
return gramText;
}
//Processing function
private void process(String singleLineInp) {
boolean indexLimitReached = false;
int startIndex = 0, lastIndex;
do {
lastIndex = startIndex + nGramValue;
if (lastIndex <= singleLineInp.length()) {
String subString = singleLineInp.substring(startIndex, lastIndex);
if (subString.matches("[a-z]{1,}")) {
int index = in_list(nGramWords, subString);
if (index == -1) {
nGramWords.add(subString);
nGramCount.add(1);
} else {
int specificWordCount = nGramCount.get(index) + 1;
nGramCount.set(index, specificWordCount);
}
}
startIndex++;
} else
indexLimitReached = true;
} while (!indexLimitReached);
}
// checks whether given value exists inside list
private int in_list(List<String> nGramWords, String word) {
int foundElementIndex = -1;
if (nGramWords == null)
return foundElementIndex;
for (int i = 0; i < nGramWords.size(); i++) {
if (nGramWords.contains(word)) {
foundElementIndex = nGramWords.indexOf(word);
break;
}
}
return foundElementIndex;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.