text
stringlengths 10
2.72M
|
|---|
package ru.cardsmobile.test.service;
import ru.cardsmobile.test.dto.ClaimDto;
import ru.cardsmobile.test.dto.CustomClaimDto;
import ru.cardsmobile.test.dto.MegaClaimDto;
import ru.cardsmobile.test.model.CustomClaim;
import ru.cardsmobile.test.model.MegaClaim;
import ru.cardsmobile.test.repository.ClaimRepository;
import org.modelmapper.ModelMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional
public class ClaimServiceImpl implements ClaimService {
private static final Logger LOG = LoggerFactory.getLogger(ClaimServiceImpl.class.getName());
private ClaimRepository<CustomClaim> customClaimRepository;
private ClaimRepository<MegaClaim> megaClaimRepository;
private ModelMapper mapper;
@Autowired
public void setMapper(ModelMapper mapper) {
this.mapper = mapper;
}
@Autowired
public void setCustomClaimRepository(ClaimRepository<CustomClaim> customClaimRepository) {
this.customClaimRepository = customClaimRepository;
}
@Autowired
public void setMegaClaimRepository(ClaimRepository<MegaClaim> megaClaimRepository) {
this.megaClaimRepository = megaClaimRepository;
}
public CustomClaimDto save(CustomClaimDto claimDto) {
CustomClaim claim = mapper.map(claimDto, CustomClaim.class);
claim = customClaimRepository.save(claim);
LOG.debug("Claim saved with id {}", claim.getId());
return mapper.map(claim, CustomClaimDto.class);
}
@Override
public MegaClaimDto save(MegaClaimDto claimDto) {
MegaClaim claim = mapper.map(claimDto, MegaClaim.class);
claim = megaClaimRepository.save(claim);
LOG.debug("Claim saved with id {}", claim.getId());
return mapper.map(claim, MegaClaimDto.class);
}
@Override
public ClaimDto find(String id) {
return null;
}
}
|
package com.fnsvalue.skillshare.dto;
import org.springframework.web.multipart.MultipartFile;
public class Board {
private int board_no_pk;
private String user_tb_user_id_pk;
private String board_tit;
private String board_con;
private String board_dt;
private String my_sk;
private String want_sk;
private String board_dur;
private String board_fl;
private String read_cnt;
private String report_id;
private String report_rs;
private String report_con;
private int page;
private int perPageNum;
private int page_start;
private int perpage_num;
public boolean isPrev() {
return prev;
}
public void setPrev(boolean prev) {
this.prev = prev;
}
public boolean isNext() {
return next;
}
public void setNext(boolean next) {
this.next = next;
}
private int totalCount;
private int startPage;
private int endPage;
private boolean prev;
private boolean next;
//------board-----------------------------------
public String getRead_cnt() {
return read_cnt;
}
public void setRead_cnt(String read_cnt) {
this.read_cnt = read_cnt;
}
public String getReport_id() {
return report_id;
}
public void setReport_id(String report_id) {
this.report_id = report_id;
}
public String getReport_rs() {
return report_rs;
}
public void setReport_rs(String report_rs) {
this.report_rs = report_rs;
}
public String getReport_con() {
return report_con;
}
public void setReport_con(String report_con) {
this.report_con = report_con;
}
public int getBoard_no_pk() {
return board_no_pk;
}
public void setBoard_no_pk(int board_no_pk) {
this.board_no_pk = board_no_pk;
}
public String getUser_tb_user_id_pk() {
return user_tb_user_id_pk;
}
public void setUser_tb_user_id_pk(String user_tb_user_id_pk) {
this.user_tb_user_id_pk = user_tb_user_id_pk;
}
public String getBoard_tit() {
return board_tit;
}
public void setBoard_tit(String board_tit) {
this.board_tit = board_tit;
}
public String getBoard_con() {
return board_con;
}
public void setBoard_con(String board_con) {
this.board_con = board_con;
}
public String getBoard_dt() {
return board_dt;
}
public void setBoard_dt(String board_dt) {
this.board_dt = board_dt;
}
public String getMy_sk() {
return my_sk;
}
public void setMy_sk(String my_sk) {
this.my_sk = my_sk;
}
public String getWant_sk() {
return want_sk;
}
public void setWant_sk(String want_sk) {
this.want_sk = want_sk;
}
public String getBoard_dur() {
return board_dur;
}
public void setBoard_dur(String board_dur) {
this.board_dur = board_dur;
}
public String getBoard_fl() {
return board_fl;
}
public void setBoard_fl(String board_fl) {
this.board_fl = board_fl;
}
//----------------------------------------------------------------
public Board() { //페이지 초기설정
this.page=1; // 처음에는 첫페이지
perPageNum=10; //게시물 10개씩
}
public void setPage(int page) { //페이지 set
if(page<=0){ //페이지 오류시
this.page =1; //페이지번호 1로
return;
}
this.page=page;
}
public void setPerPageNum(int perPageNum) { //게시물갯수 set
if(perPageNum <=0 || perPageNum>100){
this.perPageNum=10;
return;
}
this.perPageNum = perPageNum;
}
public int getPage() { //page get
return page;
}
//method for MyBatis SQL Mapper-
public int getPageStart(){ // 해당 페이지의 게시물들 get
this.page_start = (this.page-1)*perPageNum;
return (this.page-1)*perPageNum;
}
public int getStartPage() {
return startPage;
}
public void setStartPage(int startPage) {
this.startPage = startPage;
}
public int getEndPage() {
return endPage;
}
public void setEndPage(int endPage) {
this.endPage = endPage;
}
public int getPerPageNum() {
this.perpage_num = perPageNum;
return perPageNum;
}
@Override
public String toString(){
return "Criteria [page="+page+","+"perPageNum"+perPageNum+"]";
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) //전체게시물 받음
{
this.totalCount=totalCount; //전체게시물 받고
calcData(); //끝페이지, 시작페이지, 앞으로, 뒤로 설정
}
private void calcData()
{
endPage=(int)(Math.ceil(this.getPage()/(double)perPageNum)*perPageNum);
startPage=(endPage-perPageNum)+1;
int tempEndPage=(int) (Math.ceil(totalCount/(double)this.getPerPageNum()));
if(endPage>tempEndPage)
{
endPage=tempEndPage;
}
prev=startPage == 1?false :true;
next=endPage * this.getPerPageNum()>=totalCount?false :true;
}
public int getPage_start() {
return page_start;
}
public void setPage_start(int page_start) {
this.page_start = page_start;
}
public int getPerpage_num() {
return perpage_num;
}
public void setPerpage_num(int perpage_num) {
this.perpage_num = perpage_num;
}
}
|
package com.example.accounting_app.activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import com.example.accounting_app.R;
import com.example.accounting_app.adapter.adapter_activity_house_rate;
import com.example.accounting_app.fragment.fragment_house_rate_business;
import com.example.accounting_app.fragment.fragment_house_rate_combination;
import com.example.accounting_app.fragment.fragment_house_rate_find;
import com.example.accounting_app.fragment.fragment_house_rate_public_fund;
import com.example.accounting_app.listener.listener_activity_house_rate;
import com.yatoooon.screenadaptation.ScreenAdapterTools;
import java.util.ArrayList;
import java.util.List;
/**
* @Creator cetwag yuebanquan
* @Version V2.0.0
* @Time 2019.6.28
* @Description 房贷计算器类
*/
public class activity_house_rate extends AppCompatActivity {
public ViewPager viewpager;
public List<Fragment> pages = new ArrayList<>();
adapter_activity_house_rate adapter;
listener_activity_house_rate listener;
public RadioButton rdb_business, rdb_public_fund, rdb_combination, rdb_find;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_house_rate);
//屏幕适配
ScreenAdapterTools.getInstance().reset(this);//如果希望android7.0分屏也适配的话,加上这句
ScreenAdapterTools.getInstance().loadView(getWindow().getDecorView());
//控件初始化
init();
//适配器功能方法
adapter.adapter_Activity_house_rate();
//监听功能方法
listener.listener_Activity_house_rate();
}
void init() {
viewpager = findViewById(R.id.viewpager);
adapter = new adapter_activity_house_rate(this);
listener = new listener_activity_house_rate(this);
//将房贷计算器的四个碎片类装入
pages.add(new fragment_house_rate_business());
pages.add(new fragment_house_rate_public_fund());
pages.add(new fragment_house_rate_combination());
pages.add(new fragment_house_rate_find());
rdb_business = findViewById(R.id.rdb_business);
rdb_public_fund = findViewById(R.id.rdb_public_fund);
rdb_combination = findViewById(R.id.rdb_combination);
rdb_find = findViewById(R.id.rdb_find);
}
}
|
package com.altimetrik;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class HelloWorld {
@GET
@Produces(MediaType.TEXT_HTML)
public String getMsg() {
return "Hello RESTFULL";
}
}
|
package micro.usuarios.publicos.services;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import dao.auth.usuarios.publicos.PermisoPublicoDao;
import dao.auth.usuarios.publicos.ResetTokenPublicoDao;
import dao.auth.usuarios.publicos.UsuarioPublicoDao;
import dto.main.Respuesta;
import excepciones.controladas.ErrorInternoControlado;
import micro.usuarios.publicos.interfaces.IEmailService;
import micro.usuarios.publicos.interfaces.IRegistroService;
import model.auth.usuarios.publicos.PermisoPublico;
import model.auth.usuarios.publicos.ResetTokenPublico;
import model.auth.usuarios.publicos.UsuarioPublico;
import utils._config.language.Translator;
@Service
public class RegistroService implements IRegistroService {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
UsuarioPublicoDao usuariosPublicoDao;
@Autowired
PermisoPublicoDao permisoPublicoDao;
@Autowired
private BCryptPasswordEncoder bcrypt;
@Autowired
IEmailService emailService;
@Autowired
private ResetTokenPublicoDao resetTokenPublicoDao;
@Value("${correo.registro}")
String registro;
@Override
public Respuesta<UsuarioPublico> crear(UsuarioPublico usuarioPublico) {
UsuarioPublico usuario = usuariosPublicoDao.findByUsernameOrEmail(usuarioPublico.getUsername(),
usuarioPublico.getCorreo());
if (usuario != null) {// EXISTE EN LA BASE DE DATOS
return ErrorInternoControlado.usuarioDuplicado(usuarioPublico.getUsername());
}
usuarioPublico.setPassword(bcrypt.encode(usuarioPublico.getPassword()));
usuarioPublico.setPermisos(new HashSet<PermisoPublico>(permisoPublicoDao.findAll()));
usuarioPublico.setLimitRequest(100);
usuarioPublico.setTimeUnitRequest(TimeUnit.MINUTES);
usuarioPublico.setTimeUnitToken(TimeUnit.MINUTES);
usuarioPublico.setTokenExpiration(60);
usuarioPublico = usuariosPublicoDao.saveAndFlush(usuarioPublico);
emailService.registro(new String[] { usuarioPublico.getCorreo() }, new String[] {}, new String[] {},
"Bienvenido", usuarioPublico, registro);
return new Respuesta<UsuarioPublico>(200, usuarioPublico,
Translator.toLocale("usuarios.publico.registroservice.crear"));
}
@Override
public Respuesta<String> activarUsuario(String token) {
ResetTokenPublico rt = resetTokenPublicoDao.findByToken(token);
if (rt != null) {
if (!rt.isExpirado()) {
UsuarioPublico usuarioPublico = usuariosPublicoDao.findByUsernameOrEmail(
rt.getUsuarioPublico().getUsername(), rt.getUsuarioPublico().getCorreo());
usuarioPublico.setEnabled(true);
usuarioPublico = usuariosPublicoDao.saveAndFlush(usuarioPublico);
resetTokenPublicoDao.delete(rt);
return new Respuesta<String>(200, "",
Translator.toLocale("usuarios.publico.registroservice.activarusuario"));
} else {
return ErrorInternoControlado.tokenExpirado(null);
}
} else {
return ErrorInternoControlado.tokenNoExiste(null);
}
}
}
|
package com.tencent.mm.plugin.card.ui;
import com.tencent.mm.plugin.card.model.am;
import com.tencent.mm.plugin.card.model.g;
import com.tencent.mm.ui.base.h.c;
class CardNewMsgUI$7 implements c {
final /* synthetic */ int eKj;
final /* synthetic */ CardNewMsgUI hFN;
CardNewMsgUI$7(CardNewMsgUI cardNewMsgUI, int i) {
this.hFN = cardNewMsgUI;
this.eKj = i;
}
public final void ju(int i) {
switch (i) {
case 0:
g gVar = (g) CardNewMsgUI.a(this.hFN).getItem(this.eKj);
if (gVar != null) {
am.axm().xj(gVar.field_msg_id);
CardNewMsgUI.g(this.hFN);
CardNewMsgUI.a(this.hFN).a(null, null);
return;
}
return;
default:
return;
}
}
}
|
package homework;
import java.util.ArrayList;
import java.util.Date;
import java.util.ListIterator;
class Bank //3-37
{
private Account account;
private ArrayList userList;
public Bank(Account account)
{
this.account = account;
}
public boolean createAccount()
{
if (userList.contains(account.getUserName()))
{
return false;
}
else
{
account.setDate(new Date());
userList.add(account.getUserName());
return true;
}
}
public boolean saveMoney(double money)
{
if (userList.contains(account))
{
account.setBalance(money,'+');
return true;
}
else
return false;
}
public boolean withDrawals(double money)
{
if (userList.contains(account))
{
if (account.getBalance() - money < 0)
{
return false;
}
else
{
account.setBalance(money, '-');
return true;
}
}
return true;
}
public boolean search(Account account)
{
if (!userList.contains(account))
{
return false;
}
else
{
ListIterator listIterator = userList.listIterator();
while (listIterator.hasNext())
{
if (listIterator.equals(account))
{
System.out.println("User exists\n" + account.getBalance());
System.out.println(account.getDate());
System.out.println(account.getName());
System.out.println(account.getUserName());
System.out.println(account.getId());
break;
}
}
}
return true;
}
public boolean deleteUser(Account account)
{
if(!userList.contains(account))
return false;
else
{
userList.remove(account);
return true;
}
}
}
class Account
{
private String name;
private double balance=0;
private String id;
private Date date;
private String userName;
public String getName()
{
return name;
}
public double getBalance()
{
return balance;
}
public String getId()
{
return id;
}
public Date getDate()
{
return date;
}
public String getUserName()
{
return userName;
}
public void setName(String name)
{
this.name = name;
}
public void setBalance(double money, char ch)
{
if (ch == '+')
{
balance+=money;
}
else if (ch == '-')
{
balance-=money;
}
}
public void setId(String id)
{
this.id = id;
}
public void setDate(Date date)
{
this.date = date;
}
public void setUserName(String userName)
{
this.userName = userName;
}
}
|
package com.takshine.wxcrm.service;
/**
* 地址信息服务
* @author admin
*
*/
public interface WxAddressInfoService {
/**
* 根据经纬度查询地址信息
* @param lat
* @param lng
* @return
*/
public String getAddressNameByLatLng(String lat, String lng);
}
|
package it.usi.xframe.xas.bfimpl.sms.providers.vodafonepop;
public class VodafoneRuntimeException extends RuntimeException
{
/**
* Serial Version.
*/
private static final long serialVersionUID = 1L;
public VodafoneRuntimeException(String message) {
super(message);
}
public VodafoneRuntimeException(String message, Throwable throwable) {
super(message, throwable);
}
}
|
package com.trainex.uis.main;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import okio.Buffer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import com.trainex.R;
import com.trainex.diaglog.CustomAlertDialog;
import com.trainex.diaglog.CustomProgressDialog;
import com.trainex.rest.NoteRestAPI;
import com.trainex.rest.RestClient;
public class RequestFreeSessionActivity extends AppCompatActivity {
private ImageButton imgClose;
private EditText edtDate;
private Spinner spnHour;
private Spinner spnMinute;
private Spinner spn24h;
private Button btnSubmit;
private ArrayList<String> listHour;
private ArrayList<String> listMinute;
private ArrayList<String> listIs24h;
private String token;
private CustomProgressDialog progressDialog;
private String stringDate, stringTime;
private int idTrainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request_free_session);
progressDialog = new CustomProgressDialog(RequestFreeSessionActivity.this);
SharedPreferences prefs = getSharedPreferences("MY_SHARE_PREFERENCE", MODE_PRIVATE);
token = prefs.getString("token", "");
idTrainer = getIntent().getIntExtra("idTrainer", 0);
init();
bind();
}
private void init() {
imgClose = (ImageButton) findViewById(R.id.imgClose);
edtDate = (EditText) findViewById(R.id.edtDate);
spnHour = (Spinner) findViewById(R.id.spnHour);
spnMinute = (Spinner) findViewById(R.id.spnMinute);
spn24h = (Spinner) findViewById(R.id.spn24h);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
}
private void bind() {
setUpForSpinner();
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!token.equalsIgnoreCase("")) {
if (!edtDate.getText().toString().equalsIgnoreCase("")) {
progressDialog = new CustomProgressDialog(RequestFreeSessionActivity.this);
progressDialog.show();
stringTime = spnHour.getSelectedItem().toString() + ":" + spnMinute.getSelectedItem().toString() + " " + spn24h.getSelectedItem().toString();
String request = stringDate + " " + stringTime;
String dateTimeRequestFreeSession = "{\n" +
" \"date_time\":" + "\"" + request + "\"" + ",\n" +
" \"trainer_id\":" + idTrainer + "\n" +
"}";
Log.e("token", token);
Log.e("dateTime", request);
Call<JsonElement> callRequestFreeSession = RestClient.getApiInterface().requestFreeSession(NoteRestAPI.stringToRequestBody(dateTimeRequestFreeSession), token);
try {
Buffer buffer = new Buffer();
NoteRestAPI.stringToRequestBody(dateTimeRequestFreeSession).writeTo(buffer);
Log.e("request", buffer.readUtf8());
} catch (Exception e) {
}
Log.e("request", callRequestFreeSession.request().headers().toString());
Log.e("request", callRequestFreeSession.request().body().toString());
callRequestFreeSession.enqueue(new Callback<JsonElement>() {
@Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
int code = response.code();
Log.e("code", code + "");
progressDialog.dismiss();
if (response.isSuccessful()) {
if (code == 200) {
JsonObject body = response.body().getAsJsonObject();
int codeBody = body.get("code").getAsInt();
if (codeBody == 200) {
Intent intent = new Intent(RequestFreeSessionActivity.this, CallUsActivity.class);
intent.putExtra("title", "Request A Free Session");
intent.putExtra("thankyou", "Thank you for booking !");
startActivity(intent);
}else if(codeBody == 18){
CustomAlertDialog alertDialog = new CustomAlertDialog(RequestFreeSessionActivity.this,"Request Error!","You have already booked","Ok") {
@Override
public void doSomethingWhenDismiss() {
}
};
alertDialog.show();
} else{
String s = "";
if (body.has("error")){
s = body.get("error").getAsString();
}
if (body.has("message")){
s = body.get("message").getAsString();
}
CustomAlertDialog alertDialog = new CustomAlertDialog(RequestFreeSessionActivity.this,"Request Error!",s,"Ok") {
@Override
public void doSomethingWhenDismiss() {
}
};
alertDialog.show();
}
}
} else {
try {
Log.e("errorBody", response.errorBody().string());
} catch (Exception e) {
Log.e("errorExcep", e.toString());
e.printStackTrace();
}
}
}
@Override
public void onFailure(Call<JsonElement> call, Throwable t) {
CustomAlertDialog alertDialog = new CustomAlertDialog(RequestFreeSessionActivity.this, "Connection Error!", "Please check your internet!", "Ok") {
@Override
public void doSomethingWhenDismiss() {
}
};
alertDialog.show();
}
});
}
} else {
CustomAlertDialog alertDialog = new CustomAlertDialog(RequestFreeSessionActivity.this, "Request Error!", "You must login to request a free session", "Later") {
@Override
public void doSomethingWhenDismiss() {
}
};
alertDialog.show();
}
}
});
final Calendar cal = Calendar.getInstance();
edtDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DatePickerDialog datePickerDialog = new DatePickerDialog(RequestFreeSessionActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker datePicker, int y, int m, int d) {
stringDate = d + "-" + (m + 1) + "-" + y;
edtDate.setText(stringDate);
datePicker.setMinDate(Calendar.getInstance().getTimeInMillis());
}
}, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
});
imgClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
private void setUpForSpinner() {
listHour = new ArrayList<>();
listMinute = new ArrayList<>();
listIs24h = new ArrayList<>();
for (int i = 1; i < 13; i++) {
listHour.add(i + "");
}
for (int i = 0; i < 60; i++) {
if (i < 10) {
listMinute.add("0" + i);
} else {
listMinute.add(i + "");
}
}
listIs24h.add("AM");
listIs24h.add("PM");
ArrayAdapter<String> adapterHour = new ArrayAdapter<String>(RequestFreeSessionActivity.this, R.layout.item_spinner, listHour);
ArrayAdapter<String> adapterMinute = new ArrayAdapter<String>(RequestFreeSessionActivity.this, R.layout.item_spinner, listMinute);
ArrayAdapter<String> adapterIs24h = new ArrayAdapter<String>(RequestFreeSessionActivity.this, R.layout.item_spinner, listIs24h);
spnHour.setAdapter(adapterHour);
spnMinute.setAdapter(adapterMinute);
spn24h.setAdapter(adapterIs24h);
}
}
|
package chapter_1_06_Interfaces;
public class Local {
int k = 3;
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
final int j = 6;
class InnerLocal {
int getInt () {
//return k; //No Access to outer class
return 5 + j; //Has access only to final loval var
}
}
System.out.println((new InnerLocal()).getInt());
System.out.println((new InnerLocal()).getClass());
System.out.println((new InnerLocal()).getClass().getEnclosingClass());
}
}
|
package org.jboss.perf.test.server.dao.impl;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import org.jboss.perf.test.server.dao.ResultDao;
import org.jboss.perf.test.server.model.Result;
import org.jboss.perf.test.server.rest.RepRESTService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Stateless
public class ResultDaoImpl implements ResultDao {
private static final Logger logger = LoggerFactory.getLogger(ResultDaoImpl.class);
@Inject
private EntityManager em;
private Double buildAndExecuteQuery(TypedQuery<Double> query, long testSuiteRunId, long methodId, Long attributeId) {
return query.setParameter("testSuiteRunId", testSuiteRunId)
.setParameter("methodId", methodId)
.setParameter("attributeId", attributeId)
.getSingleResult();
}
@Override
public List<Result> getAttributeResultsOrderById(long attrResultId) {
return em.createNamedQuery("attributeResultsOrderById", Result.class)
.setParameter("attrResultId", attrResultId)
.getResultList();
}
@Override
public Double getAvgResultByTestSuiteRunIdAndByMethodIdAndByAttributeId(long testSuiteRunId,
long methodId, long attributeId) {
TypedQuery<Double> query = em.createNamedQuery("getAvgResultByTestSuiteRunIdAndByMethodIdAndByAttributeId", Double.class);
return buildAndExecuteQuery(query, testSuiteRunId, methodId, attributeId);
}
@Override
public Double getMinResultByTestSuiteRunIdAndByMethodIdAndByAttributeId(long testSuiteRunId,
long methodId, long attributeId) {
TypedQuery<Double> query = em.createNamedQuery("getMinResultByTestSuiteRunIdAndByMethodIdAndByAttributeId", Double.class);
return buildAndExecuteQuery(query, testSuiteRunId, methodId, attributeId);
}
@Override
public Double getMaxResultByTestSuiteRunIdAndByMethodIdAndByAttributeId(long testSuiteRunId,
long methodId, long attributeId) {
TypedQuery<Double> query = em.createNamedQuery("getMaxResultByTestSuiteRunIdAndByMethodIdAndByAttributeId", Double.class);
return buildAndExecuteQuery(query, testSuiteRunId, methodId, attributeId);
}
@Override
public Double getAvgAttributeResultsValue(long attrResultId) {
return em.createNamedQuery("getAvgAttributeResultsValue", Double.class)
.setParameter("attrResultId", attrResultId)
.getSingleResult();
}
@Override
public Double getMinAttributeResultsValue(long attrResultId) {
return em.createNamedQuery("getMinAttributeResultsValue", Double.class)
.setParameter("attrResultId", attrResultId)
.getSingleResult();
}
@Override
public Double getMaxAttributeResultsValue(long attrResultId) {
return em.createNamedQuery("getMaxAttributeResultsValue", Double.class)
.setParameter("attrResultId", attrResultId)
.getSingleResult();
}
@Override
public Double getStdDevAttributeResultsValue(long attrResultId) {
try{
return (Double) em.createNativeQuery("select stddev(value) from result where attrresult_id = :attrResultId")
.setParameter("attrResultId", attrResultId)
.getSingleResult();
} catch (Throwable t){
logger.warn("Unable to calculate STDDEV: " + t);
return null;
}
}
}
|
package com.rd.agergia.base;
import java.util.List;
import java.util.Map;
import com.rd.agergia.common.entity.Pager;
import com.rd.agergia.common.entity.PagerParam;
public interface BaseDao<T> {
/**
*插入一条记录
* @param entity
*/
public void save(T obj);
/**
* 根据id查询一条记录
* @param classentity
* @param entityId
* @return
*/
@SuppressWarnings("hiding")
public<T> T find(T obj,Object entityId);
/**
* 更新记录
* @param entity
*/
public void update(T obj);
/**
* 根据id删除指定记录
* @param entityId
*/
@SuppressWarnings("hiding")
public <T>void delete(Class<T> entityClass,Object entityId);
/**
* 批量删除记录
* @param entityIds
*/
@SuppressWarnings("hiding")
public <T>void delete(Class<T> entityClass,Object []entityIds);
/**
* 分页查询
* @param entityClass
* @param firstIndex
* @param resultMax
* @param wheresql
* @param params
* @param orderby
* @return
*/
public Pager<T> getPageingData(Class<T> entityClass,PagerParam params);
}
|
/**
* Package containing the components for the sequence panel: A panel allowing
* one of a number of sequences of filters to be applied to the image, and the
* creation of new sequences.
* <div>
* <b>See Also:</b><br/>
* {@link fotoshop.GUI.SequencePanel.FilterSequencePanel}: The JPanel for the
* application of a sequence of filters through specific buttons, or the creation
* of a new sequence.<br/><br/>
* {@link fotoshop.GUI.SequencePanel.SequenceConstructorPanel}: JPanel displayed
* in a dialog for the construction of a new sequence of filters. Created by
* entering a name into a JTextField, and selecting from a list of JButtons of
* the available filters. Upon selecting a filter it will appear in a JScrollPane
* along with a JFormattedTextField, allowing the entry of a value to be applied
* with this filter. Accepting the new filter adds a SequenceButton to the main
* FilterSequencePanel.<br/><br/>
* {@link fotoshop.GUI.SequencePanel.SequenceButton}: A JButton that contains
* the name of a sequence and a list of PropertyMessages containing the name of
* each filter to be applied.<br/>
* </div>
*@author Benjamin Nicholls, bn65@kent.ac.uk
*/
package fotoshop.GUI.SequencePanel;
|
package com.hqb.patshop.mbg.dao;
import com.hqb.patshop.mbg.model.SmsTopic;
import com.hqb.patshop.app.home.dto.TopicAndSecTopic;
import java.util.List;
public interface SmsTopicDao {
int deleteByPrimaryKey(Integer id);
int insert(SmsTopic record);
int insertSelective(SmsTopic record);
SmsTopic selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(SmsTopic record);
int updateByPrimaryKey(SmsTopic record);
List<SmsTopic> selectAllBySecTopicId(int secTopicId);
List<TopicAndSecTopic> selectAllByHotTopic(Integer hotTopic);
List<TopicAndSecTopic> selectAllByCategory(String categoryName);
}
|
package lando.systems.ld36.ai.states;
import com.badlogic.gdx.Gdx;
import lando.systems.ld36.entities.GameObject;
/**
* Created by dsgraham on 8/28/16.
*/
public class ChaseState extends State {
public ChaseState(GameObject owner){
super(owner);
}
@Override
public void update(float dt) {
float moveLeft = owner.moveSpeed * dt;
float offsetX = owner.position.x < owner.level.player.position.x ? -32 : 32;
owner.movePoint.set(owner.level.player.position.x + offsetX, owner.level.player.position.y);
moveLeft = owner.updateMove(dt, moveLeft);
owner.direction.set(owner.level.player.position.x - owner.position.x, owner.level.player.position.y - owner.position.y);
}
@Override
public void onEnter() {
}
@Override
public void onExit() {
}
}
|
package com.hawk.mgc.web;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.hawk.mgc.model.User;
import com.hawk.mgc.service.UserService;
@Controller
@SessionAttributes(types = User.class)
public class UserController {
Logger LOGGER = LoggerFactory.getLogger(UserController.class);
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@ModelAttribute("roleTypes")
public List<String> populateContactTypes() {
return Arrays.asList("manager", "user");
}
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String processFindAll(Map<String, Object> model) {
List<User> results = this.userService.findAllUsers();
model.put("selections", results);
return "user/listUser";
}
@RequestMapping(value = "/users/new", method = RequestMethod.GET)
public String initCreationForm(Map<String, Object> model) {
User user = new User();
model.put("user", user);
return "user/createOrUpdateUser";
}
@RequestMapping(value = "/users/new", method = RequestMethod.POST)
public String processCreationForm(@Valid User user, BindingResult result) {
new CreateUserValidator(userService).validate(user, result);
if (result.hasErrors()) {
return "user/createOrUpdateUser";
} else {
this.userService.saveUser(user);
return "redirect:/users";
}
}
@RequestMapping(value = "/users/{userId}/edit", method = RequestMethod.GET)
public String initUpdateForm(@PathVariable("userId") int userId,
Map<String, Object> model) {
User user = userService.findUserById(userId);
LOGGER.debug("the user is:" + user);
model.put("user", user);
return "user/createOrUpdateUser";
}
@RequestMapping(value = "/users/{userId}/edit", method = RequestMethod.POST)
public String processUpdateForm(@Valid User user, BindingResult result) {
if (result.hasErrors()) {
return "user/createOrUpdateUser";
} else {
LOGGER.debug("the user after is:" + user);
this.userService.saveUser(user);
return "redirect:/users";
}
}
@RequestMapping(value = "/users/{userId}/delete", method = RequestMethod.GET)
public String deleteUser(@PathVariable("userId") int userId,
Map<String, Object> model) {
this.userService.deleteUserById(userId);
return processFindAll(model);
}
}
|
package com.shaoye.aop.db;
import org.springframework.util.Assert;
/**
* 数据源选择类
* @author hufan
*/
public class DataSourceSwitcher {
/** 使用 ThreadLocal是为了线程安全 **/
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
/** 主库(写库) **/
public static final String MASTER_DATA_SOURCE = "master";
/** 从库(读库) **/
public static final String SLAVE_DATA_SOURCE = "slave";
public static void setDataSource(String dataSource) {
Assert.notNull(dataSource, "dataSource cannot be null");
contextHolder.set(dataSource);
}
public static void setMaster() {
clearDataSource();
}
public static void setSlave() {
setDataSource(SLAVE_DATA_SOURCE);
}
public static String getDataSource() {
return (String) contextHolder.get();
}
public static void clearDataSource() {
contextHolder.remove();
}
}
|
/*
* Copyright (C) 2020-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.services.txns.validation;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_CUSTOM_FEE_SCHEDULE_KEY;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.INVALID_PAUSE_KEY;
import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.OK;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.BDDMockito.any;
import static org.mockito.BDDMockito.given;
import com.hedera.services.sigs.utils.ImmutableKeyUtils;
import com.hederahashgraph.api.proto.java.Key;
import com.hederahashgraph.api.proto.java.KeyList;
import java.util.function.Predicate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
class TokenListChecksTest {
@Mock
Predicate<Key> adminKeyRemoval;
@Test
void permitsAdminKeyRemoval() {
TokenListChecks.adminKeyRemoval = adminKeyRemoval;
given(adminKeyRemoval.test(any())).willReturn(true);
final var validity = TokenListChecks.checkKeys(
true, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance());
assertEquals(OK, validity);
TokenListChecks.adminKeyRemoval = ImmutableKeyUtils::signalsKeyRemoval;
}
@Test
void checksInvalidFeeScheduleKey() {
final var invalidKeyList1 = KeyList.newBuilder().build();
final var invalidFeeScheduleKey =
Key.newBuilder().setKeyList(invalidKeyList1).build();
final var validity = TokenListChecks.checkKeys(
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
false, Key.getDefaultInstance(),
true, invalidFeeScheduleKey,
false, Key.getDefaultInstance());
assertEquals(INVALID_CUSTOM_FEE_SCHEDULE_KEY, validity);
}
@Test
void checksInvalidPauseKey() {
final var invalidKeyList1 = KeyList.newBuilder().build();
final var invalidPauseKey = Key.newBuilder().setKeyList(invalidKeyList1).build();
final var validity = TokenListChecks.checkKeys(
false,
Key.getDefaultInstance(),
false,
Key.getDefaultInstance(),
false,
Key.getDefaultInstance(),
false,
Key.getDefaultInstance(),
false,
Key.getDefaultInstance(),
false,
Key.getDefaultInstance(),
true,
invalidPauseKey);
assertEquals(INVALID_PAUSE_KEY, validity);
}
}
|
package org.World;
import org.Graphics.Animation;
import org.Graphics.Graphics;
public class GameObject {
//Object pos
public float x = 0,y=0;
//Size
public float width=0.5f,height=0.5f;
//Rotation
public float rotation=0;
//Animations
public Animation[] animations;
public int currentAnimation=0;
public void update(){
//Implement in subclass
}
public void render(){
animations[currentAnimation].play();
Graphics.setRotation(rotation);
Graphics.drawImage(animations[currentAnimation].getImage(),x,y,width,height);
Graphics.setRotation(0);
}
}
|
package com.example.HotelManagment.entity;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
public class UserDto {
private Long userId;
@NotEmpty(message="First name is required")
private String firstname;
@NotEmpty(message="Last name is required")
private String lastname;
@NotEmpty(message="Mobile number is required")
//@Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$",
// message="Mobile number is invalid")
@Pattern(regexp="(^$|[0-9]{10})")
private String mobilenumber;
@NotEmpty(message = "Required to enter user Address ")
private String address;
public Long getUserId() {
return userId;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public String getMobilenumber() {
return mobilenumber;
}
public String getAddress() {
return address;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public void setMobilenumber(String mobilenumber) {
this.mobilenumber = mobilenumber;
}
public void setAddress(String address) {
this.address = address;
}
}
|
package plp.orientadaObjetos1.declaracao.procedimento;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
import plp.imperative1.util.Lista;
import plp.orientadaObjetos1.excecao.declaracao.ClasseNaoDeclaradaException;
import plp.orientadaObjetos1.memoria.AmbienteCompilacaoOO1;
import plp.orientadaObjetos1.memoria.AmbienteExecucaoOO1;
/**
* Um conjunto de declarações de parâmetro.
*/
public class ListaDeclaracaoParametro extends Lista<DecParametro>{
/**
* Construtor.
*/
public ListaDeclaracaoParametro(){
}
/**
* Construtor
* @param declaracao A declaração contida por esta tail.
*/
public ListaDeclaracaoParametro(DecParametro declaracao){
super(declaracao, null);
}
/**
* Construtor.
* @param declaracao A declaração contida por esta tail.
* @param listaDeclaracao A tail de declarações que segue declaração.
*/
public ListaDeclaracaoParametro(DecParametro declaracao, ListaDeclaracaoParametro listaDeclaracao){
super(declaracao,listaDeclaracao);
}
/**
* Cria um mapeamento do identificador para esta tail de declarações
* de parâmetro.
* @param ambiente o ambiente que contem o mapeamento entre identificadores
* e valores.
* @return o ambiente modificado pela declaração da classe.
*/
public AmbienteExecucaoOO1 elabora(AmbienteExecucaoOO1 ambiente) {
AmbienteExecucaoOO1 resposta;
if(getHead() != null) {
if(getTail() != null) {
resposta = ((ListaDeclaracaoParametro)getTail()).elabora(getHead().elabora(ambiente));
}
else {
resposta = getHead().elabora(ambiente);
}
}
else {
resposta = ambiente;
}
return resposta;
}
/**
* Verifica se a declaração e a tail de declaração estão bem tipadas, ou seja, se a
* expressão de inicialização está bem tipada.
* @param ambiente o ambiente que contem o mapeamento entre identificadores
* e seus tipos.
* @return <code>true</code> se os tipos da declaração são válidos;
* <code>false</code> caso contrario.
*/
public boolean checaTipo(AmbienteCompilacaoOO1 ambiente)
throws VariavelNaoDeclaradaException, ClasseNaoDeclaradaException {
boolean resposta;
if(getHead() != null) {
if(getTail() != null) {
resposta = getHead().checaTipo(ambiente) &&
((ListaDeclaracaoParametro)getTail()).checaTipo(ambiente);
}
else {
resposta = getHead().checaTipo(ambiente);
}
}
else {
resposta = true;
}
return resposta;
}
/**
* Cria um mapeamento do identificador para o tipo do parametro
* desta declaração no AmbienteCompilacao
*
* @param ambiente o ambiente que contem o mapeamento entre identificador
* e seu tipo.
* @return o ambiente modificado pela declaração do parametro.
*/
public AmbienteCompilacaoOO1 declaraParametro(AmbienteCompilacaoOO1 ambiente)
throws VariavelNaoDeclaradaException, VariavelJaDeclaradaException {
AmbienteCompilacaoOO1 resposta;
if(getHead() != null) {
if(getTail() != null) {
resposta = ((ListaDeclaracaoParametro)getTail()).declaraParametro(getHead().declaraParametro(ambiente));
}
else {
resposta = getHead().declaraParametro(ambiente);
}
}
else {
resposta = ambiente;
}
return resposta;
}
}
|
package entity;
/**
* Created by vince on 4/25/15.
*/
public interface Model {
public Integer getId();
public void setId(Integer id);
}
|
package cn.izouxiang.vo;
import java.util.Date;
import cn.izouxiang.domain.Wallet;
import lombok.Data;
@Data
public class TransactionRecordVo {
private String id;
private int changeOfAvailable;
private int changeOfBlock;
private Wallet before;
private Wallet alter;
private String message;
private Date createTime;
}
|
import java.util.*;
import java.sql.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
class ServerGui extends JFrame
{
public JTextArea ta;
private JScrollPane sp,spl;
private JPanel p3,p4;
private DefaultListModel dlm;
private JList l;
private String line;
ServerGui()
{
setSize(500,420);
setLocation(200,200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
p3=new JPanel();
p4=new JPanel();
ta=new JTextArea(21,25);
ta.setEditable(false);
sp=new JScrollPane(ta);
dlm=new DefaultListModel();
l=new JList(dlm);
spl=new JScrollPane(l);
spl.setPreferredSize(new Dimension(180,340));
p3.add(sp);
p4.add(spl);
setLayout(new BorderLayout());
add(p4,"East");
add(p3);
setResizable(false);
setVisible(true);
//Constant.o=new Object[2][];
//Constant.o[0]=new Object[10];
//Constant.o[1]=new Object[10];
Constant.index=new Vector();
Constant.socketObj=new Vector();
try
{
ServerChat sc=new ServerChat(ta,dlm,l);
sc.start();
}
catch(IOException e)
{
System.out.println("J");
}
try
{
Db.stmt.execute("update status set st='true'");
}
catch(SQLException e)
{
System.out.println("z");
}
}
public static void main(String args[])
{
new ServerGui();
}
}
|
package mensaje;
import game.Jugador;
public class MsjPartidaPierdeTurno extends Mensaje {
private static final long serialVersionUID = 1L;
private Jugador jugadorAct;
public MsjPartidaPierdeTurno(Jugador jugAct) {
super();
setJugadorAct(jugAct);
this.clase = this.getClass().getSimpleName();
}
@Override
public void ejecutar() {
}
public Jugador getJugadorAct() {
return jugadorAct;
}
public void setJugadorAct(Jugador jugadorAct) {
this.jugadorAct = jugadorAct;
}
}
|
package br.com.smarthouse.controleclimatico.model;
public enum TipoTemperatura {
QUENTE(1), FRIO(2), AGRADAVEL(3);
private TipoTemperatura(final int temperatura) {
this.temperatura = temperatura;
}
private int temperatura;
public int getTemperatura() {
return temperatura;
}
public void setTemperatura(int temperatura) {
this.temperatura = temperatura;
}
}
|
/*
* Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory
* CODE-743439.
* All rights reserved.
* This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool.
*
* Licensed under the Apache License, Version 2.0 (the “Licensee”); you may not use this file except in compliance with the License. You may obtain a copy of the License at:
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and limitations under the license.
*
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
*/
package llnl.gnem.core.gui.plotting.plotobject;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.text.NumberFormat;
import llnl.gnem.core.gui.plotting.JBasicPlot;
import llnl.gnem.core.gui.plotting.transforms.Coordinate;
import llnl.gnem.core.gui.plotting.transforms.CoordinateTransform;
/**
* Created by dodge1 Date: Feb 7, 2008
*/
public class PositionMarker extends PlotObject {
private double xCenter;
private double yCenter;
private double innerSize;
private double outerSize;
private Color color;
public PositionMarker() {
xCenter = 0.5;
yCenter = 0.5;
innerSize = 5.0;
outerSize = 24.0;
setColor(Color.red);
}
/**
* Constructor for the Symbol object
*
* @param X
* The X-center of the symbol in real-world coordinates
* @param Y
* The Y-center of the symbol in real-world coordinates
* @param size
* The innerSize of the Symbol in mm
*/
public PositionMarker(double X, double Y, double size, double outerSize) {
xCenter = X;
yCenter = Y;
this.innerSize = size;
this.outerSize = outerSize;
setColor(Color.red);
}
public PositionMarker(double X, double Y, double innerSize, double outerSize, Color color) {
xCenter = X;
yCenter = Y;
this.innerSize = innerSize;
this.outerSize = outerSize;
setColor(color);
}
@Override
public void setSelected(boolean selected, Graphics g) {
}
/**
* render this Symbol to the supplied graphics context
*
* @param g
* The graphics context
* @param owner
* The JBasicPlot that owns this symbol
*/
@Override
public void render(Graphics g, JBasicPlot owner) {
if (g == null || !visible || owner == null || !owner.getCanDisplay()) {
return;
}
Graphics2D g2d = (Graphics2D) g;
CoordinateTransform ct = owner.getCoordinateTransform();
Coordinate coord = new Coordinate(0.0, 0.0, xCenter, yCenter);
ct.WorldToPlot(coord);
int xcenter = (int) coord.getX();
int ycenter = (int) coord.getY();
int inner = (int) (owner.getUnitsMgr().getPixelsPerUnit() * innerSize);
int outer = (int) (owner.getUnitsMgr().getPixelsPerUnit() * outerSize);
g2d.clip(owner.getPlotRegion().getRect());
paintIt(g, xcenter, ycenter, inner, outer);
}
public void paintIt(Graphics g, int x, int y, int inner, int outer) {
int width = 3;
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(color);
g2d.setStroke(new BasicStroke(width));
g2d.drawLine(x, y - inner, x, y - outer);
g2d.drawLine(x + inner, y, x + outer, y);
g2d.drawLine(x, y + inner, x, y + outer);
g2d.drawLine(x - inner, y, x - outer, y);
}
/**
* Gets the xcenter attribute of the Symbol object
*
* @return The xcenter value
*/
public double getXcenter() {
return xCenter;
}
/**
* Gets the ycenter attribute of the Symbol object
*
* @return The ycenter value
*/
public double getYcenter() {
return yCenter;
}
/**
* Gets the symbolSize attribute of the Symbol object
*
* @return The symbolSize value
*/
public double getSymbolSize() {
return innerSize;
}
/**
* Gets the color attribute of the Symbol object
*
* @return The color value
*/
public Color getColor() {
return color;
}
/**
* Sets the xcenter attribute of the Symbol object
*
* @param v
* The new xcenter value
*/
public void setXcenter(double v) {
xCenter = v;
}
/**
* Sets the ycenter attribute of the Symbol object
*
* @param v
* The new ycenter value
*/
public void setYcenter(double v) {
yCenter = v;
}
/**
* Sets the symbolSize attribute of the Symbol object
*
* @param v
* The new symbolSize value
*/
public void setSymbolSize(double v) {
innerSize = v;
}
/**
* Sets the color attribute of the Symbol object
*
* @param v
* The new color value
*/
public void setColor(Color v) {
color = v;
}
/**
* Move this Symbol to a different place in the subplot
*
* @param owner
* The JBasicPlot that owns this symbol
* @param graphics
* @param dx
* The amount to move in the X-direction in real-world
* coordinates
* @param dy
* The amount to move in the Y-direction in real-world
* coordinates
*/
@Override
public void ChangePosition(JBasicPlot owner, Graphics graphics, double dx, double dy) {
if (graphics == null) {
graphics = owner.getOwner().getGraphics();
}
Graphics2D g2d = (Graphics2D) graphics;
g2d.clip(owner.getPlotRegion().getRect());
render(graphics, owner);
if (canDragX) {
xCenter += dx;
}
if (canDragY) {
yCenter += dy;
}
render(graphics, owner);
}
/**
* Gets a String description of this Symbol object
*
* @return The String description
*/
@Override
public String toString() {
StringBuffer s = new StringBuffer(" Symbol at (");
NumberFormat f = NumberFormat.getInstance();
f.setMaximumFractionDigits(5);
s.append(f.format(xCenter));
s.append(", ");
s.append(f.format(yCenter));
s.append(')');
return s.toString();
}
public double getOuterSize() {
return outerSize;
}
public void setOuterSize(double outerSize) {
this.outerSize = outerSize;
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.unpack200.bytecode;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.harmony.pack200.Pack200Exception;
/**
* Local variable table
*/
public class LocalVariableTableAttribute extends BCIRenumberedAttribute {
private final int local_variable_table_length;
private final int[] start_pcs;
private final int[] lengths;
private int[] name_indexes;
private int[] descriptor_indexes;
private final int[] indexes;
private final CPUTF8[] names;
private final CPUTF8[] descriptors;
private int codeLength;
private static CPUTF8 attributeName;
public static void setAttributeName(CPUTF8 cpUTF8Value) {
attributeName = cpUTF8Value;
}
public LocalVariableTableAttribute(int local_variable_table_length,
int[] start_pcs, int[] lengths, CPUTF8[] names,
CPUTF8[] descriptors, int[] indexes) {
super(attributeName);
this.local_variable_table_length = local_variable_table_length;
this.start_pcs = start_pcs;
this.lengths = lengths;
this.names = names;
this.descriptors = descriptors;
this.indexes = indexes;
}
public void setCodeLength(int length) {
codeLength = length;
}
protected int getLength() {
return 2 + (10 * local_variable_table_length);
}
protected void writeBody(DataOutputStream dos) throws IOException {
dos.writeShort(local_variable_table_length);
for (int i = 0; i < local_variable_table_length; i++) {
dos.writeShort(start_pcs[i]);
dos.writeShort(lengths[i]);
dos.writeShort(name_indexes[i]);
dos.writeShort(descriptor_indexes[i]);
dos.writeShort(indexes[i]);
}
}
protected ClassFileEntry[] getNestedClassFileEntries() {
ArrayList nestedEntries = new ArrayList();
nestedEntries.add(getAttributeName());
for (int i = 0; i < local_variable_table_length; i++) {
nestedEntries.add(names[i]);
nestedEntries.add(descriptors[i]);
}
ClassFileEntry[] nestedEntryArray = new ClassFileEntry[nestedEntries
.size()];
nestedEntries.toArray(nestedEntryArray);
return nestedEntryArray;
}
protected void resolve(ClassConstantPool pool) {
super.resolve(pool);
name_indexes = new int[local_variable_table_length];
descriptor_indexes = new int[local_variable_table_length];
for (int i = 0; i < local_variable_table_length; i++) {
names[i].resolve(pool);
descriptors[i].resolve(pool);
name_indexes[i] = pool.indexOf(names[i]);
descriptor_indexes[i] = pool.indexOf(descriptors[i]);
}
}
public String toString() {
return "LocalVariableTable: " + +local_variable_table_length
+ " variables";
}
protected int[] getStartPCs() {
return start_pcs;
}
/*
* (non-Javadoc)
*
* @see org.apache.harmony.unpack200.bytecode.BCIRenumberedAttribute#renumber(java.util.List)
*/
@Override
public void renumber(List byteCodeOffsets) throws Pack200Exception {
// Remember the unrenumbered start_pcs, since that's used later
// to calculate end position.
int[] unrenumbered_start_pcs = new int[start_pcs.length];
System.arraycopy(start_pcs, 0, unrenumbered_start_pcs, 0,
start_pcs.length);
// Next renumber start_pcs in place
super.renumber(byteCodeOffsets);
// lengths are BRANCH5 encoded, not BCI-encoded.
// In other words:
// start_pc is BCI5 start_pc
// end_pc is byteCodeOffset[(index of start_pc in byteCodeOffset) +
// (encoded length)]
// real length = end_pc - start_pc
// special case if end_pc is beyond end of bytecode array
int maxSize = codeLength;
// Iterate through the lengths and update each in turn.
// This is done in place in the lengths array.
for (int index = 0; index < lengths.length; index++) {
int start_pc = start_pcs[index];
int revisedLength = -1;
int encodedLength = lengths[index];
// First get the index of the start_pc in the byteCodeOffsets
int indexOfStartPC = unrenumbered_start_pcs[index];
// Given the index of the start_pc, we can now add
// the encodedLength to it to get the stop index.
int stopIndex = indexOfStartPC + encodedLength;
if (stopIndex < 0) {
throw new Pack200Exception("Error renumbering bytecode indexes");
}
// Length can either be an index into the byte code offsets, or one
// beyond the
// end of the byte code offsets. Need to determine which this is.
if (stopIndex == byteCodeOffsets.size()) {
// Pointing to one past the end of the byte code array
revisedLength = maxSize - start_pc;
} else {
// We're indexed into the byte code array
int stopValue = ((Integer) byteCodeOffsets.get(stopIndex))
.intValue();
revisedLength = stopValue - start_pc;
}
lengths[index] = revisedLength;
}
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.qq.packets.in;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.Util;
import edu.tsinghua.lumaqq.qq.beans.QQUser;
import edu.tsinghua.lumaqq.qq.packets.BasicInPacket;
import edu.tsinghua.lumaqq.qq.packets.PacketParseException;
/**
* <pre>
* 下载分组名称的回复包,格式为
* 1. 头部
* 2. 子命令,1字节,下载是0x1
* 3. 回复码,1字节
* 5. 未知的4字节
* 6. 组序号,从1开始,0表示我的好友组,因为是缺省组,所以不包含在包中
* 7. 16字节的组信息,开始是组名,以0结尾,如果长度不足16字节,则其余部分可能为0,也可能
* 为其他字节,含义不明
* 8. 若有多个组,重复6,7部分
* 9. 尾部
*
* 上传分组名称的回复包,格式为
* 1. 头部
* 2. 子命令,1字节
* 3. 回复码,1字节
* 4. 组需要,从1开始,0表示我的好友组,因为是缺省组,所以不包含在包中
* 5. 如果有更多组,重复4部分
* 6. 尾部
* </pre>
*
* @author luma
*/
public class GroupDataOpReplyPacket extends BasicInPacket {
public List<String> groupNames;
public byte subCommand;
public byte replyCode;
/**
* 构造函数
* @param buf 缓冲区
* @param length 包长度
* @throws PacketParseException 解析错误
*/
public GroupDataOpReplyPacket(ByteBuffer buf, int length, QQUser user) throws PacketParseException {
super(buf, length, user);
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.qq.packets.OutPacket#getPacketName()
*/
@Override
public String getPacketName() {
switch(subCommand) {
case QQ.QQ_SUB_CMD_UPLOAD_GROUP_NAME:
return "Group Data Reply Packet - Upload Group";
case QQ.QQ_SUB_CMD_DOWNLOAD_GROUP_NAME:
return "Group Data Reply Packet - Download Group";
default:
return "Group Data Reply Packet - Unknown Sub Command";
}
}
/* (non-Javadoc)
* @see edu.tsinghua.lumaqq.qq.packets.InPacket#parseBody(java.nio.ByteBuffer)
*/
@Override
protected void parseBody(ByteBuffer buf) throws PacketParseException {
// 得到操作类型
subCommand = buf.get();
// 回复码
replyCode = buf.get();
if(replyCode == QQ.QQ_REPLY_OK) {
// 如果是下载包,继续解析内容
if(subCommand == QQ.QQ_SUB_CMD_DOWNLOAD_GROUP_NAME) {
// 创建list
groupNames = new ArrayList<String>();
// 未知4个字节
buf.getInt();
// 读取每个组名
while(buf.hasRemaining()) {
buf.get();
groupNames.add(Util.getString(buf, (byte)0x00, 16));
}
}
}
}
}
|
package CollectionsDemo;
import java.util.ArrayList;
/**
* Class 'ArrayList' extends class 'AbstractList' and implements interface
* 'List', is used for dynamic massive.
*
* A method 'toArray()' is used to convert 'ArrayList' to massive.
*
* @author Bohdan Skrypnyk
*/
public class ArrayListToArray {
public static void main(String arhs[]) {
// initialization of the 'ArrayList' with the type 'Integer'
ArrayList<Integer> arr = new ArrayList();
// add values to 'ArrayList'
arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);
arr.add(5);
// initialization of the massive with the type 'Integer'
Integer num[] = new Integer[arr.size()];
// create massive from ArrayList
num = arr.toArray(num);
int sum = 0;
// count sum of the massive
for (Integer n : num) {
sum += n;
}
System.out.println("Sum " + sum);
}
}
|
package com.bluejnr.wiretransfer.pattern.state;
import com.bluejnr.wiretransfer.model.domain.WireTransferVO;
public abstract class WireTransferState {
protected WireTransferVO wireTransferVO;
public WireTransferState(WireTransferVO wireTransferVO) {
this.wireTransferVO = wireTransferVO;
}
public abstract void process();
}
|
package com.app.cprogramingapp.Utils;
import android.content.Context;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Utils {
public static final String BASE_URL="https://raw.githubusercontent.com/madhukar3646/myplaystoreappslisting/master/";
public static String getStringFromFile(Context context,int id)
{
InputStream inputStream = context.getResources().openRawResource(id);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
public static String getStringFromAssestsFile(Context context,String filename)
{
InputStream inputStream = null;
try {
inputStream = context.getAssets().open(filename);
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try {
i = inputStream.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
}
|
/**
*
*/
package com.eigen.constant;
public enum DataProvider {
YAHOO (1),
EIKON_DESKTOP (2);
private final int id;
private DataProvider(int nId) {
id = nId;
}
public int getId() {
return id;
}
public static DataProvider fromId(int nId) {
DataProvider dp = null;
for (DataProvider p : DataProvider.values()) {
if (p.getId() == nId) {
dp = p;
break;
}
}
return dp;
}
}
|
package com.withertech.overtokapi.resource;
import com.withertech.overtokapi.model.OvertokModel;
import com.withertech.overtokapi.object.follower;
import org.python.util.PythonInterpreter;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/followers")
public class OvertokResource
{
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response followers()
{
OvertokModel response = new OvertokModel(0, new follower[]{
new follower(false, "6850475539113100289", "FR", "https://p16.tiktokcdn.com/aweme/1080x1080/tiktok-obj/14f897f6c703844dac6d5cf1b1bcb247.webp", "https://p16.tiktokcdn.com/aweme/720x720/tiktok-obj/14f897f6c703844dac6d5cf1b1bcb247.webp", "chendang9773", "MS4wLjABAAAA4ttO4emGy7HVr1FZj3Eu1S-4UyLIz_CvVq1dnqmQjE5xi3fwf5ojG40zM2LXvO3k", "user4658493671468", false)
});
/* try(PythonInterpreter pyInterp = new PythonInterpreter()) {
pyInterp.exec("print('Hello Python World!')");
}*/
return Response.ok(response).build();
}
}
|
package accessories.strings;
import accessories.Accessory;
public class Pickup extends Accessory {
public Pickup(String partName, String brand, String partFor, String type, double buyingPrice, double sellingPrice) {
super(partName, brand, partFor, type, buyingPrice, sellingPrice);
}
}
|
package com.simple.social.app;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import com.simple.social.config.ActiveMqConfig;
import com.simple.social.config.ApplicationConfig;
import com.simple.social.config.ApplicationInitializerConfig;
import com.simple.social.config.JpaConfig;
import com.simple.social.config.MvcConfig;
import com.simple.social.config.SwaggerConfig;
import com.simple.social.security.SecurityConfig;
@SpringBootApplication
@Import({ApplicationConfig.class, JpaConfig.class, MvcConfig.class, ActiveMqConfig.class, SecurityConfig.class, SwaggerConfig.class, ApplicationInitializerConfig.class})
public class SimpleApp { // extends SpringBootServletInitializer {
private static Logger log = LoggerFactory.getLogger(SimpleApp.class);
// //for traditional .war deployment need to extend SpringBootServletInitializer
// @Override
// protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// return application.sources(SimpleApp.class);
// }
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(SimpleApp.class);
springApplication.setBannerMode(Banner.Mode.OFF);
ApplicationContext context = springApplication.run(args);
log.warn("Context : " + context.getId());
}
}
|
import java.util.Scanner;
public class caseexample {
public static void main(String[] args) {
// Scanner input = new Scanner(System.in);
// System.out.println("Enter text: ");
// String x = input.nextLine();
//
// switch (x) {
// case "start":
// System.out.println("Machine Started");
// break;
// case "stop":
// System.out.println("Machine Started");
// break;
// default:
// System.out.println("Not Recognized");
// break;
// }
int k=2;
if(k++ == 3)
{
System.out.println("y 2");
}
if(++k == 3)
{
System.out.println("y 1");
}
System.out.println(k);
}
}
|
package com.legalzoom.api.test.client.service.factory;
/**
*
hmaheshwari
Aug 16, 2015
10:17:18 PM
*/
import com.legalzoom.api.test.client.LZClient;
import com.legalzoom.api.test.client.service.AbstractBaseServiceClient.Service;
import com.legalzoom.api.test.client.service.CoreOrdersServiceClient;
import com.legalzoom.api.test.client.service.CoreProductsServiceClient;
import org.springframework.beans.factory.annotation.Value;
import java.net.URI;
public class CoreProductsServiceClientFactory extends AbstractServiceClientFactory{
@Value("${core.products.service.name}")
private String coreProductsServiceName;
@Value("${products.availableProductTypes.path}")
private String productsAvailableProductTypesPath;
@Override
public synchronized CoreProductsServiceClient createServiceClient() {
CoreProductsServiceClient coreProductsServiceClient = createCoreProductsServiceClient();
coreProductsServiceClient.setLzClient(createLZClient(Service.CoreProductsService));
coreProductsServiceClient.setLzCoreProductsServiceURL(getLzCoreProductsServiceURL());
coreProductsServiceClient.setProductsServiceName(coreProductsServiceName);
coreProductsServiceClient.setProductsAvailableProductTypes(productsAvailableProductTypesPath);
return coreProductsServiceClient;
}
}
|
package com.mcr.mcr_galeri;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class Showroom extends AppCompatActivity {
ListView listview;
List<Araba> arabalar=new ArrayList<>();
List<Araba> bulunan_arabalar=new ArrayList<>();
String _marka = "", _model = "", _fiyat_min = "",_fiyat_max="";
VeriTabani kayitlar;
private String[] sutunlar = {"tarih","marka", "model","yil","fiyat","aciklama","resim_yolu","ad_soyad","numara"};
private void TumKayitlar() {
SQLiteDatabase db = kayitlar.getReadableDatabase();
Cursor cursorKayit = db.query("Kayitlar", sutunlar, null, null, null, null, null);
while (cursorKayit.moveToNext()) {
Araba bulunan = new Araba();
bulunan.tarih = cursorKayit.getString(cursorKayit.getColumnIndex("tarih"));
bulunan.marka = cursorKayit.getString(cursorKayit.getColumnIndex("marka"));
bulunan.model = cursorKayit.getString(cursorKayit.getColumnIndex("model"));
bulunan.yil = cursorKayit.getString(cursorKayit.getColumnIndex("yil"));
bulunan.fiyat = cursorKayit.getInt(cursorKayit.getColumnIndex("fiyat"));
bulunan.aciklama = cursorKayit.getString(cursorKayit.getColumnIndex("aciklama"));
bulunan.resim = cursorKayit.getString(cursorKayit.getColumnIndex("resim_yolu"));
bulunan.ad_soyad = cursorKayit.getString(cursorKayit.getColumnIndex("ad_soyad"));
bulunan.numara = cursorKayit.getString(cursorKayit.getColumnIndex("numara"));
arabalar.add(bulunan);
}
cursorKayit.close();
}
private void ArabaBul()
{
try {
TumKayitlar();
/*EditText txt = (EditText) findViewById(R.id.textView1);
txt.setText(" ");*/
bulunan_arabalar.clear();
if(_marka.equals("boş")==false && _model.equals("boş")==true && _fiyat_min.equals("boş")==true)
{//marka
for (int i = 0; i < arabalar.size(); i++)
{
if(arabalar.get(i).marka.equals(_marka))
{
bulunan_arabalar.add(arabalar.get(i));
}
}
}
if(_marka.equals("boş")==true && _model.equals("boş")==false && _fiyat_min.equals("boş")==true)
{//model
for (int i = 0; i < arabalar.size(); i++)
{
if(arabalar.get(i).model.equals(_model))
{
bulunan_arabalar.add(arabalar.get(i));
}
}
}
if(_marka.equals("boş")==true && _model.equals("boş")==true && _fiyat_min.equals("boş")==false)
{//fiyat
for (int i = 0; i < arabalar.size(); i++)
{
if(arabalar.get(i).fiyat>=Integer.parseInt(_fiyat_min) && arabalar.get(i).fiyat<=Integer.parseInt(_fiyat_max))
{
bulunan_arabalar.add(arabalar.get(i));
}
}
}
if(_marka.equals("boş")==false && _model.equals("boş")==false && _fiyat_min.equals("boş")==true)
{//marka,model
for (int i = 0; i < arabalar.size(); i++)
{
if(arabalar.get(i).marka.equals(_marka) && arabalar.get(i).model.equals(_model))
{
bulunan_arabalar.add(arabalar.get(i));
}
}
}
if(_marka.equals("boş")==false && _model.equals("boş")==true && _fiyat_min.equals("boş")==false)
{//marka,fiyat
for (int i = 0; i < arabalar.size(); i++)
{
if(arabalar.get(i).marka.equals(_marka) && arabalar.get(i).fiyat>=Integer.parseInt(_fiyat_min) && arabalar.get(i).fiyat<=Integer.parseInt(_fiyat_max))
{
bulunan_arabalar.add(arabalar.get(i));
}
}
}
if(_marka.equals("boş")==true && _model.equals("boş")==false && _fiyat_min.equals("boş")==false)
{//model,fiyat
for (int i = 0; i < arabalar.size(); i++)
{
if(arabalar.get(i).model.equals(_model) && arabalar.get(i).fiyat>=Integer.parseInt(_fiyat_min) && arabalar.get(i).fiyat<=Integer.parseInt(_fiyat_max))
{
bulunan_arabalar.add(arabalar.get(i));
}
}
}
} catch (Exception h) {
Toast.makeText(Showroom.this, h.getMessage(), Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showroom);
setTitle("BULUNAN ARABALAR");
kayitlar=new VeriTabani(this);
if(getIntent().getStringExtra("tum_kayitlar").toString().equals("false"))
{
if (getIntent().getStringExtra("marka").toString() != "boş") {
_marka = getIntent().getStringExtra("marka").toString();
}
if (getIntent().getStringExtra("model").toString() != "boş") {
_model = getIntent().getStringExtra("model").toString();
}
if (getIntent().getStringExtra("fiyat_min").toString() != "boş") {
_fiyat_min = getIntent().getStringExtra("fiyat_min").toString();
_fiyat_max = getIntent().getStringExtra("fiyat_max").toString();
}
try {
try {
ArabaBul();
//img.setImageResource(R.drawable.arka_plan);
/*Uri uriFromPath = Uri.fromFile(new File(bulunan_arabalar.get(0).resim));
img.setImageURI(uriFromPath);*/
//img.setImageBitmap(BitmapFactory.decodeFile(bulunan_arabalar.get(0).resim));
listview = (ListView) findViewById(R.id.listView_kayitlar);
listview.setAdapter(new CustomAdapter(Showroom.this, bulunan_arabalar));
}catch(Exception h)
{
Toast.makeText(Showroom.this, h.getMessage(), Toast.LENGTH_SHORT).show();
}
}catch (Exception hata)
{
Toast.makeText(Showroom.this, hata.getMessage(), Toast.LENGTH_SHORT).show();
}
}
else
{
try
{
TumKayitlar();
listview = (ListView) findViewById(R.id.listView_kayitlar);
listview.setAdapter(new CustomAdapter(Showroom.this, arabalar));
}
catch (Exception h)
{
Toast.makeText(Showroom.this, h.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(getApplicationContext(), Araba_ara.class);
startActivity(i);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void show_image(String yol,String numara,String aciklama,String sahibi)
{
Intent i=new Intent(getApplicationContext(),Show_image.class);
i.putExtra("yol",yol);
i.putExtra("numara",numara);
i.putExtra("aciklama",aciklama);
i.putExtra("sahibi",sahibi);
startActivity(i);
}
class CustomAdapter extends BaseAdapter {
List<Araba> arabalar_result;
Context context;
private LayoutInflater inflater=null;
public CustomAdapter(Showroom mainActivity,List<Araba> arabalar){
this.arabalar_result=arabalar;
context=mainActivity;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return arabalar_result.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView txt_bilgiler;
ImageView resim;
}
Holder holder=new Holder();
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = inflater.inflate(R.layout.costum_image_list, null);
try
{
holder.txt_bilgiler=(TextView) rowView.findViewById(R.id.txt_bilgiler);
holder.txt_bilgiler.setText(arabalar_result.get(position).marka + " " + arabalar_result.get(position).model + "\n" + arabalar_result.get(position).fiyat + "TL" + " YIL:" + arabalar_result.get(position).yil);
holder.resim=(ImageView) rowView.findViewById(R.id.resim);
//holder.resim.setImageBitmap(BitmapFactory.decodeFile(arabalar_result.get(position).resim));
holder.resim.setImageResource(R.drawable.car_icon);
//Toast.makeText(context, "hata yok", Toast.LENGTH_SHORT).show();
}
catch (Exception hata)
{
//Toast.makeText(context, hata.getMessage(), Toast.LENGTH_SHORT).show();
AlertDialog.Builder alertBuilder=new AlertDialog.Builder(context);
alertBuilder.setMessage(hata.getMessage());
AlertDialog alertDialog = alertBuilder.create();
alertDialog.show();
}
rowView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
show_image(arabalar_result.get(position).resim,arabalar_result.get(position).numara,arabalar_result.get(position).aciklama,arabalar_result.get(position).ad_soyad);
//Toast.makeText(context, arabalar_result.get(position).aciklama, Toast.LENGTH_SHORT).show();
//Toast.makeText(context, arabalar_result.get(position).marka + " " + arabalar_result.get(position).model+"\n"+arabalar_result.get(position).fiyat+"TL"+" YIL:"+arabalar_result.get(position).yil+"\n"+arabalar_result.get(position).resim, Toast.LENGTH_LONG).show();
//Toast.makeText(context, arabalar_result.get(position).resim, Toast.LENGTH_SHORT).show();
}
});
return rowView;
}
}
}
|
package com.yixin.kepler.dto.webank;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.List;
/**
* 微众一审请求入参
* Package : com.yixin.kepler.dto.webank
*
* @author YixinCapital -- wangwenlong
* 2018年7月9日 上午11:43:33
*
*/
public class WBFirstRequestDTO extends WBCommonReqDTO {
private static final long serialVersionUID = 8694439798348172851L;
/**
* 姓名/申请人姓名
*/
@JsonProperty("NAME")
private String akhxm;
/**
* 证件提交类型/证件类型
*/
@JsonProperty("ID_TYPE")
private String azjlx;
/**
* 证件号码/身份证号码
*/
@JsonProperty("ID_NO")
private String azjhm;
/**
* 注册手机号/注册手机号
*/
@JsonProperty("REG_MOBILE")
private String asjhm;
/**
* 应用提交类型
* O: qq open ID
* W: 微信ID
* M: 手机号
* C : 卡号
* A:应用账号
* 无符合选项时默认填 A
*/
@JsonProperty("APP_TYPE")
private String appType = "A";
/**
* 用户平台id 填合作方平台系统中的客户唯一编号,如无则填写身份证号码/身份证号码
*/
@JsonProperty("REG_USERID")
private String azjhm2;
/**
* 月均收入水平 /税后年薪(万元)/12,映射范围内
* 二审传数值
*/
@JsonProperty("MONTHLY_INCOME_RANGE")
private String fshnx;
/**
* 纳税居民申明
* 1.仅为中国税收居民
* 2.仅为非居民
* 3.即是中国税收居民又是其他国家(地区)税收居民\
* 默认1,2和3微众会拒绝
*/
@JsonProperty("TAXABLE_RESIDENTS")
private String taxableResidents = "1";
/**
* 代理人用户id / 提报账号
*/
@JsonProperty("AGENT_ID")
private String salesDomainAccount;
/**
* 代理人姓名 / 分公司金融经理
*/
@JsonProperty("AGENT_NAME")
private String financialManagerName;
/**
* 代理人手机号 / 销售预留手机
*/
@JsonProperty("AGENT_PHONE")
private String salesPhone;
/**
* SP代理人公司所在省 / 经销商渠道所在省名称
*/
@JsonProperty("AGENT_COMPANY_PROV")
private String dealerChannelProvinceName;
/**
* SP代理人公司所在市 / 经销商渠道所在市名称
*/
@JsonProperty("AGENT_COMPANY_CITY")
private String dealerChannelCityName;
/**
* SP代理人公司详细地址 / 经销商渠道详细地址
*/
@JsonProperty("AGENT_COMPANY_ADDR")
private String dealerChannelDetailedAddress;
/**
* SP公司ID / 经销商渠道id
*/
@JsonProperty("AGENT_COMPANY_ID")
private String dealerChannelId;
/**
* SP代理人企业名称 / 所属机构
*/
@JsonProperty("AGENT_COMPANY_NAME")
private String affiliatedInstitutions;
/**
* 他行银行卡
*/
@JsonProperty("BANK_CARD_ACCT")
private List<WBBankCardDTO> bankCardAcct;
/**
* 合同协议
*/
@JsonProperty("CONTRACT_BASE")
private List<WBContractDTO> contractBase;
/***++++++++客户行为存证域++++++++++***/
/**
*点击“获取验证码”时间
*/
@JsonProperty("CLICK_SMS_TIME")
@JsonFormat(pattern = "yyyyMMddHHmmss",timezone="GMT+8")
private Date clickSmsTime;
/**
*系统发送验证码时间
*/
@JsonProperty("SYS_SEND_SMS_TIME")
@JsonFormat(pattern = "yyyyMMddHHmmss",timezone="GMT+8")
private Date sysSendSmsTime;
/**
*接收验证码手机号码
*/
@JsonProperty("CHECK_SMS_MOBILE")
private String checkSmsMobile;
/**
*验密通过时间
*/
@JsonProperty("CHECK_PWD_SUC_TIME")
@JsonFormat(pattern = "yyyyMMddHHmmss",timezone="GMT+8")
private Date checkPwdSucTime;
/**
* 验短通过时间
*/
@JsonProperty("CHECK_SMS_SUC_TIME")
@JsonFormat(pattern = "yyyyMMddHHmmss",timezone="GMT+8")
private Date checkSmsSucTime;
/**
*提交申请时间
*/
@JsonProperty("APPLY_TIME")
@JsonFormat(pattern = "yyyyMMddHHmmss",timezone="GMT+8")
private Date applyTime;
/**
*点击"纳税居民申明"时间
*/
@JsonProperty("CLICK_TAXABLE_TIME")
@JsonFormat(pattern = "yyyyMMddHHmmss",timezone="GMT+8")
private Date clickTaxableTime;
/**
*OTP验证发送次数
*/
@JsonProperty("OTP_SEND_TIME")
private String otpSendTime;
/**
*OTP验证失败次数
*/
@JsonProperty("OTP_ERR_TIME")
private String optErrTime;
/**++++++++++++++++++++用户系统环境域+++++++++++++++++**/
/**
*操作系统
*/
@JsonProperty("OS_TYPE")
private String osType;
/**
*手机品牌
*/
@JsonProperty("MOBILE_BRANDS")
private String mobileBrands;
/**
*ios设备必须填写 idfa
*/
@JsonProperty("IOS_IDFA")
private String iosIdFa;
/**
*andriod设备必须填写
*/
@JsonProperty("ANDROID_IMEI")
private String androidImei;
/**
*IP
*/
@JsonProperty("IP")
private String ip;
/**
*mac地址
*/
@JsonProperty("MAC_ADDR")
private String macAddr;
/**
* 平台流水
*/
@JsonProperty("MER_BIZ_NO")
private String merBizNo;
public String getMerBizNo() {
return merBizNo;
}
public void setMerBizNo(String merBizNo) {
this.merBizNo = merBizNo;
}
public String getAkhxm() {
return akhxm;
}
public void setAkhxm(String akhxm) {
this.akhxm = akhxm;
}
public String getAzjlx() {
return azjlx;
}
public void setAzjlx(String azjlx) {
this.azjlx = azjlx;
}
public String getAzjhm() {
return azjhm;
}
public void setAzjhm(String azjhm) {
this.azjhm = azjhm;
}
public String getAsjhm() {
return asjhm;
}
public void setAsjhm(String asjhm) {
this.asjhm = asjhm;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public String getAzjhm2() {
return azjhm2;
}
public void setAzjhm2(String azjhm2) {
this.azjhm2 = azjhm2;
}
public String getFshnx() {
return fshnx;
}
public void setFshnx(String fshnx) {
this.fshnx = fshnx;
}
public String getTaxableResidents() {
return taxableResidents;
}
public void setTaxableResidents(String taxableResidents) {
this.taxableResidents = taxableResidents;
}
public String getSalesDomainAccount() {
return salesDomainAccount;
}
public void setSalesDomainAccount(String salesDomainAccount) {
this.salesDomainAccount = salesDomainAccount;
}
public String getFinancialManagerName() {
return financialManagerName;
}
public void setFinancialManagerName(String financialManagerName) {
this.financialManagerName = financialManagerName;
}
public String getSalesPhone() {
return salesPhone;
}
public void setSalesPhone(String salesPhone) {
this.salesPhone = salesPhone;
}
public String getDealerChannelProvinceName() {
return dealerChannelProvinceName;
}
public void setDealerChannelProvinceName(String dealerChannelProvinceName) {
this.dealerChannelProvinceName = dealerChannelProvinceName;
}
public String getDealerChannelCityName() {
return dealerChannelCityName;
}
public void setDealerChannelCityName(String dealerChannelCityName) {
this.dealerChannelCityName = dealerChannelCityName;
}
public String getDealerChannelDetailedAddress() {
return dealerChannelDetailedAddress;
}
public void setDealerChannelDetailedAddress(String dealerChannelDetailedAddress) {
this.dealerChannelDetailedAddress = dealerChannelDetailedAddress;
}
public String getDealerChannelId() {
return dealerChannelId;
}
public void setDealerChannelId(String dealerChannelId) {
this.dealerChannelId = dealerChannelId;
}
public String getAffiliatedInstitutions() {
return affiliatedInstitutions;
}
public void setAffiliatedInstitutions(String affiliatedInstitutions) {
this.affiliatedInstitutions = affiliatedInstitutions;
}
public List<WBBankCardDTO> getBankCardAcct() {
return bankCardAcct;
}
public void setBankCardAcct(List<WBBankCardDTO> bankCardAcct) {
this.bankCardAcct = bankCardAcct;
}
public List<WBContractDTO> getContractBase() {
return contractBase;
}
public void setContractBase(List<WBContractDTO> contractBase) {
this.contractBase = contractBase;
}
public Date getClickSmsTime() {
return clickSmsTime;
}
public void setClickSmsTime(Date clickSmsTime) {
this.clickSmsTime = clickSmsTime;
}
public Date getSysSendSmsTime() {
return sysSendSmsTime;
}
public void setSysSendSmsTime(Date sysSendSmsTime) {
this.sysSendSmsTime = sysSendSmsTime;
}
public String getCheckSmsMobile() {
return checkSmsMobile;
}
public void setCheckSmsMobile(String checkSmsMobile) {
this.checkSmsMobile = checkSmsMobile;
}
public Date getCheckPwdSucTime() {
return checkPwdSucTime;
}
public void setCheckPwdSucTime(Date checkPwdSucTime) {
this.checkPwdSucTime = checkPwdSucTime;
}
public Date getApplyTime() {
return applyTime;
}
public void setApplyTime(Date applyTime) {
this.applyTime = applyTime;
}
public Date getClickTaxableTime() {
return clickTaxableTime;
}
public void setClickTaxableTime(Date clickTaxableTime) {
this.clickTaxableTime = clickTaxableTime;
}
public String getOtpSendTime() {
return otpSendTime;
}
public void setOtpSendTime(String otpSendTime) {
this.otpSendTime = otpSendTime;
}
public String getOptErrTime() {
return optErrTime;
}
public void setOptErrTime(String optErrTime) {
this.optErrTime = optErrTime;
}
public String getOsType() {
return osType;
}
public void setOsType(String osType) {
this.osType = osType;
}
public String getMobileBrands() {
return mobileBrands;
}
public void setMobileBrands(String mobileBrands) {
this.mobileBrands = mobileBrands;
}
public String getIosIdFa() {
return iosIdFa;
}
public void setIosIdFa(String iosIdFa) {
this.iosIdFa = iosIdFa;
}
public String getAndroidImei() {
return androidImei;
}
public void setAndroidImei(String androidImei) {
this.androidImei = androidImei;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getMacAddr() {
return macAddr;
}
public void setMacAddr(String macAddr) {
this.macAddr = macAddr;
}
public Date getCheckSmsSucTime() {
return checkSmsSucTime;
}
public void setCheckSmsSucTime(Date checkSmsSucTime) {
this.checkSmsSucTime = checkSmsSucTime;
}
}
|
package test;
import java.util.Scanner;
public class Pizza {
int choice,Size,Flavour,Quantity,a=500,price;
public void options() {
System.out.println("1.Pizza\n2.French Freis");
System.out.println("Enter Choice");
Scanner S=new Scanner (System.in);
choice=S.nextInt();
switch (choice)
{
case 1:
System.out.println("Select Flavour");
System.out.println("1.Cheese Capsicum\t2.Corns \t3.Farm House");
Flavour=S.nextInt();
switch (Flavour)
{
case 1:
System.out.println("Select Size");
System.out.println("1.Large\t2.Medium\t3.Small");
Size=S.nextInt();
switch(Size)
{
case 1:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
price=a*Quantity;
System.out.println("Quantity is 1");
break;
case 2:
price=a*Quantity;
System.out.println("Price is"+price);
break;
}
break;
case 2:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
price=a*Quantity;
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}
break;
case 3:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
}
break;
case 2:
System.out.println("Select Size");
System.out.println("1.Large\t2.Medium\t3.Small");
Size=S.nextInt();
switch(Size)
{
case 1:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}
break;
case 2:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
case 3:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
}
break;
case 3:
System.out.println("Select Size");
System.out.println("1.Large\t2.Medium\t3.Small");
Size=S.nextInt();
switch(Size)
{
case 1:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}
break;
case 2:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
case 3:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
}}
break;
case 2:
{
System.out.println("Select Flavour");
System.out.println("1.Perry Perry\t2.Salted");
Flavour=S.nextInt();
switch (Flavour)
{
case 1:
System.out.println("Select Size");
System.out.println("1.Large\t2.Medium\t3.Small");
Size=S.nextInt();
switch(Size)
{
case 1:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}
break;
case 2:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}
break;
case 3:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
}
break;
case 2:
System.out.println("Select Size");
System.out.println("1.Large\t2.Medium\t3.Small");
Size=S.nextInt();
switch(Size)
{
case 1:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}
break;
case 2:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
case 3:
System.out.println("Select Quantity");
System.out.println("1.One\t2.Two");
Quantity=S.nextInt();
switch(Quantity)
{
case 1:
System.out.println("Quantity is 1");
break;
case 2:
System.out.println("Quantity is 2");
break;
}break;
}
break;
}
}
}}
public static void main(String[] args) {
Pizza oo=new Pizza();
oo.options();
// TODO Auto-generated method stub
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.trading.chart.drawings;
import java.awt.Graphics2D;
import java.awt.Shape;
import com.qtplaf.library.trading.chart.plotter.PlotterContext;
/**
* Base class of all drawings.
* <p>
* Drawings are responsible to return its shape given a plotter context that enables them to calculate their
* coordinates. The shape can be used by the drawer to check, for instance, intersections.
* <p>
* Additionally, the drawing is responsible to draw itself in a graphics device.
*
* @author Miquel Sas
*/
public abstract class Drawing {
/**
* The name.
*/
private String name;
/**
* Default constructor.
*/
public Drawing() {
}
/**
* Returns the name.
*
* @return The name.
*/
public String getName() {
return name;
}
/**
* Set the name.
*
* @param name The name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Returns this drawing shape.
*
* @param context The plotter context.
* @return The shape.
*/
public abstract Shape getShape(PlotterContext context);
/**
* Draw the candlestick.
*
* @param g2 The graphics object.
* @param context The plotter context.
*/
public abstract void draw(Graphics2D g2, PlotterContext context);
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package client.ui;
import client.GamerClient;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
/**
*
* @author Olga
*/
public class WaitForPlayersView extends javax.swing.JPanel {
private GamerClient clientHandler;
private boolean buttonWithSpinner;
private Timer dummyTimer;
private static final String WAITTEXT = "Waiting for other users";
private static int tick = 0;
/**
* Creates new form WaitForPlayersView
*/
public WaitForPlayersView(GamerClient handler) {
this.clientHandler = handler;
initComponents();
}
public void showWaitForOthersOnButton() {
if(buttonWithSpinner == false) {
buttonWithSpinner = true;
dummyTimer = new Timer();
dummyTimer.schedule(new TimerTask() {
public void run() {
String buttonText = WAITTEXT;
for(int i = 0; i < tick; i++) {
buttonText = buttonText + ".";
}
tick++;
if(tick > 7) {
tick = 0;
}
startGameButton.setText(buttonText);
}
}, 0, 1000);
}
}
public void updateListView(ArrayList<String> namesList) {
this.playersList.setListData(new Vector(namesList));
}
public void changeStartButtonState(boolean buttonEnabled) {
if(!buttonWithSpinner) {
this.startGameButton.setEnabled(buttonEnabled);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
commentLabel = new javax.swing.JLabel();
otherPlayersLabel = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
playersList = new javax.swing.JList();
startGameButton = new javax.swing.JButton();
commentLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
commentLabel.setText("Setting up new game....");
otherPlayersLabel.setText("Other players in this game so far: ");
jScrollPane1.setViewportView(playersList);
startGameButton.setText("Start game");
startGameButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
startGamePressed(evt);
}
});
startGameButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
startGameButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(commentLabel)
.addComponent(otherPlayersLabel))
.addGap(0, 8, Short.MAX_VALUE))
.addComponent(startGameButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(78, 78, 78))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(commentLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(otherPlayersLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(startGameButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addContainerGap(188, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void startGameButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startGameButtonActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_startGameButtonActionPerformed
private void startGamePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_startGamePressed
this.clientHandler.startGame();
}//GEN-LAST:event_startGamePressed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel commentLabel;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel otherPlayersLabel;
private javax.swing.JList playersList;
private javax.swing.JButton startGameButton;
// End of variables declaration//GEN-END:variables
}
|
package com.xindq.yilan.activity.screen;
import com.xindq.yilan.domain.Item;
import com.xindq.yilan.view.config.Config;
import com.xindq.yilan.view.shape.Shape;
import java.util.List;
import java.util.Map;
public interface ScreenCallback {
void onDecode(List<Shape> shapes, List<Config> configs);
void onReceiveDatas(Map<String, String> datas);
void onGetItem(Item item);
}
|
package one.kii.summer.beans.utils;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.*;
/**
* Created by WangYanJiong on 02/04/2017.
*/
@SuppressWarnings("unchecked")
public class SingleValueMapping {
public static <T> T from(Class<T> klass, Map map) {
T instance = null;
try {
instance = klass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
// ignore
}
Field[] fields = klass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value = map.get(field.getName());
if (value != null) {
if (field.getType().equals(value.getClass())) {
try {
field.set(instance, value);
} catch (IllegalAccessException e) {
}
} else {
if (field.getType().equals(String.class)) {
try {
field.set(instance, String.valueOf(value));
} catch (IllegalAccessException e) {
}
} else {
Object anotherValue = from(field.getType(), value);
if (anotherValue == null) {
continue;
}
try {
field.set(instance, anotherValue);
} catch (IllegalAccessException e) {
}
}
}
}
}
return instance;
}
public static <T> T from(Class<T> klass, Object src) {
if (src == null) {
return null;
}
if (isScala(klass)) {
T x = primitive(klass, src);
if (x != null) return x;
}
if (src instanceof Map) {
return from(klass, (Map) src);
}
T instance;
try {
instance = klass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
return null;
}
for (Field targetField : klass.getDeclaredFields()) {
Object targetValue = getValue(targetField, instance);
if (targetValue != null) {
continue;
}
Object srcValue = getValue(targetField.getName(), src);
if (!isScala(targetField.getType())) {
if (targetField.getGenericType() instanceof ParameterizedType) {
ParameterizedType genericType = (ParameterizedType) targetField.getGenericType();
if (genericType.getRawType().equals(List.class)) {
targetValue = from((Class) genericType.getActualTypeArguments()[0], (List) srcValue);
}
} else {
targetValue = from(targetField.getType(), srcValue);
}
} else {
if (srcValue != null) {
targetValue = primitive(targetField.getType(), srcValue);
}
}
if (targetValue != null) {
try {
targetField.setAccessible(true);
targetField.set(instance, targetValue);
} catch (IllegalAccessException e) {
setValue(instance, targetField, targetValue);
}
}
}
return instance;
}
private static <T> void setValue(T instance, Field targetField, Object targetValue) {
String fieldName = targetField.getName();
char first = Character.toUpperCase(fieldName.charAt(0));
String getMethodName = "set" + first + fieldName.substring(1);
Method method;
try {
method = instance.getClass().getMethod(getMethodName, targetField.getType());
} catch (NoSuchMethodException ignore) {
return;
}
try {
method.invoke(instance, targetValue);
} catch (IllegalAccessException | InvocationTargetException e1) {
return;
}
}
private static Object getValue(Field field, Object instance) {
try {
field.setAccessible(true);
return field.get(instance);
} catch (IllegalAccessException e) {
String fieldName = field.getName();
char first = Character.toUpperCase(fieldName.charAt(0));
String getMethodName = "get" + first + fieldName.substring(1);
Method method;
try {
method = instance.getClass().getMethod(getMethodName);
} catch (NoSuchMethodException ignore) {
return null;
}
try {
return method.invoke(instance);
} catch (IllegalAccessException | InvocationTargetException e1) {
return null;
}
}
}
private static Object getValue(String fieldName, Object instance) {
Field field = null;
try {
field = instance.getClass().getDeclaredField(fieldName);
} catch (NoSuchFieldException ignore) {
}
if (field != null) {
field.setAccessible(true);
try {
return field.get(instance);
} catch (IllegalAccessException e) {
}
}
char first = Character.toUpperCase(fieldName.charAt(0));
String getMethodName = "get" + first + fieldName.substring(1);
Method method;
try {
method = instance.getClass().getMethod(getMethodName);
} catch (NoSuchMethodException ignore) {
return null;
}
try {
return method.invoke(instance);
} catch (IllegalAccessException | InvocationTargetException e1) {
return null;
}
}
private static <T> T primitive(Class<T> klass, Object src) {
if (klass.equals(src.getClass())) {
return (T) src;
}
if (klass.equals(String.class)) {
return (T) String.valueOf(src);
}
if (klass.equals(int.class) && src.getClass().equals(Integer.class)) {
return (T) src;
}
if (klass.equals(Integer.class) && src.getClass().equals(int.class)) {
return (T) src;
}
if (klass.equals(boolean.class) && src.getClass().equals(Boolean.class)) {
return (T) src;
}
if (klass.equals(Boolean.class) && src.getClass().equals(boolean.class)) {
return (T) src;
}
if (klass.equals(long.class) && src.getClass().equals(Long.class)) {
return (T) src;
}
if (klass.equals(Long.class) && src.getClass().equals(long.class)) {
return (T) src;
}
if (klass.equals(float.class) && src.getClass().equals(Float.class)) {
return (T) src;
}
if (klass.equals(Float.class) && src.getClass().equals(float.class)) {
return (T) src;
}
if (klass.equals(double.class) && src.getClass().equals(Double.class)) {
return (T) src;
}
if (klass.equals(Double.class) && src.getClass().equals(double.class)) {
return (T) src;
}
if (klass.equals(byte.class) && src.getClass().equals(Byte.class)) {
return (T) src;
}
if (klass.equals(Byte.class) && src.getClass().equals(byte.class)) {
return (T) src;
}
if (klass.equals(char.class) && src.getClass().equals(Character.class)) {
return (T) src;
}
if (klass.equals(Character.class) && src.getClass().equals(char.class)) {
return (T) src;
}
if (klass.equals(short.class) && src.getClass().equals(Short.class)) {
return (T) src;
}
if (klass.equals(Short.class) && src.getClass().equals(short.class)) {
return (T) src;
}
if (klass.equals(long.class) && src.getClass().equals(String.class)) {
return (T) Long.valueOf((String) src);
}
if (klass.equals(Long.class) && src.getClass().equals(String.class)) {
return (T) Long.valueOf((String) src);
}
if (klass.equals(int.class) && src.getClass().equals(String.class)) {
return (T) Integer.valueOf((String) src);
}
if (klass.equals(Integer.class) && src.getClass().equals(String.class)) {
return (T) Integer.valueOf((String) src);
}
if (klass.equals(boolean.class) && src.getClass().equals(String.class)) {
return (T) Boolean.valueOf((String) src);
}
if (klass.equals(Boolean.class) && src.getClass().equals(String.class)) {
return (T) Boolean.valueOf((String) src);
}
if (klass.equals(float.class) && src.getClass().equals(String.class)) {
return (T) Float.valueOf((String) src);
}
if (klass.equals(Float.class) && src.getClass().equals(String.class)) {
return (T) Float.valueOf((String) src);
}
if (klass.equals(double.class) && src.getClass().equals(String.class)) {
return (T) Double.valueOf((String) src);
}
if (klass.equals(Double.class) && src.getClass().equals(String.class)) {
return (T) Double.valueOf((String) src);
}
if (klass.equals(byte.class) && src.getClass().equals(String.class)) {
return (T) Byte.valueOf((String) src);
}
if (klass.equals(Byte.class) && src.getClass().equals(String.class)) {
return (T) Byte.valueOf((String) src);
}
if (klass.equals(short.class) && src.getClass().equals(String.class)) {
return (T) Short.valueOf((String) src);
}
if (klass.equals(Short.class) && src.getClass().equals(String.class)) {
return (T) Short.valueOf((String) src);
}
return null;
}
public static <T> List<T> from(Class<T> klass, List sources) {
if (sources == null) {
return Collections.emptyList();
}
List<T> list = new ArrayList<>();
for (Object src : sources) {
if (src != null) {
T target = from(klass, src);
list.add(target);
}
}
return list;
}
private static boolean isScala(Class klass) {
if (klass.isPrimitive()) {
return true;
} else if (klass.equals(Date.class)) {
return true;
} else if (klass.equals(String.class)) {
return true;
} else if (klass.equals(Integer.class)) {
return true;
} else if (klass.equals(Long.class)) {
return true;
} else if (klass.equals(Boolean.class)) {
return true;
} else if (klass.equals(Float.class)) {
return true;
} else if (klass.equals(Double.class)) {
return true;
} else if (klass.equals(Byte.class)) {
return true;
} else if (klass.equals(Short.class)) {
return true;
}
return false;
}
}
|
package health.linegym.com.linegym;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebViewDatabase;
import android.widget.TextView;
/**
* Created by jongmun on 2017-03-04.
*/
public class AWebView extends BaseLineGymActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_webview_layout);
findViewById(R.id.comm_title_btn_navi_back).setOnClickListener(onBaseClickListener);
TextView title = (TextView) findViewById(R.id.tv_comm_title);
WebView web_view = (WebView) findViewById(R.id.web_view);
web_view.getSettings().setJavaScriptEnabled(true);
web_view.setWebViewClient(new MyWebViewClient());
web_view.getSettings().setPluginState(WebSettings.PluginState.ON);
if(Build.VERSION.SDK_INT < 21)
{
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
}
web_view.clearHistory();
web_view.clearCache(true);
WebViewDatabase.getInstance(this).clearHttpAuthUsernamePassword();
//************************************************************
web_view.getSettings().setSupportZoom(true);
if(Build.VERSION.SDK_INT > 10)
{
web_view.getSettings().setDisplayZoomControls(false);
}
web_view.getSettings().setBuiltInZoomControls(true);
web_view.getSettings().setUseWideViewPort(false);
web_view.getSettings().setLoadWithOverviewMode(true);
String pdfURL = "";
if(getIntent().getBooleanExtra("is_private", false)) {
pdfURL = "http://rain16boy.cafe24.com/private_individual.pdf";
title.setText("개인정보 취급");
}else {
title.setText("서비스 이용방침");
pdfURL = "http://rain16boy.cafe24.com/line_gym_member_agreement.pdf";
}
web_view.loadUrl(
"http://docs.google.com/gview?embedded=true&url=" + pdfURL);
}
public class MyWebViewClient extends WebViewClient
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// TODO Auto-generated method stub
// view.loadUrl(url);
// return false;
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm)
{
// TODO Auto-generated method stub
handler.proceed("admin", "pass");
// super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
}
}
|
package com.bingo.code.example.design.templatemethod.rewrite;
/**
* ��ͨ�û���¼���Ƶ�������
*/
public class NormalLogin extends LoginTemplate{
public LoginModel findLoginUser(String loginId) {
// ����ʡ�Ծ���Ĵ�������ʾ�⣬����һ����Ĭ�����ݵĶ���
LoginModel lm = new LoginModel();
lm.setLoginId(loginId);
lm.setPwd("testpwd");
return lm;
}
}
|
public class Test33 {
public static void main(String[] args) {
// vérifie que les asserts sont activés
if (!Test33.class.desiredAssertionStatus()) {
System.err.println("Vous devez activer l'option -ea de la JVM");
System.err.println("(Run As -> Run configurations -> Arguments -> VM Arguments)");
System.exit(1);
}
System.out.print("Test de la méthode simulation33() ... ");
int size = NetworkSimulation.simulation33(524287, 1000000);
assert(NetworkSimulation.network.nbCalls == 1840581) : "\nLe nombre total d'appels devrait être 1840581 (vous en avez enregistré " + NetworkSimulation.network.nbCalls + ").";
assert(size == 972133) : "\nLa taille de la classe du président devrait être 972133 (vous en avez enregistré " + size + ").";
System.out.println("[OK]");
}
}
|
package com.jidouauto.mvvm.ui.widget;
import android.content.Context;
import android.graphics.*;
import android.util.AttributeSet;
/**
* @author leosun.
* @date 2018/8/12.
*/
public class WaveView extends BaseSurfaceView {
/**
* 逐帧变化的 图片资源,记得压缩
*/
int[] mResArray = new int[]{
};
private Paint mPaintWave;
private int mWidth;
private int mHeight;
private int mCenterX, mCenterY;
private int mIndex;
public WaveView(Context context) {
this(context, null);
}
public WaveView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public WaveView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaint();
}
@Override
protected void onRender(Canvas canvas) {
super.onRender(canvas);
canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
enforceInitial();
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
//逐帧循环 播放
int index = mIndex % 118;
Bitmap bt = BitmapFactory.decodeResource(getResources(), mResArray[index]);
canvas.drawBitmap(bt, mCenterX - bt.getWidth() / 2, mCenterY - bt.getHeight() / 2, mPaintWave);
mIndex++;
}
void enforceInitial() {
if (mWidth == 0) {
mWidth = getWidth();
mHeight = getHeight();
mCenterX = (int) (mWidth / 2f);
mCenterY = (int) (mHeight / 2f);
}
}
private void initPaint() {
mPaintWave = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
}
}
|
package _5oneToOneMapperReturnType.mapper;
import _5oneToOneMapperReturnType.po.OrderCustom;
import java.util.List;
/**
* Created by acey on 17-3-23.
*/
public interface OrderCustomMapper {
List<OrderCustom> findOrdersUser();
}
|
package com.tencent.tencentmap.mapsdk.a;
import android.view.View;
public class nk {
private oi a = null;
public nk(oi oiVar) {
this.a = oiVar;
}
public void a() {
if (this.a != null) {
this.a = null;
}
}
public View b() {
if (this.a == null) {
return null;
}
return this.a.c();
}
}
|
package net.packet;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Arrays;
import lombok.Getter;
import net.ClientOpCode;
import net.OpCode;
import net.ServerOpCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
public class MaplePacket {
@Getter
private short type;
@Getter
private byte[] payload;
private boolean fromServer;
public MaplePacket(int type, byte[] payload, boolean fromServer) {
this.type = (short) type;
this.payload = payload;
this.fromServer = fromServer;
}
public boolean isFromServer() {
return fromServer;
}
public OpCode getOpCode(){
if(fromServer){
return ServerOpCode.getById(type);
}else{
return ClientOpCode.getById(type);
}
}
protected MaplePacket(int type){
this.type = (short) type;
}
public void setPayload(byte[] buffer){
payload = buffer;
}
protected void setPayload(ByteBuf buf){
payload = buf.array();
}
@Override
public String toString() {
Object obj = getOpCode();
if(obj == null){
obj = type;
}
return "{"+obj+"} "+Arrays.toString(getPayload())+" ("+new String(getPayload())+")";
}
public ByteBuf toBuffer() {
return Unpooled.copiedBuffer(payload).order(ByteOrder.LITTLE_ENDIAN);
}
public static String readString(ByteBuf buf, int length){
byte[] strB = new byte[length];
buf.readBytes(strB);
return new String(strB, Charset.forName("US-ASCII"));
}
public static String readString(ByteBuf buf){
short length = buf.readShort();
return readString(buf, length);
}
public static void writeString(ByteBuf buf, String str){
byte[] bytes = str.getBytes(Charset.forName("US-ASCII"));
short length = (short) str.length();
buf.writeShort(length);
buf.writeBytes(bytes);
}
}
|
import java.lang.reflect.Array;
import java.util.ArrayList;
public class BackFromTheBrinkSquare extends Square{
private final int REQUIRED_MATERIALS;
public BackFromTheBrinkSquare(String name, int pos, int requiredMaterials) {
super(name, pos);
this.REQUIRED_MATERIALS = requiredMaterials;
}
public int getRequiredMaterials() {
return this.REQUIRED_MATERIALS;
}
public void execute(Player player) {
// implementation if player has enough materials and has a biome, player is prompted if they want to buy the square
System.out.println(StdIO.printSquareLandedOn(player, this.getName()));
if (player.getInventory().getMaterials() >= getRequiredMaterials() && player.getInventory().hasCompleteBiome()) {
System.out.println("Would you like to buy it? (y/n)");
String response = StdIO.read();
if (response.equals("y")) {
BackFromTheBrink.setBftbWon();
} else {
System.out.println("Operation cancelled.");
}
} else {
System.out.println("Unfortunately you do not meet the requirements to buy the BFTB square.");
System.out.println("You need to own at least one biome and have a minimum of 1000 materials!");
}
}
@Override
public boolean isOwned() {
return false;
}
}
|
/**
* 문제: https://programmers.co.kr/learn/courses/10302/lessons/62948
* 접근 과정:
* 1. 모든 숫자의 조합을 만든 후 그 중 가장 큰 숫자 반환 => 숫자가 길어지면 표현 범위를 넘을 수 있다.
* => 반환 형태가 문자열이네 -> 숫자를 문자열로 연결 짓기
* 2. 큰 숫자 순으로 정렬했다고 큰 수가 되진 않네 (ex) 6,10,2 -> 1062 < 6210) => 숫자가 아닌 문자 정렬(내림차순) 후에 조합을 해보자.
* => 주의! s1, s2 비교가 아닌 s1+s2, s2+s1 비교를 해야한다.
*/
/**
* s1. 버블 정렬을 이용한 방법
* 시간 초과 발생
* 이유: 버블 정렬은 시간 복잡도(o(n^2))가 크다.
*/
class Solution {
public String solution(int[] numbers) {
// 숫자 -> 문자열 배열로 변환
String[] str_numbers = new String[numbers.length];
for (int i = 0; i < numbers.length; ++i) {
str_numbers[i] = Integer.toString(numbers[i]);
}
// 내림차순 정렬
for (int i = 0; i < str_numbers.length - 1; ++i) {
for (int j = i + 1; j < str_numbers.length; ++j) {
String s1 = str_numbers[i];
String s2 = str_numbers[j];
if((s1+s2).compareTo(s2+s1) < 0) {
str_numbers[i] = s2;
str_numbers[j] = s1;
}
}
}
String answer = "";
for (String val : str_numbers) {
answer += val;
}
return (answer.charAt(0) == '0') ? "0" : answer;
}
}
/**
* s2. 자바 라이브러리를 사용한 방법
* 권장 방법. 시간 초과 발생 안함
*/
import java.util.*;
class Solution {
public String solution(int[] numbers) {
// 숫자 -> 문자열 배열로 변환
String[] str_numbers = new String[numbers.length];
for (int i = 0; i < numbers.length; ++i) {
str_numbers[i] = Integer.toString(numbers[i]);
}
// 내림차순
for (int i = 0; i < str_numbers.length - 1; ++i) {
for (int j = i + 1; j < str_numbers.length; ++j) {
Arrays.sort(str_numbers, new Comparator<String>() {
public int compare(String s1, String s2) {
return (s2+s1).compareTo(s1+s2);
}
})
}
}
String answer = "";
for (String val : str_numbers) {
answer += val;
}
return (answer.charAt(0) == '0') ? "0" : answer;
}
}
/**
* s3. s2 리팩토링 버전 (Java 8의 람다함수 이용)
* 권장 방법. 시간 초과 발생 x
*/
import java.util.*;
class Solution {
public String solution(int[] numbers) {
// 숫자 -> 문자열 배열로 변환
String[] str_numbers = new String[numbers.length];
for (int i = 0; i < numbers.length; ++i) {
str_numbers[i] = Integer.toString(numbers[i]);
}
/**
* 내림차순 정렬 (람다함수 이용)
* Arrays.sort 두번째 arg는 Comparator 한 종류 밖에 없기 때문에 안 써줘도 컴파일러가 알아서 인지한다.
* Comparator 메소드는 compare 하나 밖에 없기 때문에 안 써줘도 컴파일러가 알아서 인지한다.
* str_numbers은 String 배열이기 때문에 String 타입도 생략 가능하다.
*/
Arrays.sort(str_numbers, (s1, s2) -> (s2+s1).compareTo(s1+s2));
String answer = "";
for (String val : str_numbers) {
answer += val;
}
// 첫번째 숫자가 0일 경우
// return (answer.charAt(0) == '0') ? "0" : answer;
return (answer.startsWith("0")) ? "0" : answer;
}
}
/**
* s4. s3 리팩토링 버전 (Stream 이용)
* 권장 방법. 시간 초과 발생 x
*/
import java.util.*;
import java.util.stream.*;
class Solution {
public String solution(int[] numbers) {
// 숫자 -> 문자열 배열로 변환한 후 내림차순 정렬
// 메소드 레퍼런스로 다음처럼 축약 가능
// .mapToObject(n -> String.valueOf(n)) <==> .mapToObject(String::valueOf)
String answer = IntStream.of(numbers) // <- intStream으로 반환
.mapToObj(String::valueOf) //
.sorted((s1, s2) -> (s2+s1).compareTo(s1+s2))
.collect(Collectors.joining());
return (answer.startsWith("0")) ? "0" : answer;
}
}
|
package cl.cvaldex.scrobbler.parser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
//import org.lastpod.TrackItem;
import de.umass.lastfm.scrobble.ScrobbleData;
public class CSVParser {
public static final int DEFAULT_DURATION = 4000;
public static List<ScrobbleData> fileParser(String absoluteFilePath) throws Exception{
File file = new File(absoluteFilePath);
if(!file.exists() || !file.canRead()){
throw new Exception("Error reading file: " + absoluteFilePath);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
String line = null;
List<ScrobbleData> trackList = new ArrayList<ScrobbleData>();
int currentLine = 1;
while((line = reader.readLine()) != null){
//saltar las lineas que empiezan por # ya que son comentarios
if(!line.startsWith("#")){
try{
//quitar el tab inicial que reemplaza al # cuando es línea válida
trackList.add(parseLine(line.trim()));
}
catch(Exception e){
System.out.println("Error parsing line " + currentLine + ": " + line);
}
}
currentLine++;
}
reader.close();
return trackList;
}
private static ScrobbleData parseLine(String line) throws Exception{
String [] fields = line.split("\t");
if(fields.length < 4){
throw new Exception("Campos mínimos para scrobbling son Artista, Album, Nombre Track, Largo y Playcount");
}
ScrobbleData scrobble = new ScrobbleData();
scrobble.setArtist(fields[0]);
scrobble.setAlbum(fields[1]);
scrobble.setTrack(fields[2]);
scrobble.setPlayCount(Integer.parseInt(fields[3]));
scrobble.setDuration(DEFAULT_DURATION);
return scrobble;
}
}
|
package org.iptc.extra.core.eql.tree.nodes;
/**
*
* @author manos schinas
*
* Part of search clauses:
*
* Index Relation SearchTerm
* | | |
* title any "term1 term2"
*
*/
public class Index extends Node {
private String name;
public Index(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean hasChildren() {
return false;
}
@Override
public String toString() {
return name;
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.cmsitems.impl;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.cms2.cmsitems.service.CMSItemSearchService;
import de.hybris.platform.cms2.common.functions.Converter;
import de.hybris.platform.cms2.common.service.SessionSearchRestrictionsDisabler;
import de.hybris.platform.cms2.data.PageableData;
import de.hybris.platform.cms2.exceptions.CMSItemNotFoundException;
import de.hybris.platform.cms2.model.contents.CMSItemModel;
import de.hybris.platform.cms2.servicelayer.services.admin.impl.DefaultCMSAdminSiteService;
import de.hybris.platform.cmsfacades.cmsitems.*;
import de.hybris.platform.cmsfacades.common.validator.FacadeValidationService;
import de.hybris.platform.cmsfacades.common.validator.ValidationErrors;
import de.hybris.platform.cmsfacades.common.validator.ValidationErrorsProvider;
import de.hybris.platform.cmsfacades.data.CMSItemSearchData;
import de.hybris.platform.cmsfacades.data.ItemData;
import de.hybris.platform.cmsfacades.uniqueidentifier.UniqueItemIdentifierService;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.core.model.ItemModel;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.SearchResult;
import java.util.*;
import java.util.function.Supplier;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.validation.Validator;
import com.google.common.collect.Lists;
import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.*;
import static java.util.Arrays.asList;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class DefaultCMSItemFacadeTest
{
private static final String VALID_UID = "valid-item-uid";
private static final String INVALID_UID = "invalid-item-uid";
@InjectMocks
private DefaultCMSItemFacade facade;
@Mock
private PlatformTransactionManager transactionManager;
@Mock
private ValidationErrorsProvider validationErrorsProvider;
@Mock
private CMSItemConverter CMSItemConverter;
@Mock
private ModelService modelService;
@Mock
private UniqueItemIdentifierService uniqueItemIdentifierService;
@Mock
private CMSItemModel itemModel;
@Mock
private ItemData invalidItemData;
@Mock
private ItemData validItemData;
@Mock
private ItemTypePopulatorProvider itemTypePopulatorProvider;
@Mock
private ItemDataPopulatorProvider itemDataPopulatorProvider;
@Mock
private Populator<Map<String, Object>, ItemModel> itemTypePopulator;
@Mock
private Populator<CMSItemModel, Map<String, Object>> itemDataPopulator;
@Mock
private CMSItemSearchService cmsItemSearchService;
@Mock
private Validator cmsItemSearchParamsDataValidator;
@Mock
private FacadeValidationService facadeValidationService;
@Mock
private DefaultCMSAdminSiteService defaultCMSAdminSiteService;
@Mock
private SessionSearchRestrictionsDisabler searchRestrictionsDisabler;
@Mock
private Converter<CMSItemSearchData, de.hybris.platform.cms2.data.CMSItemSearchData> cmsItemSearchDataConverter;
@Mock
private ValidationErrors validationErrors;
@Before
public void setup() throws CMSItemNotFoundException
{
when(validationErrors.getValidationErrors()).thenReturn(asList());
when(validationErrorsProvider.getCurrentValidationErrors()).thenReturn(validationErrors);
when(uniqueItemIdentifierService.getItemModel(invalidItemData)).thenReturn(Optional.empty());
when(uniqueItemIdentifierService.getItemModel(validItemData)).thenReturn(Optional.of(itemModel));
when(uniqueItemIdentifierService.getItemModel(any(), any())).thenReturn(Optional.empty());
when(uniqueItemIdentifierService.getItemModel(INVALID_UID, CMSItemModel.class)).thenReturn(Optional.empty());
when(uniqueItemIdentifierService.getItemModel(VALID_UID, CMSItemModel.class)).thenReturn(Optional.of(itemModel));
when(itemTypePopulatorProvider.getItemTypePopulator(any())).thenReturn(Optional.of(itemTypePopulator));
when(itemDataPopulatorProvider.getItemDataPopulators(any())).thenReturn(Arrays.asList(itemDataPopulator));
when(CMSItemConverter.convert(any(Map.class))).thenReturn(itemModel);
doAnswer(invocation -> {
final Object[] args = invocation.getArguments();
Supplier supplier = (Supplier)args[0];
return supplier.get();
}).when(searchRestrictionsDisabler).execute(any());
facade.setCmsAdminSiteService(defaultCMSAdminSiteService);
}
@Test(expected = RuntimeException.class)
public void whenFindByIdWithInvalidUidThenShouldThrowException() throws CMSItemNotFoundException
{
facade.getCMSItemByUuid(INVALID_UID);
}
@Test
public void whenFindByIdWithValidUidShouldPerformConversion() throws CMSItemNotFoundException
{
facade.getCMSItemByUuid(VALID_UID);
verify(CMSItemConverter).convert(itemModel);
}
@Test
public void whenDeleteByIdWithValidUidShouldRemoveItem() throws CMSItemNotFoundException
{
facade.deleteCMSItemByUuid(VALID_UID);
verify(modelService).remove(itemModel);
}
@Test
public void shouldCreateItem() throws CMSItemNotFoundException
{
final Map<String, Object> map = new HashMap<>();
facade.createItem(map);
verify(CMSItemConverter).convert(map);
verify(itemTypePopulator).populate(map, itemModel);
verify(CMSItemConverter).convert(itemModel);
verify(transactionManager, never()).rollback(any(TransactionStatus.class));
verify(itemDataPopulator).populate(itemModel, map);
}
@Test
public void shouldValidateItemForCreateAndRollbackTransaction() throws CMSItemNotFoundException
{
final Map<String, Object> map = new HashMap<>();
facade.validateItemForCreate(map);
verify(CMSItemConverter).convert(map);
verify(itemTypePopulator).populate(map, itemModel);
verify(CMSItemConverter).convert(itemModel);
verify(itemDataPopulator).populate(itemModel, map);
verify(modelService).saveAll();
verify(modelService).refresh(itemModel);
verify(modelService).detachAll();
verify(transactionManager).rollback(any(TransactionStatus.class));
}
@Test(expected = CMSItemNotFoundException.class)
public void updateShouldThrowExceptionWhenUuidIsInvalid() throws CMSItemNotFoundException
{
facade.updateItem(INVALID_UID, new HashMap<>());
}
@Test(expected = CMSItemNotFoundException.class)
public void shouldThrowExceptionWhenUpdateItemHasInconsistentValue() throws CMSItemNotFoundException
{
final Map<String, Object> map = new HashMap<>();
facade.updateItem(VALID_UID, map);
verify(CMSItemConverter).convert(map);
verify(itemTypePopulator).populate(map, itemModel);
verify(CMSItemConverter).convert(itemModel);
}
@Test
public void shouldUpdateItem() throws CMSItemNotFoundException
{
final Map<String, Object> map = new HashMap<>();
map.put(FIELD_UUID, VALID_UID);
facade.updateItem(VALID_UID, map);
verify(CMSItemConverter).convert(map);
verify(itemTypePopulator).populate(map, itemModel);
verify(CMSItemConverter).convert(itemModel);
verify(transactionManager, never()).rollback(any(TransactionStatus.class));
}
@Test
public void shouldValidateItemForUpdateAndRollbackTransaction() throws CMSItemNotFoundException
{
final Map<String, Object> map = new HashMap<>();
map.put(FIELD_UUID, VALID_UID);
facade.validateItemForUpdate(VALID_UID, map);
verify(CMSItemConverter).convert(map);
verify(itemTypePopulator).populate(map, itemModel);
verify(CMSItemConverter).convert(itemModel);
verify(modelService).saveAll();
verify(modelService).refresh(itemModel);
verify(modelService).detachAll();
verify(transactionManager).rollback(any(TransactionStatus.class));
}
@Test
public void shouldSearchForItems()
{
// Input
final CMSItemSearchData cmsItemSearchData = new CMSItemSearchData();
final PageableData pageableData = new PageableData();
// Intermediary data
final SearchResult<CMSItemModel> modelResults = mock(SearchResult.class);
final CMSItemModel mockItem1 = mock(CMSItemModel.class);
final CMSItemModel mockItem2 = mock(CMSItemModel.class);
final List<CMSItemModel> mockedResuls = Lists.newArrayList(mockItem1, mockItem2);
final de.hybris.platform.cms2.data.CMSItemSearchData cms2ItemSearchData = mock(de.hybris.platform.cms2.data.CMSItemSearchData.class);
when(cmsItemSearchDataConverter.convert(cmsItemSearchData)).thenReturn(cms2ItemSearchData);
when(cmsItemSearchService.findCMSItems(cms2ItemSearchData, pageableData)).thenReturn(modelResults);
when(modelResults.getResult()).thenReturn(mockedResuls);
facade.findCMSItems(cmsItemSearchData, pageableData);
verify(facadeValidationService).validate(cmsItemSearchParamsDataValidator, cmsItemSearchData);
verify(cmsItemSearchService).findCMSItems(cms2ItemSearchData, pageableData);
verify(CMSItemConverter).convert(mockItem1);
verify(CMSItemConverter).convert(mockItem2);
}
}
|
package com.telia.aws.cloudwatchtoremotebucket;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.util.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import static com.telia.aws.cloudwatchtoremotebucket.EnvironmentUtils.injectEnvironmentVariable;
import static com.telia.aws.cloudwatchtoremotebucket.JacksonConfiguration.mapper;
import static com.telia.aws.cloudwatchtoremotebucket.LogsDecoder.fromBase64EncodedZippedPayload;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class HandlerTest {
@Mock
private AmazonS3 s3Client;
@Mock
private Context context;
/**
* {
* "@timestamp": "2018-11-20T12:08:27.800+00:00",
* "@version": "1",
* "message": "Refreshing caches...",
* "logger_name": "no.netcom.minbedrift.caching.CacheWarmerProcess",
* "thread_name": "pool-3-thread-2",
* "level": "INFO",
* "level_value": 20000,
* "source": "/minbedrift/logs/server.log",
* "sourcetype": "minbedrift:server"
* }
*/
private String awsLogsEvent = "{\n" +
" \"awslogs\": {\n" +
" \"data\": \"H4sIAGGh9lsAA+1S3WqDMBi971OUXNsRE01N72RzZbDCqDIGyxBXQwmokSRuFPHdF9POuT7C2HcVOD/fOR/pF0s7QH42XIHNEvizAd4ZrORxq2TXjvhtJbsyU4WoZmhqFC/qa3n+w807veKFNqvJU3fv+qBEa4Rs7kVluNJW/+pAR9jzg2gFb8zF3CFvF3XNtS6OPDu1fNx6F2dxvkvSNN4ms1jJh5X/tu2nlyOJcpRjn4bYh4RAQgmhEcbrKIIUohCuaQQDZMsEGEWU+GGAAkSTl3j39Pi9anIzwuYyRT0eygkQicIQQnjFu6QfV/cM8DHls+1vL8HAhgH/BmIGPAY6zdVDaVFhThaxXGMLO85eSsPAACbjwfvv+Cc6nv/5YvgClUAhi5kDAAA=\"\n" +
" }\n" +
" }";
/**
* Basic Bas64 and Gzip decode test.
*/
@Test
public void shouldDecodeBase64EncodedAndGzippedPayload() throws IOException {
CloudWatchPutRequest event = mapper.readValue(awsLogsEvent, CloudWatchPutRequest.class);
CloudWatchLogEvents events = fromBase64EncodedZippedPayload(event.getAwslogs().getData());
assertEquals(3, events.getLogEvents().size());
}
/**
* This test makes sure that the Cloudwatch Log event is split, and that metadata like owner, log group and log
* stream are added to the each item, when the environment variable 'split' is set to true
*
* @throws Exception
*/
@Test
public void shouldSplitEvents() throws Exception {
injectEnvironmentVariable("bucket_name", "somebucket");
injectEnvironmentVariable("split", "true");
CloudWatchPutRequest awsCloudWatchEvent = mapper.readValue(awsLogsEvent, CloudWatchPutRequest.class);
CloudWatchLogEvents payload = fromBase64EncodedZippedPayload(awsCloudWatchEvent.getAwslogs().getData());
ArgumentCaptor<PutObjectRequest> captor = ArgumentCaptor.forClass(PutObjectRequest.class);
Handler handler = new Handler();
handler.setS3Client(s3Client);
when(context.getInvokedFunctionArn()).thenReturn("arn:aws:lambda:eu-west-1:369412094037:function:sample_log_forwarder");
handler.handleRequest(awsCloudWatchEvent, context);
// capture the PutObjectRequest that was sent to the object by the handler
verify(s3Client).putObject(captor.capture());
// Assert using JSON Tree , because the output stream is no longer compatible with the class due to
// Custom Serialization
System.out.println(IOUtils.toString(captor.getValue().getInputStream()));
}
}
|
package com.hj.wakeuplight.login.presenter;
import android.text.TextUtils;
import android.util.Log;
import com.hj.wakeuplight.base.net.Net;
import com.hj.wakeuplight.login.contact.LoginContact;
import com.hjtech.base.base.BasePresenterImpl;
import com.hjtech.base.retroft.RetroftUtils;
import com.hjtech.base.utils.RxSchedulers;
import com.hjtech.base.utils.ToastUtils;
import io.reactivex.functions.Consumer;
import static android.content.ContentValues.TAG;
public class LoginPresenter extends BasePresenterImpl<LoginContact.View> implements LoginContact.Presenter {
public LoginPresenter(LoginContact.View view) {
super(view);
}
@Override
public void login() {
if (TextUtils.isEmpty(view.getName())) {
ToastUtils.showShortSafe("请输入用户名");
return;
}
if (TextUtils.isEmpty(view.getPsw())) {
ToastUtils.showShortSafe("请输入密码");
return;
}
/*
else {
RetroftUtils.getApi().create(Net.class).register(view.getdata()[0])
.compose(RxSchedulers.<String>io_main())
.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
//成功回调
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
//失败处理
}
});
}
*/
}
}
|
package pt.up.fe.socialcrowd.logic;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import pt.up.fe.socialcrowd.API.RequestException;
public class DetailedEvent extends BaseEvent {
private ArrayList<Subscription> subscriptions;
private ArrayList<Comment> comments;
private ArrayList<Rating> ratings;
/**
* @param type
* @param id
* @param name
* @param description
* @param start_date
* @param end_date
* @param location
* @param tags
* @param category
* @param rating
* @param subscriptions
* @param comments
*/
public DetailedEvent(int type, int id, int author_id, String name, String description,
Date start_date, Date end_date, Location location,
ArrayList<String> tags, String category, double rating,
ArrayList<Subscription> subscriptions, ArrayList<Comment> comments, ArrayList<Rating> ratings) {
super(type, id, author_id, name, description, start_date, end_date, location,
tags, category, rating);
this.subscriptions = subscriptions;
this.comments = comments;
this.ratings = ratings;
}
public static DetailedEvent parseJSON(JSONObject data) throws JSONException, RequestException, ParseException {
int type;
double rating = 0.0;
String strtype = data.getString("type");
if (strtype.equals("public"))
type = BaseEvent.PUBLIC;
else if (strtype.equals("private"))
type = BaseEvent.PRIVATE;
else if (strtype.equals("geolocated"))
type = BaseEvent.GEOLOCATED;
else
throw new RequestException("invalid event type");
JSONArray arraytags = data.getJSONArray("tags");
ArrayList<String> tags = new ArrayList<String>();
for (int i = 0; i < arraytags.length(); i++) {
tags.add(arraytags.getString(i));
}
JSONArray arraysubscriptions = data.getJSONArray("subscriptions");
ArrayList<Subscription> subscriptions = new ArrayList<Subscription>();
for (int i = 0; i < arraysubscriptions.length(); i++) {
subscriptions.add(Subscription.parseJSON(arraysubscriptions.getJSONObject(i)));
}
JSONArray arraycomments = data.getJSONArray("comments");
ArrayList<Comment> comments = new ArrayList<Comment>();
for (int i = 0; i < arraycomments.length(); i++) {
comments.add(Comment.parseJSON(arraycomments.getJSONObject(i)));
}
JSONArray arrayratings = data.getJSONArray("ratings");
ArrayList<Rating> ratings = new ArrayList<Rating>();
for (int i = 0; i < arrayratings.length(); i++) {
ratings.add(Rating.parseJSON(arrayratings.getJSONObject(i)));
}
if(!data.isNull("rating")) {
rating = data.getDouble("rating");
}
return new DetailedEvent(
type,
data.getInt("id"),
data.getInt("author_id"),
data.getString("name"),
data.getString("description"),
DateParser.parseString(data.getString("start_date")),
DateParser.parseString(data.getString("start_date")),
Location.parseJSON(data.getJSONObject("location")),
tags,
data.getString("category"),
rating,
subscriptions,
comments,
ratings);
}
/**
* @return the subscriptions
*/
public ArrayList<Subscription> getSubscriptions() {
return subscriptions;
}
/**
* @param subscriptions the subscriptions to set
*/
public void setSubscriptions(ArrayList<Subscription> subscriptions) {
this.subscriptions = subscriptions;
}
/**
* @return the comments
*/
public ArrayList<Comment> getComments() {
return comments;
}
/**
* @param comments the comments to set
*/
public void setComments(ArrayList<Comment> comments) {
this.comments = comments;
}
/**
* @return the ratings
*/
public ArrayList<Rating> getRatings() {
return ratings;
}
/**
* @param ratings the ratings to set
*/
public void setRatings(ArrayList<Rating> ratings) {
this.ratings = ratings;
}
}
|
package actividad_1;
public class Moneda {
/**
* Actividad 1. Clase Cambio Moneda
Realiza una clase Moneda cuyo objetivo es utilizar sus métodos para convertir Euros a Dólares y viceversa.
La clase debe tener:
Un constructor Moneda(), que por defecto establezca el cambio en 1,09 (1€ son 1.09$)
Un constructor Moneda(double) que permita modificar el cambio de moneda
Y los métodos para el cambio: EurosDolares() y DolaresEuros()
Desde una clase externa con main utiliza la clase y métodos anteriores.
*/
//atributos
private double cambio;
//constructores
public Moneda() {
this.cambio = 1.13;
}
public Moneda(double cambio) {
this.cambio = cambio;
}
//* Metodos Getters and Setters *//
public double getCambio() {
return cambio;
}
public void setCambio(double cambio) {
this.cambio = cambio;
}
//* Métodos propios de la clase *//
public double EurosDolares(double euros) {
return (double) Math.round(this.cambio*euros * 100) / 100; // (double) Math.round(a * 100)/ 100 --para redondear a 2 decimales
}
public double DolaresEuros(double dolares) {
return (double) Math.round(dolares/this.cambio * 100) / 100;
}
}
|
package controller;
import http.Request;
import http.RequestMethod;
import http.Response;
import model.User;
import service.UserService;
import util.UserUtils;
/**
* IDE : IntelliJ IDEA
* Created by minho on 2018. 9. 30..
*/
public class JoinController implements Controller {
private UserService userService = new UserService();
@Override
public String execute(Request request, Response response) {
RequestMethod requestMethod = request.getMethod();
switch (requestMethod) {
case GET:
return "/user/form.html";
case POST:
User user = UserUtils.user(request.getParameters());
userService.join(user);
return "redirect:/index.html";
}
return "/index.html";
}
}
|
package com.findbank.c15.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import com.findbank.c15.hash.Hash;
import com.findbank.c15.model.Login;
import com.findbank.c15.model.Usuario;
public class UsuarioDaoImpl implements UsuarioDao{
@Autowired
DataSource datasource;
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void register(Usuario usuario) {
// TODO Auto-generated method stub
String sql = "insert into users values(?,?,?,?,?,?,?,?,?)";
jdbcTemplate.update(sql, new Object[] {usuario.getId(),usuario.getNombre(),usuario.getEmail(), Hash.sha1(usuario.getPassword()), usuario.getTipo(),null, null, null, null});
}
public List<Usuario> getUsers() {
return jdbcTemplate.query("select * from users", new RowMapper<Usuario>() {
public Usuario mapRow(ResultSet rs, int row) throws SQLException {
Usuario user = new Usuario();
user.setId(rs.getInt(1));
user.setNombre(rs.getString(2));
user.setEmail(rs.getString(3));
user.setPassword(rs.getString(4));
user.setTipo(rs.getString(5));
return user;
}
});
}
@Override
public Usuario validateUser(Login login) {
// TODO Auto-generated method stub
String sql = "select * from users where email='" + login.getEmail() + "' and password='" + Hash.sha1(login.getPassword())
+ "'";
List<Usuario> users = jdbcTemplate.query(sql, new UsuarioMapper());
return users.size() > 0 ? users.get(0) : null;
}
@Override
public List<Usuario> findAllEmployees() {
String query = "SELECT id, nombre, email, password, tipo FROM users ";
List<Usuario> users = jdbcTemplate.query(query, new UserMapper());
//
return users;
}
class UsuarioMapper implements RowMapper<Usuario> {
public Usuario mapRow(ResultSet rs, int arg1) throws SQLException {
Usuario usuario = new Usuario();
usuario.setEmail(rs.getString("email"));
usuario.setPassword(rs.getString("password"));
usuario.setNombre(rs.getString("nombre"));
usuario.setTipo(rs.getString("tipo"));
return usuario;
}
}
public class UserMapper implements RowMapper<Usuario>{
public Usuario mapRow(ResultSet rs, int rowNum) throws SQLException {
Usuario usuario = new Usuario();
usuario.setId(rs.getInt("id"));
usuario.setEmail(rs.getString("email"));
usuario.setPassword(rs.getString("password"));
usuario.setNombre(rs.getString("nombre"));
usuario.setTipo(rs.getString("tipo"));
return usuario;
}
}
@Override
public void create(String nombre, String email, String password, String tipo) {
String query = "INSERT INTO users (nombre, email, password, tipo) VALUES ( ?,?,?,? )";
Object[] params = new Object[] { nombre, email, password, tipo};
//Employee emp = null;
// create
jdbcTemplate.update(query, params);
}
@Override
public void delete(int id) {
String query = "DELETE FROM users WHERE id = ? ";
Object[] params = new Object[] { id };
jdbcTemplate.update(query, params);
}
@Override
public void update( int id, String nombre, String email, String password, String tipo) {
String query = "UPDATE users SET nombre = ?, email =?, password = ?, tipo = ? WHERE id = ?";
Object[] params = new Object[] { nombre, email, password, tipo, id };
jdbcTemplate.update(query, params);
}
@Override
public Usuario findUser(int id) {
String query = "SELECT id, nombre, email, password, tipo"
+ " FROM users WHERE id = ?";
Object[] params = new Object[] { id };
Usuario user = (Usuario) jdbcTemplate.queryForObject(query, params, new UserMapper());
//
return user;
}
}
|
package sample;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import project_classes.Customer;
import project_classes.Rental;
import project_classes.Vehicle;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Button btnNewCustomer;
@FXML
private Button btnNewVehicle;
@FXML
private Button btnRentVehicle;
@FXML
private Button btnReturnVehicle;
@FXML
private Button btnListAllRentals;
@FXML
private Pane status;
@FXML
private Label labelStatus;
@FXML
private GridPane pnAddCustomers;
@FXML
private GridPane pnAllRentals;
@FXML
private GridPane pnAddVehicle;
@FXML
private GridPane pnRentVehicle;
@FXML
private GridPane pnReturnVehicle;
@FXML
private GridPane pnAddCustomerFields;
@FXML
private GridPane pnAddVehicleFields;
@FXML
private Button addCustomerBtn;
// Add Customer Stage variable
@FXML
private Button saveNewCustomer;
@FXML
private Button cancelAddCustomerStage;
@FXML
private TextField customerIDNewCustomer;
@FXML
private TextField phoneNumberNewCustomer;
@FXML
private TextField firsNameNewCustomer;
@FXML
private TextField surnameNewCustomer;
@FXML
private CheckBox canRentNewCustomer;
// Add Vehicle Stage variable
@FXML
private Button addVehicleBtn;
@FXML
private Button saveNewVehicle;
@FXML
private Button cancelAddVehicle;
@FXML
private TextField vehicleNumNewVehicle;
@FXML
private TextField makeNewVehicle;
@FXML
private TextField dailyPriceNewVehicle;
@FXML
private TextField categoryNewVehicle;
@FXML
private CheckBox isAvalaibleNewVehicle;
/*
*************************
* CUSTOMER TABLE SET UP *
* ***********************
* */
@FXML
private TableView<Customer> customerTableView;
private ObservableList<Customer> customerCollection;
@FXML
private TableColumn<Customer, String> customerNumber;
@FXML
private TableColumn<Customer, String> customerFirstname;
@FXML
private TableColumn<Customer, String> customerSurname;
@FXML
private TableColumn<Customer, String> customerPhone;
@FXML
private TableColumn<Customer, String> customerCanRent;
/*
*************************
* VEHICLE TABLE SET UP *
* ***********************
* */
@FXML
private TableView<Vehicle> vehicleTableView;
@FXML
private TableColumn<Vehicle, String> vehNumberCol;
@FXML
private TableColumn<Vehicle, String> vehMakeCol;
@FXML
private TableColumn<Vehicle, String> vehCatCol;
@FXML
private TableColumn<Vehicle, Double> vehRentPriceCol;
@FXML
private TableColumn<Vehicle, String> vehAvailCol;
private ObservableList<Vehicle> vehicleCollection;
/*
*************************
* RENTAL TABLE SET UP *
* ***********************
* */
@FXML
private TableView<Rental> rentalsTable;
@FXML
private TableColumn<Vehicle, Integer> rentalNumCol;
@FXML
private TableColumn<Vehicle, String> rentalDateCol;
@FXML
private TableColumn<Vehicle, String> rentalReturnDateCol;
@FXML
private TableColumn<Vehicle, Double> rentalDailyPriceCol;
@FXML
private TableColumn<Vehicle, String> rentalCustCol;
@FXML
private TableColumn<Vehicle, String> rentalVehCol;
@FXML
private TableColumn<Rental, Double> rentalTotalCol;
private ObservableList<Rental> rentalCollection;
private Client client;
@Override
public void initialize(URL location, ResourceBundle resources) {
// initializing the client side
client = new Client("localhost", 8085);
client.runClient();
// customers tableview
customerNumber.setCellValueFactory(new PropertyValueFactory<>("IdNum"));
customerFirstname.setCellValueFactory(new PropertyValueFactory<>("Name"));
customerSurname.setCellValueFactory(new PropertyValueFactory<>("Surname"));
customerPhone.setCellValueFactory(new PropertyValueFactory<>("PhoneNum"));
customerCanRent.setCellValueFactory(new PropertyValueFactory<>("canRent"));
customerCollection = FXCollections.observableArrayList(client.getCustomers());
customerTableView.setItems(customerCollection);
// vehicles tableview
vehNumberCol.setCellValueFactory(new PropertyValueFactory<>("VehNumber"));
vehMakeCol.setCellValueFactory(new PropertyValueFactory<>("Make"));
vehCatCol.setCellValueFactory(new PropertyValueFactory<>("Category"));
vehRentPriceCol.setCellValueFactory(new PropertyValueFactory<>("RentalPrice"));
vehAvailCol.setCellValueFactory(new PropertyValueFactory<>("AvailableForRent"));
vehicleCollection = FXCollections.observableArrayList(client.getVehicles());
vehicleTableView.setItems(vehicleCollection);
// rentals tableview
rentalNumCol.setCellValueFactory(new PropertyValueFactory<>("RentalNumber"));
rentalDateCol.setCellValueFactory(new PropertyValueFactory<>("DateRental"));
rentalReturnDateCol.setCellValueFactory(new PropertyValueFactory<>("DateReturned"));
rentalDailyPriceCol.setCellValueFactory(new PropertyValueFactory<>("PricePerDay"));
rentalCustCol.setCellValueFactory(new PropertyValueFactory<>("CustNumber"));
rentalVehCol.setCellValueFactory(new PropertyValueFactory<>("VehNumber"));
rentalTotalCol.setCellValueFactory(new PropertyValueFactory<>("TotalRental"));
rentalCollection = FXCollections.observableArrayList(client.getRentals());
rentalsTable.setItems(rentalCollection);
}
@FXML
private void handleClicks(ActionEvent event) {
if (event.getSource() == btnNewCustomer) {
// New Customer
labelStatus.setText("Customers");
status.setBackground(new Background(new BackgroundFill(Color.rgb(113, 86, 221),
CornerRadii.EMPTY, Insets.EMPTY)));
managePaneVisibility(pnAddCustomers);
} else if (event.getSource() == btnNewVehicle) {
// New Vehicle
labelStatus.setText("Vehicles");
status.setBackground(new Background(new BackgroundFill(Color.rgb(43, 63, 99),
CornerRadii.EMPTY, Insets.EMPTY)));
managePaneVisibility(pnAddVehicle);
} else if (event.getSource() == btnRentVehicle) {
/*
* ****************
* RENT VEHICLE *
* ****************
* */
labelStatus.setText("Rentals");
status.setBackground(new Background(new BackgroundFill(Color.rgb(44, 99, 63),
CornerRadii.EMPTY, Insets.EMPTY)));
managePaneVisibility(pnRentVehicle);
} else if (event.getSource() == btnReturnVehicle) {
// Return Vehicle
labelStatus.setText("Returns");
status.setBackground(new Background(new BackgroundFill(Color.rgb(99, 43, 63),
CornerRadii.EMPTY, Insets.EMPTY)));
managePaneVisibility(pnReturnVehicle);
} else if (event.getSource() == btnListAllRentals) {
// List rentals
labelStatus.setText("All Rentals");
status.setBackground(new Background(new BackgroundFill(Color.rgb(42, 28, 66),
CornerRadii.EMPTY, Insets.EMPTY)));
managePaneVisibility(pnAllRentals);
}
}
@FXML
protected void handleAddCustomer(ActionEvent event) {
if (event.getSource() == addCustomerBtn) {
managePaneVisibility(pnAddCustomerFields);
} else if (event.getSource() == saveNewCustomer) {
/*
* *****************
* SAVE CUSTOMER *
* *****************
* */
String custID = customerIDNewCustomer.getText();
String phoneNumber = phoneNumberNewCustomer.getText();
String firstName = firsNameNewCustomer.getText();
String surname = surnameNewCustomer.getText();
boolean canRent = canRentNewCustomer.isSelected();
customerIDNewCustomer.setText("");
phoneNumberNewCustomer.setText("");
firsNameNewCustomer.setText("");
surnameNewCustomer.setText("");
canRentNewCustomer.setText("");
Customer customer = new Customer(firstName, surname, custID, phoneNumber, canRent);
String response = client.writeCustomerToServer(customer);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText(response);
alert.showAndWait();
} else if (event.getSource() == cancelAddCustomerStage) {
managePaneVisibility(pnAddCustomers);
}
}
@FXML
void handleAddVehicle(ActionEvent event) {
if (event.getSource() == addVehicleBtn) {
managePaneVisibility(pnAddVehicleFields);
} else if (event.getSource() == saveNewVehicle) {
/*
* *****************
* SAVE VEHICLE *
* *****************
* */
int vn = Integer.parseInt(vehicleNumNewVehicle.getText());
String make = makeNewVehicle.getText();
int category = categoryNewVehicle.getText().equals("Sedan")? 1 : 2;
double dailyPrice = Double.parseDouble(dailyPriceNewVehicle.getText());
boolean isAvailable = isAvalaibleNewVehicle.isSelected();
vehicleNumNewVehicle.setText("");
makeNewVehicle.setText("");
categoryNewVehicle.setText("");
dailyPriceNewVehicle.setText("");
isAvalaibleNewVehicle.setText("");
Vehicle vehicle = new Vehicle(vn, make, category, dailyPrice, isAvailable);
// String response = client.writeCustomerToServer(customer);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("response");
alert.showAndWait();
} else if (event.getSource() == cancelAddVehicle) {
managePaneVisibility(pnAddVehicle);
}
}
private void managePaneVisibility(Pane pane) {
Pane[] panes = {pnAddCustomers, pnAllRentals, pnAddVehicle, pnRentVehicle, pnReturnVehicle, pnAddCustomerFields,
pnAddVehicleFields};
for (Pane cpane : panes) {
if (pane.equals(cpane)) {
cpane.setVisible(true);
} else {
cpane.setVisible(false);
}
}
}
}
|
package com.jegsoftware.payperiodbudgeting.logic;
import android.view.View;
import com.jegsoftware.payperiodbudgeting.data.BudgetItem;
import com.jegsoftware.payperiodbudgeting.data.IBudgetItemListData;
import com.jegsoftware.payperiodbudgeting.data.ItemType;
import com.jegsoftware.payperiodbudgeting.view.IListView;
/**
* Created by jonathon on 2/6/18.
*/
public class ListController {
private IBudgetItemListData budgetItemData;
private IListView view;
public ListController(IBudgetItemListData budgetItemData, IListView view, ItemType type) {
this.budgetItemData = budgetItemData;
this.view = view;
view.setupListActivity(budgetItemData.getItemsByType(type));
}
public void onListItemClick(BudgetItem plannedItem, View viewRoot) {
view.startItemEditActivity(plannedItem, viewRoot);
}
public void onAddItemClicked(View viewRoot) {
view.startItemEditActivity(null, viewRoot);
}
}
|
import org.junit.Test;
import static org.junit.Assert.*;
public class StationeryTest {
@Test(expected = NullPointerException.class)
public void createStationeryNull1() {
Stationery stationery = Stationery.createStationery(null, 10.5);
}
@Test(expected = NullPointerException.class)
public void createStationeryNull2() {
Stationery stationery = Stationery.createStationery("Pen", -10.5);
}
@Test
public void createStationeryTest() {
assertNotNull(Stationery.createStationery("Pen", 10.5));
}
}
|
package com.packers.movers.commons.config.utils;
import com.packers.movers.commons.utils.Sequence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.constretto.model.Resource;
import java.util.HashMap;
import java.util.Map;
public class ConfigurationUtils {
private static final Logger LOG = LoggerFactory.getLogger(ConfigurationUtils.class);
public static Map<String, String> readEnvironmentVariables() {
return System.getenv();
}
public static Map<String, String> readPropertiesFile(String path) {
return PropertyFileReader.readConfiguration(Resource.create(path));
}
public static Map<String, String> readPropertiesFiles(String... paths) {
return PropertyFileReader.readConfiguration(Sequence.of(paths).map(Resource::create));
}
@SafeVarargs
public static Map<String, String> combineProperties(Map<String, String>... properties) {
HashMap<String, String> combinedProperties = new HashMap<>();
for (Map<String, String> props : properties) {
combinedProperties.putAll(props);
}
return combinedProperties;
}
public static <T> T mapProperties(Class<T> configurationClass, Map<String, String> properties) {
ConfigurationMapper mapper = new ConfigurationMapper(properties);
return mapper.mapProperties(configurationClass);
}
public static <T> T mapProperties(Class<T> configurationClass, Map<String, String>... properties) {
Map<String, String> combinedProperties = combineProperties(properties);
return mapProperties(configurationClass, combinedProperties);
}
public static Map<String, String> readProperties(String... paths) {
return readPropertiesFiles(paths);
}
}
|
package com.todoapp.repository;
import com.todoapp.entity.Invitationstatus;
import com.todoapp.entity.Priority;
import java.util.List;
public interface InvitationstatusRepository {
List<Invitationstatus> findBydescription(String description);
Invitationstatus save(Invitationstatus var1);
Invitationstatus findById(int var1);
void delete(Invitationstatus var1);
List<Invitationstatus> findAll();
}
|
package com.example.kira03.mouse3;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class MainActivity extends AppCompatActivity implements View.OnClickListener ,View.OnLongClickListener {
String de="debug";
Button left,right;
Socket s;
OutputStream o;
DataOutputStream dos;
int i=0,j=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textView = (TextView) findViewById(R.id.textView);
// this is the view on which you will listen for touch events
final View touchView = findViewById(R.id.touchView);
new Thread() {
@Override
public void run() {
try
{
Log.i(de, "attempting to connect");
s = new Socket("192.168.1.194", 5000);
Log.i(de, "connected");
o = s.getOutputStream();
dos = new DataOutputStream(o);
} catch (
Exception e
)
{
Log.e(de, e.getMessage());
}
}
}.start();
touchView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
try {
textView.setText(String.valueOf((int) event.getX()) + " " + String.valueOf((int) event.getY()));
String a;
a = (String) textView.getText();
dos.writeUTF(a);
} catch (IOException e) {
Log.e(de, e.getMessage());
}
return true;
}
});
left=(Button)findViewById(R.id.left);
right=(Button)findViewById(R.id.right);
left.setOnClickListener( this);
right.setOnClickListener( this);
left.setOnLongClickListener( this);
right.setOnLongClickListener(this);
}
public void onClick(View view)
{
Button b = (Button)view;
String s = b.getText().toString();
if(s.equals("left click"))
{
try
{
dos.writeUTF("l");
} catch (IOException e)
{
e.printStackTrace();
}
}
else
{
try
{
dos.writeUTF("r");
}catch (Exception e){}
}
}
public boolean onLongClick(View view)
{
Button b = (Button)view;
String s = b.getText().toString();
if(s.equals("left click"))
{
i=(i+1)%2;
try
{
if(i==1)
dos.writeUTF("l1");
else
dos.writeUTF("l2");
} catch (IOException e)
{
e.printStackTrace();
}
}
else if(s.equals("right click"))
{
j=(j+1)%2;
try
{ if(j==1)
dos.writeUTF("r1");
else
dos.writeUTF("r2");
} catch (IOException e)
{
e.printStackTrace();
}
}
return true;
}
}
|
package com.mahendra.library.services;
import java.util.List;
import com.mahendra.library.models.Book;
public interface BookService {
Book create(Book b);
Book findById(Integer id);
List<Book> findByAuthor(String author);
List<Book> findByCategory(String category);
List<Book> findByTitle(String title);
List<Book> findAvailableByTitle(String title);
List<Book> findAvailableByAuthor(String author);
List<Book> findAvailableByCategory(String category);
}
|
package zhku.mvc.annotation;
import java.lang.annotation.*;
/**
* Created by ipc on 2017/8/26.
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
String value() default "";
}
|
package org.alienideology.jcord.internal.object.client.relation;
import org.alienideology.jcord.handle.client.relation.IIncomingFriendRequest;
import org.alienideology.jcord.internal.object.client.ClientObject;
/**
* @author AlienIdeology
*/
public class IncomingFriendRequest extends ClientObject implements IIncomingFriendRequest {
private Relationship relationship;
public IncomingFriendRequest(Relationship relationship) {
super(relationship.getClient());
this.relationship = relationship;
}
@Override
public Relationship getRelationship() {
return relationship;
}
}
|
package com.tencent.mm.plugin.exdevice.ui;
public interface c {
void aIa();
void aIb();
}
|
package com.shawn.nichol.bakingapp.Fragments;
import android.arch.lifecycle.ViewModelProviders;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
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 com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import com.shawn.nichol.bakingapp.Data.InstructionsExtractSteps;
import com.shawn.nichol.bakingapp.R;
import java.util.Objects;
public class StepsFragment extends Fragment {
private static final String LogTag = "MyLog " + StepsFragment.class.getSimpleName();
private PlayerView mExoPlayerView;
private SimpleExoPlayer mExoPlayer;
private boolean mPlayWhenReady = true;
private static final String EXTRA_EXO_PLAYER_POSITION = "extraExoPlayerPosition";
private long position;
private String mURI;
// Requires an empty constructor
public StepsFragment() {
}
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null) {
position = savedInstanceState.getLong(EXTRA_EXO_PLAYER_POSITION);
} else {
position = 0;
}
View rootView = inflater.inflate(R.layout.fragment_step, container, false);
mExoPlayerView = rootView.findViewById(R.id.exo_player_view);
TextView stepsTv = rootView.findViewById(R.id.fragment_steps_tv);
// Access ViewModel, for the steps index position
SharedViewModel model = ViewModelProviders.of(Objects.requireNonNull(getActivity())).get(SharedViewModel.class);
int position = model.getStepPosition();
mURI = InstructionsExtractSteps.stepsVideoList.get(position);
String description = InstructionsExtractSteps.stepsDescriptionList.get(position);
Log.d(LogTag, "Index " + position);
Log.d(LogTag, description);
Log.d(LogTag, "URI " + mURI);
stepsTv.setText(description);
return rootView;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(EXTRA_EXO_PLAYER_POSITION, position);
}
@Override
public void onStart() {
super.onStart();
if (Util.SDK_INT > 23) {
if (!TextUtils.isEmpty(mURI)) {
initializePlayer(Uri.parse(mURI));
if(mExoPlayerView != null) {
mExoPlayer.seekTo(position);
}
} else {
mExoPlayerView.setVisibility(View.GONE);
}
}
}
@Override
public void onResume() {
super.onResume();
if (Util.SDK_INT < 23) {
if (!TextUtils.isEmpty(mURI)) {
initializePlayer(Uri.parse(mURI));
if(mExoPlayerView != null) {
mExoPlayer.seekTo(position);
}
} else {
mExoPlayerView.setVisibility(View.GONE);
}
}
}
@Override
public void onPause() {
super.onPause();
if(Util.SDK_INT <= 23 || mExoPlayer == null) {
if(mExoPlayerView != null) {
position = mExoPlayer.getCurrentPosition();
}
releasePlayer();
}
}
@Override
public void onStop() {
super.onStop();
if(Util.SDK_INT > 23) {
if(mExoPlayerView != null) {
position = mExoPlayer.getCurrentPosition();
}
releasePlayer();
}
}
private void initializePlayer(Uri mediaUri) {
Log.d(LogTag, "initializePlayer mediaUri: " + mediaUri);
if(mExoPlayer == null) {
DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
@SuppressWarnings("deprecation") TrackSelection.Factory videoTrackSelection = new AdaptiveTrackSelection.Factory(bandwidthMeter);
TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelection);
// Create player
mExoPlayer = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector);
// Bind player to view
mExoPlayerView.setPlayer(mExoPlayer);
// Measure BandWidth during playback.
// Produces DataSource instance through which media data is loaded
DataSource.Factory dataSource = new DefaultDataSourceFactory(Objects.requireNonNull(getContext()), Util.getUserAgent(getContext(), "Baking"));
// MediaSource being played
MediaSource videoSource = new ExtractorMediaSource.Factory(dataSource).createMediaSource(mediaUri);
// Prepare player
mExoPlayer.prepare(videoSource);
mExoPlayer.setPlayWhenReady(mPlayWhenReady);
mExoPlayer.seekTo(position);
mExoPlayerView.setVisibility(View.VISIBLE);
}
}
private void releasePlayer() {
if(mExoPlayer!= null) {
mExoPlayer.stop();
mExoPlayer.release();
mExoPlayer = null;
}
}
}
|
package com.tencent.mm.plugin.collect.b;
public final class a {
public String desc;
public int fee;
public String hTH;
public String hTI;
public long timestamp;
}
|
package com.jlxy.bllld.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HttpServletBean;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by ORCHID on 2017/3/12.
*/
@Controller
@RequestMapping("/Main")
public class MainController {
@RequestMapping(value = "/Controller")
public ModelAndView loginin() {
Logger logger = LoggerFactory.getLogger(MainController.class);
logger.info("info-redirect to login!");
ModelAndView modelAndView = new ModelAndView("/jsp/login_reg");
return modelAndView;
}
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,Object handler) throws Exception{
return true;
}
}
|
//정수를 입력받아 짝수의 합과 홀수의 합
import java.util.*;
class while1_Test {
public static void main(String ar[]){
Scanner sc = new Scanner(System.in);
System.out.println("정수 n 입력 : ");
int n = sc.nextInt();
int i = 0;
int sum1 = 0;
int sum2 = 0;
while(i<=n){
if(i%2==0){
sum1 = sum1 + i;
}
else{
sum2 = sum2 + i;
}
i++;
}
System.out.println("1부터 n까지 짝수의 합 : " + sum1);
System.out.println("1부터 n까지 홀수의 합 : " + sum2);
}
}
|
package com.company.Entities;
/**
* Created by semen on 07.10.2015.
*/
public abstract class Device {
private int number;
private boolean status = false;
public abstract String getName();
public String toString(){
return getName();
}
public Device(int number, boolean status) {
this.number = number;
this.status = status;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public boolean isOn() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
|
package real;
import org.junit.Test;
import org.openqa.selenium.By;
import util.BaseTest;
public class TestGmail1 extends BaseTest{
@Test
public void testGmailSuccees() throws InterruptedException{
driver.get("http://gmail.com");
driver.findElement(
By.xpath("//input[@aria-label='Email or phone']"))
.sendKeys("mythritechs"
+ "olutions@gmail.com");
Thread.sleep(3000);
driver.findElement(
By.xpath("//span[text()='Next']"))
.click();
Thread.sleep(3000);
driver.findElement(
By.xpath("//input[@type='password']"))
.sendKeys("mythritechsolutions@gmail.com");
Thread.sleep(3000);
driver.findElement(
By.xpath("//span[text()='Next']"))
.click();
Thread.sleep(3000);
}
}
|
package com.baldurtech;
import java.util.List;
import java.util.ArrayList;
import java.sql.SQLException;
import java.sql.ResultSet;
public class ContactService
{
public List<Contact> getAllContacts()
{
return findAllContactsBySql("select * from contact");
}
public List<Contact> findAllContactsBySql(String sql)
{
List<Contact> contacts = new ArrayList<Contact>();
DatabaseManager db = createDatabaseConnectionAndExecute(sql);
try
{
while(db.rs.next())
{
contacts.add(createContactFromResultSet(db.rs));
}
}
catch(SQLException sqle)
{
sqle.printStackTrace();
}
closeDatabaseManager(db);
return contacts;
}
public Contact getContactById(Long id)
{
return findFirstContactBySql("select * from contact where id = " + id);
}
public Contact findFirstContactBySql(String sql)
{
List<Contact> contacts = findAllContactsBySql(sql);
if(contacts.size() > 0)
{
return contacts.get(0);
}
else
{
return null;
}
}
public Contact createContactFromResultSet(ResultSet rs) throws SQLException
{
Contact contact = new Contact();
contact.setId(rs.getLong("id"));
contact.setName(rs.getString("name"));
contact.setMobile(rs.getString("mobile"));
contact.setVpmn(rs.getString("vpmn"));
contact.setEmail(rs.getString("email"));
contact.setHomeAddress(rs.getString("home_address"));
contact.setOfficeAddress(rs.getString("office_address"));
contact.setMemo(rs.getString("memo"));
contact.setJob(rs.getString("job"));
contact.setJobLevel(rs.getInt("job_level"));
return contact;
}
public DatabaseManager createDatabaseConnectionAndExecute(String sql)
{
DatabaseManager db = new DatabaseManager();
db.execute(sql);
return db;
}
public void closeDatabaseManager(DatabaseManager db)
{
db.close();
}
}
|
/*
* 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 view.secretary;
import dao.PatientFolderDao;
import dao.RoleDao;
import extrapackages.AgeCalculator;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JDesktopPane;
import javax.swing.table.DefaultTableModel;
import model.AgeModel;
import model.PatientFolderModel;
/**
*
* @author bynan
*/
public class ListPatientsFolder extends javax.swing.JInternalFrame {
public static DefaultComboBoxModel modelNumbersToShow = new DefaultComboBoxModel();
public DefaultTableModel tableForListPatientFolder;
public static String value = "";
public static Object limit = null;
public static int index = 0;
public static String idPassToAppointment = "";
/**
* Creates new form ListPatientsFolder
*/
public ListPatientsFolder() throws SQLException {
initComponents();
patientFolderList("", "");
initFiltersComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
searchValueTextField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
numbersToShowComboBox = new javax.swing.JComboBox<>();
numberOfResultsLabel = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
takeRdvButton = new javax.swing.JButton();
jPanel2 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
firstNameLabel = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
lastNameLabel = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
ageLabel = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
genderLabel = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
adressLabel = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
listPatientTable = new javax.swing.JTable();
jLabel18 = new javax.swing.JLabel();
setClosable(true);
setIconifiable(true);
setTitle("Liste des dossiers patients");
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
searchValueTextField.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
searchValueTextFieldKeyReleased(evt);
}
});
jLabel3.setText("Afficher");
numbersToShowComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
numbersToShowComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
numbersToShowComboBoxActionPerformed(evt);
}
});
numberOfResultsLabel.setText("sur (100)");
jLabel7.setText("Rechercher");
jButton1.setForeground(new java.awt.Color(255, 4, 4));
jButton1.setText("Supprimer un dossier");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setForeground(new java.awt.Color(124, 91, 0));
jButton2.setText("Modifier un dossier");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setForeground(new java.awt.Color(8, 34, 124));
jButton3.setText("Actualiser");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setForeground(new java.awt.Color(16, 117, 52));
jButton4.setText("Créer un nouveau patient");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
takeRdvButton.setText("Prendre R.D.V.");
takeRdvButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
takeRdvButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(searchValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 333, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(numbersToShowComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(numberOfResultsLabel))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(takeRdvButton, javax.swing.GroupLayout.DEFAULT_SIZE, 155, Short.MAX_VALUE))))
.addContainerGap(18, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(searchValueTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(numbersToShowComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(numberOfResultsLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
.addComponent(jButton4)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton3)
.addComponent(jButton1))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(takeRdvButton))
.addContainerGap())
);
jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jLabel8.setText("Nom :");
firstNameLabel.setText("jLabel9");
jLabel10.setText("Prénom :");
lastNameLabel.setText("jLabel11");
jLabel12.setText("Age :");
ageLabel.setText("jLabel13");
jLabel14.setText("Genre :");
genderLabel.setText("jLabel15");
jLabel16.setText("Adresse :");
adressLabel.setText("jLabel17");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel16)
.addGap(18, 18, 18)
.addComponent(adressLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel8)
.addComponent(jLabel10)
.addComponent(jLabel12)
.addComponent(jLabel14))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 17, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(firstNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lastNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(ageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(genderLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(17, 17, 17))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addContainerGap(34, Short.MAX_VALUE)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel8)
.addComponent(firstNameLabel))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel10)
.addComponent(lastNameLabel))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(ageLabel))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel14)
.addComponent(genderLabel))
.addGap(18, 18, 18)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(adressLabel))
.addGap(26, 26, 26))
);
jLabel1.setText("Opérations sur la liste");
jLabel2.setText("Détail");
jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
listPatientTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
listPatientTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
listPatientTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(listPatientTable);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE)
.addContainerGap())
);
jLabel18.setText("La liste des dossiers patients sont représentés ci-dessous");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(12, 12, 12)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(243, 243, 243)))
.addComponent(jLabel2)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel18)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel18))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(45, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jButton1ActionPerformed
private void listPatientTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listPatientTableMouseClicked
index = listPatientTable.getSelectedRow();
try {
showPatientSelected(index);
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_listPatientTableMouseClicked
private void searchValueTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_searchValueTextFieldKeyReleased
value = searchValueTextField.getText();
try {
patientFolderList(value, "");
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_searchValueTextFieldKeyReleased
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
newPatientFolder();
}//GEN-LAST:event_jButton4ActionPerformed
private void numbersToShowComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_numbersToShowComboBoxActionPerformed
limit = numbersToShowComboBox.getSelectedItem();
try {
if (limit != null) {
patientFolderList("", limit.toString());
}else{
patientFolderList("", "");
}
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_numbersToShowComboBoxActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
try {
refreshAll();
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try {
updatePatientFolder();
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void takeRdvButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_takeRdvButtonActionPerformed
try {
takeAppointment();
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_takeRdvButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JLabel adressLabel;
public javax.swing.JLabel ageLabel;
public javax.swing.JLabel firstNameLabel;
public javax.swing.JLabel genderLabel;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JLabel lastNameLabel;
public javax.swing.JTable listPatientTable;
private javax.swing.JLabel numberOfResultsLabel;
private javax.swing.JComboBox<String> numbersToShowComboBox;
public javax.swing.JTextField searchValueTextField;
public javax.swing.JButton takeRdvButton;
// End of variables declaration//GEN-END:variables
private void initFiltersComponents() throws SQLException {
PatientFolderDao dao = new PatientFolderDao();
int countPatients = dao.countPatients();
this.numberOfResultsLabel.setText("sur (" + countPatients + ")");
if (countPatients >= 1) {
int[] liste = {10, 20, 30, 50, 100, 200, 1000, countPatients};
modelNumbersToShow.removeAllElements();
for (Object o : liste) {
modelNumbersToShow.addElement(o);
}
this.numbersToShowComboBox.setModel(modelNumbersToShow);
} else {
this.numbersToShowComboBox.setEnabled(false);
}
this.numbersToShowComboBox.setSelectedIndex(0);
lastInsertedPatient();
}
public void patientFolderList(String value ,String limit) throws SQLException {
value = "";
limit = "";
String[] columnNames = {
"#", "Nom", "Prénom"
};
tableForListPatientFolder = new DefaultTableModel(columnNames, 0);
tableForListPatientFolder.setColumnCount(3);
PatientFolderDao patientFolderDao = new PatientFolderDao();
List<PatientFolderModel> patientFolderModel = null;
if (value.equals("") && limit.equals("")) {
patientFolderModel = patientFolderDao.selectAllPatientFolder();
} else {
if (!value.equals("")) {
patientFolderModel = patientFolderDao.selectPatientBySearch(value);
} else if (!limit.equals("")) {
patientFolderModel = patientFolderDao.selectWithLimitAndFilter(limit);
}
}
for (PatientFolderModel p : patientFolderModel) {
int id = p.getId();
String first_name = p.getFirst_name();
String last_name = p.getLast_name();
tableForListPatientFolder.addRow(new Object[]{
id,
first_name,
last_name
//last_name.setIcon(javax.swing.ImageIcon(getClass().getResource("/icons/ic_alarm_on_black_18dp.png"),
});
}
listPatientTable.setModel(tableForListPatientFolder);
}
public void showPatientSelected(int index) throws SQLException {
if (listPatientTable.getRowCount() != 0) {
PatientFolderDao patient = new PatientFolderDao();
List<PatientFolderModel> patientFolderModel = null;
if (value.equals("")) {
patientFolderModel = patient.selectAllPatientFolder();
//System.err.println(listPatientTable.getRowCount());
} else {
patientFolderModel = patient.selectPatientBySearch(value);
//System.err.println(listPatientTable.getRowCount());
}
if (limit == null) {
//patientFolderModel = patient.selectAllPatientFolder();
//System.err.println(listPatientTable.getRowCount());
} else {
patientFolderModel = patient.selectWithLimitAndFilter(limit.toString());
//System.err.println(listPatientTable.getRowCount());
}
int idPassing = patientFolderModel.get(index).getId();
idPassToAppointment = Integer.toString(idPassing);
String first_name = patientFolderModel.get(index).getFirst_name();
String last_name = patientFolderModel.get(index).getLast_name();
String gender = patientFolderModel.get(index).getGender();
String age = patientFolderModel.get(index).getBirth_date();
String adress = patientFolderModel.get(index).getAdress();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date birthDate = null;
try {
birthDate = (Date) sdf.parse(age);
} catch (ParseException ex) {
Logger.getLogger(RoleDao.class.getName()).log(Level.SEVERE, null, ex);
}
AgeCalculator ageFoo = new AgeCalculator();
AgeModel ageExact = ageFoo.calculateAge(birthDate);
String ageExactString = ageExact.toString();
firstNameLabel.setText(first_name);
lastNameLabel.setText(last_name);
genderLabel.setText(gender);
ageLabel.setText(ageExactString);
adressLabel.setText(adress);
} else {
System.out.println("Tableau des liste de patients vide");
}
}
public void lastInsertedPatient() throws SQLException {
int index = listPatientTable.getRowCount() - listPatientTable.getRowCount();
try {
showPatientSelected(index);
listPatientTable.getSelectionModel().setSelectionInterval(index, index);
} catch (SQLException ex) {
Logger.getLogger(ListPatientsFolder.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void selectPatientUpdated() throws SQLException {
showPatientSelected(index);
listPatientTable.getSelectionModel().setSelectionInterval(index, index);
}
private void newPatientFolder() {
CreatePatientFolder create = new CreatePatientFolder();
JDesktopPane desktopPane = getDesktopPane();
desktopPane.add(create);
create.setVisible(true);
this.setVisible(false);
create.toFront();
}
private void updatePatientFolderWindow() throws SQLException {
CreatePatientFolder create = new CreatePatientFolder();
JDesktopPane desktopPane = getDesktopPane();
desktopPane.add(create);
create.setVisible(true);
this.setVisible(false);
create.setTitle("Modifier un dossier patient");
create.toFront();
create.titleLabel.setText("Formulaire de modification d'un dossier patient");
if (listPatientTable.getRowCount() != 0) {
PatientFolderDao patient = new PatientFolderDao();
List<PatientFolderModel> patientFolderModel = null;
if (value.equals("")) {
patientFolderModel = patient.selectAllPatientFolder();
//System.err.println(listPatientTable.getRowCount());
} else {
patientFolderModel = patient.selectPatientBySearch(value);
//System.err.println(listPatientTable.getRowCount());
}
if (limit == null) {
//patientFolderModel = patient.selectAllPatientFolder();
//System.err.println(listPatientTable.getRowCount());
} else {
patientFolderModel = patient.selectWithLimitAndFilter(limit.toString());
// System.err.println(listPatientTable.getRowCount());
}
String first_name = patientFolderModel.get(index).getFirst_name();
String last_name = patientFolderModel.get(index).getLast_name();
String gender = patientFolderModel.get(index).getGender();
String age = patientFolderModel.get(index).getBirth_date();
String adress = patientFolderModel.get(index).getAdress();
create.firstNameTextField.setText(first_name);
create.lastNameTextField.setText(last_name);
create.idPatientFolder = patientFolderModel.get(index).getId();
var res = age.split("\\/");
int day = Integer.parseInt(res[0]);
int month = Integer.parseInt(res[1]);
int year = Integer.parseInt(res[2]);
//generate year
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
for (int k = currentYear - 100; k <= currentYear; k++) {
if (year == k) {
create.yearComboBox.setSelectedIndex(100 - (currentYear - year));
}
}
create.dayComboBox.setSelectedIndex(day - 1);
create.monthComboBox.setSelectedIndex(month - 1);
//create.dayComboBox.setSelectedIndex(index);
if (gender == "Féminin") {
create.femRadioButton.setSelected(true);
} else {
create.mascRadioButton.setSelected(true);
}
create.adressTextField.setText(adress);
create.saveButton.setText("Modifier");
} else {
System.out.println("Tableau vide");
}
}
private void refreshAll() throws SQLException {
this.searchValueTextField.setText("");
this.numbersToShowComboBox.setSelectedIndex(7);
patientFolderList("", "");
lastInsertedPatient();
}
private void updatePatientFolder() throws SQLException {
updatePatientFolderWindow();
}
private void takeAppointment() throws SQLException {
Appointment rdv = new Appointment();
JDesktopPane desktopPane = getDesktopPane();
desktopPane.add(rdv);
rdv.setVisible(true);
this.setVisible(false);
rdv.setBounds(0, 0, 580, 495);
rdv.searchPanel.setVisible(false);
PatientFolderDao patient = new PatientFolderDao();
List<PatientFolderModel> patientFolderModel = null;
if (value.equals("")) {
patientFolderModel = patient.selectAllPatientFolder();
//System.err.println(listPatientTable.getRowCount());
} else {
patientFolderModel = patient.selectPatientBySearch(value);
//System.err.println(listPatientTable.getRowCount());
}
if (limit == null) {
//patientFolderModel = patient.selectAllPatientFolder();
//System.err.println(listPatientTable.getRowCount());
} else {
patientFolderModel = patient.selectWithLimitAndFilter(limit.toString());
//System.err.println(listPatientTable.getRowCount());
}
// int idPassing = patientFolderModel.get(index).getId();
// idPassToAppointment = Integer.toString(idPassing);
String first_name = patientFolderModel.get(index).getFirst_name();
String last_name = patientFolderModel.get(index).getLast_name();
// rdv.idPassedThrougthListPatient = this.idPassToAppointment;
rdv.idPatientFromListpatietnFolderLabel.setText(idPassToAppointment);
rdv.showFullnameLabel.setText(first_name + " " + last_name);
rdv.infoLabel.setText("Cliquez sur réinitialiser pour faire une nouvelle entrée de dossier patient!");
rdv.toFront();
}
}
|
/*
* Copyright 2005-2010 the original author or authors.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sdloader.util;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Stack;
/**
* PathUtils
*
* @author c9katayama
*
*/
public class PathUtil {
/**
* パス中の//および./および../部分を取り除きます.
*/
public static String narrow(String path) {
path = replaceFileSeparator(path);
String[] paths = path.split("/");
Stack<String> narrowPathList = new Stack<String>();
for (int i = 0; i < paths.length; i++) {
if (paths[i].length() == 0 || paths[i].equals(".")) {
continue;
} else if (paths[i].equals("..")) {
if (narrowPathList.size() != 0) {
narrowPathList.pop();
}
} else {
narrowPathList.add(paths[i]);
}
}
boolean first = true;
String newPath = null;
for (String p : narrowPathList) {
if (first) {
newPath = path.startsWith("/") ? "/" : "";
first = false;
} else {
newPath += "/";
}
newPath += p;
}
if (path.endsWith("/")) {
newPath += "/";
}
return newPath;
}
/**
* ベースパスに対して相対パスを解決します。
*
* @param basePath
* @param path
* @return
*/
public static String computeRelativePath(String basePath, String path) {
basePath = basePath.substring(0, basePath.lastIndexOf("/"));
return jointPathWithSlash(basePath, path);
}
/**
* 2つのパスを"/"で連結します。
*/
public static String jointPathWithSlash(String path1, String path2) {
path1 = removeEndSlashIfNeed(path1);
path2 = removeStartSlashIfNeed(path2);
return path1 + "/" + path2;
}
public static String appendStartSlashIfNeed(final String path) {
if (path != null && !startsWithSlash(path)) {
return "/" + path;
}
return path;
}
public static String appendEndSlashIfNeed(final String path) {
if (path != null && !endsWithSlash(path)) {
return path + "/";
}
return path;
}
public static String removeStartSlashIfNeed(final String path) {
if (path != null && startsWithSlash(path)) {
return path.substring(1, path.length());
}
return path;
}
public static String removeEndSlashIfNeed(final String path) {
if (path != null && path.endsWith("/")) {
return path.substring(0, path.length() - 1);
}
return path;
}
public static boolean startsWithSlash(final String path) {
if (isEmpty(path)) {
return false;
}
return path.indexOf("/") == 0;
}
public static boolean endsWithSlash(final String path) {
if (isEmpty(path)) {
return false;
}
return path.lastIndexOf("/") == path.length() - 1;
}
private static boolean isEmpty(String value) {
return (value == null || value.trim().length() == 0);
}
/**
* パス中の\\を/に置き換えます。
*
* @param filepath
* @return
*/
public static final String replaceFileSeparator(String path) {
return path.replace('\\', '/');
}
public static final String getExtension(String path) {
if (path == null) {
return path;
}
int dot = path.lastIndexOf(".");
if (dot == -1) {
return null;
}
return path.substring(dot + 1, path.length());
}
/**
* 絶対パスかどうか
*
* @param path
* @return
*/
public static final boolean isAbsolutePath(String path) {
String testPath = replaceFileSeparator(path);
if (testPath.startsWith("/") || testPath.indexOf(":") != -1) {
return true;
} else {
return false;
}
}
public static URL file2URL(String filePath) {
return file2URL(new File(filePath));
}
public static URL file2URL(File file) {
try {
return file.toURI().toURL();
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static File url2File(String urlPath) {
try {
return new File(new URI(urlPath));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public static File url2File(URL url) {
try {
return new File(new URI(url.toExternalForm()));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
|
package files;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.StringTokenizer;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import javafx.collections.ObservableList;
import javafx.scene.control.TableColumn;
public class Csv {
public String filename;
public Csv(String filename) {
this.filename = filename;
}
//CSVReader reader=new CSVReader(
public <T> ArrayList<String> ReadFileToTable2 (ObservableList<TableColumn<T,?>> tableColumns) {
try {
FileInputStream fs = new FileInputStream(filename);
InputStreamReader reader = new InputStreamReader(fs, StandardCharsets.UTF_16LE);
int line = reader.read();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// new InputStreamReader(new FileInputStream("d:\\a.csv"), "UTF-8"),
// ',', '\'', 1);
// String[] line;
// while ((line = reader.readNext()) != null) {
// StringBuilder stb = new StringBuilder(400);
// for (int i = 0; i < line.length; i++) {
// stb.append(line[i]);
// stb.append(";");
// }
// System.out.println(stb);
// }
//
/*
* This function only returns the data.
*/
public <T> ArrayList<String> ReadFileToTable (ObservableList<TableColumn<T,?>> tableColumns) {
try {
BufferedReader br = new BufferedReader( new FileReader(filename));
String strLine = null;
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
ArrayList<String> res = new ArrayList<String>();
//the first line are the column headers, best verified to match tableColumn
strLine = br.readLine();
List<String> columns = new ArrayList<String>(Arrays.asList(strLine.split("\t")));
while((strLine = br.readLine()) != null) {
lineNumber++;
String tString = "";
List<String> result = new ArrayList<String>(Arrays.asList(strLine.split("\t")));
if (result.size() == tableColumns.size()) {
for (int x=0; x<columns.size(); x++) {
tString += tableColumns.get(x).getText() + ":" + result.get(x) + ";";
}
}
res.add(tString);
}
return res;
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
|
package com.tencent.mm.splash;
import android.app.Activity;
public interface c {
void a(Throwable th, String str);
void b(String str, String str2, Object... objArr);
void e(Activity activity);
}
|
package rent.common.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import rent.common.entity.ServiceTypeEntity;
import rent.common.projection.ServiceTypeBasic;
import java.util.List;
@RepositoryRestResource(
collectionResourceRel = "service-types",
path = "service-type",
itemResourceRel = "service-type",
excerptProjection = ServiceTypeBasic.class)
public interface ServiceTypeRepository extends PagingAndSortingRepository<ServiceTypeEntity, String> {
List<ServiceTypeEntity> findByNameContainingOrderByName(@Param("name") String name);
}
|
package br.unifor.realmtest;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import io.realm.Realm;
public class MainActivity extends AppCompatActivity{
private Realm realm;
private EditText editTextName;
private EditText editTextAge;
private Button buttonPersistData;
private long id = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextNameId);
editTextAge = (EditText) findViewById(R.id.editTextAgeId);
buttonPersistData = (Button) findViewById(R.id.buttonPersistDataId);
Realm.init(this);
realm = Realm.getDefaultInstance();
buttonPersistData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(editTextName.length() != 0 && editTextAge.length() != 0){
//persistDataModeOne();
persistDataModeTwo();
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
else{
Toast.makeText(MainActivity.this, "Invalid Data", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
public void persistDataModeOne(){
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Person person = realm.createObject(Person.class);
person.setId(id++);
person.setName(editTextName.getText().toString());
person.setAge(Integer.parseInt(editTextAge.getText().toString()));
}
});
}
public void persistDataModeTwo(){
Person person = new Person(id, editTextName.getText().toString(), Integer.parseInt(editTextAge.getText().toString()));
realm.beginTransaction();
realm.insert(person);
realm.commitTransaction();
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.live;
import com.tencent.mm.plugin.appbrand.jsapi.live.AppBrandLivePlayerView.a;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.page.y;
class b$5 implements a {
final /* synthetic */ p fJO;
final /* synthetic */ int fKG;
final /* synthetic */ b fRI;
final /* synthetic */ y fRL;
b$5(b bVar, p pVar, int i, y yVar) {
this.fRI = bVar;
this.fJO = pVar;
this.fKG = i;
this.fRL = yVar;
}
public final void kM(int i) {
this.fJO.agU().a(this.fKG, this.fRL, i);
}
public final void ajc() {
this.fJO.agU().lA(this.fKG);
}
public final boolean isFullScreen() {
return this.fJO.agU().lz(this.fKG);
}
}
|
/**********************************************************************************************************
* Author: <<author name redacted >>
* Purpose: To create a Java class TableSorter which has a instance method named sortable that
* sorts a Table by row and column in ascending order.
* It also has a instance method named isSorted which returns true if all rows and columns are sorted.
* Modifications: Added the functionality to return the number of operations required to sort the table.
*
*/
package cs5387;
public class TableSorter {
public static int operationCounter =0;
public static void main(String[] args) throws Exception {
Table tableInit = Table.GetTable("tableFile.txt");
sortable(tableInit);
System.out.println("Number of operations: " + operationCounter);
System.out.println(isSorted(tableInit));
}
public static void sortable (Table tableInit){
rowSorter(tableInit);
colSorter(tableInit);
}
public static boolean isSorted(Table tableInit){
/* Staring at position row = 1, and col = 1 is necessary to avoid out of bounds exception when
checking if the next item is bigger.
Instead we check that the item before is smaller.
*/
for(int row = 1 ; row <tableInit.getSize() ; row++) {
for (int col = 1; col < tableInit.getSize(); col++) {
/* Returning false as soon as we identify that the Table is not sorted
for either row or column saves us having to use another nested loop to check
them separately.
*/
if(tableInit.getTableValue(row-1,col)<tableInit.getTableValue(row-1,col-1)){
return false;
}
if(tableInit.getTableValue(row,col-1)<tableInit.getTableValue(row-1,col-1)){
return false;
}
}
}
return true;
}
/* In order to make it more readable I abstracted the sorting by row into this method
In this method I used bubble sort, since we were limited to only I/O library
this was an alternative way to sort the Table in an efficient way.
*/
public static void rowSorter(Table tableInit){
operationCounter++;
for(int row = 0 ; row <tableInit.getSize() ; row++) {
operationCounter = operationCounter + 3;
for (int col = 0; col < tableInit.getSize(); col++) {
operationCounter = operationCounter + 3;
for(int k = 0; k < tableInit.getSize()-col-1;k++){
operationCounter = operationCounter + 3;
if(tableInit.getTableValue(row,k) > tableInit.getTableValue(row,k+1)){
operationCounter = operationCounter + 3;
int temp = tableInit.getTableValue(row,k);
operationCounter = operationCounter + 2;
tableInit.setTableValue(row,k,tableInit.getTableValue(row,k+1));
operationCounter = operationCounter + 2;
tableInit.setTableValue(row,k+1,temp);
operationCounter++;
}
}
}
}
operationCounter = operationCounter + 3;
}
/* In order to make it more readable I abstracted the sorting by column into this method
In this method I used bubble sort, since we were limited to only I/O library
this was an alternative way to sort the Table in an efficient way.
*/
public static void colSorter(Table tableInit){
for(int col = 0 ; col <tableInit.getSize() ; col++) {
operationCounter+=3;
for (int row = 0; row < tableInit.getSize(); row++) {
operationCounter+=3;
for(int k = 0; k < tableInit.getSize()-row-1;k++){
operationCounter+=3;
if(tableInit.getTableValue(k,col) > tableInit.getTableValue(k+1,col)){
operationCounter+=3;
int temp = tableInit.getTableValue(k,col);
operationCounter+=2;
tableInit.setTableValue(k,col,tableInit.getTableValue(k+1,col));
operationCounter+=3;
tableInit.setTableValue(k+1,col,temp);
operationCounter++;
}
}
}
}
operationCounter+=3;
}
/*For testing purposes only*/
public static void printTable(Table tableInit){
for(int row = 0 ; row <tableInit.getSize() ; row++) {
for (int col = 0; col < tableInit.getSize(); col++) {
System.out.print(tableInit.getTableValue(row, col));
}
System.out.println();
}
}
}
|
package com.github.w4o.sa.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author frank
* @date 2019-05-14
*/
@Data
@AllArgsConstructor
public class LoginResult {
private String token;
}
|
package com.example.jinliyu.shoppingapp_1.activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.jinliyu.shoppingapp_1.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
Button signupbtn, loginbtn;
ActionBar actionBar;
EditText mobileTxt, pwTxt;
TextView forgotpw;
String mobile, password;
SharedPreferences sharedPreferences;
CheckBox checkBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
//if checkbox ischecked, show saved mobile and password
String ischecked = sharedPreferences.getString("isChecked","");
if(ischecked.equals("true"))
{
String savedpw = sharedPreferences.getString("pw","");
pwTxt.setText(savedpw);
String savedmobile = sharedPreferences.getString("mobile","");
mobileTxt.setText(savedmobile);
}
signupbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SignUpActivity.class);
startActivity(intent);
}
});
loginbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("test","click!!!!!!!!");
mobile = mobileTxt.getText().toString();
password = pwTxt.getText().toString();
//do StringRequest to Login
login(mobile, password);
}
});
forgotpw.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, ForgetPWActivity.class);
startActivity(i);
}
});
}
private void initViews() {
mobileTxt = findViewById(R.id.mobileTxtLogin);
pwTxt = findViewById(R.id.passwordTxtLogin);
sharedPreferences = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
checkBox = findViewById(R.id.checkBox);
checkBox.setChecked(true);
actionBar = getSupportActionBar();
actionBar.setTitle(R.string.signin);
signupbtn = findViewById(R.id.btnsignup);
loginbtn = findViewById(R.id.btnlogin);
forgotpw = findViewById(R.id.forgotpw);
}
private void login(String mobile, final String password)
{
JsonArrayRequest req = new JsonArrayRequest("http://rjtmobile.com/aamir/e-commerce/android-app/shop_login.php?mobile="+mobile+"&password="+password, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
Log.i("test", response.toString());
JSONObject user = (JSONObject) response.get(0);
String userfirstname = user.getString("firstname");
String userlastname = user.getString("lastname");
String useremail = user.getString("email");
String usermobile = user.getString("mobile");
String userid = user.getString("id");
String userkey = user.getString("appapikey ");
sharedPreferences.edit().putString("firstname", userfirstname).commit();
sharedPreferences.edit().putString("lastname", userlastname).commit();
sharedPreferences.edit().putString("email", useremail).commit();
sharedPreferences.edit().putString("mobile", usermobile).commit();
sharedPreferences.edit().putString("userid", userid).commit();
sharedPreferences.edit().putString("apikey", userkey).commit();
sharedPreferences.edit().putString("pw", password).commit();
if(checkBox.isChecked())
{
sharedPreferences.edit().putString("isChecked", "true").commit();
}
else
{
sharedPreferences.edit().putString("isChecked", "false").commit();
}
Intent loginsuccess = new Intent(MainActivity.this, HomeActivity.class);
startActivity(loginsuccess);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"Password or username wrong",
Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
requestQueue.add(req);
}
}
|
package com.cmsz.demon.index.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
/*import com.cmsz.demon.index.dao.QueryLagouUser;
*//*import com.cmsz.demon.index.service.LagouUserService;*/
import javax.annotation.Resource;
@Controller
public class TradeDataController {
/* @Resource
private LagouUserService service;*/
/* @Resource
private QueryLagouUser queryLagouuser;
*/
@RequestMapping(value="/index")
public String index(Model model) throws Exception{
String message="world";
model.addAttribute("output",message);
return "index";
}
/* @RequestMapping(value="/getname",method=RequestMethod.GET)
public String getName(@RequestParam("input") String input,Model model) throws Exception{
String name="";
String name=service.query().get(0).getName();
String name=queryLagouuser.queryLagouUser().get(1).getName();
if(input==null){
model.addAttribute("output",name);
}else{
model.addAttribute("output",name);
}
return "getname";
}*/
}
|
package com.example.tiamo.gym;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import org.angmarch.views.NiceSpinner;
import java.util.ArrayList;
import java.util.List;
import jp.wasabeef.glide.transformations.BlurTransformation;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
public class RegisterActivity extends AppCompatActivity {
private Button registerButton;
public void changePicture(int i){
if(i==1){
ImageView mExpert = (ImageView) findViewById(R.id.expert);
ImageView mFreshman = (ImageView) findViewById(R.id.freshman);
RequestOptions options = new RequestOptions()
.circleCrop();
Glide.with(this).load(R.drawable.test3)
.apply(options)
.into(mExpert);
RequestOptions optionss = new RequestOptions()
.circleCrop();
Glide.with(this).load(R.drawable.test1)
.apply(optionss)
.into(mFreshman);
}
else{
ImageView mExpert = (ImageView) findViewById(R.id.expert);
ImageView mFreshman = (ImageView) findViewById(R.id.freshman);
RequestOptions options = new RequestOptions()
.circleCrop();
Glide.with(this).load(R.drawable.test4)
.apply(options)
.into(mExpert);
RequestOptions optionss = new RequestOptions()
.circleCrop();
Glide.with(this).load(R.drawable.test2)
.apply(optionss)
.into(mFreshman);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
NiceSpinner niceSpinner = (NiceSpinner)findViewById(R.id.nice_spinner);
List<String> dataList = new ArrayList<>();
dataList.add("学生");
dataList.add("教练");
dataList.add("上班族");
dataList.add("老师");
niceSpinner.attachDataSource(dataList);
niceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
ImageView mExpert = (ImageView) findViewById(R.id.expert);
ImageView mFreshman = (ImageView) findViewById(R.id.freshman);
RequestOptions options = new RequestOptions()
.circleCrop();
Glide.with(this).load(R.drawable.test4)
.apply(options)
.into(mExpert);
RequestOptions optionss = new RequestOptions()
.circleCrop();
Glide.with(this).load(R.drawable.test1)
.apply(optionss)
.into(mFreshman);
mExpert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changePicture(1);
}
});
mFreshman.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
changePicture(2);
}
});
registerButton = (Button) findViewById(R.id.btn_entered);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this,FitnessActivity.class);
startActivity(i);
}
});
}
}
|
package BikeRental;
import javax.persistence.*;
import org.springframework.beans.BeanUtils;
import java.util.List;
@Entity
@Table(name="Helm_table")
public class Helm {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String status;
@PostPersist
public void onPostPersist(){
System.out.println("###onPostPersist###");
HelmRegistered helmRegistered = new HelmRegistered();
BeanUtils.copyProperties(this, helmRegistered);
helmRegistered.publishAfterCommit();
}
@PreUpdate
public void onPreUpdate(){
System.out.println("###onPreUpdate###");
HelmUpdated helmUpdated = new HelmUpdated();
BeanUtils.copyProperties(this, helmUpdated);
helmUpdated.publishAfterCommit();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package couch;
//ToDO: Code an dosex@zedat.fu-berlin.de
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MapReduceOutput;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
public class MongoDB implements DBPlugin {
MongoClient mongoClient;
DB db;
@Override
public boolean initialize(String host) {
try {
mongoClient = new MongoClient(host);
} catch (UnknownHostException e) {
System.err.println("Unable to connect to MongoDB...");
return false;
}
db = mongoClient.getDB("movies");
if (db == null) {
System.err.println("Unable to open database...");
mongoClient.close();
mongoClient = null;
return false;
}
return true;
}
@Override
public void shutdown() {
db = null;
mongoClient.close();
mongoClient = null;
}
@Override
public boolean needsAggregation() {
return true;
}
@Override
public int saveMovies(ArrayList<MLMovie> movies) {
DBCollection col = db.getCollection("movies");
for (MLMovie mov : movies) {
col.insert(toDBMovie(mov), WriteConcern.NORMAL);
}
return movies.size();
}
@Override
public int saveRatings(ArrayList<MLRating> ratings) {
DBCollection col = db.getCollection("ratings");
int i = 0;
for (MLRating rat : ratings) {
++i;
col.insert(toDBRating(rat), WriteConcern.NORMAL);
if (i % 100000 == 0)
System.err.println(i + " inserted (" + ((float) i) / ratings.size() + ")...");
}
return ratings.size();
}
@Override
public int saveUsers(ArrayList<MLUser> users) {
DBCollection col = db.getCollection("users");
for (MLUser usr : users) {
col.insert(toDBUser(usr), WriteConcern.NORMAL);
}
return users.size();
}
@Override
public void aggregate() {
DBCollection mcol = db.getCollection("movies");
DBCollection ucol = db.getCollection("users");
DBCollection rcol = db.getCollection("ratings");
mcol.ensureIndex("id");
ucol.ensureIndex("id");
rcol.ensureIndex("userid");
rcol.ensureIndex("movieid");
rcol.ensureIndex(new BasicDBObject("userid", 1).append("movieid", 1));
String map = "function(){emit(this.movieid,{rat:this.rating,num:1,users:[this.userid]})}";
String reduce = "function(k,v){var d={rat:0,num:0,users:[]};for(var i=0;i<v.length;i++){d.rat+=v[i].rat;d.num+=v[i].num;d.users=d.users.concat(v[i].users)}return d}";
String finalize = "function(k,v){return{rat:v.rat/v.num,num:v.num,users:v.users}}";
DBCollection mrcol = mapReduceFinalize(rcol, map, reduce, finalize, "movie_rating", null).getOutputCollection();
mrcol.ensureIndex("value.rat");
BasicDBObject buf;
DBCursor cur = mcol.find();
while (cur.hasNext()) {
buf = (BasicDBObject) cur.next();
mrcol.findAndModify(new BasicDBObject("_id", buf.getInt("id")), new BasicDBObject("$set", new BasicDBObject("title", buf.getString("title"))));
}
cur.close();
cur = ucol.find();
while (cur.hasNext()) {
buf = (BasicDBObject) cur.next();
mrcol.findAndModify(new BasicDBObject("values.users", new BasicDBObject("$elemMatch", buf.getInt("id"))).append("values.users", buf.getInt("id")), /*new BasicDBObject("$set", new BasicDBObject("users.$", buf))*/ new BasicDBObject("found", 1));
}
cur.close();
map = "function(){emit(this.userid,1)}";
reduce = "function(k,v){var r=0;for(var i=0;i<v.length;i++)r+=v[i];return r}";
rcol.mapReduce(map, reduce, "users_rating", null);
}
public MLUser getUserById(int id) {
DBCollection col = db.getCollection("users");
DBCursor cur = col.find(new BasicDBObject("id", id));
if (cur.count() == 0)
return null;
MLUser user = new MLUser();
user.setID((int) cur.curr().get("id"));
user.setGender((char) cur.curr().get("gender"));
user.setOccupation((int) cur.curr().get("occupation"));
user.setAge((int) cur.curr().get("age"));
user.setZipCode((String) cur.curr().get("zip"));
return user;
}
private BasicDBObject toDBUser(MLUser user) {
BasicDBObject dbo = new BasicDBObject();
dbo.append("id", user.getID())
.append("gender", user.getGender())
.append("age", user.getAge())
.append("occupation", user.getOccupation())
.append("zip", user.getZipCode());
return dbo;
}
private BasicDBObject toDBMovie(MLMovie movie) {
BasicDBObject dbo = new BasicDBObject();
dbo.append("id", movie.getID())
.append("title", movie.getTitle())
.append("genres", movie.getGenres());
return dbo;
}
private BasicDBObject toDBRating(MLRating rat) {
BasicDBObject dbo = new BasicDBObject();
dbo.append("userid", rat.getUserID())
.append("movieid", rat.getMovieID())
.append("rating", rat.getRating())
.append("timestamp", rat.getTimestamp());
return dbo;
}
@Override
public void clear() {
db.dropDatabase();
}
@Override//war float
public int getRatingOfMovieByUser(int movieId, int userId) {
DBCollection col = db.getCollection("ratings");
/*BasicDBList dbl = new BasicDBList();
dbl.put(0,new BasicDBObject("userid", userId));
dbl.put(1,new BasicDBObject("movieid", movieId));
//dbl.add(new BasicDBObject("userid", userId));
//dbl.add(new BasicDBObject("movieid", movieId));
BasicDBObject dbo = new BasicDBObject("$and", dbl);
BasicDBObject test = new BasicDBObject();
test.put("userId",userId);
System.out.println("DBO: " + dbo);
System.out.println();
System.out.println(col.findOne(test));
System.out.println(col.apply(o));
*/
BasicDBList list = new BasicDBList();
list.put(0, new BasicDBObject("userid", userId));
list.put(1, new BasicDBObject("movieid", movieId));
BasicDBObject dbo = new BasicDBObject("$and", list);
DBCursor cur = col.find(dbo);
if (!cur.hasNext())
return 0;
//war float
return (int) ((BasicDBObject) cur.next()).getDouble("rating");
}
@Override
public MLMovie getMovieByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Tupel<Integer, Float>> getAverageRatingId() {
ArrayList<Tupel<Integer, Float>> result = new ArrayList<>();
BasicDBObject buffer;
DBCollection col;
DBCursor cur;
col = db.getCollection("movie_rating");
cur = col.find().sort(new BasicDBObject("value.rat", -1));
while (cur.hasNext()) {
buffer = (BasicDBObject) cur.next();
result.add(new Tupel<Integer, Float>(buffer.getInt("_id"), (float) ((BasicDBObject) buffer.get("value")).getDouble("rat")));
}
cur.close();
return result;
}
@Override
public ArrayList<Tupel<Integer, Float>> getAverageRatingAbove10Id() {
ArrayList<Tupel<Integer, Float>> result = new ArrayList<>();
BasicDBObject buffer;
DBCollection col;
DBCursor cur;
col = db.getCollection("movie_rating");
cur = col.find(new BasicDBObject("value.num", new BasicDBObject("$gt", 10))).sort(new BasicDBObject("value.rat", -1));
while (cur.hasNext()) {
buffer = (BasicDBObject) cur.next();
result.add(new Tupel<Integer, Float>(buffer.getInt("_id"), (float) ((BasicDBObject) buffer.get("value")).getDouble("rat")));
}
cur.close();
return result;
}
@Override
public ArrayList<Tupel<String, Float>> getAverageRatingTitle() {
ArrayList<Tupel<String, Float>> result = new ArrayList<>();
BasicDBObject buffer;
DBCollection col;
DBCursor cur;
col = db.getCollection("movie_rating");
cur = col.find().sort(new BasicDBObject("value.rat", -1));
while (cur.hasNext()) {
buffer = (BasicDBObject) cur.next();
result.add(new Tupel<String, Float>(buffer.getString("title"), (float) ((BasicDBObject) buffer.get("value")).getDouble("rat")));
}
cur.close();
return result;
}
@Override
public ArrayList<Tupel<String, Float>> getAverageRatingAbove10Title() {
ArrayList<Tupel<String, Float>> result = new ArrayList<>();
BasicDBObject buffer;
DBCollection col;
DBCursor cur;
col = db.getCollection("movie_rating");
cur = col.find(new BasicDBObject("value.num", new BasicDBObject("$gt", 10))).sort(new BasicDBObject("value.rat", -1));
while (cur.hasNext()) {
buffer = (BasicDBObject) cur.next();
result.add(new Tupel<String, Float>(buffer.getString("title"), (float) ((BasicDBObject) buffer.get("value")).getDouble("rat")));
}
cur.close();
return result;
}
@Override
public ArrayList<Tripel<String, Float, Float>> getAverageRatingAgeTitle() {
ArrayList<Tripel<String, Float, Float>> result = new ArrayList<>();
MLUser ubuffer;
BasicDBObject dbuffer;
HashMap<Integer, MLUser> umap = new HashMap<>();
DBCollection col = db.getCollection("users");
DBCursor cur = col.find();
// read users
while (cur.hasNext()) {
ubuffer = new MLUser();
dbuffer = (BasicDBObject) cur.next();
ubuffer.setID(dbuffer.getInt("id"));
ubuffer.setGender(dbuffer.getString("gender").charAt(0));
ubuffer.setAge(dbuffer.getInt("age"));
ubuffer.setOccupation(dbuffer.getInt("occupation"));
ubuffer.setZipCode(dbuffer.getString("zip"));
umap.put(ubuffer.getID(), ubuffer);
}
cur.close();
int num, age;
// read ratings
col = db.getCollection("movie_rating");
cur = col.find().sort(new BasicDBObject("value.rating", -1));
while (cur.hasNext()) {
num = 0;
age = 0;
dbuffer = (BasicDBObject) cur.next();
for (Object dbo : ((BasicDBList) ((BasicDBObject) dbuffer.get("value")).get("users"))) {
++num;
// if (umap.get(dbo) != null)
age += umap.get(dbo).getAge();
}
result.add(new Tripel<String, Float, Float>(dbuffer.getString("title"), (float) ((BasicDBObject) dbuffer.get("value")).getDouble("rat"), (float) age / (float) num));
}
return result;
}
@Override
public ArrayList<Tupel<Integer, Integer>> getAllUsersSortByRatings() {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Tupel<Float, Integer>> getAverageRatingsByJob() {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Tripel<String, Integer, Float>> getAverageRatingsByJobPerMovie() {
// TODO Auto-generated method stub
return null;
}
@Override
public Tupel<String, Integer> getMaxMovieTags() {
// TODO Auto-generated method stub
return null;
}
@Override
public ArrayList<Tripel<String, String, Float>> getMaxMovieRatingByGenre() {
// TODO Auto-generated method stub
return null;
}
private MapReduceOutput mapReduceFinalize(DBCollection col, String map, String reduce, String finalize, String out_col, DBObject query) {
BasicDBObject mrf = new BasicDBObject();
mrf.append("mapreduce", col.getName())
.append("map", map)
.append("reduce", reduce)
.append("verbose", true)
.append("out", new BasicDBObject("replace", out_col))
.append("query", query)
.append("finalize", finalize);
return col.mapReduce(mrf);
}
}
|
package com.test01;
import java.awt.*;
@SuppressWarnings("serial")
public class MTest03 extends Frame {
Panel p1, p2, p3;
Label lbName, lbAddr, lbPhone;
TextField txtName, txtAddr, txtPhone, txtProfile;
Button btok, btcn;
TextArea taview;
public MTest03() { // 생성자
super("주소록");
p1 = new Panel();
p2 = new Panel();
p3 = new Panel();
lbName = new Label("Name");
lbAddr = new Label("Address");
lbPhone = new Label("Phone");
txtName = new TextField("", 30);
txtAddr = new TextField("", 30);
txtPhone = new TextField("", 30);
btok = new Button("Okay");
btcn = new Button("Cancel");
taview = new TextArea("", 5, 50);
}
public void go() {
p1.setLayout(new GridLayout(3, 2));
p1.add(lbName);
p1.add(txtName);
p1.add(lbAddr);
p1.add(txtAddr);
p1.add(lbPhone);
p1.add(txtPhone);
p2.add(btok);
p2.add(btcn);
p3.add(taview);
add(p1);
add(p2);
add(p3);
setFont(new Font("굴림", Font.BOLD, 20));
setLayout(new GridLayout(3, 1));
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args) {
new MTest03().go();
}
}
|
package com.projection.jpa.repositories;
import com.projection.jpa.entities.Author;
import com.projection.jpa.entities.Author_;
import com.projection.jpa.entities.Book;
import com.projection.jpa.entities.Book_;
import com.projection.jpa.entities.dto.BookWithAuthorNames;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import java.util.List;
@Repository
public class AuthorRepositoryImpl implements CustomAuthorRepository {
private EntityManager entityManager;
public AuthorRepositoryImpl() {
super();
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-h2-criteria");
entityManager = factory.createEntityManager();
}
@Override
public List<BookWithAuthorNames> findBookWithAuthorNamesByCriteria(String title) {
// Create query
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<BookWithAuthorNames> cq = cb.createQuery(BookWithAuthorNames.class);
// Define FROM clause
Root<Book> root = cq.from(Book.class);
Join<Book, Author> author = root.join(Book_.author);
// Define DTO projection
cq.select(cb.construct(
BookWithAuthorNames.class,
root.get(Book_.id),
root.get(Book_.title),
root.get(Book_.price),
cb.concat(author.get(Author_.firstName), author.get(Author_.lastName))
));
// Define WHERE clause
ParameterExpression<String> paramTitle = cb.parameter(String.class);
cq.where(cb.like(root.get(Book_.title), paramTitle));
// Execute query
TypedQuery<BookWithAuthorNames> q = entityManager.createQuery(cq);
q.setParameter(paramTitle, title);
List<BookWithAuthorNames> books = q.getResultList();
for (BookWithAuthorNames b : books) {
System.out.println(b);
}
return books;
}
}
|
package com.test.xiaojian.simple_reader.ui.adapter;
import android.content.Context;
import com.test.xiaojian.simple_reader.model.bean.BookHelpsBean;
import com.test.xiaojian.simple_reader.ui.adapter.view.DiscHelpsHolder;
import com.test.xiaojian.simple_reader.ui.base.adapter.IViewHolder;
import com.test.xiaojian.simple_reader.widget.adapter.WholeAdapter;
/**
* Created by xiaojian on 17-4-21.
*/
public class DiscHelpsAdapter extends WholeAdapter<BookHelpsBean>{
public DiscHelpsAdapter(Context context, Options options) {
super(context, options);
}
@Override
protected IViewHolder<BookHelpsBean> createViewHolder(int viewType) {
return new DiscHelpsHolder();
}
}
|
package com.cardinalblue.library.gifencoder;
import android.graphics.Bitmap;
import java.io.File;
/**
* Created by prada on 15/2/12.
*/
public class Giffle {
static {
System.loadLibrary("gifflen");
}
/**
* Init the gif file
* @param gifName name
* @param w width
* @param h height
* @param numColors colors
* @param quality
* @param frameDelay times
* @return
*/
private native int Init(String gifName, int w, int h, int numColors, int quality, int frameDelay);
public native void Close();
public native int AddFrame(int[] pixels);
public int AddFrame(Bitmap bitmap) {
int[] pixels = new int[bitmap.getWidth() * bitmap.getHeight()];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
return AddFrame(pixels);
}
public native void GenPalette(int len, int[] pixels);
public static class GiffleBuilder {
private File file;
private int delay;
private int w;
private int h;
private int numColor = 256;
private int qaulity = 100;
public GiffleBuilder file(File file) {
this.file = file;
return this;
}
public GiffleBuilder delay(int delayMillSecond) {
this.delay = delayMillSecond / 10;
return this;
}
public GiffleBuilder size(int w, int h) {
this.w = w;
this.h = h;
return this;
}
public GiffleBuilder numColor(int numColor) {
this.numColor = numColor;
return this;
}
public GiffleBuilder qaulity(int qaulity) {
this.qaulity = qaulity;
return this;
}
public Giffle build() {
// validate parameters
if (file == null || !file.exists()) {
throw new IllegalArgumentException("output file should not be null or non-exist");
}
if (w <= 0 || h <= 0) {
throw new IllegalArgumentException("gif size should not be < 0, width = " + w + " , height = " + h);
}
if (qaulity < 0 || qaulity > 100) {
throw new IllegalArgumentException("gif qaulity should between 0 to 100, it's not " + qaulity);
}
Giffle giffle = new Giffle();
giffle.Init(file.getAbsolutePath(), w, h, numColor, qaulity, delay);
return giffle;
}
}
}
|
package pt.client.management.repository;
import pt.client.management.domain.Customer;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CustomerRepository extends CrudRepository<Customer,Long>{
void delete (Customer deleted);
List<Customer> findAll();
Customer findOne(Long id);
Customer save(Customer customer);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.