text
stringlengths
10
2.72M
package com.dexvis.dex.task.tablemanipulation; import org.simpleframework.xml.Root; import com.dexvis.dex.exception.DexException; import com.dexvis.dex.wf.DexTask; import com.dexvis.dex.wf.DexTaskState; @Root public class AddRowNumber extends DexTask { public AddRowNumber() { super("Table Manipulation", "Add Row Number", "table_manipulation/AddRowNumber.html"); } public DexTaskState execute(DexTaskState state) throws DexException { state.getDexData().getHeader().add(0, "RI"); for (int row = 0; row < state.getDexData().getData().size(); row++) { state.getDexData().getData().get(row).add(0, "" + (row + 1)); } return state; } }
package com.badawy.carservice.fragment; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.badawy.carservice.R; import com.badawy.carservice.activity.HomepageActivity; import com.badawy.carservice.activity.SpeedFixPopUpActivity; import com.badawy.carservice.adapters.TimeAppointmentRecyclerAdapter; import com.badawy.carservice.models.CarModel; import com.badawy.carservice.models.ServiceTypeModel; import com.badawy.carservice.models.BookingModel; import com.badawy.carservice.models.TimeAppointmentModel; import com.badawy.carservice.models.UserProfileModel; import com.badawy.carservice.utils.Constants; import com.badawy.carservice.utils.CustomCalendar; import com.badawy.carservice.utils.MySharedPreferences; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import static android.app.Activity.RESULT_OK; /** * A simple {@link Fragment} subclass. */ public class DeliveryCarSpeedFixFragment extends Fragment { private final String TAG = "Speed Fix"; private final int SERVICE_TYPE_REQUEST_CODE = 1002; private SimpleDateFormat dateFormatter = new SimpleDateFormat("EEEE, d MMMM", Locale.ENGLISH); private ArrayList<ServiceTypeModel> speedFixServiceList; private DatabaseReference dbRef; private Gson gson = new Gson(); private ArrayList<TimeAppointmentModel> timeList; private Intent intent; private CustomCalendar customCalendar; private ConstraintLayout serviceLayout; private TextView serviceTypeDescription, serviceTypePrice; private TimeAppointmentRecyclerAdapter timeAdapter; private RecyclerView timeRecyclerView; private String selectedDay; private DatabaseReference timeRef; private Button orderNowBtn; private EditText additionalNote; private CarModel selectedCarObject; private ScrollView mainLayout; private Activity activity; private boolean isServiceSelected = false; private int count; public DeliveryCarSpeedFixFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_speedfix, container, false); activity = getActivity(); initializeUi(view); mainLayout.setVisibility(View.GONE); timeRecyclerView.setVisibility(View.GONE); // Get Selected Car getSelectedCar(); // Get Service List From Firebase fetchSpeedFixDataFromFirebase(); // Intent to send lists to Pop up activity intent = new Intent(getActivity(), SpeedFixPopUpActivity.class); // Init Appointment Time Root timeList = new ArrayList<>(); timeAdapter = new TimeAppointmentRecyclerAdapter(getActivity()); timeRef = FirebaseDatabase .getInstance() .getReference() .child(Constants.AVAILABLE_APPOINTMENTS) .child(Constants.DELIVERY); timeRef.keepSynced(true); isCurrentTimeIsAfterNinePM(); // Get Current Day to Retrieve Available Appointments selectedDay = customCalendar.getDateInYearFormat(); checkTimeOfSpeedFix(); customCalendar.setResetDayClick(new View.OnClickListener() { @Override public void onClick(View v) { customCalendar.resetDate(); isCurrentTimeIsAfterNinePM(); selectedDay = customCalendar.getDateInYearFormat(); checkTimeOfSpeedFix(); } }); customCalendar.setArrowClick(new View.OnClickListener() { @Override public void onClick(View v) { customCalendar.getNextDay(); selectedDay = customCalendar.getDateInYearFormat(); checkTimeOfSpeedFix(); } }); serviceLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(intent, SERVICE_TYPE_REQUEST_CODE); } }); ImageView navMenuBtn = view.findViewById(R.id.speedFix_navMenuBtn); navMenuBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HomepageActivity.openDrawer(); } }); orderNowBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!isServiceSelected) { Toast.makeText(getActivity(), "Please Select a service First", Toast.LENGTH_SHORT).show(); } else { showProgress(); final BookingModel bookingObject = new BookingModel(); Gson gson = new Gson(); String userSerializedData = MySharedPreferences.read(MySharedPreferences.USER_DATA, ""); if (!userSerializedData.equals("")) { UserProfileModel userDataObject = gson.fromJson(userSerializedData, UserProfileModel.class); if (userDataObject.getPhoneNumber() == null || userDataObject.getAddress() == null || userDataObject.getUserName() == null) { hideProgress(); Toast.makeText(getContext(), "Please Fill your information first then try again", Toast.LENGTH_SHORT).show(); if (activity instanceof HomepageActivity) { ((HomepageActivity) activity).openSettings(); } } else { bookingObject.setServiceName(TAG); bookingObject.setPrice(serviceTypePrice.getText().toString().trim()); bookingObject.setServiceDescription(serviceTypeDescription.getText().toString().trim()); bookingObject.setDate(selectedDay); bookingObject.setTimeObject(timeAdapter.getTimeObject()); bookingObject.setUserId(userDataObject.getUserId()); bookingObject.setNote(additionalNote.getText().toString().trim()); bookingObject.setCarId(selectedCarObject.getCarID()); bookingObject.setAddress(userDataObject.getAddress()); dbRef = FirebaseDatabase.getInstance().getReference().child(Constants.AVAILABLE_APPOINTMENTS) .child(Constants.DELIVERY).child(Constants.SPEED_FIX).child(bookingObject.getDate()) .child(String.valueOf(bookingObject.getTimeObject().getId())); final DatabaseReference bookingRef = FirebaseDatabase.getInstance().getReference().child(Constants.BOOKING); final DatabaseReference userRef = FirebaseDatabase.getInstance().getReference().child(Constants.USERS); dbRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { dbRef.child("booked").setValue("yes"); String orderID = bookingRef.push().getKey(); assert orderID != null; bookingObject.setOrderId(orderID); bookingRef.child(Constants.APPOINTMENTS).child(orderID) .setValue(bookingObject); userRef.child(bookingObject.getUserId()).child(Constants.APPOINTMENTS_ORDERS) .child(Constants.APPOINTMENTS) .child(orderID).setValue(0); if (activity instanceof HomepageActivity) { hideProgress(); ((HomepageActivity) activity).prepareDialog(R.layout.dialog_appointment_successful); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } } } }); return view; } private void initializeUi(View view) { customCalendar = view.findViewById(R.id.speedFix_customCalender); serviceLayout = view.findViewById(R.id.speedFix_serviceLayout); serviceTypeDescription = view.findViewById(R.id.speedFix_serviceTypeDescription); serviceTypePrice = view.findViewById(R.id.speedFix_serviceCost); timeRecyclerView = view.findViewById(R.id.speedFix_timeRecyclerView); orderNowBtn = view.findViewById(R.id.speedFix_orderNowButton); mainLayout = view.findViewById(R.id.speedFix_mainLayout); additionalNote = view.findViewById(R.id.speedFix_typeNoteET); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == SERVICE_TYPE_REQUEST_CODE && resultCode == RESULT_OK) { if (data != null) { // retrieve the serialized list and convert it to LIST type String serializedReturningList = data.getStringExtra(Constants.SERVICE_TYPES_NAME_RESULT); Type type = new TypeToken<ArrayList<ServiceTypeModel>>() { }.getType(); ArrayList<ServiceTypeModel> selectedList = gson.fromJson(serializedReturningList, type); StringBuilder builder = new StringBuilder(); if (selectedList.isEmpty()) { serviceTypeDescription.setText(R.string.click_to_select_service); isServiceSelected = false; } else { for (int i = 0; i < selectedList.size(); i++) { if (i + 1 != selectedList.size()) { builder.append(selectedList.get(i).getServiceName()).append(" + "); } else { builder.append(selectedList.get(i).getServiceName()); } } serviceTypeDescription.setText(builder.toString()); } int servicePrice = data.getIntExtra(Constants.SERVICE_TYPES_PRICE_RESULT, 0); if (servicePrice == 0) { serviceTypePrice.setText(R.string.please_select_a_service_first); } else { serviceTypePrice.setText(String.valueOf(servicePrice)); } isServiceSelected = true; } } } private void fetchSpeedFixDataFromFirebase() { showProgress(); speedFixServiceList = new ArrayList<>(); dbRef = FirebaseDatabase.getInstance().getReference().child(Constants.APP_DATA).child(Constants.SPEED_FIX); dbRef.keepSynced(true); dbRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for (DataSnapshot child : dataSnapshot.getChildren() ) { speedFixServiceList.add(new ServiceTypeModel(child.getKey(), (int) ((long) child.getValue()))); } String serializedList = gson.toJson(speedFixServiceList); intent.putExtra(Constants.SPEED_FIX, serializedList); hideProgress(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } // fetch Available Appointments private void checkTimeOfSpeedFix() { count = 0; showProgress(); // Data for Time final String[] time = {"12:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00"}; final String[] timeOfDay = {"pm", "pm", "pm", "pm", "pm", "pm", "pm", "pm", "pm", "pm"}; timeRef.child(Constants.SPEED_FIX).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { if (!dataSnapshot.hasChild(selectedDay)) { // Filling time list in Firebase for (int i = 0; i < time.length; i++) { TimeAppointmentModel obj = new TimeAppointmentModel(); obj.setId(i); obj.setBooked("no"); obj.setTime(time[i]); obj.setTimeOfDay(timeOfDay[i]); timeRef.child(Constants.SPEED_FIX) .child(selectedDay) .child(String.valueOf(obj.getId())) .setValue(obj); hideProgress(); } } else { timeList = new ArrayList<>(); // if day exist ... return available appointments for (DataSnapshot ds : dataSnapshot.child(selectedDay).getChildren()) { TimeAppointmentModel obj = new TimeAppointmentModel(); obj.setBooked(ds.child("booked").getValue(String.class)); obj.setId((int) ((long) ds.child("id").getValue())); obj.setTime(ds.child("time").getValue(String.class)); obj.setTimeOfDay(ds.child("timeOfDay").getValue(String.class)); timeList.add(obj); updateView(timeList); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } private void getSelectedCar() { assert getArguments() != null; String serializedSelectedCarObject = getArguments().getString(Constants.SELECTED_CAR); Gson gson = new Gson(); Type type = new TypeToken<CarModel>() { }.getType(); selectedCarObject = gson.fromJson(serializedSelectedCarObject, type); } private void isCurrentTimeIsAfterNinePM() { Calendar cal = Calendar.getInstance(); int currTime = cal.get(Calendar.HOUR_OF_DAY); int targetTime = 21; if (currTime >= targetTime) { customCalendar.getNextDay(); selectedDay = customCalendar.getDateInYearFormat(); checkTimeOfSpeedFix(); } } // Update Time Recycler Adapter private void updateView(ArrayList<TimeAppointmentModel> timeList) { count++; ArrayList<TimeAppointmentModel> availableTimeList = new ArrayList<>(); for (TimeAppointmentModel obj : timeList ) { String appointmentTime = obj.getTime(); if (customCalendar.getDay().equals(dateFormatter.format(Calendar.getInstance().getTime()))) { if (customCalendar.getTimeOfDay().equals("am")) { if (obj.getBooked().equals("no")) { availableTimeList.add(obj); } } else if (customCalendar.getTimeOfDay().equals("pm")) { if (appointmentTime.compareTo(customCalendar.getTime()) > 0) { if (obj.getBooked().equals("no")) { availableTimeList.add(obj); } } } } else { if (obj.getBooked().equals("no")) { availableTimeList.add(obj); } } } if (count == 10) { if (availableTimeList.size() >= 1) { timeAdapter.setTimeList(availableTimeList); timeRecyclerView.setAdapter(timeAdapter); hideProgress(); timeRecyclerView.setVisibility(View.VISIBLE); mainLayout.setVisibility(View.VISIBLE); } else { customCalendar.getNextDay(); selectedDay = customCalendar.getDateInYearFormat(); checkTimeOfSpeedFix(); } } } private void showProgress() { if (activity instanceof HomepageActivity) { ((HomepageActivity) activity).showProgressBar(true); } } private void hideProgress() { if (activity instanceof HomepageActivity) { ((HomepageActivity) activity).showProgressBar(false); } } private void fakeTimeTest(View view) { // Simple Testing Data for Time // byte[] id = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; // String[] time = {"11:00", "12:00", "1:00", "2:00", "3:00", "4:00", "5:00", "6:00", "7:00", "8:00", "9:00"}; // String[] timeOfDay = {"am", "pm", "pm", "pm", "pm", "pm", "pm", "pm", "pm", "pm", "pm"}; // String[] booked = {"yes", "yes", "yes", "yes", "yes", "no", "no", "no", "no", "no", "no"}; // // Filling time list // for (int i = 0 ; i<time.length;i++){ // // if (booked[i].equals("no")){ // timeList.add(new TimeAppointmentModel(id[i],time[i], timeOfDay[i],booked[i])); // } // // } // // Testing time list // RecyclerView timeRecyclerView = view.findViewById(R.id.speedFix_timeRecyclerView); // final TimeAppointmentRecyclerAdapter timeAdapter = new TimeAppointmentRecyclerAdapter(getActivity(), timeList); // timeRecyclerView.setAdapter(timeAdapter); } }
package at.ac.tuwien.infosys; import at.ac.tuwien.infosys.entities.DataStore; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; /** * Created by lenaskarlat on 4/10/17. */ @Controller public class SensorController { private static final String RECEIVE_URL = "/receive"; DataStore dataStoreInstance = DataStore.getInstance(); @RequestMapping(value = RECEIVE_URL, method = RequestMethod.POST) public void acceptData(@RequestParam("time") String time, @RequestParam("data") String data) throws Exception { dataStoreInstance.putSensorDataFrame(time, data); } }
/* * 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 registraclinic.pessoa; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import registraclinic.cidade.Cidade; /** * * @author Karlos */ @Entity @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) public abstract class Pessoa implements Serializable{ @Id @GeneratedValue(strategy = GenerationType.TABLE) private int idPessoa; private String nomePessoa; private String telefonePessoa; private String telefoneOcionalPessoa; private Date dataNascimentoPessoa; private String sexoPessoa; private String idadePessoa; private String cpfPessoa; private String rgPessoa; private String estadoCivilPessoa; private String enderecoPessoa; private String bairroPessoa; private String enderecoNumeroPessoa; private String complementoPessoa; private String naturalidadePessoa; private String ocupacaoPessoa; private String profissaoPessoa; private Cidade cidade; public int getIdPessoa() { return idPessoa; } public void setIdPessoa(int idPessoa) { this.idPessoa = idPessoa; } public String getNomePessoa() { return nomePessoa; } public void setNomePessoa(String nomePessoa) { this.nomePessoa = nomePessoa; } public String getTelefonePessoa() { return telefonePessoa; } public void setTelefonePessoa(String telefonePessoa) { this.telefonePessoa = telefonePessoa; } public String getTelefoneOcionalPessoa() { return telefoneOcionalPessoa; } public void setTelefoneOcionalPessoa(String telefoneOcionalPessoa) { this.telefoneOcionalPessoa = telefoneOcionalPessoa; } public Date getDataNascimentoPessoa() { return dataNascimentoPessoa; } public void setDataNascimentoPessoa(Date dataNascimentoPessoa) { this.dataNascimentoPessoa = dataNascimentoPessoa; } public String getSexoPessoa() { return sexoPessoa; } public void setSexoPessoa(String sexoPessoa) { this.sexoPessoa = sexoPessoa; } public String getIdadePessoa() { return idadePessoa; } public void setIdadePessoa(String idadePessoa) { this.idadePessoa = idadePessoa; } public String getCpfPessoa() { return cpfPessoa; } public void setCpfPessoa(String cpfPessoa) { this.cpfPessoa = cpfPessoa; } public String getRgPessoa() { return rgPessoa; } public void setRgPessoa(String rgPessoa) { this.rgPessoa = rgPessoa; } public String getEstadoCivilPessoa() { return estadoCivilPessoa; } public void setEstadoCivilPessoa(String estadoCivilPessoa) { this.estadoCivilPessoa = estadoCivilPessoa; } public String getEnderecoPessoa() { return enderecoPessoa; } public void setEnderecoPessoa(String enderecoPessoa) { this.enderecoPessoa = enderecoPessoa; } public String getBairroPessoa() { return bairroPessoa; } public void setBairroPessoa(String bairroPessoa) { this.bairroPessoa = bairroPessoa; } public String getEnderecoNumeroPessoa() { return enderecoNumeroPessoa; } public void setEnderecoNumeroPessoa(String enderecoNumeroPessoa) { this.enderecoNumeroPessoa = enderecoNumeroPessoa; } public String getComplementoPessoa() { return complementoPessoa; } public void setComplementoPessoa(String complementoPessoa) { this.complementoPessoa = complementoPessoa; } public String getNaturalidadePessoa() { return naturalidadePessoa; } public void setNaturalidadePessoa(String naturalidadePessoa) { this.naturalidadePessoa = naturalidadePessoa; } public String getOcupacaoPessoa() { return ocupacaoPessoa; } public void setOcupacaoPessoa(String ocupacaoPessoa) { this.ocupacaoPessoa = ocupacaoPessoa; } public String getProfissaoPessoa() { return profissaoPessoa; } public void setProfissaoPessoa(String profissaoPessoa) { this.profissaoPessoa = profissaoPessoa; } public Cidade getCidade() { return cidade; } public void setCidade(Cidade cidade) { this.cidade = cidade; } }
package org.notice.beans; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class RatedSkills implements Serializable { private int skillId = 0, userSkillId = 0, level = 0 , numEndorsement = 0; private String userId = null , SkillName = null; private BigDecimal avgEndorsement; public RatedSkills(int skillId, int userSkillId, int level, int numEndorsement, String userId, String skillName, BigDecimal avgEndorsement) { super(); this.skillId = skillId; this.userSkillId = userSkillId; this.level = level; this.numEndorsement = numEndorsement; this.userId = userId; this.SkillName = skillName; this.avgEndorsement = avgEndorsement; } public int getSkillId() { return skillId; } public void setSkillId(int skillId) { this.skillId = skillId; } public int getUserSkillId() { return userSkillId; } public void setUserSkillId(int userSkillId) { this.userSkillId = userSkillId; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getNumEndorsement() { return numEndorsement; } public void setNumEndorsement(int numEndorsement) { this.numEndorsement = numEndorsement; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getSkillName() { return SkillName; } public void setSkillName(String skillName) { SkillName = skillName; } public BigDecimal getAvgEndorsement() { return avgEndorsement; } public void setAvgEndorsement(BigDecimal avgEndorsement) { this.avgEndorsement = avgEndorsement; } @Override public String toString() { return "GetRatedSkills [skillId=" + skillId + ", userSkillId=" + userSkillId + ", level=" + level + ", numEndorsement=" + numEndorsement + ", userId=" + userId + ", SkillName=" + SkillName + ", avgEndorsement=" + avgEndorsement + "]"; } }
/* * 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 lister; import java.awt.Dimension; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Oldřich */ public class Control { public final String PATH; private int levels; private int timeout; private boolean keepOnDomain; private String domain; private String userAgent; private Set<String> imgsPaths; private Set<String> linkPaths; private Set<String> errPaths; private Set<String> scannedPaths; public Control(String PATH) { this.PATH = PATH; this.levels = 2; this.timeout = 0; this.keepOnDomain = true; this.userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0"; this.domain = new String(); //clearResults(); } public void Scan() throws InterruptedException, URISyntaxException { List<Page> threads = new LinkedList<>(); clearResults(); URI uri = new URI(PATH); domain = uri.getHost(); Page p = new Page(PATH); configPage(p); p.start(); p.join(); scannedPaths.add(PATH); linkPaths.removeAll(scannedPaths); linkPaths.removeAll(errPaths); imgsPaths.removeAll(scannedPaths); for (int deep = 0; deep < levels; deep++) { Set<String> tempLinks = Collections.synchronizedSet(new HashSet<>(linkPaths)); for (String path : linkPaths) { uri = new URI(path); p = new Page(path); configPage(p, tempLinks); if (deep + 1 == levels) { p.setLeaf(true); } p.start(); threads.add(p); } System.out.println("Threads:" + threads.size()); for (Page thread : threads) { thread.join(); scannedPaths.add(thread.getPATH()); } threads.clear(); linkPaths.addAll(tempLinks); linkPaths.removeAll(scannedPaths); imgsPaths.removeAll(scannedPaths); linkPaths.removeAll(errPaths); } } public List<Picture> limitTo(Dimension size) { List<Picture> list = new ArrayList<>(10); for (String imgsPath : imgsPaths) { Picture picture = new Picture(imgsPath); Dimension pr = picture.vratRozliseni(); if (pr != null && ((pr.height >= size.height && pr.width >= size.height) || (pr.height >= size.width && pr.width >= size.height))) { list.add(picture); } } return list; } private void configPage(Page p) { configPage(p, linkPaths); } private void configPage(Page p, Set<String> tempLinks) { p.setImgsPaths(imgsPaths); p.setErrPaths(errPaths); p.setLinkPaths(tempLinks); p.setTimeout(timeout); p.setUserAgent(userAgent); p.setTopDomain(domain); p.setKeepOnDomain(keepOnDomain); } public final void clearResults() { this.imgsPaths = Collections.synchronizedSet(new HashSet<>()); this.linkPaths = Collections.synchronizedSet(new HashSet<>()); this.errPaths = Collections.synchronizedSet(new HashSet<>()); this.scannedPaths = Collections.synchronizedSet(new HashSet<>()); } public boolean isKeepOnDomain() { return keepOnDomain; } public void setKeepOnDomain(boolean keepOnDomain) { this.keepOnDomain = keepOnDomain; } public int getLevels() { return levels; } public void setLevels(int levels) { this.levels = levels; } public String getPATH() { return PATH; } public Set<String> getImgsPaths() { return imgsPaths; } public Set<String> getLinkPaths() { return linkPaths; } public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } public String getUserAgent() { return userAgent; } public void setUserAgent(String userAgent) { this.userAgent = userAgent; } public static void main(String[] args) { Control c = new Control("http://www.zive.cz/"); c.setLevels(1); c.setKeepOnDomain(true); c.setTimeout(3000); Dimension dim = new Dimension(300, 300); try { c.Scan(); } catch (InterruptedException ex) { Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(Control.class.getName()).log(Level.SEVERE, null, ex); } System.out.println(c.getImgsPaths()); System.out.println(c.getImgsPaths().size()); System.out.println("*************"); System.out.println(c.getLinkPaths()); System.out.println(c.getLinkPaths().size()); System.out.println("*************"); System.out.println(c.limitTo(dim)); System.out.println(); } }
package com.fszuberski.tweets.session.core; import at.favre.lib.crypto.bcrypt.BCrypt; import com.fszuberski.tweets.jwt.JWTService; import com.fszuberski.tweets.persistence.adapter.UserProfilePersistenceAdapter; import com.fszuberski.tweets.persistence.port.out.GetUserProfilePort; import com.fszuberski.tweets.session.core.domain.Session; import com.fszuberski.tweets.session.port.in.CreateSession; import com.fszuberski.tweets.session.port.in.CreateSession.CreateSessionException.InvalidUsernameAndPassword; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Optional; public class SessionService implements CreateSession { private final GetUserProfilePort getUserProfilePort; private final JWTService jwtService; public SessionService() { this(new UserProfilePersistenceAdapter(), new JWTService()); } public SessionService(GetUserProfilePort getUserProfilePort, JWTService jwtService) { if (getUserProfilePort == null) { throw new IllegalArgumentException( String.format("Exception while initializing %s - %s cannot be null", SessionService.class.getSimpleName(), GetUserProfilePort.class.getSimpleName())); } if (jwtService == null) { throw new IllegalArgumentException( String.format("Exception while initializing %s - %s cannot be null", SessionService.class.getSimpleName(), JWTService.class.getSimpleName())); } this.getUserProfilePort = getUserProfilePort; this.jwtService = jwtService; } public Session createSession(String username, String password) { validateInput(username, password); Optional<Map<String, Object>> userProfileMapOptional = getUserProfilePort.getUserProfileAsMap(username); if (userProfileMapOptional.isEmpty()) { throw new InvalidUsernameAndPassword(); } Map<String, Object> userProfileMap = userProfileMapOptional.get(); String passwordHash = (String) userProfileMap.get("PasswordHash"); if (passwordHash == null || passwordHash.isEmpty()) { throw new RuntimeException(); } BCrypt.Result authenticationResult = BCrypt .verifyer() .verify(password.getBytes(StandardCharsets.UTF_8), passwordHash.getBytes(StandardCharsets.UTF_8)); if (!authenticationResult.verified) { throw new InvalidUsernameAndPassword(); } return Session.fromMap(userProfileMap, jwtService.createAndSignJWT(username)); } private void validateInput(String username, String password) { boolean isInvalidUsername = username == null || username.trim().isEmpty(); boolean isInvalidPassword = password == null || password.trim().isEmpty(); if (isInvalidUsername || isInvalidPassword) { throw new InvalidUsernameAndPassword(); } } }
package me.ninabernick.cookingapplication.YoutubeDialog; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.youtube.player.YouTubeInitializationResult; import com.google.android.youtube.player.YouTubePlayer; import com.google.android.youtube.player.YouTubePlayerView; import me.ninabernick.cookingapplication.R; public class YoutubePopUp extends DialogFragment implements YouTubePlayer.Provider{ private YouTubePlayerView youtube_player; public YoutubePopUp(){}; public static YoutubePopUp newInstance(String youtube_url){ YoutubePopUp f = new YoutubePopUp(); Bundle args = new Bundle(); args.putString("youtube_url", youtube_url); f.setArguments(args); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.youtube_dialog, container); youtube_player = (YouTubePlayerView) view.findViewById(R.id.player); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final String videoId = getArguments().getString("youtube_url"); youtube_player.initialize(getString(R.string.youtube_api_key), new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) { youTubePlayer.cueVideo(videoId); } @Override public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) { // do nothing for now } }); } @Override public void initialize(String s, YouTubePlayer.OnInitializedListener onInitializedListener) { } }
package diabetes.aclass.diabetes; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.gson.JsonIOException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Iterator; import java.util.Set; import diabetes.aclass.dagger.component.DataJsonCallback; import diabetes.aclass.model.MedicEntity; import diabetes.aclass.presenter.PostManagement; import diabetes.aclass.presenter.PresenterImpl; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; import static diabetes.aclass.utils.Component.API_BASE; import static diabetes.aclass.utils.Component.API_GET_MEDIC_BYID; import static diabetes.aclass.utils.Component.API_POST_MEASUREMENTS; public class DoctorProfileActivity extends AppCompatActivity { PresenterImpl mainPresenter ; private TextView name; private TextView email; private TextView hospital; public MedicEntity assigned_medic; private SharedPreferences preferences ; SharedPreferences.Editor editor; private Set<String> set ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.doctor_profile_activity); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); name = findViewById(R.id.doc_name); email = findViewById(R.id.doc_email); hospital = findViewById(R.id.clinic_hospital); name.setText("serverNotResponding"); email.setText("serverNotResponding"); hospital.setText("serverNotResponding"); preferences = PreferenceManager.getDefaultSharedPreferences(this); editor = preferences.edit(); set = preferences.getStringSet("TO_SEND", null); if(!set.isEmpty()){ saveOLDMeasurements(); } loadData(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_profile) { Intent myIntent = new Intent(this, ProfileActivity.class); //this.startActivity(myIntent); startActivity(myIntent); return true; } if (id == R.id.action_help) { Intent myIntent = new Intent(this, HelpPageActivity.class); //this.startActivity(myIntent); startActivity(myIntent); return true; } if (id == R.id.action_logout) { final Intent intent = new Intent(this, LoginActivity.class); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso); mGoogleSignInClient.revokeAccess() .addOnCompleteListener(this, new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { //this.startActivity(myIntent); startActivity(intent); } }); } return super.onOptionsItemSelected(item); } public void saveOLDMeasurements(){ PostManagement pm = new PostManagement(); String url = API_POST_MEASUREMENTS; boolean up = true; Iterator<String> it = set.iterator(); while(it.hasNext()&& up ){ final String put = it.next(); pm.saveData(url, put, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { set.remove(put); editor.putStringSet("TO_SEND", set); editor.apply(); } }); } } private void loadData(){ try { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); int MEDIC_ID = preferences.getInt("MEDIC_ID", -1); mainPresenter = new PresenterImpl(); mainPresenter.fetchData(API_GET_MEDIC_BYID+MEDIC_ID, new DataJsonCallback() { @Override public void onSuccess(JSONObject response) { try { JSONArray array = response.getJSONArray("medic"); assigned_medic = new MedicEntity(); for (int i = 0; i < array.length(); i++) { JSONObject medic = array.getJSONObject(i); name.setText(medic.getString("medic_name")); email.setText(medic.getString("medic_mail")); hospital.setText(medic.getString("medic_hospital")); } } catch (JsonIOException | JSONException e) { Log.e("", e.getMessage(), e); } } }); } catch (Exception e) { e.printStackTrace(); } } public void goToHomePageActivity(View view) { Intent myIntent = new Intent(this, HomePageActivity.class); startActivity(myIntent); } public void goToGraphActivity(View view) { Intent myIntent = new Intent(this, GraphActivity.class); startActivity(myIntent); } public void goToHistoryActivity(View view) { Intent myIntent = new Intent(this, HistoryPageActivity.class); startActivity(myIntent); } }
package nl.guuslieben.circle.views.main; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.littemplate.LitTemplate; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.template.Id; import com.vaadin.flow.component.textfield.PasswordField; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.router.RouteAlias; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.Optional; import nl.guuslieben.circle.ClientService; import nl.guuslieben.circle.ServerResponse; import nl.guuslieben.circle.common.User; import nl.guuslieben.circle.common.UserData; import nl.guuslieben.circle.common.util.CertificateUtilities; import nl.guuslieben.circle.common.util.KeyUtilities; import nl.guuslieben.circle.common.util.PasswordUtilities; import nl.guuslieben.circle.views.MainLayout; @Route(value = "register", layout = MainLayout.class) @RouteAlias(value = "register", layout = MainLayout.class) @PageTitle("The Circle - Register") @Tag("register-view") @JsModule("./views/register-view.ts") public class RegisterView extends LitTemplate { private final transient ClientService service; @Id private TextField name; @Id private TextField email; @Id private PasswordField password; @Id private Button register; public RegisterView(ClientService service) { this.service = service; this.name.addValueChangeListener(event -> this.onValidate()); this.email.addValueChangeListener(event -> this.onValidate()); this.password.addValueChangeListener(event -> this.onValidate()); this.onValidate(); this.register.addClickListener(this::onRegister); } public void onValidate() { boolean enabled = !(this.email.getValue().isEmpty() || this.password.getValue().isEmpty() || this.name.getValue().isEmpty()); this.register.setEnabled(enabled); } public void onRegister(ClickEvent<Button> event) { Notification.show("Verifying server.."); final String email = this.email.getValue(); final UserData data = new UserData(this.name.getValue(), email); final Optional<X509Certificate> x509Certificate = this.service.csr(data, this.password.getValue()); final PublicKey publicKey = this.service.getPair(email).getPublic(); if (x509Certificate.isPresent()) { boolean validCertificate = CertificateUtilities.verify(x509Certificate.get(), this.service.getServerPublic()); if (!validCertificate) { Notification.show("Server is not secure"); return; } } else { Notification.show("Could not collect certificate from server"); return; } Notification.show("Server verified, registering user.."); final String password = this.password.getValue(); final User user = new User( email, this.name.getValue(), PasswordUtilities.encrypt(password, password, publicKey) ); final ServerResponse<Boolean> register = this.service.register(user); if (register.accepted() && register.getObject()) { final String base64private = KeyUtilities.encodeKeyToBase64(this.service.getPair(email).getPrivate()); final String privateKey = PasswordUtilities.encrypt(base64private, password, publicKey); this.service.store(privateKey, email); Notification.show(this.name.getValue() + " has been registered!"); } else { Notification.show(register.getMessage()); } } }
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ package com.microsoft.office365.meetingfeedback.model.service; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; public class RatingServiceAlarmManager { public static final int TEN_SECONDS_IN_MILLIS = 10000; private final AlarmManager mAlarmManager; private Context mContext; public RatingServiceAlarmManager(Context context) { mContext = context; mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); } public void scheduleRatingService() { Intent meetingsServiceIntent = new Intent(mContext, MyMeetingsService.class); final PendingIntent pIntent = PendingIntent.getService(mContext, MyMeetingsService.MEETING_REQUEST_CODE, meetingsServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT); long firstMillis = System.currentTimeMillis(); int intervalMillis = TEN_SECONDS_IN_MILLIS; mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, intervalMillis, pIntent); } public void cancelRatingService() { Intent intent = new Intent(mContext, MyMeetingsService.class); final PendingIntent pIntent = PendingIntent.getBroadcast(mContext, MyMeetingsService.MEETING_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); mAlarmManager.cancel(pIntent); } }
package org.gaoshin.openflier.util; public interface AnnotatedFieldCallback extends FieldFoundCallback { }
package com.hamatus.repository; import com.hamatus.domain.MapMarkerTranslation; import org.springframework.data.jpa.repository.*; import java.util.List; /** * Spring Data JPA repository for the MapMarkerTranslation entity. */ public interface MapMarkerTranslationRepository extends JpaRepository<MapMarkerTranslation,Long> { MapMarkerTranslation findByMapmarkerIdAndLangKey(Long id, String langKey); MapMarkerTranslation findFirst1ByMapmarkerId(Long mapMarkerId); }
package com.bot.handlers; import com.bot.CurrencyBot; import com.bot.DataTransformerUtil; import com.bot.currencies.Currency; import com.bot.enums.CalcCommands; import com.bot.enums.Commands; import org.telegram.telegrambots.api.objects.Message; import org.telegram.telegrambots.api.objects.Update; import org.telegram.telegrambots.exceptions.TelegramApiException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Properties; public class CalculatorHandler implements UpdateHandler { private CurrencyBot bot; private DataTransformerUtil dtu; private CalcCommands command = CalcCommands.DEF; private static String notNumber; private static String enterSum; private static String betterCurse; private static String sumLayout; private static String newSearch; private static String requests; public CalculatorHandler(CurrencyBot bot, DataTransformerUtil dtu) { this.bot = bot; this.dtu = dtu; try { loadProperties(); } catch (IOException e) { e.printStackTrace(); } } @Override public void handle(Update update) throws TelegramApiException { Message message = update.getMessage(); int sum; if (update.hasMessage() && message.hasText()) { String message_text = update.getMessage().getText(); try { sum = Integer.parseInt(message_text); if (sum < 1000) { bot.sendMsg(update, getSum(sum, command, update)); bot.sendMsg(update, newSearch); } else { bot.sendMsg(update, getSum(sum, command, update)); bot.sendMsg(update, newSearch); //bot.sendMsg(message, betterCurse); } } catch (NumberFormatException e) { try { switch (message_text) { case "/new": { bot.setCalcOff(update); bot.execute(KeyboardSupplier.getStandartKeyboard(update)); break; } case "/mstat": { bot.sendMsg(update, requests + bot.messageCounter); bot.sendMsg(update, newSearch); break; } case "/start": bot.execute(KeyboardSupplier.getCityKeyboard(update)); bot.removeCity(update); break; default: { if (message_text.equals(KeyboardSupplier.exit)) { bot.setCalcOff(update); bot.execute(KeyboardSupplier.getStandartKeyboard(update)); } else { command = CommandsSupplier.getCalcCommand(message_text); if (command == CalcCommands.NOT_NUMBER)bot.sendMsg(update, notNumber); bot.sendMsg(update, enterSum); } break; } } } catch (NullPointerException ex) { ex.printStackTrace(); bot.sendMsg(update, newSearch); } } } } @Override public void loadProperties() throws IOException { Properties propsMessage = new Properties(); InputStream in = getClass().getResourceAsStream("/ru_message.properties"); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8.name())); propsMessage.load(reader); newSearch = propsMessage.getProperty("new"); requests = propsMessage.getProperty("requests"); newSearch = propsMessage.getProperty("new"); enterSum = propsMessage.getProperty("enterSum"); notNumber = propsMessage.getProperty("notNumber"); betterCurse = propsMessage.getProperty("betterCurse"); sumLayout = propsMessage.getProperty("sumLayout"); } private String getSum(int count, CalcCommands command, Update update) { Float result = 0.0f; Map<Commands, Currency> map = dtu.getMap(); switch (command) { case SELL_USD: result = count * map.get(Commands.USD).getAuc_ask(bot.getCityForUserFromUpdate(update)); break; case BUY_USD: result = count * map.get(Commands.USD).getAuc_bid(bot.getCityForUserFromUpdate(update)); break; case SELL_EUR: result = count * map.get(Commands.EURO).getAuc_ask(bot.getCityForUserFromUpdate(update)); break; case BUY_EUR: result = count * map.get(Commands.EURO).getAuc_bid(bot.getCityForUserFromUpdate(update)); break; case SELL_RUB: result = count * map.get(Commands.RUB).getAuc_ask(bot.getCityForUserFromUpdate(update)); break; case BUY_RUB: result = count * map.get(Commands.RUB).getAuc_bid(bot.getCityForUserFromUpdate(update)); break; } return String.format(sumLayout, result); } }
package com.sample.web.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class ClientHealthStatusInfo { private Long id; private String name; private String streetLocation; private String cityLocation; private String email; private String healthStatus; // normal, bad or good }
/** */ package xtext.aventuraGrafica.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import xtext.aventuraGrafica.AbrirCerrar; import xtext.aventuraGrafica.AventuraGraficaPackage; import xtext.aventuraGrafica.Estado; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Abrir Cerrar</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link xtext.aventuraGrafica.impl.AbrirCerrarImpl#getEstado <em>Estado</em>}</li> * <li>{@link xtext.aventuraGrafica.impl.AbrirCerrarImpl#getNuevoValor <em>Nuevo Valor</em>}</li> * </ul> * * @generated */ public class AbrirCerrarImpl extends AccionImpl implements AbrirCerrar { /** * The cached value of the '{@link #getEstado() <em>Estado</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getEstado() * @generated * @ordered */ protected Estado estado; /** * The default value of the '{@link #getNuevoValor() <em>Nuevo Valor</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNuevoValor() * @generated * @ordered */ protected static final String NUEVO_VALOR_EDEFAULT = null; /** * The cached value of the '{@link #getNuevoValor() <em>Nuevo Valor</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getNuevoValor() * @generated * @ordered */ protected String nuevoValor = NUEVO_VALOR_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected AbrirCerrarImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return AventuraGraficaPackage.Literals.ABRIR_CERRAR; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Estado getEstado() { if (estado != null && estado.eIsProxy()) { InternalEObject oldEstado = (InternalEObject)estado; estado = (Estado)eResolveProxy(oldEstado); if (estado != oldEstado) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, AventuraGraficaPackage.ABRIR_CERRAR__ESTADO, oldEstado, estado)); } } return estado; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Estado basicGetEstado() { return estado; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setEstado(Estado newEstado) { Estado oldEstado = estado; estado = newEstado; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AventuraGraficaPackage.ABRIR_CERRAR__ESTADO, oldEstado, estado)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getNuevoValor() { return nuevoValor; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setNuevoValor(String newNuevoValor) { String oldNuevoValor = nuevoValor; nuevoValor = newNuevoValor; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, AventuraGraficaPackage.ABRIR_CERRAR__NUEVO_VALOR, oldNuevoValor, nuevoValor)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case AventuraGraficaPackage.ABRIR_CERRAR__ESTADO: if (resolve) return getEstado(); return basicGetEstado(); case AventuraGraficaPackage.ABRIR_CERRAR__NUEVO_VALOR: return getNuevoValor(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case AventuraGraficaPackage.ABRIR_CERRAR__ESTADO: setEstado((Estado)newValue); return; case AventuraGraficaPackage.ABRIR_CERRAR__NUEVO_VALOR: setNuevoValor((String)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case AventuraGraficaPackage.ABRIR_CERRAR__ESTADO: setEstado((Estado)null); return; case AventuraGraficaPackage.ABRIR_CERRAR__NUEVO_VALOR: setNuevoValor(NUEVO_VALOR_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case AventuraGraficaPackage.ABRIR_CERRAR__ESTADO: return estado != null; case AventuraGraficaPackage.ABRIR_CERRAR__NUEVO_VALOR: return NUEVO_VALOR_EDEFAULT == null ? nuevoValor != null : !NUEVO_VALOR_EDEFAULT.equals(nuevoValor); } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (nuevoValor: "); result.append(nuevoValor); result.append(')'); return result.toString(); } } //AbrirCerrarImpl
package by.gravity.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Created by ilya.shknaj on 25.10.14. */ public class CommonServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setContentType("text/plain; charset=UTF-8"); } }
package com.sinodynamic.hkgta.util.constant; public enum PassportType { HKID,VISA }
package Galaga; import java.util.Vector; //import java.util.*; //import java.io.*; //import java.lang.*; import java.awt.*; //import java.awt.event.*; import java.awt.image.*; import javax.swing.*; //import javax.imageio.*; //import java.net.*; public class Sprites extends JLabel { /** * */ private static final long serialVersionUID = 6541711507284205192L; // Holds the generated image BufferedImage image; // Integers for dealing with the image's placement int x, y; // Current X, Y Coordinates int initialX, initialY; // Initial X, Y Coordinates // Boolean for determining if the ship is moving along a curve boolean moving = false; boolean attack = false; // Boolean for an attacking ship boolean retreat = false; // Boolean for a retreating ship // Defines the dimensions of the image Dimension d; // Creates an temporarily initializes the point arrays used by the curve Point[] attackPoints = new Point[1], retreatPoints = new Point[1]; // Constants - Random Number Generator Seeds final static int RANDOM_MOVE_SEED = 50; // Seed for moving final static int RANDOM_FIRE_SEED = 30; // Seed for firing a bullet // Declares and initializes the random move time from 1 to 101 int randomMoveTime = (int) (((Math.random() * RANDOM_MOVE_SEED) + 1) + 50); int currentMoveTime = 0; // Time tracking variable // Declares and initializes the random firing time from 1 to 61 int randomFireTime = (int) (((Math.random() * RANDOM_FIRE_SEED) + 1) + 30); int currentFireTime = 0; // Time tracking variable //****************************************************************************** // Constructor that does nothing - Abstract Class... //****************************************************************************** public Sprites() { } //****************************************************************************** // Method that draws the image held within all Sprite-derived classes //****************************************************************************** public void draw(Graphics g, int x, int y) { g.drawImage(image, x, y, null); } //****************************************************************************** // Method returns the value of the right edge of the Sprite //****************************************************************************** public int getRightSide() { return x + d.width; } //****************************************************************************** // Method returns the value of the left edge of the Sprite //****************************************************************************** public int getLeftSide() { return x; } //****************************************************************************** // Method shifts the Sprite depending on the parameters passed //****************************************************************************** public void translate(int x, int y) { this.x += x; this.y += y; } //****************************************************************************** // Method returns the dimension of the Sprite image //****************************************************************************** public Dimension getDimension() { return d; } //****************************************************************************** // Method returns the x-coordinate of the upper left of Sprite image //****************************************************************************** public int getXCoordinate() { return x; } //****************************************************************************** // Method returns the y-coordinate of the upper left of the Sprite image //****************************************************************************** public int getYCoordinate() { return y; } //****************************************************************************** // Method that returns the center x-coordinate //****************************************************************************** public int getXCenter() { return x + (d.width / 2); } //****************************************************************************** // Method that returns the center y-coordinate //****************************************************************************** public int getYCenter() { return y + (d.height / 2); } //****************************************************************************** // Method that returns whether the sprite is moving //****************************************************************************** public boolean isMoving() { return moving; } //****************************************************************************** // Method that sets whether the sprite is moving //****************************************************************************** public void setMoving(boolean yes) { moving = yes; } //****************************************************************************** // Method that initializes the two curve point-arrays //****************************************************************************** public void setCurve(Point[] points) { attackPoints = points; retreatPoints = new Point[points.length]; int j = points.length - 1; // Reverses the order of points so the sprite can retreat if necessary for(int i = 0; i < points.length; i++) { retreatPoints[i] = points[j]; j--; } } //****************************************************************************** // Method that iterates the ship's X and Y coordinates along the retreating // curve //****************************************************************************** public void retreatShip() { for(int i = 0; i < retreatPoints.length; i++) { // Find the first non-null entry in the array if(retreatPoints[i] != null) { // Set the coordinates x = retreatPoints[i].x; y = retreatPoints[i].y; // Set this entry null retreatPoints[i] = null; // Break out of the loop i = attackPoints.length; } // If all entries in the curve are null if(retreatPoints[retreatPoints.length - 1] == null) { // Stop retreating setRetreat(false); // Set the coordinates back to their initial points x = initialX; y = initialY; } } } //****************************************************************************** // Method that iterates the ship's X and Y coordinates along the retreating // curve //****************************************************************************** public void attackShip(Vector<?> enemyBullets, PlayerShip player) { for(int i = 0; i < attackPoints.length; i++) { // Find the first non-null entry in the array if(attackPoints[i] != null) { // Set the coordinates x = attackPoints[i].x; y = attackPoints[i].y; // Set this entry null attackPoints[i] = null; // Break out of the loop i = attackPoints.length; } // If the ship is in the first half of its curving path if(attackPoints[attackPoints.length / 2] != null) { // If the current time is less than the preset firing time if(randomFireTime > currentFireTime) { // Do nothing } else { // Otherwise, set the current time to zero currentFireTime = 0; // Fire a bullet // Reset the random time randomFireTime = (int) (((Math.random() * RANDOM_FIRE_SEED) + 1) + 60); } } // If all entries in the curve are null if(attackPoints[attackPoints.length - 1] == null) { // Stop attacking setAttack(false); // Start retreating setRetreat(true); } } // Increment the firing time currentFireTime++; } //****************************************************************************** // Method that checks the time for moving. If the random time has passed, // return true. If the ship is already attacking or retreating, return true. // Otherwise, increment the move time and return false. //****************************************************************************** public boolean checkTime() { // If the random time is equal to the current time counter if(randomMoveTime == currentMoveTime) { // Generate a new random time randomMoveTime = (int) (((Math.random() * RANDOM_MOVE_SEED) + 1) + 50); // Reset the current time counter currentMoveTime = 0; // Set attack to true setAttack(true); return true; } // If the ship is already attacking or retreating else if(attack || retreat) { return true; } // Otherwise, increment the moving time and return false else { currentMoveTime++; return false; } } //****************************************************************************** // Method that returns whether a sprite is attacking or not //****************************************************************************** public boolean isAttacking() { return attack; } //****************************************************************************** // Method that returns where a sprite is retreating or not //****************************************************************************** public boolean isRetreating() { return retreat; } //****************************************************************************** // Method that sets whether a sprite is attacking //****************************************************************************** public void setAttack(boolean temp) { attack = temp; } //****************************************************************************** // Method that sets whether a sprite is retreating //****************************************************************************** public void setRetreat(boolean temp) { retreat = temp; } //****************************************************************************** // Method that sets the position of a sprite //****************************************************************************** public void setPosition(int x, int y) { this.x = x; this.y = y; } //****************************************************************************** // Method that returns whether a sprite is at its initial location //****************************************************************************** public boolean isAtInitialLocation() { if(x == initialX && y == initialY) return true; else return false; } //****************************************************************************** // Abstract method that is to be implemented by the child classes //****************************************************************************** public int getScore(){ return 0; }; /// /// /// }
/* Esercizio 2 - Pieraccini Francesco 475944 */ import java.util.*; import java.lang.*; public class DigitalDocs { /* OVERVIEW: classe che implementa una collezione di DigitalDoc, composta da una lista "docs". */ private List<DigitalDoc> docs; // Lista dei documenti degli utenti. public DigitalDocs() { /* MODIFIES: this. EFFECTS: inizializza this allocando "docs". */ this.docs = new Vector<DigitalDoc>(); } public boolean addDoc(String user, String doc, int password){ /* MODIFIES: this. EFFECTS: aggiunge un documento, per far ciò, si controlla prima che non vi sia già un documento con lo stesso nome, quindi si aggiunge tale "doc" alla lista "docs" con i dati di chi ne è possessore. */ // Controllo che non vi sia un documento con lo stesso nome. for(int i = 0; i < docs.size(); i++){ if(docs.get(i).getDoc().compareTo(doc) == 0){ return false; } } docs.add(new DigitalDoc(user, doc, password)); return true; } public boolean removeDoc(String user, String doc, int password){ /* MODIFIES: this. EFFECTS: elimina il documento Doc. */ // Cerco il documento con quel nome e lo elimino. for(int i = 0; i < docs.size(); i++){ // Il controllo sulla password, teoricamente, è inutile, ma lo faccio comunque. if(this.docs.get(i).getDoc().compareTo(doc) == 0 && this.docs.get(i).getName().compareTo(user) == 0 && this.docs.get(i).getPass() == password){ docs.remove(i); return true; } } return false; // Documento "doc" non trovato. } public void removeAll(String name){ /* MODIFIES: this. EFFECTS: elimina tutti i documenti dell'utente "name". */ for(int i = 0; i < docs.size(); i++){ if(this.docs.get(i).getName().compareTo(name) == 0){ docs.remove(i); } } } public List<String> getUsers() { /* EFFECTS: restituisce una lista con i nickname dei possessori dei documenti presenti. */ List<String> nicks = new Vector<String>(); for(int i = 0; i < this.docs.size(); i++) nicks.add(this.docs.get(i).getName()); return nicks; } public List<String> getDocs() { /* EFFECTS: restituisce una lista con i nomi dei documenti presenti. */ List<String> docs = new Vector<String>(); for(int i = 0; i < this.docs.size(); i++) docs.add(this.docs.get(i).getDoc()); return docs; } public List<Integer> getPasswords() { /* EFFECTS: restituisce una lista con le password dei possessori dei documenti presenti. */ List<Integer> pass = new Vector<Integer>(); for(int i = 0; i < this.docs.size(); i++) pass.add(this.docs.get(i).getPass()); return pass; } } class DigitalDoc { /* OVERVIEW: classe che implementa il tipo documento digitale, composta dal titolo del documento "doc", l'utente proprietario "name" e la sua password "pass". */ private String doc; private String name; private int pass; public DigitalDoc(String name, String doc, int pass) { /* MODIFIES: this. EFFECTS: inizializza this assegnando i valori passati al costruttore alle variabili di istanza. */ this.doc = doc; this.name = name; this.pass = pass; } public String getDoc(){ /* EFFECTS: restituisce il titolo di this. */ return this.doc; } public String getName(){ /* EFFECTS: restituisce il nickname del proprietario di this. */ return this.name; } public int getPass(){ /* EFFECTS: restituisce la password del proprietario di this. */ return this.pass; } }
package Day3.swing; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; /** * Created by student on 05-May-16. */ public class Coupon { private String description; private double value; private Scanner filereader; public Coupon(double value, String description) { this.value = value; this.description = description; } public double getValue() { return value; } public String getDescription() { return description; } public void setValue(double value) { this.value = value; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Coupon{" + "description='" + description + '\'' + ", value= £" + value + '}'; } public void loadInfoFromFile() { filereader = new Scanner(getClass().getResourceAsStream("input.txt")); } public Scanner getFilereader() { return filereader; } public void saveToAFile(String filename) throws FileNotFoundException { File file = new File(filename); PrintWriter pw = new PrintWriter(file); pw.println("Description : " + getDescription()); pw.println("Value : " + getValue()); pw.close(); } }
/* * Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.petrinator.util; import java.io.File; /** * This class contains some simple string management functions. * * @author Martin Riesz <riesz.martin at gmail.com> */ public class StringTools { /** * This method converts strings like "deCamelCase" to "De camel case" * * @param string string to be converted */ public static String deCamelCase(String string) { StringBuffer sb = new StringBuffer(string); sb.setCharAt(0, string.substring(0, 1).toUpperCase().charAt(0)); //first letter -> uppercase for (int i = 1; i < sb.length(); i++) { String currentChar = sb.substring(i, i + 1); //for each char in string: if (currentChar.equals(currentChar.toUpperCase())) { //if current char is uppercase sb.insert(i++, " "); //insert space sb.setCharAt(i, currentChar.toLowerCase().charAt(0)); //current char -> lowercase } } return sb.toString(); } /** * Returns extension of a file i.e. from File("example.html.txt") returns * "txt" * * @param file file to get the extension from * @return extension of the file */ public static String getExtension(File file) { return getExtension(file.getName()); } private static String getExtension(String filename) { String ext = null; String s = filename; int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) { ext = s.substring(i + 1).toLowerCase(); } if (ext != null) { return ext; } else { return ""; } } public static String getExtensionCutOut(String filename) { String extension = getExtension(filename); String result = filename.substring(0, filename.length() - 1 - extension.length()); return result; } }
package org.calc; import static org.junit.Assert.assertEquals; import org.calc.model.CalculationResponse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Launcher.class) @WebAppConfiguration @IntegrationTest @DirtiesContext public class RestApplicationTest { private static final double DELTA = 1e-15; @Value("${management.address}") String managementAddress; @Value("${management.port}") int managementPort; @Value("${server.address}") String serverAddress; @Value("${server.port}") int serverPort; String serverBaseUrl() { return "http://" + serverAddress + ":" + serverPort; } String managementBaseUrl() { return "http://" + managementAddress + ":" + managementPort; } @Test public void testHealthResource() throws Exception { ResponseEntity<String> entity = new TestRestTemplate() .getForEntity(managementBaseUrl() + "/health", String.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals("{\"status\":\"UP\"}", entity.getBody()); } @Test public void testAddWithThree() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/add/3/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(8.0, entity.getBody().getValue(), DELTA); } @Test public void testAddWithThreeWithCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/add/3/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(8.0, entity.getBody().getValue(), DELTA); } @Test public void testAddWithTwo() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/add/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(5.0, entity.getBody().getValue(), DELTA); } @Test public void testAddWithTwoWithCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/add/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(5.0, entity.getBody().getValue(), DELTA); } @Test public void testSubtractWithThree() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/subtract/9/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(4.0, entity.getBody().getValue(), DELTA); } @Test public void testSubtractWithThreeWithCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/subtract/9/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(4.0, entity.getBody().getValue(), DELTA); } @Test public void testSubtractWithTwo() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/subtract/2/4", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(-2.0, entity.getBody().getValue(), DELTA); } @Test public void testSubtractWithTwoWithCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/subtract/2/4", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(-2.0, entity.getBody().getValue(), DELTA); } @Test public void testMultiplyWithThree() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/multiply/2/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(12.0, entity.getBody().getValue(), DELTA); } @Test public void testMultiplyWithThreeWithCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/multiply/2/2/3", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(12.0, entity.getBody().getValue(), DELTA); } @Test public void testMultiplyWithTwo() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/multiply/2/2", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(4.0, entity.getBody().getValue(), DELTA); } @Test public void testMultiplyWithTwoWithCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/multiply/2/2", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(4.0, entity.getBody().getValue(), DELTA); } @Test public void testDivide() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/divide/4/4", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(1.0, entity.getBody().getValue(), DELTA); } @Test public void testDivideCache() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/divide/4/4", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(1.0, entity.getBody().getValue(), DELTA); } @Test public void testDivideError() throws Exception { ResponseEntity<CalculationResponse> entity = new TestRestTemplate() .getForEntity(serverBaseUrl() + "/api/calculator/divide/4/0", CalculationResponse.class); assertEquals(HttpStatus.OK, entity.getStatusCode()); assertEquals(1.0, entity.getBody().getValue(), DELTA); } }
package com.study.dynamic; import java.util.Arrays; /** * Created by sandy on 11/7/2015. */ public class CoinChange { public static void main(String[] args) { int []change = new int[]{ 2,3, 4}; int total = 17; System.out.println( String.format("Minimum number of coins with %s for total %d -> %d", Arrays.toString(change), total, optimalCoinsForChange(total, change))); } private static int optimalCoinsForChange(int total, int[] change) { if(total <= 0) return 0; int []cache = new int[total+1]; Arrays.fill(cache, Integer.MAX_VALUE); cache[0] = 0; for(int t = 1; t <= total ; t++) { for (int i = 0; i < change.length; i++) { if(change[i] > t) continue; int subResult = cache[t-change[i]]; if( subResult != Integer.MAX_VALUE && subResult + 1 < cache[t]) cache[t] = subResult + 1; } } return cache[total]; } }
package com.keny.api.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.keny.api.modal.Transportadora; public interface TransortadoraRepository extends JpaRepository<Transportadora, Integer> { }
/* * Written by Mustafa Toprak * Contact <mustafatoprak@iyte.edu.tr> for comments and bug reports * * Copyright (C) 2014 Mustafa Toprak * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.darg.NLPOperations.stemmer; import java.util.ArrayList; import java.util.HashMap; import org.tartarus.snowball.ext.EnglishStemmer; public class StemmerTartarus { /**This method stems a given term (just one term) as a string by using * Tartarus Stemmer. If the process is successful returns stemmed term, * otherwise returns null pointer. * * @author mustafa toprak * * @param term * @return String */ public String stemWordTartarus(String term) { String stemmedTerm = null; try { EnglishStemmer stemmer = new EnglishStemmer(); stemmer.setCurrent(term); if(stemmer.stem()) { stemmedTerm = stemmer.getCurrent(); } } catch(Exception exc) { stemmedTerm = null; exc.printStackTrace(); } return stemmedTerm; } /**This method stems keywords given as hashmap (keys are keywords and values are frequencies). * If stemmed version of two different keywords are the same, frequencies of these two words * are summed. (Tartarus Stemmer is used for the stemming process). If the process is * successfully finalized, hashmap of stemmed terms are returned, otherwise null pointer * is returned. * * @author mustafa toprak * * * @param keywords * @return HashMap<String, Long> */ public HashMap<String, Long> stemWordsTartarus(HashMap<String, Long> keywords) { HashMap<String, Long> stemmedKeywords = new HashMap<>(); try { if(keywords != null && keywords.size()>0) { String stemmedKeyword; long tempFreq; for(String keyword : keywords.keySet()) { stemmedKeyword = stemWordTartarus(keyword); tempFreq = 0; if(stemmedKeywords.containsKey(stemmedKeyword)) { tempFreq = stemmedKeywords.get(stemmedKeyword) + keywords.get(keyword); stemmedKeywords.put(stemmedKeyword, tempFreq); } else { stemmedKeywords.put(stemmedKeyword, keywords.get(keyword)); } } }else { stemmedKeywords = null; } } catch(Exception exc) { stemmedKeywords = null; exc.printStackTrace(); } return stemmedKeywords; } /**This method stems keywords given as list.. If the process is * successfully finalized, list of stemmed terms are returned, otherwise * null pointer is returned. Before stemming process, keyword converted * to lower case. * * @author mustafa toprak * * * @param keywords * @return ArrayList<String> */ public ArrayList<String> stemWordListTartarus(ArrayList<String> keywords) { ArrayList<String> stemmedKeywords = new ArrayList<>(); try { if(keywords != null && keywords.size()>0) { String stemmedKeyword; for(String keyword : keywords) { stemmedKeyword = stemWordTartarus(keyword); if(!stemmedKeywords.contains(stemmedKeyword)) { stemmedKeywords.add(stemmedKeyword); } } } else { stemmedKeywords = null; } } catch(Exception exc) { stemmedKeywords = null; exc.printStackTrace(); } return stemmedKeywords; } }
package com.xianzaishi.wms.tmscore.manage.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.xianzaishi.wms.common.exception.BizException; import com.xianzaishi.wms.tmscore.dao.itf.IDistributionAreaDao; import com.xianzaishi.wms.tmscore.manage.itf.IDistributionAreaManage; import com.xianzaishi.wms.tmscore.vo.DistributionAreaQueryVO; import com.xianzaishi.wms.tmscore.vo.DistributionAreaVO; public class DistributionAreaManageImpl implements IDistributionAreaManage { @Autowired private IDistributionAreaDao distributionAreaDao = null; private void validate(DistributionAreaVO distributionAreaVO) { if (distributionAreaVO.getAgency() == null || distributionAreaVO.getAgency() <= 0) { throw new BizException("agencyID error:" + distributionAreaVO.getAgency()); } if (distributionAreaVO.getName() == null || distributionAreaVO.getName().isEmpty()) { throw new BizException("name error:" + distributionAreaVO.getName()); } } private void validate(Long id) { if (id == null || id <= 0) { throw new BizException("ID error:" + id); } } public IDistributionAreaDao getDistributionAreaDao() { return distributionAreaDao; } public void setDistributionAreaDao(IDistributionAreaDao distributionAreaDao) { this.distributionAreaDao = distributionAreaDao; } public Boolean addDistributionAreaVO(DistributionAreaVO distributionAreaVO) { validate(distributionAreaVO); distributionAreaDao.addDO(distributionAreaVO); return true; } public List<DistributionAreaVO> queryDistributionAreaVOList( DistributionAreaQueryVO distributionAreaQueryVO) { return distributionAreaDao.queryDO(distributionAreaQueryVO); } public DistributionAreaVO getDistributionAreaVOByID(Long id) { return (DistributionAreaVO) distributionAreaDao.getDOByID(id); } public Boolean modifyDistributionAreaVO( DistributionAreaVO distributionAreaVO) { return distributionAreaDao.updateDO(distributionAreaVO); } public Boolean deleteDistributionAreaVOByID(Long id) { return distributionAreaDao.delDO(id); } public List<DistributionAreaVO> getArea(DistributionAreaQueryVO queryVO) { return distributionAreaDao.getArea(queryVO); } }
/* * * Hands-On code of the book Introduction to Reliable Distributed Programming * by Christian Cachin, Rachid Guerraoui and Luis Rodrigues * Copyright (C) 2005-2011 Luis Rodrigues * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA * * Contact * Address: * Rua Alves Redol 9, Office 605 * 1000-029 Lisboa * PORTUGAL * Email: * ler@ist.utl.pt * Web: * http://homepages.gsd.inesc-id.pt/~ler/ * */ package org.vanilladb.comm.process; import java.io.Serializable; import java.net.InetSocketAddress; /** * Represents a process in the system. * * @author nuno, yslin */ public class CommProcess implements Serializable { private static final long serialVersionUID = 20200318001L; // Identifiers private int id; private InetSocketAddress address; private boolean isSelf; // Machine States private ProcessState state; public CommProcess(InetSocketAddress addr, int id, boolean isSelf) { this.address = addr; this.id = id; this.isSelf = isSelf; if (isSelf) this.state = ProcessState.CORRECT; else this.state = ProcessState.UNINITIALIZED; } /** * Clone the given process. * * @param process the process to be cloned */ public CommProcess(CommProcess process) { this.address = process.address; this.id = process.id; this.isSelf = process.isSelf; this.state = process.state; } /** * Gets the address of the process. * * @return the address of the process */ public InetSocketAddress getAddress() { return address; } /** * Gets the process id. * * @return the process id */ public int getId() { return id; } /** * Check if the process is self. * * @return true if it is self, false otherwise */ public boolean isSelf() { return isSelf; } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object test) { if (test == this) return true; if (test == null) return false; if (!(test instanceof CommProcess)) return false; CommProcess proc = (CommProcess) test; return address.equals(proc.address) && (id == proc.id); } @Override public int hashCode() { int hash = 17; hash = hash * 31 + address.hashCode(); hash = hash * 31 + id; return hash; } public void setState(ProcessState state) { this.state = state; } /** * Is the process initialized. * * @return true if initialized, false otherwise */ public boolean isInitialized() { return state != ProcessState.UNINITIALIZED; } /** * Is the process correct. * * @return true if correct, false otherwise */ public boolean isCorrect() { return state == ProcessState.CORRECT; } }
package se.mauritzz.kth.inet.http.request; public enum RequestType { GET, HEAD, POST, PUT, DELETE; public static RequestType fromString(String input) { switch (input.trim()) { case "GET": return GET; case "HEAD": return HEAD; case "POST": return POST; case "PUT": return PUT; case "DELETE": return DELETE; default: return GET; } } }
package com.alpha.toy.vo; public class TechImageVo { private int image_no; private int tech_no; private String image_url; private String image_ori; public TechImageVo() { } public TechImageVo(int image_no, int tech_no, String image_url, String image_ori) { super(); this.image_no = image_no; this.tech_no = tech_no; this.image_url = image_url; this.image_ori = image_ori; } public int getImage_no() { return image_no; } public void setImage_no(int image_no) { this.image_no = image_no; } public int getTech_no() { return tech_no; } public void setTech_no(int tech_no) { this.tech_no = tech_no; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public String getImage_ori() { return image_ori; } public void setImage_ori(String image_ori) { this.image_ori = image_ori; } }
package com.dan.bbs.controller; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.dan.bbs.common.QRCodeUtil; @WebServlet("/CheckInServlet") public class CheckInServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String name = request.getParameter("name"); try { String text = request.getServletContext().getRealPath("/") + "checkIn?name=" + name; File f = new File(request.getServletContext().getRealPath("/")+ "/tmp/erweima"); System.out.println(text); if (!f.exists()) { f.mkdirs(); } QRCodeUtil.encodeNew(text, request.getServletContext().getRealPath("/")+ "/tmp/erweima", true,name); } catch (Exception e) { } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
package kr.or.ddit.vo; public class SuccessBoardVO { private String r; private String success_no; private String project_no; private String mem_id; private String success_title; private String success_content; private String success_regdate; private String success_hit; public String getR() { return r; } public void setR(String r) { this.r = r; } public String getSuccess_no() { return success_no; } public void setSuccess_no(String success_no) { this.success_no = success_no; } public String getProject_no() { return project_no; } public void setProject_no(String project_no) { this.project_no = project_no; } public String getMem_id() { return mem_id; } public void setMem_id(String mem_id) { this.mem_id = mem_id; } public String getSuccess_title() { return success_title; } public void setSuccess_title(String success_title) { this.success_title = success_title; } public String getSuccess_content() { return success_content; } public void setSuccess_content(String success_content) { this.success_content = success_content; } public String getSuccess_regdate() { return success_regdate; } public void setSuccess_regdate(String success_regdate) { this.success_regdate = success_regdate; } public String getSuccess_hit() { return success_hit; } public void setSuccess_hit(String success_hit) { this.success_hit = success_hit; } }
/* *Joaquín Bello Jiménez */ public class Ejercicio10 { public static void main (String args[]) { //Declaro los arrays int[] numero = new int[20]; int[] par = new int[20]; int[] impar = new int[20]; int cuentaPar = 0; int cuentaImpar = 0; //Bucle para asignar los valores for (int i = 0; i < numero.length; i++) { numero[i] = (int)(Math.random() * 101); //Comprueba si es par o no y lo asigna a su array if ((numero[i] >= 2) && (numero[i] % 2 == 0)){ par[cuentaPar] = numero[i]; cuentaPar++; }else if (numero[i] % 2 != 0) { impar[cuentaImpar] = numero[i]; cuentaImpar++; } } //Ordenar los pares primero for (int j = 0; j < numero.length;j++){ if (par[j] != 0){ numero[j] = par[j]; System.out.print(numero[j] +" "); } } //Ordenar detrás los impares for (int k = 0; k < numero.length;k++){ if (impar[k] != 0){ numero[k] = impar[k]; System.out.print(numero[k] +" "); } } } }
package command.dining; public class dReservationCommand { Long rstNo; String fromdate; String resTime; Long resMans; String resName; String resTel; String emailVal1; String emailVal2; String resCnt; Long menuNo; Long rstTbl; String menuName; Long menuPrice; String menuImg; public String getMenuName() { return menuName; } public void setMenuName(String menuName) { this.menuName = menuName; } public Long getMenuPrice() { return menuPrice; } public void setMenuPrice(Long menuPrice) { this.menuPrice = menuPrice; } public String getMenuImg() { return menuImg; } public void setMenuImg(String menuImg) { this.menuImg = menuImg; } public Long getMenuNo() { return menuNo; } public void setMenuNo(Long menuNo) { this.menuNo = menuNo; } public Long getRstTbl() { return rstTbl; } public void setRstTbl(Long rstTbl) { this.rstTbl = rstTbl; } public Long getRstNo() { return rstNo; } public void setRstNo(Long rstNo) { this.rstNo = rstNo; } public String getFromdate() { return fromdate; } public void setFromdate(String fromdate) { this.fromdate = fromdate; } public String getResTime() { return resTime; } public void setResTime(String resTime) { this.resTime = resTime; } public Long getResMans() { return resMans; } public void setResMans(Long resMans) { this.resMans = resMans; } public String getResName() { return resName; } public void setResName(String resName) { this.resName = resName; } public String getResTel() { return resTel; } public void setResTel(String resTel) { this.resTel = resTel; } public String getEmailVal1() { return emailVal1; } public void setEmailVal1(String emailVal1) { this.emailVal1 = emailVal1; } public String getEmailVal2() { return emailVal2; } public void setEmailVal2(String emailVal2) { this.emailVal2 = emailVal2; } public String getResCnt() { return resCnt; } public void setResCnt(String resCnt) { this.resCnt = resCnt; } }
package com.example.lte; import cn.dev33.satoken.SaTokenManager; import cn.dev33.satoken.spring.SaTokenSetup; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SaTokenSetup @SpringBootApplication public class LteApplication { public static void main(String[] args) { SpringApplication.run(LteApplication.class, args); System.out.println("启动成功:sa-token配置如下:" + SaTokenManager.getConfig()); } }
package com.example.demo.service; import java.util.List; import java.util.Optional; import com.example.demo.model.Message; public interface MessageService { List < Message > getMessageByUser(String user); Optional < Message > getMessageById(long id); void updateMessage(Message message); void addMessage(long id, String messagedesc); void deleteMessage(long id); void saveMessage(Message message); }
package sop.vo; /** * @Author: LCF * @Date: 2020/1/9 11:46 * @Package: sop.vo */ public class PoSearchItemConditionVo extends SoSearchItemConditionVo { private String fromPoNo; private String toPoNo; public String getFromPoNo() { return fromPoNo; } public void setFromPoNo(String fromPoNo) { this.fromPoNo = fromPoNo; } public String getToPoNo() { return toPoNo; } public void setToPoNo(String toPoNo) { this.toPoNo = toPoNo; } }
/** https://codeforces.com/contest/1328/problem/C #implementation */ import java.util.Scanner; public class TernaryXOR { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int testcases = sc.nextInt(); for (int t = 0; t < testcases; t++) { int n = sc.nextInt(); char[] s = sc.next().toCharArray(); char[] a = new char[n]; char[] b = new char[n]; a[0] = b[0] = '1'; // provided that A <= B. boolean aLessThanB = false; for (int i = 1; i < n; i++) { if (s[i] == '2') { if (aLessThanB) { a[i] = '2'; b[i] = '0'; } else { a[i] = '1'; b[i] = '1'; } } else if (s[i] == '1') { if (!aLessThanB) { aLessThanB = true; a[i] = '0'; b[i] = '1'; } else { a[i] = '1'; b[i] = '0'; } } else { a[i] = b[i] = '0'; } } /* better implementation for (int i = 0; i < n; i++) { if (s[i] == '1') { // a Less Than b a[i] = '0'; b[i] = '1'; for (int j = i + 1; j < n; j++) a[j] = s[j]; b[j] = '0'; } break; } else { a[i] = b[i] = '0' + (s[i] - '0') / 2; } } */ // result for (int i = 0; i < n; i++) { System.out.print(a[i]); } System.out.println(); for (int i = 0; i < n; i++) { System.out.print(b[i]); } System.out.println(); } } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FindSubset { /* Given two arrays: arr1[0..m-1] and arr2[0..n-1]. Find whether arr2[] is a subset of arr1[] or not. Both the arrays are not in sorted order. It may be assumed that elements in both array are distinct. Time Complexity: O(m*n) */ public boolean findSubset(int[] array1, int[] array2, int m, int n) { boolean isContained; for (int i = 0; i < n; i++) { isContained = false; for (int j = 0; j < m; j++) { if (array2[i] == array1[j]) { isContained = true; break; } } if (!isContained) { return false; } } return true; } // O(mLogm + nLogm) public boolean findSubsetBetter(int[] array1, int[] array2, int m, int n) { //quickSort algorithm Arrays.sort(array1); for(int item : array2){ if(binarySearch(array1, 0, array1.length, item) == -1){ return false; } } return true; } int binarySearch(int[] a, int min, int max, int target) { if (max >= min) { int mid = (min + max) / 2; if ((mid == 0 || target > a[mid - 1]) && (a[mid] == target)) return mid; else if (target > a[mid]) { return binarySearch(a, (mid + 1), max, target); } else { return binarySearch(a, min, (mid - 1), target); } } return -1; } }
package com.github.bukama.ir.utils; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; import java.util.ArrayList; import java.util.List; import com.github.bukama.ir.builder.IssueTestCaseBuilder; import com.github.bukama.ir.builder.IssueTestSuiteBuilder; import com.github.bukama.ir.jaxb.IssueType; import com.github.bukama.ir.jaxb.TestCaseType; import org.junit.jupiter.api.Test; import org.junitpioneer.jupiter.IssueTestCase; import org.junitpioneer.jupiter.IssueTestSuite; public class IssueUtilsTests { static final TestCaseType TEST1 = new TestCaseType("test1", "SUCCESSFUL"); static final IssueType ISSUE1 = new IssueType("req-123", "description", "1"); static final IssueType ISSUE2 = new IssueType("req-222", "another one", "2"); @Test void convertToTestCaseTypeCorrectly() { List<IssueTestCase> testCases = IssueTestCaseBuilder.listWithThreeTestsFixedNameAndAllResults(); List<TestCaseType> actual = IssueUtils.convertToTestCaseType(testCases); assertAll(() -> assertThat(actual.size()).isEqualTo(3), () -> assertThat(actual.get(0)).isEqualTo(TEST1)); } @Test void convertToTestCaseTypeEmptyList() { List<TestCaseType> actual = IssueUtils.convertToTestCaseType(new ArrayList<>()); assertThat(actual.size()).isEqualTo(0); } @Test void mergeListEmptyList() { List<IssueType> actual = IssueUtils.mergeLists(new ArrayList<>(), new ArrayList<>()); assertThat(actual.size()).isEqualTo(0); } @Test void mergeListNoIssueList() { List<IssueTestSuite> testSuites = new ArrayList<>(); testSuites.add(IssueTestSuiteBuilder.withThreeFixedNamesTests("req-123")); List<IssueType> actual = IssueUtils.mergeLists(new ArrayList<>(), testSuites); assertAll(() -> assertThat(actual.size()).isEqualTo(1), () -> assertThat(actual.get(0).getIssueId()).isEqualTo("req-123"), () -> assertThat(actual.get(0).getDescription()).isNull(), () -> assertThat(actual.get(0).getTests().getTestCase().size()).isEqualTo(3)); } @Test void mergeListNoIssueTestSuiteList() { List<IssueType> issues = new ArrayList<>(); issues.add(ISSUE1); issues.add(ISSUE2); List<IssueType> actual = IssueUtils.mergeLists(issues, new ArrayList<>()); assertAll(() -> assertThat(actual.size()).isEqualTo(2), () -> assertThat(actual.get(0).getIssueId()).isEqualTo("req-123"), () -> assertThat(actual.get(0)).isEqualTo(ISSUE1), () -> assertThat(actual.get(1)).isEqualTo(ISSUE2)); } @Test void mergeListBothPresentList() { List<IssueType> issues = new ArrayList<>(); issues.add(ISSUE1); issues.add(ISSUE2); List<IssueTestSuite> testSuites = new ArrayList<>(); testSuites.add(IssueTestSuiteBuilder.withThreeFixedNamesTests("req-123")); List<IssueType> actual = IssueUtils.mergeLists(issues, testSuites); assertAll(() -> assertThat(actual.size()).isEqualTo(2), () -> assertThat(actual.get(0).getIssueId()).isEqualTo("req-123"), () -> assertThat(actual.get(0).getTests().getTestCase().size()).isEqualTo(3), () -> assertThat(actual.get(0).getTests().getTestCase().get(0).getTestId()).isEqualTo("test1"), () -> assertThat(actual.get(1)).isEqualTo(ISSUE2)); } }
package com.isg.ifrend.core.model.mli.dto; public class PersonalDetailRequest { }
package se.kth.eh2745.moritzv.assigment1.objects; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import org.w3c.dom.Element; import se.kth.eh2745.moritzv.assigment1.XmlParser; import se.kth.eh2745.moritzv.assigment1.db.MysqlField; import se.kth.eh2745.moritzv.assigment1.db.MysqlFieldTypes; import se.kth.eh2745.moritzv.assigment1.exception.XmlStructureNotAsAssumedException; public class RatioTapChanger extends IdentifiedObject { protected double step; public RatioTapChanger(Element element) throws XmlStructureNotAsAssumedException { super(element); } @Override public void updateFromXML(Element element) throws XmlStructureNotAsAssumedException { super.updateFromXML(element); this.step = XmlParser.ParseDoubleNodeContent(element, "cim:TapChanger.step"); } public static String getCimName() { return "cim:RatioTapChanger"; } public static boolean hasDbTable() { return true; } public static ArrayList<MysqlField> getTabelFields() { ArrayList<MysqlField> list = EquipmentContainer.getTabelFields(); list.add(new MysqlField("step", MysqlFieldTypes.FLOAT)); return list; } @Override public int insertData(PreparedStatement statment) throws SQLException { int index = super.insertData(statment); statment.setDouble(++index, getStep()); return index; } public double getStep() { return step; } }
/* ~~ The InsertForm is part of BusinessProfit. ~~ * * The BusinessProfit's classes and any part of the code * cannot be copied/distributed without * the permission of Sotiris Doudis * * Github - RiflemanSD - https://github.com/RiflemanSD * * Copyright © 2016 Sotiris Doudis | All rights reserved * * License for BusinessProfit project - in GREEK language * * Οποιοσδήποτε μπορεί να χρησιμοποιήσει το πρόγραμμα για προσωπική του χρήση. * Αλλά απαγoρεύεται η πώληση ή διακίνηση του προγράμματος σε τρίτους. * * Aπαγορεύεται η αντιγραφή ή διακίνηση οποιοδήποτε μέρος του κώδικα χωρίς * την άδεια του δημιουργού. * Σε περίπτωση που θέλετε να χρεισημοποιήσετε κάποια κλάση ή μέρος του κώδικα. * Πρέπει να συμπεριλάβεται στο header της κλάσης τον δημιουργό και link στην * αυθεντική κλάση (στο github). * * ~~ Information about BusinessProfit project - in GREEK language ~~ * * Το BusinessProfit είναι ένα project για την αποθήκευση και επεξεργασία * των εσόδων/εξόδων μίας επιχείρησης με σκοπό να μπορεί ο επιχειρηματίας να καθορήσει * το καθαρό κέρδος της επιχείρησης. Καθώς και να κρατάει κάποια σημαντικά * στατιστικά στοιχεία για τον όγκο της εργασίας κτλ.. * * Το project δημιουργήθηκε από τον Σωτήρη Δούδη. Φοιτητή πληροφορικής του Α.Π.Θ * για προσωπική χρήση. Αλλά και για όποιον άλλον πιθανόν το χρειαστεί. * * Το project προγραμματίστηκε σε Java (https://www.java.com/en/download/). * Με χρήση του NetBeans IDE (https://netbeans.org/) * Για να το τρέξετε πρέπει να έχετε εγκαταστήσει την java. * * Ο καθένας μπορεί δωρεάν να χρησιμοποιήσει το project αυτό. Αλλά δεν επιτρέπεται * η αντιγραφή/διακήνηση του κώδικα, χωρίς την άδεια του Δημιουργού (Δείτε την License). * * Github - https://github.com/RiflemanSD/BusinessProfit * * * Copyright © 2016 Sotiris Doudis | All rights reserved */ package org.riflemansd.businessprofit.main; import java.awt.FlowLayout; import javax.swing.JOptionPane; import org.riflemansd.businessprofit.MyItemListener; import org.riflemansd.businessprofit2.Category; import org.riflemansd.businessprofit2.IncomeCost; import org.riflemansd.businessprofit2.PackagesIncome; /** <h1>InsertForm</h1> * * <p></p> * * <p>Last Update: 01/02/2016</p> * <p>Author: <a href=https://github.com/RiflemanSD>RiflemanSD</a></p> * * <p>Copyright © 2016 Sotiris Doudis | All rights reserved</p> * * @version 1.0.7 * @author RiflemanSD */ public class InsertForm extends javax.swing.JFrame { private String[] categorys; /** Creates new form InsertForm */ public InsertForm() { this.setBounds(100, 100, 1000, 1000); initComponents(); setDefaultCloseOperation(DISPOSE_ON_CLOSE); categorys = BusinessProfit.database.getCategorys().split("\n"); categoryJCB.removeAllItems(); for (String cat : categorys) { categoryJCB.addItem(cat.split(",")[1]); } categoryJCB.addItemListener(new MyItemListener(this)); esodoeksodoJCB.removeAllItems(); esodoeksodoJCB.addItem("Έσοδο"); esodoeksodoJCB.addItem("Έξοδο"); esodoeksodoJCB.addItemListener(new MyItemListener(this)); centerPanel.setLayout(new FlowLayout(1)); if (categoryJCB.getSelectedItem().equals("Δέματα")) { centerPanel.add(new InsertPanelPackages()); } else { centerPanel.add(new InsertPanel()); } //revalidate(); //repaint(); this.setLocationRelativeTo(null); } public void setInsertPanel() { centerPanel.removeAll(); if (categoryJCB.getSelectedItem().equals("Δέματα") && esodoeksodoJCB.getSelectedIndex() == 0) { centerPanel.add(new InsertPanelPackages()); } else { centerPanel.add(new InsertPanel()); } revalidate(); repaint(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); insertButton = new javax.swing.JButton(); centerPanel = new javax.swing.JPanel(); HeaderPanel = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); categoryJCB = new javax.swing.JComboBox(); esodoeksodoJCB = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setLayout(new java.awt.BorderLayout()); insertButton.setText("Εισαγωγή"); insertButton.setHideActionText(true); insertButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); insertButton.setPreferredSize(new java.awt.Dimension(80, 100)); insertButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { insertButtonActionPerformed(evt); } }); jPanel1.add(insertButton, java.awt.BorderLayout.PAGE_END); centerPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); centerPanel.setPreferredSize(new java.awt.Dimension(100, 100)); centerPanel.setLayout(new java.awt.BorderLayout()); jPanel1.add(centerPanel, java.awt.BorderLayout.CENTER); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel2.setText("Κατηγορία"); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N jLabel1.setText("Έσοδο/Έξοδο"); categoryJCB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N categoryJCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); categoryJCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { categoryJCBActionPerformed(evt); } }); esodoeksodoJCB.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N esodoeksodoJCB.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Έσοδο", "Έξοδο" })); esodoeksodoJCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { esodoeksodoJCBActionPerformed(evt); } }); javax.swing.GroupLayout HeaderPanelLayout = new javax.swing.GroupLayout(HeaderPanel); HeaderPanel.setLayout(HeaderPanelLayout); HeaderPanelLayout.setHorizontalGroup( HeaderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HeaderPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(HeaderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(HeaderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(esodoeksodoJCB, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(categoryJCB, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(118, Short.MAX_VALUE)) ); HeaderPanelLayout.setVerticalGroup( HeaderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(HeaderPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(HeaderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(categoryJCB, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(HeaderPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(esodoeksodoJCB, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 25, Short.MAX_VALUE)) .addGap(17, 17, 17)) ); jPanel1.add(HeaderPanel, java.awt.BorderLayout.PAGE_START); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void insertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_insertButtonActionPerformed String item = (String)categoryJCB.getSelectedItem(); Category cat = BusinessProfit.database.getCategory(item); int index = esodoeksodoJCB.getSelectedIndex(); //Δέματα και έσοδο if (item.equals("Δέματα") && index == 0) { InsertPanelPackages p = (InsertPanelPackages)centerPanel.getComponent(0); String aitiologia = p.getAitiologia(); int paradoseis = p.getParadoseis(); int paralabes = p.getParalabes(); if (paradoseis == -1 || paralabes == -1) { JOptionPane.showMessageDialog(this, "Δεν είναι δυνατή η αποθήκευση!","Αποτυχία",JOptionPane.ERROR_MESSAGE); } else { System.out.println(aitiologia + " " + paradoseis + " " + paralabes); BusinessProfit.database.savePackIn(new PackagesIncome(0, cat, aitiologia, paradoseis, paralabes), p.getDate()); JOptionPane.showMessageDialog(this, "Τα δεδομένα αποθηκεύτηκαν!","Επιτυχία",JOptionPane.INFORMATION_MESSAGE); } } else { //Έσοδο if (index == 0) { InsertPanel p = (InsertPanel)centerPanel.getComponent(0); String aitiologia = p.getAitiologia(); double poso = p.getPoso(); double fpa = p.fpaCount(); if (poso == -1) { JOptionPane.showMessageDialog(this, "Δεν είναι δυνατή η αποθήκευση!","Αποτυχία",JOptionPane.ERROR_MESSAGE); } else { if (fpa != -1) { Category fpaCat = BusinessProfit.database.getCategory("ΦΠΑ"); if (fpaCat == null) { fpaCat = new Category(1, "ΦΠΑ"); BusinessProfit.database.saveCategory(fpaCat); } poso = p.getPoso(); System.out.println(fpaCat.getName()); BusinessProfit.database.saveOut(new IncomeCost(0, fpaCat, aitiologia, fpa), p.getDate()); } System.out.println(aitiologia + " " + poso); BusinessProfit.database.saveIn(new IncomeCost(0, cat, aitiologia, poso), p.getDate()); JOptionPane.showMessageDialog(this, "Τα δεδομένα αποθηκεύτηκαν!","Επιτυχία",JOptionPane.INFORMATION_MESSAGE); } } //Έξοδο else if (index == 1) { InsertPanel p = (InsertPanel)centerPanel.getComponent(0); String aitiologia = p.getAitiologia(); double poso = p.getPoso(); if (poso == -1) { JOptionPane.showMessageDialog(this, "Δεν είναι δυνατή η αποθήκευση!","Αποτυχία",JOptionPane.ERROR_MESSAGE); } else { System.out.println(aitiologia + " " + poso); BusinessProfit.database.saveOut(new IncomeCost(0, cat, aitiologia, poso), p.getDate()); JOptionPane.showMessageDialog(this, "Τα δεδομένα αποθηκεύτηκαν!","Επιτυχία",JOptionPane.INFORMATION_MESSAGE); } } } }//GEN-LAST:event_insertButtonActionPerformed private void esodoeksodoJCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_esodoeksodoJCBActionPerformed // TODO add your handling code here: }//GEN-LAST:event_esodoeksodoJCBActionPerformed private void categoryJCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categoryJCBActionPerformed // TODO add your handling code here: }//GEN-LAST:event_categoryJCBActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(InsertForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new InsertForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel HeaderPanel; private javax.swing.JComboBox categoryJCB; private javax.swing.JPanel centerPanel; private javax.swing.JComboBox esodoeksodoJCB; private javax.swing.JButton insertButton; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; // End of variables declaration//GEN-END:variables }
package com.needii.dashboard.service; import com.needii.dashboard.dao.ReasonCancelOrderDao; import com.needii.dashboard.model.ReasonCancelOrder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional @Service("reasonCancelOrderService") public class ReasonCancelOrderServiceImpl implements ReasonCancelOrderService{ @Autowired private ReasonCancelOrderDao reasonCancelOrderDao; @Override public List<ReasonCancelOrder> findAll() { return reasonCancelOrderDao.findAll(); } @Override public ReasonCancelOrder findOne(long id){ return reasonCancelOrderDao.findOne(id); } @Override public void create(ReasonCancelOrder entity) { reasonCancelOrderDao.create(entity); } @Override public void update(ReasonCancelOrder entity) { reasonCancelOrderDao.update(entity); } @Override public void delete(ReasonCancelOrder entity) { reasonCancelOrderDao.delete(entity); } }
package com.driveanddeliver.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.ui.ModelMap; /** * * @author Amandeep Singh Dhammu * */ @Controller public class HomepageController { private String contextPath; public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } @RequestMapping(value = {"/","/index","/welcome"}, method = RequestMethod.GET) public String printHello(ModelMap model, HttpServletRequest httpServletRequest) { model.addAttribute("message", "Welcome to Drive and Deliver"); model.addAttribute("contextPath", httpServletRequest.getContextPath()); this.setContextPath(httpServletRequest.getContextPath()); return "index"; } }
package loanObserver; public class NewsOutlets implements Observers, DisplayInfo { private float interest; private Subject someLoan; public NewsOutlets(Subject someLoan) { this.someLoan = someLoan; this.someLoan.addObserver(this);//someloan adds the object of NewsOutlets to the list of observers in Loan } @Override public void display() { System.out.println("================ Punch Breaking News ============="); System.out.println("New interest is now " + interest); } @Override public void update(float interest) { // the interest parameter updates this class' interest field this.interest = interest; display(); } }
/* * Copyright 2002-2017 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.stereotype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicate that the annotated element represents a stereotype for the index. * * <p>The {@code CandidateComponentsIndex} is an alternative to classpath * scanning that uses a metadata file generated at compilation time. The * index allows retrieving the candidate components (i.e. fully qualified * name) based on a stereotype. This annotation instructs the generator to * index the element on which the annotated element is present or if it * implements or extends from the annotated element. The stereotype is the * fully qualified name of the annotated element. * * <p>Consider the default {@link Component} annotation that is meta-annotated * with this annotation. If a component is annotated with {@link Component}, * an entry for that component will be added to the index using the * {@code org.springframework.stereotype.Component} stereotype. * * <p>This annotation is also honored on meta-annotations. Consider this * custom annotation: * <pre class="code"> * package com.example; * * &#064;Target(ElementType.TYPE) * &#064;Retention(RetentionPolicy.RUNTIME) * &#064;Documented * &#064;Indexed * &#064;Service * public @interface PrivilegedService { ... } * </pre> * * If the above annotation is present on a type, it will be indexed with two * stereotypes: {@code org.springframework.stereotype.Component} and * {@code com.example.PrivilegedService}. While {@link Service} isn't directly * annotated with {@code Indexed}, it is meta-annotated with {@link Component}. * * <p>It is also possible to index all implementations of a certain interface or * all the subclasses of a given class by adding {@code @Indexed} on it. * * Consider this base interface: * <pre class="code"> * package com.example; * * &#064;Indexed * public interface AdminService { ... } * </pre> * * Now, consider an implementation of this {@code AdminService} somewhere: * <pre class="code"> * package com.example.foo; * * import com.example.AdminService; * * public class ConfigurationAdminService implements AdminService { ... } * </pre> * * Because this class implements an interface that is indexed, it will be * automatically included with the {@code com.example.AdminService} stereotype. * If there are more {@code @Indexed} interfaces and/or superclasses in the * hierarchy, the class will map to all their stereotypes. * * @author Stephane Nicoll * @since 5.0 */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Indexed { }
package me.ewriter.chapter1; /** * Created by zubin on 16/8/4. */ public class MuteQuack implements QuackBehavior { @Override public void quack() { System.out.println("<<Silence>>"); } }
package by.academy.tasks.oop; public class PersonApplication { public static void main(String[] args) { Person person1 = new Person (); Person person2 = new Person ("Коля", 21); person1.fullName = "Aгата"; System.out.println(person1); System.out.println(person2); person1.move(); person1.talk(); person2.move(); person2.talk(); } }
package com.project.universitystudentassistant.data.local; import android.content.Context; import androidx.annotation.NonNull; import androidx.room.AutoMigration; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; import com.project.universitystudentassistant.models.Subject; import com.project.universitystudentassistant.models.SubjectSchedule; import com.project.universitystudentassistant.models.UniversityEntity; import com.project.universitystudentassistant.models.UniversityEntityPrep; import com.project.universitystudentassistant.models.User; @Database(entities = {UniversityEntity.class, User.class, UniversityEntityPrep.class, Subject.class, SubjectSchedule.class}, // autoMigrations = @AutoMigration( // from = 7, // to = 8 // ), version = 8, exportSchema = true) @TypeConverters({SubjectTimeConverter.class}) public abstract class AppDatabase extends RoomDatabase { private static AppDatabase appDatabase; public abstract UserDao userDao(); public abstract UniversityDao universityDao(); public abstract PrepUniversityDao prepUniversityDao(); public abstract SubjectDao subjectDao(); public abstract SubjectScheduleDao subjectScheduleDao(); public static AppDatabase getInstance(Context context) { if (appDatabase == null) { appDatabase = Room.databaseBuilder(context, AppDatabase.class, "university-assistant-database.db") .fallbackToDestructiveMigration() .addMigrations(new Migration(7,8) { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { // database.execSQL("ALTER TABLE prepopulated_universities_table " // + " ADD COLUMN graduation_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE prepopulated_universities_table " // + " ADD COLUMN acceptance_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE prepopulated_universities_table " // + " ADD COLUMN description TEXT"); // database.execSQL("ALTER TABLE my_universities_table " // + " ADD COLUMN graduation_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE my_universities_table " // + " ADD COLUMN acceptance_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE my_universities_table " // + " ADD COLUMN description TEXT"); database.execSQL("CREATE TABLE IF NOT EXISTS`subjects_shcedule_table` (`uid` INTEGER, " + "'teacher' TEXT, " + "'location' TEXT, " + "'repeating_time' TEXT, " + "'color' INTEGER NOT NULL, " + "'is_repeating_event' INTEGER NOT NULL, " + "'single_time' TEXT, " + "`name` TEXT NOT NULL, PRIMARY KEY(`uid`))"); } }) .build(); } return appDatabase; } // .addMigrations(new Migration(4, 5) { // @Override // public void migrate(@NonNull SupportSQLiteDatabase database) { // database.execSQL("ALTER TABLE prepopulated_universities_table " // + " ADD COLUMN graduation_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE prepopulated_universities_table " // + " ADD COLUMN acceptance_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE prepopulated_universities_table " // + " ADD COLUMN description TEXT"); // database.execSQL("ALTER TABLE my_universities_table " // + " ADD COLUMN graduation_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE my_universities_table " // + " ADD COLUMN acceptance_rate INTEGER DEFAULT 1 NOT NULL"); // database.execSQL("ALTER TABLE my_universities_table " // + " ADD COLUMN description TEXT"); // } // }) // .allowMainThreadQueries() }
package com.mvc4.bean; import java.math.BigDecimal; /** * Created with IntelliJ IDEA. * User: uc203808 * Date: 6/14/16 * Time: 5:46 PM * To change this template use File | Settings | File Templates. */ public class DoubleTest { public static void main(String[] args){ String ex = "100000000"; String ss = "10700.71"; BigDecimal bigDecimal = new BigDecimal(ss); BigDecimal bigDecimal2 = new BigDecimal(ex); System.out.println(bigDecimal.multiply(bigDecimal2)); double doubleVal = Double.valueOf(ss).doubleValue(); System.out.println(((Double)(doubleVal * Long.valueOf(ex).longValue()))); System.out.println(Double.valueOf(ss)); System.out.println(Double.valueOf(ss).longValue()); } }
package com.test.controllers; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.SessionAttribute; import com.test.beans.Login; @Controller public class UserProfileController { @PostMapping("/userprofile") public String getUserProfile(@SessionAttribute("login")Login login, Model model) { System.out.println("In user profile controller"); System.out.println("username from session " + login.getUsername()); model.addAttribute("username", login.getUsername()); return "profile"; } }
package io.breen.socrates.test.python; import io.breen.socrates.test.Test; public abstract class VariableTest extends Test { /** * This empty constructor is used by SnakeYAML for the extenders of this class that are * instantiated from a criteria file. */ public VariableTest() {} public VariableTest(double deduction, String description) { super(deduction, description); } }
import java.util.*; import java.lang.*; public class Menagerie { //creates an Array List for animals to be stored in. public ArrayList<Animal> collection = new ArrayList<Animal>(); public void AddAnimal(Animal animal) { //if statement is created to avoid duplication if(!collection.contains(animal)) { collection.add(animal); } } public Animal GetAnimal(String name) { //loops through and trying to find the name of the desired animal is in the collection. for(int k=0; k < collection.size(); k++) { //the if statement compares the names and ignores caps so if the person doesn't //have to match the string exactly method acquired from https://howtodoinjava.com/java/string/string-equalsignorecase-method/ // possible improvement is removing the spaces when comparing //in case one either forgets to space or adds and extra space. if(name.equalsIgnoreCase(collection.get(k).name)) { return collection.get(k); } } //if the animal doesn't exist in the collection it is printed out and returns null //it returns null because if this was expanded more could be then done if the //desired animal was not in the collection as well as method expect to return something System.out.println(name + " can not be found"); return null; } }
package net.sxt.tcp.chat.server2multi_client; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; public class Send implements Runnable{ private BufferedReader br=null; private DataOutputStream dos=null; private boolean isRunning=true; public Send() { br=new BufferedReader(new InputStreamReader(System.in)); } public Send(Socket socket) { //这里调用了无参构造函数,很关键!! this(); try { dos=new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dos,br); isRunning=false; } } private String getMessageFromCosole() { try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } public void send() { String meg=getMessageFromCosole(); //字符串不为null且字符串不为空字符串--->主要针对控制台打印 if(meg!=null && !meg.equals("")) { try { dos.writeUTF(meg); } catch (IOException e) { //e.printStackTrace(); CloseUtil.closeAll(dos); isRunning=false; } } } public void run() { while(isRunning) { send(); } } }
package com.pic.kb.java_log4j2; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Created by wzunix on 21/07/16. */ public class Log4J2Demo1 { /** * LogManager.getLogger() creates a logger with the containing class qualified name (com.pic.kb.java_log4j2.Log4J2Demo1 in this case). * The getLogger() method fetches the logger with that name if exists, creates a new one if doesn’t exist. * Meaning, if at some point later in the application, * I called getLogger() (if called in the same class, or getLogger(“com.pic.kb.java_log4j2.Log4J2Demo1”) if called anywhere), the very same logger will be returned. */ private static final Logger logger = LogManager.getLogger(); public static void main(String... args){ for(int i = 0; i < 100; i++){ logger.fatal("This is a FATAL error"); logger.error("This is an ERROR msg."); logger.warn("This is a WARNING msg"); logger.info("This is a INFO msg"); logger.debug("This is a DEBUG msg"); logger.trace("This is a TRACE msg"); } } }
package Factory; public class ContaFactory { public Conta criaConta(String tipo) { Conta conta = null; if(tipo.equals("conta corrente")) conta = new ContaCorrente(); else if(tipo.equals("conta salario")) conta = new ContaSalario(); else if (tipo.equals("conta poupanca")) conta = new ContaPoupanca(); return conta; } }
Not like recursion, put the value into table in order public int fibo(int n) { int[] fiboFound = new int[n + 1]; fiboFound[0] = 0; fiboFound[1] = 1; for(int i = 2; i <= n; i++) { fiboFound[i] = fiboFound[i - 1] + fiboFound[i - 2]; } return fiboFound; }
package com.Memento.blackbox; /** * Created by Valentine on 2018/5/11. */ public class Originatore { private int state = 0; Caretaker caretaker = new Caretaker(); public Memento saveMemento(){ return new MementoImpl(state); } public void resumeMemento(Memento memento){ this.setState(((MementoImpl)memento).getState()); } public int getState() { return state; } public void setState(int state) { this.state = state; } private class MementoImpl implements Memento{ private int state; public MementoImpl(int state){ this.state = state; } public int getState() { return state; } public void setState(int state) { this.state = state; } } }
package exercise1; public class AccountType { public static final int REGULAR_ACCOUNT = 0; public static final int PREMIUM_ACCOUNT = 1; private int accountType; public boolean isPremium() { if (this.accountType == PREMIUM_ACCOUNT) return true; return false; } // Consider there is additional code here... }
package com.delrima.webgene.server.configuration; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.orm.jpa.JpaTransactionManager; import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; @Configuration @EnableTransactionManagement public class PersistenceJPAConfiguration { private static final EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("transactions-optional"); @Bean public EntityManagerFactory entityManagerFactory() { return entityManagerFactory; } @Bean public EntityManager entityManager() { return entityManagerFactory.createEntityManager(); } @Bean public PlatformTransactionManager transactionManager() { JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(entityManagerFactory); return transactionManager; } @Bean public PersistenceAnnotationBeanPostProcessor persistenceAnnotationBeanPostProcessor() { return new PersistenceAnnotationBeanPostProcessor(); } }
package com.eegeo.mapapi.indoors; import androidx.annotation.WorkerThread; public class ExpandFloorsJniCalls { @WorkerThread public static native void expandIndoor(long jniEegeoMapApiPtr); @WorkerThread public static native void collapseIndoor(long jniEegeoMapApiPtr); }
/* Name: Sara Bernstein * UNI: sgb2137 * Assignment: CreditCard - checking for valid card number * / /* Method that tests if a credit card number is valid * The credit card is valid under the following 6 conditions: * 1. The first digit must be a 4. * 2. The fourth digit must be one greater than the fifth digit * 3. The product of the first, fifth, and ninth digits must be 24 * 4. The sum of all digits must be evenly divisible by 4 * 5. The sum of the first four digits must be one less than the sum of the last four digits * 6. If you treat the first two digits as a two-digit number, and the seventh and eight digits as a two digit number, their sum must be 100. * If does not meet one of the 6 requirements, it is invalid and its errorCode int value is the rule # is didn't follow */ public class CreditCard { private String cardNumber; // credit card number is stored as a String private boolean valid; // boolean indicating valid or not private int errorCode; // int indicating which rule is violated first // constructor to initialize instance variables // accepts String as input/parameter // Assumes cardNumber is valid public CreditCard(String number) { cardNumber = number; valid = true; errorCode = 0; } // This method checks rule 1 // Rule 1: First digit is 4 private void check1() { int d1 = Integer.parseInt(cardNumber.substring(0,1)); if (d1 != 4) { valid = false; errorCode = 1; } } // This method checks rule 2 // Rule 2: Fourth digit is one greater than fifth private void check2() { int d4 = Integer.parseInt(cardNumber.substring(3,4)); int d5 = Integer.parseInt(cardNumber.substring(4,5)); if ( d4 != (d5 + 1) ) { valid = false; errorCode = 2; } } // This method checks rule 3 // Rule 3: Product of first, fifth and ninth digits is 24 private void check3() { int d1 = Integer.parseInt(cardNumber.substring(0,1)); int d5 = Integer.parseInt(cardNumber.substring(4,5)); int d9 = Integer.parseInt(cardNumber.substring(8,9)); if ( (d1 * d5 * d9) != 24 ) { valid = false; errorCode = 3; } } // This method checks rule 4 // Rule 4: Sum of all digits is evenly divisible by 4 private void check4() { int sumAllDigits = 0; for (int i = 0; i < 12; i++) { int digit = Integer.parseInt(cardNumber.substring(i, i+1)); sumAllDigits += digit; } if ((sumAllDigits % 4) != 0 ) { valid = false; errorCode = 4; } } // This method checks rule 5 // Rule 5: Sum of first four is one less than sum of last four private void check5() { int sumFirstFour = 0; int sumLastFour = 0; for (int i = 0; i < 12; i++) { int digit = Integer.parseInt(cardNumber.substring(i,i+1)); if ( i < 4) { sumFirstFour += digit; } else if ( i >= 8) { sumLastFour += digit; } } if ( sumFirstFour != (sumLastFour - 1) ) { valid = false; errorCode = 5; } } // This method checks rule 6 // Rule 6: first two digits as one number and // seventh and eigth digits as one number must add up to 100 private void check6() { int oneAndTwo = Integer.parseInt(cardNumber.substring(0, 2)); int sevenAndEight = Integer.parseInt(cardNumber.substring(6, 8)); if ( (oneAndTwo + sevenAndEight) != 100 ) { valid = false; errorCode = 6; } } // This method checks overall credit card to see if it's valid // Calls on the other check methods specific to the rules only if // one has not been violated yet public void check() { check1(); if ( valid == true ) { check2(); } if ( valid == true) { check3(); } if ( valid == true) { check4(); } if ( valid == true) { check5(); } if ( valid == true) { check6(); } } // accessor method to get info about if card is valid public boolean isValid() { return valid; } // accessor method to know which test the card failed if it's not valid public int getErrorCode() { return errorCode; } }
package com.example.uiassit; import com.jerome.weibo.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class gridviewadapter extends BaseAdapter implements OnClickListener{ private static final String TAG = null; private ImageView view1; private TextView view2; private LayoutInflater inflater; public gridviewadapter(Context context){ super(); this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } gridviewadapter(){ } @Override public int getCount() { // TODO Auto-generated method stub return gridvietianchong.deploy().size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if(convertView == null){ convertView = inflater.inflate(R.layout.gridviewcontent, null); view1 = (ImageView)convertView.findViewById(R.id.contentphoto); view2 = (TextView)convertView.findViewById(R.id.contentwenzi); } else{} view1.setImageResource(gridvietianchong.tupian[position]); //»ñȡͼƬ view2.setText(gridvietianchong.deploy().get(position).get("introduce").toString()); view1.setOnClickListener(this); view2.setOnClickListener(this); return convertView; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.contentphoto: Log.i(TAG, "sdf"); break; case R.id.contentwenzi: Log.i(TAG, "sdfsf"); break; default: break; } } }
import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; import java.util.Map; /** * 说明:IDataLoader * 创建人:吕德奎 * 创建时间:2018/8/13 */ public interface IDataLoader { public List<Map<String,Object>> load(); public Connection getConnection(); public void releaseConn(Statement statement, ResultSet resultSet); }
package jikanganai.server.actors; import akka.actor.typed.ActorRef; import akka.actor.typed.Behavior; import akka.actor.typed.javadsl.AbstractBehavior; import akka.actor.typed.javadsl.ActorContext; import akka.actor.typed.javadsl.Behaviors; import akka.actor.typed.javadsl.Receive; import jikanganai.server.entities.ChargeCode; import java.util.List; public class ChargeCodeActor extends AbstractBehavior<ChargeCodeActor.ChargeCodesRequest> { /** * The incoming message this Actor will process */ public static final class ChargeCodesRequest { public final ActorRef<ChargeCodesResponse> replyTo; public ChargeCodesRequest(ActorRef<ChargeCodesResponse> replyTo) { this.replyTo = replyTo; } } /** * The outgoing message this Actor will respond with */ public static final class ChargeCodesResponse { public final ActorRef<ChargeCodesRequest> replyTo; public final List<ChargeCode> chargeCodes; public ChargeCodesResponse( List<ChargeCode> chargeCodes, ActorRef replyTo ) { this.replyTo = replyTo; this.chargeCodes = chargeCodes; } } public static Behavior<ChargeCodesRequest> create() { return Behaviors.setup(ChargeCodeActor::new); } private ChargeCodeActor(ActorContext<ChargeCodesRequest> context) { super(context); } @Override public Receive<ChargeCodesRequest> createReceive() { return newReceiveBuilder().onMessage( ChargeCodesRequest.class, this::onRequest ).build(); } private Behavior<ChargeCodesRequest> onRequest( ChargeCodesRequest request ) { getContext().getLog().info("First Message from Actor"); ChargeCodesResponse response = new ChargeCodesResponse( null, getContext().getSelf() ); request.replyTo.tell(response); return this; } }
package com.softserveinc.uschedule.entity; import com.softserveinc.uschedule.entity.util.LocalDatePersistenceConverter; import javax.persistence.*; import java.time.LocalDate; import java.util.HashSet; import java.util.Set; @Entity @Table(name = "app_user") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "first_name") private String firstName; @Column(name = "last_name") private String lastName; @Column(name = "password") private String password; @Column(name = "login_attempt_count") private Integer loginAttemptCount; @Column(name = "locked") private Boolean locked; @Column(name = "birthday") @Convert(converter = LocalDatePersistenceConverter.class) private LocalDate birthday; @Column(name = "email") private String email; @Column(name = "phone") private String phone; @Enumerated(EnumType.STRING) @Column(name = "schedule_view_type") private ScheduleViewType scheduleViewType; @Enumerated(EnumType.STRING) @Column(name = "notification_type") private NotificationType notificationType; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "image_id") private Image image; @OneToMany(mappedBy = "pk.user", fetch = FetchType.LAZY) private Set<UserToGroup> userGroups = new HashSet<UserToGroup>(); @ManyToOne @JoinColumn(name = "application_role_id") private ApplicationRole applicationRole; @PrePersist public void onCreate() { this.locked = Boolean.FALSE; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getLoginAttemptCount() { return loginAttemptCount; } public void setLoginAttemptCount(Integer loginAttemptCount) { this.loginAttemptCount = loginAttemptCount; } public Boolean getLocked() { return locked; } public void setLocked(Boolean locked) { this.locked = locked; } public LocalDate getBirthday() { return birthday; } public void setBirthday(LocalDate birthday) { this.birthday = birthday; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public ScheduleViewType getScheduleViewType() { return scheduleViewType; } public void setScheduleViewType(ScheduleViewType scheduleViewType) { this.scheduleViewType = scheduleViewType; } public NotificationType getNotificationType() { return notificationType; } public void setNotificationType(NotificationType notificationType) { this.notificationType = notificationType; } public Image getImage() { return image; } public void setImage(Image image) { this.image = image; } public Set<UserToGroup> getUserGroups() { return userGroups; } public void setUserGroups(Set<UserToGroup> userGroups) { this.userGroups = userGroups; } public ApplicationRole getApplicationRole() { return applicationRole; } public void setApplicationRole(ApplicationRole applicationRole) { this.applicationRole = applicationRole; } }
package org.ow2.proactive.resourcemanager.nodesource.infrastructure; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.concurrent.atomic.AtomicInteger; import org.objectweb.proactive.core.node.Node; import org.objectweb.proactive.core.util.ProActiveCounter; import org.ow2.proactive.resourcemanager.exception.RMException; import org.ow2.proactive.resourcemanager.nodesource.common.Configurable; import org.ow2.proactive.utils.FileToBytesConverter; /** * * An infrastructure manager that operates custom scripts in order to deploy/remove nodes. * Deployment phase: * - launch the script by providing host name, node name, node source name, rm url. * - if no node within timeout => terminates the script * * Removal phase: * - remove node from the resource manager * - launch removal script giving host name and node url. * */ public class CLIInfrastructure extends HostsFileBasedInfrastructureManager { /** */ private static final long serialVersionUID = 31L; @Configurable(description = "An interpreter that executes the script") protected String interpreter = "bash"; @Configurable(fileBrowser = true, description = "A script that deploys a node on host (parameters: host, node, ns names and rm url).") protected File deploymentScript; @Configurable(fileBrowser = true, description = "A script that removes a node (parameters: host name and node url") protected File removalScript; private final AtomicInteger numberOfRemovalThread = new AtomicInteger(0); /** * Configures the Infrastructure * * @param parameters * parameters[3] : An interpreter that launch the script * parameters[4] : A script that deploys nodes on a single host * parameters[5] : A script that removes a node * @throws IllegalArgumentException configuration failed */ @Override protected void configure(Object... parameters) { super.configure(parameters); int index = 3; // TODO super admin rights check if (parameters != null && parameters.length >= 6) { this.interpreter = parameters[index++].toString(); try { byte[] bytes = (byte[]) parameters[index++]; // putting .cmd as an extension so that it works on Windows deploymentScript = File.createTempFile("deployment", ".cmd"); FileToBytesConverter.convertByteArrayToFile(bytes, deploymentScript); //deploymentScript.setExecutable(true); } catch (Exception e) { throw new IllegalArgumentException("Could not read deployment script", e); } try { byte[] bytes = (byte[]) parameters[index++]; // putting .cmd as an extension so that it works on Windows removalScript = File.createTempFile("removal", ".cmd"); FileToBytesConverter.convertByteArrayToFile(bytes, removalScript); //removalScript.setExecutable(true); } catch (Exception e) { throw new IllegalArgumentException("Could not read removal script file", e); } } } /** * Internal node acquisition method * <p> * Starts a PA runtime on remote host using a custom script, register it manually in the * nodesource. * * @param host hostname of the node on which a node should be started * @throws RMException acquisition failed */ protected void startNodeImpl(InetAddress host) throws RMException { final String nodeName = "SCR-" + this.nodeSource.getName() + "-" + ProActiveCounter.getUniqID(); final String commandLine = interpreter + " " + deploymentScript.getAbsolutePath() + " " + host.getHostName() + " " + nodeName + " " + this.nodeSource.getName() + " " + rmUrl; final String pnURL = super.addDeployingNode(nodeName, commandLine, "Deploying node on host " + host, this.nodeTimeOut); this.pnTimeout.put(pnURL, new Boolean(false)); Process p; try { logger.debug("Launching the command: " + commandLine); p = Runtime.getRuntime().exec(commandLine); } catch (IOException e1) { super.declareDeployingNodeLost(pnURL, "Cannot run command: " + commandLine + " - " + e1.getMessage()); throw new RMException("Cannot run command: " + commandLine, e1); } String lf = System.getProperty("line.separator"); int circuitBreakerThreshold = 5; while (!this.pnTimeout.get(pnURL) && circuitBreakerThreshold > 0) { try { int exitCode = p.exitValue(); if (exitCode != 0) { logger.error("Child process at " + host.getHostName() + " exited abnormally (" + exitCode + ")."); } else { logger.error("Launching node script has exited normally whereas it shouldn't."); } String pOutPut = Utils.extractProcessOutput(p); String pErrPut = Utils.extractProcessErrput(p); final String description = "Script failed to launch a node on host " + host.getHostName() + lf + " >Error code: " + exitCode + lf + " >Errput: " + pErrPut + " >Output: " + pOutPut; logger.error(description); if (super.checkNodeIsAcquiredAndDo(nodeName, null, new Runnable() { public void run() { CLIInfrastructure.this.declareDeployingNodeLost(pnURL, description); } })) { return; } else { //there isn't any race regarding node registration throw new RMException("A node " + nodeName + " is not expected anymore because of an error."); } } catch (IllegalThreadStateException e) { logger.trace("IllegalThreadStateException while waiting for " + nodeName + " registration"); } if (super.checkNodeIsAcquiredAndDo(nodeName, null, null)) { //registration is ok, we destroy the process logger.debug("Destroying the process: " + p); p.destroy(); return; } try { Thread.sleep(1000); } catch (Exception e) { circuitBreakerThreshold--; logger.trace("An exception occurred while monitoring a child process", e); } } //if we exit because of a timeout if (this.pnTimeout.get(pnURL)) { //we remove it this.pnTimeout.remove(pnURL); //we destroy the process p.destroy(); throw new RMException("Deploying Node " + nodeName + " not expected any more"); } if (circuitBreakerThreshold <= 0) { logger.error("Circuit breaker threshold reached while monitoring a child process."); throw new RMException("Several exceptions occurred while monitoring a child process."); } } /** * {@inheritDoc} */ @Override protected void killNodeImpl(Node node, InetAddress h) { final Node n = node; final InetAddress host = h; numberOfRemovalThread.incrementAndGet(); this.nodeSource.executeInParallel(new Runnable() { public void run() { try { final String commandLine = interpreter + " " + removalScript.getAbsolutePath() + " " + host.getHostName() + " " + n.getNodeInformation().getURL(); Process p; try { logger.debug("Launching the command: " + commandLine); p = Runtime.getRuntime().exec(commandLine); // TODO add timeout behavior int exitCode = p.waitFor(); String pOutPut = Utils.extractProcessOutput(p); String pErrPut = Utils.extractProcessErrput(p); String lf = System.getProperty("line.separator"); final String description = "Removal script ouput" + lf + " >Error code: " + exitCode + lf + " >Errput: " + pErrPut + " >Output: " + pOutPut; if (exitCode != 0) { logger.error("Child process at " + host.getHostName() + " exited abnormally (" + exitCode + ")."); logger.error(description); } else { logger.info("Removal node process has exited normally for " + n.getNodeInformation().getURL()); logger.debug(description); } } catch (IOException e1) { logger.error(e1); } } catch (Exception e) { logger.trace("An exception occurred during node removal", e); } numberOfRemovalThread.decrementAndGet(); } }); } /** * @return short description of the IM */ public String getDescription() { return "Creates remote runtimes using custom scripts"; } /** * {@inheritDoc} */ @Override public String toString() { return "Script Infrastructure"; } /** * {@inheritDoc} */ @Override public void shutDown() { deploymentScript.delete(); // checking if we need to delete the removal script if (this.numberOfRemovalThread.get() <= 0) { removalScript.delete(); } } }
package structures; import java.util.*; /** * This class implements an HTML DOM Tree. Each node of the tree is a TagNode, with fields for * tag/text, first child and sibling. * */ public class Tree { /** * Root node */ TagNode root=null; /** * Scanner used to read input HTML file when building the tree */ Scanner sc; /** * Initializes this tree object with scanner for input HTML file * * @param sc Scanner for input HTML file */ public Tree(Scanner sc) { this.sc = sc; root = null; } /** * Builds the DOM tree from input HTML file, through scanner passed * in to the constructor and stored in the sc field of this object. * * The root of the tree that is built is referenced by the root field of this object. */ public void build() { /** COMPLETE THIS METHOD **/ if(sc == null) { return; } String lineCurrent; int lengthOfCurrent; Stack<TagNode> htmlTags = new Stack<TagNode>(); sc.nextLine(); root = new TagNode("html",null,null);//set root to start at html htmlTags.push(root);//pushes tags into to root TagNode newHtml; TagNode htmlPtr; while(sc.hasNextLine()) { lineCurrent = sc.nextLine(); boolean isHtml = false;//sets isHtml to false if(lineCurrent.charAt(0) == '<') { //ending of tags if(lineCurrent.charAt(1) == '/') { htmlTags.pop(); continue; } else { lineCurrent = lineCurrent.substring(1,lineCurrent.length()-1); isHtml = true;//this checks to see if it html } } newHtml = new TagNode(lineCurrent, null, null); if(htmlTags.peek().firstChild == null) {//checks to if the firstchild is null htmlTags.peek().firstChild = newHtml; } else { htmlPtr = htmlTags.peek().firstChild; //while sibling != null while(htmlPtr.sibling != null) { htmlPtr = htmlPtr.sibling; } htmlPtr.sibling = newHtml; } if( isHtml == true ){//checks to see if html is true htmlTags.push(newHtml); } } } /** * Replaces all occurrences of an old tag in the DOM tree with a new tag * * @param oldTag Old tag * @param newTag Replacement tag */ //helper method: private void helperReplace(TagNode root, String oldHtml, String newTag) { if(root == null) {//base case return; } else if(root.tag.equals(oldHtml)) {//checks to see if the tag equals the old tag root.tag = newTag; } //Recursively go through the firstChild and Sibling helperReplace(root.firstChild,oldHtml,newTag); //Sibling helperReplace(root.sibling,oldHtml,newTag); } //Method: public void replaceTag(String oldTag, String newTag) { if(root == null) { return; } if(oldTag == null) { return; } if(newTag == null) { return; } //calls helper method helperReplace(root,oldTag,newTag); } /** * Boldfaces every column of the given row of the table in the DOM tree. The boldface (b) * tag appears directly under the td tag of every column of this row. * * @param row Row to bold, first row is numbered 1 (not 0). */ private void helperBold(int rowTable, int counter, TagNode prevTag, TagNode traverseTag) {//helper method: //checks to see if traverse is null: if(traverseTag == null) { return; } else if(traverseTag.tag.equals("tr")) { counter++;//increments counter } else if(counter == rowTable && traverseTag.firstChild == null) { prevTag.firstChild = new TagNode("b", traverseTag, null); } //recurivsely go through each row helperBold(rowTable, counter, traverseTag, traverseTag.firstChild); //goes to the sibling helperBold(rowTable, counter, traverseTag, traverseTag.sibling); } public void boldRow(int row) { /** COMPLETE THIS METHOD **/ if(root == null) { return; } //now using the helper method we can bold each table if(row <= 0) { // checks to see if row is less than 0 return; }else {//otherwise call our helper method helperBold(row,0,root,root.firstChild); } } /** * Remove all occurrences of a tag from the DOM tree. If the tag is p, em, or b, all occurrences of the tag * are removed. If the tag is ol or ul, then All occurrences of such a tag are removed from the tree, and, * in addition, all the li tags immediately under the removed tag are converted to p tags. * * @param tag Tag to be removed, can be p, em, b, ol, or ul */ //method: public void removeTag(String tag) { if(root == null) { return; } if(tag.equals("p") || tag.equals("em") || tag.equals("b")) { //checks to see if tag equals any these html tagRemoverOne(root,tag); } else if(tag.equals("ol") || tag.equals("ul")) {//same as above tagRemoverTwo(root,tag); } } //helper method one public void tagRemoverOne(TagNode rootTemp, String strTarget) { //consist for p, em, b if(rootTemp == null || strTarget == null) { return; } else { tagRemoverOne(rootTemp.firstChild, strTarget); if(rootTemp.sibling != null && rootTemp.sibling.tag.equals(strTarget)){ TagNode traverse = rootTemp.firstChild; while(traverse.sibling != null){ //pointer traverse = traverse.sibling; } traverse.sibling = rootTemp.sibling.sibling; //root.sibling to sibling of firstChild rootTemp.sibling = rootTemp.sibling.firstChild; } if(rootTemp.firstChild != null && rootTemp.firstChild.tag.equals(strTarget)){ // checks to see if firstChild and firstChildTag is not equal to null and string Target rootTemp.firstChild = rootTemp.firstChild.firstChild; } //recursion: tagRemoverOne(rootTemp.sibling, strTarget); } } //second helper method public void tagRemoverTwo(TagNode rootTemp, String strTarget) { // consist for ol and ul if( strTarget == null ) { return; } if(rootTemp == null) { return; } //recursion: else { String p = " p"; //recursion part tagRemoverTwo(rootTemp.firstChild, strTarget); //now if statement similar to first helper method: if(rootTemp.sibling != null && rootTemp.sibling.tag.equals(strTarget)) { TagNode traverse = rootTemp.sibling.firstChild; //while: while(traverse.sibling != null) { traverse.tag = "p"; // makes it equal to p traverse = traverse.sibling; } traverse.tag = "p"; // makes ptr = "p" traverse.sibling = rootTemp.sibling.sibling; rootTemp.sibling = rootTemp.sibling.firstChild; } if(rootTemp.firstChild != null && rootTemp.firstChild.tag.equals(strTarget)) { //pointer: TagNode traverse = rootTemp.firstChild.firstChild; //while while(traverse.sibling != null) { traverse.tag = "p"; // makes ptr = p traverse = traverse.sibling; } traverse.tag = "p"; // makes ptr = p traverse.sibling = rootTemp.firstChild.sibling; rootTemp.firstChild = rootTemp.firstChild.firstChild; } //Recursion: String tag; tagRemoverTwo(rootTemp.sibling,strTarget); } } /** * Adds a tag around all occurrences of a word in the DOM tree. * * @param word Word around which tag is to be added * @param tag Tag to be added */ //helper method: private void helperAdd(TagNode curr, String word, String tag) { //Base Case for method if(curr == null){ return; } //Recursion helperAdd(curr.firstChild, word, tag); helperAdd(curr.sibling, word, tag); if(curr.firstChild == null) { while(curr.tag.toLowerCase().contains(word)) { //splits the array accordingly String[] arr = curr.tag.split(" "); int found = 0; String stringTagged = ""; //tags the word StringBuilder wordTagger = new StringBuilder(curr.tag.length());//stringbuilder int strWords; for( strWords = 0; strWords < arr.length; strWords++) { if(arr[strWords].toLowerCase().matches(word+"[.,?!:;]?")) {//checks puncation found = 1; //true stringTagged = arr[strWords]; int i = strWords+1; while( i < arr.length) { wordTagger.append(arr[i]+" "); i++; } break;//breaks out of loop structure } } if(found == 0){//false -> return return; } String finalWord = wordTagger.toString().trim();//trims the final word if(strWords == 0) { //if stringWords = 0 then creates the tag to suround the word curr.firstChild = new TagNode(stringTagged, null, null); curr.tag = tag; if(!finalWord.equals("")) { curr.sibling = new TagNode(finalWord, null, curr.sibling); curr = curr.sibling; } }//otherwise: else { TagNode taggedWordNode = new TagNode(stringTagged, null, null); TagNode htmlNew = new TagNode(tag, taggedWordNode, curr.sibling); curr.sibling = htmlNew; curr.tag = curr.tag.replaceFirst(" " + stringTagged, ""); if(!finalWord.equals("")) { // not equal to empty string curr.tag = curr.tag.replace(finalWord, ""); htmlNew.sibling = new TagNode(finalWord, null, htmlNew.sibling); curr = htmlNew.sibling; } } } } } public void addTag(String word, String tag) { if(word == null) { //make sure word is not null return; } if(root == null) { return; } if(tag.equals("em") || tag.equals("b")) { helperAdd(root, word.toLowerCase(), tag); } } /** * Gets the HTML represented by this DOM tree. The returned string includes * new lines, so that when it is printed, it will be identical to the * input file from which the DOM tree was built. * * @return HTML string, including new lines. */ public String getHTML() { StringBuilder sb = new StringBuilder(); getHTML(root, sb); return sb.toString(); } private void getHTML(TagNode root, StringBuilder sb) { for (TagNode ptr=root; ptr != null;ptr=ptr.sibling) { if (ptr.firstChild == null) { sb.append(ptr.tag); sb.append("\n"); } else { sb.append("<"); sb.append(ptr.tag); sb.append(">\n"); getHTML(ptr.firstChild, sb); sb.append("</"); sb.append(ptr.tag); sb.append(">\n"); } } } /** * Prints the DOM tree. * */ public void print() { print(root, 1); } private void print(TagNode root, int level) { for (TagNode ptr=root; ptr != null;ptr=ptr.sibling) { for (int i=0; i < level-1; i++) { System.out.print(" "); }; if (root != this.root) { System.out.print("|---- "); } else { System.out.print(" "); } System.out.println(ptr.tag); if (ptr.firstChild != null) { print(ptr.firstChild, level+1); } } } }
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.reviewit.widget; import android.content.Context; import android.support.annotation.DrawableRes; import android.util.AttributeSet; import android.widget.ImageView; import android.widget.LinearLayout; import com.google.gerrit.extensions.common.ApprovalInfo; import com.google.reviewit.R; import com.google.reviewit.app.Change; import com.google.reviewit.util.WidgetUtil; import java.util.HashSet; import java.util.List; import java.util.Set; import static com.google.reviewit.util.LayoutUtil.matchLayout; import static com.google.reviewit.util.WidgetUtil.setInvisible; public class VerifiedVotes extends LinearLayout { private final WidgetUtil widgetUtil; public VerifiedVotes(Context context) { this(context, null, 0); } public VerifiedVotes(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VerifiedVotes(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); this.widgetUtil = new WidgetUtil(getContext()); setOrientation(VERTICAL); } public void init(Change change) { List<ApprovalInfo> verifiedApprovals = (change.info.labels != null && change.info.labels.get("Verified") != null) ? change.info.labels.get("Verified").all : null; if (verifiedApprovals == null) { setLayoutParams(new LinearLayout.LayoutParams( widgetUtil.dpToPx(48), widgetUtil.dpToPx(48))); return; } Set<Integer> values = new HashSet<>(); for (ApprovalInfo approval : verifiedApprovals) { if (approval.value != null) { values.add(approval.value); } } values.remove(0); if (values.contains(-1)) { ImageView icon = createVoteIcon(-1); icon.setLayoutParams(matchLayout()); addView(icon); } else if (values.contains(1)) { ImageView icon = createVoteIcon(1); icon.setLayoutParams(matchLayout()); addView(icon); } else { ImageView icon = createVoteIcon(0); icon.setLayoutParams(matchLayout()); setInvisible(icon); addView(icon); } } private ImageView createVoteIcon(int verifiedVote) { ImageView icon = new ImageView(getContext()); @DrawableRes int iconRes; if (verifiedVote == -1) { icon.setColorFilter(widgetUtil.color(R.color.voteNegative)); iconRes = R.drawable.ic_clear_black_48dp; } else if (verifiedVote == 0) { iconRes = R.drawable.ic_exposure_zero_black_48dp; } else { icon.setColorFilter(widgetUtil.color(R.color.votePositive)); iconRes = R.drawable.ic_done_black_48dp; } icon.setImageDrawable(widgetUtil.getDrawable(iconRes)); return icon; } }
package com.mercadolibre.android.ui.drawee.state; import android.content.res.Resources; import android.os.Build; import androidx.annotation.NonNull; import com.mercadolibre.android.ui.R; import com.mercadolibre.android.ui.drawee.StateDraweeView; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; import static org.junit.Assert.fail; @RunWith(RobolectricTestRunner.class) @Config(sdk = Build.VERSION_CODES.LOLLIPOP) public class StateTest { @Test public void test_IsValidKeyIsTakenIntoAccount() { State state = newState(); try { state.add(-1, 0); } catch (Exception e) { Assert.assertEquals("Invalid key: -1 used for: " + state.getClass().getName() + " when adding drawable: 0", e.getMessage()); } } @Test public void test_GetDrawable() { Assert.assertEquals(R.drawable.ui_ic_view_feedback_default, newState().add(9, R.drawable.ui_ic_view_feedback_default).getDrawable(9)); } @Test public void test_GetDrawableNonExistent() { try { newState() .add(9, R.drawable.ui_ic_view_feedback_default) .getDrawable(20); fail(); } catch (Resources.NotFoundException e) { Assert.assertEquals("Drawable resource not found for key: 20", e.getMessage()); } } @Test public void test_AddKey() { State state = newState(); state.add(0, R.drawable.ui_ic_view_feedback_default); state.add(1, R.drawable.ui_ic_view_feedback_default); state.add(2, R.drawable.ui_ic_view_feedback_default); Assert.assertEquals(3, state.states.size()); } private State newState() { return new State() { @Override protected boolean isValidKey(final int key) { return key >= 0; } @Override public void attach(@NonNull final StateDraweeView view) { // Do nothing } @Override public void detach(@NonNull final StateDraweeView view) { // Do nothing } }; } }
package objects.transportsystem.transportsystems.vehicle; import objects.people.Person; import objects.transportsystem.Transport; import service.utility.UserInteractions; import java.util.ArrayList; public abstract class Vehicle extends Transport { /////////////////////////////////////////////////////ATTRIB///////////////////////////////////////////////////////// protected int gasTank; protected String make; protected String model; /////////////////////////////////////////////////////CONSTR///////////////////////////////////////////////////////// public Vehicle(String transportId, String transportName, String status, int gasTank, String make, String model) { super(transportId, transportName, status); this.gasTank = gasTank; this.make = make; this.model = model; } public Vehicle() { } /////////////////////////////////////////////////////METHOD///////////////////////////////////////////////////////// public ArrayList<String> gatherInfo() { ArrayList<String> s = super.gatherInfo(); s.add(Integer.toString(gasTank)); s.add(make); s.add(model); return s; } public ArrayList<ArrayList<String>> gatherListedInfo() { return super.gatherListedInfo(); } public void modifyMe(ArrayList<String> atribMod) { if (atribMod.contains("Gasolina")|| atribMod.contains("*")) { this.setGasTank(UserInteractions.numRequest("Introduzca nivel de gasolina")); } if (atribMod.contains("Marca")|| atribMod.contains("*")) { this.setMake(UserInteractions.strRequest("Seleccione el modelo del vehiculo")); } if (atribMod.contains("Modelo")|| atribMod.contains("*")) { this.setModel(UserInteractions.strRequest("Seleccione la marca del vehiculo")); } } /////////////////////////////////////////////////////AUTOGEN//////////////////////////////////////////////////////// public int getGasTank() { return gasTank; } public void setGasTank(int gasTank) { this.gasTank = gasTank; } public String getMake() { return make; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } }
package com.bchetty.ejb.business.contracts; import javax.ejb.Remote; /** * * @author Babji, Chetty */ @Remote public interface MrBeanRemote extends MrBeanSuper {}
package ProxyPattern13.example.Proxy.extend; /** * @Author Zeng Zhuo * @Date 2020/5/4 16:20 * @Describe */ public class Logger { public void log(String userID){ System.out.println("记录" + userID + "的访问。。。。。"); } }
package com.dfire.common.service; import com.dfire.common.entity.HeraAction; import com.dfire.common.entity.model.TablePageForm; import com.dfire.common.entity.vo.HeraActionVo; import com.dfire.common.kv.Tuple; import com.dfire.common.vo.GroupTaskVo; import com.dfire.common.vo.JobStatus; import java.util.List; /** * @author: <a href="mailto:lingxiao@2dfire.com">凌霄</a> * @time: Created in 下午3:41 2018/5/16 * @desc */ public interface HeraJobActionService { int insert(HeraAction heraAction, Long nowAction); /** * 批量插入 * * @param heraActionList * @return */ List<HeraAction> batchInsert(List<HeraAction> heraActionList, Long nowAction); int delete(String id); int update(HeraAction heraAction); List<HeraAction> getAll(); HeraAction findById(String actionId); HeraAction findLatestByJobId(String jobId); List<HeraAction> findByJobId(String jobId); int updateStatus(JobStatus jobStatus); Tuple<HeraActionVo, JobStatus> findHeraActionVo(String jobId); /** * 查找当前版本的运行状态 * * @param actionId * @return */ JobStatus findJobStatus(String actionId); JobStatus findJobStatusByJobId(String jobId); Integer updateStatus(HeraAction heraAction); Integer updateStatusAndReadDependency(HeraAction heraAction); List<HeraAction> getTodayAction(); /** * 根据jobId 获取所有的版本 * * @param jobId * @return */ List<String> getActionVersionByJobId(Long jobId); List<HeraActionVo> getNotRunScheduleJob(); List<HeraActionVo> getFailedJob(); List<GroupTaskVo> findByJobIds(List<Integer> idList, String startDate, String endDate, TablePageForm pageForm, Integer type); }
package com.ekuaibao.invoice; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.nio.charset.StandardCharsets; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; //http end /** * Hello world! */ public class InvoiceTest { //这里填写测试用的秘钥和服务商id static String epPubKeyBase64 = ""; // 开票企业公钥 static String epPriKeyBase64 = ""; // 开票企业私钥 static String spPubKeyBase64 = "BMOgG0DA9orCPjY05MDdnfcOItyGvyFSbbL5vTCvm1RhPoYyRfmzyVZRQT31AwTqCeVk6bS5ijITPRDV9fE4pw0="; // 服务商公钥 static String spPriKeyBase64 = "BA3Gc1omajZRqaJeKDXtIlmO/P46XD0q4Da+qNyPHKY="; // 服务商私钥 static String spvPubKeyBase64 = ""; // SPV公钥 static String sp_id = "sp2019120616253571704"; public static void main(String[] args) throws Exception { try { test_QueryBillInfo(); // 发票查询 //test_DigitalEnvelopeDecode(); } catch (Exception e) { System.out.println(e); } } public static void test_QueryBillInfo() throws Exception { String cgi = "/bers_ep_api/v2/BatchVerifyBill"; // val body1 = "{\"tx_hash\":\"0196b971609a02e8b8a4f2afb55f02717a182f2f396305d6bf372d4581f12f6999\"}" String body = "{\n" + " \"query_bill_size\": 1,\n" + " \"query_bill_list\": [\n" + " {\n" + " \"bill_code\":\"845032009110\",\n" + " \"bill_num\":\"03539845\",\n" + " \"issue_date\":\"20200619\",\n" + " \"ch_code\":\"df0e3\",\n" + " \"bill_net_amout\":26549\n" + " }\n" + " ]\n" + "}"; test_http_post(cgi, body); } public static String test_http_post(String cgi, String body) throws Exception { HttpURLConnection connection = null; InputStream is = null; OutputStream os = null; BufferedReader br = null; String result = null; try { String httpUrl = "https://bcfp.baas.qq.com" + cgi; URL url = new URL(httpUrl); // 通过远程url连接对象打开连接 connection = (HttpURLConnection) url.openConnection(); // 设置连接请求方式 connection.setRequestMethod("POST"); // 设置连接主机服务器超时时间:15000毫秒 connection.setConnectTimeout(15000); // 设置读取主机服务器返回数据超时时间:60000毫秒 connection.setReadTimeout(60000); // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true connection.setDoOutput(true); // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无 connection.setDoInput(true); // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。 connection.setRequestProperty("Content-Type", "application/json"); // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0 long timestamp = System.currentTimeMillis() / 1000; Sm2SDK sdk = new Sm2SDK(); String spSign = sdk.Sm2SignForSp("POST", cgi, timestamp, body, spPubKeyBase64, spPriKeyBase64); String sAuthorization = "BERS-SM3-SM2 sp_id=\"" + sp_id + "\", timestamp=\"" + String.valueOf(timestamp) + "\",signature=\"" + spSign + "\""; System.out.println("Authorization: "+sAuthorization); connection.setRequestProperty("Authorization", sAuthorization); // set body end // 通过连接对象获取一个输出流 os = connection.getOutputStream(); String param = null; // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 //os.write(param.getBytes()); os.write(body.getBytes()); // 通过连接对象获取一个输入流,向远程读取 if (connection.getResponseCode() == 200) { String rspTimestamp = connection.getHeaderField("BERS-Timestamp"); String rspSignature = connection.getHeaderField("BERS-Signature"); is = connection.getInputStream(); // 对输入流对象进行包装:charset根据工作项目组的要求来设置 br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sbf = new StringBuffer(); String temp = null; // 循环遍历一行一行读取数据 while ((temp = br.readLine()) != null) { sbf.append(temp); } result = sbf.toString(); System.out.println("result: " + result); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != br) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != os) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } // 断开与远程地址url的连接 connection.disconnect(); } return null; } }
package com.energytrade.app.dao; import org.springframework.data.jpa.repository.Modifying; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import com.energytrade.app.model.AllDrNotification; import com.energytrade.app.model.AllElectricityBoard; import com.energytrade.app.model.AllEventSet; import com.energytrade.app.model.AllForecast; import com.energytrade.app.model.AllOtp; import com.energytrade.app.model.AllSellOrder; import com.energytrade.app.model.AllState; import com.energytrade.app.model.AllTimeslot; import com.energytrade.app.model.AllUser; import com.energytrade.app.model.ContractStatusPl; import com.energytrade.app.model.EventCustomerMapping; import com.energytrade.app.model.EventCustomerStatusPl; import com.energytrade.app.model.EventSetStatusPl; import com.energytrade.app.model.LocalityPl; import com.energytrade.app.model.NonTradeHour; import com.energytrade.app.model.NonTradehourStatusPl; import com.energytrade.app.model.OrderStatusPl; import com.energytrade.app.model.StateBoardMapping; import com.energytrade.app.model.UserAccessLevelMapping; import com.energytrade.app.model.UserRolesPl; import com.energytrade.app.model.UserTypePl; import org.springframework.data.jpa.repository.JpaRepository; @Repository public interface AllDRNotificationsRepository extends JpaRepository<AllDrNotification, Long> { @Query("Select a from AllDrNotification a where a.allUser.userId=?1") List<AllDrNotification> getUserNotifications(int userId); @Modifying @Query("update AllDrNotification a set a.notificationStatusPl.notifStatusId=?1 where a.notificationId=?2") void updateNotificationStatus(int status,int notificationId); }
package com.windtalker.model; import android.content.Context; import java.util.Map; /** * Created by jaapo on 26-10-2017. */ public class ServiceContact { private static ServiceContact sSingleton; public static synchronized ServiceContact getInstance() { if(sSingleton == null) { sSingleton = new ServiceContact(); } return sSingleton; } public static synchronized ServiceContact getInstance(Context context) { if(sSingleton == null) { sSingleton = new ServiceContact(context); } return sSingleton; } public ServiceContact() { } public ServiceContact(Context context) { load(context); } private void load(Context context) { } public void enqueue(Map<String, String> message) { } }
package com.test.base; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private Solution solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(); } private void assertSolution() { // A TreeNode rootA = new TreeNode(3); TreeNode aRight = new TreeNode(20); aRight.left = new TreeNode(15); aRight.right = new TreeNode(7); rootA.left = new TreeNode(9); rootA.right = aRight; assertEquals(3, solution.maxDepth(rootA)); // B TreeNode rootB = new TreeNode(1); TreeNode bLeft = new TreeNode(2); bLeft.left = new TreeNode(4); TreeNode bRight = new TreeNode(3); bRight.right = new TreeNode(5); rootB.left = bLeft; rootB.right = bRight; assertEquals(3, solution.maxDepth(rootB)); } @Override protected void tearDown() throws Exception { solution = null; super.tearDown(); } }
class ValidAnagram { public boolean isAnagram(String s, String t) { if(s.length()!=t.length()) return false; char[] c1=s.toCharArray(); Arrays.sort(c1); char[] c2=t.toCharArray(); Arrays.sort(c2); s=Arrays.toString(c1); t=Arrays.toString(c2); System.out.println(s+" "+t); return(s.equals(t)); } }
package pl.muklejski.searchengine.service; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import pl.muklejski.searchengine.model.Document; public interface InvertedIndex { void addDocuments(List<Document> documents); Map<Document, Long> findDocuments(String token); AtomicLong getNumberOfAllDocuments(); }
/* * Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.engine; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import pl.edu.icm.unity.db.generic.tprofile.TranslationProfileDB; import pl.edu.icm.unity.engine.authz.AuthorizationManager; import pl.edu.icm.unity.engine.authz.AuthzCapability; import pl.edu.icm.unity.engine.events.InvocationEventProducer; import pl.edu.icm.unity.engine.transactions.SqlSessionTL; import pl.edu.icm.unity.engine.transactions.Transactional; import pl.edu.icm.unity.exceptions.EngineException; import pl.edu.icm.unity.exceptions.IllegalTypeException; import pl.edu.icm.unity.server.api.TranslationProfileManagement; import pl.edu.icm.unity.server.registries.InputTranslationActionsRegistry; import pl.edu.icm.unity.server.registries.OutputTranslationActionsRegistry; import pl.edu.icm.unity.server.translation.in.InputTranslationProfile; import pl.edu.icm.unity.server.translation.out.OutputTranslationProfile; import pl.edu.icm.unity.server.utils.UnityMessageSource; import pl.edu.icm.unity.stdext.translation.out.CreateAttributeActionFactory; import pl.edu.icm.unity.types.translation.ProfileType; import pl.edu.icm.unity.types.translation.TranslationAction; import pl.edu.icm.unity.types.translation.TranslationProfile; import pl.edu.icm.unity.types.translation.TranslationRule; /** * Implementation of {@link TranslationProfileManagement} * * @author K. Benedyczak */ @Component @InvocationEventProducer public class TranslationProfileManagementImpl implements TranslationProfileManagement { private AuthorizationManager authz; private TranslationProfileDB tpDB; private InputTranslationActionsRegistry inputActionReg; private OutputTranslationActionsRegistry outputActionReg; private OutputTranslationProfile defaultProfile; private UnityMessageSource msg; @Autowired public TranslationProfileManagementImpl(AuthorizationManager authz, TranslationProfileDB tpDB, InputTranslationActionsRegistry inputActionReg, OutputTranslationActionsRegistry outputActionReg, UnityMessageSource msg) throws IllegalTypeException, EngineException { this.authz = authz; this.tpDB = tpDB; this.inputActionReg = inputActionReg; this.outputActionReg = outputActionReg; this.msg = msg; this.defaultProfile = createDefaultOutputProfile(); } @Override @Transactional public void addProfile(TranslationProfile toAdd) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); tpDB.insert(toAdd.getName(), toAdd, sql); } @Override @Transactional public void removeProfile(String name) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); tpDB.remove(name, sql); } @Override @Transactional public void updateProfile(TranslationProfile updated) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); tpDB.update(updated.getName(), updated, sql); } @Override @Transactional(noTransaction=true, autoCommit=false) public Map<String, InputTranslationProfile> listInputProfiles() throws EngineException { return listProfiles(InputTranslationProfile.class, ProfileType.INPUT); } @Override @Transactional(noTransaction=true, autoCommit=false) public Map<String, OutputTranslationProfile> listOutputProfiles() throws EngineException { return listProfiles(OutputTranslationProfile.class, ProfileType.OUTPUT); } private <T extends TranslationProfile> Map<String, T> listProfiles(Class<T> clazz, ProfileType type) throws EngineException { authz.checkAuthorization(AuthzCapability.maintenance); SqlSession sql = SqlSessionTL.get(); Map<String, TranslationProfile> all = tpDB.getAllAsMap(sql); sql.commit(); Map<String, T> ret = new HashMap<String, T>(); for (Map.Entry<String, TranslationProfile> e: all.entrySet()) if (e.getValue().getProfileType().equals(type)) ret.put(e.getKey(), makeInstance(e.getValue())); return ret; } @SuppressWarnings("unchecked") private <T extends TranslationProfile> T makeInstance(TranslationProfile core) { switch (core.getProfileType()) { case INPUT: return (T)new InputTranslationProfile(core.getName(), core.getDescription(), core.getRules(), inputActionReg); case OUTPUT: return (T)new OutputTranslationProfile(core.getName(), core.getDescription(), core.getRules(), outputActionReg); default: throw new IllegalStateException("The stored translation profile with type id " + core.getProfileType() + " is not accessible as a standalone profile"); } } @Override public OutputTranslationProfile getDefaultOutputProfile() throws EngineException { return defaultProfile; } private OutputTranslationProfile createDefaultOutputProfile() throws IllegalTypeException, EngineException { List<TranslationRule> rules = new ArrayList<>(); TranslationAction action1 = new TranslationAction(CreateAttributeActionFactory.NAME, new String[] {"memberOf", "groups", "false", msg.getMessage("DefaultOutputTranslationProfile.attr.memberOf"), msg.getMessage("DefaultOutputTranslationProfile.attr.memberOfDesc")}); rules.add(new TranslationRule("true", action1)); return new OutputTranslationProfile("DEFAULT OUTPUT PROFILE", "", rules, outputActionReg); } }
package collection_framework; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.PriorityQueue; public class PriorityqueueDemo { public static void main(String[] args) { /* PriorityQueue<String> queue=new PriorityQueue<String>(); queue.add("hello"); queue.add("yelo"); queue.add("pelo"); queue.add("khalo"); System.out.println(queue); System.out.println(queue.poll()); System.out.println(queue.element()); System.out.println(queue.offer("ji")); System.out.println(queue); */ PriorityQueue<Percentage> queue=new PriorityQueue<Percentage>(); queue.offer(new Percentage("vishal rana", 550, 444)); queue.offer(new Percentage("arun rana", 550, 450)); queue.offer(new Percentage("tarun rana", 550, 350)); queue.offer(new Percentage("bunty rana", 550, 490)); for (Percentage percentage : queue) { System.out.println(percentage); } System.out.println("now delete elements one by one :"); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); } } class Percentage implements Comparable<Percentage> { String name; int total_marks; int marks_obtained; public Percentage(String name, int total_marks, int marks_obtained) { super(); this.name = name; this.total_marks = total_marks; this.marks_obtained = marks_obtained; } @Override public int compareTo(Percentage o) { return this.name.compareToIgnoreCase(o.name); } @Override public String toString() { return "Percentage [name=" + name + ", total_marks=" + total_marks + ", marks_obtained=" + marks_obtained + "]"; } }
package org.crazyit.service; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startService(View source) { // 创建需要启动的Service的Intent Intent intent = new Intent(this, MyService.class); // 启动Service startService(intent); } public void startIntentService(View source) { // 创建需要启动的IntentService的Intent Intent intent = new Intent(this, MyIntentService.class); // 启动IntentService startService(intent); } }
package com.cinema.sys.dao; import java.io.Serializable; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.alibaba.fastjson.JSONObject; import com.cinema.sys.model.Property; public interface PropertyMapper{ /** * 获取属性 */ public List<Property> getAllList(@Param("type")String type); /** * 获取属性 */ public List<Property> getDeviceProperties(@Param("type")String type); /** * 查询属性列表分页 */ public List<Property> getList(@Param("paraMap") Map<String, Object> paraMap); public int getTotal(@Param("paraMap") Map<String, Object> paraMap); /** * 验证设备属性是否重名(true:存在重名) * * @param type * :属性类型 * @param id * :属性id * @param name * :属性名称 * @return */ public List<Property> checkProerty(@Param("paraMap") Map<String, Object> paraMap); /** * 保存任意类型tmode * * @param o * @return */ void insert(Property m); /** * 更新数据库对象 * * @param obj */ void update(Property m); /** * 删除指定对象 * * @param o */ void delete(@Param("type") String type,@Param("id") String id); /** * 判断name不存在 * * @param o */ Boolean isNotExist(@Param("type") String type,@Param("id") String id,@Param("name") String name); /** * 通过主键获得对象 * * @param c * 类名.class * @param id * 主键 * @return 对象 */ @SuppressWarnings("hiding") public <T> T get(Class<T> c, Serializable id); }
package com.game.service.impl; import com.game.service.R2LastWeekReportService; import com.game.biz.model.R2LastWeekReport; import com.game.repository.R2LastWeekReportRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; /** * Service Implementation for managing {@link R2LastWeekReport}. */ @Service @Transactional public class R2LastWeekReportServiceImpl implements R2LastWeekReportService { private final Logger log = LoggerFactory.getLogger(R2LastWeekReportServiceImpl.class); private final R2LastWeekReportRepository r2LastWeekReportRepository; public R2LastWeekReportServiceImpl(R2LastWeekReportRepository r2LastWeekReportRepository) { this.r2LastWeekReportRepository = r2LastWeekReportRepository; } /** * Save a r2LastWeekReport. * * @param r2LastWeekReport the entity to save. * @return the persisted entity. */ @Override public R2LastWeekReport save(R2LastWeekReport r2LastWeekReport) { log.debug("Request to save R2LastWeekReport : {}", r2LastWeekReport); return r2LastWeekReportRepository.save(r2LastWeekReport); } /** * Get all the r2LastWeekReports. * * @return the list of entities. */ @Override @Transactional(readOnly = true) public List<R2LastWeekReport> findAll() { log.debug("Request to get all R2LastWeekReports"); return r2LastWeekReportRepository.findAll(); } /** * Get one r2LastWeekReport by id. * * @param id the id of the entity. * @return the entity. */ @Override @Transactional(readOnly = true) public Optional<R2LastWeekReport> findOne(Long id) { log.debug("Request to get R2LastWeekReport : {}", id); return r2LastWeekReportRepository.findById(id); } /** * Delete the r2LastWeekReport by id. * * @param id the id of the entity. */ @Override public void delete(Long id) { log.debug("Request to delete R2LastWeekReport : {}", id); r2LastWeekReportRepository.deleteById(id); } }
package rss.printlnstuidios.com.myapplication; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Timer; import java.util.TimerTask; /** * Created by Justin Hill on 12/2/2014. * * Represents the users main list of posts where then can click on one to view it and select to view * them by feed or my read/unread/stared state */ public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener { //Elements in the view that the user interacts with private ListView contentListView; private static Spinner activeFeeds; private Spinner viewSelect; private ContentListAdapter contentAdapter; //List of all the users feeds and adapter to display them private static List<String> feedsList = new ArrayList<String>(); ArrayAdapter<String> adapter; //What state of posts the user wants to view public int whatPostsToView = 0; private static Post p; //Auto refresh timer private static Timer timer; private int timerSpeed = 100000; //Reference to mainActivity to use in different threads. MainActivity mainActivity = this; /** * Sets up the main view and makes the necessary reference and listeners to the interactive UI * elements in the view. */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //make a reference to the content list and set a click listener to this class contentListView = (ListView) findViewById(R.id.main_feed); contentListView.setOnItemClickListener(this); //make a reference to the spinner which allows the user to select what feeds they want to view activeFeeds = (Spinner) findViewById(R.id.select_feeds); activeFeeds.setOnItemSelectedListener(this); //make a reference to the spinner which allows the user to select what posts they want to view viewSelect = (Spinner) findViewById(R.id.view_select); viewSelect.setOnItemSelectedListener(this); //Add two options two the Spinner of what feeds to view if(feedsList.size()==0) { feedsList.add("All Feeds"); feedsList.add("Add New"); } //puts feeds list into the active feeds spinner adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, feedsList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); activeFeeds.setAdapter(adapter); contentAdapter = new ContentListAdapter(this, getLayoutInflater()); contentListView.setAdapter(contentAdapter); //Load Feeds GetContent.findContent(this); //start the auto refresh timer timer = new Timer(); timer.schedule(new timeUpdate(),0, timerSpeed); } /** * Updates the view when new posts are added. */ public synchronized void foundContent() { ArrayList<Post> postsFromOpenFeeds = GetContent.postsFromOpenFeeds; //remove duplicates for(int i = 0; i < postsFromOpenFeeds.size(); i++) { for (int j = i + 1; j < postsFromOpenFeeds.size(); j++) { if (postsFromOpenFeeds.get(j).equals(postsFromOpenFeeds.get(i))) { postsFromOpenFeeds.remove(j); j--; } } } GetContent.postsFromOpenFeeds = postsFromOpenFeeds; //Sorts the posts chronologically Collections.sort(postsFromOpenFeeds); GetContent.postsFromOpenFeeds = postsFromOpenFeeds; this.runOnUiThread(new Runnable() { @Override public void run() { contentAdapter.notifyDataSetChanged(); contentAdapter.update(); } }); //update the list of feeds if(GetContent.allFeeds.size()>=feedsList.size()-1) { for(Feed f : GetContent.allFeeds) { if(f.allPosts!=null&&f.allPosts.size()>0&&!feedsList.contains(f.allPosts.get(0).source)) { feedsList.add(feedsList.size()-1,f.allPosts.get(0).source); adapter.notifyDataSetChanged(); } } } this.runOnUiThread(new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } /** * Inflate the menu; this adds items to the action bar if it is present. */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } /** * Adds items to the action bar */ @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } else if(id == R.id.action_refresh) { GetContent.findContent(); } return super.onOptionsItemSelected(item); } /** * Open the View Post Activity when the user clicks on a post */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { p = GetContent.postsFromOpenFeeds.get(position); GetContent.readPost(position); Intent viewPost = new Intent(this, ViewPostActivity.class); viewPost.putExtra("Post", GetContent.getContent(position)); this.startActivity(viewPost); } /** * Called when an item is selected in on of the two spinners that allow the user to selct * what posts tol view */ @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if(viewSelect.getId()==parent.getId()) //change in view star/read/unread { whatPostsToView = position; GetContent.foundNewContent(); } else //change in active feeds { GetContent.setActive(feedsList.get(position)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } GetContent.save(mainActivity); } } /** * Overrides the noting selected method so nothing happens when nothing is selected in a spinner */ @Override public void onNothingSelected(AdapterView<?> parent) { } /** * Toggles if a posts is starred */ public static void starPost() { p.star = !p.star; } /** * Sets the left spinner to view posts from All Feeds. Called when the user adds a new feed. */ public static void resetSpinner() { activeFeeds.setSelection(0); } /** * Periodically refresh the page */ class timeUpdate extends TimerTask { @Override public void run() { GetContent.findContent(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } GetContent.save(mainActivity); } }; }
package us.team7pro.EventTicketsApp.Repositories; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import us.team7pro.EventTicketsApp.Models.Transaction; public interface TransactionRepository extends JpaRepository<Transaction, Integer> { public List<Transaction> findByUserID(long userID); public List<Transaction> findByUserIDAndStatus(long userID, boolean status); public Transaction findByUserIDAndEventID(long userID, int eventID); public Transaction findByTransactionID(int transactionID); }
package kr.co.flyingturtle.repository.mapper; import java.util.List; import kr.co.flyingturtle.repository.vo.Member; public interface MypageMapper { /* 작성글, 작성댓글 보기 */ Member listMypage(int memberNo); List<Member> listMyWrite(int memberNo); List<Member> listMyComment(int memberNo); /* 작성글 갯수, 작성댓글 갯수 보기 */ int countWriteVideo(int memberNo); int countWriteQna(int memberNo); int countCommentVideo(int memberNo); int countCommentQna(int memberNo); /*회원 정보 수정*/ void updateMember(Member member); }
package com.javiermarsicano.algorithms.hackerrank; import java.util.Scanner; public class Staircase { public static int stairs(int n, int lim, int[] lookup) { if (n == lim) { return 1; } else { int acum = 0; for (int i = 1; (i <= 3) && ((n + i) <= lim); i++) { if (lookup[n + i - 1] == -1) { lookup[n + i - 1] = stairs(n + i, lim, lookup); } acum = acum + lookup[n + i - 1]; } return acum; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int s = in.nextInt(); int n[] = new int[s]; for(int a0 = 0; a0 < s; a0++){ n[a0] = in.nextInt(); } for(int a0 = 0; a0 < s; a0++){ int[] lookup = new int[n[a0]]; for (int i = 0; i < n[a0]; i++) { lookup[i] = -1; } System.out.println(stairs(0, n[a0], lookup)); } } } /* * 5 19 18 35 20 25 * */
package window.search; import java.util.Vector; public class IngredientsHelper { static int INGR_NUM = 6; public static String getIngredientName(int ingredient){ String res; switch(ingredient){ case 1: res = "ser"; break; case 2: res = "szynka"; break; case 4: res = "pieczarki"; break; case 8: res = "kukurydza"; break; case 16: res = "salami"; break; case 32: res = "ananas"; break; default: res = ""; } return res; } public static Vector<String> getIngredients(int sklad){ Vector<String> res = new Vector(); int power = 1; for(int i=0; i<INGR_NUM; i++){ if(!getIngredientName(power & sklad).equals("")){ res.add(getIngredientName(power & sklad)); } power*=2; } return res; } public static Vector<String> getAllIngredients() { return getIngredients(Integer.MAX_VALUE); } public static int translateToInt(boolean[] ingr){ int power = 1; int res = 0; for(int i=0; i<INGR_NUM; i++){ if(ingr[i]) res += power; power*=2; } return res; } }
package com.example.buglordie.myweatherapp; import android.app.Activity; import android.widget.ImageView; import java.util.Calendar; class Shared { static String background = "background index"; static String tomorrow = "tomorrow"; static String week = "week"; static String pressure = "pressure"; static void setBackground(Activity activity) { ImageView background = activity.findViewById(R.id.background); int currentHours = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); if (currentHours > 5 && currentHours < 21) background.setBackground(activity.getResources().getDrawable(R.drawable.background_daylight)); else background.setBackground(activity.getResources().getDrawable(R.drawable.background_night)); } }
package com.tao.wsa.service; public class RequestTemplateService { //TO DO }
package util; public enum DepositTypeEnum { DEBTOR("debtor"), CREDITOR("creditor"); private final String depositType; DepositTypeEnum(String depositType) { this.depositType = depositType; } public String getDepositType() { return this.depositType; } public static DepositTypeEnum fromValue(String type) { for (DepositTypeEnum depositType : DepositTypeEnum.values()) { if (depositType.getDepositType().equals(type)) { return depositType; } } return null; } }
package com.mmm.service.exceptionPackage; /** * 年龄异常类 */ public class AgeException extends UserException { public AgeException(String msg) { super(msg); } }
package com.edasaki.rpg.spells.reaper; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.util.Vector; import com.edasaki.core.utils.RMath; import com.edasaki.core.utils.RParticles; import com.edasaki.core.utils.RScheduler; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.spells.Spell; import com.edasaki.rpg.spells.SpellEffect; import de.slikey.effectlib.util.ParticleEffect; public class BloodPact extends SpellEffect { @Override public boolean cast(final Player p, final PlayerDataRPG pd, int level) { Vector dir = p.getLocation().getDirection().normalize().multiply(0.3); Location start = p.getLocation().add(0, p.getEyeHeight() * 0.75, 0).clone(); Location curr = start.clone(); Entity target = null; for (int k = 0; k < 30; k++) { for (Entity e : RMath.getNearbyEntities(curr, 1.5)) { if (e != p) { if (Spell.canDamage(e, true)) { target = e; break; } } } if (target != null) break; curr.add(dir); if (!RParticles.isAirlike(curr.getBlock())) break; } if (target == null) { p.sendMessage(ChatColor.RED + "Failed to find a Blood Pact target."); return false; } double mult = 0.08; switch (level) { case 1: mult = 0.08; break; case 2: mult = 0.11; break; case 3: mult = 0.14; break; case 4: mult = 0.17; break; case 5: mult = 0.20; break; } int selfDmg = (int) (mult * (pd.baseMaxHP + pd.maxHP)); if (pd.hp <= selfDmg) { p.sendMessage(ChatColor.RED + "You don't have enough HP to cast Blood Pact!"); return false; } if (selfDmg >= pd.hp) selfDmg = pd.hp - 1; start = target.getLocation().clone(); pd.damageSelfTrue(selfDmg); RParticles.showWithOffset(ParticleEffect.REDSTONE, p.getLocation().add(0, p.getEyeHeight() * 0.7, 0), 0.6, 50); final int tickDmg = selfDmg / 2 < 1 ? 1 : selfDmg / 2; final Entity fTarget = target; for (int k = 1; k <= 2; k++) { RScheduler.schedule(Spell.plugin, new Runnable() { public void run() { if(!p.isOnline() || !fTarget.isValid() || (fTarget instanceof Player && !((Player) fTarget).isOnline())) return; if (Spell.damageEntity(fTarget, tickDmg, p, true, false)) { Location loc = fTarget.getLocation().clone().add(0, p.getEyeHeight() * 0.7, 0); RParticles.showWithOffset(ParticleEffect.REDSTONE, loc, 0.6, 50); } } }, k * 20); } Spell.notify(p, "You form a Blood Pact with your enemy."); return true; } }
package com.wipro.overridingpolymorphism; class Fruit { String name; String taste; String size; Fruit(String name,String taste) { this.name=name; this.taste=taste; } public void eat() { System.out.println("Fruit : "+name+", taste : "+taste); } } class Apple extends Fruit { Apple(String name,String taste) { super(name,taste); } public void eat() { System.out.println("Fruit : "+name+", taste : "+taste); } } class Orange extends Fruit { Orange(String name,String taste) { super(name,taste); } public void eat() { System.out.println("Fruit : "+name+", taste : "+taste); } } public class Ex1 { public static void main(String[] args) { // TODO Auto-generated method stub Fruit fruit=new Fruit("Fruit","sweet"); Apple apple=new Apple("Apple","very sweet"); Orange orange=new Orange("Orange","sweet and sour"); fruit.eat(); apple.eat(); orange.eat(); } }
package com.example.ramonsl.myjobs; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ArrayList<Categoria> categorias = new ArrayList<>(); categorias.add(new Categoria("PRESENCIAL", R.drawable.)); categorias.add(new Categoria("REMOTA", R.drawable.)); final CategoriaAdapter adapter = new CategoriaAdapter(this, categorias); ListView lista = (ListView) findViewById(R.id.); lista.setAdapter(adapter); lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { switch(i) { case 0: final Intent intentSalgados = new Intent(getApplicationContext(), .class); startActivity(intentSalgados); break; } } }); } }
package com.design.pattern; import java.util.Calendar; /** * @Author: 98050 * @Time: 2019-01-09 22:38 * @Feature: */ public class Test { public static void main(String[] args) throws CloneNotSupportedException { Student student1 = new Student(); student1.setName("1"); student1.setAge(2); Professor professor = new Professor(); professor.setName("a"); professor.setAge(11); student1.setProfessor(professor); System.out.println("student1" + student1); Student student2 = (Student) student1.clone(); Professor professor2 = student2.getProfessor(); professor2.setName("b"); professor2.setAge(22); student2.setProfessor(professor2); System.out.println(student1); System.out.println(student2); } }
package com.memory.platform.common.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.sql.SQLException; import java.sql.Timestamp; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p> * Title: GCRCS * </p> * <p> * Description: 静态方法类,如字符转换等 * </p> * <p> * Copyright: Copyright (c) 2014 * </p> * <p> * Company: Sunny * </p> * * @author * @version 1.0 update dy 2014-6-16 13:00 */ public class StaticMethod { /** * slf4j */ private static final Logger logger = LoggerFactory.getLogger(StaticMethod.class); /** * classpath标识 */ public final static String CLASSPATH_FLAG = "classpath:"; @SuppressWarnings("unchecked") public static String method2class(Method method) { // 方法名称 String methodName = method.getName(); // 类名 String clz = method.getDeclaringClass().getName(); // 方法类型 Class paramTypes[] = method.getParameterTypes(); // 存放方法类型的临时对象 String types = ""; if (paramTypes != null && paramTypes.length > 0) { for (int i = 0; i < paramTypes.length; i++) { types += paramTypes[i].getName() + ","; } types = types.substring(0, types.length() - 1); } return clz + "." + methodName + "(" + types + ")"; } /** * classpath标识 */ // public final static ClassLoader loader = Thread.currentThread() // .getContextClassLoader(); // 得到的是当前的classpath的绝对URI路径 public final static URL URI = StaticMethod.class.getResource("/"); /** * 取filePath的绝对路径 * * @param filePath * 文件路径 * @deprecated 尽量命名用getFileUrl及getFilePathForUrl替代 * @see StaticMethod#getClasspath() * @return */ public static String getFilePath(String filePath) { if (filePath != null) { if (filePath.length() > CLASSPATH_FLAG.length()) { if (CLASSPATH_FLAG.equals(filePath.substring(0, CLASSPATH_FLAG .length()))) { filePath = getClasspath() + filePath.substring(CLASSPATH_FLAG.length()); } } } return filePath; } /** * 取classpath路径 * * @return classpath路径 * @see StaticMethod#getFilePath(String) * @see StaticMethod#getFileUrl(String) */ public final static String getClasspath() { // String classpath = Thread.currentThread().getContextClassLoader() // .getResource("").getPath() // + ""; // return classpath.substring(1); return URI.getFile(); } /** * web-inf同级路径 * * @return */ public static String getWebPath() throws FileNotFoundException { // String path = // getFilePathForUrl("classpath:config/applicationContext-all.xml"); // System.out.println("path=" + path); // int position = path.indexOf("/WEB-INF"); // return path.substring(0, position); // 因为类名为Application,因此 Application.class一定能找到 String result = StaticMethod.class.getResource("StaticMethod.class") .toString(); int index = result.indexOf("WEB-INF"); if (index == -1) { index = result.indexOf("bin"); } result = result.substring(0, index); if (result.startsWith("jar")) { // 当class文件在jar文件中时,返回”jar:file:/F:/ …”样的路径 result = result.substring(10); } else if (result.startsWith("file")) { // 当class文件在jar文件中时,返回”file:/F:/ …”样的路径 result = result.substring(6); } return result; } /** * 去掉classpath * * @param path * @return */ private static String getPathButClasspath(String path) { return path.substring(CLASSPATH_FLAG.length()); } public StaticMethod() { } /** * @see 字符处理方法:将首字符转换为大写 * @param string * @return */ public static String firstToUpperCase(String string) { String post = string.substring(1, string.length()); String first = ("" + string.charAt(0)).toUpperCase(); return first + post; } /** * @see 将中文格式转换成标准格式 * @see 例如:StaticMethod.getString("中文"); * @param para * String 中文字符串 * @return String para的标准格式的串 */ public static String getString(String para) { String reStr = ""; try { reStr = new String(para.getBytes("GB2312"), "ISO-8859-1"); } catch (Exception e) { e.printStackTrace(); } return reStr; } /** * @see 修改iso到GB2312 * * @param para * String * @return String */ public static String getPageString(String para) { String reStr = ""; try { reStr = new String(para.getBytes("ISO-8859-1"), "GB2312"); } catch (Exception e) { e.printStackTrace(); } return reStr; } public static String getPageUTF(String para) { String reStr = ""; try { reStr = new String(para.getBytes("UTF-8"), "GB2312"); } catch (Exception e) { e.printStackTrace(); } return reStr; } /** * @see 得到一指定分隔符号分隔的vector 如:Vector nn = * StaticMethod.getVector("2003-4-5","-"); */ @SuppressWarnings("unchecked") public static Vector getVector(String string, String tchar) { StringTokenizer token = new StringTokenizer(string, tchar); Vector vector = new Vector(); if (!string.trim().equals("")) { try { while (token.hasMoreElements()) { vector.add(token.nextElement().toString()); } } catch (Exception e) { e.printStackTrace(); } } return vector; } /** * @see 将一个字符串按照一定长度截为一个List * * @param str * @param size * @return */ @SuppressWarnings("unchecked") public static ArrayList getArrayList(String str, int size) { ArrayList vec = new ArrayList(); String temp = ""; str = str.trim(); try { while (str.length() > size) { temp = str; vec.add(temp); str = str.substring(0, str.length() - size); } if (!str.equals("")) { vec.add(str); } } catch (Exception e) { e.printStackTrace(); } return vec; } /** * @see 得到一指定分隔符号分隔的ArrayList * * @param string * @param tchar * @return */ @SuppressWarnings("unchecked") public static ArrayList getArrayList(String string, String tchar) { StringTokenizer token = new StringTokenizer(string, tchar); ArrayList array = new ArrayList(); if (!string.trim().equals("")) { try { while (token.hasMoreElements()) { array.add(token.nextElement().toString()); } } catch (Exception e) { e.printStackTrace(); } } return array; } /** * @see 判断id值是否包含在数组中 * @param id * int id * @param array * 集合 数组 * @return * @throws Exception */ @SuppressWarnings("unchecked") public static boolean fHasId(int id, ArrayList array) throws Exception { boolean ret = false; int i = 0; try { while (i < array.size() && ret == false) { if (id == StaticMethod.nullObject2int(array.get(i))) { ret = true; } i++; } } catch (Exception e) { } return ret; } /** * @see 得到两个集合的交集,返回一个新的集合 * * @param array1 * @param array2 * @return */ @SuppressWarnings("unchecked") public static ArrayList getArrayList(ArrayList array1, ArrayList array2) { ArrayList array = new ArrayList(); try { for (int i = 0; i < array1.size(); i++) { int temp = StaticMethod.nullObject2int(array1.get(i)); if (StaticMethod.fHasId(temp, array2) == true) { array.add(new Integer(temp)); } } } catch (Exception e) { // BocoLog.error("StaticMethod.java", 0, "错误", e); } return array; } /** * @see 得到两个集合的叉集,返回一个新的集合,即:在array1中,不在array2中 * * @param array1 * @param array2 * @return */ @SuppressWarnings("unchecked") public static ArrayList getArrayList2(ArrayList array1, ArrayList array2) { ArrayList array = new ArrayList(); int size1 = array1.size(); int size2 = array2.size(); if ((size2 == 0) || (size1 == 0)) { array = array1; } else { try { for (int i = 0; i < array1.size(); i++) { int temp = StaticMethod.nullObject2int(array1.get(i)); if (StaticMethod.fHasId(temp, array2) == false) { array.add(new Integer(temp)); } } } catch (Exception e) { // BocoLog.error("StaticMethod.java", 0, "错误", e); } } return array; } /** * 字符转换函数 * * @param s * @return output:如果字符串为null,返回为空,否则返回该字符串 */ public static String nullObject2String(Object s) { String str = ""; try { str = s.toString(); } catch (Exception e) { str = ""; } return str; } /** * 将一个对象转换为String,如果 * * @param s * @param chr * @return */ public static String nullObject2String(Object s, String chr) { String str = chr; try { str = s.toString(); } catch (Exception e) { str = chr; } return str; } /** * 将一个对象转换为String,如果 * * @param s * @return */ public static Integer nullObject2Integer(Object s) { return new Integer(StaticMethod.nullObject2int(s)); } /** * 将一个对象转换为整形 * * @param s * @return */ public static int nullObject2int(Object s) { String str = ""; int i = 0; try { str = s.toString(); i = Integer.parseInt(str); } catch (Exception e) { i = 0; } return i; } /** * 将对象转换为整形 * * @param s * @param in * @return */ public static int nullObject2int(Object s, int in) { String str = ""; int i = in; try { str = s.toString(); i = Integer.parseInt(str); } catch (Exception e) { i = in; } return i; } public static Timestamp nullObject2Timestamp(Object s) { Timestamp str = null; try { str = Timestamp.valueOf(s.toString()); } catch (Exception e) { str = null; } return str; } /** * 字符转换函数如果字符串为null,返回为空,否则返回该字符串 * * @param s * @return */ public static String null2String(String s) { return s == null ? "" : s; } @SuppressWarnings("unchecked") public static ArrayList getSubList(ArrayList list1, ArrayList list2) { ArrayList list = new ArrayList(); int j = list1.size(); int k = list2.size(); if ((j > 0) && (k > 0)) { Collections.sort(list1); Collections.sort(list2); for (int i = 0; i < j; i++) { String temp = StaticMethod.nullObject2String(list1.get(i)); for (int l = 0; l < k; l++) { String temp2 = StaticMethod.nullObject2String(list2.get(l)); if (temp.equals(temp2)) { list.add(temp); } } } } return list; } /** * * @param list1 * @param list2 * @return */ @SuppressWarnings("unchecked") public static Vector getSubVec(Vector list1, Vector list2) { Vector list = new Vector(); int j = list1.size(); int k = list2.size(); if ((j > 0) && (k > 0)) { Collections.sort(list1); Collections.sort(list2); for (int i = 0; i < j; i++) { String temp = StaticMethod.nullObject2String(list1.get(i)); for (int l = 0; l < k; l++) { String temp2 = StaticMethod.nullObject2String(list2.get(l)); if (temp.equals(temp2)) { list.add(temp); } } } } return list; } /** * 字符转换函数,如果字符串1为null,返回为字符串2,否则返回该字符串 * * @param s * @param s1 * @return */ public static String null2String(String s, String s1) { return s == null ? s1 : s; } /** * 字符转换函数:如果字符串1为null或者不能转换成整型,返回为0 * * @param s * @return */ public static int null2int(String s) { int i = 0; try { i = Integer.parseInt(s); } catch (Exception e) { i = 0; } return i; } /** * 字符转换函数:如果字符串1为null或者不能转换成整型,返回为0 * * @param s * @return */ public static long null2Long(String s) { long i = 0; try { i = Long.parseLong(s); } catch (Exception e) { i = 0; } return i; } /** * 对象转换为long型 * * @param s * @return */ public static long nullObject2Long(Object s) { long i = 0; String str = ""; try { str = s.toString(); i = Long.parseLong(str); } catch (Exception e) { i = 0; } return i; } /** * 将对象转换为long,如果无法转换则返回temp * * @param s * @param temp * @return */ public static long nullObject2Long(Object s, long temp) { long i = temp; String str = ""; try { str = s.toString(); i = Long.parseLong(str); } catch (Exception e) { i = temp; } return i; } /** * 将对象转换为float,如果无法转换则返回temp * @param s * @param temp * @return */ public static float nullObject2Float(Object s, float temp) { float i = temp; String str = ""; try { str = s.toString(); i = Float.parseFloat(str); } catch (Exception e) { i = temp; } return i; } /** * 字符转换函数:如果字符串1为null或者不能转换成整型,返回为整型2 * * @param s * @param in * @return */ public static int null2int(String s, int in) { int i = in; try { i = Integer.parseInt(s); } catch (Exception e) { i = in; } return i; } /** * 字符串处理方法: * * @param str * @param dim * @return */ @SuppressWarnings("unchecked") public static ArrayList TokenizerString(String str, String dim) { return TokenizerString(str, dim, false); } /*************************************************************************** * 将输入的字符串str按照分割符dim分割成字符串数组并返回ArrayList字符串数组**** If the returndim flag is * true, then the dim characters are also returned as tokens. Each delimiter * is returned as a string of length one. If the flag is false, the * delimiter characters are skipped and only serve as separators between * tokens. **************************************************************************/ @SuppressWarnings("unchecked") public static ArrayList TokenizerString(String str, String dim, boolean returndim) { str = null2String(str); dim = null2String(dim); ArrayList strlist = new ArrayList(); StringTokenizer strtoken = new StringTokenizer(str, dim, returndim); while (strtoken.hasMoreTokens()) { strlist.add(strtoken.nextToken()); } return strlist; } /** * 字符串处理方法: 类似上面的方法,将输入的字符串str按照分割符dim分割成字符串数组,**** 并返回定长字符串数组 * * @param str * @param dim * @return * @see TokenizerString */ public static String[] TokenizerString2(String str, String dim) { return TokenizerString2(str, dim, false); } /** * 字符串处理方法: * * @see TokenizerString * @param str * @param dim * @param returndim * @return */ @SuppressWarnings("unchecked") public static String[] TokenizerString2(String str, String dim, boolean returndim) { ArrayList strlist = TokenizerString(str, dim, returndim); int strcount = strlist.size(); String[] strarray = new String[strcount]; for (int i = 0; i < strcount; i++) { strarray[i] = (String) strlist.get(i); } return strarray; } /** * * @param v * @param l * @return */ public static String add0(int v, int l) { long lv = (long) Math.pow(10, l); return String.valueOf(lv + v).substring(1); } /** * Cookie系列方法:获得请求中Cookie的某个key的值 * * @param req * @param key * @return */ public static String getCookie(HttpServletRequest req, String key) { Cookie[] cookies = req.getCookies(); for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(key)) { return cookies[i].getValue(); } } return null; } /** * Cookie系列方法 * * @param res * @param key * @param value * @param age * @param domain */ public static void setCookie(HttpServletResponse res, String key, String value, int age, String domain) { Cookie newCookie = new Cookie(key, value); newCookie.setMaxAge(age); newCookie.setDomain(domain); newCookie.setPath("/"); res.addCookie(newCookie); } /** * Cookie系列方法 * * @param res * @param key * @param value * @param age */ public static void setCookie(HttpServletResponse res, String key, String value, int age) { Cookie newCookie = new Cookie(key, value); newCookie.setMaxAge(age); newCookie.setPath("/"); res.addCookie(newCookie); } /** * Cookie系列方法 * * @param res * @param key * @param value */ public static void setCookie(HttpServletResponse res, String key, String value) { setCookie(res, key, value, -1); } /** * 编码处理方法: * * @param s * @return */ public static String fromScreen(String s) { if (s == null) { s = null2String(s); } s = fromBaseEncoding(s); s = toHtml(s); return s; } /** * 编码处理方法: * * @param s * @return */ public static String toScreen(String s) { if (s == null) { s = null2String(s); } s = toBaseEncoding(s); s = fromHtml(s); return s; } /** * 字符串处理方法: * * @param s * @param languageid * @return */ public static String toScreenToEdit(String s, int languageid) { if (s == null) { s = null2String(s).trim(); } s = toBaseEncoding(s); s = fromHtmlToEdit(s); return s; } /** * 编码处理方法:转换GB2312到ISO-8859-1 * * @param s * @return */ public static String toBaseEncoding(String s) { try { byte[] target_byte = s.getBytes("GB2312"); return new String(target_byte, "ISO-8859-1"); } catch (Exception ex) { return s; } } /** * 编码处理方法:转换ISO-8859-1到GB2312 * * @param s * @return */ public static String fromBaseEncoding(String s) { try { byte[] target_byte = s.getBytes("ISO-8859-1"); return new String(target_byte, "GB2312"); } catch (Exception ex) { return s; } } /** * 字符串处理方法:转换html标签为可显示 * * @param s * @return */ public static String toHtml(String s) { char c[] = s.toCharArray(); char ch; int i = 0; StringBuffer buf = new StringBuffer(); while (i < c.length) { ch = c[i++]; if (ch == '"') { buf.append("&quot;"); } else if (ch == '\'') { buf.append("\\'"); } else if (ch == '&') { buf.append("&amp;"); } else if (ch == '<') { buf.append("&lt;"); } else if (ch == '>') { buf.append("&gt;"); } else if (ch == '\n') { buf.append("<br>"); } else { buf.append(ch); } } return buf.toString(); } /** * 字符串处理方法:转换html标签为可显示 * * @param s * @return */ public static String fromHtml(String s) { return StringReplace(s, "\\'", "\'"); } /** * 字符串处理方法:转换html标签为可显示 * * @param s * @return */ public static String fromHtmlToEdit(String s) { return StringReplace(StringReplace(s, "<br>", ""), "\\'", "\'"); } /** * 数组处理方法:察看某数组对象是否有s对象 * * @param a * @param s * @return */ public static boolean contains(Object a[], Object s) { if (a == null || s == null) { return false; } for (int i = 0; i < a.length; i++) { if (a[i] != null && a[i].equals(s)) { return true; } } return false; } /** * 字符串处理方法:根据起始结束标记截断String c * * @param c * @param begin_tag * @param end_tag * @return */ public static String extract(String c, String begin_tag, String end_tag) { int begin = begin_tag == null ? 0 : c.indexOf(begin_tag); int len = begin_tag == null ? 0 : begin_tag.length(); int end = end_tag == null ? c.length() : c .indexOf(end_tag, begin + len); if (begin == -1) { begin = 0; len = 0; } if (end == -1) { end = c.length(); } return c.substring(begin + len, end); } /** * 字符串处理:截取s1中的对象 * * @param s1 * @param s2 * @return */ public static String remove(String s1, String s2) { int i = s1.indexOf(s2); int l = s2.length(); if (i != -1) { return s1.substring(0, i) + s1.substring(i + l); } return s1; } /** * 字符串处理: * * @param s * @param c1 * @param c2 * @return */ public static String replaceChar(String s, char c1, char c2) { if (s == null) { return s; } char buf[] = s.toCharArray(); for (int i = 0; i < buf.length; i++) { if (buf[i] == c1) { buf[i] = c2; } } return String.valueOf(buf); } /** * 校验方法:是否含有@ * * @param s * @return */ public static boolean isEmail(String s) { int pos = 0; pos = s.indexOf("@"); if (pos == -1) { return false; } return true; } /** * 数组处理:将对象数组中的第i个对象与第j个对象对调 * * @param a * @param i * @param j */ public static void swap(Object a[], int i, int j) { Object t = a[i]; a[i] = a[j]; a[j] = t; } /** * 字符串处理方法: * * @param sou * @param s1 * @param s2 * @return */ public static String StringReplace(String sou, String s1, String s2) { int idx = sou.indexOf(s1); if (idx < 0) { return sou; } return StringReplace(sou.substring(0, idx) + s2 + sou.substring(idx + s1.length()), s1, s2); } /** * * @param sentence * @param oStart * @param oEnd * @param rWord * @param matchCase * @return */ public static String replaceRange(String sentence, String oStart, String oEnd, String rWord, boolean matchCase) { int sIndex = -1; int eIndex = -1; if (matchCase) { sIndex = sentence.indexOf(oStart); } else { sIndex = sentence.toLowerCase().indexOf(oStart.toLowerCase()); } if (sIndex == -1 || sentence == null || oStart == null || oEnd == null || rWord == null) { return sentence; } else { if (matchCase) { eIndex = sentence.indexOf(oEnd, sIndex); } else { eIndex = sentence.toLowerCase().indexOf(oEnd.toLowerCase(), sIndex); } String newStr = null; if (eIndex > -1) { newStr = sentence.substring(0, sIndex) + rWord + sentence.substring(eIndex + oEnd.length()); } else { newStr = sentence.substring(0, sIndex) + rWord + sentence.substring(sIndex + oStart.length()); } return replaceRange(newStr, oStart, oEnd, rWord, matchCase); } } /** * 类型转换:字符串转换为整形 * * @param v * @return */ public static int getIntValue(String v) { return getIntValue(v, -1); } /** * 类型转换:字符串转换为整形如果例外则返回预给值def * * @param v * @return */ public static int getIntValue(String v, int def) { try { return Integer.parseInt(v); } catch (Exception ex) { return def; } } /** * 类型转换:将给出的字符串v转换成浮点值返回,如果例外则返回预给值-1 * * @param v * @return */ public static float getFloatValue(String v) { return getFloatValue(v, -1); } /** * 类型转换:将给出的字符串v转换成浮点值返回,如果例外则返回预给值def * * @param v * @return */ public static float getFloatValue(String v, float def) { try { return Float.parseFloat(v); } catch (Exception ex) { return def; } } /** * * @param in * @return */ public static String makeNavbar(int current, int total, int per_page, String action) { int begin = 1; int border = 100; String prevLink = ""; String nextLink = ""; String rslt = ""; String strNext = "Next"; String strPrev = "Previous"; String strStart = ""; if (action.indexOf("?") < 0) { strStart = "?start="; } else { strStart = "&start="; } Hashtable ht = new Hashtable(); ht.put("action", action); begin = current + 1; int j = 0; while (j * border < begin) { j++; } begin = (((j - 1) * border) + 1); if (current + 1 > border) { prevLink = "<a href=" + action + strStart + Math.max(1, begin - border) + ">[ " + strPrev + " " + border + " ]</a>&nbsp;"; } while (begin < (j * border) && begin < total + 1) { ht.put("from", String.valueOf(begin)); ht.put("to", String.valueOf(Math.min(total, begin + per_page - 1))); if (current + 1 >= begin && current + 1 <= begin + per_page - 1) { rslt += fillValuesToString("[$from - $to]&nbsp;", ht); } else { rslt += fillValuesToString("<a href='$action" + strStart + "$from'>[$from - $to]</a>&nbsp;", ht); } begin += per_page; } if (total >= begin) { nextLink = "&nbsp;<a href=" + action + strStart + begin + ">[ " + strNext + " " + Math.min(border, total - begin + 1) + " ]</a>"; } return prevLink + rslt + nextLink; } /** * * @param current * @param total * @param per_page * @param action * @return */ public static String makeNavbarReverse(int current, int total, int per_page, String action) { int border = 100; String prevLink = ""; String nextLink = ""; String rslt = ""; int begin = current + 1; Hashtable ht = new Hashtable(); ht.put("action", action); String strNext = "Next"; String strPrev = "Previous"; String strStart = ""; if (action.indexOf("?") < 0) { strStart = "?start="; } else { strStart = "&start="; } int j = 0; while (j * border < begin) { j++; } begin = ((j - 1) * border) + 1; if (begin > border) { prevLink = "<a href=" + action + strStart + Math.max(1, begin - border) + ">[ " + strNext + " " + border + " ]</a>&nbsp;"; } current++; for (int i = 0; i < per_page && begin <= total; i++) { ht.put("from", String.valueOf(total - begin + 1)); ht.put("to", String.valueOf(Math.max(1, total - begin + 1 + 1 - per_page))); if (current >= begin && current <= begin + per_page - 1) { rslt += fillValuesToString("[$from - $to]&nbsp;", ht); } else { rslt += fillValuesToString( "<a href='$action" + strStart + String.valueOf(begin) + "'>[ $from - $to ]</a>&nbsp;", ht); } begin += per_page; } if (total > begin) { nextLink = "&nbsp;<a href=" + action + strStart + String.valueOf(begin) + ">[ " + strPrev + " " + Math.min(total - begin + 1, 100) + " ]</a>"; } return prevLink + rslt + nextLink; } /** * 字符串处理方法: * * @param str * @param ht * @return */ public static String fillValuesToString(String str, Hashtable ht) { char VARIABLE_PREFIX = '$'; char TERMINATOR = '\\'; if (str == null || str.length() == 0 || ht == null) { return str; } char s[] = str.toCharArray(); char ch, i = 0; String vname; StringBuffer buf = new StringBuffer(); ch = s[i]; while (true) { if (ch == VARIABLE_PREFIX) { vname = ""; if (++i < s.length) { ch = s[i]; } else { break; } while (true) { if (ch != '_' && ch != '-' && !Character.isLetterOrDigit(ch)) { break; } vname += ch; if (++i < s.length) { ch = s[i]; } else { break; } } if (vname.length() != 0) { String vval = (String) ht.get(vname); if (vval != null) { buf.append(vval); } } if (vname.length() != 0 && ch == VARIABLE_PREFIX) { continue; } if (ch == TERMINATOR) { if (++i < s.length) { ch = s[i]; } else { break; } continue; } if (i >= s.length) { break; } } buf.append(ch); if (++i < s.length) { ch = s[i]; } else { break; } } return buf.toString(); } public static char getSeparator() { return 2; } /** * 时间处理方法: * * @param time1 * @param time2 * @return */ public static String addTime(String time1, String time2) { if (time1.equals("") || time2.equals("")) { return "00:00"; } else { ArrayList timearray1 = TokenizerString(time1, ":"); ArrayList timearray2 = TokenizerString(time2, ":"); int hour1; int hour2; int min1; int min2; int hour; int min; hour1 = getIntValue((String) timearray1.get(0)); min1 = getIntValue((String) timearray1.get(1)); hour2 = getIntValue((String) timearray2.get(0)); min2 = getIntValue((String) timearray2.get(1)); if ((min1 + min2) >= 60) { hour = hour1 + hour2 + 1; min = min1 + min2 - 60; } else { hour = hour1 + hour2; min = min1 + min2; } if (hour < 10) { if (min < 10) { return "0" + hour + ":" + "0" + min; } else { return "0" + hour + ":" + "" + min; } } else { if (min < 10) { return "" + hour + ":" + "0" + min; } else { return "" + hour + ":" + "" + min; } } } } /** * 时间处理方法: * * @param time1 * @param time2 * @return */ public static String subTime(String time1, String time2) { if (time1.equals("") || time2.equals("")) { return "00:00"; } else { ArrayList timearray1 = TokenizerString(time1, ":"); ArrayList timearray2 = TokenizerString(time2, ":"); int hour1; int hour2; int min1; int min2; int hour; int min; hour1 = getIntValue((String) timearray1.get(0)); min1 = getIntValue((String) timearray1.get(1)); hour2 = getIntValue((String) timearray2.get(0)); min2 = getIntValue((String) timearray2.get(1)); if ((min1 - min2) < 0) { hour = hour1 - hour2 - 1; min = min1 - min2 + 60; } else { hour = hour1 - hour2; min = min1 - min2; } if (hour < 10) { if (min < 10) { return "0" + hour + ":" + "0" + min; } else { return "0" + hour + ":" + "" + min; } } else { if (min < 10) { return "" + hour + ":" + "0" + min; } else { return "" + hour + ":" + "" + min; } } } } /** * 获得每dimlen位的逗号 * * @param str * @param dimlen * @return */ public static String getFloatStr(String str, int dimlen) { int dicimalindex = str.indexOf("."); String decimalstr = ""; if (dicimalindex != -1) { decimalstr = extract(str, ".", null); } String intstr = extract(str, null, "."); if (intstr.length() < (dimlen + 1)) { return str; } String beginstr = ""; int thebeginlen = intstr.length() % dimlen; beginstr = intstr.substring(0, thebeginlen); intstr = intstr.substring(thebeginlen); int intstrcount = intstr.length() / dimlen; for (int i = 0; i < intstrcount; i++) { if (beginstr.equals("") || beginstr.equals("-")) { beginstr += intstr.substring(0, dimlen); intstr = intstr.substring(dimlen); } else { beginstr += "," + intstr.substring(0, dimlen); intstr = intstr.substring(dimlen); } } if (dicimalindex != -1) { return beginstr + "." + decimalstr; } else { return beginstr; } } /** * 将字符串日期转成日历型 * * @param strDate * @return */ public static GregorianCalendar String2Cal(String strDate) { GregorianCalendar calDate = new GregorianCalendar(); strDate = StaticMethod.null2String(strDate).replaceAll("\\.0", ""); Vector vecDate = StaticMethod.getVector(strDate, " "); if (vecDate.size() > 0 && vecDate.size() < 3) { if (vecDate.size() == 1) { Vector vecData = StaticMethod.getVector(String.valueOf(vecDate .elementAt(0)), "-"); if (vecData.size() == 3) { int intYear = Integer.parseInt(String.valueOf(vecData .elementAt(0))); int intMonth = Integer.parseInt(String.valueOf(vecData .elementAt(1))); int intDay = Integer.parseInt(String.valueOf(vecData .elementAt(2))); calDate.set(Calendar.YEAR, intYear); calDate.set(Calendar.MONTH, intMonth - 1); calDate.set(Calendar.DATE, intDay); } calDate.set(Calendar.HOUR_OF_DAY, 0); calDate.set(Calendar.MINUTE, 0); calDate.set(Calendar.SECOND, 0); } if (vecDate.size() == 2) { Vector vecData = StaticMethod.getVector(String.valueOf(vecDate .elementAt(0)), "-"); Vector vecTime = StaticMethod.getVector(String.valueOf(vecDate .elementAt(1)), ":"); if (vecData.size() == 3) { int intYear = Integer.parseInt(String.valueOf(vecData .elementAt(0))); int intMonth = Integer.parseInt(String.valueOf(vecData .elementAt(1))); int intDay = Integer.parseInt(String.valueOf(vecData .elementAt(2))); calDate.set(Calendar.YEAR, intYear); calDate.set(Calendar.MONTH, intMonth - 1); calDate.set(Calendar.DATE, intDay); } if (vecTime.size() == 3) { int intHour = Integer.parseInt(String.valueOf(vecTime .elementAt(0))); int intMinute = Integer.parseInt(String.valueOf(vecTime .elementAt(1))); int intSecond = Integer.parseInt(String.valueOf(vecTime .elementAt(2))); calDate.set(Calendar.HOUR_OF_DAY, intHour); calDate.set(Calendar.MINUTE, intMinute); calDate.set(Calendar.SECOND, intSecond); } } } return calDate; } /** * 将日历型转成日期字符串 * * @param calDate * @return */ public static String Cal2String(GregorianCalendar calDate) { String strDate = ""; strDate = String.valueOf(calDate.get(Calendar.YEAR)); strDate = strDate + "-" + String.valueOf(calDate.get(Calendar.MONTH) + 1); strDate = strDate + "-" + String.valueOf(calDate.get(Calendar.DATE)); strDate = strDate + " " + String.valueOf(calDate.get(Calendar.HOUR_OF_DAY)); strDate = strDate + ":" + String.valueOf(calDate.get(Calendar.MINUTE)); strDate = strDate + ":" + String.valueOf(calDate.get(Calendar.SECOND)); return strDate; } /** * @see 得到时间字符串 * @see 例如:StaticMethod.getDateString(-1),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串 例如:返回'2003-8-10' */ public static String getDateString(int disday) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); String _yystr = "", _mmstr = "", _ddstr = ""; int _yy = c.get(Calendar.YEAR); _yystr = _yy + ""; int _mm = c.get(Calendar.MONTH) + 1; _mmstr = _mm + ""; if (_mm < 10) { _mmstr = "0" + _mm; } int _dd = c.get(Calendar.DATE); _ddstr = _dd + ""; if (_dd < 10) { _ddstr = "0" + _dd; } ls_display = "'" + _yystr + "-" + _mmstr + "-" + _ddstr + "'"; return ls_display; } /** * @see 得到时间字符串 * @see 例如:StaticMethod.getDateString(-1),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串 例如:返回'2003-8-10' */ public static String getDateString(String strDateLimit, int disday) { Calendar c = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date thisdate = dateFormat.parse(strDateLimit); c.setTime(thisdate); } catch (Exception e) { } c.set(Calendar.DATE, c.get(Calendar.DATE) + disday); String ls_display = dateFormat.format(c.getTime()).toString(); return ls_display; } /** * @see 得到时间字符串 * @see 例如:StaticMethod.getDateString(-1),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串,例如:返回'2003-8-10 00:00:00' */ public static String getTimeString(int disday) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); int _yy = c.get(Calendar.YEAR); int _mm = c.get(Calendar.MONTH) + 1; int _dd = c.get(Calendar.DATE); ls_display = "'" + _yy + "-" + _mm + "-" + _dd + " 00:00:00'"; return ls_display; } /** * @see 得到时间字符串 * @see 例如:StaticMethod.getDateString(-1),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串,例如:返回2003-8-10 00:00:00 */ public static String getCurrentTimeString(int disday) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); int _yy = c.get(Calendar.YEAR); int _mm = c.get(Calendar.MONTH) + 1; int _dd = c.get(Calendar.DATE); ls_display = _yy + "-" + _mm + "-" + _dd + " 00:00:00"; return ls_display; } /** * @see 得到某一天开始的时间字符串 * @see 例如:StaticMethod.getDateString(-1),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串,例如:返回'2003-8-10 00:00:00' */ public static String getTimeBeginString(int disday) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); int _yy = c.get(Calendar.YEAR); int _mm = c.get(Calendar.MONTH) + 1; int _dd = c.get(Calendar.DATE); ls_display = _yy + "-" + _mm + "-" + _dd + " 00:00:00"; return ls_display; } /** * @see 得到某一天结束的时间字符串 * @see 例如:StaticMethod.getDateString(-1),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串,例如:返回'2003-8-10 00:00:00' */ public static String getTimeEndString(int disday) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); int _yy = c.get(Calendar.YEAR); int _mm = c.get(Calendar.MONTH) + 1; int _dd = c.get(Calendar.DATE); ls_display = _yy + "-" + _mm + "-" + _dd + " 23:59:59"; return ls_display; } /** * @see 得到时间字符串 * @see 例如:StaticMethod.getTimeString(-1,16),可以返回昨天的时间字符串 * @param disday * int 和当前距离的天数 * @return String para的标准时间格式的串,例如:返回'2003-8-10 16:00:00' */ public static String getTimeString(int disday, int hour) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); String _hourstr = ""; int _yy = c.get(Calendar.YEAR); int _mm = c.get(Calendar.MONTH) + 1; int _dd = c.get(Calendar.DATE); if (hour < 10) { _hourstr = "0" + hour; } else { _hourstr = "" + hour; } ls_display = "'" + _yy + "-" + _mm + "-" + _dd + " " + _hourstr + ":00:00'"; return ls_display; } /** * 时间处理方法 * * @param disday * @return */ public static Timestamp getTimestamp(int disday) { Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; return new Timestamp(realtime); } /** * 时间串分割函数,将时间串分割成年、月、日、小时、分、秒。 * * @param time * @return */ public static String[] subTimeString(String time) { String[] timeString = time.split(" "); String[] time1 = timeString[0].split("-"); String[] time2 = timeString[1].split(":"); int length = time1.length + time2.length; String[] Time = new String[length]; for (int i = 0; i < time1.length; i++) { Time[i] = time1[i]; } for (int j = 0; j < time2.length; j++) { Time[time1.length + j] = time2[j]; } return Time; } /** * 时间处理方法 * * @param str * @return */ public static Timestamp getTimestamp(String str) { Timestamp ret = null; try { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); Date date = dateFormat.parse(str); long datelong = date.getTime(); ret = new Timestamp(datelong); } catch (Exception e) { } return ret; } /** * 时间处理方法 * * @param str * @return */ public static Timestamp getTimestampSimple(String str) { Timestamp ret = null; try { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd"); Date date = dateFormat.parse(str); long datelong = date.getTime(); ret = new Timestamp(datelong); } catch (Exception e) { } return ret; } /** * 时间处理方法 * * @param str * @return */ public static String date2String(Date date) { String ret = ""; try { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); ret = dateFormat.format(date); } catch (Exception e) { } return ret; } public static Timestamp getTimestamp() { return getTimestamp(0); } public static String getTimestampString(Timestamp sta) { String ret = ""; try { String str = sta.toString(); ret = str.substring(0, str.lastIndexOf('.')); } catch (Exception e) { ret = ""; } return ret; } /** * @see 由运维系统发送工单确认信息,到客服系统 * @param operateId * KF工单流水号 * @param dealId * KF工单派单号 * @param userId * EOMS处理人 * @param dealDept * EOMS处理部门 根据编码表获取KF 的部门ID * @param contact * EOMS联系方式 * @return XML格式字符串 <?xml version="1.0" encoding="UTF-8"?> * <SOAP-ENV:Envelope * xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" * xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:xsd="http://www.w3.org/2001/XMLSchema" * xmlns:ns="urn:KFWebService"> <SOAP-ENV:Body * encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> * <ns:CONFIRM-CPLT><CONFIRM-CPLT><FLOW-NO></FLOW-NO> <DEAL-ID> * </DEAL-ID> <PROCESS-UNIT></PROCESS-UNIT> <PROCESS-NAME> * </PROCESS-NAME> <CONTACTOR-TEL></CONTACTOR-TEL> </CONFIRM-CPLT> * </ns:CONFIRM-CPLT> </SOAP-ENV:Body> </SOAP-ENV:Envelope> */ public static String confirmMSGEOMS21860(String operateId, String dealId, String userId, int dealDept, String contact) { String xmlComfirmString = ""; xmlComfirmString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; xmlComfirmString = xmlComfirmString + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""; xmlComfirmString = xmlComfirmString + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\""; xmlComfirmString = xmlComfirmString + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; xmlComfirmString = xmlComfirmString + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns=\"urn:KFWebService\">"; xmlComfirmString = xmlComfirmString + "<SOAP-ENV:Body encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\">"; xmlComfirmString = xmlComfirmString + "<ns:CONFIRM-CPLT>"; xmlComfirmString = xmlComfirmString + "<CONFIRM-CPLT>"; xmlComfirmString = xmlComfirmString + "<FLOW-NO>" + operateId.trim() + "</FLOW-NO>"; xmlComfirmString = xmlComfirmString + "<DEAL-ID>" + dealId.trim() + "</DEAL-ID>"; xmlComfirmString = xmlComfirmString + "<PROCESS-UNIT>" + dealDept + "</PROCESS-UNIT>"; xmlComfirmString = xmlComfirmString + "<PROCESS-NAME>" + userId + "</PROCESS-NAME>"; xmlComfirmString = xmlComfirmString + "<CONTACTOR-TEL>" + contact.trim() + "</CONTACTOR-TEL>"; xmlComfirmString = xmlComfirmString + "</CONFIRM-CPLT>"; xmlComfirmString = xmlComfirmString + "</ns:CONFIRM-CPLT>"; xmlComfirmString = xmlComfirmString + "</SOAP-ENV:Body>"; xmlComfirmString = xmlComfirmString + "</SOAP-ENV:Envelope>"; return xmlComfirmString; } /** * @see 由运维系统发送工单回复信息,到客服系统 * @param operateId * KF工单流水号 * @param dealID * KF 派单号 * @param userId * 处理人 * @param dealDept * 处理部门更具编码表获取KF 的部门ID * @param proTime * 处理时间 * @param finallyResult * 最终处理结果。如果是退回,可以为空。 * @param rejectCause * 故障原因可以为空 * @param Status * 对应运维EOMS工单主要有两个回复操作,处理结束(status = 0)和处理未结束(status=1) * @param areaCode * 地区代码 * @return XML格式化字符串 */ public static String returnMSGEOMS21860(String operateId, String dealId, String userId, int dealDept, String proTime, String finallyResult, String rejectCause, int status, int areaCode) { String xmlReturnString = ""; xmlReturnString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; xmlReturnString = xmlReturnString + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""; xmlReturnString = xmlReturnString + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\""; xmlReturnString = xmlReturnString + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""; xmlReturnString = xmlReturnString + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:ns=\"urn:KFWebService\">"; xmlReturnString = xmlReturnString + "<SOAP-ENV:Body encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding\">"; xmlReturnString = xmlReturnString + "<ns:FILL-PRCS-RSLT>"; xmlReturnString = xmlReturnString + "<PRCS-RSLT>"; xmlReturnString = xmlReturnString + "<FLOW-NO>" + operateId.trim() + "</FLOW-NO>"; xmlReturnString = xmlReturnString + "<DEAL-ID>" + dealId.trim() + "</DEAL-ID>"; xmlReturnString = xmlReturnString + "<PROCESS-UNIT>" + dealDept + "</PROCESS-UNIT>"; xmlReturnString = xmlReturnString + "<PROCESS-NAME>" + userId.trim() + "</PROCESS-NAME>"; xmlReturnString = xmlReturnString + "<PROCESS-TIME>" + proTime.trim() + "</PROCESS-TIME>"; xmlReturnString = xmlReturnString + "<PROCESS-RESULT>" + finallyResult + "</PROCESS-RESULT>"; /* * if(status ==0) { xmlReturnString = xmlReturnString + " * <PROCESS-RESULT>"+finallyResult+" </PROCESS-RESULT>"; }else if(status == * 1) { xmlReturnString = xmlReturnString + " * <PROCESS-RESULT>"+rejectCause+" </PROCESS-RESULT>"; }else { * xmlReturnString = xmlReturnString + " <PROCESS-RESULT> * </PROCESS-RESULT>"; } */ xmlReturnString = xmlReturnString + "<AREA-CODE>" + areaCode + "</AREA-CODE>"; xmlReturnString = xmlReturnString + "<END-HANDLE-FLAG>" + status + "</END-HANDLE-FLAG>"; xmlReturnString = xmlReturnString + "</PRCS-RSLT>"; xmlReturnString = xmlReturnString + "</ns:FILL-PRCS-RSLT>"; xmlReturnString = xmlReturnString + "</SOAP-ENV:Body>"; xmlReturnString = xmlReturnString + "</SOAP-ENV:Envelope>"; return xmlReturnString; } /** * @see 得到当前时刻的时间字符串 * @return String para的标准时间格式的串,例如:返回'2003-08-09 16:00:00' */ public static String getLocalString() { java.util.Date currentDate = new java.util.Date(); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String date = dateFormat.format(currentDate); return date; } /** * 时间处理方法: * * @param day * @return */ public static String getLocalString(int day) { Calendar c = Calendar.getInstance(); c.add(Calendar.DATE, day); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String date = dateFormat.format(c.getTime()); return date; } /** * 时间处理方法 * * @param hour * @return */ public static String getLocalStringByHours(int hour) { Calendar c = Calendar.getInstance(); c.add(Calendar.HOUR, hour); java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String date = dateFormat.format(c.getTime()); return date; } /** * @see 根据参数str,得到标准的时间字符串 * @param str * @returnpara的标准时间格式的串,例如:返回'2003-08-09 16:00:00' */ public static String getLocalString(String str) { String time = ""; Vector temp = StaticMethod.getVector(str, " "); if (!temp.isEmpty()) { Vector first = StaticMethod.getVector(temp.get(0).toString(), "-"); Vector last = StaticMethod.getVector(temp.get(1).toString(), ":"); String year = first.get(0).toString(); ; String month = first.get(1).toString(); ; String day = first.get(2).toString(); String hour = last.get(0).toString(); String minute = last.get(1).toString(); String second = last.get(2).toString(); if (month.length() == 1) { month = "0" + month; } if (day.length() == 1) { day = "0" + day; } if (hour.length() == 1) { hour = "0" + hour; } if (minute.length() == 1) { minute = "0" + minute; } if (second.length() == 1) { second = "0" + second; } time = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; } return time; } /** * 时间转换方法 * * @param disday * @param hour * @return */ public static String getLocalString(int disday, int hour) { String ls_display = ""; Calendar c; c = Calendar.getInstance(); long realtime = c.getTimeInMillis(); realtime += 86400000 * disday; c.setTimeInMillis(realtime); String _mmstr = "", _ddstr = "", _hourstr = ""; int _yy = c.get(Calendar.YEAR); int _mm = c.get(Calendar.MONTH) + 1; _mmstr = _mm + ""; if (_mm < 10) { _mmstr = "0" + _mm; } int _dd = c.get(Calendar.DATE); _ddstr = _dd + ""; if (_dd < 10) { _ddstr = "0" + _dd; } if (hour < 10) { _hourstr = "0" + hour; } else { _hourstr = "" + hour; } ls_display = _yy + "-" + _mmstr + "-" + _ddstr + " " + _hourstr + ":00:00"; return ls_display; } /** * @see 转换时间方法:转换格式,如时间“2002-1-12”转换成字符串“020112” * @param DateStr * “2002-1-12” * @return “020112” */ public static String getYYMMDD() { return getYYMMDD(getCurrentDateTime()); } public static String getYYMMDD(String DateStr) { String YY, MM, DD; String ReturnDateStr; int s = DateStr.indexOf(" "); ReturnDateStr = DateStr.substring(0, s); Vector ss = getVector(ReturnDateStr, "-"); YY = ss.elementAt(0).toString(); YY = YY.substring(2, 4); MM = ss.elementAt(1).toString(); if (Integer.valueOf(MM).intValue() < 10) { MM = "0" + Integer.valueOf(MM).intValue(); } DD = ss.elementAt(2).toString(); if (Integer.valueOf(DD).intValue() < 10) { DD = "0" + Integer.valueOf(DD).intValue(); } ReturnDateStr = YY + MM + DD; return ReturnDateStr; } /** * 时间处理方法:返回日期格式:20051201 * * @param DateStr * @return */ public static String getYYYYMMDD(String DateStr) { String YY, MM, DD; String ReturnDateStr; int s = DateStr.indexOf(" "); ReturnDateStr = DateStr.substring(0, s); Vector ss = getVector(ReturnDateStr, "-"); YY = ss.elementAt(0).toString(); // YY = YY.substring(2, 4); MM = ss.elementAt(1).toString(); DD = ss.elementAt(2).toString(); ReturnDateStr = YY + MM + DD; return ReturnDateStr; } /** * @see 时间转换方法:根据传入的分钟数,得到转化后的天,小时和分钟值 * @param times * int * @return ArrayList 保存这些值的集合,0位置保存天,1位置保存小时,2位置保存分钟 */ public static ArrayList getDHMString(long times) { long day; long hour; long minute; ArrayList list = new ArrayList(); day = times / (24 * 60); if (day == 0) { hour = times / 60; minute = times - hour * 60; } else { hour = (times % (24 * 60)) / 60; minute = times - day * 24 * 60; if (hour != 0) { minute -= hour * 60; } } list.add(String.valueOf(day)); list.add(String.valueOf(hour)); list.add(String.valueOf(minute)); return list; } /** * * 时间转换方法:根据输入的格式(String _dtFormat)得到当前时间格式得到当前的系统时间 Add By ChengJiWu * * @param _dtFormat * @return */ public static String getCurrentDateTime(String _dtFormat) { String currentdatetime = ""; try { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat dtFormat = new SimpleDateFormat(_dtFormat); currentdatetime = dtFormat.format(date); } catch (Exception e) { logger.error("时间格式不正确"); } return currentdatetime; } /** * 时间转换方法:得到默认的时间格式为("yyyy-MM-dd HH:mm:ss")的当前时间 * * @return */ public static String getCurrentDateTime() { return getCurrentDateTime("yyyy-MM-dd HH:mm:ss"); } /** * @param strDate * 时间型的字符串 * @param _dtFormat * 形如"yyyy-MM-dd HH:mm:ss"的字符串 把 strDate 时间字符串 转换为 _dtFormat 格式 * @return */ public static String getDateTime(String strDate, String _dtFormat) { String strDateTime; Date tDate = null; if (null == strDate) { return getCurrentDateTime(); } SimpleDateFormat smpDateFormat = new SimpleDateFormat(_dtFormat); ParsePosition pos = new ParsePosition(0); tDate = smpDateFormat.parse(strDate, pos); // 标准格式的date类型时间 strDateTime = smpDateFormat.format(tDate); // 标准格式的String 类型时间 return strDateTime; } /** * @param strDate * 时间型的字符串 * @param _dtFormat * 形如"yyyy-MM-dd HH:mm:ss"的字符串 把 strDate 时间字符串 转换为 _dtFormat 格式 * @return */ public static String getDateTime(String strDate, SimpleDateFormat smpDateFormat) { String strDateTime; Date tDate = null; if (null == strDate) { return getCurrentDateTime(); } ParsePosition pos = new ParsePosition(0); tDate = smpDateFormat.parse(strDate, pos); // 标准格式的date类型时间 strDateTime = smpDateFormat.format(tDate); // 标准格式的String 类型时间 return strDateTime; } /** * * @param vec1 * @param vec2 * @return */ public static Vector unionAllVec(Vector vec1, Vector vec2) { boolean flag = false; int itemp = 0; for (int i = 0; i < vec2.size(); i++) { itemp = 0; flag = false; while ((itemp < vec1.size()) && (!flag)) { if (vec1.get(itemp).toString().equals(vec2.get(i).toString())) { flag = true; } else { itemp = itemp + 1; } } if (!flag) { vec1.add(vec2.get(i)); } } return vec1; } /** * @see 格式化字符串 * @param OriStr * 分割符号为“,”情况下,“,Str1,Str2,Str3” 或 “Str1,Str2,Str3,”或 * “,Str1,Str2,Str3,”等 * @param dim * 分割符号,如“,” * @return Str1,Str2,Str3 */ public static String right(String str, int i) { String sc = ""; if (!str.equals("")) { int strlength = str.length(); int priostrlength = (strlength - i); sc = str.substring(priostrlength, strlength); } return sc; } /** * @see 字符串处理方法 * * @param str * @param i * @return */ public static String left(String str, int i) { String sc = ""; if (!str.equals("")) { int priostrlength = (i); sc = str.substring(0, priostrlength); } return sc; } /** * @see 字符串处理方法 * * @param OriStr * @param dim * @return */ public static String getFormatStr(String OriStr, String dim) { // OriStr 不能为空; OriStr = null2String(OriStr, ""); if (OriStr == "") { OriStr = ""; } else { int dimLength = dim.length(); if (left(OriStr, dimLength).equals(dim)) { OriStr = right(OriStr, (OriStr.length() - dimLength)); } if (right(OriStr, dimLength).equals(dim)) { OriStr = left(OriStr, (OriStr.length() - dimLength)); } } return OriStr; } /** * @see 时间处理方法 * @return */ public static synchronized int getSingleId() { int ret = 0; Date date = new Date(); ret = new Long(date.getTime()).intValue(); if (ret < 0) ret = -ret; return ret; } /** * @see 时间处理方法:for applysheet 2005-09-27 add by chenyuanshu * * @see 将millonSecond转换成时:分:秒 * @param millonSecond * long * @return String */ public static String convert(long millonSecond) { int totalsecond = (int) millonSecond / 1000; int hour, min, sec; String minStr = "", hourStr = ""; /* * day=totalsecond /(60*60*24); dayStr=String.valueOf(day); */ hour = (totalsecond) / (60 * 60); hourStr = String.valueOf(hour); min = (totalsecond - hour * 60 * 60) / 60; minStr = String.valueOf(min); sec = totalsecond - min * 60 - hour * 60 * 60; if (min == 0) minStr = "00"; if (hour == 0) hourStr = "00"; return hourStr + ":" + minStr + ":" + sec; } /** * @see 计算步骤之间历时 * @throws Exception * 输入参数:如下所示: 参数名称 参数类型 参数说明 备注 historyTime String 历史步骤时间 * nowTime String 当前步骤时间 输出:步骤之间历时(单位小时) */ public static int getTimeIntervals(String historyTime, String nowTime) { String[] timeHistory = subTimeString(historyTime); String[] timeNow = subTimeString(nowTime); int year1 = StaticMethod.getIntValue(timeHistory[0]); int year2 = StaticMethod.getIntValue(timeNow[0]); int month1 = StaticMethod.getIntValue(timeHistory[1]); int month2 = StaticMethod.getIntValue(timeNow[1]); int day1 = StaticMethod.getIntValue(timeHistory[2]); int day2 = StaticMethod.getIntValue(timeNow[2]); int hour1 = StaticMethod.getIntValue(timeHistory[3]); int hour2 = StaticMethod.getIntValue(timeNow[3]); int min1 = StaticMethod.getIntValue(timeHistory[4]); int min2 = StaticMethod.getIntValue(timeNow[4]); int sec1 = StaticMethod.getIntValue(timeHistory[5]); int sec2 = StaticMethod.getIntValue(timeNow[5]); int flag, minutes; GregorianCalendar localCalendar = new GregorianCalendar(year1, month1, day1, hour1, min1, sec1); GregorianCalendar limitCalendar = new GregorianCalendar(year2, month2, day2, hour2, min2, sec2); Date localDate = localCalendar.getTime(); Date limitDate = limitCalendar.getTime(); flag = historyTime.compareTo(nowTime); if (flag <= 0) { long oddTime = limitDate.getTime() - localDate.getTime(); minutes = (int) (oddTime / (60 * 60 * 1000)); } else { long oddTime = localDate.getTime() - limitDate.getTime(); minutes = (int) (oddTime / (60 * 60 * 1000)); minutes = 0 - minutes; } return minutes; } /** * @see 计算步骤之间历时 * @throws Exception * 输入参数:如下所示: 参数名称 参数类型 参数说明 备注 historyTime String 历史步骤时间 * nowTime String 当前步骤时间 输出:步骤之间历时(单位分钟) */ public static int getTimeDistance(String historyTime, String nowTime) { String[] timeHistory = subTimeString(historyTime); String[] timeNow = subTimeString(nowTime); int year1 = StaticMethod.getIntValue(timeHistory[0]); int year2 = StaticMethod.getIntValue(timeNow[0]); int month1 = StaticMethod.getIntValue(timeHistory[1]); int month2 = StaticMethod.getIntValue(timeNow[1]); int day1 = StaticMethod.getIntValue(timeHistory[2]); int day2 = StaticMethod.getIntValue(timeNow[2]); int hour1 = StaticMethod.getIntValue(timeHistory[3]); int hour2 = StaticMethod.getIntValue(timeNow[3]); int min1 = StaticMethod.getIntValue(timeHistory[4]); int min2 = StaticMethod.getIntValue(timeNow[4]); int sec1 = StaticMethod.getIntValue(timeHistory[5]); int sec2 = StaticMethod.getIntValue(timeNow[5]); int flag, minutes; GregorianCalendar localCalendar = new GregorianCalendar(year1, month1, day1, hour1, min1, sec1); GregorianCalendar limitCalendar = new GregorianCalendar(year2, month2, day2, hour2, min2, sec2); Date localDate = localCalendar.getTime(); Date limitDate = limitCalendar.getTime(); flag = historyTime.compareTo(nowTime); if (flag <= 0) { long oddTime = limitDate.getTime() - localDate.getTime(); minutes = (int) (oddTime / (60 * 1000)); } else { long oddTime = localDate.getTime() - limitDate.getTime(); minutes = (int) (oddTime / (60 * 1000)); minutes = 0 - minutes; } return minutes; } public static String calcHMS(long timeInSeconds) { long hours = 0; long minutes = 0; long seconds = 0; try { hours = timeInSeconds / 3600; timeInSeconds = timeInSeconds - (hours * 3600); minutes = timeInSeconds / 60; timeInSeconds = timeInSeconds - (minutes * 60); seconds = timeInSeconds; } catch (Exception e) { e.printStackTrace(); } return hours + "小时 " + minutes + "分钟 " + seconds + "秒"; } /** * @see 转换时间的方法: * @param timeInSeconds * @param time2 * @return */ public static String calcHMS(long timeInSeconds, long time2) { long hours = 0; long minutes = 0; long seconds = 0; String ret = ""; try { timeInSeconds = timeInSeconds / time2; hours = timeInSeconds / 3600; timeInSeconds = timeInSeconds - (hours * 3600); minutes = timeInSeconds / 60; timeInSeconds = timeInSeconds - (minutes * 60); seconds = timeInSeconds; ret = hours + "小时 " + minutes + "分钟 " + seconds + "秒"; } catch (Exception e) { ret = "0"; e.printStackTrace(); } return ret; } /** * @see 转换时间方法 * @param year * @param month * @return */ public static int getMonthLastDay(int year, int month) { if (month == 2) { if (year % 4 == 0) return 29; else return 28; } else if (month == 4 || month == 6 || month == 9 || month == 11) return 30; else return 31; } /** * @see 获取当前时间(Date类型) * @author qinmin * @return */ public static Date getLocalTime() { Calendar cal = Calendar.getInstance(); Date date = cal.getTime(); return date; } /** * 字符类型转换函数(String->long) * * @author qinmin * @param str * @return */ public static long getLongValue(String str) { long i = 0; try { i = Long.parseLong(str); } catch (Exception e) { i = 0; } return i; } /** * 给对象的一个String型的属性赋值 * * @author xqz * * @param obj * @param attributeName * 属性名 * @param value * @return */ public static Object invokeStringMethod(Object obj, String attributeName, String value) throws Exception { try { String setMethod = "set" + StaticMethod.firstToUpperCase(attributeName); Method setterMethod = obj.getClass().getMethod(setMethod, new Class[] { String.class }); return setterMethod.invoke(obj, new Object[] { value }); } catch (Exception e) { throw e; } } /** * list转换为vector * * @param list * java.util.list * @return 返回 java.util.vector */ public static Vector list2vector(List list) { Vector vector = new Vector(); if (null != list && !list.isEmpty()) { for (Iterator it = list.iterator(); it.hasNext();) { vector.add(it.next()); } } return vector; } /** * 得到当前时间 * * @return */ public static String getOperDay() { String strday = ""; Calendar currentCalendars = Calendar.getInstance(); String years = String.valueOf(currentCalendars.get(Calendar.YEAR)); String months = String .valueOf(currentCalendars.get(Calendar.MONTH) + 1); String days = String.valueOf(currentCalendars .get(Calendar.DAY_OF_MONTH)); String hours = String.valueOf(currentCalendars .get(Calendar.HOUR_OF_DAY)); String mm = String.valueOf(currentCalendars.get(Calendar.MINUTE)); String ss = String.valueOf(currentCalendars.get(Calendar.SECOND)); strday = years + "-" + months + "-" + days + " " + hours + ":" + mm + ":" + ss; return strday; } public static int diffDate(java.util.Date date, java.util.Date date1) { return (int) ((getMillis(date) - getMillis(date1)) / (24 * 3600 * 1000)); } public static int diffDateToHour(Date date, Date date1) { return (int) ((getMillis(date) - getMillis(date1)) / (1000 * 60 * 60)); } public static long getMillis(java.util.Date date) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTime(date); return c.getTimeInMillis(); } /** * 删除尾部空格 * * @param str * 字符串 * @param removedStr * 要删除的尾部字符串 * @return */ public static String removeLastStr(String str, String removedStr) { String result = null; if (str.endsWith(removedStr)) { result = str.substring(0, str.length() - removedStr.length()); } return result; } public static int getByMonthToNum(String year, String month) throws SQLException { int num = 0; int m = Integer.parseInt(month); int y = Integer.parseInt(year); switch (m) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: num = 31; break; case 2: if (y % 4 == 0) { num = 29; } else { num = 28; } break; case 4: case 6: case 9: case 11: num = 30; break; } return num; } /** * 时间处理方法 * * @param str * @return */ public static String getNoZero(String str) { String time = ""; try { String[] time_ = str.split("-"); String month = time_[1]; if (month.substring(0, 1).equals("0")) month = month.substring(1, 2); String day = time_[2]; if (day.substring(0, 1).equals("0")) day = day.substring(1, 2); time = time_[0] + "-" + month + "-" + day; } catch (Exception e) { e.printStackTrace(); } return time; } /** * 根据时间字符串(yyyy-mm-dd hh:mm:ss) 加上一定的分钟数,返回一个加和后的时间字符串 * add by gongyfueng for duty * @param str 时间字符串, int minute * @return str */ public static String getDateForMinute (String str ,int minute){ String time = ""; try{ GregorianCalendar cal = String2Cal(str); cal.add(cal.MINUTE , minute); time = String.valueOf(cal.get(cal.YEAR)); time = time + "-" + String.valueOf(cal.get(cal.MONTH) + 1); time = time + "-" + String.valueOf(cal.get(cal.DATE)); time = time + " " + String.valueOf(cal.get(cal.HOUR_OF_DAY)); time = time + ":" + String.valueOf(cal.get(cal.MINUTE)); time = time + ":" + String.valueOf(cal.get(cal.SECOND)); System.out.println(time); }catch (Exception e){ e.printStackTrace(); } return time; } public static void main(String[] args){ System.out.println(StaticMethod.getLocalString()); System.out.println(StaticMethod.getLocalString(0)); System.out.println(StaticMethod.getLocalString(-1)); System.out.println(StaticMethod.getLocalString(1)); } public static String file2stream(String url){ File file=new File(url); String back=""; try { FileInputStream in=new FileInputStream(file); byte buffer[]=new byte[1024]; in.read(buffer); back=buffer.toString(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return back; } /** * 时间处理方法 * * @param str * @return */ public static String date2Str(Date date) { String ret = ""; try { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); ret = dateFormat.format(date); } catch (Exception e) { try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); ret = dateFormat.format(date); } catch (Exception ex) { } return ret; } return ret; } }