text
stringlengths 10
2.72M
|
|---|
package com.hl.model;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class BaseResponse {
public static <E> ResponseEntity<GenericResponse<E>> ltResponse(E obj, HttpStatus httpStatus) {
GenericResponse<E> restResponseDTO = new GenericResponse<E>(obj, httpStatus.value(), null);
return new ResponseEntity<GenericResponse<E>>(restResponseDTO, httpStatus);
}
public static <Any> ResponseEntity<GenericResponse<Any>> ltResponse(Any obj) {
return ltResponse(obj, HttpStatus.OK);
}
}
|
/*
* [46] Permutations
*
* https://leetcode-cn.com/problems/permutations/description/
*
* algorithms
* Medium (61.27%)
* Total Accepted: 4.3K
* Total Submissions: 7K
* Testcase Example: '[1,2,3]'
*
* 给定一个没有重复数字的序列,返回其所有可能的全排列。
*
* 示例:
*
* 输入: [1,2,3]
* 输出:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
* ]
*
*/
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> resultList = new ArrayList<>();
backTrace(resultList,new ArrayList<>(),nums);
return resultList;
}
private void backTrace(List<List<Integer>> resultList,List<Integer>tempList,int[] nums){
if(tempList.size() == nums.length){
resultList.add(new ArrayList<>(tempList));
}else{
for(int i=0;i<nums.length;i++){
if(tempList.contains(nums[i])){
continue;
}
tempList.add(nums[i]);
backTrace(resultList,tempList,nums);
tempList.remove(tempList.size()-1);
}
}
}
}
|
package com.github.jearls.SPRaceTracker.data;
/**
* @author jearls
*/
public interface SeasonObserver {
/**
* @author jearls Used to indicate which part of a Team has changed
*/
public enum SeasonElement {
NAME, TEAMS, RACES, SEASON_ORDER
}
/**
* This method is called when some part of a Team has changed.
*
* @param team
* The team being observed.
* @param changed
* What element of the team was changed.
*/
public void seasonChanged(Season season, SeasonElement changed);
}
|
package com.wangzhu.spring.Processor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Created by wangzhu on 2018/4/24 下午11:41.
*/
public class DefaultPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("DefaultPostProcessor postProcessBeforeInitialization " + beanName);
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("DefaultPostProcessor postProcessAfterInitialization " + beanName);
return bean;
}
}
|
package com.self.config.dubbo;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@Configuration
//@ImportResource({ "classpath:dubbo.xml" })
public class DubboConfig {
}
|
package com.tibco.as.util.convert.impl;
public class NumberToString extends AbstractConverter<Number, String> {
@Override
protected String doConvert(Number source) {
return source.toString();
}
}
|
package com.example.youtubeex.usecases;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import com.example.youtubeex.entities.channelVideos.VideosChannelInfo;
import com.example.youtubeex.entities.channels.ChannelsInfo;
import com.example.youtubeex.usecases.repos.ChannelsRepo;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class ChannelsUsecases {
public MutableLiveData<ChannelsInfo> channelsInfoMutableLiveData;
ChannelsRepo channelsRepo;
public ChannelsUsecases(MutableLiveData<ChannelsInfo> channelsInfoMutableLiveData) {
this.channelsInfoMutableLiveData = channelsInfoMutableLiveData;
channelsRepo = new ChannelsRepo();
}
public void getChannelsInfo(String key,String part,String ids)
{
channelsRepo.getChannelsInfo(key,part,ids).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<ChannelsInfo>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ChannelsInfo channelsInfo) {
channelsInfoMutableLiveData.postValue(channelsInfo);
}
@Override
public void onError(Throwable e) {
Log.e("observe error",e.getMessage());
}
@Override
public void onComplete() {
}
});
}
}
|
package de.dotwee.rgb.canteen.model.api.specs;
import android.support.annotation.NonNull;
import java.util.Arrays;
import java.util.Date;
import de.dotwee.rgb.canteen.model.constant.Label;
import de.dotwee.rgb.canteen.model.constant.Price;
import de.dotwee.rgb.canteen.model.constant.Type;
import de.dotwee.rgb.canteen.model.constant.Weekday;
/**
* Created by lukas on 19.11.2016.
*/
public class Item {
private static final String TAG = Item.class.getSimpleName();
private String name;
private Date date;
private Weekday weekday;
private String info;
private Label[] labels;
private String priceEmployee;
private String priceGuest;
private String priceStudent;
private String priceAll;
private String tag;
private Type type;
public Item(@NonNull String name) {
setName(getName(name));
setInfo(getInfo(name));
}
@NonNull
public String getName() {
return name;
}
private void setName(@NonNull String name) {
this.name = name;
}
@NonNull
public Date getDate() {
return date;
}
public void setDate(@NonNull Date date) {
this.date = date;
}
@NonNull
public Weekday getWeekday() {
return weekday;
}
public void setWeekday(@NonNull Weekday weekday) {
this.weekday = weekday;
}
@NonNull
public String getInfo() {
return info;
}
private void setInfo(@NonNull String info) {
this.info = info;
}
@NonNull
public Label[] getLabels() {
return labels;
}
public void setLabels(@NonNull Label[] labels) {
this.labels = labels;
}
@NonNull
public String getPrice(@NonNull Price price) {
switch (price) {
case STUDENT:
return priceStudent;
case GUEST:
return priceGuest;
case EMPLOYEE:
return priceEmployee;
default:
return priceAll;
}
}
public void setPriceEmployee(@NonNull String priceEmployee) {
this.priceEmployee = priceEmployee;
}
public void setPriceGuest(@NonNull String priceGuest) {
this.priceGuest = priceGuest;
}
public void setPriceStudent(@NonNull String priceStudent) {
this.priceStudent = priceStudent;
}
public void setPriceAll(@NonNull String priceAll) {
this.priceAll = priceAll;
}
@NonNull
public String getTag() {
return tag;
}
public void setTag(@NonNull String tag) {
this.tag = tag;
}
@NonNull
public Type getType() {
return type;
}
public void setType(@NonNull Type type) {
this.type = type;
}
@NonNull
private String getName(@NonNull String text) {
return text.substring(0, getIndexOfStartBracket(text));
}
@NonNull
private String getInfo(@NonNull String text) {
return text.substring(getIndexOfStartBracket(text));
}
private int getIndexOfStartBracket(@NonNull String text) {
int index = text.indexOf("(");
return index != -1 ? index : text.length();
}
@Override
public String toString() {
return "Item{" +
"name='" + name + '\'' +
", date=" + date +
", info='" + info + '\'' +
", labels=" + Arrays.toString(labels) +
", priceEmployee='" + priceEmployee + '\'' +
", priceGuest='" + priceGuest + '\'' +
", priceStudent='" + priceStudent + '\'' +
", priceAll='" + priceAll + '\'' +
", tag='" + tag + '\'' +
", type=" + type +
'}';
}
}
|
package org.fonuhuolian.videoplay;
import android.content.Context;
import org.fonuhuolian.xvideoplayer.XVideoCallBack;
import org.fonuhuolian.xvideoplayer.XVideoPlayer;
import org.greenrobot.eventbus.EventBus;
import java.util.List;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;
public class Adapter extends SimpleSingleLayoutAdapter<String> {
public Adapter(Context context, int layoutResId) {
super(context, layoutResId);
}
public Adapter(Context context, int layoutResId, List<String> list) {
super(context, layoutResId, list);
}
@Override
public void bind(RecyclerViewHolder var1, String var2, int var3) {
// 查找控件
XVideoPlayer xVideoPlayer = (XVideoPlayer) var1.getView(R.id.videoplayer);
// 装载视频地址并缓存
xVideoPlayer.setUp(xVideoPlayer.setUpLazyUrl(var2), "", JzvdStd.SCREEN_WINDOW_NORMAL);
// 裁剪视频
Jzvd.setVideoImageDisplayType(Jzvd.VIDEO_IMAGE_DISPLAY_TYPE_FILL_SCROP);
// 显示预览图
// Glide.with(this).load("img-url").into(myJzvdStd.thumbImageView);
// 设置监听
xVideoPlayer.setVideoAllCallBack(new XVideoCallBack() {
@Override
public void onStateNormal() {
}
@Override
public void onStatePreparing() {
}
@Override
public void onStatePlaying() {
}
@Override
public void onStatePause() {
}
@Override
public void onStateError() {
}
@Override
public void onStateAutoComplete() {
// 通知播放下一个
if (getAttachDatas().size() - 1 > var3) {
EventBus.getDefault().post(new NextPosition(var3 + 1));
}
}
});
}
}
|
package com.cg.bo.model.security;
import com.cg.bo.model.security.BaseEntity;
import com.cg.bo.model.security.Role;
import lombok.*;
import javax.persistence.*;
@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "users")
public class User extends BaseEntity {
@Column(unique = true, nullable = false)
private String username;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String fullName;
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", fullName='" + fullName + '\'' +
", roles=" + role +
'}';
}
}
|
package com.nisira.view.Activity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.transition.Fade;
import android.transition.Slide;
import android.transition.TransitionInflater;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.nisira.core.dao.ConsumidorDao;
import com.nisira.core.dao.DordenservicioclienteDao;
import com.nisira.core.entity.Consumidor;
import com.nisira.core.entity.Dordenserviciocliente;
import com.nisira.core.entity.Ordenserviciocliente;
import com.nisira.gcalderon.policesecurity.R;
import java.util.ArrayList;
import java.util.List;
public class mnt_DOrdenServicio_Fragment extends Fragment {
// TODO: ELEMENTOS DE LAYOUT
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private Ordenserviciocliente ordenserviciocliente;
private Dordenserviciocliente dordenserviciocliente;
private AutoCompleteTextView txt_vehiculos;
private AutoCompleteTextView txtplaca;
private FloatingActionButton btn_cancelar;
private FloatingActionButton btn_acaptar;
// TODO: PARAMETROS DE ENTRADA
private String mParam1;
private String mParam2;
public mnt_DOrdenServicio_Fragment() {
// Required empty public constructor
}
// TODO: FUNCIONES Y METODOS
public static mnt_DOrdenServicio_Fragment newInstance(String param1, String param2) {
mnt_DOrdenServicio_Fragment fragment = new mnt_DOrdenServicio_Fragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
ordenserviciocliente = (Ordenserviciocliente) getArguments().getSerializable("OrdenServicio");
dordenserviciocliente = (Dordenserviciocliente)getArguments().getSerializable("DOrdenServicio");
}
}
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mnt_dordenservicio_vehiculo, container, false);
animacionEntrada();
txtplaca = (AutoCompleteTextView)view.findViewById(R.id.txtplaca);
btn_cancelar = (FloatingActionButton)view.findViewById(R.id.fab_cancelar);
btn_acaptar = (FloatingActionButton)view.findViewById(R.id.fab_aceptar);
txt_vehiculos = (AutoCompleteTextView) view.findViewById(R.id.txt_vehiculos);
LlenarCampos();
Listeners();
return view;
}
public void animacionEntrada(){
// TODO: TRANSICIONES Y ANIMACIONES
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Fade fade = (Fade) TransitionInflater.from(this.getContext()).inflateTransition(R.transition.activity_fade);
setEnterTransition(fade);
Slide slide = (Slide) TransitionInflater.from(getContext()).inflateTransition(R.transition.activity_slide);
setExitTransition(slide);
}
}
public void LlenarCampos(){
TextView view = (TextView) getActivity().findViewById(R.id.campo_titulo2);
view.setText(getString(R.string.mnt_DPersonalServicio));
txt_vehiculos.setText(dordenserviciocliente.getIdvehiculo());
txtplaca.setText(dordenserviciocliente.getPlaca_cliente());
ConsumidorDao dao = new ConsumidorDao();
List<Consumidor> consumidors= new ArrayList<>();
try {
consumidors = dao.ListarConsumidor(ordenserviciocliente);
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<Consumidor> adapter = new ArrayAdapter<Consumidor>(getContext(),
android.R.layout.simple_dropdown_item_1line,consumidors);
txtplaca.setAdapter(adapter);
}
public void Listeners(){
//TODO EVENTOS
txtplaca.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Consumidor selected = (Consumidor) parent.getAdapter().getItem(position);
dordenserviciocliente.setPlaca_cliente(txtplaca.getText().toString());
dordenserviciocliente.setIdvehiculo(selected.getIdconsumidor());
txt_vehiculos.setText(selected.getDescripcion());
Log.i("Clicked " , selected.getIdconsumidor() + " " + selected.getDescripcion());
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);
}
});
btn_cancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
btn_acaptar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (dordenserviciocliente.getPlaca_cliente()==null && dordenserviciocliente.getPlaca_cliente().equals("")) {
Snackbar.make(getView(), "Error, seleccione una placa", Snackbar.LENGTH_SHORT).show();
} else {
DordenservicioclienteDao dao = new DordenservicioclienteDao();
try {
dao.mezclarLocal(dordenserviciocliente);
} catch (Exception e) {
e.printStackTrace();
}
getActivity().onBackPressed();
}
}
});
}
}
|
/*
* 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 poker2;
import java.time.LocalDate;
/**
*
* @author Danil
*/
public abstract class Jugador {
private String NIF;
private String nombre;
private String apellidos;
private LocalDate fechaNacimiento;
private double saldoAcumulado;
/**
*
* @param NIF
* @param nombre
* @param apellidos
* @param fechaNacimiento
* @param saldoAcumulado
*/
public Jugador(String NIF, String nombre, String apellidos, LocalDate fechaNacimiento, double saldoAcumulado) {
this.NIF = NIF;
this.nombre = nombre;
this.apellidos = apellidos;
this.fechaNacimiento = fechaNacimiento;
this.saldoAcumulado = saldoAcumulado;
}
/**
*
* @return
*/
public double getSaldoAcumulado() {
return saldoAcumulado;
}
/**
*
* @param saldoAcumulado
*/
public void setSaldoAcumulado(double saldoAcumulado) {
this.saldoAcumulado = saldoAcumulado;
}
/**
*
* @return
*/
public LocalDate getFechaNacimiento() {
return fechaNacimiento;
}
/**
*
* @param fechaNacimiento
*/
public void setFechaNacimiento(LocalDate fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
/**
*
* @return
*/
public String getApellidos() {
return apellidos;
}
/**
*
* @param apellidos
*/
public void setApellidos(String apellidos) {
this.apellidos = apellidos;
}
/**
*
* @return
*/
public String getNombre() {
return nombre;
}
/**
*
* @param nombre
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
*
* @return
*/
public String getNIF() {
return NIF;
}
/**
*
* @param NIF
*/
public void setNIF(String NIF) {
this.NIF = NIF;
}
/**
*
* @return
*/
abstract public double retirarBeneficios(); //Metodo abstracto
/**
*
* @param saldo
*/
public void aumentarSaldo(double saldo){
this.saldoAcumulado+=saldo; //Aumentamos el saldo del jugador
}
@Override
public String toString() {
return "NIF=" + NIF + ", nombre=" + nombre + ", apellidos=" + apellidos + ", fechaNacimiento=" + fechaNacimiento + ", saldoAcumulado=" + saldoAcumulado ;
}
}
|
package pkgmain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
public static void main(String[] args) {
// Logging - only using the slf4j API here
// (logging implementation is added via Runtime option by adding an automatic module,
// see libraries of the three launch files variants)
Logger logger = LoggerFactory.getLogger(Main.class);
logger.info("This is Main - logging.");
}
}
|
package Class1.InterfaceDemo2;
/**
* Created by FLK on 2019-12-21.
*/
public interface Swimmable {
void swim();
}
|
package com.solucionfactible.dev;
/**
* comp checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means,
* here, that the elements in b are the elements in a squared, regardless of the order.
*
* @author developer
*/
public class AreSame {
public static boolean comp(int[] a, int[] b) {
// Si ambos arreglos llegan vacios existen los mismos elementos en ambos arreglos y retornamos un true
if( a.length == 0 && b.length == 0 ) {
return true;
}
// Su uno de los 2 arreglos llega con datos y el otro no, no existen los mismos datos y se retorna un false
if(( a.length != 0 && b.length == 0 ) ||(b.length != 0 && a.length== 0) ) {
return false;
}
// Obtenemos el cuadrado del primer elemento del arreglo a
int squared = a[0] * a[0];
// Recorremos el arreglo b hasta encontrar el cuadrado
for( int i = 0; i < b.length; i++) {
if( b[i] == squared ) {
// Si lo encontramos eliminamos el elemento de ambos arreglos
int[] new_a = removeElement(a, 0);
int[] new_b = removeElement(b, i);
return comp(new_a, new_b);
}
}
return false;
}
// Funcion que elimina un elemento que existe en ambos arreglos
static int[] removeElement(int[] arr, int i) {
int[] newArray = new int[arr.length - 1];
if (i > 0){
System.arraycopy(arr, 0, newArray, 0, i);
}
if (newArray.length > i){
System.arraycopy(arr, i + 1, newArray, i, newArray.length - i);
}
return newArray;
}
}
|
package com.github.life.lab.leisure.backend.gateway.application.service;
import com.github.life.lab.leisure.backend.gateway.model.sign.*;
import com.github.life.lab.leisure.member.authorization.token.impl.AuthToken;
/**
* SignService
*
* @author weichao.li (liweichao0102@gmail.com)
* @date 2018/11/5
*/
public interface SignService {
AuthToken password(SignInPassword model);
AuthToken mobile(SignInMobile model);
AuthToken email(SignInEmail model);
AuthToken refreshToken(SignInRefreshToken model);
PrimaryPlatform switchPrimaryPlatform(SwitchPlatformModel model, String accessToken);
void signOut(String accessToken);
void memberListener(Long id);
}
|
package com.zjf.myself.codebase.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.zjf.myself.codebase.R;
import java.util.List;
public class MyRecycleViewAdapter1 extends RecyclerView.Adapter<MyRecycleViewAdapter1.MyViewHolder>
implements View.OnClickListener{
private List<String> mData;
public MyRecycleViewAdapter1(List<String> data) {
mData = data;
}
private OnItemClickListener mOnItemClickListener = null;
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = View.inflate(parent.getContext(), R.layout.item_layout, null);
itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
itemView.setOnClickListener(this);
return new MyViewHolder(itemView);
}
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
//注意这里使用getTag方法获取position
mOnItemClickListener.onItemClick(v,(int)v.getTag());
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mOnItemClickListener = listener;
}
public static interface OnItemClickListener {
void onItemClick(View view , int position);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mTv.setText(mData.get(position));
holder.itemView.setTag(position);
}
@Override
public int getItemCount() {
return mData.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView mTv;
public MyViewHolder(View itemView) {
super(itemView);
mTv = (TextView) itemView.findViewById(R.id.text1);
}
}
}
|
package com.framgia.fsalon.screen.listbill;
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.support.annotation.IdRes;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.RadioGroup;
import com.android.databinding.library.baseAdapters.BR;
import com.framgia.fsalon.FSalonApplication;
import com.framgia.fsalon.R;
import com.framgia.fsalon.data.model.BillResponse;
import com.framgia.fsalon.data.model.ListBillRespond;
import com.framgia.fsalon.data.model.Salon;
import com.framgia.fsalon.data.model.User;
import com.framgia.fsalon.screen.bill.BillActivity;
import com.framgia.fsalon.screen.billdetail.BillDetailActivity;
import com.framgia.fsalon.screen.listbill.customerlist.CustomerListActivity;
import com.framgia.fsalon.screen.scheduler.DepartmentAdapter;
import com.framgia.fsalon.utils.OnDepartmentItemClick;
import com.framgia.fsalon.utils.Utils;
import com.framgia.fsalon.utils.navigator.Navigator;
import com.framgia.fsalon.wiget.StickyHeaderLayoutManager;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import static android.app.Activity.RESULT_OK;
import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.framgia.fsalon.data.source.remote.ManageBookingRemoteDataSource.FILTER_DAY;
import static com.framgia.fsalon.data.source.remote.ManageBookingRemoteDataSource.FILTER_SPACE;
import static com.framgia.fsalon.screen.scheduler.SchedulerViewModel.TabFilter.TAB_END_DATE;
import static com.framgia.fsalon.screen.scheduler.SchedulerViewModel.TabFilter.TAB_SELECT_DATE;
import static com.framgia.fsalon.screen.scheduler.SchedulerViewModel.TabFilter.TAB_START_DATE;
import static com.framgia.fsalon.screen.scheduler.SchedulerViewModel.TabFilter.TAB_TODAY;
import static com.framgia.fsalon.screen.scheduler.SchedulerViewModel.TabFilter.TAB_TOMORROW;
import static com.framgia.fsalon.screen.scheduler.SchedulerViewModel.TabFilter.TAB_YESTERDAY;
import static com.framgia.fsalon.utils.Constant.EXTRA_CUSTOMER;
import static com.framgia.fsalon.utils.Constant.FIRST_ITEM;
import static com.framgia.fsalon.utils.Constant.OUT_OF_INDEX;
import static com.framgia.fsalon.utils.Constant.RequestPermission.REQUEST_START_CUSTOMER_FILTER_ACTIVITY;
/**
* Exposes the data to be used in the Listbill screen.
*/
public class ListBillViewModel extends BaseObservable
implements ListBillContract.ViewModel, OnDepartmentItemClick,
DatePickerDialog.OnDateSetListener,
DialogInterface.OnCancelListener, ListBillAdapter.OnBillItemClick {
public static final int STATUS_WAITING = 0;
public static final int STATUS_COMPLETED = 1;
public static final int STATUS_CANCEL = 2;
public static final String STT_WAITING = "Waiting";
public static final String STT_COMPLETED = "Completed";
public static final String STT_CANCEL = "Cancel";
private ListBillContract.Presenter mPresenter;
private Activity mActivity;
private Context mContext;
private Navigator mNavigator;
private StickyHeaderLayoutManager mLayoutManager = new StickyHeaderLayoutManager();
private ListBillAdapter mAdapter;
private int mVisibleProgressBar = GONE;
private int mRadioButtonId;
private DepartmentAdapter mDepartmentAdapter;
private User mCustomer;
private String mTitleFragment;
private boolean mIsWaiting;
private boolean mIsCompleted;
private boolean mIsCanceled;
private Calendar mCalendar;
private int mStartDate = Utils.createTimeStamp(TAB_TODAY);
private int mEndDate = OUT_OF_INDEX;
private DatePickerDialog mDatePickerDialog;
private int mTypeSelectDate;
private String mTypeFilter;
private String mStatusId = "";
private int mDepartmentId = OUT_OF_INDEX;
private FragmentManager mFragmentManager;
private String mSpaceTime = "";
private String mSalonName;
private ListBillFragment mListBillFragment;
private DrawerLayout.DrawerListener mDrawerListener = new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
}
@Override
public void onDrawerClosed(View drawerView) {
makeStatusFilter();
mPresenter
.filterBills(mTypeFilter, mStartDate, mEndDate, mStatusId, mDepartmentId,
mCustomer.getId());
}
@Override
public void onDrawerStateChanged(int newState) {
}
};
private void makeStatusFilter() {
mStatusId = "";
if (mIsCanceled) {
mStatusId = mStatusId.concat(STATUS_CANCEL + ",");
}
if (mIsCompleted) {
mStatusId = mStatusId.concat(STATUS_COMPLETED + ",");
}
if (mIsWaiting) {
mStatusId = mStatusId.concat(STATUS_WAITING + ",");
}
mStatusId = mStatusId.substring(0, mStatusId.length() - 1);
}
private RadioGroup.OnCheckedChangeListener mChangeListener = new RadioGroup
.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
case R.id.filter_today:
mTypeFilter = FILTER_DAY;
mEndDate = OUT_OF_INDEX;
mStartDate = Utils.createTimeStamp(TAB_TODAY);
setTitleFragment(FSalonApplication.getInstant().getResources()
.getString(R.string.title_today));
setRadioButtonId(R.id.filter_today);
break;
case R.id.filter_yesterday:
mEndDate = OUT_OF_INDEX;
mTypeFilter = FILTER_DAY;
mStartDate = Utils.createTimeStamp(TAB_YESTERDAY);
setTitleFragment(FSalonApplication.getInstant().getResources()
.getString(R.string.title_yesterday));
setRadioButtonId(R.id.filter_yesterday);
break;
case R.id.filter_tomorrow:
mEndDate = OUT_OF_INDEX;
mTypeFilter = FILTER_DAY;
mStartDate = Utils.createTimeStamp(TAB_TOMORROW);
setTitleFragment(FSalonApplication.getInstant().getResources()
.getString(R.string.title_tomorrow));
setRadioButtonId(R.id.filter_tomorrow);
break;
default:
break;
}
}
};
public ListBillViewModel(Activity activity, ListBillFragment fragment) {
mActivity = activity;
mContext = activity.getApplicationContext();
mListBillFragment = fragment;
mNavigator = new Navigator(mListBillFragment);
mFragmentManager = mActivity.getFragmentManager();
setAdapter(new ListBillAdapter(new ArrayList<ListBillRespond>(), this));
mCustomer = new User();
mCustomer.setId(OUT_OF_INDEX);
if (mCalendar == null) {
mCalendar = Calendar.getInstance();
}
mDatePickerDialog =
DatePickerDialog.newInstance(this, mCalendar.get(Calendar.YEAR),
mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
mDatePickerDialog.setOnDateSetListener(this);
mDatePickerDialog.setOnCancelListener(this);
setRadioButtonId(R.id.filter_today);
setWaiting(true);
setCompleted(true);
setCanceled(true);
}
@Override
public void onStart() {
mPresenter.onStart();
}
@Override
public void onStop() {
mPresenter.onStop();
}
@Override
public void setPresenter(ListBillContract.Presenter presenter) {
mPresenter = presenter;
}
@Override
public void onCreateBillClick() {
mNavigator.startActivity(BillActivity.getInstance(mContext, -1));
}
@Override
public void onFilterSuccessfully(List<ListBillRespond> bills) {
mAdapter.clear();
mAdapter.updateData(bills);
}
@Override
public void onHideProgressBar() {
setVisibleProgressBar(GONE);
}
@Override
public void onShowProgressBar() {
setVisibleProgressBar(VISIBLE);
}
@Override
public void onFilterClick(DrawerLayout layout) {
if (layout.isDrawerOpen(Gravity.START)) {
layout.closeDrawer(Gravity.START);
return;
}
layout.openDrawer(Gravity.START);
}
@Override
public void onSpaceTimeClick() {
mTypeFilter = FILTER_SPACE;
mTypeSelectDate = TAB_START_DATE;
showDatePickerDialog();
}
@Override
public void onSelectDateClick() {
mEndDate = OUT_OF_INDEX;
mTypeFilter = FILTER_DAY;
mTypeSelectDate = TAB_SELECT_DATE;
showDatePickerDialog();
}
private void showDatePickerDialog() {
switch (mTypeSelectDate) {
case TAB_SELECT_DATE:
mDatePickerDialog.setTitle(FSalonApplication.getInstant().getResources()
.getString(R.string.title_select_date));
break;
case TAB_START_DATE:
mDatePickerDialog.setTitle(FSalonApplication.getInstant().getResources()
.getString(R.string.title_select_start_day));
break;
case TAB_END_DATE:
mDatePickerDialog.setTitle(FSalonApplication.getInstant().getResources()
.getString(R.string.title_select_end_day));
break;
default:
break;
}
mDatePickerDialog.show(mFragmentManager, "");
}
@Override
public void onGetSalonsSuccess(List<Salon> salons) {
setDepartmentAdapter(new DepartmentAdapter(mContext, salons, this));
mDepartmentAdapter.selectedPosition(FIRST_ITEM);
mDepartmentId = mDepartmentAdapter.getItem(FIRST_ITEM).getId();
setSalonName(mDepartmentAdapter.getItem(FIRST_ITEM).getName());
}
@Override
public void getCustomerSuccessfull(User user) {
setCustomer(user);
}
@Override
public void onSearchCustomer() {
mNavigator.startActivityForResult(CustomerListActivity.getInstance(),
REQUEST_START_CUSTOMER_FILTER_ACTIVITY);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_START_CUSTOMER_FILTER_ACTIVITY:
if (data == null) {
break;
}
getCustomerSuccessfull((User) data.getParcelableExtra(EXTRA_CUSTOMER));
break;
default:
break;
}
}
@Override
public void onBillDetailClick(BillResponse bill) {
if (bill == null) {
return;
}
mNavigator.startActivity(BillDetailActivity.getInstance(mContext, bill.getId()));
}
public StickyHeaderLayoutManager getLayoutManager() {
return mLayoutManager;
}
public void setLayoutManager(StickyHeaderLayoutManager layoutManager) {
mLayoutManager = layoutManager;
}
public ListBillAdapter getAdapter() {
return mAdapter;
}
public void setAdapter(ListBillAdapter adapter) {
mAdapter = adapter;
}
public int getVisibleProgressBar() {
return mVisibleProgressBar;
}
public void setVisibleProgressBar(int visibleProgressBar) {
mVisibleProgressBar = visibleProgressBar;
}
public DrawerLayout.DrawerListener getDrawerListener() {
return mDrawerListener;
}
public void setDrawerListener(DrawerLayout.DrawerListener drawerListener) {
mDrawerListener = drawerListener;
}
public RadioGroup.OnCheckedChangeListener getChangeListener() {
return mChangeListener;
}
public void setChangeListener(RadioGroup.OnCheckedChangeListener changeListener) {
mChangeListener = changeListener;
}
@Bindable
public int getRadioButtonId() {
return mRadioButtonId;
}
public void setRadioButtonId(int radioButtonId) {
mRadioButtonId = radioButtonId;
notifyPropertyChanged(BR.radioButtonId);
}
@Bindable
public DepartmentAdapter getDepartmentAdapter() {
return mDepartmentAdapter;
}
public void setDepartmentAdapter(DepartmentAdapter departmentAdapter) {
mDepartmentAdapter = departmentAdapter;
notifyPropertyChanged(BR.departmentAdapter);
}
public Activity getActivity() {
return mActivity;
}
public void setActivity(Activity activity) {
mActivity = activity;
}
@Bindable
public User getCustomer() {
return mCustomer;
}
public void setCustomer(User customer) {
mCustomer = customer;
notifyPropertyChanged(BR.customer);
}
@Bindable
public String getTitleFragment() {
return mTitleFragment;
}
public void setTitleFragment(String titleFragment) {
mTitleFragment = titleFragment;
notifyPropertyChanged(BR.titleFragment);
}
@Bindable
public boolean isWaiting() {
return mIsWaiting;
}
public void setWaiting(boolean waiting) {
mIsWaiting = waiting;
notifyPropertyChanged(BR.waiting);
}
@Bindable
public boolean isCompleted() {
return mIsCompleted;
}
public void setCompleted(boolean completed) {
mIsCompleted = completed;
notifyPropertyChanged(BR.completed);
}
@Bindable
public boolean isCanceled() {
return mIsCanceled;
}
public void setCanceled(boolean canceled) {
mIsCanceled = canceled;
notifyPropertyChanged(BR.canceled);
}
public Calendar getCalendar() {
return mCalendar;
}
public void setCalendar(Calendar calendar) {
mCalendar = calendar;
}
public int getStartDate() {
return mStartDate;
}
public void setStartDate(int startDate) {
mStartDate = startDate;
}
public int getEndDate() {
return mEndDate;
}
public void setEndDate(int endDate) {
mEndDate = endDate;
}
public int getTypeSelectDate() {
return mTypeSelectDate;
}
public void setTypeSelectDate(int typeSelectDate) {
mTypeSelectDate = typeSelectDate;
}
@Override
public void onSelectedSalonPosition(int pos, Salon salon) {
if (salon == null) {
return;
}
mDepartmentAdapter.selectedPosition(pos);
setDepartmentId(salon.getId());
}
public String getTypeFilter() {
return mTypeFilter;
}
public void setTypeFilter(String typeFilter) {
mTypeFilter = typeFilter;
}
public String getStatusId() {
return mStatusId;
}
public void setStatusId(String statusId) {
mStatusId = statusId;
}
public int getDepartmentId() {
return mDepartmentId;
}
public void setDepartmentId(int departmentId) {
mDepartmentId = departmentId;
}
@Bindable
public String getSalonName() {
return mSalonName;
}
public void setSalonName(String salonName) {
mSalonName = salonName;
notifyPropertyChanged(BR.salonName);
}
@Override
public void onCancel(DialogInterface dialogInterface) {
setRadioButtonId(mRadioButtonId);
}
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
if (mDatePickerDialog != null) {
mDatePickerDialog.dismiss();
}
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
mCalendar.set(Calendar.HOUR_OF_DAY, 0);
mCalendar.set(Calendar.MINUTE, 0);
mCalendar.set(Calendar.SECOND, 0);
mCalendar.set(Calendar.MILLISECOND, 0);
switch (mTypeSelectDate) {
case TAB_START_DATE:
mStartDate = (int) (mCalendar.getTimeInMillis() / 1000);
mTypeSelectDate = TAB_END_DATE;
mDatePickerDialog = DatePickerDialog.newInstance(this, year,
monthOfYear, dayOfMonth);
mDatePickerDialog.setOnCancelListener(this);
mSpaceTime = Utils.convertDate(mCalendar.getTime());
showDatePickerDialog();
return;
case TAB_SELECT_DATE:
mEndDate = OUT_OF_INDEX;
setTitleFragment(Utils.convertDate(mCalendar.getTime()));
mStartDate = (int) (mCalendar.getTimeInMillis() / 1000);
setRadioButtonId(R.id.filter_select_date);
break;
case TAB_END_DATE:
mEndDate = (int) (mCalendar.getTimeInMillis() / 1000);
mSpaceTime = mSpaceTime.concat(" - " + Utils.convertDate(mCalendar.getTime()));
setTitleFragment(mSpaceTime);
setRadioButtonId(R.id.filter_space_time);
mPresenter.filterBills(mTypeFilter, mStartDate, mEndDate, mStatusId, mDepartmentId,
mCustomer.getId());
break;
default:
break;
}
}
}
|
package com.santotomas.peso_usd;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DecimalFormat;
public class MainActivity extends AppCompatActivity {
private EditText val_valor1;
private TextView tv_resultado1;
private TextView tv_resultado2;
DecimalFormat decimal = new DecimalFormat("$#,###.##");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
val_valor1=(EditText)findViewById(R.id.txt_valor1);
tv_resultado1=(TextView)findViewById(R.id.tv_resultado1);
tv_resultado2=(TextView)findViewById(R.id.tv_resultado2);
}
public void Calcular(View view){
String valor1_String=val_valor1.getText().toString();
double valor1_int=Double.parseDouble(valor1_String);
double tran = valor1_int / 706.98;
String resultado = decimal.format(tran);
tv_resultado1.setText(resultado);
double ufs = valor1_int / 27593.25;
String resultado2 = decimal.format(ufs);
tv_resultado2.setText(resultado2);
}
}
|
package com.seboid.udembottin;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.unboundid.ldap.sdk.Attribute;
import com.unboundid.ldap.sdk.LDAPConnection;
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.ldap.sdk.LDAPSearchException;
import com.unboundid.ldap.sdk.ResultCode;
import com.unboundid.ldap.sdk.SearchRequest;
import com.unboundid.ldap.sdk.SearchResult;
import com.unboundid.ldap.sdk.SearchResultEntry;
import com.unboundid.ldap.sdk.SearchScope;
public class MainActivity extends Activity {
AutoCompleteTextView tvNom;
AutoCompleteTextView tvTel;
TextView status;
CheckBox etudiants;
WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// doLDAP();
status = (TextView) findViewById(R.id.status);
etudiants = (CheckBox) findViewById(R.id.etudiants);
web = (WebView) findViewById(R.id.infopersonne);
web.setScrollContainer(true);
web.setScrollbarFadingEnabled(false);
web.setBackgroundColor(0xff000000);
web.getSettings().setJavaScriptEnabled(false);
tvNom = (AutoCompleteTextView) findViewById(R.id.auto_nom);
tvTel = (AutoCompleteTextView) findViewById(R.id.auto_tel);
/** Get the list of the months */
// String[] months =
// getResources().getStringArray(R.array.months_array);
/** Create a new ArrayAdapter and bind list_item.xml to each list item */
// final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// R.layout.list_item, months);
AutoCompleteAdapter adapterNom = new AutoCompleteAdapter(this, "cn");
AutoCompleteAdapter adapterTel = new AutoCompleteAdapter(this,
"telephonenumber");
/** Associate the adapter with textView */
tvNom.setAdapter(adapterNom);
tvTel.setAdapter(adapterTel);
// tv.addTextChangedListener(new TextWatcher() {
//
// @Override
// public void afterTextChanged(Editable arg0) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void beforeTextChanged(CharSequence arg0, int arg1,
// int arg2, int arg3) {
// // TODO Auto-generated method stub
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before,
// int count) {
// // adapter.add(">"+count+"<");
// // MainActivity.this.tv.getAdapter().add("yoyo");
// Log.d("text", ">" + s + "<" + start + ":" + before + ":"
// + count);
// // if( s.charAt(start)=='b' ) adapter.add("bonjour");
// }
// });
tvNom.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View v, int pos,
long id) {
Log.d("bottin", "click pos=" + pos);
//
// affiche!
//
Personne p = (Personne) adapter.getItemAtPosition(pos);
web.loadDataWithBaseURL(null, p.toHtml(), "text/html", "utf-8",
null);
}
});
tvTel.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View v, int pos,
long id) {
Log.d("bottin", "click pos=" + pos);
//
// affiche!
//
Personne p = (Personne) adapter.getItemAtPosition(pos);
web.loadDataWithBaseURL(null, p.toHtml(), "text/html", "utf-8",
null);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//
// Personne
//
private class Personne implements Comparable {
String cn;
String title;
String telephonenumber; // 514 343-6852
String roomnumber; // 2391
String buildingname; // PAVILLON ANDRE-AISENSTADT
String ou; // Faculté des arts et des sciences - Département
// labeleduri =
String mail; // sebastien.3d.roy@umontreal.ca
// givenname = Sébastien
// sn = Roy
// le tostring donne la string a mettre dans le text entry
@Override
public String toString() {
return cn;
}
public int compareTo(Personne p) {
return cn.compareToIgnoreCase(p.cn);
}
@Override
public int compareTo(Object p) {
return this.compareTo((Personne) p);
}
public String toHtml() {
String res="<style type=\"text/css\">body { color:" + "#ffffff"
+ "; background-color:" + "#000000" + " } a { color:"
+ "#8080ff" + "; } h2 { color:" + "#ffffff"
+ "; } </style><body>";
res+= "<font size=\"+2\">" + cn + "</font><br/>";
res+= title + "<br/>";
if( ou!=null ) res+= "<p>"+ou + "</p>";
if( telephonenumber!=null ) res+= "tél: "+telephonenumber + "<br/>";
if( buildingname!=null ) {
res+= "<p>"+buildingname;
if( roomnumber!=null ) res+= "<br/>"+roomnumber;
res+="</p>";
}
if( mail!=null ) res+= "<p>" + mail + "</p>";
res+="</body>";
return res;
};
}
private class AutoCompleteAdapter extends ArrayAdapter<Personne> implements
Filterable {
private LayoutInflater mInflater;
private boolean tooMany; // true -> too many results returned to ldap.
// getCount will be 0.
private String field; // "cn", ... pour le LDAP search
public AutoCompleteAdapter(final Context context, String field) {
super(context, -1);
mInflater = LayoutInflater.from(context);
this.field = field;
tooMany = false;
}
@Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
final LinearLayout layout;
TextView tvNom, tvTitre;
if (convertView != null) {
layout = (LinearLayout) convertView;
} else {
layout = (LinearLayout) mInflater.inflate(R.layout.rangee2,
parent, false);
}
tvNom = (TextView) layout.findViewById(R.id.nom);
tvTitre = (TextView) layout.findViewById(R.id.titre);
Personne p = getItem(position);
tvNom.setText(p.cn);
tvTitre.setText(p.title);
return layout;
}
@Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
Log.d("bottin", "dataset changed!");
showSomeResults();
}
@Override
public void notifyDataSetInvalidated() {
// TODO Auto-generated method stub
super.notifyDataSetInvalidated();
Log.d("bottin", "dataset invalidated!");
if( !NetUtil.networkOK(MainActivity.this) ) {
status.setText("net!");
}
}
public void showNoResult() {
Log.d("publish", "got no result!");
// status.setImageDrawable(getResources().getDrawable(R.drawable.beer));
status.setText("( 0 )");
}
public void showTooManyResult() {
Log.d("publish", "got too many result!");
// status.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));
status.setText("( >30 )");
}
public void showSomeResults() {
Log.d("publish", "got some results!");
// status.setImageDrawable(getResources().getDrawable(R.drawable.martini));
status.setText("( " + getCount() + ")");
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence s) {
if (s == null) {
Log.d("filter", "no constraint");
return null;
}
final FilterResults filterResults = new FilterResults();
Log.d("filter", "constraint=" + s);
if (s.length() <= 2) {
filterResults.values = null;
filterResults.count = -2; // too many!
return filterResults; // au moins 1 char pour une
// recherche
}
// trouve dans le bottin!
List<Personne> vals;
try {
vals = doLDAP(s.toString(), field);
filterResults.values = vals;
filterResults.count = vals.size();
} catch (NoResultException e) {
filterResults.values = null;
filterResults.count = -1;
} catch (TooManyResultsException e) {
filterResults.values = null;
filterResults.count = -2;
}
return filterResults;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence s, FilterResults res) {
Log.d("bottin", "publich results");
if (res == null) {
notifyDataSetInvalidated();
showNoResult();
return;
}
if (res.count == -1 || res.count == 0) {
showNoResult();
} else if (res.count == -2) {
showTooManyResult();
}
if (res.values == null) {
notifyDataSetInvalidated();
return;
}
// check noresult/toomany
List<Personne> plist = (List<Personne>) res.values;
// change l'adapter pour refleter le resultat
clear();
for (Personne v : (List<Personne>) res.values) {
add(v);
}
if (res.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
@SuppressWarnings("serial")
class NoResultException extends Exception {
};
@SuppressWarnings("serial")
class TooManyResultsException extends Exception {
};
//
// recherche LDAP
// field: "cn", ...
//
public List<Personne> doLDAP(String s, String field)
throws NoResultException, TooManyResultsException {
try {
LDAPConnection ldap = new LDAPConnection("bottin.umontreal.ca", 389);
// Log.d("ldap", "connected");
// String filter = "(cn=roy sebastien)";
// String filter="(telephonenumber=*6852*)";
// String filter="(uid=425780)";
// String filter = "(cn=" + s + "*)";
// String filter = "(|(cn=" + s + "*)(telephonenumber=*"+s+"*))";
// String filter = "(telephonenumber=*"+s+"*)";
// cherche pour *s*, en realite...
// cherche pour un mot (nom ou prenom) qui FINIT par s
// String filter = "(cn=*" + s + ")";
// cherche pour un mot qui COMMENCE par s
// String filter = "(cn=" + s + "*)";
// cherche pour un mot qui CONTIENT s (plus lent)
String filter = "(" + field + "=*" + s + "*)";
// (dn='uid=425780, ou=personnel, ou=people, dc=UMontreal, dc=CA')
// telephonenumber = 514 343-6852
// roomnumber = 2391
// buildingname = PAVILLON ANDRE-AISENSTADT
// ou = Faculté des arts et des sciences - Département
// d'informatique et de recherche opérationnelle
// title = Professeur agrégé
// labeleduri =
// mail = sebastien.3d.roy@umontreal.ca
// givenname = Sébastien
// sn = Roy
// cn = Roy Sébastien
SearchRequest request = new SearchRequest("", SearchScope.SUB,
filter);
request.setSizeLimit(100);
request.setTimeLimitSeconds(30);
SearchResult result;
try {
Log.d("ldap", "searching " + field);
result = ldap.search(request);
} catch (LDAPSearchException lse) {
result = lse.getSearchResult();
Log.d("LDAP",
"(too many) search exception " + result.getEntryCount());
throw new TooManyResultsException();
}
if (result.getResultCode() == ResultCode.SUCCESS) {
int k = result.getEntryCount();
Log.d("ldap", "got " + k + " entries");
List<Personne> res = new ArrayList<Personne>();
if (k == 0) {
Log.d("ldap", "no results");
throw new NoResultException();
}
boolean etud = etudiants.isChecked();
List<SearchResultEntry> se = result.getSearchEntries();
for (SearchResultEntry sre : se) {
// Log.d("ldap", "------");
Collection<Attribute> att = sre.getAttributes();
if (!etud
&& sre.getAttributeValue("title").matches(
"Étudiant.*"))
continue; // skip etudiants
Personne p = new Personne();
p.cn = sre.getAttributeValue("cn");
p.title = sre.getAttributeValue("title");
p.telephonenumber = sre
.getAttributeValue("telephonenumber");
p.roomnumber = sre.getAttributeValue("roomnumber");
p.buildingname = sre.getAttributeValue("buildingname");
p.ou = sre.getAttributeValue("ou");
p.mail = sre.getAttributeValue("mail");
res.add(p);
}
Collections.sort(res);
return res;
} else {
Log.d("ldap", "got ... failed.");
}
ldap.close();
return null;
} catch (LDAPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
|
package com.atguigu.java2;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
public class MapAPI {
/**
* Set keySet():返回所有key构成的Set集合
Collection values():返回所有value构成的Collection集合
Set entrySet():返回所有key-value对构成的Set集合
*/
@Test
public void test5(){
HashMap map = new HashMap();
map.put("aaa", "AAA");
map.put("bbb", "BBB");
map.put("ccc", "CCC");
Set keySet = map.keySet();
for (Object key : keySet) {
System.out.println(key);
}
System.out.println("---------------");
Collection values = map.values();
for (Object value : values) {
System.out.println(value);
}
System.out.println("---------------");
Set entrySet = map.entrySet();
for (Object entry : entrySet) {
Map.Entry e = (Map.Entry) entry;
System.out.println(e.getKey() + "-----" + e.getValue());
}
}
/**
* Object get(Object key):获取指定key对应的value
boolean containsKey(Object key):是否包含指定的key
boolean containsValue(Object value):是否包含指定的value
int size():返回map中key-value对的个数
boolean isEmpty():判断当前map是否为空
boolean equals(Object obj):判断当前map和参数对象obj是否相等
*/
@Test
public void test4(){
HashMap map = new HashMap();
map.put("aaa", "AAA");
map.put("bbb", "BBB");
HashMap map2 = new HashMap();
map2.put("bbb", "BBB");
map2.put("aaa", "AAA");
System.out.println(map.equals(map2));
}
@Test
public void test3(){
HashMap map = new HashMap();
map.put("aaa", "AAA");
map.put("ccc", new Student("小龙哥", 18));
//Object get(Object key):获取指定key对应的value
Object value = map.get("aaa");
System.out.println(value);
//boolean containsKey(Object key):是否包含指定的key
System.out.println(map.containsKey("aaa"));
//boolean containsValue(Object value):是否包含指定的value
System.out.println(map.containsValue(new Student("小龙哥", 18)));
}
/**
* Object put(Object key,Object value):将指定key-value添加到(或修改)当前map对象中
void putAll(Map m):将m中的所有key-value对存放到当前map中
Object remove(Object key):移除指定key的key-value对,并返回value
void clear():清空当前map中的所有数据
*/
@Test
public void test2(){
HashMap map = new HashMap();
map.put("aaa", "AAA");
//key中存放的对象所在的类必须重写equals和hashCode方法
map.put(new Person("强哥", 10), "qiangge");
// HashMap map2 = new HashMap();
// map2.put("bbb", "BBB");
// map2.put("ccc", "CCC");
// map2.put("ddd", "DDD");
// map.putAll(map2);
// System.out.println(map);
//Object remove(Object key):移除指定key的key-value对,并返回value
// Object value = map.remove(new Person("强哥", 10));
// System.out.println("map=" + map);
// System.out.println("value=" + value);
map.clear();
System.out.println();
}
}
|
package com.redhat.service.bridge.executor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.redhat.service.bridge.infra.models.filters.BaseFilter;
import com.redhat.service.bridge.infra.models.filters.StringBeginsWith;
import com.redhat.service.bridge.infra.models.filters.StringContains;
import com.redhat.service.bridge.infra.models.filters.StringEquals;
public class FilterEvaluatorFactoryFEEL implements FilterEvaluatorFactory {
public static final String IS_VALID = "OK";
public static final String IS_INVALID = "NOT_OK";
private static final String TEMPLATE = "if %s then \"" + IS_VALID + "\" else \"" + IS_INVALID + "\"";
@Override
public FilterEvaluator build(Set<BaseFilter> filters) {
Set<String> templates = filters == null ? null : filters.stream().map(this::getTemplateByFilterType).collect(Collectors.toSet());
return new FilterEvaluatorFEEL(templates);
}
protected String getTemplateByFilterType(BaseFilter filter) {
return String.format(TEMPLATE, getFilterCondition(filter));
}
private String getFilterCondition(BaseFilter filter) {
switch (filter.getType()) {
case StringEquals.FILTER_TYPE_NAME:
return String.format("%s = \"%s\"", filter.getKey(), filter.getValueAsString());
case StringContains.FILTER_TYPE_NAME:
return getFilterConditionForListValues("(contains (%s, \"%s\"))", filter);
case StringBeginsWith.FILTER_TYPE_NAME:
return getFilterConditionForListValues("(starts with (%s, \"%s\"))", filter);
default:
throw new IllegalArgumentException("Filter type " + filter.getType() + " is not supported by FEELTemplateFactory.");
}
}
@SuppressWarnings("unchecked")
private String getFilterConditionForListValues(String singleFormatTemplate, BaseFilter filter) {
List<String> conditions = new ArrayList<>();
for (String value : (List<String>) filter.getValue()) {
conditions.add(String.format(singleFormatTemplate, filter.getKey(), value));
}
return String.join(" or ", conditions);
}
}
|
package cn.huangqiqiang.halbum.activity;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.MediaController;
import android.widget.VideoView;
import com.bm.library.PhotoView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import cn.huangqiqiang.halbum.R;
import cn.huangqiqiang.halbum.common.FunctionConfig;
import cn.huangqiqiang.halbum.entity.LocalMedia;
/**
* 在此写用途
*
* @version V1.0 <描述当前版本功能>
* @FileName: cn.huangqiqiang.halbum.activity.AlbumPreviewFragment.java
* @author: 黄其强
* @date: 2017-05-08 17:56
*/
public class AlbumPreviewFragment extends Fragment {
public static final String PATH = "path";
public static final String DATA = "data";
public static AlbumPreviewFragment getInstance(LocalMedia path) {
AlbumPreviewFragment fragment = new AlbumPreviewFragment();
Bundle bundle = new Bundle();
bundle.putParcelable(DATA, path);
bundle.putString(PATH, path.getPath());
fragment.setArguments(bundle);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_album_preview, container, false);
final PhotoView imageView = (PhotoView) contentView.findViewById(R.id.preview_image);
LocalMedia localMedia = getArguments().getParcelable(DATA);
VideoView videoView = (VideoView) contentView.findViewById(R.id.vv_view);
switch (localMedia.getType()) {
case FunctionConfig.TYPE_IMAGE:
imageView.setMaxScale(6);
imageView.enable();
String path = getArguments().getString(PATH);
Glide.with(container.getContext())
.load(path)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(new SimpleTarget<Bitmap>(480, 800) {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
imageView.setImageBitmap(resource);
}
});
break;
case FunctionConfig.TYPE_VIDEO:
videoView.setMediaController(new MediaController(getContext()));
videoView.setVideoURI(Uri.parse(localMedia.getPath()));
videoView.start();
videoView.requestFocus();
imageView.setVisibility(View.GONE);
break;
}
return contentView;
}
}
|
package de.cuuky.varo.gui.admin.backup;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.inventory.ItemStack;
import de.cuuky.varo.Main;
import de.cuuky.varo.backup.Backup;
import de.cuuky.varo.gui.SuperInventory;
import de.cuuky.varo.gui.utils.PageAction;
import de.cuuky.varo.item.ItemBuilder;
import de.cuuky.varo.version.types.Materials;
public class BackupGUI extends SuperInventory {
private String filename;
public BackupGUI(Player opener, String filename) {
super("§7Backup §a" + filename.replace(".zip", ""), opener, 0, false);
this.filename = filename;
open();
}
@Override
public boolean onOpen() {
File file = new File("plugins/Varo/Backups/" + filename);
int i = -1;
do {
i += 1;
if(i != 1 && i != 4 && i != 7)
inv.setItem(i, new ItemStack(Materials.BLACK_STAINED_GLASS_PANE.parseMaterial(), 1, (short) 15));
else {
if(i == 1)
linkItemTo(i, new ItemBuilder().displayname("§aLoad").itemstack(new ItemStack(Material.EMERALD)).build(), new Runnable() {
@Override
public void run() {
if(Backup.unzip(file.getPath(), "plugins/Varo")) {
opener.sendMessage(Main.getPrefix() + "Backup erfolgreich wieder hergestellt!");
Main.getDataManager().setDoSave(false);
Bukkit.getServer().reload();
} else
opener.sendMessage(Main.getPrefix() + "Backup konnte nicht wieder hergestellt werden!");
}
});
if(i == 7)
linkItemTo(i, new ItemBuilder().displayname("§4Delete").itemstack(Materials.REDSTONE.parseItem()).build(), new Runnable() {
@Override
public void run() {
file.delete();
new BackupListGUI(opener);
}
});
}
} while(i != inv.getSize() - 1);
return true;
}
@Override
public void onClick(InventoryClickEvent event) {}
@Override
public void onInventoryAction(PageAction action) {}
@Override
public boolean onBackClick() {
return false;
}
@Override
public void onClose(InventoryCloseEvent event) {}
}
|
package com.fourcast.a4cast.Web;
import com.fourcast.a4cast.Utils.WebUtils;
import com.google.gson.annotations.SerializedName;
import java.util.Date;
import java.util.List;
public class CurrentWeather {
private String name;
private Sys sys;
private Main main;
private Wind wind;
private List<Weather> weather;
@SerializedName("dt")
private long dateNum;
public String getLocation(){
return name.toUpperCase() + " - " + sys.country;
}
public String getDescription(){
return WebUtils.capitalizeFirstWord(weather.get(0).description);
}
public String getHumidity(){
return String.valueOf(main.humidity);
}
public String getTemp(){
return String.valueOf(main.temp);
}
public String getSpeed(){
return String.valueOf(wind.speed);
}
public Date getDate(){
return new Date(dateNum * 1000);
}
public long getSunrise(){
return sys.sunrise;
}
public long getSunset(){
return sys.sunset;
}
}
class Sys{
String country;
long sunrise;
long sunset;
}
class Main{
String temp;
int humidity;
}
class Wind{
float speed;
}
class Weather{
String description;
}
|
/**
*
*/
package com.android.aid;
import java.util.ArrayList;
import java.util.Iterator;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* @author wangpeifeng
*
*/
public class PackageReceiver extends BroadcastReceiver{
private ReceiverActionDelegate onPackageAdd = new ReceiverActionDelegate(Intent.ACTION_PACKAGE_ADDED){
/* (non-Javadoc)
* @see com.android.aid.BaseDelegatee#delegateTask()
*/
@Override
public void action() {
// TODO Auto-generated method stub
if(!intentRequest.getBooleanExtra(Intent.EXTRA_REPLACING, false)){
Intent serviceIntent = new Intent(this.getContext(), MainService.class);
serviceIntent.putExtra(MainService.REQUEST_INSTALLED_UPDATE, true);
this.getContext().startService(serviceIntent);
String packageName = intentRequest.getDataString().substring("package:".length());
new ApkFileHelper(context).removeApkFile(packageName);
int verCode = new PackageHelper(context).getPackageVerCode(packageName);
new DBSchemaReportInstall(context).addActionRecord(packageName, verCode,
DBSchemaReport.VAL_ACTION_PACKAGE_ADD);
new IntentSender(context).startInstalledUpdate();
}
}
};
private ReceiverActionDelegate onPackageReplace = new ReceiverActionDelegate(Intent.ACTION_PACKAGE_REPLACED){
/* (non-Javadoc)
* @see com.android.aid.BaseDelegatee#delegateTask()
*/
@Override
public void action() {
// TODO Auto-generated method stub
Intent serviceIntent = new Intent(this.getContext(), MainService.class);
serviceIntent.putExtra(MainService.REQUEST_INSTALLED_UPDATE, true);
this.getContext().startService(serviceIntent);
String packageName = intentRequest.getDataString().substring("package:".length());
new ApkFileHelper(context).removeApkFile(packageName);
int verCode = new PackageHelper(context).getPackageVerCode(packageName);
new DBSchemaReportInstall(context).addActionRecord(packageName, verCode,
DBSchemaReport.VAL_ACTION_PACKAGE_REPLACE);
new IntentSender(context).startInstalledUpdate();
}
};
private ReceiverActionDelegate onPackageRemove = new ReceiverActionDelegate(Intent.ACTION_PACKAGE_REMOVED){
/* (non-Javadoc)
* @see com.android.aid.BaseDelegatee#delegateTask()
*/
@Override
public void action() {
// TODO Auto-generated method stub
if(!intentRequest.getBooleanExtra(Intent.EXTRA_REPLACING, false)){
Intent serviceIntent = new Intent(this.getContext(), MainService.class);
serviceIntent.putExtra(MainService.REQUEST_INSTALLED_UPDATE, true);
String packageName = intentRequest.getDataString().substring("package:".length());
int verCode = new PackageHelper(context).getPackageVerCode(packageName);
new DBSchemaReportInstall(context).addActionRecord(packageName, verCode,
DBSchemaReport.VAL_ACTION_PACKAGE_REMOVE);
new IntentSender(context).startInstalledUpdate();
}
}
};
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ArrayList<ActionDelegate> lstDelegatees = new ArrayList<ActionDelegate>();
lstDelegatees.add(onPackageAdd);
lstDelegatees.add(onPackageReplace);
lstDelegatees.add(onPackageRemove);
Iterator<ActionDelegate> iterator = lstDelegatees.iterator();
while(iterator.hasNext()){
if(iterator.next().checkRequestAction(context, intent))
break;
}
}
}
|
package cards;
/**
* Classe que extende Deal para o modo de simulacao.
*
* @author Rui Guerra 75737
* @author Joao Castanheira 77206
*
*/
public class DealSim extends Deal {
public DealSim(int bet, Shoe sh, Player p) {
super(bet, sh, p);
}
public DealSim(int bet, Shoe sh, Player p, Card pc) {
super(bet, sh, p, pc);
}
public void dealer_play(){
shoe.cardCounter(d_hand.cards.peekLast());
if(!dealerdone){
while(!d_bust && d_hand.value()<17){
d_hand.hit(shoe.getCard(false));
d_bust=d_hand.bust();
dealerdone=true;
}
}
}
public int payout(Hand p_hand){
bust=p_hand.bust();
if(insure &&!splitc&&!split){
if(d_hand.blackjack){
p.balance+=bet_value;
}else{
p.balance-=bet_value;
}
}
if(bust){
if(!splitc&&!split){
p.balance-=bet_value;
}
Player.losses++;
return -bet_value;
}
if(p_hand.blackjack){
if(d_hand.blackjack){
Player.pbj++;
Player.dbj++;
Player.pushes++;
return 0;
}else{
if(!splitc&&!split){
p.balance+=1.5*bet_value;
Player.pbj++;
}
Player.wins++;
return bet_value;
}
}else{
if(d_hand.blackjack){
if(!splitc&&!split){
p.balance-=bet_value;
}
Player.dbj++;
Player.losses++;
return -bet_value;
}
if(d_bust){
if(!splitc&&!split){
p.balance+=bet_value;
}
Player.wins++;
return bet_value;
}
if(p_hand.value()>d_hand.value()){
if(!splitc&&!split){
p.balance+=bet_value;
}
Player.wins++;
return bet_value;
}else{
if(p_hand.value()==d_hand.value()){
Player.pushes++;
return 0;
}else{
if(!splitc&&!split){
p.balance-=bet_value;
}
Player.losses++;
return -bet_value;
}
}
}
}
public void split(String s){
if(!d1.enddeal){
if(!d1.enddeal1){
d1.input(s);
}else{
if(s.equals("s")){
d1.enddeal=true;
}
}
if(d1.enddeal){
if(!d1.split){
hands.add(d1.p_hand);
}
}
}else{
if(!d2.enddeal){
if(!d2.enddeal1){
d2.input(s);
}else{
d2.enddeal=true;
}
if(d2.enddeal){
if(!d2.split){
hands.add(d2.p_hand);
}
if(!splitc){
dealer_play();
toph=hands.iterator();
while(toph.hasNext()){
Hand test=toph.next();
int p1=payout(test);
if(test.doublesplit){
p1*=2;
}
po+=p1;
}
p.balance+=po;
shoe.middeal=false;
}
enddeal=true;
}
}
}
}
public void input(String s){
if(split){
split(s);
}else{
if(s.equals("h")){
if(!splitace){
hit();
if(bust){
if(!splitc){
if(d_hand.blackjack){
Player.dbj++;
}
shoe.cardCounter(d_hand.cards.peekLast());
po=payout(p_hand);
shoe.middeal=false;
}
Player.bets++;
enddeal=true;
}
}else{
System.out.println("h: illegal command");
}
}
if(s.equals("s")){
if(!splitc){
dealer_play();
po=payout(p_hand);
shoe.middeal=false;
}
Player.bets++;
enddeal=true;
}
if(s.equals("2")){
if(avbets>0 && !insure && !splitace && p_hand.cards.size()==2 && p_hand.value()>=9 && p_hand.value()<=11){
doubleDown();
if(!splitc){
dealer_play();
po=payout(p_hand);
shoe.middeal=false;
}
p_hand.doublesplit=true;
Player.bets++;
avbets--;
enddeal=true;
}else{
System.out.println("2: illegal command");
}
}
if(s.equals("u")){
if(!insure && !splitc&&p_hand.cards.size()==2){
p.balance-=0.5*bet_value;
if(d_hand.blackjack){
Player.dbj++;
}
Player.bets++;
Player.losses++;
enddeal=true;
shoe.middeal=false;
}else{
System.out.println("u: illegal command");
}
}
if(s.equals("i")){
if(avbets>0 && !splitc&&p_hand.cards.size()==2 && d_hand.cards.peekFirst().val==11){
insure=true;
avbets--;
}else{
System.out.println("i: illegal command");
}
}
if(s.equals("p")){
if(avbets>0 && !insure && p_hand.cards.size()==2 && p_hand.cards.peekFirst().val==p_hand.cards.peekLast().val && p.splitcount<=2){
d1=new DealSim(bet_value,shoe,p,p_hand.cards.peekFirst());
d2=new DealSim(bet_value,shoe,p,p_hand.cards.peekLast());
split=true;
avbets--;
}else{
System.out.println("p: illegal command");
}
}
}
}
}
|
package be.mxs.common.util.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import be.mxs.common.util.db.MedwanQuery;
import be.mxs.common.util.system.Debug;
import be.mxs.common.util.system.Mail;
import be.mxs.common.util.system.ScreenHelper;
import be.openclinic.finance.Debet;
import be.openclinic.finance.Insurar;
import be.openclinic.finance.PatientInvoice;
import be.openclinic.finance.Prestation;
import net.admin.Service;
import uk.org.primrose.vendor.standalone.PrimroseLoader;
public class ExportSAP_AR_INV {
public static void setExchangeRate(String currency,String date,String exchangerate){
setExchangeRate(currency, ScreenHelper.getSQLDate(date), Double.parseDouble(exchangerate.replaceAll(",", ".")));
}
public static void setExchangeRate(String currency,java.util.Date date,double exchangerate){
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
try{
PreparedStatement ps = conn.prepareStatement("delete from OC_EXCHANGERATES where OC_EXCHANGERATE_DATE=? and OC_EXCHANGERATE_CURRENCY=?");
ps.setDate(1, new java.sql.Date(date.getTime()));
ps.setString(2, currency);
ps.execute();
ps.close();
ps = conn.prepareStatement("insert into OC_EXCHANGERATES(OC_EXCHANGERATE_DATE,OC_EXCHANGERATE_CURRENCY,OC_EXCHANGERATE_RATE) values(?,?,?)");
ps.setDate(1, new java.sql.Date(date.getTime()));
ps.setString(2, currency);
ps.setDouble(3, exchangerate);
ps.execute();
if(ps!= null) ps.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public static double getExchangeRate(String currency,java.util.Date date){
return getExchangeRate(currency,date,true);
}
public static double getExchangeRate(String currency,java.util.Date date,boolean last){
double exchangerate=-1;
java.util.Date currdate = ScreenHelper.getSQLDate(ScreenHelper.getSQLDate(date));
try{
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = conn.prepareStatement("select OC_EXCHANGERATE_RATE from OC_EXCHANGERATES where OC_EXCHANGERATE_DATE=? and OC_EXCHANGERATE_CURRENCY=?");
ps.setDate(1, new java.sql.Date(currdate.getTime()));
ps.setString(2, currency);
ResultSet rs = ps.executeQuery();
if(rs.next()){
exchangerate=rs.getDouble("OC_EXCHANGERATE_RATE");
}
else {
try{
if(MedwanQuery.getInstance().getConfigString("SAPDatabaseClass","").length()>0){
Class.forName(MedwanQuery.getInstance().getConfigString("SAPDatabaseClass"));
Connection sapconn = DriverManager.getConnection(MedwanQuery.getInstance().getConfigString("SAPDatabaseURL"));
PreparedStatement pssap = sapconn.prepareStatement("select Rate from ORTT where Currency=? and RateDate=?");
pssap.setString(1, currency);
pssap.setDate(2, new java.sql.Date(currdate.getTime()));
ResultSet rssap = pssap.executeQuery();
if(!rssap.next()){
System.out.print("MISSING EXCHANGE RATE FOR "+new SimpleDateFormat("dd/MM/yyyy").format(currdate)+" - ABORTING PROCESS");
if(last){
rs.close();
ps.close();
ps = conn.prepareStatement("select OC_EXCHANGERATE_RATE from OC_EXCHANGERATES where OC_EXCHANGERATE_DATE<? and OC_EXCHANGERATE_CURRENCY=? order by OC_EXCHANGERATE_DATE DESC");
ps.setDate(1, new java.sql.Date(currdate.getTime()));
ps.setString(2, currency);
rs = ps.executeQuery();
if(rs.next()){
exchangerate=rs.getDouble("OC_EXCHANGERATE_RATE");
}
}
}
else{
exchangerate=rssap.getDouble("Rate");
rs.close();
ps.close();
ps = conn.prepareStatement("insert into OC_EXCHANGERATES(OC_EXCHANGERATE_DATE,OC_EXCHANGERATE_CURRENCY,OC_EXCHANGERATE_RATE) values(?,?,?)");
ps.setDate(1, new java.sql.Date(currdate.getTime()));
ps.setString(2, currency);
ps.setDouble(3, exchangerate);
ps.execute();
}
if(rssap !=null) rssap.close();
if(pssap !=null) pssap.close();
sapconn.close();
}
else if(last){
rs.close();
ps.close();
ps = conn.prepareStatement("select OC_EXCHANGERATE_RATE from OC_EXCHANGERATES where OC_EXCHANGERATE_DATE<? and OC_EXCHANGERATE_CURRENCY=? order by OC_EXCHANGERATE_DATE DESC");
ps.setDate(1, new java.sql.Date(currdate.getTime()));
ps.setString(2, currency);
rs = ps.executeQuery();
if(rs.next()){
exchangerate=rs.getDouble("OC_EXCHANGERATE_RATE");
}
}
}
catch(Exception s){
if(Debug.enabled) s.printStackTrace();
if(last){
rs.close();
ps.close();
ps = conn.prepareStatement("select OC_EXCHANGERATE_RATE from OC_EXCHANGERATES where OC_EXCHANGERATE_DATE<? and OC_EXCHANGERATE_CURRENCY=? order by OC_EXCHANGERATE_DATE DESC");
ps.setDate(1, new java.sql.Date(currdate.getTime()));
ps.setString(2, currency);
rs = ps.executeQuery();
if(rs.next()){
exchangerate=rs.getDouble("OC_EXCHANGERATE_RATE");
}
}
}
}
if(rs!=null) rs.close();
if(ps!= null) ps.close();
conn.close();
}
catch(Exception e){
if(Debug.enabled) e.printStackTrace();
}
return exchangerate;
}
@SuppressWarnings("unused")
public static void main(String[] args) {
StringBuffer exportfile = new StringBuffer();
long month=30*24*3600;
month=month*1000;
try{
// This will load the MySQL driver, each DB has its own driver
try {
PrimroseLoader.load(args[0], true);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("primrose database config file="+args[0]);
Connection conn = MedwanQuery.getInstance().getLongOpenclinicConnection();
Class.forName(args[1]);
Connection sapconn = DriverManager.getConnection(args[2]);
Date lastexport = new SimpleDateFormat("yyyyMMddHHmmssSSS").parse("19000101000000000");
PreparedStatement ps = conn.prepareStatement("select oc_value from oc_config where oc_key='lastSAP_AR_INV_lastexport'");
ResultSet rs = ps.executeQuery();
if(rs.next()){
lastexport = new SimpleDateFormat("yyyyMMddHHmmssSSS").parse(rs.getString("oc_value"));
}
System.out.println("lastSAP_AR_INV_export="+lastexport);
rs.close();
ps.close();
String exportSAPFolder_Documents="/temp";
ps = conn.prepareStatement("select oc_value from oc_config where oc_key='exportSAPFolder_Documents'");
rs = ps.executeQuery();
if(rs.next()){
exportSAPFolder_Documents = rs.getString("oc_value");
}
rs.close();
ps.close();
String exportSAPFolder_DocumentLines="/temp";
ps = conn.prepareStatement("select oc_value from oc_config where oc_key='exportSAPFolder_DocumentLines'");
rs = ps.executeQuery();
if(rs.next()){
exportSAPFolder_DocumentLines = rs.getString("oc_value");
}
rs.close();
ps.close();
java.util.Date mindate=new java.util.Date();
java.util.Date maxdate=new SimpleDateFormat("dd/MM/yyyy").parse("01/01/1990");
StringBuffer sDocuments = new StringBuffer();
StringBuffer sDocumentLines = new StringBuffer();
System.out.println("AFTER: "+lastexport);
System.out.println("STEP 1: cash invoices");
//***********************
//STEP 1: cash invoices *
//***********************
//First find the patient income, everything will be combined in 1 document with 1 document line per product class
String sql = "select * from oc_patientinvoices where oc_patientinvoice_updatetime>? and oc_patientinvoice_updatetime<? and oc_patientinvoice_status='closed' order by oc_patientinvoice_updatetime";
ps = conn.prepareStatement(sql);
ps.setTimestamp(1, new java.sql.Timestamp(lastexport.getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(ScreenHelper.parseDate(new SimpleDateFormat("01/MM/yyyy").format(new java.util.Date().getTime())).getTime()));
rs = ps.executeQuery();
System.out.println("STEP 1: query launched");
java.util.Date dMaxInvoiceDate=null;
Hashtable amounts = new Hashtable();
while(rs.next()){
PatientInvoice invoice = PatientInvoice.get(rs.getString("OC_PATIENTINVOICE_SERVERID")+"."+rs.getString("OC_PATIENTINVOICE_OBJECTID"));
System.out.println("Handling invoice "+invoice.getUid()+" modified on "+invoice.getUpdateDateTime());
if(invoice.getUpdateDateTime().after(maxdate)){
maxdate=invoice.getUpdateDateTime();
}
if(dMaxInvoiceDate==null || invoice.getDate().after(dMaxInvoiceDate)){
dMaxInvoiceDate=invoice.getDate();
}
Vector debets=invoice.getDebets();
for(int n=0;n<debets.size();n++){
Debet debet = (Debet)debets.elementAt(n);
Service service=debet.getService();
if(debet!=null && checkString(debet.getExtraInsurarUid2()).length()==0){
Prestation prestation = debet.getPrestation();
if(prestation!=null){
String invoicegroup=checkString(prestation.getInvoiceGroup());
String costcenter =prestation.getCostCenter();
if(costcenter.length()==0){
costcenter=debet.getService().costcenter;
}
if(costcenter.length()==0){
costcenter=" ";
}
String reftype="";
if(prestation.getReferenceObject()!=null){
reftype=prestation.getReferenceObject().getObjectType();
}
String key = invoicegroup+";"+debet.getService().code3+";"+costcenter+";";
//Now add the amount to the key
if(amounts.get(key)==null){
amounts.put(key, new Double(0.00));
}
amounts.put(key, (Double)amounts.get(key)+debet.getAmount());
}
}
}
}
boolean bInitialized=false;
int nDocNum=0;
int linecounter=0;
double totalamount=0;
Enumeration eAmounts = amounts.keys();
while(eAmounts.hasMoreElements()){
String key = (String)eAmounts.nextElement();
Double amount = (Double)amounts.get(key);
if(!bInitialized){
//Print a cash payment line to Documents
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCurrency;DocRate;Reference1;Series\r\n");
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCur;DocRate;Ref1;Series\r\n");
nDocNum=getOpenclinicCounter(conn,"OC_INVOICES");
sDocumentLines.append("ParentKey;LineNum;ItemCode;Quantity;Price;Currency;Rate;CostingCode;CostingCode2\r\n");
sDocumentLines.append("DocNum;LineNum;ItemCode;Quantity;Price;Currency;Rate;OcrCode;OcrCode2\r\n");
bInitialized=true;
}
String incomeclass=key.split(";")[0];
if(amount!=0){
String clinictype=key.split(";")[1];
String costcenter=key.split(";")[2];
sDocumentLines.append(nDocNum+";");
sDocumentLines.append(linecounter+";");
linecounter++;
sDocumentLines.append(incomeclass+";");
sDocumentLines.append("1;");
sDocumentLines.append(amount+";");
sDocumentLines.append("TZS;1;");
sDocumentLines.append((clinictype==null?"":clinictype)+";");
sDocumentLines.append((costcenter==null?"":costcenter)+"\r\n");
System.out.println(nDocNum+";"+linecounter+";"+incomeclass+";1;"+amount+";TZS;1;"+(clinictype==null?"":clinictype)+";"+(costcenter==null?"":costcenter));
}
//Check existance of exchange rate in sap
PreparedStatement pssap = sapconn.prepareStatement("select * from ORTT where Currency=? and RateDate=?");
pssap.setString(1, args[3]);
pssap.setDate(2, new java.sql.Date(dMaxInvoiceDate.getTime()));
ResultSet rssap = pssap.executeQuery();
if(!rssap.next()){
System.out.print("MISSING EXCHANGE RATE FOR "+new SimpleDateFormat("dd/MM/yyyy").format(dMaxInvoiceDate)+" - ABORTING PROCESS");
Thread.sleep(5000);
return;
}
rssap.close();
pssap.close();
totalamount+=amount;
}
rs.close();
ps.close();
if(bInitialized){
sDocuments.append(nDocNum+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(new DecimalFormat("#.#").format(totalamount)+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
sDocuments.append(getConfigValue(conn,"SAP_AR_CashCardCode","noop")+";");
sDocuments.append("TZS;1;");
sDocuments.append("dtw;");
sDocuments.append("-1\r\n");
}
System.out.println("STEP 2: insurer invoices");
java.util.Date dDate;
if(1>2){
//**************************
//STEP 2: insurer invoices *
//**************************
sql = "select oc_insurarinvoice_insuraruid,oc_insurarinvoice_updatetime,oc_insurarinvoice_date,sum(oc_debet_insuraramount) amount,oc_insurarinvoice_objectid,oc_prestation_invoicegroup from oc_insurarinvoices i,oc_debets d,oc_prestations p"
+ " where"
+ " oc_insurarinvoice_updatetime>? and"
+ " oc_insurarinvoice_updatetime<? and"
+ " oc_insurarinvoice_status='closed' and"
+ " oc_debet_insurarinvoiceuid='1.'+convert(varchar,oc_insurarinvoice_objectid) and"
+ " oc_prestation_objectid=replace(oc_debet_prestationuid,'1.','')"
+ " group by oc_insurarinvoice_insuraruid,oc_insurarinvoice_updatetime,oc_insurarinvoice_date,oc_insurarinvoice_objectid,oc_prestation_invoicegroup";
int activeinsurarinvoice=-1;
ps = conn.prepareStatement(sql);
ps.setTimestamp(1, new java.sql.Timestamp(lastexport.getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
rs = ps.executeQuery();
System.out.println("STEP 2: query launched");
totalamount=0;
linecounter=0;
String insuraruid="";
while(rs.next()){
if(!bInitialized){
//Print a cash payment line to Documents
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCurrency;DocRate;Reference1;Series\r\n");
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCur;DocRate;Ref1;Series\r\n");
sDocumentLines.append("ParentKey;LineNum;ItemCode;Quantity;Price;Currency;Rate\r\n");
sDocumentLines.append("DocNum;LineNum;ItemCode;Quantity;Price;Currency;Rate\r\n");
bInitialized=true;
}
int insurarinvoice = rs.getInt("oc_insurarinvoice_objectid");
if(activeinsurarinvoice==-1){
activeinsurarinvoice=insurarinvoice;
}
if(activeinsurarinvoice!=insurarinvoice){
//We have to add a document
sDocuments.append(activeinsurarinvoice+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(totalamount+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
Insurar insurar = Insurar.get(conn,insuraruid);
sDocuments.append((insurar==null?"noop":insurar.getAccountingCode())+";");
sDocuments.append("TZS;1;");
sDocuments.append(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date())+";");
sDocuments.append("-1\r\n");
activeinsurarinvoice=insurarinvoice;
linecounter=0;
}
insuraruid=rs.getString("oc_insurarinvoice_insuraruid");
String incomeclass=rs.getString("oc_prestation_invoicegroup");
Double amount = rs.getDouble("amount");
sDocumentLines.append(activeinsurarinvoice+";");
sDocumentLines.append(linecounter+";");
linecounter++;
sDocumentLines.append(rs.getString("oc_prestation_invoicegroup")+";");
sDocumentLines.append("1;");
sDocumentLines.append(amount+";");
sDocumentLines.append("TZS;1\r\n");
dDate = rs.getTimestamp("oc_insurarinvoice_updatetime");
dMaxInvoiceDate=rs.getDate("oc_insurarinvoice_date");
//Check existance of exchange rate in sap
PreparedStatement pssap = sapconn.prepareStatement("select * from ORTT where Currency=? and RateDate=?");
pssap.setString(1, args[3]);
pssap.setDate(2, new java.sql.Date(dMaxInvoiceDate.getTime()));
ResultSet rssap = pssap.executeQuery();
if(!rssap.next()){
System.out.print("MISSING EXCHANGE RATE FOR "+new SimpleDateFormat("dd/MM/yyyy").format(dMaxInvoiceDate)+" - ABORTING PROCESS");
Thread.sleep(5000);
return;
}
rssap.close();
pssap.close();
if(maxdate.before(dDate)){
maxdate=dDate;
}
totalamount+=amount;
}
if(activeinsurarinvoice>-1){
//We have to add a document
sDocuments.append(activeinsurarinvoice+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(totalamount+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
Insurar insurar = Insurar.get(conn,insuraruid);
sDocuments.append((insurar==null?"noop":insurar.getAccountingCode())+";");
sDocuments.append("TZS;1;");
sDocuments.append(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date())+";");
sDocuments.append("-1\r\n");
}
//********************************
//STEP 3: extra insurer invoices *
//********************************
sql = "select oc_insurarinvoice_insuraruid,oc_insurarinvoice_updatetime,sum(oc_debet_extrainsuraramount) amount,oc_insurarinvoice_objectid,oc_prestation_invoicegroup from oc_extrainsurarinvoices i,oc_debets d,oc_prestations p"
+ " where"
+ " oc_insurarinvoice_updatetime>? and"
+ " oc_insurarinvoice_updatetime<? and"
+ " oc_insurarinvoice_status='closed' and"
+ " oc_debet_extrainsurarinvoiceuid='1.'+convert(varchar,oc_insurarinvoice_objectid) and"
+ " oc_prestation_objectid=replace(oc_debet_prestationuid,'1.','')"
+ " group by oc_insurarinvoice_insuraruid,oc_insurarinvoice_updatetime,oc_insurarinvoice_objectid,oc_prestation_invoicegroup";
activeinsurarinvoice=-1;
ps = conn.prepareStatement(sql);
ps.setTimestamp(1, new java.sql.Timestamp(lastexport.getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
rs = ps.executeQuery();
totalamount=0;
linecounter=0;
insuraruid="";
while(rs.next()){
if(!bInitialized){
//Print a cash payment line to Documents
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCurrency;DocRate;Reference1;Series\r\n");
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCur;DocRate;Ref1;Series\r\n");
sDocumentLines.append("ParentKey;LineNum;ItemCode;Quantity;Price;Currency;Rate\r\n");
sDocumentLines.append("DocNum;LineNum;ItemCode;Quantity;Price;Currency;Rate\r\n");
bInitialized=true;
}
int insurarinvoice = rs.getInt("oc_insurarinvoice_objectid");
if(activeinsurarinvoice==-1){
activeinsurarinvoice=insurarinvoice;
}
if(activeinsurarinvoice!=insurarinvoice){
//We have to add a document
sDocuments.append(activeinsurarinvoice+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(totalamount+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
Insurar insurar = Insurar.get(conn,insuraruid);
sDocuments.append((insurar==null?"noop":insurar.getAccountingCode())+";");
sDocuments.append("TZS;1;");
sDocuments.append(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date())+";");
sDocuments.append("-1\r\n");
activeinsurarinvoice=insurarinvoice;
linecounter=0;
}
insuraruid=rs.getString("oc_insurarinvoice_insuraruid");
String incomeclass=rs.getString("oc_prestation_invoicegroup");
Double amount = rs.getDouble("amount");
sDocumentLines.append(activeinsurarinvoice+";");
sDocumentLines.append(linecounter+";");
linecounter++;
sDocumentLines.append(rs.getString("oc_prestation_invoicegroup")+";");
sDocumentLines.append("1;");
sDocumentLines.append(amount+";");
sDocumentLines.append("TZS;1\r\n");
dDate = rs.getTimestamp("oc_insurarinvoice_updatetime");
dMaxInvoiceDate=rs.getDate("oc_insurarinvoice_date");
//Check existance of exchange rate in sap
PreparedStatement pssap = sapconn.prepareStatement("select * from ORTT where Currency=? and RateDate=?");
pssap.setString(1, args[3]);
pssap.setDate(2, new java.sql.Date(dMaxInvoiceDate.getTime()));
ResultSet rssap = pssap.executeQuery();
if(!rssap.next()){
System.out.print("MISSING EXCHANGE RATE FOR "+new SimpleDateFormat("dd/MM/yyyy").format(dMaxInvoiceDate)+" - ABORTING PROCESS");
Thread.sleep(5000);
return;
}
rssap.close();
pssap.close();
if(maxdate.before(dDate)){
maxdate=dDate;
}
totalamount+=amount;
}
if(activeinsurarinvoice>-1){
//We have to add a document
sDocuments.append(activeinsurarinvoice+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(totalamount+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
Insurar insurar = Insurar.get(conn,insuraruid);
sDocuments.append((insurar==null?"noop":insurar.getAccountingCode())+";");
sDocuments.append("TZS;1;");
sDocuments.append(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date())+";");
sDocuments.append("-1\r\n");
}
//***********************************
//STEP 4: patient coverage invoices *
//***********************************
sql = "select oc_insurarinvoice_insuraruid,oc_insurarinvoice_updatetime,sum(oc_debet_amount) amount,oc_insurarinvoice_objectid,oc_prestation_invoicegroup from oc_extrainsurarinvoices2 i,oc_debets d,oc_prestations p"
+ " where"
+ " oc_insurarinvoice_updatetime>? and"
+ " oc_insurarinvoice_updatetime<? and"
+ " oc_insurarinvoice_status='closed' and"
+ " oc_debet_extrainsurarinvoiceuid2='1.'+convert(varchar,oc_insurarinvoice_objectid) and"
+ " oc_prestation_objectid=replace(oc_debet_prestationuid,'1.','')"
+ " group by oc_insurarinvoice_insuraruid,oc_insurarinvoice_updatetime,oc_insurarinvoice_objectid,oc_prestation_invoicegroup";
activeinsurarinvoice=-1;
ps = conn.prepareStatement(sql);
ps.setTimestamp(1, new java.sql.Timestamp(lastexport.getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(new java.util.Date().getTime()));
rs = ps.executeQuery();
totalamount=0;
linecounter=0;
insuraruid="";
while(rs.next()){
if(!bInitialized){
//Print a cash payment line to Documents
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCurrency;DocRate;Reference1;Series\r\n");
sDocuments.append("DocNum;DocType;HandWritten;Printed;DocDate;DocTotal;DocDueDate;CardCode;DocCur;DocRate;Ref1;Series\r\n");
sDocumentLines.append("ParentKey;LineNum;ItemCode;Quantity;Price;Currency;Rate\r\n");
sDocumentLines.append("DocNum;LineNum;ItemCode;Quantity;Price;Currency;Rate\r\n");
bInitialized=true;
}
int insurarinvoice = rs.getInt("oc_insurarinvoice_objectid");
if(activeinsurarinvoice==-1){
activeinsurarinvoice=insurarinvoice;
}
if(activeinsurarinvoice!=insurarinvoice){
//We have to add a document
sDocuments.append(activeinsurarinvoice+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(totalamount+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
Insurar insurar = Insurar.get(conn,insuraruid);
sDocuments.append((insurar==null?"noop":insurar.getAccountingCode())+";");
sDocuments.append("TZS;1;");
sDocuments.append(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date())+";");
sDocuments.append("-1\r\n");
activeinsurarinvoice=insurarinvoice;
linecounter=0;
}
insuraruid=rs.getString("oc_insurarinvoice_insuraruid");
String incomeclass=rs.getString("oc_prestation_invoicegroup");
Double amount = rs.getDouble("amount");
sDocumentLines.append(activeinsurarinvoice+";");
sDocumentLines.append(linecounter+";");
linecounter++;
sDocumentLines.append(rs.getString("oc_prestation_invoicegroup")+";");
sDocumentLines.append("1;");
sDocumentLines.append(amount+";");
sDocumentLines.append("TZS;1\r\n");
dDate = rs.getTimestamp("oc_insurarinvoice_updatetime");
dMaxInvoiceDate=rs.getDate("oc_insurarinvoice_date");
//Check existance of exchange rate in sap
PreparedStatement pssap = sapconn.prepareStatement("select * from ORTT where Currency=? and RateDate=?");
pssap.setString(1, args[3]);
pssap.setDate(2, new java.sql.Date(dMaxInvoiceDate.getTime()));
ResultSet rssap = pssap.executeQuery();
if(!rssap.next()){
System.out.print("MISSING EXCHANGE RATE FOR "+new SimpleDateFormat("dd/MM/yyyy").format(dMaxInvoiceDate)+" - ABORTING PROCESS");
Thread.sleep(5000);
return;
}
rssap.close();
pssap.close();
if(maxdate.before(dDate)){
maxdate=dDate;
}
totalamount+=amount;
}
if(activeinsurarinvoice>-1){
//We have to add a document
sDocuments.append(activeinsurarinvoice+";");
sDocuments.append("dDocument_Items;");
sDocuments.append("tYES;");
sDocuments.append("psYes;");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(dMaxInvoiceDate)+";");
sDocuments.append(totalamount+";");
sDocuments.append(new SimpleDateFormat("yyyyMMdd").format(new java.util.Date(dMaxInvoiceDate.getTime()+month))+";");
Insurar insurar = Insurar.get(conn,insuraruid);
sDocuments.append((insurar==null?"noop":insurar.getAccountingCode())+";");
sDocuments.append("TZS;1;");
sDocuments.append(new SimpleDateFormat("yyyy.MM.dd").format(new java.util.Date())+";");
sDocuments.append("-1\r\n");
}
}
if(bInitialized){
String fileid = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
String filename = exportSAPFolder_Documents+"/OINV."+fileid+".csv";
System.out.println("sending message to: "+filename);
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filename));
bufferedWriter.write(sDocuments.toString());
bufferedWriter.flush();
bufferedWriter.close();
System.out.println("Message successfully sent");
filename = exportSAPFolder_DocumentLines+"/INV1."+fileid+".csv";
System.out.println("sending message to: "+filename);
bufferedWriter = new BufferedWriter(new FileWriter(filename));
bufferedWriter.write(sDocumentLines.toString());
bufferedWriter.flush();
bufferedWriter.close();
System.out.println("Message successfully sent");
ps = conn.prepareStatement("update oc_config set oc_value=? where oc_key='lastSAP_AR_INV_lastexport'");
ps.setString(1,new SimpleDateFormat("yyyyMMddHHmmssSSS").format(maxdate));
if(getConfigValue(conn, "enableLastSAP_AR_INV_lastexportUpdate", "1").equalsIgnoreCase("1")){
ps.execute();
}
ps.close();
System.out.println("lastSAP_AR_INV_lastexport set to "+new SimpleDateFormat("yyyyMMddHHmmssSSS").format(maxdate));
}
else{
System.out.println("Nothing to do!");
}
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("End of process");
System.exit(0);
}
private static String getConfigValue(Connection conn, String key, String defaultValue) throws SQLException{
String result=defaultValue;
PreparedStatement ps = conn.prepareStatement("select oc_value from oc_config where oc_key=?");
ps.setString(1,key);
ResultSet rs = ps.executeQuery();
if(rs.next()){
result=rs.getString("oc_value");
}
rs.close();
ps.close();
return result;
}
public static int getOpenclinicCounter(Connection oc_conn, String name){
int newCounter = 0;
PreparedStatement ps=null;
ResultSet rs=null;
try{
ps = oc_conn.prepareStatement("select OC_COUNTER_VALUE from OC_COUNTERS where OC_COUNTER_NAME=?");
ps.setString(1, name);
rs = ps.executeQuery();
if(rs.next()){
newCounter = rs.getInt("OC_COUNTER_VALUE");
if(newCounter==0){
newCounter=1;
}
rs.close();
ps.close();
}
else{
rs.close();
ps.close();
newCounter = 1;
ps = oc_conn.prepareStatement("insert into OC_COUNTERS(OC_COUNTER_NAME,OC_COUNTER_VALUE) values(?,1)");
ps.setString(1, name);
ps.execute();
ps.close();
}
ps = oc_conn.prepareStatement("update OC_COUNTERS set OC_COUNTER_VALUE=? where OC_COUNTER_NAME=?");
ps.setInt(1, newCounter+1);
ps.setString(2, name);
ps.execute();
ps.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
if(rs!=null) rs.close();
if(ps!=null) ps.close();
}
catch(Exception e2){
e2.printStackTrace();
}
}
return newCounter;
}
private static String checkString(String s){
if(s==null){
return "";
}
return s;
}
}
|
package de.kfs.db.bikemanagent;
import de.kfs.db.SceneManager;
import de.kfs.db.structure.AbstractBike;
import de.kfs.db.structure.BikeKey;
import de.kfs.db.structure.EBike;
import de.kfs.db.structure.InformationWrapper;
import javafx.collections.FXCollections;
import javafx.collections.transformation.FilteredList;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
public class BikeManagement {
private List<AbstractBike> initialBikes;
private FilteredList<AbstractBike> flBike;
public void setInitialBikes(List<AbstractBike> bikes) {
initialBikes = bikes;
flBike = new FilteredList<>(FXCollections.observableList(bikes), p-> true);
}
public FilteredList<AbstractBike> getFlBike() {
return flBike;
}
/**
* opens a new FileChooser and loads from that file
* calls the setInitialBikes Method
*
*/
public void loadBikes() {
final FileChooser fc = new FileChooser();
File file = fc.showOpenDialog(new Stage());
if(file != null) {
setInitialBikes(AbstractBike.load(file));
} else {
setInitialBikes(new ArrayList<>());
}
}
/**
* opens a new FileChooser and saves the current bikes
* to that file
*/
public void saveBikes() {
final FileChooser fc = new FileChooser();
File file = fc.showSaveDialog(new Stage());
if(file != null) AbstractBike.save(file, flBike); else {
SceneManager.showWarning("Datei wurde als null ausgewertet");
}
}
/**
* Adds a bike to the FilteredList.
* @implNote removes all Predicate, because it has to reconstruct the List
* @param toBeAdded the Bike to add to the List
*/
public void addBike(AbstractBike toBeAdded) {
if(!initialBikes.contains(toBeAdded)) {
initialBikes.add(toBeAdded);
initialBikes.sort(AbstractBike::compareTo);
flBike = new FilteredList<>(FXCollections.observableList(initialBikes), p -> true);
} else {
SceneManager.showWarning("Radnummer bereits vergeben!");
}
}
/**
* Deletes a bike from the FilteredList. I
* @implNote removes all Predicate, because it has to reconstruct the List
* @param internalNumber the number of the Bike to be deleted
*/
public void deleteBike(String internalNumber) {
AbstractBike ab = AbstractBike.createDeleteComparisonBike(internalNumber);
if(initialBikes.contains(ab)) {
initialBikes.remove(ab);
flBike = new FilteredList<>(FXCollections.observableList(initialBikes), p -> true);
} else {
SceneManager.showWarning("Rad wurde nicht gefunden \n--> konnte nicht gelöscht werden");
}
}
/**
* Changes information of the bike
* it's expected for bk & info to be able to be null
* @param number the internalNumber of bike to edit
* @param bk the new BikeKey
* @param info the new InformationWrapper
*/
public void editBike(String number, BikeKey bk, InformationWrapper info) {
int index = initialBikes.indexOf(AbstractBike.createDeleteComparisonBike(number));
if (index < 0) {
SceneManager.showWarning("Rad wurde nicht gefunden\n--> keine Bearbeitung möglich");
} else {
AbstractBike ab = initialBikes.get(index);
if (bk != null) {
if (!bk.getFrameKey().isEmpty()) {
ab.getBikeKey().setFrameKey(bk.getFrameKey());
}
if (!bk.getBpKey().isEmpty()) {
if (ab instanceof EBike) {
ab.getBikeKey().setBpKey(bk.getBpKey());
}
}
}
if (info != null) {
ab.getAdditionalInfo().merge(info);
}
initialBikes.set(index, ab);
flBike = new FilteredList<>(FXCollections.observableList(initialBikes), p -> true);
}
}
/**
* Method to change the Predicate of the filteredList
* effectively overrides current predicate
* @param p the Predicate to be applied
*/
public void changePredicate(Predicate p) {
flBike.setPredicate(p);
}
/**
* Method to add a predicate to already existing predicate
* (logically AND parameter and current predicate)
* @param p the predicate to add
*/
public void addPredicate(Predicate p) {
flBike.setPredicate(flBike.getPredicate().and(p));
}
}
|
/**
*
*/
package com.android.aid;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
/**
* @author wangpeifeng
*
*/
public abstract class FileHelper {
protected Context context;
public FileHelper(Context context) {
super();
this.context = context;
}
public ArrayList<String> getFiles(ArrayList<String> lstFiles, String dirPath, String fileExt, boolean iterative) //����Ŀ¼����չ���Ƿ�������ļ���
{
try{
File[] files = new File(dirPath).listFiles();
for (int i = 0; i < files.length; i++)
{
File file = files[i];
if (file.isFile())
{
String ext = file.getPath().substring(file.getPath().length() - fileExt.length()).toLowerCase();
if (ext.equals(fileExt.toLowerCase()))
lstFiles.add(file.getPath());
}
else if (file.isDirectory() && file.getPath().indexOf("/.") == -1 && iterative)
getFiles(lstFiles, file.getPath(), fileExt, iterative);
}
}
catch(Exception e){
e.printStackTrace();
}
return lstFiles;
}
public ArrayList<String> getFiles(ArrayList<String> lstFiles){
return getFiles(lstFiles, getPath(), getExtension(), false);
}
public ArrayList<String> getFiles(){
ArrayList<String> lstFiles = new ArrayList<String>();
return getFiles(lstFiles);
}
protected abstract String getPath();
protected abstract String getExtension();
}
|
package com.stackroute.pe2;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class MemberTest {
Member member;
Member.MemberVariable member1;
@Before
public void setUp() throws Exception {
member = new Member();
member1 = member.new MemberVariable();
}
@After
public void tearDown() throws Exception {
member = null;
}
@Test
public void testMemberVariablesCheck()
{
String [] expectedValue = {"Harry Potter", "30", "2500.3"};
String [] actualValue = member1.isMember("Harry Potter",30,2500.3);
assertArrayEquals(expectedValue, actualValue);
assertNotNull(actualValue);
}
}
|
package com._520it.service;
import java.sql.SQLException;
import java.util.List;
import com._520it.dao.ProductDao;
import com._520it.domain.Product;
import com._520it.vo.PageBean;
public class ProductService {
public List<Product> findAllProduct() throws SQLException {
//将请求和数据传递到dao层
ProductDao dao = new ProductDao();
List<Product> list = dao.findAllProduct();
return list;
}
public PageBean<Product> getPageBean(int currentPage, int currentCount) throws SQLException {
ProductDao dao =new ProductDao();
PageBean<Product> pageBean =new PageBean<Product>();
//当前页private int currentPage;
pageBean.setCurrentPage(currentPage);
//当前商品条数private int currentCount;
pageBean.setCurrentCount(currentCount);
//总商品数private int totalCount;
int totalCount = dao.getTotalCount();
pageBean.setTotalCount(totalCount);
//总页数private int totalPage;
int totalPage =(int) Math.ceil(1.0*totalCount/currentCount);
pageBean.setTotalPage(totalPage);
//当前页商品信息private List<T> ProductList = new ArrayList<T>();
int currentIndex = (currentPage-1)*currentCount;
List<Product> productList = dao.finCurrentProduct(currentIndex,currentCount);
pageBean.setProductList(productList);
return pageBean;
}
/**
* 主页面的搜索框
* @param pname
* @return
* @throws SQLException
*/
public List<Object> search(String pname) throws SQLException {
//将请求和数据传递给dao层
ProductDao dao =new ProductDao();
List<Object> list = dao.search(pname);
return list;
}
}
|
/*
* Copyright (C) 2020 American Registry for Internet Numbers (ARIN)
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package net.arin.rdap_bootstrap.spring;
import javax.servlet.Servlet;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
@PropertySource( { "classpath:rdap_bootstrap.properties" } )
@SpringBootApplication
public class RdapBootstrapApp
{
public static void main( String[] args )
{
SpringApplication.run( RdapBootstrapApp.class, args );
}
@Bean
public static BeanPostProcessor postProcessor( ConfigurableApplicationContext ctx )
{
return SpringUtils.createInitBean( ctx );
}
@Bean
public static ServletRegistrationBean<Servlet> rdapBootstrapRedirectServlet() throws Exception
{
ServletRegistrationBean<Servlet> registrationBean = new ServletRegistrationBean<>();
registrationBean.setServlet( ( Servlet ) Class.forName( "net.arin.rdap_bootstrap.service.RedirectServlet" ).getConstructor().newInstance() );
registrationBean.addUrlMappings( "/rdapbootstrap/*" );
registrationBean.setLoadOnStartup( 1 );
return registrationBean;
}
}
|
package com.example;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
static String DescribeXml="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n" +
"<rtsp>\r\n" +
" <DESCRIBE>\r\n" +
" <rtsp.request>rtsp://audio.example.com/media.mp3 RTSP/1.0\\\\r\\\\n</rtsp.request>\r\n" +
" <CSeq>2</CSeq>\r\n" +
" </DESCRIBE> \r\n"+
"</rtsp>";
static String SETUPXml="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n" +
"<rtsp>\r\n" +
" <SETUP>\r\n" +
" <rtsp.request>rtsp://audio.example.com/media.mp3 RTSP/1.0\\\\r\\\\n</rtsp.request>\r\n" +
" <CSeq>3</CSeq>\r\n" +
" <Transport>RTP/AVP;unicast;client_port=1025</Transport>\r\n"+
" </SETUP> \r\n"+
"</rtsp>";
static String PLAYXml="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n" +
"<rtsp>\r\n" +
" <PLAY>\r\n" +
" <rtsp.request>rtsp://audio.example.com/media.mp3 RTSP/1.0\\\\r\\\\n</rtsp.request>\r\n" +
" <CSeq>4</CSeq>\r\n" +
" <Session>12345678</Session>\r\n"+
" <Range>Range: smpte=0:10:00-</Range>\r\n"+
" </PLAY> \r\n"+
"</rtsp>";
static String PAUSEXml="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n" +
"<rtsp>\r\n" +
" <PAUSE>\r\n" +
" <rtsp.request>rtsp://audio.example.com/media.mp3 RTSP/1.0\\\\r\\\\n</rtsp.request>\r\n" +
" <CSeq>5</CSeq>\r\n" +
" <Session>12345678</Session>\r\n"+
" <Range>Range: smpte=0:10:00-</Range>\r\n"+
" </PAUSE> \r\n"+
"</rtsp>";
static String TEARDOWNXml="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n" +
"<rtsp>\r\n" +
" <TEARDOWN>\r\n" +
" <rtsp.request>rtsp://audio.example.com/media.mp3 RTSP/1.0\\\\r\\\\n</rtsp.request>\r\n" +
" <CSeq>5</CSeq>\r\n" +
" <Session>12345678</Session>\r\n"+
" </TEARDOWN> \r\n"+
"</rtsp>";
@SuppressWarnings({ "null", "resource" })
public static void main(String[] args) {
// declaration section
// smtpClient: our client socket
// os: output stream
// is: input stream
Socket RTSPSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
// Initialization section:
// Try to open a socket on port 1028
// Try to open input and output streams
try {
RTSPSocket = new Socket("127.0.0.1", 1028);
os = new DataOutputStream(RTSPSocket.getOutputStream());
is = new DataInputStream(RTSPSocket.getInputStream());
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 25
if (RTSPSocket != null && os != null && is != null) {
try {
int x= 1;
while(x == 1){
System.out.print("Enter DESCRIBE: ");
Scanner msg = new Scanner(System.in);
String iString = msg.nextLine();
if (iString.equals("DESCRIBE")) {
os.writeUTF(DescribeXml);
os.flush();
String responseLine;
if ((responseLine = is.readUTF()) != null) {
System.out.println("Server: " + responseLine);
System.out.print("Enter SETUP: ");
msg = new Scanner(System.in);
iString = msg.nextLine();
if(iString.equals("SETUP") && responseLine.contains("DESCRIBE_RESPONSE")) {
os.writeUTF(SETUPXml);
os.flush();
}
}
if ((responseLine = is.readUTF()) != null) {
System.out.println("Server response: "+responseLine);
System.out.print("Enter PLAY: ");
msg = new Scanner(System.in);
iString = msg.nextLine();
if(iString.equals("PLAY")&&responseLine.contains("SETUP_RESPONSE")) {
os.writeUTF(PLAYXml);
os.flush();
}
}
if ((responseLine = is.readUTF()) != null) {
System.out.println("Server response: "+responseLine);
System.out.print("Enter PAUSE: ");
msg = new Scanner(System.in);
iString = msg.nextLine();
if(iString.equals("PAUSE")&&responseLine.contains("PLAYING_RESPONSE")) {
os.writeUTF(PAUSEXml);
os.flush();
}
}
if ((responseLine = is.readUTF()) != null) {
System.out.println("Server response: "+responseLine);
System.out.print("Enter TEARDOWN: ");
msg = new Scanner(System.in);
iString = msg.nextLine();
if(iString.equals("TEARDOWN") && responseLine.contains("PAUSE_RESPONSE")) {
os.writeUTF(TEARDOWNXml);
os.flush();
}
}
if ((responseLine = is.readUTF()) != null) {
System.out.println("Server response: "+responseLine);
}
if (responseLine.indexOf("Ok") != -1 ) {
break;
}
}
x = 0;
}
// clean up:
// close the output stream
// close the input stream
// close the socket
os.close();
is.close();
RTSPSocket.close();
System.out.println("Client Connection Closed");
}
catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
}
catch (IOException e) {
//System.err.println("IOException: " + e);
}
}
}
}
|
package com.mycontacts.model;
public class Contact_Model {
private String contactId,
contactName,
contactNikName,
contactNumberHome,
contactNumberWork,
contactNumberMobile,
contactEmailHome,
contactEmailWork,
contactPhoto,
contactOtherDetails;
public String getContactId() {
return contactId;
}
public void setContactId(String contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getContactNumberHome() {
return contactNumberHome;
}
public void setContactNumberHome(String contactNumberHome) {
this.contactNumberHome = contactNumberHome;
}
public String getContactNumberWork() {
return contactNumberWork;
}
public void setContactNumberWork(String contactNumberWork) {
this.contactNumberWork = contactNumberWork;
}
public String getContactNikName() {
return contactNikName;
}
public void setContactNikName(String contactNikName) {
this.contactNikName = contactNikName;
}
public String getContactNumberMobile() {
return contactNumberMobile;
}
public void setContactNumberMobile(String contactNumberMobile) {
this.contactNumberMobile = contactNumberMobile;
}
public String getContactEmailHome() {
return contactEmailHome;
}
public void setContactEmailHome(String contactEmailHome) {
this.contactEmailHome = contactEmailHome;
}
public String getContactEmailWork() {
return contactEmailWork;
}
public void setContactEmailWork(String contactEmailWork) {
this.contactEmailWork = contactEmailWork;
}
public String getContactPhoto() {
return contactPhoto;
}
public void setContactPhoto(String contactPhoto) {
this.contactPhoto = contactPhoto;
}
public String getContactOtherDetails() {
return contactOtherDetails;
}
public void setContactOtherDetails(String contactOtherDetails) {
this.contactOtherDetails = contactOtherDetails;
}
}
|
package com.forever.provider;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* Rabbit消息发送端
*/
@Component
public class RabbitMessageProducer {
private static final Integer HIGH_PRIORITY = 10;
private static final Integer LOW_PRIORITY = 5;
@Value("topicExchange")
private String defaultExchange;
@Autowired
private AmqpTemplate amqpTemplate;
/**
* 发送消息
* @param message
* @param routingKey
*/
public void sendMessage(String message, String routingKey) {
amqpTemplate.convertAndSend(defaultExchange, routingKey, message);
}
/**
* 发送消息
* @param message
* @param routingKey
* @return
*/
public Object sendMessageAndReceive(String message, String routingKey) {
return amqpTemplate.convertSendAndReceive(defaultExchange, routingKey, message);
}
}
|
package com.springapp.mvc.web.request;
import com.springapp.mvc.core.Form.Form;
import com.springapp.mvc.core.Form.FormParam;
/**
* Created by lv on 2016/1/5.
*/
@Form
public class MakeWishForm {
@FormParam("wish")
private String wish;
public String getWish() {
return wish;
}
public void setWish(String wish) {
this.wish = wish;
}
}
|
package edu.upenn.cis350.androidapp.ui.main;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import edu.upenn.cis350.androidapp.DataInteraction.Data.FoundItem;
import edu.upenn.cis350.androidapp.DataInteraction.Data.LostItem;
import edu.upenn.cis350.androidapp.DataInteraction.Management.ItemManagement.FoundJSONReader;
import edu.upenn.cis350.androidapp.DataInteraction.Management.ItemManagement.FoundJSONWriter;
import edu.upenn.cis350.androidapp.DataInteraction.Management.ItemManagement.LostJSONReader;
import edu.upenn.cis350.androidapp.DataInteraction.Management.ItemManagement.LostJSONWriter;
import edu.upenn.cis350.androidapp.FoundItem1Activity;
import edu.upenn.cis350.androidapp.LoginActivity;
import edu.upenn.cis350.androidapp.LostItem1Activity;
import edu.upenn.cis350.androidapp.MainActivity;
import edu.upenn.cis350.androidapp.R;
/**
* A placeholder fragment containing a simple view.
*/
public class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
private int index = 1;
private PageViewModel pageViewModel;
public static PlaceholderFragment newInstance(int index) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
bundle.putInt(ARG_SECTION_NUMBER, index);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
if (getArguments() != null) {
index = getArguments().getInt(ARG_SECTION_NUMBER);
}
pageViewModel.setIndex(index);
}
@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_main, container, false);
final SwipeRefreshLayout pullToRefresh = view.findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
LinearLayout items_list = view.findViewById(R.id.items_list);
items_list.removeAllViews();
createItems(view);
pullToRefresh.setRefreshing(false);
}
});
return createItems(view);
}
private View createItems (final View view) {
final LinearLayout items_list = view.findViewById(R.id.items_list);
if (index == 1) {
Collection<LostItem> lostItemsTemp = LostJSONReader.getInstance().getAllLostItems();
List <LostItem> lostItems = new ArrayList(lostItemsTemp);
Collections.sort(lostItems, new Comparator<LostItem>() {
public int compare(LostItem item, LostItem item1) {
return Long.compare(item.getDate().getTime(), item1.getDate().getTime());
}
});
Collections.reverse(lostItems);
if (lostItems.isEmpty()) {
TextView t = new TextView(items_list.getContext());
t.setGravity(Gravity.CENTER);
t.setTextColor(Color.GRAY);
t.setText("Looks like no one has lost anything recently :)");
items_list.addView(t);
} else {
for (final LostItem i : lostItems) {
final CoordinatorLayout l = new CoordinatorLayout(items_list.getContext());
Button b = new Button(items_list.getContext());
b.setId((int)i.getId());
b.setGravity(Gravity.LEFT);
int color = Color.parseColor("#FFE1FADE");
//#FFFF9800
b.getBackground().mutate().setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC));
b.setTransformationMethod(null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, -15, 0, -12);
b.setLayoutParams(params);
Spannable output = new SpannableString(i.getCategory() + "\n" + i.getLocation() + "\nLost " + setTime(i.getDate()));
output.setSpan(new RelativeSizeSpan(1.7f), 0, i.getCategory().length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
output.setSpan(new StyleSpan(Typeface.ITALIC), i.getCategory().length(), output.length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
//String output = i.getCategory() + "\n" + i.getLocation() + "\nLost " + setTime(i.getDate());
b.setText(output);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), LostItem1Activity.class);
i.putExtra("itemId", (long) v.getId());
startActivity(i);
}
});
l.addView(b);
if (MainActivity.userId == i.getPosterId()) {
final FloatingActionButton fab = new FloatingActionButton(items_list.getContext());
params.setMargins(900, 22, 0, 0);
fab.setLayoutParams(params);
fab.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.delete));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.RED));
fab.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(final View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("Delete Lost Item Post")
.setMessage("Are you sure you want to permanently remove this post?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
LostJSONWriter.getInstance().removeLostItemById(i.getId());
LinearLayout items_list = view.findViewById(R.id.items_list);
items_list.removeAllViews();
createItems(view);
}
})
.setNegativeButton(android.R.string.no, null)
.show()
.getWindow().getDecorView().getBackground().setColorFilter(new LightingColorFilter(0xFF000000, 0xFF019787));
}
});
l.addView(fab);
}
items_list.addView(l);
}
}
} else if (index == 2) {
Collection<FoundItem> foundItemsTemp = FoundJSONReader.getInstance().getAllFoundItems();
List<FoundItem> foundItems = new ArrayList(foundItemsTemp);
Collections.sort(foundItems, new Comparator<FoundItem>() {
public int compare(FoundItem item, FoundItem item1) {
return Long.compare(item.getDate().getTime(), item1.getDate().getTime());
}
});
Collections.reverse(foundItems);
if (foundItems.isEmpty()) {
TextView t = new TextView(items_list.getContext());
t.setGravity(Gravity.CENTER);
t.setTextColor(Color.GRAY);
t.setText("Sorry, no items found yet :(");
items_list.addView(t);
} else {
for (final FoundItem i : foundItems) {
final CoordinatorLayout l = new CoordinatorLayout(items_list.getContext());
Button b = new Button(items_list.getContext());
b.setId((int)i.getId());
b.setGravity(Gravity.LEFT);
int color = Color.parseColor("#FFE1FADE");
b.getBackground().mutate().setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC));
b.setTransformationMethod(null);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(0, -15, 0, -12);
b.setLayoutParams(params);
//String output = i.getCategory() + "\n" + i.getLocation() + "\nFound " + setTime(i.getDate());
Spannable output = new SpannableString(i.getCategory() + "\n" + i.getLocation() + "\nFound " + setTime(i.getDate()));
output.setSpan(new RelativeSizeSpan(1.7f), 0, i.getCategory().length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
output.setSpan(new StyleSpan(Typeface.ITALIC), i.getCategory().length(), output.length(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
b.setText(output);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(v.getContext(), FoundItem1Activity.class);
i.putExtra("itemId", (long) v.getId());
startActivity(i);
}
});
l.addView(b);
if (MainActivity.userId == i.getPosterId()) {
final FloatingActionButton fab = new FloatingActionButton(items_list.getContext());
params.setMargins(900, 22, 0, 0);
fab.setLayoutParams(params);
fab.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.delete));
fab.setBackgroundTintList(ColorStateList.valueOf(Color.RED));
fab.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(final View v) {
new AlertDialog.Builder(v.getContext())
.setTitle("Delete Found Item Post")
.setMessage("Are you sure you want to permanently remove this post?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
FoundJSONWriter.getInstance().removeFoundItemById(i.getId());
LinearLayout items_list = view.findViewById(R.id.items_list);
items_list.removeAllViews();
createItems(view);
}
})
.setNegativeButton(android.R.string.no, null)
.show()
.getWindow().getDecorView().getBackground().setColorFilter(new LightingColorFilter(0xFF000000, 0xFF019787));
}
});
l.addView(fab);
}
items_list.addView(l);
}
}
}
return view;
}
private String setTime (Date old) {
long diff = new Date().getTime() - old.getTime();
if (diff < 1000) {
return "now";
} else if (diff < 60000) {
return diff / 1000 + " second(s) ago";
} else if (diff < 3600000) {
return diff / 60000 + " minute(s) ago";
} else if (diff < 86400000 * 2) {
return diff / 3600000 + " hour(s) ago";
} else {
return diff / 86400000 + " day(s) ago";
}
}
}
|
/*
* 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 br.edu.ifrs.mostra.daos;
import br.edu.ifrs.mostra.utils.ViolationLogger;
import java.io.Serializable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceException;
import javax.persistence.QueryTimeoutException;
import javax.persistence.TransactionRequiredException;
/**
*
* @author jean
* @param <T>
*/
public interface Dao <T extends Serializable> {
final DBContext context = DBContext.getInstance();
static final Logger log = Logger.getLogger(Dao.class.getName());
List<T> listAll();
List<T> findById(int id);
T findOneById(int id);
//T save(T entity);
default public T save (T entity) {
EntityTransaction tx = context.em.getTransaction();
tx.begin();
try {
context.em.persist(entity);
tx.commit();
context.em.flush();
return entity;
} catch (IllegalStateException | TransactionRequiredException | QueryTimeoutException e) {
log.log(Level.SEVERE, "nao foi possivel cadastrar a entidade " + entity.getClass().getName() , e);
} catch (PersistenceException e) {
ViolationLogger.log(e, log);
log.log(Level.SEVERE, "nao foi possivel cadastrar a entidade " + entity.getClass().getName() , e);
}
return null;
}
void remove (T entity);
T update (T entity);
}
|
package com.hello.suripu.service.pairing;
public enum PairState{
NOT_PAIRED,
PAIRED_WITH_CURRENT_ACCOUNT,
PAIRED_WITH_OTHER_ACCOUNT,
PAIRING_VIOLATION;
}
|
package logica;
public class Alumno {
//atributos
private String apellido;
private int grupo;
private double cuotaBase;
//constructor por defecto
public Alumno() {
apellido = null;
grupo = 0;
cuotaBase = 0.0;
}
// constructor especifico
public Alumno(String ape, int gru, double cuota) {
apellido = ape;
grupo = gru;
cuotaBase = cuota;
}
// getter y setter get:obtener y set:poner
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public int getGrupo() {
return grupo;
}
public void setGrupo(int gru) {
grupo = gru;
}
public double getCuotaBase() {
return cuotaBase;
}
public void setCuotaBase(double cuota) {
cuotaBase = cuota;
}
public double cuotaNeta() {
double monto = cuotaBase;
if (grupo == 1 || grupo == 2)
monto = cuotaBase * 0.60;
if (grupo == 3 || grupo == 4)
monto = cuotaBase * 0.80;
return monto;
}
// metodos específicos
// toString
@Override
public String toString() {
return "apellido: " + apellido + "\n" + " grupo: " + grupo + "\n" + " cuotaBase: " + cuotaBase + "\n";
}
}
|
package com.sepnotican.stargame.base;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.sepnotican.stargame.math.Rect;
import java.util.function.Consumer;
import java.util.function.Function;
public class SimpleButton extends Sprite{
Consumer<SimpleButton> action;
Function<Rect, Float> posXFunc;
Function<Rect, Float> posYFunc;
private boolean pressed;
private int pointer;
public SimpleButton(TextureRegion region, Function<Rect, Float> posXFunc, Function<Rect, Float> posYFunc, Consumer<SimpleButton> action) {
super(region);
this.action = action;
this.posXFunc = posXFunc;
this.posYFunc = posYFunc;
setHeightProportion(0.1f);
}
@Override
public void touchDown(Vector2 touch, int pointer) {
if (pressed || !isMe(touch)) return;
this.pressed = true;
this.pointer = pointer;
}
@Override
public void touchUp(Vector2 touch, int pointer) {
if (this.pointer != pointer || !pressed) return;
if (isMe(touch)) action.accept(this);
this.pressed = false;
this.pointer = -1;
}
@Override
public void resize(Rect worldBounds) {
super.resize(worldBounds);
pos.x = posXFunc.apply(worldBounds);
pos.y = posYFunc.apply(worldBounds);
}
}
|
package com.github.silencesu.helper.http.request.param.get;
import com.github.silencesu.helper.http.request.RequestParams;
import java.util.Map;
/**
* Http Help请求参数
* @author SilenceSu
* @Email Silence.Sx@Gmail.com
* Created by Silence on 2020/10/15.
*/
@FunctionalInterface
public interface GetParams extends RequestParams {
Map<String, String> getParams();
}
|
package com.barnettwong.view_library.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.barnettwong.view_library.R;
import java.util.LinkedHashMap;
public class WaterMark {
private static LinkedHashMap<String, BitmapDrawable> mBitmapCache = new LinkedHashMap<String, BitmapDrawable>();
private Context mContext;
private String mContent;
private BitmapDrawable mBitmapDrawable;
private static final int HORIZONTAL_SPACING = 160;
private static final int VERTICAL_SPACEING = 110;
private static final int ROTATION = 20;
private static final int TEXT_SIZE = 20;
public Context getContext() {
return mContext;
}
public String getContent() {
return mContent;
}
public BitmapDrawable getBitmapDrawable() {
return mBitmapDrawable;
}
public static class Builder {
private Context mContext;
private String mContent;
private int mContentColor;
private int mContentTextSize;
private int mBackGroudColor;
private int mRotateAngle;
private int mPaddingRight;
private int mPaddingBottom;
private Bitmap mBitmap;
private BitmapDrawable mBitmapDrawable;
public Builder(Context context) {
this.mContext = context;
}
public Builder setContent(String content) {
this.mContent = content;
return this;
}
public Builder setContentColor(int contentColor) {
this.mContentColor = contentColor;
return this;
}
public Builder setContentTextSize(int contentTextSize) {
this.mContentTextSize = contentTextSize;
return this;
}
public Builder setBackGroudColor(int backGroudColor) {
this.mBackGroudColor = backGroudColor;
return this;
}
public Builder setRotateAngle(int rotateAngle) {
this.mRotateAngle = rotateAngle;
return this;
}
public Builder setHorizontalPadding(int padding) {
this.mPaddingRight = padding;
return this;
}
public Builder setVerticalPadding(int padding) {
this.mPaddingBottom = padding;
return this;
}
private int getScreenWidth() {
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
return width;
}
private int getScreenHeight() {
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int height = dm.heightPixels;
return height;
}
public WaterMark build() {
initParameter();
mBitmapDrawable = getBitmapDrawableFromCache();
if (mBitmapDrawable == null) {
createBitmapDrawable();
}
WaterMark waterMark = new WaterMark();
waterMark.mContext = mContext;
waterMark.mContent = mContent;
waterMark.mBitmapDrawable = mBitmapDrawable;
return waterMark;
}
private void initParameter() {
if (TextUtils.isEmpty(mContent)) {
String userName = "BarnettWong";
String hostPhoneNum = "13244889847";
if (!TextUtils.isEmpty(hostPhoneNum)) {
String suffix = hostPhoneNum.substring(hostPhoneNum.length() - 4, hostPhoneNum.length());
mContent = userName + suffix;
} else {
String userId = "1993kxhp";
String suffix = userId.substring(userId.length() - 4, userId.length());
mContent = userName + suffix;
}
}
if (mBackGroudColor == 0) {
mBackGroudColor = mContext.getResources().getColor(android.R.color.white);
}
if (mContentColor == 0) {
mContentColor = mContext.getResources().getColor(R.color.water_mark_color);
}
if (mContentTextSize == 0) {
float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
mContentTextSize = (int) (TEXT_SIZE / 2 * fontScale + 0.5f);
}
if (mRotateAngle == 0) {
mRotateAngle = ROTATION;
}
if (mPaddingRight == 0) {
final float scale = mContext.getResources().getDisplayMetrics().density;
mPaddingRight = (int) (HORIZONTAL_SPACING / 2 * scale + 0.5f);
}
if (mPaddingBottom == 0) {
final float scale = mContext.getResources().getDisplayMetrics().density;
mPaddingBottom = (int) (VERTICAL_SPACEING / 2 * scale + 0.5f);
}
}
private BitmapDrawable getBitmapDrawableFromCache() {
String waterMarkConfiguration = mContent + "_" + mContentColor + "_" + mContentTextSize + "_" + mBackGroudColor + "_" + mRotateAngle + "_" + mPaddingRight + "_" + mPaddingBottom;
for (String key : mBitmapCache.keySet()) {
if (key.equals(waterMarkConfiguration)) {
return mBitmapCache.get(waterMarkConfiguration);
}
}
return null;
}
private void createBitmapDrawable() {
TextPaint paint = new TextPaint();
paint.setColor(mContentColor);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(mContentTextSize);
Rect rect = new Rect();
paint.getTextBounds(this.mContent, 0, this.mContent.length(), rect);
int textWidth = rect.width();
int textHeight = rect.height();
mBitmap = Bitmap.createBitmap(getScreenWidth(), getScreenHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(mBitmap);
canvas.drawColor(mBackGroudColor);
double sinRotateAngle = Math.sin(ROTATION);
double cosRotateAngle = Math.cos(ROTATION);
int canvasHeight = (int) ((getScreenHeight() * cosRotateAngle + getScreenWidth() * sinRotateAngle) * 1.5);
int canvasWidth = (int) (getScreenHeight() * sinRotateAngle + getScreenWidth() * cosRotateAngle);
canvas.rotate(-mRotateAngle, getScreenWidth() / 2, getScreenHeight() / 2);
int startX = 0;
int startY = 0;
int i = 1;
for (int positionY = startY; positionY <= canvasHeight; positionY += (textHeight + mPaddingBottom)) {
i++;
if (i % 2 == 0) {
startX = -getScreenWidth() + +textWidth + (mPaddingRight - textWidth) / 2;
} else {
startX = -getScreenWidth();
}
for (float positionX = startX; positionX <= canvasWidth; positionX += (textWidth + mPaddingRight)) {
canvas.drawText(mContent, positionX, positionY, paint);
}
}
mBitmapDrawable = new BitmapDrawable(mContext.getResources(), mBitmap);
mBitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
mBitmapDrawable.setDither(true);
String waterMarkConfiguration = mContent + "_" + mContentColor + "_" + mContentTextSize + "_" + mBackGroudColor + "_" + mRotateAngle + "_" + mPaddingRight + "_" + mPaddingBottom;
mBitmapCache.put(waterMarkConfiguration, mBitmapDrawable);
}
}
}
|
package com.example.s183363.kadai_app.models;
public class Fire extends GameCharacter {
private Player player = null;
private int ySpeed = 2;
private boolean activeFlag = false;
private OnOverlapListener onOverlapListener;
public Fire(int x){
xSize = 24;
ySize = 48;
this.x = getRandom(100,1000);
this.y = 600;
}
public boolean isActiveFlag(){
return activeFlag;
}
public void setPlayer(Player player){
this.player = player;
}
public void setOnOverlapListener(OnOverlapListener onOverlapListener){
this.onOverlapListener = onOverlapListener;
}
public void fire(){
if(activeFlag == false){
this.x = x;
this.y = y;
activeFlag = true;
}
}
public void move(){
if(activeFlag == true){
y = y - ySpeed;
if(y + ySize < 0){
activeFlag = false;
}
}
if(isOverlapWith(player) == true){
player.dead();
onOverlapListener.onOverlap(this);
}
}
}
|
package com.crackdevelopers.goalnepal.Latest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.crackdevelopers.goalnepal.News.NewsDetailsActivity;
import com.crackdevelopers.goalnepal.R;
import com.crackdevelopers.goalnepal.Volley.VolleySingleton;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Created by script on 9/12/15.
*/
public class LatestNewsAdapter extends RecyclerView.Adapter<LatestNewsAdapter.MyViewHolder>
{
private LayoutInflater inflater;
private Context context;
private List<NewsSingleRow> data= Collections.emptyList();
public LatestNewsAdapter(Context context)
{
inflater = LayoutInflater.from(context);
this.context = context;
}
public void setData(List<NewsSingleRow> data)
{
this.data=data;
notifyItemRangeChanged(0, data.size());
}
public void setScrollUpdate(List scrollData)
{
int previousSize=data.size();
for(Object scrollItem:scrollData)
{
data.add((NewsSingleRow)scrollItem);
}
notifyItemRangeInserted(previousSize, scrollData.size());
}
@Override
public LatestNewsAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
return new MyViewHolder(inflater.inflate(R.layout.news_row, parent, false));
}
@Override
public void onBindViewHolder(final LatestNewsAdapter.MyViewHolder viewHolder, int i)
{
ImageLoader imageLoader= VolleySingleton.getInstance().getmImageLoader();
NewsSingleRow item=data.get(i);
viewHolder.title.setText(item.subtitle);
viewHolder.details.setText(item.title);
viewHolder.image.setImageResource(R.drawable.goalnepal_white);
//IMAGE BINDING USING VOLLEY IMAGE LOADER
String imageUrl=item.imageUrl;
if(imageUrl!=null)
{
imageLoader.get(imageUrl,
new ImageLoader.ImageListener()
{
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate)
{
viewHolder.image.setImageBitmap(response.getBitmap());
}
@Override
public void onErrorResponse(VolleyError error)
{
viewHolder.image.setImageResource(R.drawable.goalnepal_white);
}
});
}
else
{
viewHolder.image.setImageResource(R.drawable.goalnepal_white);
}
// Setting date format
SimpleDateFormat inputFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat outputFormat=new SimpleDateFormat("MMM dd");
Date date=new Date();
try{
date = inputFormat.parse(data.get(i).date);
}catch(ParseException e){
Log.d("Exception", "Invalid Date Format");
}
viewHolder.date.setText(outputFormat.format(date));
}
@Override
public int getItemCount()
{
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
{
TextView title, details,date;
ImageView image;
public MyViewHolder(View itemView)
{
super(itemView);
itemView.setOnClickListener(this);
title=(TextView)itemView.findViewById(R.id.newsTitle);
details=(TextView)itemView.findViewById(R.id.newsDetails);
image=(ImageView)itemView.findViewById(R.id.newsImage);
date= (TextView) itemView.findViewById(R.id.newsDate);
}
@Override
public void onClick(View v)
{
Intent intent=new Intent(context, NewsDetailsActivity.class);
Bundle bundle=new Bundle();
NewsSingleRow row=data.get(getAdapterPosition());
bundle.putString(NewsDetailsActivity.IMAGE_ID, row.imageId);
bundle.putString(NewsDetailsActivity.NEWS_DATE, row.date);
bundle.putString(NewsDetailsActivity.NEWS_TITLE, row.subtitle);
bundle.putString(NewsDetailsActivity.NEWS, row.news);
intent.putExtra(NewsDetailsActivity.BUNDLE, bundle);
context.startActivity(intent);
}
}
}
|
package org.example;
import org.example.chatutils.ChatBot;
import org.example.utils.AppConstants;
import org.example.utils.StringUtils;
import java.util.*;
public class App
{
public static void main(String[] args )
{
String startText;
Scanner scan = new Scanner(System.in);
System.out.println(AppConstants.GREETINGS_TEXT);
String readOption = scan.nextLine();
switch (readOption)
{
case AppConstants.OPTION_1:
System.out.println(AppConstants.OPTION_TEXT);
startText = scan.nextLine();
String textWithMorda = StringUtils.vowelsToMorda(startText);
System.out.println(AppConstants.REPLY_TEXT + textWithMorda);
break;
case AppConstants.OPTION_2:
System.out.println(AppConstants.OPTION_TEXT);
startText = scan.nextLine();
String textUpperToLower = StringUtils.upperToLower(startText);
System.out.println(AppConstants.REPLY_TEXT + textUpperToLower);
break;
case AppConstants.OPTION_3:
ChatBot chatBot = new ChatBot();
System.out.println(AppConstants.START_CHAT);
StringUtils.SpeakingWithBot(scan, chatBot);
break;
case AppConstants.OTRION_4:
String forLearnQuestion;
String forLearnAnswer;
Map<String, String> dataSet = new HashMap<String, String>();
StringUtils.QuestionsAndAnswers(scan, dataSet);
ChatBot chatBotLearn = new ChatBot(dataSet);
System.out.println(AppConstants.START_CHAT);
StringUtils.SpeakingWithBot(scan, chatBotLearn);
break;
default:
System.out.println(AppConstants.ERROR_TEXT);
}
}
}
|
package btnhom1;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
public class frmDangNhap {
JFrame main;
JTextField txtUser;
JPasswordField txtPass;
JButton btnDangNhap, btnThoat;
PreparedStatement stmt;
ResultSet rs;
public frmDangNhap() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
main = new JFrame("Đăng Nhập");
main.setBounds((int) width / 2 - 250, (int) height / 2 - 200, 500, 400);
main.setResizable(false);
main.setLayout(null);
main.setVisible(true);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Quản Lý Sinh Viên");
label.setFont(new Font("Courier New", Font.BOLD, 25));
label.setBounds(130, 20, 400, 50);
main.add(label);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(null, "Viết tên đăng nhập"));
panel.setBounds(50, 100, 400, 150);
panel.setLayout(null);
JLabel label1 = new JLabel("Tên đăng nhập:");
label1.setBounds(10, 40, 150, 20);
JLabel label2 = new JLabel("Mật khẩu:");
label2.setBounds(10, 70, 150, 20);
panel.add(label1);
panel.add(label2);
txtUser = new JTextField();
txtUser.setBounds(170, 40, 200, 20);
txtPass = new JPasswordField();
txtPass.setBounds(170, 70, 200, 20);
panel.add(txtUser);
panel.add(txtPass);
main.add(panel);
btnDangNhap = new JButton("Đăng Nhập");
btnDangNhap.setBounds(80, 260, 120, 60);
btnThoat = new JButton("Thoát");
btnThoat.setBounds(280, 260, 120, 60);
main.add(btnDangNhap);
main.add(btnThoat);
txtPass.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
DangNhap();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(frmDangNhap.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
btnDangNhap.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
DangNhap();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(frmDangNhap.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
btnThoat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
void DangNhap() throws IOException, ClassNotFoundException {
boolean pass = false;
String passwords = String.copyValueOf(txtPass.getPassword());
if ("".equals(txtUser.getText().trim()) || "".equals(passwords.trim())) {
JOptionPane.showMessageDialog(null, "Không được bỏ trống tên đăng nhập hoặc mật khẩu", "Lỗi", JOptionPane.ERROR_MESSAGE);
return;
}
if (txtUser.getText().toLowerCase().contains("gv")) {
QLGiaoVien qlgv = new QLGiaoVien();
if (!qlgv.checkLogin(txtUser.getText(), passwords)) {
JOptionPane.showMessageDialog(null, "Sai tên đăng nhập hoặc mật khẩu", "Lỗi", JOptionPane.ERROR_MESSAGE);
return;
}
pass = true;
}
if (txtUser.getText().toLowerCase().contains("sv")) {
QLSinhVien qlsv = new QLSinhVien();
if (!qlsv.checkLogin(txtUser.getText(), passwords)) {
JOptionPane.showMessageDialog(null, "Sai tên đăng nhập hoặc mật khẩu", "Lỗi", JOptionPane.ERROR_MESSAGE);
return;
}
pass = true;
}
if (pass == false) {
JOptionPane.showMessageDialog(null, "Sai tên đăng nhập hoặc mật khẩu", "Lỗi", JOptionPane.ERROR_MESSAGE);
return;
}
// xử lý đăng nhập thành công
System.out.println("Thành công");
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
frmDangNhap form = new frmDangNhap();
}
});
}
}
|
public class Scales {
private int[] currScale;
/**
* intialize arrays for scales (constructor)
*/
public Scales() {
currScale = new int[7];
currScale[0] = 2;
currScale[1] = 2;
currScale[2] = 1;
currScale[3] = 2;
currScale[4] = 2;
currScale[5] = 2;
currScale[6] = 1;
}
/**
* find desired scale degree in array of number of halfsteps
* from tonic to note in scale
* @param deg - the starting note (0=c, 1=d...)
* @return scale degree desired:
* 0 = ionian
* 1 = dorian
* 2 = phrygian
* 3 = lydian
* 4 = mixolydian
* 5 = aeolian
* 6 = locrian
*/
public int[] getScale(int deg) {
int[] scale = new int[7];
scale[0] = 0;
int count = 1;
int val = 0;
while (count < 7) {
scale[count] = currScale[deg % 7] + val;
val = scale[count];
deg++;
count++;
}
return scale;
}
}
|
/*
* Autopsy Forensic Browser
*
* Copyright 2011 Basis Technology Corp.
* Contact: carrier <at> sleuthkit <dot> org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sleuthkit.autopsy.casemodule;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class RecentCasesTest {
RecentCases instance;
public RecentCasesTest() {
instance = RecentCases.getInstance();
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
instance.actionPerformed(null);
}
@After
public void tearDown() {
}
/**
* Test of getInstance method, of class RecentCases.
*/
@Test
public void testGetInstance() {
System.out.println("getInstance");
RecentCases expResult = RecentCases.getInstance();
RecentCases result = RecentCases.getInstance();
assertEquals(expResult, result);
assertNotNull(result);
}
/**
* Test of getMenuPresenter method, of class RecentCases.
*/
@Test
public void testGetMenuPresenter() {
System.out.println("getMenuPresenter");
JMenuItem result = instance.getMenuPresenter();
assertNotNull(result);
}
/**
* Test of actionPerformed method, of class RecentCases.
*/
@Test
public void testActionPerformed() {
System.out.println("actionPerformed");
ActionEvent e = null;
instance.addRecentCase("test", "test");
instance.actionPerformed(e);
assertEquals(instance.getTotalRecentCases(), 0);
}
/**
* Test of addRecentCase method, of class RecentCases.
*/
@Test
public void testAddRecentCase() {
System.out.println("addRecentCase");
String name = "name";
String path = "C:\\path";
instance.addRecentCase(name, path);
instance.addRecentCase(name, path);
assertEquals(name, instance.getRecentCaseNames()[0]);
assertEquals(path, instance.getRecentCasePaths()[0]);
assertEquals(1, instance.getTotalRecentCases());
}
/**
* Test of updateRecentCase method, of class RecentCases.
*/
@Test
public void testUpdateRecentCase() throws Exception {
System.out.println("updateRecentCase");
String oldName = "oldName";
String oldPath = "C:\\oldPath";
String newName = "newName";
String newPath = "C:\\newPath";
instance.addRecentCase(oldName, oldPath);
instance.updateRecentCase(oldName, oldPath, newName, newPath);
assertEquals(newName, instance.getRecentCaseNames()[0]);
assertEquals(newPath, instance.getRecentCasePaths()[0]);
assertEquals(1, instance.getTotalRecentCases());
}
/**
* Test of getTotalRecentCases method, of class RecentCases.
*/
@Test
public void testGetTotalRecentCases() {
System.out.println("getTotalRecentCases");
int expResult = 0;
int result = instance.getTotalRecentCases();
assertEquals(expResult, result);
instance.addRecentCase("name", "path");
result = instance.getTotalRecentCases();
expResult = 1;
assertEquals(expResult, result);
}
/**
* Test of removeRecentCase method, of class RecentCases.
*/
@Test
public void testRemoveRecentCase() {
System.out.println("removeRecentCase");
String name = "name";
String path = "path";
String name1 = "name1";
String path1 = "path1";
instance.addRecentCase(name, path);
instance.addRecentCase(name1, path1);
instance.removeRecentCase(name, path);
assertEquals(1, instance.getTotalRecentCases());
instance.removeRecentCase(name, path);
assertEquals(1, instance.getTotalRecentCases());
instance.removeRecentCase(name1, path1);
assertEquals(0, instance.getTotalRecentCases());
}
/**
* Test of getRecentCaseNames method, of class RecentCases.
*/
@Test
public void testGetRecentCaseNames() {
System.out.println("getRecentCaseNames");
String[] expResult = {"","","","",""};
String[] result = instance.getRecentCaseNames();
assertArrayEquals(expResult, result);
String name = "name";
String path = "C:\\path";
String name1 = "name1";
String path1 = "C:\\path1";
instance.addRecentCase(name, path);
instance.addRecentCase(name1, path1);
String[] expResult1 = {name1,name,"","",""};
String[] result1 = instance.getRecentCaseNames();
assertArrayEquals(expResult1, result1);
}
/**
* Test of getRecentCasePaths method, of class RecentCases.
*/
@Test
public void testGetRecentCasePaths() {
System.out.println("getRecentCasePaths");
String[] expResult = {"","","","",""};
String[] result = instance.getRecentCasePaths();
assertArrayEquals(expResult, result);
String name = "name";
String path = "C:\\path";
String name1 = "name1";
String path1 = "C:\\path1";
instance.addRecentCase(name, path);
instance.addRecentCase(name1, path1);
String[] expResult1 = {path1, path,"","",""};
String[] result1 = instance.getRecentCasePaths();
assertArrayEquals(expResult1, result1);
}
/**
* Test of getName method, of class RecentCases.
*/
@Test
public void testGetName() {
System.out.println("getName");
String result = instance.getName();
assertNotNull(result);
}
/**
* Regression tests for TSK-227
* Make sure that paths are normalized, so that different representations of
* the same path don't result in duplicates.
*/
@Test
public void testNormalizePathAddRecentCase1() {
System.out.println("normalizePathAddRecentCase1");
String name = "name";
String path = "C:\\biig-case\\biig-case.aut";
String oddPath = "c:\\\\biig-case\\biig-case.aut";
instance.addRecentCase(name, path);
instance.addRecentCase(name, oddPath);
assertEquals(1, instance.getTotalRecentCases());
}
@Test
public void testNormalizePathAddRecentCase2() {
System.out.println("normalizePathAddRecentCase2");
String name = "name";
String path = "C:\\biig-case\\biig-case.aut";
String oddPath = "c:\\\\biig-case\\biig-case.aut";
instance.addRecentCase(name, oddPath);
instance.addRecentCase(name, path);
assertEquals(1, instance.getTotalRecentCases());
}
@Test
public void testNormalizePathUpdateRecentCase1() throws Exception {
System.out.println("normalizePathUpdateRecentCase1");
String oldName = "oldName";
String oldPath = "C:\\biig-case\\biig-case.aut";
String oddOldPath = "c:\\\\biig-case\\biig-case.aut";
String newName = "newName";
String newPath = "newPath";
instance.addRecentCase(oldName, oldPath);
instance.updateRecentCase(oldName, oddOldPath, newName, newPath);
assertEquals(1, instance.getTotalRecentCases());
}
@Test
public void testNormalizePathUpdateRecentCase2() throws Exception {
System.out.println("normalizePathUpdateRecentCase2");
String oldName = "oldName";
String oldPath = "C:\\biig-case\\biig-case.aut";
String oddOldPath = "c:\\\\biig-case\\biig-case.aut";
String newName = "newName";
String newPath = "newPath";
instance.addRecentCase(oldName, oddOldPath);
instance.updateRecentCase(oldName, oldPath, newName, newPath);
assertEquals(1, instance.getTotalRecentCases());
}
@Test
public void testNormalizePathRemoveRecentCase1() {
System.out.println("normalizePathRemoveRecentCase1");
String name = "name";
String path = "C:\\biig-case\\biig-case.aut";
String oddPath = "c:\\\\biig-case\\biig-case.aut";
instance.addRecentCase(name, path);
instance.removeRecentCase(name, oddPath);
assertEquals(0, instance.getTotalRecentCases());
}
@Test
public void testNormalizePathRemoveRecentCase2() {
System.out.println("normalizePathRemoveRecentCase2");
String name = "name";
String path = "C:\\biig-case\\biig-case.aut";
String oddPath = "c:\\\\biig-case\\biig-case.aut";
instance.addRecentCase(name, oddPath);
instance.removeRecentCase(name, path);
assertEquals(0, instance.getTotalRecentCases());
}
}
|
package com.sirma.itt.javacourse.networkingAndGui.task2.downloadAgent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLConnection;
import javax.swing.JProgressBar;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.Spy;
/**
* Test class for {@link DownloadUITask}
*
* @author Simeon Iliev
*/
public class DownloadWorkerTest {
private static Logger log = Logger.getLogger(DownloadWorkerTest.class);
@Spy
private DownloadUITask spyTask;
@Mock
private JProgressBar progressBar;
@Mock
private URLConnection connection;
private File testFile;
/**
* Set up before method.
*
* @throws java.lang.Exception
* something went wrong
*/
@Before
public void setUp() throws Exception {
progressBar = Mockito.mock(JProgressBar.class);
connection = Mockito.mock(URLConnection.class);
log.info(getClass().getResource("/test.png"));
testFile = new File(getClass().getResource("/test.png").toURI());
spyTask = Mockito.spy(new DownloadUITask(testFile.toURI().toURL()
.toString(), "target", progressBar));
}
/**
* Test method for
* {@link com.sirma.itt.javacourse.networkingAndGui.task2.downloadAgent.javacourse.networkingAndGui.task2.downloadAgent.DownloadUITask#doInBackground()}
* .
*
* @throws IOException
* @throws MalformedURLException
*/
@Test
public void testDoInBackground() throws MalformedURLException, IOException {
Mockito.when(spyTask.openConnection()).thenReturn(connection);
Mockito.when(connection.getContentLengthLong()).thenReturn(154952L);
Mockito.when(connection.getInputStream()).thenReturn(
new FileInputStream(testFile));
try {
spyTask.doInBackground();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
Mockito.verify(progressBar, Mockito.atLeastOnce()).setValue(0);
Mockito.verify(connection, Mockito.atLeastOnce())
.getContentLengthLong();
Mockito.verify(connection, Mockito.atLeastOnce()).getInputStream();
}
}
|
package org.base.algorithm.sort;
/**
* Created by wangwr on 2016/6/2.
*/
public class P {
public static void show(String format){
System.out.println(format);
}
public static void show(String format,Object... objs){
System.out.println(String.format(format,objs));
}
}
|
package ul.stage.officeassignment.model;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CustomListSerializer extends StdSerializer<Bureau> {
public CustomListSerializer(Class<Bureau> t) {
super(t);
}
public CustomListSerializer(JavaType type) {
super(type);
}
@Override
public void serialize(Bureau bureau, JsonGenerator gen, SerializerProvider provider) throws IOException {
gen.writeObject(bureau.getNumero());
}
}
|
/*
* Copyright 2017 Grzegorz Skorupa <g.skorupa at gmail.com>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cricketmsf.out.db;
import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.cricketmsf.Adapter;
import org.cricketmsf.Event;
import org.cricketmsf.Kernel;
import org.cricketmsf.out.OutboundAdapter;
import org.h2.jdbcx.JdbcConnectionPool;
/**
*
* @author greg
*/
public class H2EmbededDB extends OutboundAdapter implements SqlDBIface, Adapter {
private JdbcConnectionPool cp;
private String location;
private String path;
private String fileName;
private String testQuery;
private String userName;
private String password;
private String systemVersion;
private boolean encrypted;
private String filePassword;
@Override
public void loadProperties(HashMap<String, String> properties, String adapterName) {
super.loadProperties(properties, adapterName);
setPath(properties.get("path"));
Kernel.getLogger().print("\tpath: " + getPath());
setFileName(properties.get("file"));
Kernel.getLogger().print("\tfile: " + getFileName());
setLocation(getPath() + File.separator + getFileName());
setTestQuery(properties.get("test-query"));
Kernel.getLogger().print("\ttest-query: " + getTestQuery());
setSystemVersion(properties.get("version"));
Kernel.getLogger().print("\tversion: " + getSystemVersion());
setUserName(properties.get("user"));
Kernel.getLogger().print("\tuser: " + getUserName());
setPassword(properties.get("password"));
Kernel.getLogger().print("\tpassword=" + getPassword());
setEncrypted(properties.get("encrypted"));
Kernel.getLogger().print("\tencrypted=" + isEncrypted());
setFilePassword(properties.get("filePassword"));
Kernel.getLogger().print("\tfilePassword=" + getFilePassword());
try {
start();
} catch (KeyValueDBException ex) {
Kernel.getInstance().dispatchEvent(Event.logSevere(this, ex.getMessage()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public String getName() {
return getFileName();
}
@Override
public void createDatabase(Connection conn, String version) {
if (conn == null || getTestQuery() == null || getTestQuery().isEmpty()) {
Kernel.getInstance().dispatchEvent(Event.logSevere(this, "problem connecting to the database"));
return;
}
String createQuery
= "CREATE TABLE SERVICEVERSION(VERSION VARCHAR);"
+ "INSERT INTO SERVICEVERSION VALUES('" + version + "')";
try {
conn.createStatement().execute(createQuery);
conn.close();
} catch (SQLException e) {
Kernel.getInstance().dispatchEvent(Event.logSevere(this, e.getMessage()));
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public Connection getConnection() throws SQLException {
return cp.getConnection();
}
@Override
public String getVersion() {
String version = null;
try {
Connection conn = getConnection();
ResultSet rs = conn.createStatement().executeQuery("select * from serviceversion");
while (rs.next()) {
version = rs.getString("version");
}
conn.close();
} catch (SQLException ex) {
Kernel.getInstance().dispatchEvent(Event.logSevere(this, ex.getMessage()));
}
return version;
}
@Override
public void start() throws KeyValueDBException {
if (isEncrypted()) {
cp = JdbcConnectionPool.create("jdbc:h2:" + getLocation()+";CIPHER=AES", getUserName(), getFilePassword()+" "+getPassword());
} else {
cp = JdbcConnectionPool.create("jdbc:h2:" + getLocation(), getUserName(), getPassword());
}
Connection conn = null;
try {
conn = cp.getConnection();
ResultSet rs = conn.createStatement().executeQuery(getTestQuery());
if (rs.next()) {
Kernel.getLogger().print("\tdatabase " + getFileName() + " version: " + rs.getString("VERSION"));
}
conn.close();
} catch (SQLException e) {
try {
createDatabase(conn, getSystemVersion());
} catch (Exception ex) {
e.printStackTrace();
Kernel.getInstance().shutdown();
}
}
String version = getVersion();
try {
updateStructure(cp.getConnection(), version, getSystemVersion());
} catch (SQLException e) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_WRITE, "cannot update database version information");
}
}
@Override
public void stop() {
//nothing todo
}
@Override
public void deleteTable(String tableName) throws KeyValueDBException {
String query = "drop if exists table ??";
try (Connection conn = cp.getConnection()) {
query = query.replaceAll("\\?\\?", tableName);
PreparedStatement pstmt = conn.prepareStatement(query);
if (!pstmt.execute()) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_DELETE, "table " + tableName + " not dropped");
}
conn.close();
} catch (SQLException e) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_DELETE, "unable to drop " + tableName);
}
}
@Override
public List<String> getTableNames() throws KeyValueDBException {
String query = "show tables from public";
ArrayList list = new ArrayList();
try (Connection conn = cp.getConnection()) {
PreparedStatement pstmt = conn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(rs.getString("TABLE_NAME"));
}
conn.close();
} catch (SQLException e) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_DELETE, "unable to get table names");
}
return list;
}
@Override
public void clear(String tableName) throws KeyValueDBException {
String query = "delete from ??";
try (Connection conn = cp.getConnection()) {
query = query.replaceAll("\\?\\?", tableName);
PreparedStatement pstmt = conn.prepareStatement(query);
if (!pstmt.execute()) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_DELETE, "table " + tableName + " not cleared");
}
conn.close();
} catch (SQLException e) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_DELETE, "unable to clear table " + tableName);
}
}
@Override
public void destroy() {
if (cp != null) {
cp.dispose();
}
}
@Override
public void addTable(String string, int i, boolean bln) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void put(String string, String string1, Object o) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object get(String string, String string1) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Object get(String string, String string1, Object o) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Map getAll(String string) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List search(String string, ComparatorIface ci, Object o) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean containsKey(String string, String string1) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public boolean remove(String tableName, String key) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public List search(String tableName, String statement, String[] parameters) throws KeyValueDBException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* @return the location
*/
public String getLocation() {
return location;
}
/**
* @param location the location to set
*/
public void setLocation(String location) {
this.location = location;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* @return the fileName
*/
public String getFileName() {
return fileName;
}
/**
* @param fileName the fileName to set
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @return the testQuery
*/
public String getTestQuery() {
return testQuery;
}
/**
* @param testQuery the testQuery to set
*/
public void setTestQuery(String testQuery) {
this.testQuery = testQuery;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the systemVersion
*/
public String getSystemVersion() {
return systemVersion;
}
/**
* @param systemVersion the systemVersion to set
*/
public void setSystemVersion(String systemVersion) {
this.systemVersion = systemVersion;
}
@Override
public void backup(String fileLocation) throws KeyValueDBException {
String query = "backup to '" + fileLocation + "'";
try (Connection conn = cp.getConnection()) {
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.executeUpdate();
}
conn.close();
} catch (SQLException e) {
throw new KeyValueDBException(KeyValueDBException.CANNOT_DELETE, "backup error - " + e.getMessage());
}
}
@Override
public String getBackupFileName() {
return getName() + ".zip";
}
public final void updateStructure(Connection conn, String from, String to) throws KeyValueDBException {
int fromVersion = 1;
int toVersion = -1;
try {
fromVersion = Integer.parseInt(from);
} catch (NumberFormatException | NullPointerException e) {
e.printStackTrace();
}
try {
toVersion = Integer.parseInt(to);
} catch (NumberFormatException | NullPointerException e) {
e.printStackTrace();
throw new KeyValueDBException(KeyValueDBException.CANNOT_WRITE, "cannot update database structure of " + this.getClass().getSimpleName());
}
for (int i = fromVersion; i < toVersion; i++) {
updateStructureTo(conn, i + 1);
}
String query = "update serviceversion set version='" + to + "' where version='" + from + "'";
try {
conn.createStatement().execute(query);
conn.close();
} catch (SQLException e) {
Kernel.getInstance().dispatchEvent(Event.logSevere(this, e.getMessage()));
} catch (Exception e) {
e.printStackTrace();
}
}
protected void updateStructureTo(Connection conn, int versionNumber) throws KeyValueDBException {
throw new KeyValueDBException(KeyValueDBException.UNKNOWN, "method not implemented");
}
/**
* @return the encrypted
*/
public boolean isEncrypted() {
return encrypted;
}
/**
* @param encrypted the encrypted to set
*/
public void setEncrypted(String encrypted) {
this.encrypted = Boolean.parseBoolean(encrypted);
}
/**
* @return the filePassword
*/
public String getFilePassword() {
return filePassword;
}
/**
* @param filePassword the filePassword to set
*/
public void setFilePassword(String filePassword) {
this.filePassword = filePassword;
}
}
|
import sample.Question;
class Quiz extends Question {
private Question []quiz;
int top;
public Quiz(int num) //Number of Question in the quiz
{
quiz = new Question[num];
top = 0;
}
public void addQuestion(String question,String opt1,String opt2,String opt3,String opt4)
{
Question q = new Question((top+1),question,opt1,opt2,opt3,opt4);
quiz[top] = q;
top +=1;
}
public void update_Question(int qno)
{
if(qno>(top+1))
{
System.out.println("Invalid Question number");
}
else
{
for (int i = 0; i < top; i += 1) {
if (qno == quiz[i].get_qno())
{
quiz[i].display();//Display original question
//GET INPUTS FROM USER FOR QUESTIONS AND OPTIONS
//quiz[i].update_question(String question,String opt1,String opt2,String opt3,String opt4);
quiz[i].display();//Display updated question
break;
}
}
}
}
}
|
package com.castis.dto;
import java.util.List;
public class TreeNodeDTO extends NameDTO{
private String id;
private List<TreeNodeDTO> children;
private String fullpath;
public TreeNodeDTO(){
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public List<TreeNodeDTO> getChildren() {
return children;
}
public void setChildren(List<TreeNodeDTO> children) {
this.children = children;
}
public void setFullpath(String fullpath) {
this.fullpath = fullpath;
}
public String getFullpath() {
return fullpath;
}
}
|
package tech.makers.bank;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
public class Statement {
private final String header = "date || credit || debit || balance\n";
public String print() {
return header;
}
public String print(ArrayList<ITransaction> transactions) {
String stringOfTransactions = createStringOfTransactions(transactions);
return header + stringOfTransactions;
}
private String createStringOfTransactions(ArrayList<ITransaction> transactions) {
StringBuilder stringOfTransactions = new StringBuilder();
for(ITransaction transaction : transactions) {
stringOfTransactions.append(createTransactionLine(transaction));
}
return stringOfTransactions.toString();
}
private String createTransactionLine(ITransaction transaction) {
String date = formatDate(transaction.getDate());
String credit = formatAmount(transaction.getCredit());
String debit = formatAmount(transaction.getDebit());
String balance = formatAmount(transaction.getRunningBalance());
return String.join(" || ", date, credit, debit, balance) + "\n";
}
private String formatDate(LocalDate date) {
return date.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
}
private String formatAmount(double amount) {
String formattedAmount;
if ( amount == 0 ) {
formattedAmount = "-";
} else {
formattedAmount = String.format("%.2f", amount);
}
return formattedAmount;
}
}
|
/**
* Description: This holds the address of someone
* including their zip code, town, street, and country
* @author Killian O'Dálaigh
* @version 10 October 2018
*/
public class Address {
private String street;
private String town;
private String zip;
private String country;
/*
* Class Constructor with no address
*/
public Address() {
street = null;
town = null;
zip = null;
country = null;
}// End Constructor
/*
* Class Constructor given address
*/
public Address(String str, String twn, String zp, String contry) {
street = str;
town = twn;
zip = zp;
country = contry;
}// End Constructor
/*
* Methods
*/
// Creates a single string of the Address in a single line
public String catAddress() {
return (street + "," + town + "," + zip + "," + country);
}
// Creates a String of the Address going to new lines after each attribute
public String catAddressNewLine() {
return (street + ",\n" + town + ",\n" + zip + ",\n" + country);
}
// Checks if the Object is empty or not
public boolean isEmpty() {
if((this.street != null && !this.street.isEmpty())&&((this.town != null && !this.town.isEmpty()))&&((this.zip != null && !this.zip.isEmpty()))&&((this.country != null && !this.country.isEmpty())))
{
return true;
}
else {
return false;
}
}
/*
* Getters and Setters
*/
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}// End Class Address
|
package ru.shikhovtsev.proxy;
public class Main {
public static void main(String[] args) {
var container = new IoCContainer();
MyService service = getService(container);
service.computeLastDateTime();
service.setCount(123);
service.setParams(1, 5, "simple string");
System.out.println(service.getClass());
}
public static MyService getService(IoCContainer container) {
return container.getProxiedObject(MyService.class, new MyServiceImpl());
}
}
|
package ch.so.agi.cadastre.webservice;
import org.locationtech.jts.geom.Geometry;
public class Grundstueck {
private String egrid;
private String nummer;
private String nbident;
private String art;
private double flaechenmass;
private Geometry geometrie;
private int bfsnr;
private String gemeinde;
private String kanton;
private String gbSubKreis;
private int gbSubKreisNummer;
private String grundbuchamt;
public String getEgrid() {
return egrid;
}
public void setEgrid(String egrid) {
this.egrid = egrid;
}
public String getNummer() {
return nummer;
}
public void setNummer(String nummer) {
this.nummer = nummer;
}
public String getNbident() {
return nbident;
}
public void setNbident(String nbident) {
this.nbident = nbident;
}
public String getArt() {
return art;
}
public void setArt(String art) {
this.art = art;
}
public double getFlaechenmass() {
return flaechenmass;
}
public void setFlaechenmass(double flaechenmass) {
this.flaechenmass = flaechenmass;
}
public Geometry getGeometrie() {
return geometrie;
}
public void setGeometrie(Geometry geometrie) {
this.geometrie = geometrie;
}
public int getBfsnr() {
return bfsnr;
}
public void setBfsnr(int bfsnr) {
this.bfsnr = bfsnr;
}
public String getGemeinde() {
return gemeinde;
}
public void setGemeinde(String gemeinde) {
this.gemeinde = gemeinde;
}
public String getKanton() {
return kanton;
}
public void setKanton(String kanton) {
this.kanton = kanton;
}
public String getGbSubKreis() {
return gbSubKreis;
}
public void setGbSubKreis(String gbSubKreis) {
this.gbSubKreis = gbSubKreis;
}
public int getGbSubKreisNummer() {
return gbSubKreisNummer;
}
public void setGbSubKreisNummer(int gbSubKreisNummer) {
this.gbSubKreisNummer = gbSubKreisNummer;
}
public String getGrundbuchamt() {
return grundbuchamt;
}
public void setGrundbuchamt(String grundbuchamt) {
this.grundbuchamt = grundbuchamt;
}
}
|
/*
* Copyright (c) 2009, Julian Gosnell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.dada.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class TransformingModel<IK, IV, OK, OV> extends AbstractModel<OK, OV> implements View<IV> {
public interface Transformer<IV, OK, OV> {
OV transform(IV value);
OK getKey(OV value);
}
//private final Logger logger = LoggerFactory.getLogger(getClass());
private final Map<OK, OV> keyToData = new ConcurrentHashMap<OK, OV>();
private final Transformer<IV, OK, OV> transformer;
public TransformingModel(String name, Metadata<OK, OV> metadata, Transformer<IV, OK, OV> transformer) {
super(name, metadata);
this.transformer = transformer;
}
@Override
public Data<OV> getData() {
return new Data<OV>(keyToData.values(), null);
}
@Override
public void update(Collection<Update<IV>> insertions, Collection<Update<IV>> alterations, Collection<Update<IV>> deletions) {
Collection<Update<OV>> i;
if (!insertions.isEmpty()) {
i = new ArrayList<Update<OV>>(insertions.size());
for (Update<IV> insertion : insertions) {
IV inputValue = insertion.getNewValue();
OV outputValue = transformer.transform(inputValue);
OK outputKey = transformer.getKey(outputValue);
keyToData.put(outputKey, outputValue);
i.add(new Update<OV>(null ,outputValue));
}
} else {
i = Collections.emptyList();
}
Collection<Update<OV>> u;
if (!alterations.isEmpty()) {
u = new ArrayList<Update<OV>>(alterations.size());
for (Update<IV> update : alterations) {
IV oldInputValue = update.getOldValue();
IV newInputValue = update.getNewValue();
OV oldOutputValue = transformer.transform(oldInputValue);
OV newOutputValue = transformer.transform(newInputValue);
keyToData.remove(transformer.getKey(oldOutputValue));
keyToData.put(transformer.getKey(newOutputValue), newOutputValue);
u.add(new Update<OV>(oldOutputValue, newOutputValue));
}
} else {
u = Collections.emptyList();
}
Collection<Update<OV>> d;
if (!deletions.isEmpty()) {
d = new ArrayList<Update<OV>>(deletions.size());
for (Update<IV> deletion : deletions) {
IV inputValue = deletion.getOldValue();
OV outputValue = transformer.transform(inputValue);
keyToData.remove(transformer.getKey(outputValue));
d.add(new Update<OV>(outputValue, null));
}
} else {
d = Collections.emptyList();
}
notifyUpdate(i, u, d);
}
@Override
public OV find(OK key) {
// TODO Auto-generated method stub
// return null;
throw new UnsupportedOperationException("NYI");
}
}
|
/*
* Test 18
*
* da questo test inizia il test per la generazione di espressioni. Iniziamo da
* ..?..:..
*/
class HelloWorld {
static public void main(String[] argv)
{
int i=1;
int l=2;
int k;
k=i>l ? 10 : 20;
System.out.println(k); // stampo 20.
}
}
|
package com.smart.droidies.tamil.natkati.library.util;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
public class DownloadUtil {
private final static String C_LOG_TAG = "TAMIL CALENDER";
public static boolean checkConnectivity(Context ctx) {
boolean bConnected = false;
ConnectivityManager connMgr = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// Check for network connectivity
if (networkInfo != null && networkInfo.isConnected()) {
bConnected = true;
}
return bConnected;
}
public static InputStream downloadURL(String strURL) {
InputStream is = null;
try {
Log.i(C_LOG_TAG, "DownLoad URL: " + strURL);
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
// int response = conn.getResponseCode();
// Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
} catch (Exception e) {
Log.i(C_LOG_TAG, "Exception in downloading metadata file. Data will not syncronize");
}
return is;
}
}
|
package com.cs.persistence;
import com.cs.payment.Currency;
/**
* @author Omid Alaepour
*/
public class InvalidCurrencyException extends RuntimeException {
private static final long serialVersionUID = 1L;
public static final String CURRENCY_IS_NOT_VALID = "Currency: %s not found";
public InvalidCurrencyException(final Currency currency) {
super(String.format(CURRENCY_IS_NOT_VALID, currency));
}
public InvalidCurrencyException(final String message) {
super(String.format(CURRENCY_IS_NOT_VALID, message));
}
}
|
/**
* J2HomeWork4
*
* @author Andrew Shevelev
* @version Jun, 16 2018
* @link https://github.com/ShevelevAndrew
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
public class J2HomeWork4 extends JFrame implements ActionListener {
Dimension sizeScreen = Toolkit.getDefaultToolkit().getScreenSize();
JTextArea jta;
JTextField jtField;
public static void main(String[] args) {
new J2HomeWork4();
}
J2HomeWork4() {
setTitle("Client of the chat");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(sizeScreen.width-350, sizeScreen.height - 600, 350, 550);
jta = new JTextArea();
jta.setEditable(false);
JScrollPane jsp = new JScrollPane(jta);
JPanel jp = new JPanel();
jp.setLayout(new BoxLayout(jp, BoxLayout.X_AXIS));
jtField = new JTextField();
jtField.addActionListener(this);
JButton butSend = new JButton("Send message");
butSend.addActionListener(this);
jp.add(jtField);
jp.add(butSend);
add(BorderLayout.CENTER, jsp);
add(BorderLayout.SOUTH, jp);
setVisible(true);
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent e) {
StringBuffer buffer = new StringBuffer();
try (BufferedReader file = new BufferedReader (new FileReader("logChat.txt"))) {
while (file.ready())
buffer.append(file.readLine() + "\n");
jta.append(buffer.toString());
file.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try (FileWriter file = new FileWriter("logChat.txt")) {
file.write(jta.getText());
file.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
}
@Override
public void actionPerformed(ActionEvent event) {
if (jtField.getText().trim().length() > 0) {
jta.append(jtField.getText() + "\n");
}
jtField.setText("");
jtField.requestFocusInWindow();
}
}
|
package dev.ghimire.daos;
import dev.ghimire.entities.Expense;
import org.apache.log4j.Logger;
import java.util.*;
public class ExpenseDaoLocalImpl implements ExpenseDAO {
public static ExpenseDaoLocalImpl expenseDaoLocal= new ExpenseDaoLocalImpl();
private static int idMaker=0;
private static Map<Integer,Expense> allExpense = new HashMap<>();
private static Logger logger = Logger.getLogger(ExpenseDaoLocalImpl.class);
@Override
public Expense createExpense(Expense expense) {
expense.setExpenseId(++idMaker);
allExpense.put(expense.getExpenseId(), expense);
Expense createdExpense = allExpense.get(expense.getExpenseId());
if(createdExpense!=null)
{
logger.info("A new expense was created");
return createdExpense;
}
else
{
logger.error("Wasn't able to create an expense");
return null;
}
}
@Override
public Set<Expense> getAllExpense() {
Set<Expense> expenses = new HashSet<>(allExpense.values());
return expenses;
}
@Override
public Expense getExpenseById(int id) {
Expense expense = allExpense.get(id);
return expense;
}
@Override
public Expense updateExpense(Expense expense) {
expense.setDecisionDate(System.currentTimeMillis());
int id = expense.getExpenseId();
allExpense.put(id,expense);
return allExpense.get(id);
}
@Override
public boolean deleteExpenseById(int id) {
Expense expense = allExpense.remove(id);
if(expense == null)
{
return false;
}
return true;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package search;
import BDD.Requete;
import Entite.Enseignant;
import Entite.Etudiant;
import Entite.Enseignant;
import Entite.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author seck
*/
public class SearchEnseignant {
Requete requete = new Requete();
Enseignant ens = new Enseignant();
////////////////Rechercher par idEnseignant///////////////////
public ArrayList<Enseignant> RechercherParidEnseignant(int id_ens) {
try {
String req = "SELECT * FROM enseignant WHERE id_enseignant='" + id_ens + "'" ;
ArrayList<Enseignant> liste = new ArrayList<>();
ResultSet res = requete.exeRead(req);
SearchClasse Sclasse = new SearchClasse();
SearchUser Suser = new SearchUser();
while (res.next()) {
ens.setIdEnseignant(res.getInt(1));
ens.setNom(res.getString(2));
ens.setPrenom(res.getString(3));
ens.setEmailEnseignant(res.getString(4));
ens.setTelEnseignant(res.getString(5));
ens.setIdUser(res.getInt(6));
liste.add(ens);
}
return liste;
} catch (SQLException ex) {
Logger.getLogger(SearchEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
////////////////Rechercher par nom///////////////////
public ArrayList<Enseignant> RechercherParNom(String nom) {
try {
String req = "SELECT * FROM enseignant WHERE nom_enseignant='" + nom + "'" ;
ArrayList<Enseignant> liste = new ArrayList<>();
ResultSet res = requete.exeRead(req);
SearchClasse Sclasse = new SearchClasse();
SearchUser Suser = new SearchUser();
while (res.next()) {
ens.setIdEnseignant(res.getInt(1));
ens.setNom(res.getString(2));
ens.setPrenom(res.getString(3));
ens.setEmailEnseignant(res.getString(4));
ens.setTelEnseignant(res.getString(5));
ens.setIdUser(res.getInt(6));
liste.add(ens);
}
return liste;
} catch (SQLException ex) {
Logger.getLogger(SearchEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
////////////////Rechercher par telephone///////////////////
public ArrayList<Enseignant> RechercherParTelephone(String tel) {
try {
String req = "SELECT * FROM enseignant WHERE tel_enseignant='" + tel + "'" ;
ArrayList<Enseignant> liste = new ArrayList<>();
ResultSet res = requete.exeRead(req);
SearchClasse Sclasse = new SearchClasse();
SearchUser Suser = new SearchUser();
while (res.next()) {
ens.setIdEnseignant(res.getInt(1));
ens.setNom(res.getString(2));
ens.setPrenom(res.getString(3));
ens.setEmailEnseignant(res.getString(4));
ens.setTelEnseignant(res.getString(5));
ens.setIdUser(res.getInt(6));
liste.add(ens);
}
return liste;
} catch (SQLException ex) {
Logger.getLogger(SearchEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
////////////////Rechercher par prenom///////////////////
public ArrayList<Enseignant> RechercherParPrenom(String prenom) {
try {
String req = "SELECT * FROM enseignant WHERE prenom_enseignant='" + prenom + "'" ;
ArrayList<Enseignant> liste = new ArrayList<>();
ResultSet res = requete.exeRead(req);
SearchClasse Sclasse = new SearchClasse();
SearchUser Suser = new SearchUser();
while (res.next()) {
ens.setIdEnseignant(res.getInt(1));
ens.setNom(res.getString(2));
ens.setPrenom(res.getString(3));
ens.setEmailEnseignant(res.getString(4));
ens.setTelEnseignant(res.getString(5));
ens.setIdUser(res.getInt(6));
liste.add(ens);
}
return liste;
} catch (SQLException ex) {
Logger.getLogger(SearchEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
////////////////Rechercher par email///////////////////
public ArrayList<Enseignant> RechercherParEmail(String email) {
try {
String req = "SELECT * FROM enseignant WHERE email_enseignant='" + email + "'" ;
ArrayList<Enseignant> liste = new ArrayList<>();
ResultSet res = requete.exeRead(req);
SearchClasse Sclasse = new SearchClasse();
SearchUser Suser = new SearchUser();
while (res.next()) {
ens.setIdEnseignant(res.getInt(1));
ens.setNom(res.getString(2));
ens.setPrenom(res.getString(3));
ens.setEmailEnseignant(res.getString(4));
ens.setTelEnseignant(res.getString(5));
ens.setIdUser(res.getInt(6));
liste.add(ens);
}
return liste;
} catch (SQLException ex) {
Logger.getLogger(SearchEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
////////////////Rechercher par iduser///////////////////
public ArrayList<Enseignant> RechercherParIduser(User id_user) {
try {
String req = "SELECT * FROM enseignant WHERE id_user='" + id_user.getId_user()+ "'" ;
ArrayList<Enseignant> liste = new ArrayList<>();
ResultSet res = requete.exeRead(req);
while (res.next()) {
ens.setIdEnseignant(res.getInt(1));
ens.setNom(res.getString(2));
ens.setPrenom(res.getString(3));
ens.setEmailEnseignant(res.getString(4));
ens.setTelEnseignant(res.getString(5));
ens.setIdUser(res.getInt(6));
liste.add(ens);
}
return liste;
} catch (SQLException ex) {
Logger.getLogger(SearchEtudiant.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
|
package ua.siemens.dbtool.model.entities;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
/**
* The class is a representation of Profiles of the users
*
* @author Perevoznyk Pavlo
* creation date 29 august 2017
* @version 1.0
*/
@Entity
@Table(name = "profiles")
public class Profile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@NotNull
@Column(name = "name", nullable = false, unique = true)
private String name;
public Profile() {
this.name = "";
}
@Override
public String toString() {
return "[ id=" + id +
", name=" + name + " ]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Profile profile = (Profile) o;
return name != null ? name.equals(profile.name) : profile.name == null;
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setId(Long id) {
this.id = id;
}
}
|
package com.mycompany.controllers;
import com.jfoenix.controls.JFXButton;
import com.mycompany.interacciondb.InfoSuscriptores;
import com.mycompany.interacciondb.datos;
import com.mycompany.interacciondb.extra;
import com.mycompany.persistencia.DataBase;
import com.mycompany.persistencia.Instructor;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javax.persistence.EntityManager;
import javax.persistence.Query;
/**
* FXML Controller class
*
* @author elias
*/
public class MasSuscriptoresController implements Initializable {
@FXML private AnchorPane pane;
@FXML
private Label Nombre,edad, colonia, calle,ml,celular,Fijo, email,inst;
@FXML
private JFXButton cancelar;
@Override
public void initialize(URL url, ResourceBundle rb) {
cerrar();
hilo();
}
//Metodo para cerrar la ventana
private void cerrar(){
cancelar.setOnAction((e)->{
pane.getScene().getWindow().hide();
});
}
private void hilo(){
info i = new info();
i.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, (WorkerStateEvent e)->{
InfoSuscriptores in = i.getValue();
Nombre.setText(extra.getNombre());
email.setText(extra.getEmail());
edad.setText(extra.getEdad());
colonia.setText(extra.getColonia());
ml.setText(extra.getMl());
celular.setText(" "+in.getCelular());
Fijo.setText(" "+in.getFijo());
calle.setText(in.getCalle());
inst.setText(in.getInstructor());
});
new Thread(i).start();
}
//Clase para obtener la info
private class info extends Task<InfoSuscriptores>{
@Override
protected InfoSuscriptores call() throws Exception {
return obtener();
}
private InfoSuscriptores obtener(){
InfoSuscriptores ip = null;
try{
EntityManager manager = DataBase.getEMF().createEntityManager();
manager.getTransaction().begin();
Query result = manager.createQuery("SELECT NEW com.mycompany.interacciondb.InfoSuscriptores(b.calle,a.sUSTELCelular,a.susTelm) FROM Suscriptor a, Direccion_SUS b WHERE a.susId = b.suscriptor.susId AND a.susId= :id");
result.setParameter("id", datos.getId());
List<InfoSuscriptores> info = result.getResultList();
if(info.size()>0){
ip = info.get(0);
}
Query re = manager.createQuery("SELECT a FROM Instructor a, Suscriptor b, Instruidos c WHERE a.insId = c.primaryKey.instructor.insId AND b.susId = c.primaryKey.sus.susId AND b.susId= :id");
re.setParameter("id", datos.getId());
List<Instructor> io = re.getResultList();
if(io.size()>0){
Instructor il = io.get(0);
ip.setInstructor(il.getInsNom()+" "+il.getInsApat()+" "+il.getInsAm());
}
manager.getTransaction().commit();
manager.close();
}catch(Exception e){
}
return ip;
}
}
}
|
package com.practice.geneticstypetest;
// ジェネリクス(総称型)
public class TestClass<T> {
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
package com.hackthon.kisainsur.src;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.hackthon.kisainsur.R;
import java.util.ArrayList;
import java.util.List;
public class ExpandableListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public static final int HEADER = 0;
public static final int CHILD = 1;
private List<Item> data;
public ExpandableListAdapter(List<Item> data) {
this.data = data;
}
boolean[] isCheckedItem;
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = null;
Context context = parent.getContext();
isCheckedItem = new boolean[6];
float dp = context.getResources().getDisplayMetrics().density;
switch (type) {
case HEADER:
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.recycler_item, parent, false);
ListHeaderViewHolder header = new ListHeaderViewHolder(view);
return header;
case CHILD:
LayoutInflater inflater1 = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater1.inflate(R.layout.recycler_item_people, parent, false);
ListChildViewHolder child = new ListChildViewHolder(view);
return child;
}
return null;
}
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final Item item = data.get(position);
switch (item.type) {
case HEADER:
final ListHeaderViewHolder itemController = (ListHeaderViewHolder) holder;
itemController.refferalItem = item;
itemController.header_title.setText(item.text);
if (item.invisibleChildren == null) {
itemController.btn_expand_toggle.setImageResource(R.drawable.tri_bottom);
} else {
itemController.btn_expand_toggle.setImageResource(R.drawable.tri_top);
}
itemController.btn_expand_toggle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (item.invisibleChildren == null) {
item.invisibleChildren = new ArrayList<>();
int count = 0;
int pos = data.indexOf(itemController.refferalItem);
while (data.size() > pos + 1 && data.get(pos + 1).type == CHILD) {
item.invisibleChildren.add(data.remove(pos + 1));
count++;
}
notifyItemRangeRemoved(pos + 1, count);
itemController.btn_expand_toggle.setImageResource(R.drawable.tri_bottom);
} else {
int pos = data.indexOf(itemController.refferalItem);
int index = pos + 1;
for (Item i : item.invisibleChildren) {
data.add(index, i);
index++;
}
notifyItemRangeInserted(pos + 1, index - pos - 1);
itemController.btn_expand_toggle.setImageResource(R.drawable.tri_top);
item.invisibleChildren = null;
}
}
});
break;
case CHILD:
final ListChildViewHolder listChildViewHolder = (ListChildViewHolder) holder;
TextView itemTextView = listChildViewHolder.peopleName;
final ImageView imageView = listChildViewHolder.checkPeople;
imageView.setImageResource(R.drawable.ic_unchecked);
itemTextView.setText(data.get(position).text);
listChildViewHolder.checkPeople.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!item.check) {
imageView.setImageResource(R.drawable.ic_checked);
item.check = true;
}else {
imageView.setImageResource(R.drawable.ic_unchecked);
item.check = false;
}
}
});
break;
}
}
@Override
public int getItemViewType(int position) {
return data.get(position).type;
}
@Override
public int getItemCount() {
return data.size();
}
private static class ListHeaderViewHolder extends RecyclerView.ViewHolder {
public TextView header_title;
public ImageView btn_expand_toggle;
public Item refferalItem;
public ListHeaderViewHolder(View itemView) {
super(itemView);
header_title = itemView.findViewById(R.id.className);
btn_expand_toggle = itemView.findViewById(R.id.checkClass);
}
}
private static class ListChildViewHolder extends RecyclerView.ViewHolder {
public TextView peopleName;
public ImageView checkPeople;
public ListChildViewHolder(View itemView) {
super(itemView);
peopleName = itemView.findViewById(R.id.peopleName);
checkPeople = itemView.findViewById(R.id.checkPeople);
}
}
public static class Item {
public int type;
public String text;
public String phone;
public boolean check;
public List<Item> invisibleChildren;
public Item() {
}
public Item(int type, String text, boolean check, String phone) {
this.type = type;
this.text = text;
this.check = check;
this.phone = phone;
}
}
}
|
package com.datayes.textmining.storm.topology;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import com.datayes.textmining.Utils.ConfigFileLoader;
import com.datayes.textmining.Utils.LogUtil;
import com.datayes.textmining.storm.bolt.ReportClsbolt;
import com.datayes.textmining.storm.bolt.RptSummarizeBolt;
import com.datayes.textmining.storm.spout.ReportProcessSpout;
import backtype.storm.Config;
import backtype.storm.LocalCluster;
import backtype.storm.StormSubmitter;
import backtype.storm.generated.AlreadyAliveException;
import backtype.storm.generated.InvalidTopologyException;
import backtype.storm.topology.TopologyBuilder;
/**
* ReportsClsTopology.java
* com.datayes.algorithm.dpipe.reportClsStorm.storm.topology
* 工程:rptClassificationKeyWords
* 功能: report processing topology
*
* author date time
* ─────────────────────────────────────────────
* jiminzhou 2014年2月10日 下午1:24:17
*
* Copyright (c) 2014, Datayes All Rights Reserved.
*/
public class ReportsClsTopology {
public ReportsClsTopology() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TridentTopology topology = new TridentTopology();
// Map<Integer,Integer> result = new TreeMap<Integer, Integer>();
// Log4jConfig log4j = new Log4jConfig();
// log4j.setLog4jFilePath(args[0]);
// log4j.setLog4jThreshold("debug");
// log4j.resetLog4jConfig();
TopologyBuilder topologyBuilder = new TopologyBuilder();
topologyBuilder.setSpout("run_spout", new ReportProcessSpout(), 1);
// topologyBuilder.setSpout("update_spout", new ModelUpdtSpout(), 1);
// topologyBuilder.setBolt("company_classifier",
// new CompanyClassificationBolt(), 1).shuffleGrouping("input");
// topologyBuilder.setBolt("event_classifier",
// new EventClassificationBolt(), 1).shuffleGrouping(
// "company_classifier");
//
// topologyBuilder.setBolt("hotnews_mining", new HotNewsMiningBolt(), 1)
// .shuffleGrouping("input");
topologyBuilder.setBolt("rpt_classifier", new ReportClsbolt(args), 1).shuffleGrouping("run_spout");
topologyBuilder.setBolt("rpt_summerizar", new RptSummarizeBolt(args) , 1).shuffleGrouping("run_spout");
// topologyBuilder.setBolt("aggregation", new
// AggregationBolt("10.20.112.103",6379), 1)12c
// .shuffleGrouping("event_classifier")
// .shuffleGrouping("hotnews_mining")
// .shuffleGrouping("subject_extraction")
// .shuffleGrouping("summarizer");
Config config = new Config();
config.setDebug(false);
config.setNumWorkers(1);
config.setMaxSpoutPending(5000);
config.setNumAckers(1);
// config.setMessageTimeoutSecs(5);
// config.setMaxTaskParallelism(5);
//
/*LocalCluster localCluster = new LocalCluster();
localCluster.submitTopology("report_classification", config,
topologyBuilder.createTopology());*/
try {
StormSubmitter.submitTopology("report_classification", config, topologyBuilder.createTopology());
}catch(Exception e)
{
e.printStackTrace();
}
}
}
|
package com.gagetalk.gagetalkcustomer.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.gagetalk.gagetalkcommon.constant.ConstValue;
import com.gagetalk.gagetalkcommon.util.MyLog;
import com.gagetalk.gagetalkcustomer.database.AccessDB;
/**
* Created by hyochan on 7/12/15.
*/
public class ChatReadReceiver extends BroadcastReceiver {
private static final String TAG = "ChatReadReceiver";
private String marId;
@Override
public void onReceive(Context context, Intent intent) {
MyLog.d(TAG, "ChatReadReceiver : " + intent.getAction());
if(intent.getAction().equals(ConstValue.CHAT_READ_RECEIVER)){
marId = intent.getStringExtra("mar_id");
// update local chatroom db
AccessDB.getInstance(context).updateChatRoomReadFlag(marId);
}
}
}
|
package com.zareca.prototype;
import java.util.ArrayList;
/**
* @Auther: ly
* @Date: 2020/10/15 11:17
* @Description:
*/
public class PrototypeTest {
public static void main(String[] args) throws Exception {
QiTianDaSheng qiTianDaSheng = new QiTianDaSheng();
qiTianDaSheng.setName("孙悟空");
qiTianDaSheng.setHeight(190);
qiTianDaSheng.setWeight(160);
ArrayList<String> list = new ArrayList<String>();
list.add("孙1");
list.add("孙2");
qiTianDaSheng.setSon(list);
JiGuBang jiGuBang = new JiGuBang();
jiGuBang.setJlong(200);
jiGuBang.setJshort(100);
qiTianDaSheng.setJiGuBang(jiGuBang);
System.out.println(qiTianDaSheng);
QiTianDaSheng clone = (QiTianDaSheng)qiTianDaSheng.clone();
clone.getJiGuBang().setJshort(300);
clone.setName("美猴王");
clone.setHeight(230);
System.out.println(qiTianDaSheng);
System.out.println(clone);
System.out.println(qiTianDaSheng.getName()==clone.getName());
System.out.println(qiTianDaSheng.getHeight() == qiTianDaSheng.getHeight());
System.out.println(qiTianDaSheng.getSon() == clone.getSon());
System.out.println(qiTianDaSheng.getJiGuBang() == clone.getJiGuBang());
}
}
|
package com.beike.entity.onlineorder;
import com.beike.entity.merchant.Merchant;
public class BranchInfo extends Merchant {
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((branchid == null) ? 0 : branchid.hashCode());
result = prime * result
+ ((branchname == null) ? 0 : branchname.hashCode());
result = prime * result
+ ((businesstime == null) ? 0 : businesstime.hashCode());
result = prime * result + ((logo == null) ? 0 : logo.hashCode());
result = prime * result + Float.floatToIntBits(reviewRate);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
BranchInfo other = (BranchInfo) obj;
if (branchid == null) {
if (other.branchid != null)
return false;
} else if (!branchid.equals(other.branchid))
return false;
if (branchname == null) {
if (other.branchname != null)
return false;
} else if (!branchname.equals(other.branchname))
return false;
if (businesstime == null) {
if (other.businesstime != null)
return false;
} else if (!businesstime.equals(other.businesstime))
return false;
if (logo == null) {
if (other.logo != null)
return false;
} else if (!logo.equals(other.logo))
return false;
if (Float.floatToIntBits(reviewRate) != Float
.floatToIntBits(other.reviewRate))
return false;
return true;
}
private String businesstime;
private String branchname;
private Long branchid;
public Long getBranchid() {
return branchid;
}
public void setBranchid(Long branchid) {
this.branchid = branchid;
}
private String logo;
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
public String getBusinesstime() {
return businesstime;
}
public void setBusinesstime(String businesstime) {
this.businesstime = businesstime;
}
public String getBranchname() {
return branchname;
}
public void setBranchname(String branchname) {
this.branchname = branchname;
}
public float getReviewRate() {
return reviewRate;
}
public void setReviewRate(float reviewRate) {
this.reviewRate = reviewRate;
}
private float reviewRate;
}
|
/*
* 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 servlet;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import connection.Issue;
import connection.Usermanager;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.text.SimpleDateFormat;
import javax.servlet.annotation.WebServlet;
public class createuserissue extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int k = 0;
String user = request.getParameter("user_id");
String n = request.getParameter("name");
String e = request.getParameter("user_email");
String ph = request.getParameter("phn");
String l = request.getParameter("location");
String s = request.getParameter("subject");
String d = request.getParameter("dept");
String des = request.getParameter("descrip");
String fd = " ";
String pr = "low";
String sta = "open";
String rt = " ";
String min = " ";
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
String date1= date.toString();
List<Integer> ids = new ArrayList<Integer>();
List <Issue> list = Issue.get_issue();
for (Issue i:list)
{
ids.add(Integer.parseInt(i.getissue_id()));
}
k = Collections.max(ids,null);
k = k+1;
String str = String.valueOf(k);
Issue issue = new Issue();
issue.setissue_id(str);
issue.setsubject(s);
issue.setdes(des);
issue.setname(n);
issue.setlocation(l);
issue.setstatus(sta);
issue.setuser(user);
issue.setfeedback(fd);
issue.setfeedback_rate(rt);
issue.setdepartment(d);
issue.setpriority(pr);
issue.setphn(ph);
issue.setemail(e);
issue.setdate(date1);
issue.setminfeed(min);
if(user != "" || s != "" || e != "" || ph != "" || l != "" || n != "" || des != "" || d != "" )
{ try{
int[] arr = Usermanager.user_create_issue(issue);
if(arr[0]>=0){
k=arr[1];
response.sendRedirect("createIssue.jsp?m1="+k);
}
else {
response.sendRedirect("createIssue.jsp?m2=failed");
}
}
catch(Exception ex){
Logger.getLogger(Usermanager.class.getName()).log(Level.SEVERE, null, ex);
}
}
else
{
response.sendRedirect("createissue.jsp");
}
}
}
|
package com.yf.bigdata.kafka.hollysys.factory;
import org.springframework.beans.factory.DisposableBean;
/**
* @author: YangFei
* @description: 服务生命周期
* @create:2020-12-03 15:32
*/
public interface LifeCycle extends DisposableBean, AutoCloseable {
/**
* 描述: 启动服务
*
* @author ZhangYi
* @date 2019-10-25 12:30:34
*/
public void start();
/**
* 描述: 关闭(销毁)服务
*
* @author ZhangYi
* @date 2019-10-25 12:30:34
*/
public void reconnect();
/**
* 描述: 是否延迟加载
*
* @author ZhangYi
* @date 2019-10-25 12:30:34
*/
public boolean delay();
@Override
default public void destroy() throws Exception {
close();
}
/**
* @throws InterruptedException
* @throws Exception
* @描述 切换CPU负荷(防止CPU负荷100 %)
* @author ZhangYi
* @时间 2020年10月22日 上午9:59:27
*/
default public void release() throws InterruptedException {
Thread.sleep(3);
}
/**
* 描述: 检查连接是否连通
*
* @param uris 多地址以','分割(地址与端口以':'分割)
* @return
* @author ZhangYi
* @date 2020-06-12 17:11:02
*/
// default public boolean ping(String uris) {
// return HttpUtils.isConnected(uris);
// }
}
|
package ru.yandex.yamblz.ui.recyclerstuff;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import ru.yandex.yamblz.R;
import ru.yandex.yamblz.ui.recyclerstuff.interfaces.IGetItemColor;
import static android.support.v7.widget.RecyclerView.NO_POSITION;
public class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.ContentHolder>
implements IGetItemColor {
private final Random rnd = new Random();
private final List<Integer> colors = new ArrayList<>();
private static final int CHANGE_COLOR_DURATION = 100;
public ContentAdapter() {
super();
setHasStableIds(true);
}
@Override
public ContentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final ContentHolder contentHolder = new ContentHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.content_item, parent, false));
contentHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int newColor = ContentAdapter.this.getRandomColor();
int position = contentHolder.getAdapterPosition();
if (position == NO_POSITION)
return;
ValueAnimator valueAnimator
= ValueAnimator.ofObject(new ArgbEvaluator(), colors.get(position), newColor);
valueAnimator.addUpdateListener(animation ->
contentHolder.itemView.setBackgroundColor((Integer) animation.getAnimatedValue()));
valueAnimator.setDuration(CHANGE_COLOR_DURATION);
valueAnimator.start();
colors.set(position, newColor);
notifyItemChanged(position);
}
});
return contentHolder;
}
@Override
public void onBindViewHolder(ContentHolder holder, int position) {
holder.bind(getColorForPosition(position));
}
@Override
public int getItemCount() {
return Integer.MAX_VALUE;
}
@Override
public long getItemId(int position) {
addIfNotExist(position);
return colors.get(position);
}
private Integer getColorForPosition(int position) {
addIfNotExist(position);
return colors.get(position);
}
public void notifyAllMoved() {
notifyDataSetChanged();
}
private int getRandomColor() {
return Color.rgb(rnd.nextInt(255), rnd.nextInt(255), rnd.nextInt(255));
}
private void addIfNotExist(int position) {
while (position >= colors.size())
colors.add(getRandomColor());
}
public void moveElement(int prevPos, int nextPos) {
Collections.swap(colors, prevPos, nextPos);
notifyItemMoved(prevPos, nextPos);
}
public void deleteElement(int pos) {
colors.remove(pos);
notifyItemRemoved(pos);
}
@Override
public int getDefaultColorForItem(int itemPosition) {
if (itemPosition < 0 || itemPosition >= colors.size())
return 0;
return colors.get(itemPosition);
}
public static class ContentHolder extends RecyclerView.ViewHolder {
ContentHolder(View itemView) {
super(itemView);
}
void bind(int color) {
itemView.setBackgroundColor(color);
((TextView) itemView).setText("#".concat(Integer.toHexString(color).substring(2)));
}
}
}
|
package kr.co.shop.batch.order.model.master;
import kr.co.shop.batch.order.model.master.base.BaseOcOrderProductHistory;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Data
public class OcOrderProductHistory extends BaseOcOrderProductHistory {
}
|
package net.awesomekorean.podo;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.android.billingclient.api.AccountIdentifiers;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.List;
public class PurchaseInfo {
FirebaseFirestore db = FirebaseFirestore.getInstance();
public String orderId;
public String userEmail;
public String tag;
public String purchaseToken;
public int purchaseState;
public Long purchaseTime;
public AccountIdentifiers accountIdentifiers;
public String signature;
public boolean acknowledged;
public String sku;
public String skuPrice;
public int responseCode;
public String responseMessage;
public PurchaseInfo(Context context, BillingResult billingResult, Purchase purchase, String skuPrice) {
String CHALLENGER = "challenger";
String POINT = "point";
this.orderId = purchase.getOrderId();
this.userEmail = SharedPreferencesInfo.getUserEmail(context);
this.purchaseToken = purchase.getPurchaseToken();
this.purchaseState = purchase.getPurchaseState();
this.purchaseTime = purchase.getPurchaseTime();
this.accountIdentifiers = purchase.getAccountIdentifiers();
this.acknowledged = purchase.isAcknowledged();
this.signature = purchase.getSignature();
this.sku = purchase.getSku();
this.skuPrice = skuPrice;
this.responseCode = billingResult.getResponseCode();
this.responseMessage = billingResult.getDebugMessage();
if(sku.contains(CHALLENGER)) {
this.tag = CHALLENGER;
} else if(sku.contains(POINT)) {
this.tag = POINT;
}
}
public boolean checkPurchase() {
String GPA = "GPA";
String subOrderId = orderId.substring(0, 3);
if (subOrderId.equals(GPA)) {
System.out.println("True purchasing");
return true;
} else {
System.out.println("Fake purchasing");
return false;
}
}
public void uploadInfo() {
db.collection("android/podo/purchase").add(this).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
System.out.println("구매기록을 저장했습니다.");
}
});
}
}
|
// SPDX-License-Identifier: BSD-3-Clause
// -*- Java -*-
//
// Copyright (c) 2005, Matthew J. Rutherford <rutherfo@cs.colorado.edu>
// Copyright (c) 2005, University of Colorado at Boulder
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the University of Colorado at Boulder nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
package org.xbill.DNS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
class SerialTest {
@Test
void compare_NegativeArg1() {
long arg1 = -1;
long arg2 = 1;
assertThrows(IllegalArgumentException.class, () -> Serial.compare(arg1, arg2));
}
@Test
void compare_OOBArg1() {
long arg1 = 0xFFFFFFFFL + 1;
long arg2 = 1;
assertThrows(IllegalArgumentException.class, () -> Serial.compare(arg1, arg2));
}
@Test
void compare_NegativeArg2() {
long arg1 = 1;
long arg2 = -1;
assertThrows(IllegalArgumentException.class, () -> Serial.compare(arg1, arg2));
}
@Test
void compare_OOBArg2() {
long arg1 = 1;
long arg2 = 0xFFFFFFFFL + 1;
assertThrows(IllegalArgumentException.class, () -> Serial.compare(arg1, arg2));
}
@Test
void compare_Arg1Greater() {
long arg1 = 10;
long arg2 = 9;
int ret = Serial.compare(arg1, arg2);
assertTrue(ret > 0);
}
@Test
void compare_Arg2Greater() {
long arg1 = 9;
long arg2 = 10;
int ret = Serial.compare(arg1, arg2);
assertTrue(ret < 0);
}
@Test
void compare_ArgsEqual() {
long arg1 = 10;
long arg2 = 10;
int ret = Serial.compare(arg1, arg2);
assertEquals(ret, 0);
}
@Test
void compare_boundary() {
long arg1 = 0xFFFFFFFFL;
long arg2 = 0;
int ret = Serial.compare(arg1, arg2);
assertEquals(-1, ret);
ret = Serial.compare(arg2, arg1);
assertEquals(1, ret);
}
@Test
void increment_NegativeArg() {
long arg = -1;
assertThrows(IllegalArgumentException.class, () -> Serial.increment(arg));
}
@Test
void increment_OOBArg() {
long arg = 0xFFFFFFFFL + 1;
assertThrows(IllegalArgumentException.class, () -> Serial.increment(arg));
}
@Test
void increment_reset() {
long arg = 0xFFFFFFFFL;
long ret = Serial.increment(arg);
assertEquals(1, ret);
}
@Test
void increment_normal() {
long arg = 10;
long ret = Serial.increment(arg);
assertEquals(arg + 1, ret);
}
}
|
package HakerRank.FraudulentActivityNotifications;
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
static double CalMedian(int[] tmpArr, int d) {
int countSum = 0;
double median = 0;
int medianIdx = 0;
/* 표본이 홀수 인 경우 */
if( d % 2 == 1 ) {
medianIdx = d / 2 + 1;
for(int i=0; i<tmpArr.length; i++) {
countSum += tmpArr[i];
if(countSum >= medianIdx) {
median = i;
break;
}
}
}else {
// 표본이 짝수인 경우 median은 두 값의 평균으로 한다.
medianIdx = d / 2;
double median1=0, median2=0;
for(int i=0; i<tmpArr.length; i++) {
countSum += tmpArr[i];
if(countSum >= medianIdx) {
median1 = i;
if(countSum > medianIdx) {
median2 = i;
break;
}else {
for(int j=i+1; j<tmpArr.length; j++) {
if(tmpArr[j] != 0) {
median2 = j;
break;
}
}
break;
}
}
}
median = (median1 + median2)/2.0;
}
return median;
}
// Complete the activityNotifications function below.
static int activityNotifications(int[] expenditure, int d) {
int count = 0;
int[] tmpArr = new int[201];
for(int i = 0 ; i < d ; i++) {
tmpArr[expenditure[i]]++;
}
//System.out.println(">> 초기상태");
//print(tmpArr, expenditure.length);
double median = 0;
for(int i = d ; i < expenditure.length ; i++) {
//System.out.println("i:"+i);
median = CalMedian(tmpArr, d);
//System.out.println("Median: "+median);
if(median*2 <= expenditure[i]) {
count++;
}
tmpArr[expenditure[i-d]]--;
tmpArr[expenditure[i]]++;
//print(tmpArr, expenditure.length);
}
return count;
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String[] nd = scanner.nextLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
int[] expenditure = new int[n];
String[] expenditureItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int expenditureItem = Integer.parseInt(expenditureItems[i]);
expenditure[i] = expenditureItem;
}
int result = activityNotifications(expenditure, d);
System.out.println(result);
// bufferedWriter.write(String.valueOf(result));
// bufferedWriter.newLine();
// bufferedWriter.close();
scanner.close();
}
}
|
package com.fhsoft.word.control;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSON;
import com.fhsoft.base.bean.JsonResult;
import com.fhsoft.base.bean.Page;
import com.fhsoft.model.PlaceName;
import com.fhsoft.model.SubjectProperty;
import com.fhsoft.model.Word;
import com.fhsoft.util.ExcelContentParser;
import com.fhsoft.word.service.NameAndPlaceNameService;
/**
*
* @Classname com.fhsoft.word.control.NameAndPlaceNameCtrol
* @Description
*
* @author lw
* @Date 2015-11-17 上午10:44:18
*
*/
@Controller
public class NameAndPlaceNameCtrol {
@Autowired
private NameAndPlaceNameService nameService;
private Logger logger = Logger.getLogger(NameAndPlaceNameCtrol.class);
@RequestMapping("toPlaceName.do")
public String czyw(){
return "word/placeNameList";
}
@RequestMapping("addPlaceName")
@ResponseBody
public Object addWord(HttpServletRequest request, HttpServletResponse response,PlaceName name){
JsonResult result = new JsonResult();
try {
nameService.addName(name);
result.setSuccess(true);
result.setMsg("添加成功!");
} catch (Exception e) {
result.setMsg("添加失败!");
logger.error("英文人名地名信息添加失败!", e);
}
return JSON.toJSONString(result);
}
@RequestMapping("updatePlaceName")
@ResponseBody
public Object updateWord(HttpServletRequest request, HttpServletResponse response,PlaceName name){
JsonResult result = new JsonResult();
try {
nameService.updateName(name);
result.setSuccess(true);
result.setMsg("修改成功!");
} catch (Exception e) {
result.setMsg("修改失败!");
logger.error("英文人名地名信息修改失败!", e);
}
return JSON.toJSONString(result);
}
@RequestMapping("delPlaceName")
@ResponseBody
public Object delWord(HttpServletRequest request, HttpServletResponse response,PlaceName name){
JsonResult result = new JsonResult();
try {
nameService.delName(name);
result.setSuccess(true);
result.setMsg("删除成功!");
} catch (Exception e) {
result.setMsg("删除失败!");
logger.error("英文人名地名信息删除失败!", e);
}
return JSON.toJSONString(result);
}
@RequestMapping("placeNameList")
@ResponseBody
public Object placeNameList(HttpServletRequest request, HttpServletResponse response,PlaceName name){
int pageRows=20;
int page=1;
if(null!=request.getParameter("rows")){
pageRows=Integer.parseInt(request.getParameter("rows").toString());
}
if(null!=request.getParameter("page")){
page=Integer.parseInt(request.getParameter("page").toString());
}
Page pageInfo = null;
try {
pageInfo = nameService.list(page,pageRows,name);
} catch(Exception e) {
e.printStackTrace();
logger.error("得到英文人名地名信息信息出错", e);
}
return pageInfo;
}
@RequestMapping("uploadPlaceName")
@ResponseBody
public Object uploadEnglishWord(MultipartFile file,HttpServletRequest request, HttpServletResponse response){
JsonResult result = new JsonResult();
try {
ExcelContentParser<PlaceName> parser = new ExcelContentParser<PlaceName>();
List<PlaceName> list = new ArrayList<PlaceName>();
String[] propertyNames = {"name","cname","type"};
parser.parseExcel(list, PlaceName.class, file.getInputStream(), propertyNames, file.getOriginalFilename(), 1);
String msg = nameService.save(list);
if("success".equals(msg)) {
result.setSuccess(true);
result.setMsg("上传成功");
} else {
result.setSuccess(false);
result.setMsg(msg);
}
} catch (Exception e) {
result.setMsg("删除失败!");
logger.error("英文人名地名信息删除失败!", e);
}
return JSON.toJSONString(result);
}
@RequestMapping("getPlaceNameInfo")
@ResponseBody
public Object getPlaceNameInfo(HttpServletRequest request, HttpServletResponse response,PlaceName name){
JsonResult result = new JsonResult();
try {
List<PlaceName> list = nameService.getWordInfo(name);
List<SubjectProperty> sps = nameService.getJctxOfYw();
List<Word> ws = nameService.getWordJctx(name);
Map<String,Object> obj = new HashMap<String, Object>();
obj.put("list", list);
obj.put("sps", sps);
obj.put("ws", ws);
result.setObj(obj);
result.setSuccess(true);
} catch (Exception e) {
result.setSuccess(false);
result.setMsg("查询英文人名地名信息信息失败!");
logger.error("查询英文人名地名信息信息失败!", e);
}
return JSON.toJSONString(result);
}
@RequestMapping("getPlaceNameBasic")
@ResponseBody
public Object getPlaceNameBasic(HttpServletRequest request, HttpServletResponse response,PlaceName name){
try {
List<PlaceName> list = nameService.getWordInfo(name);
return list.get(0);
} catch (Exception e) {
logger.error("查询英文人名地名信息失败!", e);
}
return null;
}
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.r2dbc.core.binding;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* Index-based bind marker. This implementation creates indexed bind
* markers using a numeric index and an optional prefix for bind markers
* to be represented within the query string.
*
* @author Mark Paluch
* @author Jens Schauder
* @since 5.3
*/
class IndexedBindMarkers implements BindMarkers {
private static final AtomicIntegerFieldUpdater<IndexedBindMarkers> COUNTER_INCREMENTER =
AtomicIntegerFieldUpdater.newUpdater(IndexedBindMarkers.class, "counter");
private final int offset;
private final String prefix;
// access via COUNTER_INCREMENTER
@SuppressWarnings("unused")
private volatile int counter;
/**
* Create a new {@link IndexedBindMarker} instance given {@code prefix} and {@code beginWith}.
* @param prefix bind parameter prefix
* @param beginWith the first index to use
*/
IndexedBindMarkers(String prefix, int beginWith) {
this.counter = 0;
this.prefix = prefix;
this.offset = beginWith;
}
@Override
public BindMarker next() {
int index = COUNTER_INCREMENTER.getAndIncrement(this);
return new IndexedBindMarker(this.prefix + "" + (index + this.offset), index);
}
/**
* A single indexed bind marker.
* @author Mark Paluch
*/
static class IndexedBindMarker implements BindMarker {
private final String placeholder;
private final int index;
IndexedBindMarker(String placeholder, int index) {
this.placeholder = placeholder;
this.index = index;
}
@Override
public String getPlaceholder() {
return this.placeholder;
}
@Override
public void bind(BindTarget target, Object value) {
target.bind(this.index, value);
}
@Override
public void bindNull(BindTarget target, Class<?> valueType) {
target.bindNull(this.index, valueType);
}
public int getIndex() {
return this.index;
}
}
}
|
package com.kheirallah.inc.linkedlists;
//Medium
//Crack the coding interview 2.8
/*
Given a circular linked list, implement an algorithm that returns the node at the beginning of the loop.
Definition:
Circular linked list: A (corrupt) linked list in which a node's next pointer points to an earlier node, so as to make a loop in the linked list
Input: 1 -> 2 -> 3 -> 4 -> 2 (same 2 as earlier)
Output: 2
*/
import com.kheirallah.inc.model.LinkedList;
import com.kheirallah.inc.model.Node;
public class LoopDetection {
public static void main(String[] args) {
Node head = new Node(1);
LinkedList list = new LinkedList(head);
list.appendToTail(2);
list.appendToTail(3);
list.appendToTail(4);
list.appendToTail(head.next);
System.out.println(findLoop(head).value);
}
//Time Complexity O(N), traverse through the length of the list
//Space Complexity O(1), no new data structures needed
private static Node findLoop(Node head) {
Node slow = head;
Node fast = head;
//Find meeting point. This will be LOOP_SIZE - k steps into the linked list
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) { //Collision
break;
}
}
//Error check - no meeting point, and therefore no loop
if (fast == null || fast.next == null) {
return null;
}
//Move slow to Head. Keep fast at Meeting point. Each are k steps from the loop start. If they move at the same pace, they must meet at the loop start.
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
//Both now point to the start of the loop
return fast;
}
}
|
package ch.zli.m223.punchclock.domain;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
@Entity
public class Company {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cid;
@Column(nullable = false)
private String name;
@OneToMany
private List<ApplicationUser> user;
public Long getCid() {
return cid;
}
public void setCid(Long cid) {
this.cid = cid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ApplicationUser> getUser() {
return user;
}
public void setUser(List<ApplicationUser> user) {
this.user = user;
}
}
|
package com.project.myclassroom1.ui.home;
public class Details {
String Type;
String TeacherName,Date,Link,roll,Marks;
public String getMarks() {
return Marks;
}
public void setMarks(String marks) {
Marks = marks;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getLink() {
return Link;
}
public void setLink(String link) {
Link = link;
}
public String getTeacherName() {
return TeacherName;
}
public void setTeacherName(String teacherName) {
TeacherName = teacherName;
}
}
|
package graphvisualizer.graph;
//Interface for the priority queue ADT
public interface PriorityQueue <K,V>{
int size();
boolean isEmpty();
Entry<K,V> insert(K key, V value) throws IllegalArgumentException;
Entry<K,V> min();
Entry<K,V> removeMin();
}
|
package org.group.projects.simple.gis.online.model.transport;
import lombok.*;
@NoArgsConstructor
@AllArgsConstructor
@ToString(includeFieldNames = true)
@EqualsAndHashCode
public class AbstractSearchEntity implements SearchEntity {
@Getter
@Setter
protected String content;
}
|
package fr.eni.cach.clinique.bo;
public class Secretaire extends Personnel {
public Secretaire() {
// TODO Auto-generated constructor stub
}
public Secretaire(int codePersonnel, String nom, String motPasse, String role, boolean archive) {
super(codePersonnel, nom, motPasse, role, archive);
// TODO Auto-generated constructor stub
}
public Secretaire(String nom, String motPasse, String role, boolean archive) {
super(nom, motPasse, role, archive);
// TODO Auto-generated constructor stub
}
}
|
package com.feng.collection.map;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 常用方法
* 添加、删除、修改操作:
* Object put(Object key,Object value):将指定key-value添加到(或修改)当前map对象中
* void putAll(Map m):将m中的所有key-value对存放到当前map中
* Object remove(Object key):移除指定key的key-value对,并返回value
* void clear():清空当前map中的所有数据
* 元素查询的操作:
* Object get(Object key):获取指定key对应的value
* boolean containsKey(Object key):是否包含指定的key
* boolean containsValue(Object value):是否包含指定的value
* int size():返回map中key-value对的个数
* boolean isEmpty():判断当前map是否为空
* boolean equals(Object obj):判断当前map和参数对象obj是否相等
* 元视图操作的方法:
* Set keySet():返回所有key构成的Set集合
* Collection values():返回所有value构成的Collection集合
* Set entrySet():返回所有key-value对构成的Set集合
*/
public class MapMethodTest {
/**
* 添加、删除、修改操作:
*/
@Test
public void test1(){
Map map = new HashMap();
Map map2 = new HashMap();
map.put(101,"晴天");
map2.put(102,"厚厚的云");
map2.put(103,"斜阳");
// map2.put(101,"雨天");
map.putAll(map2);
System.out.println("----put-putAll----");
System.out.println(map2);
System.out.println(map);
System.out.println("----remove----");
System.out.println(map);
Object remove = map.remove(101);
System.out.println(remove);
System.out.println(map);
Object remove2 = map.remove("102");
System.out.println(remove2);
System.out.println(map);
System.out.println("----clear----");
System.out.println(map);
map.clear();
System.out.println(map);
}
/**
* 元素查询的操作:
*/
@Test
public void test2(){
Map map = new HashMap();
Map map2 = new HashMap();
map.put(101,"晴天");
map2.put(102,"厚厚的云");
map2.put(103,"斜阳");
map.putAll(map2);
System.out.println("-----test/out-------");
System.out.println(map);
System.out.println("-----get-------");//只能根据key值获取value值
System.out.println(map.get(102));
System.out.println(map.get("晴天"));
System.out.println("-----containsKey、Value-------");//返回Boolean值
System.out.println(map.containsKey(101));
System.out.println(map.containsValue("晴天"));
System.out.println("-----size-------");
System.out.println(map.size());
System.out.println(map2.size());
System.out.println("-----isEmpty()------");
System.out.println(map.isEmpty());
map.clear();
System.out.println(map.isEmpty());
System.out.println("------equals-------");
System.out.println(map.equals(map2));
map2.clear();
System.out.println(map.equals(map2));//都为空结果为:true
}
/**
* 元视图操作的方法:
*/
@Test
public void test3(){
Map map = new HashMap();
Map map2 = new HashMap();
map.put(101,"晴天");
map2.put(102,"厚厚的云");
map2.put(103,"斜阳");
map.putAll(map2);
System.out.println("-----test/out-------");
System.out.println(map);
System.out.println("-----keySet-------");
System.out.println(map);
Set set = map.keySet();
System.out.println(set);
System.out.println("-----values-------");
System.out.println(map);
Collection values = map.values();
System.out.println(values);
System.out.println("-----entrySet-------");
System.out.println(map);
Set set1 = map.entrySet();
System.out.println(set1);
}
}
|
package com.seven.contract.manage.common;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* Created by apple on 2018/12/11.
*/
public interface BaseDao<T> {
public void insert(T t);
public void update(T t);
public T selectOne(@Param("id") long id);
public void deleteById(@Param("id") long id);
public List<T> selectList(Map<String, Object> params);
public int totalRows(Map<String, Object> params);
}
|
package webuters.com.geet_uttarakhand20aprilpro.pojo;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sunil on 16-02-2018.
*/
public class LatestSongHolderAdapter {
List<LatestSongPOJO> latestSongPOJOS=new ArrayList<>();
public List<LatestSongPOJO> getLatestSongPOJOS() {
return latestSongPOJOS;
}
public void setLatestSongPOJOS(List<LatestSongPOJO> latestSongPOJOS) {
this.latestSongPOJOS = latestSongPOJOS;
}
}
|
package com.dambroski.repositories;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.dambroski.domain.Produto;
@Repository
public interface ProdutoRepository extends JpaRepository<Produto, Integer> {
Page<Produto> findDistinctByNomeContainingIgnoreCaseAndCategoriasIdIn(String nome, List<Integer> categoriasId, Pageable pageable);
}
|
package gr.javapemp.vertxonspring.model;
import io.vertx.codegen.annotations.DataObject;
import io.vertx.core.json.JsonObject;
import javax.persistence.*;
@Entity
@Table(name = "users")
@DataObject(generateConverter = true)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "auth_guid")
private String authGuid;
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "timezone")
private String timezone;
@Column(name = "lang")
private String lang;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String lastName;
@Column(name = "enabled")
private boolean enabled;
public User() {
}
public User(JsonObject jsonObject) {
UserConverter.fromJson(jsonObject, this);
}
public JsonObject toJson() {
JsonObject json = new JsonObject();
UserConverter.toJson(this, json);
return json;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAuthGuid() {
return authGuid;
}
public void setAuthGuid(String authGuid) {
this.authGuid = authGuid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
|
package com.huruilei.designpattern.observer;
/**
* @author: huruilei
* @date: 2019/10/31
* @description:
* @return
*/
public interface Subject {
void registerObserver(Observer o);
void removeObserver(Observer o);
void notifyObservers();
}
|
/* ------------------------------------------------------------------------------
* 软件名称:他秀手机版
* 公司名称:多宝科技
* 开发作者:Yongchao.Yang
* 开发时间:2014年7月15日/2014
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容均来自多宝科技研发部,仅限内部交流使用,未经过公司许可 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.duobao.video.logic
* fileName:UserService.java
* -------------------------------------------------------------------------------
*/
package com.ace.database.service;
import java.util.ArrayList;
import java.util.HashMap;
import javax.transaction.UserTransaction;
import org.apache.log4j.Logger;
import com.ace.database.ds.UserTransactionManager;
import com.ace.database.module.AccountModule;
import com.ace.database.module.OrderModule;
import com.rednovo.ace.constant.Constant;
import com.rednovo.ace.entity.AD;
import com.rednovo.ace.entity.GoodInfo;
import com.rednovo.ace.entity.Order;
import com.rednovo.ace.entity.Server;
import com.rednovo.ace.globalData.ServerRoutManager;
import com.rednovo.tools.Validator;
/**
* @author yongchao.Yang/2014年7月15日
*/
public class OrderService {
private static Logger logger = Logger.getLogger(OrderService.class);
public OrderService() {}
/**
* 创建订单
*
* @param payerId
* @param receiverId
* @param goodId
* @param goodCnt
* @return
* @author Yongchao.Yang
* @param orderChannel
* @param channel
* @since 2016年3月4日下午3:12:27
*/
public static String createOrder(String payerId, String thirdId, String receiverId, String goodId, int goodCnt, Constant.payChannel channel, String orderChannel, String appchannel) {
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule om = new OrderModule();
try {
ut.begin();
String orderId = om.createOrder(payerId, thirdId, receiverId, goodId, goodCnt, channel, orderChannel, appchannel);
if (Validator.isEmpty(orderId)) {
ut.rollback();
} else {
ut.commit();
return orderId;
}
} catch (Exception e) {
try {
logger.error("[用户 " + payerId + "创建订单失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return "";
}
/**
* 开通订单
*
* @param orderId
* @param openUserId
* @return
* @author Yongchao.Yang
* @since 2016年3月4日下午3:16:46
*/
public static String openOrder(String orderId, String openUserId) {
String exeRes = Constant.OperaterStatus.FAILED.getValue();
OrderModule om = new OrderModule();
AccountModule am = new AccountModule();
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
exeRes = om.openOrder(orderId, openUserId, "");
if (!Constant.OperaterStatus.SUCESSED.getValue().equals(exeRes)) {
ut.rollback();
return exeRes;
}
Order order = om.getOrder(orderId);
// 加币
exeRes = am.addMoney(order.getReceiverId(), order.getPayerId(), order.getCoinAmount(), Constant.logicType.ORDER);
if (!Constant.OperaterStatus.SUCESSED.getValue().equals(exeRes)) {
ut.rollback();
return exeRes;
}
ut.commit();
} catch (Exception e) {
try {
logger.error("[" + openUserId + "开通订单" + orderId + "失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
am.release();
}
return exeRes;
}
/**
* 获取订单列表
*
* @param orderId
* @param openUserId
* @return
* @author Yongchao.Yang
* @since 2016年3月4日下午3:16:46
*/
public static ArrayList<Order> getOrderList(String userId, String beginTime, String endTime, Constant.OrderStatus status, int page, int pageSize) {
OrderModule om = new OrderModule();
ArrayList<Order> list = null;
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
list = om.getOrderList(userId, beginTime, endTime, status, page, pageSize);
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取订单列表失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return list;
}
/**
* 获取系统配置参数
*
* @return
* @author Yongchao.Yang
* @since 2016年3月17日下午12:21:42
*/
public static HashMap<String, String> getSysConfig() {
OrderModule om = new OrderModule();
HashMap<String, String> map = new HashMap<String, String>();
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
map = om.getSysConfig();
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取系统配置参数失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return map;
}
public static Order getOrder(String orderId) {
Order order = null;
OrderModule om = new OrderModule();
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
order = om.getOrder(orderId);
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取订单" + orderId + "失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return order;
}
public static Order getOrderWithThirdId(String thirdId) {
Order order = null;
OrderModule om = new OrderModule();
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
order = om.getOrderWithThirdId(thirdId);
ut.commit();
} catch (Exception e) {
try {
logger.error("[根据第三方ID" + thirdId + "获取订单失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return order;
}
/**
* 获取待同步商品信息
*
* @param synId
* @param maxCnt
* @return
* @author Yongchao.Yang
* @since 2016年3月7日上午12:03:37
*/
public static ArrayList<GoodInfo> getAllGood() {
ArrayList<GoodInfo> list = null;
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule om = new OrderModule();
try {
ut.begin();
list = om.getAllGood();
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取待同步商品数据失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return list;
}
public static ArrayList<AD> getADList(String status) {
ArrayList<AD> list = new ArrayList<AD>();
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule om = new OrderModule();
try {
ut.begin();
list = om.getADList(status);
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取待同步广告数据失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return list;
}
/**
* 获取服务器列表
*
* @return
* @author Yongchao.Yang
* @since 2016年5月26日下午3:52:41
*/
public static ArrayList<Server> getServerList() {
ArrayList<Server> list = new ArrayList<Server>();
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule om = new OrderModule();
try {
ut.begin();
list = om.getServers();
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取服务器配置数据失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return list;
}
/**
* @param id
* @param ip
* @param port
* @param status
* @param description
* @param string
* @author ZuKang.Song
* @since 2016年6月8日上午11:54:32
*/
public static String updateServerInfo(String id, String ip, String port, String status, String description) {
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule um = new OrderModule();
String exeCode = "";
try {
ut.begin();
if (Validator.isEmpty(ServerRoutManager.getServer(id))) {
exeCode = um.addServerInfo(ip, port, description);
} else {
exeCode = um.updateServerInfo(id, ip, port, status, description);
}
ut.commit();
} catch (Exception e) {
logger.error("[修改seversetting失败]", e);
try {
ut.rollback();
} catch (Exception e1) {
logger.error("修改seversetting失败回滚事务时错误]", e1);
}
} finally {
um.release();
}
return exeCode;
}
/**
* @param id
* @author ZuKang.Song
* @return
* @since 2016年6月8日上午11:55:16
*/
public static String delServerInfo(String id) {
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule um = new OrderModule();
String exeCode = "";
try {
ut.begin();
exeCode = um.delServerInfo(id);
ut.commit();
} catch (Exception e) {
logger.error("[修改severInfo失败]", e);
try {
ut.rollback();
} catch (Exception e1) {
logger.error("修改severInfo失败回滚事务时错误]", e1);
}
} finally {
um.release();
}
return exeCode;
}
/**
* 获取订单列表
*
* @param userId
* @param startTime
* @param endTime
* @param status
* @param page
* @param pageSize
* @return
* @author ZuKang.Song
* @since 2016年6月13日下午5:09:02
*/
public static ArrayList<Order> getOrderList(String userId, String startTime, String endTime, String status, int page, int pageSize) {
OrderModule om = new OrderModule();
ArrayList<Order> list = null;
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
if (Validator.isEmpty(userId)) {
list = om.getOrderList(startTime, endTime, status, page, pageSize);
} else {
list = om.getOrderList(userId, startTime, endTime, status, page, pageSize);
}
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取订单列表失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return list;
}
/**
* 创建批量付款批次号
*
* @param batchFee 批量付款总金额
* @param batchNum 几笔
* @param detailData 0315006^testture0002@126.com^常炜买家^20.00^hello
* @return
* @author ZuKang.Song
* @since 2016年6月23日下午3:19:36
*/
public static String createBatchInfo(String batchFee, String batchNum) {
UserTransaction ut = UserTransactionManager.getUserTransaction();
OrderModule om = new OrderModule();
try {
ut.begin();
String batchNo = om.createBatchInfo(batchFee, batchNum);
if (Validator.isEmpty(batchNo)) {
ut.rollback();
} else {
ut.commit();
return batchNo;
}
} catch (Exception e) {
try {
logger.error("[创建批量付款失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return "";
}
/**
* 获取批量打款号
* @param batchNo
* @return
* @author ZuKang.Song
* @since 2016年6月24日下午5:12:23
*/
public static boolean getBatchInfo(String batchNo) {
boolean istrue = false;
OrderModule om = new OrderModule();
UserTransaction ut = UserTransactionManager.getUserTransaction();
try {
ut.begin();
istrue = om.getBatchInfo(batchNo);
ut.commit();
} catch (Exception e) {
try {
logger.error("[获取批量打款号" + batchNo + "失败]", e);
ut.rollback();
} catch (Exception e1) {
e1.printStackTrace();
}
} finally {
om.release();
}
return istrue;
}
}
|
package come.clientside.models;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Address {
private String cityName;
private String StreetName;
private long pinCode;
}
|
package com.lifeplan.lifeplanapplication;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class LifePlanEditKazokuListViewAdapter extends BaseAdapter {
/**
* フィールド
*/
Context context;
LayoutInflater layoutInflater = null;
ArrayList<LifePlanEditKazokuListItem> lifePlanEditKazokuListItems;
/**
* コンストラクタ
*/
public LifePlanEditKazokuListViewAdapter(Context context) {
this.context = context;
this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/**
* メソッド
*/
public void setLifePlanEditKazokuList(ArrayList<LifePlanEditKazokuListItem> lifePlanEditKazokuListItems) {
this.lifePlanEditKazokuListItems = lifePlanEditKazokuListItems;
}
/**
* イベント
*/
@Override
public int getCount() {
return lifePlanEditKazokuListItems.size();
}
@Override
public Object getItem(int position) {
return lifePlanEditKazokuListItems.get(position);
}
@Override
public long getItemId(int position) {
return lifePlanEditKazokuListItems.get(position).getId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = layoutInflater.inflate(R.layout.fragment_lifeplan_edit_kazoku_listview, parent, false);
((ImageView) convertView.findViewById(R.id.ivKazokuListIcon)).setImageResource (lifePlanEditKazokuListItems.get(position).getIconId());
((TextView) convertView.findViewById(R.id.tvKazokuName)).setText(lifePlanEditKazokuListItems.get(position).getKazokuName());
((TextView) convertView.findViewById(R.id.tvKazokuOld)).setText(lifePlanEditKazokuListItems.get(position).getOld().toString());
return convertView;
}
}
|
package Models;
import java.sql.Date;
public class Abono {
private int idAbono;
private int CodigoFactura;
private double Monto;
private Date fecha;
private int idTipoDePago;
public Abono() {
}
public Abono(int idAbono, int CodigoFactura, double Monto, Date fecha, int idTipoDePago) {
this.idAbono = idAbono;
this.CodigoFactura = CodigoFactura;
this.Monto = Monto;
this.fecha = fecha;
this.idTipoDePago = idTipoDePago;
}
public int getIdAbono() {
return idAbono;
}
public void setIdAbono(int idAbono) {
this.idAbono = idAbono;
}
public int getCodigoFactura() {
return CodigoFactura;
}
public void setCodigoFactura(int CodigoFactura) {
this.CodigoFactura = CodigoFactura;
}
public double getMonto() {
return Monto;
}
public void setMonto(double Monto) {
this.Monto = Monto;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
public int getIdTipoDePago() {
return idTipoDePago;
}
public void setIdTipoDePago(int idTipoDePago) {
this.idTipoDePago = idTipoDePago;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.