text
stringlengths
10
2.72M
package view.sentences; import java.awt.GridBagConstraints; import java.lang.reflect.Parameter; import java.util.List; import model.Sentences; import model.SentencesManager; import view.DefaultGridPanel; import view.StyleParameters; import view.customized_widgets.CustomizedLabel; import view.customized_widgets.CustomizedTextPane; import javax.swing.*; import javax.swing.text.Style; public class SentencesEndPanel extends DefaultGridPanel { private Sentences sentences; private CustomizedLabel sentenceLabel; private CustomizedLabel knownRulesLabel; private CustomizedLabel rulesToReviewLabel; private CustomizedTextPane knownRulesContentLabel; private CustomizedTextPane rulesToReviewContentLabel; private SentencesManager sentencesManager; public SentencesEndPanel(Sentences sentences, SentencesManager sentencesManager) { super(); this.sentences = sentences; this.sentencesManager = sentencesManager; sentenceLabel = new CustomizedLabel(""); sentenceLabel.setBorder(BorderFactory.createLineBorder(StyleParameters.defaultBackgroundColor, 20)); knownRulesLabel = new CustomizedLabel("<html><center>Known rules</center></html>"); rulesToReviewLabel = new CustomizedLabel("<html><center>Rules to review</center></html>"); knownRulesContentLabel = new CustomizedTextPane(); knownRulesContentLabel.setFont(StyleParameters.defaultNormalFont); rulesToReviewContentLabel = new CustomizedTextPane(); rulesToReviewContentLabel.setFont(StyleParameters.defaultNormalFont); addComponent(sentenceLabel, 0, 0, 2, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); addComponent(knownRulesLabel, 0, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); addComponent(rulesToReviewLabel, 1, 1, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); addComponent(knownRulesContentLabel, 0, 2, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); addComponent(rulesToReviewContentLabel, 1, 2, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE); } public void updateScore() { sentencesManager.addScore(sentences.getPackageName(), sentences.getScore() * 100 / sentences.getSentencesCount()); sentenceLabel.setText("<html><center>You have finished !<br><br>You score : " + (sentences.getScore() * 100 / sentences.getSentencesCount()) + "%<br>Best score : " + (int)sentencesManager.getBestScore(sentences.getPackageName()) + " %</center></html>"); List<String> knownRules = sentences.getRulesNames(sentencesManager, true); List<String> rulesToReview = sentences.getRulesNames(sentencesManager, false); String knownRulesRender = ""; String rulesToReviewRender = ""; for (String rule : knownRules) if (!rulesToReview.contains(rule)) knownRulesRender += rule + "\n"; for (String rule : rulesToReview) rulesToReviewRender += rule + "\n"; System.out.println(); knownRulesContentLabel.setText(knownRulesRender); rulesToReviewContentLabel.setText(rulesToReviewRender); } }
package p0400; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JCheckBox; import javax.swing.JPanel; public class P0405 extends JFrame implements ActionListener { private P0405CP pnlShape; private JCheckBox cbxFilled; private JCheckBox cbxSymetric; private JCheckBox cbxRounded; /** * @param args */ public static void main(String[] args) { P0405 f = new P0405(); f.setVisible(true); } public P0405() { super("P0405"); initGUI(); } private void initGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); pnlShape = new P0405CP(); cbxFilled = new JCheckBox("filled"); cbxSymetric = new JCheckBox("symetric"); cbxRounded = new JCheckBox("rounded"); JPanel pnlCheckboxes = new JPanel(); pnlCheckboxes.add(cbxFilled); pnlCheckboxes.add(cbxSymetric); pnlCheckboxes.add(cbxRounded); cbxFilled.addActionListener(this); cbxSymetric.addActionListener(this); cbxRounded.addActionListener(this); getContentPane().add(pnlCheckboxes, BorderLayout.SOUTH); getContentPane().add(pnlShape); setSize(600, 400); } @Override public void actionPerformed(ActionEvent e) { pnlShape.changeShape(cbxFilled.isSelected(), cbxSymetric.isSelected(), cbxRounded.isSelected()); } }
package net.tecgurus.persistence.dao.impl; import net.tecgurus.exception.TGPersistenceException; import net.tecgurus.persistence.dao.GenericDAO; import org.hibernate.SessionFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.Serializable; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; /** * Created by Amaro on 10/08/2017. */ public abstract class GenericDAOImpl<T, PK extends Serializable> implements GenericDAO<T, PK> { @Autowired private SessionFactory sessionFactory; private final static Logger log = LoggerFactory.getLogger(GenericDAOImpl.class); @SuppressWarnings("unchecked") public List<T> getAll() throws TGPersistenceException { List<T> entities = new ArrayList<T>(); try{ entities = getSessionFactory().getCurrentSession().createCriteria(this.getPersistentClass()).list(); }catch(Exception e){ log.error(e.getMessage(), e); } return entities; } @SuppressWarnings("unchecked") public T findByPK(PK id) throws TGPersistenceException{ try{ return (T) getSessionFactory().getCurrentSession().get(this.getPersistentClass(), id); }catch(Exception e){ throw new TGPersistenceException("Excepción en BD", e); } } public void update(T object) throws TGPersistenceException{ try{ getSessionFactory().getCurrentSession().update(object); }catch(Exception e){ throw new TGPersistenceException("Excepción en BD", e); } } public void remove(T object) throws TGPersistenceException{ try{ getSessionFactory().getCurrentSession().delete(object); log.debug("Se ejecuto el borrado del objeto"); }catch(Exception e){ log.debug("Cayo en exception al borrar el objeto", e); throw new TGPersistenceException("Excepción en BD", e); } } @SuppressWarnings("unchecked") public PK save(T object) throws TGPersistenceException{ try{ return (PK) getSessionFactory().getCurrentSession().save(object); }catch(Exception e){ throw new TGPersistenceException("Excepción en BD", e); } } public void saveOrUpdate(T object) throws TGPersistenceException{ try{ getSessionFactory().getCurrentSession().saveOrUpdate(object); }catch(Exception e){ throw new TGPersistenceException("Excepción en BD", e); } } public boolean exists(PK paramPK) throws TGPersistenceException{ try{ Object entity = this.findByPK(paramPK); return (entity != null); }catch(Exception e){ throw new TGPersistenceException("Excepción en BD", e); } } /** * Método para obtener la clase que persiste el DAO * * @return <T> clase a persistir. */ @SuppressWarnings("unchecked") private Class<T> getPersistentClass() { Class<T> type = null; Class<?> clazz = getClass(); while (!(clazz.getGenericSuperclass() instanceof ParameterizedType)) { clazz = clazz.getSuperclass(); } type = (Class<T>) ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0]; if (log.isDebugEnabled()) { log.debug("type DO :: " + type); } return type; } /** * @return the sessionFactory */ public SessionFactory getSessionFactory(){ return sessionFactory; } /** * @param sessionFactory the sessionFactory to set */ public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } }
package com.example.agnciadeturismo.presenter.view.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.agnciadeturismo.R; import com.example.agnciadeturismo.model.ReservaDto; import java.util.ArrayList; public class CompraAdapter extends RecyclerView.Adapter<CompraAdapter.viewHolder> { OnClickItemCompra listener; ArrayList<ReservaDto> listReserva; public CompraAdapter(OnClickItemCompra listener, ArrayList<ReservaDto> listReserva) { this.listener = listener; this.listReserva = listReserva; } @NonNull @Override public viewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_compra, parent, false); return new viewHolder(view, listener); } @Override public void onBindViewHolder(@NonNull viewHolder holder, int position) { ReservaDto reserva = listReserva.get(position); holder.textViewValor.setText("R$"+reserva.getValorTotal()); holder.textViewCartao.setText(reserva.getNomeCartao()); holder.textViewCliente.setText(reserva.getNomeCliente()); String ano = reserva.getData().substring(0,4); String mes = reserva.getData().substring(5,7); String dia = reserva.getData().substring(8,10); String horas = reserva.getData().substring(11,19); String data = dia+"/"+mes+"/"+ano+" às "+horas; holder.textViewData.setText(data); } @Override public int getItemCount() { return listReserva.size(); } class viewHolder extends RecyclerView.ViewHolder{ TextView textViewValor, textViewCartao, textViewCliente, textViewData; public viewHolder(@NonNull View itemView, OnClickItemCompra listener) { super(itemView); textViewValor = itemView.findViewById(R.id.txt_valorItem); textViewCartao = itemView.findViewById(R.id.txt_nomeCartaoItem); textViewCliente = itemView.findViewById(R.id.txt_nomeClienteItem); textViewData = itemView.findViewById(R.id.txt_dataItem); itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onClick(getAdapterPosition()); } }); } } }
package com.example.kyle.myapplication.Screens.CreateEdit; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.kyle.myapplication.Database.Abstract.Abstract_Table; import com.example.kyle.myapplication.Database.Abstract.Abstract_Table_Manager; import com.example.kyle.myapplication.Database.DBOperation; import com.example.kyle.myapplication.Database.Role.Tbl_Role; import com.example.kyle.myapplication.Database.Role.Tbl_Role_Manager; import com.example.kyle.myapplication.Helpers.OpenScreens; import com.example.kyle.myapplication.R; import com.example.kyle.myapplication.Screens.DataList; public class CreateEditRole extends AppCompatActivity { private EditText txtRoleTitle; public static Tbl_Role toUpdate = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_createedit_role); txtRoleTitle = (EditText) findViewById(R.id.txtRoleTitle); Button btnCreate = (Button) findViewById(R.id.btnCreate); btnCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { create(); } }); Button btnClear = (Button) findViewById(R.id.btnClear); btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { clear(); } }); if (toUpdate != null) { btnCreate.setText("Update"); btnClear.setText("Revert Changes"); } clear(); } private void create() { String roleTitle = txtRoleTitle.getText().toString(); Tbl_Role record = new Tbl_Role(roleTitle); String anyErrors = record.isValidRecord(); if (anyErrors.isEmpty()) { if (toUpdate != null) { record.roleID = toUpdate.roleID; record.sqlMode = Abstract_Table.SQLMode.UPDATE; toUpdate = record; DBOperation resultOperation = Tbl_Role_Manager.current.RecordOperation(this, toUpdate, "Role Updated", "Unable to Update Role"); if (resultOperation != null && resultOperation.Success()) { OpenScreens.OpenDataListScreen(DataList.Mode.Edit, Abstract_Table_Manager.Table.ROLE); finish(); } } else { record.sqlMode = Abstract_Table.SQLMode.INSERT; DBOperation resultOperation = Tbl_Role_Manager.current.RecordOperation(this, record, "Role Added", "Unable to Add Role"); if (resultOperation != null && resultOperation.Success()) { clear(); } } } else { Toast.makeText(this, anyErrors, Toast.LENGTH_LONG).show(); } } private void clear() { if (toUpdate != null) { txtRoleTitle.setText(toUpdate.title); } else { txtRoleTitle.setText(""); } } }
// Copyright 2017 Google Inc. // // 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 codeu.model.data; import java.text.SimpleDateFormat; import java.time.Instant; import java.util.UUID; import java.util.*; /** Class representing a registered user. */ public class User { public enum Sex { MALE, FEMALE } public enum OccupationType{ STUDENT, EMPLOYED, UNEMPLOYED } Set<String> admin = new HashSet<>(Arrays.asList("anAdmin", "Admin1", "Admin2","Hazim")); private final UUID id; private final String name; private final String passwordHash; private final Instant creation; private Date birthday; private String description; private Occupation occupation; private ProfileImage profileImage; private Sex sex; private String email; /** * Constructs a new User. * * @param id the ID of this User * @param name the username of this User * @param passwordHash the password hash of this User * @param creation the creation time of this User */ public User(UUID id, String name, String passwordHash, Instant creation) { this.id = id; this.name = name; this.passwordHash = passwordHash; this.creation = creation; } /** Returns the ID of this User. */ public UUID getId() { return id; } /** Returns the username of this User. */ public String getName() { return name; } /** Returns the password hash of this User. */ public String getPasswordHash() { return passwordHash; } /** Returns the creation time of this User. */ public Instant getCreationTime() { return creation; } public boolean checkAdmin() { return admin.contains(name); } public String getBirthday(SimpleDateFormat sdf) { if(birthday != null) { return sdf.format(birthday); } return "Birthday not set"; } public Date getBirthdayAsString(){ return birthday; } public Date getBirthday(){ if(birthday != null){ return birthday; } return null; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getDescription() { if(description == null || description.trim().equals("")) { return "Description not set"; } return description; } public void setDescription(String description) { this.description = description; } public Occupation getOccupation() { if(occupation == null) { return new Occupation(); } return occupation; } public void setOccupation(Occupation occupation) { this.occupation = occupation; } public Occupation parseOccupation(String occupationString) { if(occupationString.equals("null")) { return null; } String[] valueArray = occupationString.split(";"); for(String value : valueArray) { while(value.indexOf(-1) != -1) { value = value.substring(0,value.indexOf(";")) + value.substring(value.indexOf(";")+1); } } if(valueArray[0].equals("UNEMPLOYED")) { Occupation out = new Occupation(); return out; } else { Occupation out = new Occupation( valueArray[0], valueArray[1] ); return out; } } public ProfileImage getProfileImage() { if(profileImage == null) { return ProfileImage.getDefaultImage(sex); } return profileImage; } public void setProfileImage(ProfileImage profileImage) { this.profileImage = profileImage; } public Sex getSex() { return sex; } public void setSex(Sex sex) { this.sex = sex; } public String getEmail() { if(email == null) { return "Email not set"; } return email; } public void setEmail(String email) { this.email = email; } //Inner class public class Occupation { private OccupationType occupationType; private String f1; private String f2; public Occupation(String f1, String f2){ this.occupationType = OccupationType.EMPLOYED; this.f1 = f1; this.f2 = f2; } public Occupation() { this.occupationType = OccupationType.UNEMPLOYED; } public OccupationType getOccupationType() { return occupationType; } public String getf1() { return f1; } public String getf2() { return f2; } public String toString() { if(occupationType == OccupationType.UNEMPLOYED && f1 != null && f2 != null) { return f1 + " at " + f2; } return "Unemployed"; } public String storableValue() { if(occupationType == null) { return "null"; } String out = ""; out += occupationType.toString(); out += ";"; if(occupationType == OccupationType.STUDENT || occupationType == OccupationType.EMPLOYED) { out += f1 + ";" + f2; } return out; } } }
package factoring.math; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multiset; import com.google.common.collect.TreeMultiset; import factoring.trial.variant.TrialFact; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Created by Thilo Harich on 16.12.2017. */ public class FermatResiudesTest { /** * x^2 - 23 = y^2 mod 24 * x^2 + 1 = y^2 mod 24 * * 0 -> 0 * 1 -> 1 * 2 -> 4 * 3 -> 9 * 4 -> 16 * 5 -> 1 * 6 -> 12 * 7 -> 1 * 8 -> 16 * 9 -> 9 * 10-> 4 * 11-> 1 * 12-> 0 * x = 0, 12 * * n^2 mod 12 * 1 -> 1 * 5 -> 1 * 7 -> 49 -> 1 * 11 -> 121 -> 1 * * Multiply n with n mod residueclass */ @Test public void testNumber () { // 16 * 27 // int number = 2*2*2*2*2 * 3*3 * 5 * 7 * 11; // int number = 2*2*2 * 3*3 * 5 * 7 * 11; // int number = 8*9*5*7*11; int number = 2; for (int i = number; i <= number + 32; i++) { FermatResidueMergeByInversion fermat = new FermatResidueMergeByInversion(i); Stream<Boolean> stream = IntStream.range(0, fermat.squares.length) .mapToObj(idx -> fermat.squares[idx]); long countSquares = stream.filter(b -> b == true).count(); TrialFact factorizer = new TrialFact(); long max = 0; long min = Long.MAX_VALUE; int minIndex = 0; double avg = 0; int num = 0; String details = ""; for (int n = 1; n< i; n++) { if (PrimeMath.gcd(i, n) == 1) { fermat.initX(n); long countFermat = Arrays.stream(fermat.xArray).boxed().collect(Collectors.toList()).indexOf(-1); max = Math.max(max, countFermat); if (countFermat < min) minIndex = n; min = Math.min(min, countFermat); avg += countFermat; num++; details += countFermat + " , "; } } // double quality = Math.pow(Math.log(i),1.2) / Math.log(min); // double quality = Math.log(i) / Math.log(max); double quality = (i + 0.0) / (min); // if (quality > 5) { float ifl = (float)i; String factors = String.format("%-20s", factorizer.printFactorization(i)); System.out.print(i + "(" + factors + ") \t: " + countSquares + " ; "); System.out.print(" exp : " + (ifl+1)/(2*ifl) * ifl); System.out.print(" max : " + max + " min : " + min + "(" + minIndex + ") avg : " + (avg/ num) + " quality : " + quality + " : " + details); System.out.println(); // TreeMultiset<Long> factorSet = factorizer.findAllPrimeFactors(i); // for (int j=1; j<i; j++) // { // boolean hasDivisor = hasDivisor(factorSet, j); // if (!hasDivisor) { // // // Integer multiplier = null; // for (int k=0; k<i && multiplier == null; k++) // if (PrimeMath.mod(k*j, i) == minIndex) { // multiplier = k; // } // if (multiplier == null) // System.out.println("no Multiplier found for " + j); // // } // } // int n = minIndex; // int[] xArray = fermat.xArray(n); // System.out.println(Arrays.stream(xArray).boxed().filter(x -> x> 0).map(Object::toString).collect(Collectors.joining(","))); } } } public boolean hasDivisor(TreeMultiset<Long> factorSet, int j) { Iterator<Long> iter = factorSet.elementSet().iterator(); while(iter.hasNext()) { long factor = iter.next(); if (j % factor == 0) { return true; } } return false; } }
package msip.go.kr.search.entity; import java.io.Serializable; import java.util.Date; @SuppressWarnings("serial") public class SearchDTO implements Serializable { private Long id; private String title; private String content; private String fileId; private String startYmd; private String endYmd; private String deadlineYmd; private String deadlineTime; private boolean isalarmReqEmail; private boolean isalarmReqSms; private boolean isalarmReqAlimi; private boolean isalarmResEmail; private boolean isalarmResSms; private boolean isalarmResAlimi; private boolean isalarmWarnEmail; private boolean isalarmWarnSms; private boolean isalarmWarnAlimi; private int status; private int hits; private String regId; private String regNm; private Date regDate; private String modId; private String modNm; private Date modDate; private String regDisp; private String memberId; private String memberNm; private Long orgCd; private String orgNm; int reqCnt; int resCnt; int shreCnt; int totalCnt; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getStartYmd() { return startYmd; } public void setStartYmd(String startYmd) { this.startYmd = startYmd.replaceAll("\\/", "");; } public String getEndYmd() { return endYmd; } public void setEndYmd(String endYmd) { this.endYmd = endYmd.replaceAll("\\/", "");; } public String getDeadlineYmd() { return deadlineYmd; } public void setDeadlineYmd(String deadlineYmd) { this.deadlineYmd = deadlineYmd.replaceAll("\\/", ""); } public String getDeadlineTime() { return deadlineTime; } public void setDeadlineTime(String deadlineTime) { this.deadlineTime = deadlineTime; } public boolean isIsalarmReqEmail() { return isalarmReqEmail; } public void setIsalarmReqEmail(boolean isalarmReqEmail) { this.isalarmReqEmail = isalarmReqEmail; } public boolean isIsalarmReqSms() { return isalarmReqSms; } public void setIsalarmReqSms(boolean isalarmReqSms) { this.isalarmReqSms = isalarmReqSms; } public boolean isIsalarmReqAlimi() { return isalarmReqAlimi; } public void setIsalarmReqAlimi(boolean isalarmReqAlimi) { this.isalarmReqAlimi = isalarmReqAlimi; } public boolean isIsalarmResEmail() { return isalarmResEmail; } public void setIsalarmResEmail(boolean isalarmResEmail) { this.isalarmResEmail = isalarmResEmail; } public boolean isIsalarmResSms() { return isalarmResSms; } public void setIsalarmResSms(boolean isalarmResSms) { this.isalarmResSms = isalarmResSms; } public boolean isIsalarmResAlimi() { return isalarmResAlimi; } public void setIsalarmResAlimi(boolean isalarmResAlimi) { this.isalarmResAlimi = isalarmResAlimi; } public boolean isIsalarmWarnEmail() { return isalarmWarnEmail; } public void setIsalarmWarnEmail(boolean isalarmWarnEmail) { this.isalarmWarnEmail = isalarmWarnEmail; } public boolean isIsalarmWarnSms() { return isalarmWarnSms; } public void setIsalarmWarnSms(boolean isalarmWarnSms) { this.isalarmWarnSms = isalarmWarnSms; } public boolean isIsalarmWarnAlimi() { return isalarmWarnAlimi; } public void setIsalarmWarnAlimi(boolean isalarmWarnAlimi) { this.isalarmWarnAlimi = isalarmWarnAlimi; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getHits() { return hits; } public void setHits(int hits) { this.hits = hits; } public String getRegId() { return regId; } public void setRegId(String regId) { this.regId = regId; } public String getRegNm() { return regNm; } public void setRegNm(String regNm) { this.regNm = regNm; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public String getModId() { return modId; } public void setModId(String modId) { this.modId = modId; } public String getModNm() { return modNm; } public void setModNm(String modNm) { this.modNm = modNm; } public Date getModDate() { return modDate; } public void setModDate(Date modDate) { this.modDate = modDate; } public String getRegDisp() { return regDisp; } public void setRegDisp(String regDisp) { this.regDisp = regDisp; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public String getMemberNm() { return memberNm; } public void setMemberNm(String memberNm) { this.memberNm = memberNm; } public Long getOrgCd() { return orgCd; } public void setOrgCd(Long orgCd) { this.orgCd = orgCd; } public String getOrgNm() { return orgNm; } public void setOrgNm(String orgNm) { this.orgNm = orgNm; } public int getReqCnt() { return reqCnt; } public void setReqCnt(int reqCnt) { this.reqCnt = reqCnt; } public int getResCnt() { return resCnt; } public void setResCnt(int resCnt) { this.resCnt = resCnt; } public int getShreCnt() { return shreCnt; } public void setShreCnt(int shreCnt) { this.shreCnt = shreCnt; } public int getTotalCnt() { return totalCnt; } public void setTotalCnt(int totalCnt) { this.totalCnt = totalCnt; } }
//package com.turios.activities.setup; // //import android.app.ActionBar; //import android.content.Intent; //import android.os.Bundle; //import android.support.v4.app.FragmentManager; //import android.text.TextUtils; //import android.widget.Button; //import android.widget.EditText; // //import com.parse.ParseInstallation; //import com.turios.R; //import com.turios.activities.SplashScreen; //import com.turios.activities.fragments.dialog.GenericOkDialogFragment; //import com.turios.activities.fragments.dialog.GenericOkDialogFragment.GenericOkDialogInterface; //import com.turios.dagger.DaggerActivity; //import com.turios.modules.core.ParseCoreModule; //import com.turios.modules.core.ParseCoreModule.ParseLoginCallback; //import com.turios.modules.core.parse.ParseObjectHelper; // //import javax.inject.Inject; // //import butterknife.BindView; //import butterknife.ButterKnife; //import butterknife.OnClick; // //public class SetupWelcome extends DaggerActivity { // // @Inject FragmentManager fm; // @Inject ParseCoreModule parse; // @Inject ActionBar actionbar; // // @BindView(R.id.input_unit_name) EditText unitname; // // @OnClick(R.id.button_continue) public void onContinue(Button button) { // String name = unitname.getText().toString(); // // if (TextUtils.isEmpty(name.trim())) { // GenericOkDialogFragment.newInstance(new GenericOkDialogInterface() { // // @Override public void okClicked() { // // } // }, android.R.string.dialog_alert_title, R.string.missing_name, // android.R.drawable.ic_dialog_alert).show(fm, // "Dialog_name_missing"); // } else { // ParseInstallation parseInstallation = parse.getParseInstallation(); // parseInstallation.put(ParseObjectHelper.ParseInstallation.name, // name); // parseInstallation.saveEventually(); // // parse.getPreferences().setDevicename(name); // // startActivity(WizardHelper.getNextScreen()); // SetupWelcome.this.finish(); // } // } // // @Override protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // // ensure that we are logged in to parse // parse.login(new ParseLoginCallback() { // // @Override public void success() { // setContentView(R.layout.setup_welcome); // // actionbar.setTitle("Velkommen"); // // ButterKnife.bind(SetupWelcome.this); // // unitname.setText(parse.getPreferences().getDevicename()); // // overridePendingTransition(R.anim.slide_in_right, // R.anim.slide_out_left); // } // // @Override public void failed(Exception e) { // Intent i = new Intent(SetupWelcome.this, SplashScreen.class) // .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); // startActivity(i); // } // }); // // } // // @Override public void onBackPressed() { // // do nothing // } //}
package edu.pitt.is17.ERL67.menumanager; /** * Class FileManager0 * author : ERL67 * created: 11/02/2016 * */ import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class FileManager0 { final static String SPLIT = "@@"; //string of separating chars /** * Method readEntrees * @param fileName a string of the data file holding the menu info * @return ArrayList<Entree> */ public static ArrayList<Entree> readEntrees (String fileName){ //all the file read methods are the same, only the first will be commented ArrayList<Entree> entrees = new ArrayList<Entree>(); //create array list to hold data read int arrayIndex=0; //tracks the array index and increments after each line of the file try { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { int first = line.indexOf(SPLIT); //determine the two spots in the line that split the data int second = line.indexOf(SPLIT, first + 1); //add to the arraylist a new object of each menu type using the constructor and substrings of the file line entrees.add(arrayIndex, //index of arraylist starts at 0 and goes up each line new Entree(line.substring(0,first), //Name of item line.substring(first+2,second), //Description Integer.parseInt(line.substring(second+2)),0)); //calories arrayIndex++; //increment the arraylist index for the next line } br.close(); fr.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return entrees; } /** * Method readSides * @param fileName a string of the data file holding the menu info * @return ArrayList<Side> */ public static ArrayList<Side> readSides (String fileName){ ArrayList<Side> sides = new ArrayList<Side>(); int arrayIndex = 0 ; try { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { int first = line.indexOf(SPLIT); int second = line.indexOf(SPLIT, first + 1); sides.add(arrayIndex, new Side(line.substring(0,first), line.substring(first+2,second), Integer.parseInt(line.substring(second+2)),0)); arrayIndex++; } br.close(); fr.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return sides; } /** * Method readSalads * @param fileName a string of the data file holding the menu info * @return ArrayList<Salad> */ public static ArrayList<Salad> readSalads (String fileName){ ArrayList<Salad> salads = new ArrayList<Salad>(); int arrayIndex = 0 ; try { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { int first = line.indexOf(SPLIT); int second = line.indexOf(SPLIT, first + 1); salads.add(arrayIndex, new Salad(line.substring(0,first), line.substring(first+2,second), Integer.parseInt(line.substring(second+2)),0)); arrayIndex++; } br.close(); fr.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return salads; } /** * Method readDesserts * @param fileName a string of the data file holding the menu info * @return ArrayList<Dessert> */ public static ArrayList<Dessert> readDesserts (String fileName){ ArrayList<Dessert> desserts = new ArrayList<Dessert>(); int arrayIndex = 0 ; try { FileReader fr = new FileReader(fileName); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { int first = line.indexOf(SPLIT); int second = line.indexOf(SPLIT, first + 1); desserts.add(arrayIndex, new Dessert(line.substring(0,first), line.substring(first+2,second), Integer.parseInt(line.substring(second+2)),0 )); arrayIndex++; } br.close(); fr.close(); } catch (Exception e) { System.out.println(e.getMessage()); } return desserts; } }
package com.zheng.highconcurrent.atomic; import org.junit.Test; import java.util.concurrent.atomic.AtomicLongArray; /** * @Author zhenglian * @Date 2019/1/18 */ public class AtomicLongArrayApp { @Test public void init() { AtomicLongArray array = new AtomicLongArray(5); System.out.println(array.get(0)); } }
package domain; import java.io.Serializable; /** * Created by rodrique on 4/19/2018. */ public class POS_Cashier extends Employee implements Role { public String getJobDescription() { return "Cashier is responsible for recording all transactions and ensuring accurate stock take"; } }
package Assignment2; import java.util.InputMismatchException; import java.util.Iterator; import java.util.Scanner; public class Game { private static Scanner input; // game constants private static final int SIZE = 7; private static int[] list = null; private static int l = 0, r = SIZE - 1; // pointers to edges of the list private static boolean running = true; private static int[][] bestMoves = null; // game variables private static int playerSum = 0, computerSum = 0; public static void main(String[] args) { input = new Scanner(System.in); char c = ' '; initList(); bestMoves = new int[SIZE][SIZE]; calculateBestMoves(); while (running) { boolean shouldStop = false; while (!shouldStop) { showList(); shouldStop = turn(); System.out.println("---------------"); } checkWinner(); restart(); } input.close(); } public static void initList() { // method to initialize list and fill in random numbers list = new int[SIZE]; for (int i = 0; i < list.length; i++) { list[i] = (int)(Math.random()* 3) + 1; } } public static void showList() { System.out.println("Current list: "); for (int i = l; i <= r; i++) { System.out.print(list[i] + " "); } System.out.println(); } public static boolean turn() { // player's turn if (l >= r) { // last item System.out.printf("Last item %d chosen automatically\n", list[l]); playerSum += list[l]; return true; } System.out.printf("Your options are %d (type 'l') or %d (type 'r')", list[l], list[r]); System.out.printf("\nBest choice is: %s \n", bestMoves[l][r] == l ? "l" : "r"); // pull best move from table System.out.print("You choose: "); boolean success = false; char choice = ' '; while (!success) { try { choice = input.next().toLowerCase().charAt(0); success = true; } catch (InputMismatchException e) { System.out.println("Please enter 'l' for left or 'r' for right"); } } if (choice == 'r') playerSum += list[r--]; // add to playerSum and decrement r else playerSum += list[l++]; // add to playerSum and increment l System.out.println("---------------"); // show list between turns showList(); // computer's turn int compChoice = bestMoves[l][r]; System.out.printf("Computer chooses: %s\n" , compChoice == l ? "l" : "r"); computerSum += list[compChoice]; // add to computer sum if (compChoice == l) l++; else r--; return false; } public static void calculateBestMoves() { // function to compute best moves for a given game int x,y,z; // compute turn by : max(list[i] + min(x,y), list[j] + min(y,z)) // we expect opponent to make the best move also for (int k = 0; k < SIZE; ++k) { for (int i = 0, j = k; j < SIZE; ++i, ++j) { // get values for x, y, z if ((i + 2) <= j) x = bestMoves[i+2][j]; else x = 0; if ((i + 1) <= (j - 1)) y = bestMoves[i + 1][j - 1]; else y = 0; if (i <= j - 2) z = bestMoves[i][j - 2]; else z = 0; if (list[i] + min(x,y) > list[j] + min(y,z)) bestMoves[i][j] = i; // choose left else bestMoves[i][j] = j; // choose right } } } public static void checkWinner() { System.out.printf("You scored %d\n", playerSum); System.out.printf("The computer scored %d\n", computerSum); if (playerSum == computerSum) { System.out.println("TIE :|"); return; } if (playerSum > computerSum) System.out.println("You win :)"); else System.out.println("You lose :("); } public static int min (int a, int b) { return Math.min(a, b); } public static int max (int a, int b) { return Math.max(a, b); } public static void restart() { System.out.println("Would you like to play again?"); System.out.println("y/n"); char c = input.next().toLowerCase().charAt(0); if (c != 'y') { running = false; System.out.println("Okay, cya :)"); return; } // generate a new list initList(); // restart bestMoves bestMoves = new int[SIZE][SIZE]; // calculate new best moves calculateBestMoves(); // reset l, r l = 0; r = SIZE - 1; // reset sums playerSum = 0; computerSum = 0; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.mwi.aws.dynamodb.ui; //import com.mwi.cad.web.jms.CADServiceManager; //import com.mwi.cad.client.util.MwiResourceMap; //import com.mwi.cad.systemmgr.message.LoginOutput; //import com.mwi.cad.systemmgr.message.SystemMgrConstant; //import com.mwi.cad.web.config.ApplicationBeanConfig; import javax.annotation.PostConstruct; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import com.mwi.aws.dynamodb.SessionBean; /** * * @author Naveen S */ @ManagedBean(name = "loginView", eager = true) @RequestScoped public class Login { private String userName; private String passWord; // @ManagedProperty(value = "#{applicationBeanConfig}") // private ApplicationBeanConfig applicationBeanConfig; @ManagedProperty(value = "#{sessionBean}") private SessionBean sessionBean; @PostConstruct public void init() { try { if (sessionBean.isIsLoggedIn()) { sessionBean.redirect("/printerweb/faces/PrinterWeb.xhtml"); } } catch (Exception e) { //if error occurs due to session time out do nothing } } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the passWord */ public String getPassWord() { return passWord; } /** * @param passWord the passWord to set */ public void setPassWord(String passWord) { this.passWord = passWord; } /** * @return the sessionBean */ public SessionBean getSessionBean() { return sessionBean; } /** * @param sessionBean the sessionBean to set */ public void setSessionBean(SessionBean sessionBean) { this.sessionBean = sessionBean; } public String login() { String str = null; if(sessionBean.login(userName, passWord)){ str = "PrinterWeb"; }else{ FacesContext.getCurrentInstance().addMessage("form1:messages1", new FacesMessage(FacesMessage.SEVERITY_WARN, "WARN", "Invalid login!")); // LoginOutput output = CADServiceManager.getInstance().getJmsSystemServiceProvider().login(userName, passWord, "Client1"); // if (output == null) { // FacesContext.getCurrentInstance().addMessage("loginForm:messages1", new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR", "Server Communication Error!")); // } else if (output.getLoginResult() == SystemMgrConstant.E_LOGIN_FAIL_INVALID_USER) { // FacesContext.getCurrentInstance().addMessage("loginForm:messages1", new FacesMessage(FacesMessage.SEVERITY_WARN, "WARN", MwiResourceMap.getResourceStr("error.login.invalid_user_pwd", "Invaild password"))); // } else if (output.getLoginResult() == SystemMgrConstant.E_LOGIN_FAIL_INVALID_PWD) { // FacesContext.getCurrentInstance().addMessage("loginForm:messages1", new FacesMessage(FacesMessage.SEVERITY_WARN, "WARN", MwiResourceMap.getResourceStr("error.login.invalid_user_pwd", "Invaild password"))); // } else if (output.getLoginResult() == SystemMgrConstant.E_LOGIN_SUCCEED) { // str = "radioDisp"; // } } return str; } // /** // * @return the applicationBeanConfig // */ // public ApplicationBeanConfig getApplicationBeanConfig() { // return applicationBeanConfig; // } // // /** // * @param applicationBeanConfig the applicationBeanConfig to set // */ // public void setApplicationBeanConfig(ApplicationBeanConfig applicationBeanConfig) { // this.applicationBeanConfig = applicationBeanConfig; // } }
package com.shensu.dao; import com.shensu.pojo.LearningWorldImg; public interface LearningWorldImgMapper { int deleteByPrimaryKey(Integer learningworldimgid); int insert(LearningWorldImg record); int insertSelective(LearningWorldImg record); LearningWorldImg selectByPrimaryKey(Integer learningworldimgid); int updateByPrimaryKeySelective(LearningWorldImg record); int updateByPrimaryKey(LearningWorldImg record); }
package com.nfet.icare.service; import java.util.List; import com.nfet.icare.pojo.Area; import com.nfet.icare.pojo.City; import com.nfet.icare.pojo.Province; public interface ZoneService { //获取所有省份 public List<Province> provinceList(); //根据省份id获取城市 public List<City> cityList(int provinceId); //根据城市id获取地区 public List<Area> areaList(int cityId); //根据省份id获取省份名称 public String queryProvinceName(int provinceId); //根据城市id获取城市名称 public String quertCityName(int cityId); //根据地区id获取地区名称 public String queryAreaName(int areaId); }
package raft.server; import raft.server.proto.RaftCommand; /** * Author: ylgrgyq * Date: 18/5/9 */ public interface RaftCommandBroker { void onWriteCommand(RaftCommand cmd); void onFlushCommand(); void shutdown(); default void onWriteAndFlushCommand(RaftCommand cmd) { onWriteCommand(cmd); onFlushCommand(); } }
package stacksnqueues; import static org.junit.Assert.*; import org.junit.Test; public class QueueOfStacksTest { @Test public void testBasic() { QueueOfStacks<String> queue = new QueueOfStacks<String>(); queue.push("1"); queue.push("2"); queue.push("3"); assertTrue(queue.isEmpty()); assertEquals("1",queue.pop()); assertEquals("2",queue.pop()); assertEquals("3",queue.pop()); assertTrue(queue.isEmpty()); } @Test public void testIntermidiateInsertions() { QueueOfStacks<String> queue = new QueueOfStacks<String>(); queue.push("1"); queue.push("2"); queue.push("3"); assertTrue(queue.isEmpty()); assertEquals("1",queue.pop()); queue.push("4"); assertEquals("2",queue.pop()); assertEquals("3",queue.pop()); assertEquals("4",queue.pop()); assertTrue(queue.isEmpty()); } }
package org.jenkinsci.test.acceptance.plugins.tasks; import org.jenkinsci.test.acceptance.plugins.analysis_core.AbstractTablePortlet; import org.jenkinsci.test.acceptance.plugins.dashboard_view.DashboardView; import org.jenkinsci.test.acceptance.po.Describable; /** * A task scanner portlet for {@link DashboardView}. * * @author Fabian Trampusch */ @Describable("Open tasks per project") public class TasksPortlet extends AbstractTablePortlet { public TasksPortlet(final DashboardView parent, final String path) { super(parent, path); } }
package com.san.bracelet; import org.springframework.stereotype.Service; @Service public class BraceletService { }
package by.realovka.diploma.dto; import by.realovka.diploma.entity.Post; import by.realovka.diploma.entity.User; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class CommentOnPageDTO { private long id; private String text; private String dataTime; private Post post; private User user; }
import java.util.*; class TestSleep extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{ Thread.sleep(500); } catch(InterruptedException e){ System.out.println(e); } System.out.println(i); } } public static void main(String args[]){ TestSleep t1=new TestSleep(); TestSleep t2=new TestSleep(); t1.start(); t2.start(); } }
import java.util.*; public class GCDLCMEasy { private ArrayList<int[]>[] edges; private int[] values; private int[] changedValues; public String possible(int n, int[] A, int[] B, int[] G, int[] L) { edges = new ArrayList[n]; for(int i = 0; i < n; ++i) { edges[i] = new ArrayList(); } for(int i = 0; i < A.length; ++i) { edges[A[i]].add(new int[] {B[i], G[i], L[i]}); edges[B[i]].add(new int[] {A[i], G[i], L[i]}); } values = new int[n]; for(int i = 0; i < values.length; ++i) { if(values[i] == 0) { boolean possible = false; for(int j = 1; j <= 10000 && !possible; ++j) { changedValues = new int[n]; possible = dfs(i, j); } if(!possible) { return "Solution does not exist"; } else { for(int j = 0; j < changedValues.length; ++j) { if(changedValues[j] != 0) { values[j] = changedValues[j]; } } } } } return "Solution exists"; } private boolean dfs(int index, int value) { if(changedValues[index] == 0) { changedValues[index] = value; ArrayList<int []> currentEdge = edges[index]; for(int i = 0; i < currentEdge.size(); ++i) { int next = currentEdge.get(i)[1] * currentEdge.get(i)[2]; if(next%value == 0) { next /= value; int gcd = GCD(value, next); int lcm = (value * next)/gcd; if(gcd != currentEdge.get(i)[1] || lcm != currentEdge.get(i)[2] || !dfs(currentEdge.get(i)[0], next)) { return false; } } else { return false; } } } else if(changedValues[index] != value) { return false; } return true; } private int GCD(int a, int b) { while(a != b) { if(b < a) { a -= b; } else { b -= a; } } return a; } }
package kxg.searchaf.url.amazonWeibo; import java.util.*; import kxg.searchaf.url.Constant; public class SearchAmazonWeibo { public HashMap<String, AmazonProduct> alloldprolist = new HashMap<String, AmazonProduct>(); public HashMap<String, AmazonProduct> allnewprolist = new HashMap<String, AmazonProduct>(); public static void main(String[] args) { SearchAmazonWeibo af = new SearchAmazonWeibo(); // while (true) { try { // System.out.println("start checking..."); af.getnewproduct(); // System.out.println(new Date() + "done..."); // Thread.sleep(1000 * 60 * Constant.sleeptime); // sleep 10 // mines } catch (Exception e) { e.printStackTrace(); } // } } public void getnewproduct() { System.out.println("Checking ..."); checkMennewproduct(); } private void send2Weibo(AmazonProduct product) { System.out.println("send weibo:" + product); } private void checkMennewproduct() { List<AmazonSearchPage> urllist = AmazonSearchPage.getInstance(); for (int i = 0; i < urllist.size(); i++) { this.allnewprolist.clear(); AmazonSearchPage afpage = urllist.get(i); ParserAmazonPage parserAfpage = new ParserAmazonPage(afpage, allnewprolist); parserAfpage.checkprice(); System.out.println("found products:" + allnewprolist.size()); // check new product Iterator<String> entryKeyIterator = allnewprolist.keySet() .iterator(); while (entryKeyIterator.hasNext()) { String key = entryKeyIterator.next(); AmazonProduct product = allnewprolist.get(key); AmazonProduct oldproduct = alloldprolist.get(key); if (oldproduct != null) { // have found this if (oldproduct.price > product.price) { // price dis send2Weibo(product); } } alloldprolist.put(key, product); } } } }
package com.pos.porschetower.pagertransformations; import android.util.Log; import android.view.View; import androidx.viewpager.widget.ViewPager; public class FrontPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.55f; private static final float MAX_SCALE = 1.0f; private static final float MIN_ALPHA = 0.2f; private static final float MAX_ALPHA = 1.0f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); position -= 2.0f * 0.15f; if (position < -1.0f) { view.setAlpha(0.0f); } else if (position <= 1.0f) { float factor = Math.abs(position); factor *= factor; float factorComplement = 1.0f - factor; float scale = factorComplement * (MAX_SCALE - MIN_SCALE) + MIN_SCALE; view.setScaleX(scale); view.setScaleY(scale); Log.e("scaleee", scale + ""); float alpha = factorComplement * (MAX_ALPHA - MIN_ALPHA) + MIN_ALPHA; view.setAlpha(alpha); float translationFactor = 0.1f * (float) Math.sin(Math.PI * position - 0.1f * Math.PI) + 0.1f; translationFactor *= translationFactor; float translationX = -Math.signum(position) * 0.92f * pageWidth * translationFactor; view.setTranslationX(translationX); } else { view.setAlpha(0.0f); } } }
package bip.controller; import static org.assertj.core.api.Assertions.assertThat; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONObject; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.stubbing.OngoingStubbing; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import bip.utilities.ImageResizeService; import bip.utilities.ImageUploaderService; import bip.utilities.NameUtil; import bip.utilities.S3Uploader; import io.github.resilience4j.circuitbreaker.CircuitBreaker; import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry; import static org.mockito.Mockito.when; import static org.hamcrest.Matchers.containsString; import static org.mockito.Matchers.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.io.File; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicLong; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class UploadImageLoadTest { @Autowired private MockMvc mockMvc; @Autowired private UploadController uploadController; @MockBean private S3Uploader s3Uploader; @MockBean private NameUtil nameUtils; private InputStream testImage; @Autowired CircuitBreakerRegistry registry; @Before public void setup() { when(nameUtils.makeKeyName(any(String.class))).thenReturn("mocked-key.jpg"); when(nameUtils.updateKeyName("mocked-key.jpg", "LARGE")).thenReturn("mocked-key-LARGE.jpg"); when(nameUtils.updateKeyName("mocked-key.jpg", "THUMB")).thenReturn("mocked-key-THUMB.jpg"); testImage = this.getClass().getResourceAsStream("/test-photo.jpg"); assertThat(testImage).isNotNull(); } @Test public void testImageUploadParallel() throws Exception { MockMultipartFile imageFile = new MockMultipartFile("image", "nicephoto.jpg", "image/jpeg", testImage); // always return true for upload. when(s3Uploader.upload(any(String.class), any(String[].class), any(String[].class))) .thenReturn(true); ExecutorService executor = Executors.newFixedThreadPool(10); // submit 12 parallel image uploads. Anything more than 5 should trigger circuit breaker. final AtomicLong counter = new AtomicLong(0); for (int i = 0; i < 12; i++) { executor.execute(new Runnable() { public void run() { try { int expectedStatus = 200; long running = counter.incrementAndGet(); if (running > 10) { expectedStatus = 503; } mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(expectedStatus)); } catch (Exception ex) { // fail test if we get this exception. assertThat(10).isEqualTo(0); } } }); } executor.shutdown(); while (!executor.isTerminated()) { } } @Test public void testImageUploadLoad() throws Exception { MockMultipartFile imageFile = new MockMultipartFile("image", "nicephoto.jpg", "image/jpeg", testImage); CircuitBreaker breaker = registry.circuitBreaker("imageUpload"); // Succeed 2 times when(s3Uploader.upload(any(String.class), any(String[].class), any(String[].class))) .thenReturn(true, true) .thenThrow(new Exception("fake fail"), new Exception("fake fail"), new Exception("fake fail")) .thenReturn(true, true, true); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(200)); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(200)); for(int i = 0; i < 3; i++) { mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(500)); } // Our failure threshold went over limit of 50% mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(503)); breaker.transitionToHalfOpenState(); mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(200)); // CLOSED state expected. so all good. mockMvc.perform(MockMvcRequestBuilders.fileUpload("/image/upload") .file(imageFile)) .andExpect(status().is(200)); } }
package com.legaoyi.platform.ext.service; import java.util.Map; /** * @author gaoshengbo */ public interface ExtendService { /** * 获取记录 * * @param id * @return * @throws Exception */ public Object get(Object id) throws Exception; /** * 统计记录条数 * * @param form * @return * @throws Exception */ public long count(Map<String, Object> form) throws Exception; /** * 查询记录列表 * * @param selects * @param orderBy * @param desc * @param pageSize * @param pageNo * @param countable * @param form * @return * @throws Exception */ public Object query(String[] selects, String orderBy, boolean desc, int pageSize, int pageNo, boolean countable, Map<String, Object> form) throws Exception; /** * 添加记录 * * @param entity * @return * @throws Exception */ public Object persist(Map<String, Object> entity) throws Exception; /** * 修改记录 * * @param id * @param entity * @return * @throws Exception */ public Object merge(Object id, Map<String, Object> entity) throws Exception; /** * 删除记录 * * @param ids * @throws Exception */ public void delete(Object[] ids) throws Exception; }
package com.proyectogrado.alternativahorario.alternativahorario.negocio; import com.proyectogrado.alternativahorario.entidades.Menu; import java.util.List; import javax.ejb.Local; /** * * @author Steven */ @Local public interface AdministracionMenuLocal { List<Menu> getMenus(); }
package com.zhaolong.lesson10.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiParam; @ApiModel(description = "user11") public class User { @ApiModelProperty("id") private Long id; @ApiModelProperty(value = "name",required = true) private String name; @ApiModelProperty("age") private int age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.rednovo.libs.common; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.view.Window; import android.view.WindowManager; public class ImmerseHelper { }
/* * @FileName : ProductDetailFragment.java * @Version : 1.0 * @DateOfCreation : 2/08/2016 * @Author : Rakesh * @Dependencies : FaceBook SDK * @Description : Fragment for display Product Details linked from {@link ProductDetailActivity}. * * Copyright (c) 2016, BluRack. All rights reserved. */ package com.blurack.fragments; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.VolleyLog; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.android.volley.toolbox.StringRequest; import com.blurack.AppController; import com.blurack.R; import com.blurack.activities.BaseActivity; import com.blurack.activities.ProductDetailActivity; import com.blurack.activities.RecipeDetailActivity; import com.blurack.constants.Constants; import com.blurack.utils.Preferences; import com.blurack.utils.ToastUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * A simple {@link Fragment} subclass. * Use the {@link ProductDetailFragment#newInstance} factory method to * create an instance of this fragment. */ public class ProductDetailFragment extends Fragment { // / the fragment initialization parameters, e.g. PRODUCT ID private static final String ARG_PRODUCT_ID = "product-id"; private static final String TAG = "PRODUCT %s"; // Volley Request Tag private static final String TAG_PRODUCT_DETAIL = "Product-Detail"; private static final String TAG_PRODUCT_RATE = "Product-Rate"; // Image Loader to load Images from Server Using Volley private ImageLoader imageLoader = AppController.getInstance().getImageLoader(); private String mProductId; // UI Views private NetworkImageView mProductPhoto; private Button mReserve; private TextView mProductName; private TextView mProductDescription; private RatingBar mProductReting; private LinearLayout recipiesContainer; private LinearLayout reviewsContainer; private JSONObject responseData = null; private String imageUrl; public ProductDetailFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param productID Product id from list. * @return A new instance of fragment ProductsDetailFragment. */ public static ProductDetailFragment newInstance(String productID) { ProductDetailFragment fragment = new ProductDetailFragment(); Bundle args = new Bundle(); args.putString(ARG_PRODUCT_ID, productID); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mProductId = getArguments().getString(ARG_PRODUCT_ID); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View rootView = inflater.inflate(R.layout.fragment_product_detail, container, false); mProductPhoto = (NetworkImageView) rootView.findViewById(R.id.product_photo); mReserve = (Button) rootView.findViewById(R.id.button_reserve); ImageButton mShare = (ImageButton) rootView.findViewById(R.id.button_share); mProductName = (TextView) rootView.findViewById(R.id.textViewName); mProductDescription = (TextView) rootView.findViewById(R.id.textDescription); mProductReting = (RatingBar) rootView.findViewById(R.id.ratingProduct); recipiesContainer = (LinearLayout) rootView.findViewById(R.id.recipiesContainer); reviewsContainer = (LinearLayout) rootView.findViewById(R.id.reviewsContainer); mReserve.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(responseData!=null){ FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); fragmentManager.beginTransaction().replace(R.id.content_frame, ProductReserveFragment.newInstance(responseData.toString())).addToBackStack(null).commit(); } } }); mShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(responseData!=null){ ShareOnFb(); } } }); // Cancel all pending requests if any. AppController.getInstance().cancelPendingRequests(TAG_PRODUCT_DETAIL); if(responseData!=null){ try { populateData(responseData); }catch (JSONException e){ Log.e(TAG,e.getMessage()); } }else{ getDataTask(mProductId); } return rootView; } /** * Represents an asynchronous task used to * Get Product Description Details from server. * @param productId Product Id */ private void getDataTask(String productId) { String url = String.format(Constants.PRODUCT_DETAIL_URL, productId); Log.d(TAG_PRODUCT_DETAIL,url); StringRequest jsonObjReq = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG_PRODUCT_DETAIL, response); try { JSONObject responseObject = new JSONObject(response); responseData = responseObject.getJSONObject("data"); populateData(responseData); } catch (JSONException e) { e.printStackTrace(); VolleyLog.v(TAG, "Error: " + e.getMessage()); ToastUtils.showToast(R.string.error_500); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); ToastUtils.showToast("Oops! No data found."); } }){ @Override public Map<String, String> getHeaders() { Map<String, String> mHeaders = new HashMap<String, String>(); Preferences prefs = Preferences.getInstance(getActivity()); String apiKey = prefs.getString(Constants.TAG_API_KEY); mHeaders.put(Constants.TAG_HEADER_API_KEY, apiKey); return mHeaders; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, TAG_PRODUCT_DETAIL); } /** * Populate Data get from server using Product Id * @param dataObject Product Details Object from getDataTask() * @throws JSONException */ private void populateData(JSONObject dataObject) throws JSONException { if("".equalsIgnoreCase(getText(dataObject,"image"))) { imageUrl = Constants.NO_IMAGES_URL; }else{ imageUrl = Constants.PRODUCTS_IMAGES_URL+getText(dataObject,"image"); } // thumbnail image mProductPhoto.setImageUrl(imageUrl,imageLoader); mProductName.setText(getText(dataObject,"product_name")); mProductDescription.setText(getText(dataObject,"product_description")); if(!"".equalsIgnoreCase(getText(dataObject,"review_rating")) && !"null".equalsIgnoreCase(getText(dataObject,"review_rating"))) { mProductReting.setRating(Float.parseFloat(getText(dataObject, "review_rating"))); } mProductReting.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { ShowRatingDialog(mProductReting.getRating()); } return true; } }); JSONArray recipiesArray = dataObject.getJSONArray("recipes"); populateRecipies(recipiesArray); JSONArray reviewsArray = dataObject.getJSONArray("reviews"); populateReviews(reviewsArray); } /** * Populate recipes data called from populateData() * @param recipiesArray Recipes List * @throws JSONException */ private void populateRecipies(JSONArray recipiesArray) throws JSONException { if(recipiesArray!=null && recipiesArray.length()>0){ recipiesContainer.removeAllViews(); for (int i = 0; i < recipiesArray.length(); i++) { final JSONObject recipes = recipiesArray.getJSONObject(i); LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.item_recipies, null, false); TextView mNameView = (TextView) view.findViewById(R.id.recipe_name); NetworkImageView mImageView = (NetworkImageView) view.findViewById(R.id.recipe_photo); mNameView.setText(getText(recipes,"recipe_name")); if (imageLoader == null) imageLoader = AppController.getInstance().getImageLoader(); String imageUrl = ""; if("".equalsIgnoreCase(getText(recipes,"recipe_image"))) { imageUrl = Constants.NO_IMAGES_URL; }else{ imageUrl = Constants.RECIPES_IMAGES_URL+getText(recipes,"recipe_image"); } // thumbnail image mImageView.setImageUrl(imageUrl,imageLoader); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), RecipeDetailActivity.class); try { intent.putExtra("recipe-id",getText(recipes,"id")); startActivity(intent); } catch (JSONException e) { e.printStackTrace(); } } }); recipiesContainer.addView(view); } } } /** * Populate Product Reviews * @param reviewsArray * @throws JSONException */ private void populateReviews(JSONArray reviewsArray) throws JSONException { if(reviewsArray!=null && reviewsArray.length()>0){ reviewsContainer.removeAllViews(); for (int i = 0; i < reviewsArray.length(); i++) { final JSONObject reviewObj = reviewsArray.getJSONObject(i); LayoutInflater inflater = LayoutInflater.from(getActivity()); View view = inflater.inflate(R.layout.item_reviews, null, false); TextView mNameView = (TextView) view.findViewById(R.id.userName); TextView mCommentView = (TextView) view.findViewById(R.id.textView); mNameView.setText(String.format("%s %s",getText(reviewObj,"first_name"),getText(reviewObj,"last_name"))); RatingBar mRating = (RatingBar) view.findViewById(R.id.ratingBar); mCommentView.setText(getText(reviewObj,"review_description")); if(!"".equalsIgnoreCase(getText(reviewObj,"review_rating")) && !"null".equalsIgnoreCase(getText(reviewObj,"review_rating"))) { mRating.setRating(Float.parseFloat(getText(reviewObj, "review_rating"))); } reviewsContainer.addView(view); } } } /** * Method to get text from a {@link JSONObject} * @param dataObject JsonObject from which Text to be get * @param key Key for value * @return String Text if exist in this object or an Empty String to avoid NullPointer * @throws JSONException */ private String getText(JSONObject dataObject,String key) throws JSONException { if(dataObject!=null && dataObject.has(key)){ return dataObject.getString(key); } return ""; } /** * Show External Popup for Rate the product * @param ratings current Ratings */ public void ShowRatingDialog(float ratings) { final AlertDialog.Builder popDialog = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View ratingPopup = inflater.inflate(R.layout.rating_pop_up,null); final EditText commentBox = (EditText)ratingPopup.findViewById(R.id.editComment); final RatingBar rating = (RatingBar) ratingPopup.findViewById(R.id.ratingBar); rating.setMax(5); rating.setRating(ratings); popDialog.setTitle("Rate!! "); popDialog.setView(ratingPopup); // Button OK popDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { //txtView.setText(String.valueOf(rating.getProgress())); rateProduct(String.valueOf(rating.getProgress()),commentBox.getText().toString()); dialog.dismiss(); } }) // Button Cancel .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); popDialog.create(); popDialog.show(); } /** * Method to save Ratings to Server. * @param rating Ratings Provided by User * @param comment Comment Provided by User */ private void rateProduct(final String rating,final String comment) { showProgress(); StringRequest jsonObjReq = new StringRequest(Request.Method.POST, Constants.RATE_PRODUCT, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG_PRODUCT_RATE, response); try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.has("type") && jsonObject.getString("type").equalsIgnoreCase("success")) { showSuccess(); } } catch (JSONException e) { e.printStackTrace(); VolleyLog.v(TAG, "Error: " + e.getMessage()); showFailed(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error haour : " + error.getMessage()); showFailed(); } }){ @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); params.put(Constants.TAG_PRODUCT_ID, mProductId); params.put(Constants.TAG_RATING, rating); params.put(Constants.TAG_COMMENT, comment); return params; } @Override public Map<String, String> getHeaders() { Map<String, String> mHeaders = new HashMap<String, String>(); Preferences prefs = Preferences.getInstance(getActivity()); String apiKey = prefs.getString(Constants.TAG_API_KEY); mHeaders.put(Constants.TAG_HEADER_API_KEY, apiKey); return mHeaders; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, TAG_PRODUCT_RATE); } /** * Method to show Success message dialog by animating from hides Progress. */ private void showSuccess(){ getDataTask(mProductId); Activity activity = getActivity(); ((BaseActivity)activity).hideProgressWithSuccess(getString(R.string.rate_success_title),getString(R.string.rate_success_message)); } /** * Method to show Failed message dialog by animating from hides Progress. */ private void showFailed(){ ToastUtils.showToast(R.string.error_500); Activity activity = getActivity(); ((BaseActivity)activity).hideProgressWithError(getString(R.string.oops),getString(R.string.error_500)); } /** * Show Progress Popup from Sweet Dialog Dependency to show a eye catching animation * instead showing default Progress dialog. */ private void showProgress(){ Activity activity = getActivity(); ((BaseActivity)activity).showProgressDialog(); } /** * Provides functionality to share on facebook by loosely coupled from ProductDetailActivity. */ private void ShareOnFb(){ Activity activity = getActivity(); String pName = mProductName.getText().toString(); String pDes = mProductDescription.getText().toString(); ((ProductDetailActivity)activity).shareOnFB(pName,pDes,imageUrl); } }
package edit; import database.DataBase; import info.InfoTable; import search.SelectionQuery; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class InspectorDeletion { private InfoTable infoTable; private PreparedStatement statement; private Connection connection; private String deleteInspector = "DELETE FROM inspector WHERE inspectorID = ?;"; public static String showAllInspectors = "SELECT * FROM inspector"; public InspectorDeletion(InfoTable infoTable){ this.infoTable = infoTable; } public void deleteInspector(String inspectorID) { DataBase db = new DataBase(); try { connection = db.getOpenedConnection(); statement = connection.prepareStatement(deleteInspector); statement.setInt(1, Integer.parseInt(inspectorID)); statement.executeUpdate(); statement.close(); connection.close(); } catch (SQLException ex) { ex.printStackTrace(); } } public void redrawTable(){ infoTable.getTable().removeAll(); SelectionQuery query = new SelectionQuery(showAllInspectors); try { infoTable.updateInspectorTable(query.show(), infoTable.getTable()); query.closeAll(); } catch (SQLException ex) { ex.printStackTrace(); } } }
package br.com.projecthibernate; import java.util.List; import javax.persistence.EntityManager; import org.junit.Test; import dao.GenericDao; import model.Telefone; import model.UsuarioPessoa; public class TesteHibernate { @Test public void addTest() { GenericDao<UsuarioPessoa> genericDao = new GenericDao<UsuarioPessoa>(); UsuarioPessoa usuario = new UsuarioPessoa(); usuario.setEmail("huber.produtos@gmail.com"); usuario.setLogin("huberaba"); usuario.setNome("Ana"); usuario.setSenha("1atl389guh"); usuario.setIdade(45); usuario.setSobrenome("Cristina"); usuario = genericDao.update(usuario); } @Test public void addFone() { GenericDao<Object> genericDao = new GenericDao<>(); UsuarioPessoa usuario = new UsuarioPessoa(); usuario = (UsuarioPessoa) genericDao.finder(new UsuarioPessoa(), 7L); // Pesquiso Telefone telefone = new Telefone("Trabalho", "092", "98402-5926", "120", usuario); telefone.setUsuarioPessoa(usuario); telefone = (Telefone) genericDao.update(telefone); } @Test public void updateTest() { GenericDao<UsuarioPessoa> genericDao = new GenericDao<UsuarioPessoa>(); UsuarioPessoa usuario = new UsuarioPessoa(); usuario = genericDao.finder(new UsuarioPessoa(), 5L); // Pesquiso usuario.setEmail("antonio_gostoso@hmail"); // Altero usuario = genericDao.update(usuario); // Atualizo } @Test public void deleteTest() { GenericDao<UsuarioPessoa> genericDao = new GenericDao<UsuarioPessoa>(); UsuarioPessoa usuario = new UsuarioPessoa(); usuario = genericDao.finder(new UsuarioPessoa(), 4L); // Pesquiso genericDao.delete(usuario, usuario.getId()); } @Test public void listAllTest() { GenericDao<UsuarioPessoa> genericDao = new GenericDao<UsuarioPessoa>(); List<UsuarioPessoa> list = genericDao.listAll(new UsuarioPessoa()); list.forEach(user-> user.getTelefones().forEach(telefone -> System.out.println(telefone.toString()))); } @SuppressWarnings("unchecked") @Test public void listMax() { EntityManager entityManager = HibernateUtil.getEntityManager(); List<UsuarioPessoa> list = entityManager.createQuery(" from usuarios").setMaxResults(2).getResultList(); list.forEach(user -> System.out.println(user)); } @SuppressWarnings("unchecked") @Test public void listByParameter() { EntityManager entityManager = HibernateUtil.getEntityManager(); List<UsuarioPessoa> list = entityManager.createQuery(" from usuarios where nome = :nome or sobrenome = :sobrenome") .setParameter("nome", "huber") .setParameter("sobrenome", "martins") .getResultList(); list.forEach(user -> System.out.println(user)); } @Test public void totalAge() { EntityManager entityManager = HibernateUtil.getEntityManager(); Long sumAge = (Long) entityManager.createQuery("select sum(idade) from usuarios").getSingleResult(); System.out.println("Sum of all ages: " + sumAge); } @SuppressWarnings("unchecked") @Test public void namedQueriesTest() { List<UsuarioPessoa> list = HibernateUtil.getEntityManager().createNamedQuery("UsuarioPessoa.listAll").getResultList(); list.forEach(user -> System.out.println(user)); } }
package main; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.Scanner; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; public class Main{ /** * @param args */ public static Map map = new Map(); public static JFrame frame = new JFrame(); public static Screen scr = new Screen(); public static boolean running = true; public static boolean showGrid = false; public static boolean debug = false; public static boolean painting = false; public static int scrollingSpeed = 8; public static KeyHandler KH = new KeyHandler(); public static MouseHandler MH = new MouseHandler(); public static ScrollwheelHandler SWH = new ScrollwheelHandler(); public static ArrayList<TerrainImage> terrainImages = new ArrayList<TerrainImage>(); public static ArrayList<ClimateImage> climateImages = new ArrayList<ClimateImage>(); public static ArrayList<Terrain> terrains = new ArrayList<Terrain>(); public static ArrayList<Climate> climates = new ArrayList<Climate>(); public static BufferedImage terrainmap = null; public static BufferedImage climatemap = null; public static int mousex = 0; public static int mousey = 0; public static ArrayList<Button> buttons = new ArrayList<Button>(); public static ArrayList<ImageButton> imgButtons = new ArrayList<ImageButton>(); public static Brush brush = new Brush(getHexWidth(), 0, 0); public static BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB); public static Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, new Point(0, 0), "blank cursor"); public static double zoom = 1.0; public static int hexDiameter = 128; public static int hexWidth = 110; public static void main(String[] args) { init(); run(); } public static void init(){ loadClimates(); loadClimateImages(); loadTerrains(); loadTerrainImages(); frame.setResizable(true); frame.setVisible(true); frame.setSize(1280, 800); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.add(scr); frame.addKeyListener(KH); frame.addMouseListener(MH); frame.addMouseWheelListener(SWH); frame.setTitle("Editor v0.3"); updateButtons(); createNewMap(); frame.getContentPane().setCursor(cursor); loadSettings(); } public static void run(){ while(running){ try{ mousex = scr.getMousePosition().x; mousey = scr.getMousePosition().y; }catch(Exception ex){ mousex = 0; mousey = 0; } try{ Thread.sleep(5); map.update(); scr.repaint(); if(readyToUpdateButtons()){ updateButtons(); } if(painting){ paint(); } brush.update(mousex, mousey); }catch(Exception ex){ ex.printStackTrace(System.out); } } } public static BufferedImage getTerrainImage(int terrain){ BufferedImage img = terrainImages.get(0).IMG; for(int i = 0; i < terrainImages.size(); i++){ if(terrainImages.get(i).TERRAIN == terrain){ img = terrainImages.get(i).IMG; break; } } return img; } public static BufferedImage getClimateImageByTerrain(int terrain){ int climate = getClimateId(terrain); BufferedImage img = climateImages.get(0).IMG; for(int i = 0; i < climateImages.size(); i++){ if(climateImages.get(i).CLIMATE == climate){ img = climateImages.get(i).IMG; break; } } return img; } public static BufferedImage getClimateImageByClimate(int climate){ BufferedImage img = climateImages.get(0).IMG; for(int i = 0; i < climateImages.size(); i++){ if(climateImages.get(i).CLIMATE == climate){ img = climateImages.get(i).IMG; break; } } return img; } public static BufferedImage getClimateImageByClimate(String climate){ BufferedImage img = climateImages.get(0).IMG; for(int i = 0; i < climateImages.size(); i++){ if(getClimateName(climateImages.get(i).CLIMATE).equals(climate)){ img = climateImages.get(i).IMG; break; } } return img; } public static int getClimateId(int terrain){ int climate = getClimateId(terrains.get(terrain).CLIMATE); return climate; } public static int getClimateId(String climate){ int id = 0; for(int i = 0; i < climates.size(); i++){ if(climates.get(i).CLIMATE.equals(climate)){ id = i; break; } } return id; } public static String getClimateName(int climate){ return climates.get(climate).CLIMATE; } public static String[] getClimates(){ ArrayList<String> strings = new ArrayList<String>(); for(int i = 0; i < climates.size(); i++){ strings.add(climates.get(i).CLIMATE); } String[] res = new String[strings.size()]; for(int i = 0; i < strings.size(); i++){ res[i] = strings.get(i); } return res; } public static boolean contains(ArrayList<String> a, String e){ boolean temp = false; if(a.size() > 0 && !e.isEmpty()){ for(int i = 0; i < a.size(); i++){ if(a.get(i) != null){ if(a.get(i).equals(e)){ temp = true; break; } } } } return temp; } public static boolean contains(String[] a, String e){ boolean temp = false; if(a.length > 0 && !e.isEmpty()){ for(int i = 0; i < a.length; i++){ if(a[i] != null){ if(a[i].equals(e)){ temp = true; break; } } } } return temp; } public static String[] getTerrainsByClimate(String climate){ ArrayList<String> strings = new ArrayList<String>(); for(int i = 0; i < terrains.size(); i++){ if(terrains.get(i).CLIMATE.equals(climate)){ strings.add(terrains.get(i).TERRAIN); } } String[] res = new String[strings.size()]; for(int i = 0; i < strings.size(); i++){ res[i] = strings.get(i); } return res; } public static void loadTerrainImages(){ try{ terrainImages.clear(); terrainmap = ImageIO.read(new File("data/images/terrainmap.png")); int length = terrainmap.getWidth() / hexDiameter; for(int i = 0; i < length; i++){ TerrainImage TI = new TerrainImage(); BufferedImage img = terrainmap.getSubimage(hexDiameter * i, 0, hexDiameter, hexDiameter); TI.set(img, i); terrainImages.add(TI); } }catch(Exception ex){} } public static void loadClimateImages(){ try{ climateImages.clear(); climatemap = ImageIO.read(new File("data/images/climatemap.png")); int length = climatemap.getWidth() / hexDiameter; for(int i = 0; i < length; i++){ ClimateImage CI = new ClimateImage(); BufferedImage img = climatemap.getSubimage(hexDiameter * i, 0, hexDiameter, hexDiameter); CI.set(img, i); climateImages.add(CI); } }catch(Exception ex){} } public static void loadTerrains(){ try{ terrains.clear(); Scanner reader = new Scanner(new File("data/terrains.txt")); while(reader.hasNextLine()){ reader.nextLine(); String terrain = reader.nextLine(); String climate = reader.nextLine(); String title = reader.nextLine(); int id = Integer.parseInt(reader.nextLine()); terrains.add(new Terrain(terrain, climate, title, id)); } reader.close(); }catch(Exception ex){ex.printStackTrace();} } public static void loadClimates(){ try{ climates.clear(); Scanner reader = new Scanner(new File("data/climates.txt")); while(reader.hasNextLine()){ reader.nextLine(); String climate = reader.nextLine(); String title = reader.nextLine(); int id = Integer.parseInt(reader.nextLine()); climates.add(new Climate(climate, title, id)); } reader.close(); }catch(Exception ex){ex.printStackTrace();} } public static long lastButtonUpdate = 0; public static boolean readyToUpdateButtons(){ if(lastButtonUpdate + 50 <= System.currentTimeMillis()){ lastButtonUpdate = System.currentTimeMillis(); return true; }else{ return false; } } public static void updateButtons(){ buttons.clear(); buttons.add(new Button("scroll speed (+/-): " + scrollingSpeed, "", 10, 0)); buttons.add(new Button("Show grid (space): " + showGrid, "switchshowgrid", 10, 16)); buttons.add(new Button("Mouse: " + mousex + ", " + mousey, "", 10, 32)); buttons.add(new Button("Debug (d): " + debug, "switchdebug", 10, 48)); buttons.add(new Button("Brush size: " + brush.SIZE, "resetBrushsize", 150, 0)); buttons.add(new Button("++++++ (scroll up)", "+brushsize", 150, 16)); buttons.add(new Button("------ (scroll down)", "-brushsize", 150, 32)); buttons.add(new Button("New Map", "clearMap", 150, 48)); buttons.add(new Button("Title: " + map.title, "changeTitle", 300, 0)); buttons.add(new Button("ID: " + map.id, "changeId", 300, 16)); buttons.add(new Button("Save Map", "saveMap", 300, 32)); buttons.add(new Button("Load Map", "loadMap", 300, 48)); buttons.add(new Button("Pos: " + map.x + ", " + map.y + " (r)", "resetmappos", 750, 0)); buttons.add(new Button("Scale: " + map.width + ", " + map.height, "", 750, 16)); buttons.add(new Button("zoom: " + zoom, "", 750, 32)); buttons.add(new Button("++++++ (page up)", "+zoom", 750, 48)); buttons.add(new Button("------ (page down)", "-zoom", 750, 64)); imgButtons.clear(); imgButtons.add(new ImageButton(getClimateImageByClimate(brush.CLIMATE), getClimateName(brush.CLIMATE), "changeBrushClimate", 450, 0, 64, 64)); imgButtons.add(new ImageButton(getTerrainImage(brush.TERRAIN), getTerrainName(brush.TERRAIN), "changeBrushTerrain", 600, 0, 64, 64)); for(int i = 0; i < buttons.size(); i++){ if(buttons.get(i).BOX.intersects(new Rectangle(mousex, mousey, 1, 1))){ buttons.get(i).hover = true; }else{ buttons.get(i).hover = false; } } for(int i = 0; i < imgButtons.size(); i++){ if(imgButtons.get(i).BOX.intersects(new Rectangle(mousex, mousey, 1, 1))){ imgButtons.get(i).hover = true; }else{ imgButtons.get(i).hover = false; } } } public static void createNewMap(){ int responce = JOptionPane.showConfirmDialog(frame, "Create(y) or Load(n)?", "create or load", JOptionPane.YES_NO_CANCEL_OPTION); if(responce == JOptionPane.YES_OPTION){ map.width = Integer.parseInt(JOptionPane.showInputDialog(frame, "Map Width", "12")); map.height = Integer.parseInt(JOptionPane.showInputDialog(frame, "Map Height", "12")); CmdHandler.changeBrushClimate(); CmdHandler.changeBrushTerrain(); map.x = 100; map.y = 150; zoom = 1.0; map.createEmptyMap(); }else if(responce == JOptionPane.NO_OPTION){ Main.loadMap(); } } public static void paint(){ if(map.loaded){ for(int x = 0; x < map.cells.length; x++){ for(int y = 0; y < map.cells[x].length; y++){ if(map.cells[x][y].intersects(brush.BOX)){ map.cells[x][y].mirror(brush); } } } } } public static void exit(){ if(JOptionPane.showConfirmDialog(frame, "Do you want to exit?", "Exit?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){ System.exit(0); } } public static String getTerrainTitle(int terrain){ String title = ""; for(int i = 0; i < terrains.size(); i++){ if(terrains.get(i).ID == terrain){ title = terrains.get(i).TITLE; break; } } return title; } public static String getTerrainName(int terrain){ String name = ""; for(int i = 0; i < terrains.size(); i++){ if(terrains.get(i).ID == terrain){ name = terrains.get(i).TERRAIN; break; } } return name; } public static int getTerrainId(String terrain){ int id = 0; for(int i = 0; i < terrains.size(); i++){ if(terrains.get(i).TERRAIN == terrain){ id = terrains.get(i).ID; break; } } return id; } public static void saveMap(){ JFileChooser fc = new JFileChooser(CmdHandler.lastDirectory); int returnVal = fc.showSaveDialog(frame); CmdHandler.lastDirectory = fc.getCurrentDirectory().getPath(); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); if(file.exists()){ if(file.isFile() && file.getName().substring(file.getName().length() - 3).equals("txt")){ Main.save(file); }else{ JOptionPane.showMessageDialog(frame, "Bad file"); } }else{ if(file.getName().substring(file.getName().length() - 3).equals("txt")){ Main.save(file); }else{ JOptionPane.showMessageDialog(frame, "Bad file, remember to include .txt"); } } } } public static void save(File file){ try{ BufferedWriter pen = new BufferedWriter(new FileWriter(file)); pen.write(map.title + System.getProperty("line.separator")); pen.write(map.id + System.getProperty("line.separator")); pen.write(map.width + System.getProperty("line.separator")); pen.write(map.height + System.getProperty("line.separator")); for(int x = 0; x < map.cells.length; x++){ for(int y = 0; y < map.cells[x].length; y++){ pen.write(x + System.getProperty("line.separator")); pen.write(y + System.getProperty("line.separator")); pen.write(map.cells[x][y].WIDTH + System.getProperty("line.separator")); pen.write(map.cells[x][y].TERRAIN + System.getProperty("line.separator")); } } pen.close(); }catch(Exception ex){ JOptionPane.showMessageDialog(frame, "Error saving file"); } } public static void loadMap(){ JFileChooser fc = new JFileChooser(CmdHandler.lastDirectory); int returnVal = fc.showOpenDialog(frame); CmdHandler.lastDirectory = fc.getCurrentDirectory().getPath(); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); if(file.isFile() && file.getName().substring(file.getName().length() - 3).equals("txt")){ Main.load(file); }else{ JOptionPane.showMessageDialog(frame, "Bad file"); } } map.x = 100; map.y = 150; } public static void load(File file){ try{ map.loaded = false; Scanner reader = new Scanner(file); map.title = reader.nextLine(); map.id = reader.nextLine(); map.width = Integer.parseInt(reader.nextLine()); map.height = Integer.parseInt(reader.nextLine()); map.cells = new Cell[map.width][map.height]; while(reader.hasNextLine()){ int cx = Integer.parseInt(reader.nextLine()); int cy = Integer.parseInt(reader.nextLine()); int width = Integer.parseInt(reader.nextLine()); int ter = Integer.parseInt(reader.nextLine()); int cli = getClimateId(ter); map.cells[cx][cy] = new Cell(width, ter, cli); } reader.close(); map.loaded = true; }catch(Exception ex){ JOptionPane.showMessageDialog(frame, "Error loading file"); } } public static void clearMap(){ if(JOptionPane.showConfirmDialog(frame, "Do you really want to clear the map?", "Rasputinbullar?", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){ createNewMap(); } } public static void zoomOut(){ if(zoom > 1.0 && map.loaded){ //Main.map.x += (Main.map.getWidth() - (Main.map.getWidth() * 0.9)) / 2; //Main.map.y += (Main.map.getHeight() - (Main.map.getHeight() * 0.9)) / 2; zoom -= 0.1; } } public static void zoomIn(){ if(zoom < 5.0 && map.loaded){ //Main.map.x += (Main.map.getWidth() - (Main.map.getWidth() * 1.1)) / 2; //Main.map.y += (Main.map.getHeight() - (Main.map.getHeight() * 1.1)) / 2; zoom += 0.1; } } public static int getHexWidth(){ //return (int) (Main.hexDiameter / 1.547); return hexWidth; } public static void loadSettings(){ try{ Scanner reader = new Scanner(new File("data/settings.txt")); hexDiameter = Integer.parseInt(reader.nextLine().substring(9)); hexWidth = Integer.parseInt(reader.nextLine().substring(6)); reader.close(); }catch(Exception ex){} } }
package com.itheima.day_02.homework.feeder; public class Feeder { public void feed(Animal animal) { animal.drink(); animal.eat(); if (animal instanceof Dog) { ((Dog) animal).swim(); } else if (animal instanceof Frog) { ((Frog) animal).swim(); } } }
package com.buddybank.mdw.ejb.util.eventbus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; public class TransactionListPrefetchSubscriber { private static final Logger logger = LoggerFactory.getLogger("EventBus"); private static final int ITEMS_PER_PAGE = 25; private static final String XF_DATE_FORMAT = "MM/dd/yyyy"; private static final String COMPARATOR_DATE_FORMAT = "yyyyMMdd"; @Subscribe public void transactionListPrefetch(final TransactionListPrefetchEvent e) { // final AccountId accountId = e.getAccountId(); // logger.info("Going to prefetch transactions list for accountId '{}'", accountId); // // final TransactionRequest tr = new TransactionRequestBean(); // final AccountIdBean aib = new AccountIdBean(); // aib.setBranch(""+accountId.getBranch()); // aib.setCategory(""+accountId.getCategory()); // aib.setCurrency(accountId.getCurrency().name()); // aib.setPosition(""+accountId.getPosition()); // aib.setService(""+accountId.getService()); // // trb.setAccountId(aib); // trb.setQueryByPage(true); // trb.setPage(e.getPage()); // trb.setRefreshCacheData(true); // trb.setApiVersion(e.getApiVersion()); // trb.setAppId(e.getAppId()); // trb.setAppVersion(e.getAppVersion()); // trb.setIp("127.0.0.1"); // trb.setQueryByDateInterval(false); // trb.setSecureToken(e.getSecureToken()); // trb.setItemsPerPage(ITEMS_PER_PAGE); // trb.setNDG(e.getNDG()); // try { // CacheManager.getInstance().setTransactions(accountId, e.getPage(), getTransactionsFromXF(trb)); // } catch (final Exception e1) { // logger.error("Caugh exception: stopping execution!", e1); // return; // } } // private List<Transaction> getTransactionsFromXF(final TransactionRequest tr) throws MDWException // { // final List<Movimento> xfResponse = XFAccount.getInstance().getTransactionList(tr); // final List<Transaction> transactions = new ArrayList<Transaction>(xfResponse.size()); // final SimpleDateFormat sdfXF = new SimpleDateFormat(XF_DATE_FORMAT); // final SimpleDateFormat sdfComparator = new SimpleDateFormat(COMPARATOR_DATE_FORMAT); // // for (final Movimento m : xfResponse) // { // if (m==null) // { // //Don't know why but we can enter here when m is null! // continue; // } // final Transaction tb = new Transaction(); // // final Money amount = new Money(); // amount.setAmount(Double.parseDouble(m.getVSEGNM().getValue()+m.getVIMPOM().getValue())); // amount.setCurrency(m.getVMISOS().getValue()); // tb.setAmount(amount); // // final String description = StringUtils.trimToEmpty(m.getVTXT1().getValue()) + // StringUtils.trimToEmpty(m.getVTXT2().getValue()) + // StringUtils.trimToEmpty(m.getVTXT3().getValue()); // tb.setDescription(description); // tb.setTransactionId(Long.parseLong(StringUtils.trimToEmpty(m.getVTXT4().getValue()))); // // try { // final Date moneyDate = sdfXF.parse(m.getVDATVM().getValue()); // tb.setMoneyDate(new com.buddybank.mdw.dataobject.domain.Date(moneyDate)); // } catch (final ParseException e) { // logger.error("Error parsing date '{}' with format '{}'", m.getVDATVM().getValue(), XF_DATE_FORMAT, e); // } // try { // final Date opDate = sdfXF.parse(m.getVDATOM().getValue()); // tb.setOpDate(new com.buddybank.mdw.dataobject.domain.Date(opDate)); // tb.setComparatorDate(sdfComparator.format(sdfXF.parse(m.getVDATOM().getValue()))); // } catch (final ParseException e) { // logger.error("Error parsing date '{}' with format '{}'", m.getVDATOM().getValue(), XF_DATE_FORMAT, e); // } // tb.setTitle(m.getVCAUEM().getValue()); // transactions.add(tb); // } // return transactions; // } }
package base; import handler.ScoreboardHandler; import handler.ScoreboardManager; import org.bukkit.entity.Player; import java.util.HashMap; import java.util.UUID; public class ScoreboardBase { private final HashMap<String, ScoreboardTeam> teams = new HashMap<>(); private final HashMap<UUID, ScoreboardTeam> players = new HashMap<>(); private final HashMap<String, ScoreboardTeam> ranks = new HashMap<>(); private final Sidebar bar = new Sidebar(); public ScoreboardBase() { } public Sidebar getSidebar() { return bar; } public ScoreboardBase addNewTeam(final String name, final String prefix, final String chat, final String suffix, final String scoreboard, final String priority, String permission) { ScoreboardTeam team = new ScoreboardTeam(name, prefix, chat, suffix, scoreboard, priority); teams.put(name, team); ranks.put(permission, team); return this; } public ScoreboardBase unregisterPlayer(final Player player) { ScoreboardManager.getScoreboardHandler(player).destroyScoreboard(); players.remove(player.getUniqueId()); return this; } public ScoreboardTeam getPlayerTeam(final Player player) { return players.get(player.getUniqueId()); } public ScoreboardTeam getTeam(String name) { return teams.get(name); } public ScoreboardBase setScoreboard(final Player player) { String permission = player.isOp() ? "admin" : "default"; players.put(player.getUniqueId(), ranks.get(permission)); new ScoreboardHandler(player).createScoreboard(); return this; } }
package oopConcept; public class oopRun { public static void main(String[] args) { home h=new home(5,"test"); System.out.println(h.numberofDoors); System.out.println(h.nameofThehome); home a = new home(10,"Test1"); System.out.println(a.numberofDoors); System.out.println(a.nameofThehome); home l=new home(12,"test3"); System.out.println(l.numberofDoors); System.out.println(l.nameofThehome); } }
package scheduler; import java.io.IOException; import java.net.ServerSocket; import org.apache.log4j.Logger; /** * manages Server Socket * @author babz * */ public class ClientConnectionManager implements Runnable { @SuppressWarnings("unused") // private static Logger log = Logger.getLogger("class client connection manager"); private static final Logger LOG = Logger.getLogger(ClientConnectionManager.class); private ServerSocket serverSocket; private GTEManager engineManager; private boolean alive = true; public ClientConnectionManager(int tcpPort, GTEManager engineManager) throws IOException { serverSocket = new ServerSocket(tcpPort); this.engineManager = engineManager; } @Override public void run() { while (alive) { try { //da mehrere requests, je request 1 thread benötigt new Thread(new ClientListener(serverSocket.accept(), engineManager.getGTEAssigner())).start(); } catch (IOException e) { // shutdown } } } public void terminate() { alive = false; try { serverSocket.close(); } catch (IOException e) { } } }
package temp; 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 java.sql.*; import javax.servlet.RequestDispatcher; import javax.swing.*; @WebServlet(name = "sprofile", urlPatterns = {"/sprofile"}) public class sprofile extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String sfnm=request.getParameter("txtfnm"); String scnm=request.getParameter("txtcnm"); String sadd=request.getParameter("add"); String scat=request.getParameter("category"); String sphon=request.getParameter("txtmo"); String semail=request.getParameter("txtEM"); String smark=request.getParameter("txtmark"); String sgpa=request.getParameter("txtPA"); String resume=request.getParameter("res"); try { int em=semail.length(); if(em>0) { boolean chk= semail.contains("@"); boolean chk1= semail.contains(".com"); if(chk==true && chk1==true) { RequestDispatcher rd=request.getRequestDispatcher("/studprof.jsp"); rd.forward(request, response); } else { JOptionPane.showMessageDialog(null,"Email should be in neat format"); RequestDispatcher rd=request.getRequestDispatcher("/studprof.jsp"); rd.forward(request, response); } Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost/campus","root",""); Statement st=con.createStatement(); st.executeUpdate("insert into sprofile (snm,cnm,sadd,squal,mno,email,lsemresult,cgpa,resume)values('"+sfnm+"','"+scnm+"','"+sadd+"','"+scat+"','"+sphon+"','"+semail+"',"+smark+","+sgpa+",'"+resume+"')"); JOptionPane.showMessageDialog(null,"Profile created successfully"); RequestDispatcher rd=request.getRequestDispatcher("/studhom.jsp"); rd.forward(request, response); } } catch(Exception ee) { } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package prj.designpatterns.decorator.prototype; /** * 具体组件 * * @author LuoXin * */ public class ConcreteComponent extends Component { @Override public void operate() { System.out.println("我是未装饰的组件"); } }
package com.aisino.invoice.xtjk.po; /** * @ClassName: FwkpQyxx * @Description: * @author: ZZc * @date: 2016年10月11日 下午5:40:16 * @Copyright: 2016 航天信息股份有限公司-版权所有 * */ public class FwkpQyxx{ private Integer ismain; private int xhid;//序号id private String xfsh; private Integer kpjh; private String version; private Integer jsponline; private Integer qylock; private String dzbs; private String wldz; private String fxjlq; private String hybz; private String dqbh; private String qymc; private String xfdzdh; private String xfyhzh; private Integer syfpyjz; private String jsph; private String yssh; private String hxsh; private String qdsj; private String fxicnum; private Integer fjsl; private String sbbbh; private Integer hzfwbs; private String zyjgsq; private String hysq; private Integer nsrxz; private String hylx; private Integer tlqybs; private Integer lxssq; private Integer lxkpsc; private String swjgdm; private String swjgmc; private String gsxx; private Integer iszpsq; private String ythbgjsh; private String reserve; private Integer dxqybs; // private BigDecimal pageNo = new BigDecimal("1"); // private int pageSize = 10; // private BigDecimal totalRecords; // private BigDecimal totalPage; public String getXfsh() { return xfsh; } public void setXfsh(String xfsh) { this.xfsh = xfsh == null ? null : xfsh.trim(); } public Integer getKpjh() { return kpjh; } public void setKpjh(Integer kpjh) { this.kpjh = kpjh; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version == null ? null : version.trim(); } public Integer getJsponline() { return jsponline; } public void setJsponline(Integer jsponline) { this.jsponline = jsponline; } public Integer getQylock() { return qylock; } public void setQylock(Integer qylock) { this.qylock = qylock; } public String getDzbs() { return dzbs; } public void setDzbs(String dzbs) { this.dzbs = dzbs == null ? null : dzbs.trim(); } public String getWldz() { return wldz; } public void setWldz(String wldz) { this.wldz = wldz == null ? null : wldz.trim(); } public String getFxjlq() { return fxjlq; } public void setFxjlq(String fxjlq) { this.fxjlq = fxjlq == null ? null : fxjlq.trim(); } public String getHybz() { return hybz; } public void setHybz(String hybz) { this.hybz = hybz == null ? null : hybz.trim(); } public String getDqbh() { return dqbh; } public void setDqbh(String dqbh) { this.dqbh = dqbh == null ? null : dqbh.trim(); } public String getQymc() { return qymc; } public void setQymc(String qymc) { this.qymc = qymc == null ? null : qymc.trim(); } public String getXfdzdh() { return xfdzdh; } public void setXfdzdh(String xfdzdh) { this.xfdzdh = xfdzdh == null ? null : xfdzdh.trim(); } public String getXfyhzh() { return xfyhzh; } public void setXfyhzh(String xfyhzh) { this.xfyhzh = xfyhzh == null ? null : xfyhzh.trim(); } public Integer getSyfpyjz() { return syfpyjz; } public void setSyfpyjz(Integer syfpyjz) { this.syfpyjz = syfpyjz; } public String getJsph() { return jsph; } public void setJsph(String jsph) { this.jsph = jsph == null ? null : jsph.trim(); } public String getYssh() { return yssh; } public void setYssh(String yssh) { this.yssh = yssh == null ? null : yssh.trim(); } public String getHxsh() { return hxsh; } public void setHxsh(String hxsh) { this.hxsh = hxsh == null ? null : hxsh.trim(); } public String getQdsj() { return qdsj; } public void setQdsj(String qdsj) { this.qdsj = qdsj == null ? null : qdsj.trim(); } public String getFxicnum() { return fxicnum; } public void setFxicnum(String fxicnum) { this.fxicnum = fxicnum == null ? null : fxicnum.trim(); } public Integer getFjsl() { return fjsl; } public void setFjsl(Integer fjsl) { this.fjsl = fjsl; } public String getSbbbh() { return sbbbh; } public void setSbbbh(String sbbbh) { this.sbbbh = sbbbh == null ? null : sbbbh.trim(); } public Integer getHzfwbs() { return hzfwbs; } public void setHzfwbs(Integer hzfwbs) { this.hzfwbs = hzfwbs; } public String getZyjgsq() { return zyjgsq; } public void setZyjgsq(String zyjgsq) { this.zyjgsq = zyjgsq == null ? null : zyjgsq.trim(); } public String getHysq() { return hysq; } public void setHysq(String hysq) { this.hysq = hysq == null ? null : hysq.trim(); } public Integer getNsrxz() { return nsrxz; } public void setNsrxz(Integer nsrxz) { this.nsrxz = nsrxz; } public String getHylx() { return hylx; } public void setHylx(String hylx) { this.hylx = hylx == null ? null : hylx.trim(); } public Integer getTlqybs() { return tlqybs; } public void setTlqybs(Integer tlqybs) { this.tlqybs = tlqybs; } public Integer getLxssq() { return lxssq; } public void setLxssq(Integer lxssq) { this.lxssq = lxssq; } public Integer getLxkpsc() { return lxkpsc; } public void setLxkpsc(Integer lxkpsc) { this.lxkpsc = lxkpsc; } public String getSwjgdm() { return swjgdm; } public void setSwjgdm(String swjgdm) { this.swjgdm = swjgdm == null ? null : swjgdm.trim(); } public String getSwjgmc() { return swjgmc; } public void setSwjgmc(String swjgmc) { this.swjgmc = swjgmc == null ? null : swjgmc.trim(); } public String getGsxx() { return gsxx; } public void setGsxx(String gsxx) { this.gsxx = gsxx == null ? null : gsxx.trim(); } public Integer getIszpsq() { return iszpsq; } public void setIszpsq(Integer iszpsq) { this.iszpsq = iszpsq; } public String getYthbgjsh() { return ythbgjsh; } public void setYthbgjsh(String ythbgjsh) { this.ythbgjsh = ythbgjsh == null ? null : ythbgjsh.trim(); } public String getReserve() { return reserve; } public void setReserve(String reserve) { this.reserve = reserve == null ? null : reserve.trim(); } public int getXhid() { return xhid; } public void setXhid(int xhid) { this.xhid = xhid; } public Integer getIsmain() { return ismain; } public void setIsmain(Integer ismain) { this.ismain = ismain; } public Integer getDxqybs() { return dxqybs; } public void setDxqybs(Integer dxqybs) { this.dxqybs = dxqybs; } @Override public String toString() { return "FwkpQyxx [ismain=" + ismain + ", xhid=" + xhid + ", xfsh=" + xfsh + ", kpjh=" + kpjh + ", version=" + version + ", jsponline=" + jsponline + ", qylock=" + qylock + ", dzbs=" + dzbs + ", wldz=" + wldz + ", fxjlq=" + fxjlq + ", hybz=" + hybz + ", dqbh=" + dqbh + ", qymc=" + qymc + ", xfdzdh=" + xfdzdh + ", xfyhzh=" + xfyhzh + ", syfpyjz=" + syfpyjz + ", jsph=" + jsph + ", yssh=" + yssh + ", hxsh=" + hxsh + ", qdsj=" + qdsj + ", fxicnum=" + fxicnum + ", fjsl=" + fjsl + ", sbbbh=" + sbbbh + ", hzfwbs=" + hzfwbs + ", zyjgsq=" + zyjgsq + ", hysq=" + hysq + ", nsrxz=" + nsrxz + ", hylx=" + hylx + ", tlqybs=" + tlqybs + ", lxssq=" + lxssq + ", lxkpsc=" + lxkpsc + ", swjgdm=" + swjgdm + ", swjgmc=" + swjgmc + ", gsxx=" + gsxx + ", iszpsq=" + iszpsq + ", ythbgjsh=" + ythbgjsh + ", reserve=" + reserve + "]"; } }
package scraper.ui.assertion; import org.assertj.core.api.Assertions; import org.openqa.selenium.Cookie; import scraper.ui.utils.CookiesUtil; import java.util.Set; public class CookiesAssertions { private static final CookiesAssertions ourInstance = new CookiesAssertions(); public static CookiesAssertions getInstance() { return ourInstance; } private CookiesAssertions() { } private CookiesUtil fCookiesUtil = CookiesUtil.getInstance(); public CookiesAssertions assertCookiesAreNotEmpty() { Assertions.assertThat(fCookiesUtil.get().size()).as("Cookies are empty").isGreaterThan(0); return this; } public CookiesAssertions assertNumberOfCookies(int expectedCount) { Assertions.assertThat(fCookiesUtil.get().size()).isEqualTo(expectedCount); return this; } public CookiesAssertions assertCookiesAreEmpty() { Assertions.assertThat(fCookiesUtil.get().size()).as("Cookies are not empty").isEqualTo(0); return this; } public CookiesAssertions assertCookieName(String expectedCookieName) { assertCookiesAreNotEmpty(); Cookie cookie = fCookiesUtil.getCookieByName(expectedCookieName); Assertions.assertThat(cookie).as("Cookie is not present for name: " + expectedCookieName).isNotNull(); Assertions.assertThat(cookie.getName()).isEqualTo(expectedCookieName); return this; } public CookiesAssertions assertCookieValue(String expectedValue) { boolean found = false; assertCookiesAreNotEmpty(); Set<Cookie> cookies = fCookiesUtil.get(); for (Cookie cookie : cookies) { if (cookie.getValue().contains(expectedValue)) { found = true; break; } } Assertions.assertThat(found).as("Cookie is not present for value: " + expectedValue).isTrue(); return this; } public CookiesAssertions assertCookieDomain(String expectedDomain) { boolean found = false; assertCookiesAreNotEmpty(); Set<Cookie> cookies = fCookiesUtil.get(); for (Cookie cookie : cookies) { if (cookie.getDomain().contains(expectedDomain)) { found = true; break; } } Assertions.assertThat(found).as("Cookie is not present for domain: " + expectedDomain).isTrue(); return this; } public CookiesAssertions assertCookiePath(String expectedPath) { boolean found = false; assertCookiesAreNotEmpty(); Set<Cookie> cookies = fCookiesUtil.get(); for (Cookie cookie : cookies) { if (cookie.getPath().contains(expectedPath)) found = true; } Assertions.assertThat(found).as("Cookie is not present for path: " + expectedPath).isTrue(); return this; } public CookiesAssertions assertUserCredentialsNotStored(String cookieName, String userName, String password) { assertCookiesAreNotEmpty(); Assertions.assertThat(fCookiesUtil.getCookiesAsString(cookieName)) .doesNotContain(userName) .doesNotContain(password); return this; } }
package com.example.arti_scream.sqllaws; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class DisplayLaws extends AppCompatActivity { MainActivity.DBHelper dbHelper = new MainActivity.DBHelper(this); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.display_laws); SQLiteDatabase db = dbHelper.getWritableDatabase(); Cursor c = db.query("Laws", null, null, null, null, null,null ); ListView listView = findViewById(R.id.displaylistview); ArrayList<String> theList = new ArrayList<>(); if (c.getCount()==0){ Toast.makeText(DisplayLaws.this, "Empty database", Toast.LENGTH_LONG).show(); }else { while(c.moveToNext()){ theList.add(c.getString(3)); theList.add(c.getString(4)); ListAdapter listadapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList); listView.setAdapter(listadapter); } } } }
package com.z2wenfa.leetcode.basic.array; /** * (初级算法)删除排序数组中的重复项 * 解决方法:使用两个指针,分别指向第一个数与第二个数,首先移动右侧指针, * 如果右侧和左侧一致,右侧指针右移一位,右侧和左侧不一致,左侧右移一位,进行交换。 */ public class RemoveDuplicates { public static void main(String[] args) { int[] arrs = new int[]{1, 2, 2, 3, 4, 4, 4, 5}; int length = new RemoveDuplicates().removeDuplicates(arrs); for (int i = 0; i < length; i++) { System.out.print(arrs[i] + " "); } System.out.println("总长度:" + length); } public int removeDuplicates(int[] nums) { if (nums == null || nums.length == 0) return 0; int left = 0; for (int right = 1; right < nums.length; right++) { if (nums[left] != nums[right]) { nums[++left] = nums[right]; } } return ++left; } }
/* * 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 prop.assignment0; /** * * @author Geoffrey-Port */ public class FactorNode implements INode { private float intt; private ExpressionNode expr; public FactorNode(float intt, ExpressionNode expr) { this.intt = intt; this.expr=expr; //System.out.println("Lexeme:" + value + " " + token); } @Override public Object evaluate(Object[] args) throws Exception { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void buildString(StringBuilder builder, int tabs) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package com.oodles; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OodlesTechApplication { public static void main(String[] args) { SpringApplication.run(OodlesTechApplication.class, args); } }
package mf0227.uf2404.actividad1; import java.util.ArrayList; import java.util.Scanner; import com.ipartek.Utilidades; /** * Crear un proyecto en modo consola que nos muestre un menú de 3 opciones:<br> * <ul> * <li>Calcular la letra del dni</li> * <li>Calcular medida de cm a pulgadas</li> * <li>Salir</li> * </ul> * Hacer que dicho menú se ejecute en bucle hasta que se pulse salir, y si el usuario escoge cada una<br> * de las funciones, que permita introducir los datos correspondientes por teclado para poder dar el<br> * resultado<br> * @author Arturo Montañez Cabanillas * */ import java.util.Scanner; public class EjercicioPractico1B { //variables globales para esta Clase static Scanner sc = null; static String opcion = ""; // opcion seleccionada en el menu por el usuario //constantes static final String OP_DNI = "1"; static final String OP_CONVERSION = "2"; static final String OP_SALIR = "S"; static final char LETRAS_DNI[] = { 'T', 'R', 'W', 'A', 'G', 'M', 'Y', 'F', 'P', 'D', 'X', 'B', 'N', 'J', 'Z', 'S', 'Q', 'V', 'H', 'L', 'C', 'K', 'E' }; public static void main(String[] args) { sc = new Scanner(System.in); boolean salir = false; do { crearMenu(); switch (opcion.toUpperCase()) { case OP_DNI: calcularDNI(); break; case OP_CONVERSION: calcularMedida(); break; case OP_SALIR: salir = true; System.out.println("*********** Fin del programa **************"); break; default: System.out.println("** Error. Elija una opción correcta. **"); } }while(!salir); sc.close(); } private static void crearMenu() { System.out.println("************* MENU **************"); System.out.println(" 1.- Calcular la letra del DNI"); System.out.println(" 2.- Calcular medida de centimetros a pulgadas"); System.out.println(" "); System.out.println(" S - Salir"); System.out.println("************************************"); System.out.println("\n Selecciona una opcion del menu:"); opcion = sc.nextLine(); } private static void calcularDNI() { boolean correcto = false; String numeroDNI = ""; String todoDNI = ""; do { try { System.out.println("Introduzca el número del DNI:"); numeroDNI = sc.nextLine(); todoDNI= calcularLetraDNI(numeroDNI); System.out.println("El DNI es "+ todoDNI); correcto = true; }catch (Exception e) { System.out.println(e.getMessage()); }; }while(!correcto); System.out.println(" "); System.out.println("------------------------------------"); System.out.println(" "); } private static void calcularMedida() { float distancia = 0; boolean correcto = false; String pulgadas = ""; do { try { System.out.println("Introduce una distancia en centimetros:"); distancia = Float.parseFloat(sc.nextLine()); correcto = true; }catch (Exception e) { System.out.println("Debes introducir un número correcto, o poner un punto como separador decimal"); } }while (!correcto); //Formateo para que las pulgadas salgan con dos decimales. pulgadas = String.format(" %.2f",distancia*0.39379); System.out.println(distancia + " centimetros son " + pulgadas + " pulgadas."); System.out.println("------------------------------------"); System.out.println(" "); } private static String calcularLetraDNI ( String numeroDNI ) throws Exception { char letra; if (numeroDNI == null) { throw new Exception("Debe introducir un numero"); } try { int posicion = Integer.parseInt(numeroDNI) % 23; letra = LETRAS_DNI[posicion]; }catch (Exception e) { throw new Exception("'" + numeroDNI +"' no es un número de DNI correcto"); } //En caso de que numeroDNI sea un numero, pero no tenga la longitud adecuada if ( numeroDNI.length() != 8 ) { throw new Exception("Para tener un DNI correcto se necesita un número de 8 dígitos"); } return numeroDNI + letra; } }
package servicenow.datamart; import java.io.File; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ LoaderConfigTest.class, DateTimeFactoryTest.class, DBTest.class, CreateTableTest.class, InsertTest.class, PruneTest.class, TimestampTest.class, }) public class AllTests { static public File yamlFile(String name) { assert name != null; return new File("src/test/resources/yaml/" + name + ".yaml"); } }
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeClass; import java.util.concurrent.TimeUnit; /** * Created by Dima on 19.02.2018. */ public class SetUp { WebDriver webDriver; MainPage mainPage; @BeforeClass public void setUp() { System.setProperty("webdriver.chrome.driver", "c:\\automation\\selenium\\chromedriver.exe"); webDriver = new ChromeDriver(); webDriver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS); webDriver.manage().window().maximize(); webDriver.get("https://github.com/"); mainPage = new MainPage(webDriver); // WebDriverWait wait = new WebDriverWait(driver,5); // wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(""))); } @AfterTest public void close() { webDriver.close(); } }
package com.fubang.wanghong.ui; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import com.fubang.wanghong.AppConstant; import com.fubang.wanghong.adapters.HomeTitleAdapter; import com.fubang.wanghong.R; import com.fubang.wanghong.fragment.MyItemFragment_; import com.fubang.wanghong.fragment.VipFragment_; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.ViewById; import java.util.ArrayList; import java.util.List; /** * 特权页面 */ @EActivity(R.layout.activity_privilege) public class PrivilegeActivity extends BaseActivity { @ViewById(R.id.privilege_tablayout) TabLayout tabLayout; @ViewById(R.id.privilege_viewpage) ViewPager viewPager; @ViewById(R.id.privilege_back_btn) ImageView backImage; private List<Fragment> fragments = new ArrayList<>(); private List<String> titles = new ArrayList<>(); @Override public void initView() { backImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); for (int i = 0; i < AppConstant.MY_TYPE_TITLE.length; i++) { titles.add(AppConstant.MY_TYPE_TITLE[i]); } fragments.add(VipFragment_.builder().arg(AppConstant.HOME_TYPE,titles.get(0)).build()); fragments.add(VipFragment_.builder().arg(AppConstant.HOME_TYPE,titles.get(1)).build()); fragments.add(VipFragment_.builder().arg(AppConstant.HOME_TYPE,titles.get(2)).build()); fragments.add(VipFragment_.builder().arg(AppConstant.HOME_TYPE,titles.get(3)).build()); HomeTitleAdapter adapter = new HomeTitleAdapter(getSupportFragmentManager(),fragments,titles); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); tabLayout.setTabMode(TabLayout.MODE_FIXED); } }
package com.example.bookspace; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; public class SplashActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences pref = getSharedPreferences("AppPreferences", MODE_PRIVATE); if(pref.contains("token")) startActivity(new Intent(getApplicationContext(), user_page.class)); else { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); } } }
package com.imooc.config; import com.imooc.service.OrdersService; import com.imooc.utils.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class OrderTask { private static final Logger logger = LoggerFactory.getLogger(OrderTask.class); @Autowired private OrdersService ordersService; /** * 使用定时任务关闭超时未支付订单,存在的弊端 * 1.存在时间差,程序不严谨 * 10点39下单,11点检查不足一小时,12点检查超过一小时39分钟(假如一小时超时关闭订单) * 2.不支持集群 * 如果使用集群后,会有多个定时任务,操作一个数据库 * 解决方案:只使用一个节点来执行定时任务 * 3.会对数据库进行全表扫描,影响数据库性能 * 后续会使用消息队列来解决这些问题 * 延时任务(队列) * 10点39下单,11点39检查,如果超时,直接关闭,不会出现问题(假如一小时超时关闭订单) */ @Scheduled(cron = "${autoCloseOrder.task.timerTask}") public void autoCloseOrder(){ ordersService.closeOrder(); logger.info("正在执行超时未支付订单自动关闭定时任务!当前时间为:{}", DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN)); System.out.println("正在执行超时未支付订单自动关闭定时任务!当前时间为:{}"+ DateUtil.getCurrentDateString(DateUtil.DATETIME_PATTERN)); } }
package java8.nashorn; import java.io.FileNotFoundException; import java.io.FileReader; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class CallingJSFunctionInJava { public static void main(String[] args) { // Creating script engine ScriptEngine ee = new ScriptEngineManager().getEngineByName("Nashorn"); // Reading Nashorn file try { ee.eval(new FileReader("F:/java_programs/Advanced Features/src/java8/nashorn/hello2.js")); } catch (FileNotFoundException | ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } Invocable invocable = (Invocable)ee; // calling a function try { invocable.invokeFunction("functionDemo1"); } catch (NoSuchMethodException | ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } // calling a function and passing variable as well. try { invocable.invokeFunction("functionDemo2","Nashorn"); } catch (NoSuchMethodException | ScriptException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.biz.controller; import java.util.Random; import com.biz.model.ScoreVO; public class Score_Exec_03 { public static void main(String[] args) { // ScoreVO 클래스를 이용해서 10개의 배열을 생성하고 // 번호는 순서대로 설정하고 // 이름은 입력하지 않고 // kor, eng, math 점수를 각각 난수로 생성해서 저장 // 단, 점수는 51 ~ 100까지 // 입력(저장된)값을 콘솔에서 확인하고 // 총점과 평균을 계산해 봅시다. Random rnd = new Random(); ScoreVO[] sVOs = new ScoreVO[10]; for (int i = 0; i < sVOs.length; i++) { sVOs[i] = new ScoreVO(); // num 필드를 private으로 선언했기때문에 // sVOs[i].number 코드는 사용불가 // number필드는 String형인데 i값은 int형이다 == sVOs[i].setNumber(i); <=오류발생 // 따라서 nuber필드에 값을 저장하기 위해서는 // int형을 String 형으로 변환시켜야 한다. // 기존의 자바 전통 문법 // sVOs[i].setNumber(Integer.toString(i + 1)); // 문자열 + 숫자형 은 문자열 취급을 한다. sVOs[i].setNumber("" + (i + 1)); // "" 은 문자열 i+1은 int형 i+1를 먼저실행하도록 ()이용 int intkor = rnd.nextInt(50) + 51; int inteng = rnd.nextInt(50) + 51; int intmath = rnd.nextInt(50) + 51; // 따로 변수를 만들지않고 rnd.nextInt(50)+51;를 넣는 방법도있음 sVOs[i].setKor(intkor); sVOs[i].setEng(inteng); sVOs[i].setMath(intmath); // 따로 변수를 만들었을 경우 int intTotal = intkor + inteng + intmath ; 사용가능 // int intTotal = intkor // intTotal += inteng // intTotal += intmath int intTotal = sVOs[i].getKor(); intTotal += sVOs[i].getEng(); intTotal += sVOs[i].getMath(); sVOs[i].setTotal(intTotal); sVOs[i].setAverage(intTotal / 3); System.out.println(sVOs[i].toString()); } // 총점을 별도로 계산 // for (ScoreVO vo : sVOs){ // int intkor = vo.getKor(); // int inteng = vo.getEng(); // int intmath = vo.getMath(); // } // for(ScoreVO vo : sVOs){ // System.out.println(sVOs.toString()); //} } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.onlinejudge.IntegerToRoman; /** * */ public class IntegerToRomanCalculativeImpl implements IntegerToRoman { @Override public String intToRoman(int num) { return null; //To change body of implemented methods use File | Settings | File Templates. } /** * class Solution { public: string intToRoman(int num) { const static char* Roman = "IVXLCDM"; string ret; for (int base = 0; num; num /= 10, base += 2) { int x = num % 10; switch (x) { case 1: case 2: case 3: ret = string(x, Roman[base]) + ret; break; case 4: ret = Roman[base+1] + ret; ret = Roman[base] + ret; break; case 5: ret = Roman[base+1] + ret; break; case 6: case 7: case 8: ret = string(x-5, Roman[base]) + ret; ret = Roman[base+1] + ret; break; case 9: ret = Roman[base+2] + ret; ret = Roman[base] + ret; break; default: break; } } return ret; } }; */ }
package cyfixusBot.game.entities; import java.util.Random; public abstract class Avatar extends Entity{ protected byte strength; protected byte stamina; protected byte intelligence; protected byte will; protected CyClass cyClass; private Random random = new Random(); public Avatar(float x, float y, ObjectID id) { super(x, y, id); generateStats(); } private void generateStats(){ strength = (byte)(random.nextInt(6)+4); stamina = (byte)(random.nextInt(6)+4); intelligence = (byte)(random.nextInt(6)+4); will = (byte)(random.nextInt(6)+4); } public byte getStrength(){ return strength; } public byte getStamina(){ return stamina; } public byte getIntelligence(){ return intelligence; } public byte getWill(){ return will; } public void setStrength(byte strength){ this.strength = strength; } public void setStamina(byte stamina){ this.stamina = stamina; } public void setIntelligence(byte intelligence){ this.intelligence = intelligence; } public void setWill(byte will){ this.will = will; } public void incStrength(byte strength){ this.strength += strength; } public void incStamina(byte stamina){ this.stamina += stamina; } public void incIntelligence(byte intelligence){ this.intelligence += intelligence; } public void incWill(byte will){ this.will += will; } }
package com.gxtc.huchuan.ui.mine.editinfo; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TextInputEditText; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.gxtc.commlibrary.base.BaseTitleActivity; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.R; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.http.ApiObserver; import com.gxtc.huchuan.http.ApiResponseBean; import com.gxtc.huchuan.http.service.MineApi; import com.gxtc.huchuan.utils.RegexUtils; import java.util.HashMap; import java.util.Map; import butterknife.BindView; import butterknife.OnClick; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by zzg on 2017/2/23. * 编辑昵称 */ public class BindEPayActivity extends BaseTitleActivity { @BindView(R.id.et_user_name) TextInputEditText mEtUserName; @BindView(R.id.et_nike_name) TextInputEditText mEtNikeName; @BindView(R.id.iv_delete) ImageView mIvDelete; private String mNikeName; private Subscription sub; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_epay_number); initData(); } @Override public void initData() { super.initData(); getBaseHeadView().showTitle(getString(R.string.title_epay_card)); getBaseHeadView().showCancelBackButton(getString(R.string.label_cancel), new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getBaseHeadView().showHeadRightButton(getString(R.string.label_save), new View.OnClickListener() { @Override public void onClick(View v) { nikeNameSave(); } }); mEtNikeName.addTextChangedListener(new EditTextWatcher()); } @OnClick({R.id.iv_delete}) public void onClick(View view) { switch (view.getId()){ case R.id.iv_delete: mEtNikeName.setText(""); break; } } private void nikeNameSave() { if (TextUtils.isEmpty(mEtNikeName.getText().toString())){ ToastUtil.showShort(this,getString(R.string.epay_number_canot_empty)); }else { // finish(); BindEpay(); } } private void BindEpay() { if (TextUtils.isEmpty(mEtNikeName.getText().toString())){ ToastUtil.showShort(this,"账号不能为空"); return; } if (TextUtils.isEmpty(mEtUserName.getText().toString())){ ToastUtil.showShort(this,"用户名不能为空"); return; } HashMap<String,String> map=new HashMap<>(); map.put("token", UserManager.getInstance().getToken()); map.put("withdrawCashType","2");//账户类型。1:微信;2:支付宝;3:银行卡 map.put("userAccount",mEtNikeName.getText().toString()); map.put("userName",mEtUserName.getText().toString()); sub=MineApi.getInstance().bindAccount(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new ApiObserver<ApiResponseBean<Object>>(new ApiCallBack() { @Override public void onSuccess(Object data) { ToastUtil.showShort(BindEPayActivity.this,"绑定成功"); setResult(); } @Override public void onError(String errorCode, String message) { ToastUtil.showShort(BindEPayActivity.this,message); } })); } public void setResult(){ Intent intent=new Intent(); intent.putExtra("paynumber",mEtNikeName.getText().toString()); setResult(RESULT_OK,intent); finish(); } @Override protected void onDestroy() { super.onDestroy(); if(sub != null && sub.isUnsubscribed()){ sub.unsubscribe(); } } /** * 编辑框监听 */ class EditTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (!TextUtils.isEmpty(mEtNikeName.getText().toString())) { mIvDelete.setVisibility(View.VISIBLE); } else { mIvDelete.setVisibility(View.INVISIBLE); } } } }
package com.lbo.foursquare.model; import java.util.List; public class SimpleVenue { public String id; public String name; public Location location; public List<Category> categories; }
package testSWE; public class TestRepeat { public static void main(String[] args) { System.out.println("Case 1: REPEAT: " + "\n Expect output : I want REPEAT go to REPEAT zoo" + "\n Real Output : " +repeat.Replace("I want to to go to the zoo")); System.out.println("Case 1: REPEAT: " + "\n Expect output : I want REPEAT go to REPEAT zoo" + "\n Real Output : " +repeat.Replace("I want to to go to the zoo")); System.out.println("Case 1: REPEAT: " + "\n Expect output : I want REPEAT go to REPEAT zoo" + "\n Real Output : " +repeat.Replace("I want to To go to the zoo")); System.out.println("Case 1: REPEAT: " + "\n Expect output : I want REPEAT go to REPEAT zoo" + "\n Real Output : " +repeat.Replace("I want to To go to the zoo")); } }
package com.github.fierioziy.particlenativeapi.core.asm.particle.type.v1_8; import com.github.fierioziy.particlenativeapi.core.asm.ContextASM; import com.github.fierioziy.particlenativeapi.core.asm.particle.type.v1_8.skeleton.ParticleTypeComplexSkeletonASM_1_8; import com.github.fierioziy.particlenativeapi.core.asm.skeleton.ClassSkeleton; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.MethodVisitor; public class ParticleTypeBlockASM_1_8 extends ParticleTypeComplexSkeletonASM_1_8 { public ParticleTypeBlockASM_1_8(ContextASM context, ClassSkeleton superType, ClassSkeleton returnType) { super(context, superType, returnType); } @Override protected void writeMethods(ClassWriter cw) { writeMethod_of(cw); writeCommonMethods(cw); } private void writeMethod_of(ClassWriter cw) { MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, OF_METHOD_NAME, "(" + refs.material.desc() + "B)" + interfaceReturnType.desc(), null, null); mv.visitCode(); int local_this = 0; int local_material = 1; int local_meta = 2; int local_particleType = 3; /* ParticleTypeImpl_X particleType = this.particleWrapper; */ mv.visitVarInsn(ALOAD, local_this); mv.visitFieldInsn(GETFIELD, implType.internalName(), PARTICLE_WRAPPER_FIELD_NAME, implReturnType.desc()); mv.visitVarInsn(ASTORE, local_particleType); /* particleType.setParticle( this.particle, new int[] { material.getId(), material.getId() | (meta << 12) } ); */ mv.visitVarInsn(ALOAD, local_particleType); // get particle from field mv.visitVarInsn(ALOAD, local_this); mv.visitFieldInsn(GETFIELD, implType.internalName(), PARTICLE_FIELD_NAME, refs.enumParticle.desc()); // new int[2] mv.visitInsn(ICONST_2); mv.visitIntInsn(NEWARRAY, T_INT); mv.visitInsn(DUP); mv.visitInsn(ICONST_0); // operating on above array // dataArr[0] = material.getId() mv.visitVarInsn(ALOAD, local_material); mv.visitMethodInsn(INVOKEVIRTUAL, refs.material.internalName(), "getId", "()I", false); mv.visitInsn(IASTORE); mv.visitInsn(DUP); mv.visitInsn(ICONST_1); // dataArr[1] = material.getId() | (meta << 12); mv.visitVarInsn(ALOAD, local_material); mv.visitMethodInsn(INVOKEVIRTUAL, refs.material.internalName(), "getId", "()I", false); mv.visitVarInsn(ILOAD, local_meta); mv.visitLdcInsn(12); mv.visitInsn(ISHL); mv.visitInsn(IOR); mv.visitInsn(IASTORE); mv.visitMethodInsn(INVOKEVIRTUAL, implReturnType.internalName(), SET_PARTICLE_METHOD_NAME, "(" + refs.enumParticle.desc() + "[I)V", false); // return particleType; mv.visitVarInsn(ALOAD, local_particleType); mv.visitInsn(ARETURN); mv.visitMaxs(0, 0); mv.visitEnd(); } }
package MVC.views; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import MVC.controllers.deletePartController; import MVC.models.inventoryModel; public class errorView extends JFrame{ private inventoryModel model; private JPanel deletePanel = new JPanel(); private JLabel confirm; private JButton Button = new JButton("OK"); private String[] errorArray = new String[10]; public errorView (inventoryModel model){ super("Error!"); this.model = model; errorArray = model.getErrorArray(); for(int i=0;i<errorArray.length;i++){ confirm = new JLabel(errorArray[i]); deletePanel.add(confirm); } deletePanel.add(Button); this.add(deletePanel); Button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { resetErrors(); closeWindow(); } }); } public void registerListeners(deletePartController controller) { Button.addActionListener(controller); } public void resetErrors(){ model.resetErrors(); } public void closeWindow (){ this.dispose(); } }
package br.com.Bytebank.Banco.testes; import br.com.Bytebank.Banco.modelo.Cliente; import br.com.Bytebank.Banco.modelo.ContaCorrente; import br.com.Bytebank.Banco.modelo.ContaPoupanca; public class TesteObject { public static void main(String[] args) { ContaCorrente cc = new ContaCorrente(123, 32123); ContaPoupanca cp = new ContaPoupanca(122, 212121); Cliente c = new Cliente(); System.out.println(cc.toString()); System.out.println(cp.toString()); System.out.println(); } }
package amery.entity; import lombok.Builder; import lombok.Data; /** * Created by ahan on 23/02/2017. */ @Builder @Data public class Room { private String name; private int id; }
package io.empyre.commands; import io.empyre.util.ChatUtil; import org.apache.commons.lang.math.NumberUtils; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.HumanEntity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; public class CmdDamage implements TabExecutor { @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { if (sender.hasPermission("empyre.damage")) { if (args.length >= 2) { Player target = Bukkit.getPlayer(args[0]); if (target != null && NumberUtils.isNumber(args[1])) { double damage = Double.parseDouble(args[1]); target.damage(damage); target.sendMessage(ChatUtil.cl("&cYou have been smitten!")); sender.sendMessage(ChatUtil.cl("&8You damaged &b" + target.getName() + " &8for &b" + damage + " &8damage!")); } else { sender.sendMessage(ChatUtil.cl("&cInvalid args!")); } } else { sender.sendMessage(ChatUtil.cl("&cInvalid args!")); } } else { sender.sendMessage(ChatUtil.cl("&cYou don't have permission to do that!")); } return true; } @Override public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { if (args.length == 1) { return Bukkit.getOnlinePlayers().stream().map(HumanEntity::getName).collect(Collectors.toList()); } else { return Collections.singletonList("(damage amount)"); } } }
package server.sport.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import server.sport.model.Responsibility; import server.sport.model.Sport; import java.util.List; import java.util.Optional; public interface ResponsibilityRepository extends JpaRepository<Responsibility, Integer> { List<Responsibility> findAllBySport(Sport sport); }
package com.liuyufei.bmc_android.utility; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** * Created by Ying Chen on 06/21/17. */ public class DateUtil { // init private static final Map<String, String> DATE_FORMAT_REGEXPS = new HashMap<String, String>() {{ put("^\\d{8}$", "yyyyMMdd"); put("^\\d{1,2}-\\d{1,2}-\\d{4}$", "dd-MM-yyyy"); put("^\\d{4}-\\d{1,2}-\\d{1,2}$", "yyyy-MM-dd"); put("^\\d{1,2}/\\d{1,2}/\\d{4}$", "MM/dd/yyyy"); put("^\\d{4}/\\d{1,2}/\\d{1,2}$", "yyyy/MM/dd"); put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}$", "dd MMM yyyy"); put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}$", "dd MMMM yyyy"); put("^\\d{12}$", "yyyyMMddHHmm"); put("^\\d{8}\\s\\d{4}$", "yyyyMMdd HHmm"); put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}$", "dd-MM-yyyy HH:mm"); put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy-MM-dd HH:mm"); put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}$", "MM/dd/yyyy HH:mm"); put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy/MM/dd HH:mm"); put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMM yyyy HH:mm"); put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMMM yyyy HH:mm"); put("^\\d{14}$", "yyyyMMddHHmmss"); put("^\\d{8}\\s\\d{6}$", "yyyyMMdd HHmmss"); put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd-MM-yyyy HH:mm:ss"); put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy-MM-dd HH:mm:ss"); put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "MM/dd/yyyy HH:mm:ss"); put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy/MM/dd HH:mm:ss"); put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMM yyyy HH:mm:ss"); put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMMM yyyy HH:mm:ss"); }}; // 1. check date format public static String determineDateFormat(String dateString) { for (String regexp : DATE_FORMAT_REGEXPS.keySet()) { if (dateString.toLowerCase().matches(regexp)) { return DATE_FORMAT_REGEXPS.get(regexp); } } return null; // Unknown format. } // 2. get remain hours public static Hashtable getRemainingTime(Date date) throws ParseException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); java.util.Date now = Calendar.getInstance().getTime(); long l=now.getTime()-date.getTime(); long day=l/(24*60*60*1000); long hour=(l/(60*60*1000)-day*24); long min=((l/(60*1000))-day*24*60-hour*60); Hashtable alarm = new Hashtable<String, Long>(); alarm.put("day",day); alarm.put("hour",hour); alarm.put("min",min); return alarm; } }
package com.flowedu.dto; import lombok.Data; @Data public class StudentSimpleMemoDto { private Long studentSimpleMemoId; private Long studentId; private Long flowMemberId; private String memoContent; private String createDate; }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package mif18.orm; import java.io.Serializable; import javax.persistence.*; /** * * @author BJ */ @Entity public class Producteur implements Serializable{ private int id; private String nom; @Id @GeneratedValue // "id" est une primary key (et not null) public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } }
package com.niall.nmdb.entities; import java.util.HashMap; import java.util.Map; import java.util.Objects; public class Movie { private String title; private int id; private String image; private String rating; private String language; private int userRating; public Map<String, Object> toMap(){ HashMap<String, Object> result = new HashMap<>(); result.put("title", title); result.put("id", id); result.put("image", image); result.put("rating", rating); result.put("language", language); return result; } public Movie(){ } public Movie(String image,String title, String rating, String language) { this.image = image; this.title = title; this.rating = rating; this.language = language; } public String getRating() { return rating; } public void setRating(String rating) { this.rating = rating; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public int getUserRating() { return userRating; } public void setUserRating(int userRating) { this.userRating = userRating; } @Override public String toString() { return "Movie{" + "title='" + title + '\'' + ", id=" + id + ", image='" + image + '\'' + ", rating='" + rating + '\'' + ", language='" + language + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Movie movie = (Movie) o; return id == movie.id && Objects.equals(title, movie.title) && Objects.equals(image, movie.image) && Objects.equals(language, movie.language); } @Override public int hashCode() { return Objects.hash(title, id, image, language); } }
package com.rsmartin.arquitecturamvvm.repository; import androidx.arch.core.util.Function; import androidx.lifecycle.LiveData; import androidx.lifecycle.Transformations; import com.rsmartin.arquitecturamvvm.AppExecutors; import com.rsmartin.arquitecturamvvm.utils.AbsentLiveData; import com.rsmartin.arquitecturamvvm.utils.RateLimiter; import com.rsmartin.arquitecturamvvm.api.ApiResponse; import com.rsmartin.arquitecturamvvm.api.WebServiceApi; import com.rsmartin.arquitecturamvvm.db.GitHubDb; import com.rsmartin.arquitecturamvvm.db.RepoDao; import com.rsmartin.arquitecturamvvm.model.Contributor; import com.rsmartin.arquitecturamvvm.model.Repo; import com.rsmartin.arquitecturamvvm.model.RepoSearchResponse; import com.rsmartin.arquitecturamvvm.model.RepoSearchResult; import java.util.List; import java.util.concurrent.TimeUnit; import javax.inject.Inject; import javax.inject.Singleton; /** * Se encargara de acceder a nuestro Webservice y a RepoDao */ @Singleton public class RepoRepository { private final GitHubDb db; private final RepoDao repoDao; private final WebServiceApi githubService; private final AppExecutors appExecutors; private RateLimiter<String> repoListRateLimit = new RateLimiter<>(10, TimeUnit.MINUTES); @Inject public RepoRepository(AppExecutors appExecutors, GitHubDb db, RepoDao repoDao, WebServiceApi githubService) { this.appExecutors = appExecutors; this.db = db; this.repoDao = repoDao; this.githubService = githubService; } public LiveData<Resource<List<Repo>>> loadRepos(String owner){ return new NetworkBoundResource<List<Repo>, List<Repo>>(appExecutors){ @Override protected boolean shouldFetchData(List<Repo> data) { return data == null || data.isEmpty() || repoListRateLimit.shouldFetch(owner); } @Override protected LiveData<List<Repo>> loadFromDb() { return repoDao.loadRepositories(owner); } @Override protected void saveCallResult(List<Repo> item) { repoDao.insertRepos(item); } @Override protected LiveData<ApiResponse<List<Repo>>> createCall() { return githubService.getRepos(owner); } @Override protected void onFetchFailed(){ repoListRateLimit.reset(owner); } }.asLiveData(); } public LiveData<Resource<Repo>> loadRepo(String owner, String name){ return new NetworkBoundResource<Repo, Repo>(appExecutors){ @Override protected boolean shouldFetchData(Repo data) { return data == null; } @Override protected LiveData<Repo> loadFromDb() { return repoDao.load(owner, name); } @Override protected void saveCallResult(Repo item) { repoDao.insert(item); } @Override protected LiveData<ApiResponse<Repo>> createCall() { return githubService.getRepo(owner, name); } }.asLiveData(); } public LiveData<Resource<List<Contributor>>> loadContributors(String owner, String name){ return new NetworkBoundResource<List<Contributor>, List<Contributor>>(appExecutors){ @Override protected boolean shouldFetchData(List<Contributor> data) { return data == null || data.isEmpty(); } @Override protected LiveData<List<Contributor>> loadFromDb() { return repoDao.loadContributors(owner, name); } @Override protected void saveCallResult(List<Contributor> contributors) { for(Contributor contributor: contributors){ contributor.setRepoName(name); contributor.setRepoOwner(owner); } db.beginTransaction(); try{ repoDao.createRepoIfNotExists(new Repo(Repo.UNKNOWN_ID, name, owner + "/" + name, "", 0, new Repo.Owner(owner, null))); repoDao.insertContributors(contributors); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override protected LiveData<ApiResponse<List<Contributor>>> createCall() { return githubService.getContributors(owner, name); } }.asLiveData(); } public LiveData<Resource<Boolean>> searchNextPage(String query){ FetchNextSearchPageTask fetchNextSearchPageTask = new FetchNextSearchPageTask(query, githubService, db); appExecutors.networkIO().execute(fetchNextSearchPageTask); return fetchNextSearchPageTask.getLiveData(); } public LiveData<Resource<List<Repo>>> search(String query){ return new NetworkBoundResource<List<Repo>, RepoSearchResponse>(appExecutors){ @Override protected boolean shouldFetchData(List<Repo> data) { return data == null; } @Override protected LiveData<List<Repo>> loadFromDb() { return Transformations.switchMap(repoDao.search(query), new Function<RepoSearchResult, LiveData<List<Repo>>>() { @Override public LiveData<List<Repo>> apply(RepoSearchResult searchData) { if(searchData == null){ return AbsentLiveData.create(); } else { return repoDao.loadOrdered(searchData.repoIds); } } }); } @Override protected void saveCallResult(RepoSearchResponse item) { List<Integer> repoIds = item.getRepoIds(); RepoSearchResult repoSearchResult = new RepoSearchResult(query, repoIds, item.getTotal(), item.getNextPage()); db.beginTransaction(); try{ repoDao.insertRepos(item.getItems()); repoDao.insert(repoSearchResult); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override protected LiveData<ApiResponse<RepoSearchResponse>> createCall() { return githubService.searchRepos(query); } @Override protected RepoSearchResponse processResponse(ApiResponse<RepoSearchResponse> response){ RepoSearchResponse body = response.body; if(body != null){ body.setNextPage(response.getNextPage()); } return body; } }.asLiveData(); } }
package com.kacperwozniak.customer.controller; import com.kacperwozniak.customer.model.Customer; import com.kacperwozniak.customer.service.CustomerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.Optional; @RestController @RequestMapping(value = "/restapi/customer") public class CustomerController { @Autowired CustomerService customerService; @GetMapping(value = "/getCustomer/{creditId}") public Optional<Customer> getCustomer(@PathVariable("creditId") int creditId){ return customerService.getCustomer(creditId); } @GetMapping(value = "/getCustomers") public List<Customer> getCustomers(){ return customerService.getCustomers(); } @PostMapping(value = "/createCustomer") public void createCustomer(@RequestBody Customer customer){ customerService.createCustomer(customer); } }
/* * Copyright (c) 2020 Omega Launcher * * 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.saggitt.omega.allapps; import android.content.Context; import android.util.AttributeSet; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.android.launcher3.Insettable; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.allapps.AllAppsContainerView; import com.android.launcher3.allapps.FloatingHeaderView; import com.android.launcher3.appprediction.ComponentKeyMapper; import com.android.launcher3.appprediction.PredictionRowView; import com.android.launcher3.appprediction.PredictionUiStateManager; import java.util.List; public class PredictionsFloatingHeader extends FloatingHeaderView implements Insettable { private final PredictionUiStateManager mPredictionUiStateManager; private Context mContext; private boolean mShowAllAppsLabel; private PredictionRowView mPredictionRowView; public PredictionsFloatingHeader(@NonNull Context context) { this(context, null); } public PredictionsFloatingHeader(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); mContext = context; mPredictionUiStateManager = PredictionUiStateManager.INSTANCE.get(context); } @Override protected void onFinishInflate() { super.onFinishInflate(); mPredictionRowView = findViewById(R.id.prediction_row); updateShowAllAppsLabel(); } @Override public void setup(AllAppsContainerView.AdapterHolder[] mAH, boolean tabsHidden) { mTabsHidden = tabsHidden; updateExpectedHeight(); super.setup(mAH, tabsHidden); } public void updateShowAllAppsLabel() { setShowAllAppsLabel(Utilities.getOmegaPrefs(mContext).getShowAllAppsLabel()); } public void setShowAllAppsLabel(boolean show) { if (mShowAllAppsLabel != show) { mShowAllAppsLabel = show; } } public PredictionRowView getPredictionRowView() { return mPredictionRowView; } public boolean hasVisibleContent() { return mPredictionUiStateManager.getCurrentState().isEnabled; } public void setPredictedApps(boolean enabled, List<ComponentKeyMapper> list) { mPredictionUiStateManager.getCurrentState().apps = list; mPredictionUiStateManager.getCurrentState().isEnabled = enabled; mPredictionUiStateManager.onAppsUpdated(); } }
package org.imo.gisis.xml.lrit._2008; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.xml.bind.annotation.XmlSeeAlso; import org.imo.gisis.xml.lrit.ddprequest._2008.DDPRequestType; import org.imo.gisis.xml.lrit.receipt._2008.ReceiptType; import org.imo.gisis.xml.lrit.systemstatus._2008.SystemStatusType; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.1.3-b02- * Generated source version: 2.1 * */ @WebService(name = "ddpPortType", targetNamespace = "http://gisis.imo.org/XML/LRIT/2008") @SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE) @XmlSeeAlso({ org.imo.gisis.xml.lrit.ddprequest._2008.ObjectFactory.class, org.imo.gisis.xml.lrit.receipt._2008.ObjectFactory.class, org.imo.gisis.xml.lrit._2008.ObjectFactory.class, org.imo.gisis.xml.lrit.types._2008.ObjectFactory.class, org.imo.gisis.xml.lrit.systemstatus._2008.ObjectFactory.class }) public interface DdpPortType { /** * * @param params * @return * returns org.imo.gisis.xml.lrit._2008.Response */ @WebMethod(operationName = "DDPRequest") @WebResult(name = "Response", targetNamespace = "http://gisis.imo.org/XML/LRIT/2008", partName = "params") public Response ddpRequest( @WebParam(name = "DDPRequest", targetNamespace = "http://gisis.imo.org/XML/LRIT/ddpRequest/2008", partName = "params") DDPRequestType params); /** * * @param params * @return * returns org.imo.gisis.xml.lrit._2008.Response */ @WebMethod(operationName = "Receipt") @WebResult(name = "Response", targetNamespace = "http://gisis.imo.org/XML/LRIT/2008", partName = "params") public Response receipt( @WebParam(name = "Receipt", targetNamespace = "http://gisis.imo.org/XML/LRIT/receipt/2008", partName = "params") ReceiptType params); /** * * @param params * @return * returns org.imo.gisis.xml.lrit._2008.Response */ @WebMethod(operationName = "SystemStatus") @WebResult(name = "Response", targetNamespace = "http://gisis.imo.org/XML/LRIT/2008", partName = "params") public Response systemStatus( @WebParam(name = "SystemStatus", targetNamespace = "http://gisis.imo.org/XML/LRIT/systemStatus/2008", partName = "params") SystemStatusType params); }
package slimeknights.tconstruct.plugin.jei.interpreter; import mezz.jei.api.ISubtypeRegistry.ISubtypeInterpreter; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagList; import slimeknights.tconstruct.library.utils.TagUtil; // Handles all Tinker tool parts subtypes public class ToolSubtypeInterpreter implements ISubtypeInterpreter { @Override public String getSubtypeInfo(ItemStack stack) { StringBuilder builder = new StringBuilder(); builder.append(stack.getItemDamage()); // just pull the list of materials from the NBT, no need to convert to materials then back again NBTTagList materials = TagUtil.getBaseMaterialsTagList(stack); if(materials.getTagType() == TagUtil.TAG_TYPE_STRING) { builder.append(':'); for(int i = 0; i < materials.tagCount(); i++) { // looks nicer if there is no comma at the start if(i != 0) { builder.append(','); } builder.append(materials.getStringTagAt(i)); } } return builder.toString(); } }
package tictactoe; import java.util.Scanner; public class tictactoe_main { static final int COMPUTER = 1; static final int USER = 0; // For test, these will be removed when program released static final int CONTINUE = 0; static final int USER_WIN = 1; static final int COMPUTER_WIN = 2; static final int NO_WIN = 3; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String state = "Yes"; // Make array map int[][] map = new int[3][3]; LoadSave loadSaveHandler = new LoadSave(); // Array initialize SaveMakeClean(map); Computer ai = new Computer(); int turn = USER; int flag = CONTINUE; LogicCheck check = new LogicCheck(); Print.origin(); RockPaperSissor ordergame = new RockPaperSissor(); turn=ordergame.RPS(); while(state.toLowerCase().charAt(0) == 'y') { // Handle input (in InputHandle, Logic check will be called and return that value) if (turn == COMPUTER) { System.out.println("<<computer>>"); ai.computerInput(map); flag = check.ScoreCheck(map); } else { InputHandle.run(map); flag = check.ScoreCheck(map); } // Save try { loadSaveHandler.save("load_save.txt", map); } catch (Exception e) { System.out.println(e.getMessage()); } Print.show(map); if (flag != CONTINUE) { if (turn == USER_WIN) { // User win process System.out.println("You win!!"); } else if(turn == COMPUTER_WIN) { // Computer win process System.out.println("Computer win!!"); } else { System.out.println("no winner!!"); } System.out.print("Do you want to play game again? (Y/N) "); state = scanner.next(); if (state.toLowerCase().charAt(0) == 'y') { SaveMakeClean(map); turn = USER; continue; } } turn = (turn == COMPUTER) ? USER : COMPUTER; } scanner.close(); } private static void SaveMakeClean(int[][]array) { int i=0; int j=0; for(i=0;i<3;i++) { for(j=0;j<3;j++) { array[i][j] = 0; } } } }
package oasispv.pv; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.StrictMode; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.sql.Connection; import java.sql.SQLException; public class MainActivity extends AppCompatActivity { private DBhelper dbhelper; private SQLiteDatabase dbs; Button btnini; TextView txtuser; TextView txtpwd; ConnectOra db = ConnectOra.getInstance(); Connection conexion; @Override protected void onCreate(Bundle savedInstanceState) { dbhelper = DBhelper.getInstance(getApplicationContext()); dbs = dbhelper.getWritableDatabase(); super.onCreate(savedInstanceState); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitNetwork().build(); StrictMode.setThreadPolicy(policy); setContentView(R.layout.activity_main); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); btnini = (Button) findViewById(R.id.btnini); txtuser = (TextView) findViewById(R.id.usrtxt); txtpwd = (TextView) findViewById(R.id.pwdtxt); final TextView txtturno = (TextView) findViewById(R.id.txtturno); btnini.setText(variables.movi_desc); btnini.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String usr = txtuser.getText().toString().trim(); String pwd = txtpwd.getText().toString().trim(); int loging ; try { loging = db.getlogin(usr, pwd); } catch (Exception e) { loging = 2; } if (loging == 1) { variables.mesero = txtuser.getText().toString().trim(); variables.turno = Integer.parseInt(txtturno.getText().toString()); dbs.delete(DBhelper.TABLE_SESION, null, null); ContentValues cv = new ContentValues(); cv.put(DBhelper.SES_MESERO, variables.mesero); cv.put(DBhelper.SES_MOVI, variables.movi); cv.put(DBhelper.SES_FASE, variables.fase); cv.put(DBhelper.SES_STATUS, "A"); dbs.insert(DBhelper.TABLE_SESION, null, cv); Intent intent = new Intent(getApplicationContext(), tables.class); startActivity(intent); } else if (loging == 2) { Toast.makeText(getApplicationContext(), "Favor de revisar Conexion", Toast.LENGTH_LONG).show(); } else { Toast.makeText(getApplicationContext(), "Favor de revisar Usuario y Contraseña", Toast.LENGTH_LONG).show(); } } }); //// Datos Turno txtturno.setText("1"); Button btnmenost = (Button) findViewById(R.id.btnmenostu); btnmenost.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int turno = Integer.parseInt(txtturno.getText().toString()); if (turno == 1) { txtturno.setText("1"); } else { turno = turno - 1; txtturno.setText(Integer.toString(turno)); } } }); Button btnmast = (Button) findViewById(R.id.btnmastu); btnmast.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int turno = Integer.parseInt(txtturno.getText().toString()); if (turno == 3) { txtturno.setText("3"); } else { turno = turno + 1; txtturno.setText(Integer.toString(turno)); } } }); //Mantener Wifi Activo wifiManager.keepWiFiOn(getApplicationContext(), true); } @Override protected void onDestroy() { super.onStop(); dbs.close(); try { conexion.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package com.dian.diabetes.activity.sugar; import java.util.List; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.chart.PointStyle; import org.achartengine.model.XYMultipleSeriesDataset; import org.achartengine.model.XYSeries; import org.achartengine.renderer.XYMultipleSeriesRenderer; import org.achartengine.renderer.XYSeriesRenderer; import android.graphics.Color; import android.graphics.Paint.Align; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.LinearLayout.LayoutParams; import com.dian.diabetes.R; import com.dian.diabetes.db.dao.Diabetes; import com.dian.diabetes.tool.CommonUtil; import com.dian.diabetes.widget.anotation.ViewInject; /** * 录入图表fragment * @author hua * */ public class EntryChartFragment extends EntryBaseFragment { @ViewInject(id = R.id.chart) private RelativeLayout chart; private GraphicalView lineChart; // chart private XYMultipleSeriesDataset dataSet; private XYMultipleSeriesRenderer mRenderer; private SugarEntryFragment fragment; // private float alignment[]; public static EntryChartFragment getInstance() { EntryChartFragment fragment = new EntryChartFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ContantsUtil.ENTRY_UPDATE_VIEW = false; dataSet = new XYMultipleSeriesDataset(); XYSeries series = new XYSeries("血糖线"); dataSet.addSeries(series); getRender(); fragment = (SugarEntryFragment) getParentFragment(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_entry_chart, container, false); fieldView(view); initView(view); return view; } private void initView(View view) { loadChart(); // if(!ContantsUtil.ENTRY_UPDATE_VIEW){ // alignment = new float[]{ // Config.getFloatPro("levelLow" + ContantsUtil.EAT_PRE), // Config.getFloatPro("levelHigh" + ContantsUtil.EAT_PRE) }; // ContantsUtil.ENTRY_UPDATE_VIEW = true; // } new DataTask().execute(); } @Override public void loadEntryData(List<Diabetes> data) { new DataTask().execute(); } private void loadData(List<Diabetes> data) { mRenderer.clearXTextLabels(); dataSet.clear(); XYSeries series = new XYSeries("血糖线"); int index = 0; for (int i = 0; i < data.size(); i++) { Diabetes item = data.get(i); series.add(i, (double) (Math.round(item.getValue() * 100)) / 100); mRenderer.addXTextLabel( i, CommonUtil.getValue("diabetes" + item.getType() + item.getSub_type())); index = i; } // if ("今天".equals(fragment.getDay())) { // if (subType == 0) { // subType++; // } else { // subType = 0; // type++; // } // for (int i = type; i < 4; i++) { // for (int j = subType; j < 2; j++) { // index++; // mRenderer.addXTextLabel(index, // CommonUtil.getValue("diabetes" + i + j)); // } // subType = 0; // } // mRenderer.removeXTextLabel(index); // mRenderer.setXAxisMax(index - 1); // } else { if (index == 0) { index = 1; } mRenderer.setXAxisMax(index); // } // 准线 // mRenderer.setAlign(alignment); // mRenderer.setAlignColors(new int[] { Color.RED, // Color.rgb(136, 204, 153), Color.RED }); // mRenderer.setAlignLineColor(Color.rgb(120, 253, 100)); dataSet.addSeries(series); lineChart.repaint(); } @SuppressWarnings("deprecation") private void loadChart() { lineChart = ChartFactory.getLineChartView(context, dataSet, mRenderer); chart.addView(lineChart, 0, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); } private XYMultipleSeriesRenderer getRender() { if (mRenderer != null) { return mRenderer; } float size = getResources().getDimension(R.dimen.text_size_14); mRenderer = new XYMultipleSeriesRenderer(); mRenderer .setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL); mRenderer.setYAxisMin(0);// 设置y轴最小值是0 mRenderer.setYAxisMax(29.9); mRenderer.setZoomEnabled(false, false); mRenderer.setPanEnabled(false, false); mRenderer.setShowGrid(true); mRenderer.setYLabelsPadding(10); mRenderer.setLabelsTextSize(size); mRenderer.setAxisTitleTextSize(size); mRenderer.setLegendTextSize(size); mRenderer.setXLabelsAlign(Align.CENTER); mRenderer.setYLabelsAlign(Align.CENTER); mRenderer.setLabelsColor(Color.BLACK); mRenderer.setShowAxes(false); mRenderer.setShowLegend(false); mRenderer.setShowLabels(true); mRenderer.setApplyBackgroundColor(true); mRenderer.setBackgroundColor(Color.WHITE); mRenderer.setMarginsColor(Color.WHITE); mRenderer.setXLabelsPadding(getResources().getDimension( R.dimen.text_size_14)); // 画一条线 XYSeriesRenderer r = new XYSeriesRenderer();// (类似于一条线对象) r.setColor(Color.rgb(136, 204, 153));// 设置颜色 r.setPointStyle(PointStyle.CIRCLE);// 设置点的样式 r.setDisplayChartValues(true); r.setDisplayChartValuesDistance(1); r.setChartValuesTextSize(size); r.setFillBelowLine(true);// 是否填充折线图的下方 r.setFillBelowLineColor(Color.argb(40, 136, 204, 153));// 填充的颜色,如果不设置就默认与线的颜色一致 r.setLineWidth(2);// 设置线宽 mRenderer.addSeriesRenderer(r); return mRenderer; } private class DataTask extends AsyncTask<Object, Object, Object> { @Override protected Object doInBackground(Object... arg0) { fragment.getData(); return null; } @Override protected void onPostExecute(Object result) { loadData(fragment.getData()); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hw1.q02; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author yribbens */ public class AnimalTest { @Test public void CowTest() { Cow aCow = new Cow(); String expectedType = "Cow"; String actualType = aCow.getType(); assertEquals("Cow",expectedType,actualType); String expectedSound = "moo"; String actualSound = aCow.getSound(); assertEquals("Cow Sound",expectedType,actualType); } @Test public void DuckTest() { Duck aDuck = new Duck(); String expectedType = "Duck"; String actualType = aDuck.getType(); assertEquals("Duck",expectedType,actualType); String expectedSound = "quack"; String actualSound = aDuck.getSound(); assertEquals("Duck Sound",expectedType,actualType); } @Test public void GazelleTest() { Gazelle aGazelle = new Gazelle(); String expectedType = "gazelle"; String actualType = aGazelle.getType(); assertEquals("Gazelle",expectedType,actualType); String expectedSound = ""; String actualSound = aGazelle.getSound(); assertEquals("Gazelle Sound",expectedType,actualType); } @Test public void HorseTest() { Horse aHorse = new Horse(); String expectedType = "Horse"; String actualType = aHorse.getType(); assertEquals("Horse",expectedType,actualType); String expectedSound = "neigh"; String actualSound = aHorse.getSound(); assertEquals("Horse Sound",expectedType,actualType); } }
package com.daypos.cart; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.recyclerview.widget.RecyclerView; import com.daypos.R; import com.daypos.container.DrawerData; import com.daypos.fragments.home.ProductData; import java.text.DecimalFormat; import java.util.ArrayList; public class CartAdapter extends RecyclerView.Adapter<CartAdapter.myViewHolder> { private Context context; private ArrayList<CartData> cartDataArrayList; private static DecimalFormat df = new DecimalFormat("0.00"); public CartAdapter(Context context, ArrayList<CartData> data) { this.context = context; this.cartDataArrayList = data; } @Override public CartAdapter.myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context) .inflate(R.layout.cart_item, parent, false); return new myViewHolder(view); } @Override public void onBindViewHolder(CartAdapter.myViewHolder holder, int position) { CartData cartData = cartDataArrayList.get(position); holder.tv_product_name.setText(cartData.getProduct_name()); holder.tv_quantity.setText("X "+cartData.getQty()); holder.tv_product_name.setText(cartData.getProduct_name()); try { float price = Float.parseFloat(cartData.getPrice()); int qty = Integer.parseInt(cartData.getQty()); float total_price = price * qty; holder.tv_calculate_price.setText(df.format(total_price)); }catch (Exception e){ e.printStackTrace(); } holder.tv_quantity.setOnClickListener(v -> { mClickListenerEdit.onItemClickEdit(position, cartData); }); holder.delete_iv.setOnClickListener(v -> { mClickListenerDetete.onItemClickDelete(position, cartData); }); } @Override public int getItemCount() { return cartDataArrayList.size(); } public class myViewHolder extends RecyclerView.ViewHolder { ImageView delete_iv; TextView tv_product_name, tv_quantity, tv_calculate_price; public myViewHolder(View itemView) { super(itemView); delete_iv = itemView.findViewById(R.id.delete_iv); tv_product_name = itemView.findViewById(R.id.tv_product_name); tv_quantity = itemView.findViewById(R.id.tv_quantity); tv_calculate_price = itemView.findViewById(R.id.tv_calculate_price); } } private ItemClickListenerEdit mClickListenerEdit; private ItemClickListenerDetete mClickListenerDetete; public void setClickListenerEdit(ItemClickListenerEdit itemClickListener) { this.mClickListenerEdit = itemClickListener; } public void setClickListenerDetete(ItemClickListenerDetete itemClickListener) { this.mClickListenerDetete = itemClickListener; } public interface ItemClickListenerEdit { void onItemClickEdit(int position, CartData cartData); } public interface ItemClickListenerDetete { void onItemClickDelete(int position, CartData cartData); } }
/** * */ package org.apache.hadoop.mapreduce.lib.output; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.util.Iterator; import java.util.regex.Matcher; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.util.TreeMultiMap; import sun.nio.ch.DirectBuffer; /** * @author tim */ public class TextTextRecordReader extends RecordReader<Text, Text> { private ByteBuffer buffer; private StringBuilder sb; // TODO // need to do something sensible here. // Hadoop splits the data during submission so knows the number of rows upfront // since it can ask for the number of splits // We on the other hand chunk into blocks for mappers, and then split into records in // parallel before we ever know how many rows are in a chunk. An ordered row number is therefore // not possible to deduce private static long rowNumber = 0; private Text rowText; private Text keyText; //protected RecordParser recParser; protected Iterator iterator; private byte[] barray; protected int bufferLength; protected BufferedReader br; protected String line; protected ByteArrayInputStream bstream; public static final char lineTerminator = '\n'; private final static int MASK = 0x000000FF; private String[] tokens; private int ind = 0; private Matcher lineMatcher; @Override public Text getCurrentKey() { return keyText; } @Override public Text getCurrentValue() { return rowText; } @Override public void initialize(ByteBuffer input) { // make a read only copy just in case //buffer = input.asReadOnlyBuffer(); input.rewind(); buffer = input; // Charset charset = Charset.forName("UTF-8"); // CharsetDecoder decoder = charset.newDecoder(); // try { // buffer = decoder.decode(input); // } catch (CharacterCodingException ex) { // Logger.getLogger(LineRecordReader.class.getName()).log(Level.SEVERE, null, ex); // } //buffer.rewind(); rowText = new Text(); keyText = new Text(); sb = new StringBuilder(); // Pattern linePattern = Pattern.compile(".*$", Pattern.MULTILINE); // lineMatcher = linePattern.matcher(buffer); // //System.out.println("Initial bytebuffer size: " + MemoryUtil.deepMemoryUsageOf(buffer)); } @Override public void initialize(byte[] input) { // make a read only copy just in case //buffer = input.asReadOnlyBuffer(); barray = input; rowText = new Text(); sb = new StringBuilder(); //index = 0; bufferLength = barray.length; bstream = new ByteArrayInputStream(barray); br = new BufferedReader(new InputStreamReader(bstream)); } // @Override // public boolean nextKeyValue() { // try { // if ((line = br.readLine()) != null) { // rowNumber++; // rowText.set(line); // return true; // } else { // br.close(); // bstream.close(); // } // } catch (IOException ex) { // //Logger.getLogger(LineRecordReader.class.getName()).log(Level.SEVERE, null, ex); // } // return false; // } // @Override // public boolean nextKeyValue() { // // while (index < bufferLength) { // char value = (char) barray[index++]; // if (lineTerminator == value || index == bufferLength) { // rowNumber++; // rowText.set(sb.toString()); // //// String[] tokenArray = line.split(" "); //// int len1 = tokenArray.length; //// for (int j = 0; j < len1; ++j) { //// data.add(tokenArray[j]); //// //Thread.yield(); //// } // //strArray.add(line); // //System.out.println(line); // sb.setLength(0); // return true; // } else { // sb.append(value); // } // } // barray = null; // return false; // } public static void unmap(MappedByteBuffer buffer) { sun.misc.Cleaner cleaner = ((DirectBuffer) buffer).cleaner(); cleaner.clean(); } @Override public final boolean nextKeyValue() { // For each line // while (lineMatcher.find()) { // // Get line // CharSequence line = lineMatcher.group(); // rowText.set(line.toString()); // // return true; // } while (buffer.hasRemaining()) { final char value = (char) (buffer.get() & MASK); //final char value = buffer.get(); if (lineTerminator == value || !buffer.hasRemaining()) { if (!buffer.hasRemaining()) { sb.append(value); //Thread.yield(); } rowNumber++; rowText.set(sb.toString()); //System.out.println(sb.toString()); //Thread.yield(); sb.setLength(0); return true; } else { sb.append(value); //Thread.yield(); } //Thread.yield(); } //sb = null; //buffer = null; //LineRecordReader.unmap((MappedByteBuffer)buffer); return false; } @Override public void initialize(final TreeMultiMap<WritableComparable, WritableComparable> input) { throw new UnsupportedOperationException("Not supported yet."); } @Override public boolean nextKeyValue(final int ind) { throw new UnsupportedOperationException("Not supported yet."); } @Override public Object getKeyDataValue() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void initialize(byte[] input, byte[] offsets, int offsetSize) { throw new UnsupportedOperationException("Not supported yet."); } }
package com.gk.service; import java.util.List; import com.gk.entities.College; public interface CollegeService { public List<College> getAll(); public boolean batchAdd(List<College> colleges); public College getCollegeById(Integer id); public College getCollegeByObject(College college); }
import Staff.Management.Director; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class DirectorTest { Director director; @Before public void before(){ director = new Director("Peter Jackson", "GB224466",175000, "Weta", 20000000); } @Test public void canGetDeptName(){ assertEquals("Weta", director.getDeptName()); } @Test public void canRaiseSalary(){ director.raiseSalary(25000); assertEquals(200000, director.getSalary(), 0.01); } @Test public void canPayBonus(){ assertEquals(3500, director.payBonus(), 0.01); } @Test public void canGetName(){ assertEquals("Peter Jackson", director.getName()); } @Test public void canGetNatInsNum(){ assertEquals("GB224466", director.getNatInsNum()); } @Test public void canGetBudget(){ assertEquals(20000000, director.getBudget(), 0.01); } @Test public void cannotHaveNegativeRaise(){ director.raiseSalary(-25000); assertEquals(175000, director.getSalary(), 0.01);; } @Test public void canChangeName(){ director.setName("Steven Speilberg"); assertEquals("Steven Speilberg", director.getName()); } @Test public void cannotSetNullName(){ director.setName(null); assertEquals("Peter Jackson", director.getName()); } }
/* * (C) Copyright IBM Corp. 2020. * * 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.ibm.cloud.cloudant.v1.model; import com.google.gson.annotations.SerializedName; import com.ibm.cloud.sdk.core.service.model.GenericModel; /** * Schema for information about a geospatial index. */ public class GeoIndexInformation extends GenericModel { @SerializedName("geo_index") protected GeoIndexStats geoIndex; protected String name; /** * Gets the geoIndex. * * Schema for geospatial index statistics. * * @return the geoIndex */ public GeoIndexStats getGeoIndex() { return geoIndex; } /** * Gets the name. * * The name of the geospatial index design document. * * @return the name */ public String getName() { return name; } }
package com.explore.service.Impl; import com.explore.common.ServerResponse; import com.explore.dao.CampusMapper; import com.explore.dao.SourceMapper; import com.explore.pojo.Campus; import com.explore.pojo.Source; import com.explore.service.ISourceService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Service public class SourceServiceImpl implements ISourceService { @Autowired SourceMapper sourceMapper; @Autowired CampusMapper campusMapper; @Override public ServerResponse addSource(Source source) { int count = sourceMapper.insertSelective(source); if(count==1) { return ServerResponse.createBySuccessMessage("增加资源成功"); } return ServerResponse.createByErrorMessage("增加资源失败"); } @Override public ServerResponse showSources() { List<HashMap<String,Object>> allData=new ArrayList<>(); List<Source> sources = sourceMapper.showSources(); for(int i=0;i<sources.size();i++) { Campus campus = campusMapper.selectByPrimaryKey(sources.get(i).getCampusId()); HashMap<String,Object> data=new HashMap<>(); data.put("source",sources.get(i)); data.put("campus",campus); allData.add(data); } return ServerResponse.createBySuccess(allData); } @Override public ServerResponse reviseSource(Source source) { int count = sourceMapper.updateByPrimaryKeySelective(source); if(count==1) { return ServerResponse.createBySuccessMessage("修改资源成功"); } return ServerResponse.createByErrorMessage("修改资源失败"); } @Override public ServerResponse deleteSource(Integer id) { int count = sourceMapper.deleteByPrimaryKey(id); if(count==1) { return ServerResponse.createBySuccessMessage("删除资源成功"); } return ServerResponse.createByErrorMessage("删除资源失败"); } @Override public ServerResponse showSource(Source source) { List<HashMap<String,Object>> allData=new ArrayList<>(); List<Source> sources = sourceMapper.showSource(source); for(int i=0;i<sources.size();i++) { Campus campus = campusMapper.selectByPrimaryKey(sources.get(i).getCampusId()); HashMap<String,Object> data=new HashMap<>(); data.put("source",sources.get(i)); data.put("campus",campus); allData.add(data); } return ServerResponse.createBySuccess(allData); } @Override public Integer allCount() { return sourceMapper.selectAllCount(); } }
package robustgametools.guide; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import butterknife.ButterKnife; import butterknife.InjectView; import robustgametools.adapter.DownloadedGuideListAdapter; import robustgametools.playstation_guide.R; import robustgametools.util.Storage; public class MyGuideFragment extends Fragment { @InjectView(R.id.downloaded_guides) ListView mDownloadedList; @InjectView(R.id.empty) TextView mEmptyMessage; private OnFragmentInteractionListener mListener; private ArrayList<String> mDownloadedTitle; private DownloadedGuideListAdapter mAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_my_guide, container, false); ButterKnife.inject(this, view); mDownloadedTitle = new ArrayList<>(); refreshDownloadedList(); showDownloadedGuides(); return view; } public void refreshDownloadedList() { if (getActivity() != null) { Storage storage = Storage.getInstance(getActivity()); ArrayList<String> newList = storage.getGuideList(); mDownloadedTitle.clear(); mDownloadedTitle.addAll(newList); if (mAdapter != null) { mAdapter.notifyDataSetChanged(); } if (!mDownloadedTitle.isEmpty()) { mEmptyMessage.setVisibility(View.GONE); } else { mEmptyMessage.setVisibility(View.VISIBLE); } } } private void showDownloadedGuides() { mAdapter = new DownloadedGuideListAdapter(getActivity(), mDownloadedTitle); mDownloadedList.setAdapter(mAdapter); mDownloadedList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mListener.onDownloadedGuideSelected(mDownloadedTitle.get(position)); } }); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnFragmentInteractionListener { public void onDownloadedGuideSelected(String name); } }
package com.sheza.bombie; public class LevelDefinition { private String filename; private int width; private int height; private int nbOfColumns; private int nbOfRows; public String getFilename() { return filename; } public int getNbOfColumns() { return nbOfColumns; } public int getNbOfRows() { return nbOfRows; } public int getWidth() { return width; } public int getHeight() { return height; } public static class Builder { private String filename; private int width; private int height; private int nbOfColumns; private int nbOfRows; public Builder filename(String filename) { this.filename = filename; return this; } public Builder width(int width) { this.width = width; return this; } public Builder height(int height) { this.height = height; return this; } public Builder nbOfColumns(int nbOfColumns) { this.nbOfColumns = nbOfColumns; return this; } public Builder nbOfRows(int nbOfRows) { this.nbOfRows = nbOfRows; return this; } public LevelDefinition build() { return new LevelDefinition(this); } } private LevelDefinition(Builder builder) { this.filename = builder.filename; this.width = builder.width; this.height = builder.height; this.nbOfColumns = builder.nbOfColumns; this.nbOfRows = builder.nbOfRows; } }
package com.sul.person.service.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Spy; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; import com.sul.rest.service.RestApplication; import com.sul.rest.service.controller.PersonRestController; import com.sul.rest.service.dto.PersonDTO; import com.sul.rest.service.dto.PersonError; import com.sul.rest.service.messaging.event.EventPublisher; import com.sul.rest.service.repository.PersonJpaRepository; /** * @author sulaiman * * Testing PersonRestController: Database must be connected */ @RunWith(SpringRunner.class) @SpringBootTest(classes = RestApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class PersonRestControllerIntegrationTest { @Spy private PersonRestController restController; @Mock private PersonJpaRepository personJpaRepository; @Mock private EventPublisher applicationEventPublisher; @Before public void setup() { restController = new PersonRestController(); restController.setPersonJpaRepository(personJpaRepository); restController.setApplicationEventPublisher(applicationEventPublisher); } @Test public void getPersonByIdNotFoundTest() { ResponseEntity<PersonDTO> response = restController.getPersonById(11l); assertNotNull(response); assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); assertNotNull(response.getBody()); assertTrue(response.getBody() instanceof PersonError); } @Test public void getPersonByIdTest() { PersonDTO person = new PersonDTO(); person.setId(11l); person.setName("Test"); when(personJpaRepository.getPersonById(11l)).thenReturn(person); ResponseEntity<PersonDTO> response = restController.getPersonById(11l); assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode()); PersonDTO responseBody = response.getBody(); assertNotNull(responseBody); assertEquals("Test", responseBody.getName()); assertEquals(new Long(11), responseBody.getId()); } @Test public void createPersonTest() { PersonDTO person = new PersonDTO(); person.setId(11l); person.setName("Test"); when(personJpaRepository.getPersonByName("Test")).thenReturn(null); ResponseEntity<PersonDTO> response = restController.createPerson(person); assertNotNull(response); assertEquals(HttpStatus.CREATED, response.getStatusCode()); PersonDTO responseBody = response.getBody(); assertNotNull(responseBody); assertEquals("Test", responseBody.getName()); assertEquals(new Long(11), responseBody.getId()); } @Test public void createPersonConflictTest() { PersonDTO person = new PersonDTO(); person.setId(11l); person.setName("Test"); when(personJpaRepository.getPersonByName("Test")).thenReturn(new PersonDTO()); ResponseEntity<PersonDTO> response = restController.createPerson(person); assertNotNull(response); assertEquals(HttpStatus.CONFLICT, response.getStatusCode()); assertNotNull(response.getBody()); assertTrue(response.getBody() instanceof PersonError); } @Test public void updatePersonTest() { PersonDTO person = new PersonDTO(); person.setId(11l); person.setName("Test"); when(personJpaRepository.getPersonById(11l)).thenReturn(person); PersonDTO updatedPerson = new PersonDTO(); // id must not be updated updatedPerson.setId(2l); updatedPerson.setName("Test2"); ResponseEntity<PersonDTO> response = restController.updatePerson(11l, updatedPerson); assertEquals(HttpStatus.OK, response.getStatusCode()); PersonDTO responseBody = response.getBody(); assertNotNull(responseBody); assertEquals("Test2", responseBody.getName()); assertEquals(new Long(11), responseBody.getId()); } @Test public void updatePersonNotFoundTest() { PersonDTO personToUpdate = new PersonDTO(); personToUpdate.setId(11l); personToUpdate.setName("Test"); when(personJpaRepository.getPersonByName("Test")).thenReturn(null); ResponseEntity<PersonDTO> response = restController.updatePerson(11l, personToUpdate); assertNotNull(response); assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); assertNotNull(response.getBody()); assertTrue(response.getBody() instanceof PersonError); } @Test public void getAllPersonsTest() { List<PersonDTO> persons = new ArrayList<PersonDTO>(); persons.add(new PersonDTO()); when(personJpaRepository.findAll()).thenReturn(persons); ResponseEntity<List<PersonDTO>> response = restController.getAllPersons(); assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode()); List<PersonDTO> responseBody = response.getBody(); assertNotNull(responseBody); assertEquals(1, responseBody.size()); } @Test public void getAllPersonsNotFoundTest() { List<PersonDTO> persons = new ArrayList<PersonDTO>(); when(personJpaRepository.findAll()).thenReturn(persons); ResponseEntity<List<PersonDTO>> response = restController.getAllPersons(); assertNotNull(response); assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); assertNull(response.getBody()); } @Test public void deltePersonTest() { PersonDTO person = new PersonDTO(); person.setId(11l); when(personJpaRepository.getPersonById(11l)).thenReturn(person); ResponseEntity<PersonDTO> response = restController.deletePerson(11l); assertEquals(HttpStatus.OK, response.getStatusCode()); PersonDTO responseBody = response.getBody(); assertNull(responseBody); } @Test public void deltePersonNotFoundTest() { when(personJpaRepository.getPersonById(11l)).thenReturn(null); ResponseEntity<PersonDTO> response = restController.deletePerson(11l); assertEquals(HttpStatus.NOT_FOUND, response.getStatusCode()); PersonDTO responseBody = response.getBody(); assertNotNull(responseBody); assertTrue(responseBody instanceof PersonError); } @After public void tearDown() { restController = null; } }
package src.farm; import javafx.scene.image.ImageView; import src.entity.Crop; public class FarmPlots { private static ImageView[] farmPlot; private static Crop[] cropsOnFarm; private static int day = 1; private static int extraPlotPrice = 20; private static int water = 5; private static int currWater = 5; private static int previousMax = 4; private static int harvestMax = 4; private static int currHarvest = harvestMax; public static ImageView[] getFarmPlot() { return farmPlot; } public static void setFarmPlot(ImageView[] arr) { farmPlot = arr; } public static Crop[] getCropsOnFarm() { return cropsOnFarm; } public static void setCropsOnFarm(Crop[] arr) { cropsOnFarm = arr; } public static void setCropOnFarm(Crop c, int index) { cropsOnFarm[index] = c; } public static String getDay() { return ("DAY " + day); } public static void incrementDay() { day++; } public static int getDayNum() { return day; } public static int getPlotPrice() { return extraPlotPrice; } public static void incrementPlotPrice() { extraPlotPrice *= 2; } public static int getCurrWaterQuantity() { return currWater; } public static int getWaterQuantity() { return water; } public static void setWaterQuantity(int w) { water = w; } public static void decrementWater() { currWater--; } public static void resetWater() { currWater = water; } public static void setHarvestMax(int max) { harvestMax = max; } public static int getHarvestMax() { return harvestMax; } public static int getPreviousMax() { return previousMax; } public static void resetPreviousMax() { previousMax = harvestMax; } public static int getCurrHarvest() { return currHarvest; } public static void setCurrHarvest(int x) { currHarvest = x; } }
package rs2.time; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * * @author Jake Bellotti * @since 1.0 */ public class EventManager implements Runnable { /** * The time period in milliseconds that the run method will be executed by * the scheduler. */ public static final int CYCLE_RATE = 600; /** * The executor service which calls the run method, and ticks all of the * events. */ private static final ScheduledExecutorService scheduler = Executors .newSingleThreadScheduledExecutor(); /** * Events that will be cycled through every full tick (600ms). */ private static final ArrayList<Event> fullTickEvents = new ArrayList<>(); /** * Full tick events to be added next tick cycle (avoiding concurrent * modification errors). */ private static final ArrayDeque<Event> queuedFullTickEvents = new ArrayDeque<>(); /** * Creates a new EventManager, and starts ticking the events. */ public EventManager() { scheduler.scheduleAtFixedRate(this, 0, CYCLE_RATE, TimeUnit.MILLISECONDS); System.out.println("Started event manager."); } @Override public void run() { Event queuedEvent; while ((queuedEvent = queuedFullTickEvents.poll()) != null) { fullTickEvents.add(queuedEvent); } for (final Iterator<Event> fullTicks = fullTickEvents.iterator(); fullTicks.hasNext();) { final Event event = fullTicks.next(); try { if (!event.tick()) { fullTicks.remove(); } } catch (Exception e) { event.stop(); e.printStackTrace(); } } } /** * Schedules an event to be executed every full tick (600ms). * * @param event */ public static final void scheduleEvent(Event event) { queuedFullTickEvents.add(event); } }
/* * generated by Xtext 2.24.0 */ package org.example.entities.ide; import com.google.inject.Guice; import com.google.inject.Injector; import org.eclipse.xtext.util.Modules2; import org.example.entities.EntitiesRuntimeModule; import org.example.entities.EntitiesStandaloneSetup; /** * Initialization support for running Xtext languages as language servers. */ public class EntitiesIdeSetup extends EntitiesStandaloneSetup { @Override public Injector createInjector() { return Guice.createInjector(Modules2.mixin(new EntitiesRuntimeModule(), new EntitiesIdeModule())); } }
package com.logicbig.example; import org.springframework.context.i18n.SimpleTimeZoneAwareLocaleContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.LocaleContextResolver; import org.springframework.web.servlet.support.RequestContextUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.time.ZoneId; import java.time.ZoneOffset; import java.util.Locale; import java.util.TimeZone; @Controller public class TzExampleController { @RequestMapping("/") @ResponseBody public String testHandler (Locale clientLocale, ZoneId clientZoneId) { ZoneOffset serverZoneOffset = ZoneOffset.ofTotalSeconds( TimeZone.getDefault().getRawOffset() / 1000); return String.format("client timeZone: %s" + "<br/> " + "server timeZone: %s" + "<br/>" + " locale: %s%n", clientZoneId.normalized().getId(), serverZoneOffset.getId(), clientLocale); } @RequestMapping("/tzHandler") public String handle () { return "tzJsPage"; } @RequestMapping(value = "/tzValueHandler", method = RequestMethod.POST) public String handleTzValue ( Locale locale, HttpServletRequest req, HttpServletResponse res, @RequestParam("requestedUrl") String requestedUrl, @RequestParam("timeZoneOffset") int timeZoneOffset) { ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(-timeZoneOffset * 60); TimeZone timeZone = TimeZone.getTimeZone(zoneOffset); LocaleContextResolver localeResolver = (LocaleContextResolver) RequestContextUtils.getLocaleResolver(req); localeResolver.setLocaleContext(req, res, new SimpleTimeZoneAwareLocaleContext( locale, timeZone)); return "redirect:" + requestedUrl; } }
package com.gxtc.huchuan.ui.mine.personalhomepage.Deal; import com.gxtc.commlibrary.utils.ErrorCodeUtil; import com.gxtc.huchuan.bean.DealListBean; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.data.deal.DealRepository; import com.gxtc.huchuan.data.deal.DealSource; import com.gxtc.huchuan.http.ApiCallBack; import java.util.List; /** * 来自 伍玉南 的装逼小尾巴 on 17/11/3. */ public class PersonDealPresenter implements PersonDealContract.Presenter { private PersonDealContract.View mView; private DealSource mData; private int start = 0 ; private String userCode; private String token; public PersonDealPresenter(PersonDealContract.View view) { mView = view; mView.setPresenter(this); mData = new DealRepository(); } @Override public void getUserDealList(String token, String userCode) { this.userCode = userCode; this.token = token; mData.getUserDealList(token,userCode,start, new ApiCallBack<List<DealListBean>>() { @Override public void onSuccess(List<DealListBean> data) { if(data == null || data.size() == 0){ mView.showEmpty(); return; } mView.showData(data); } @Override public void onError(String errorCode, String message) { ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } @Override public void refreshData() { start = 0; mData.getUserDealList(token,userCode,start, new ApiCallBack<List<DealListBean>>() { @Override public void onSuccess(List<DealListBean> data) { if(data == null || data.size() == 0){ mView.showEmpty(); return; } mView.showRefreshData(data); } @Override public void onError(String errorCode, String message) { ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } @Override public void loadMoreData() { start += 15; String token = UserManager.getInstance().getToken(); mData.getUserDealList(token,userCode,start, new ApiCallBack<List<DealListBean>>() { @Override public void onSuccess(List<DealListBean> data) { if(data == null || data.size() == 0){ mView.showNoLoadMore(); return; } mView.showLoadMoreData(data); } @Override public void onError(String errorCode, String message) { ErrorCodeUtil.handleErr(mView,errorCode,message); } }); } @Override public void start() {} @Override public void destroy() { mData.destroy(); mView = null; } }
package com.hp.roam.config; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.AsyncConfigurer; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * @author ck * @date 2019年3月13日 下午4:48:50 */ @Configuration @EnableAsync public class TreadPoolConfig { @Bean public Executor getAsyncExecutor() { ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor(); //核心线程数 threadPoolExecutor.setCorePoolSize(500); // 最大线程数 线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 threadPoolExecutor.setMaxPoolSize(10100); // 队列最大长度 threadPoolExecutor.setQueueCapacity(1000); // 线程池维护线程所允许的空闲时间(单位秒) threadPoolExecutor.setKeepAliveSeconds(120); // 线程池对拒绝任务(无线程可用)的处理策略 ThreadPoolExecutor.CallerRunsPolicy策略 , //调用者的线程会执行该任务,如果执行器已关闭,则丢弃. threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy()); //用来设置线程池关闭的时候等待所有任务都完成再继续销毁其他Bean threadPoolExecutor.setWaitForTasksToCompleteOnShutdown(true); //用来设置线程池中任务的等待时间,超过时间强制销毁,以确保应用最后能够被关闭,而不是被阻塞住。 threadPoolExecutor.setAwaitTerminationSeconds(60); threadPoolExecutor.setThreadNamePrefix("testopenfire-"); threadPoolExecutor.initialize(); return threadPoolExecutor; } }
package com.bupsolutions.polaritydetection.model; public enum Polarity implements Label { POSITIVE(0, "Positive"), NEGATIVE(1, "Negative"); private int value; private String label; Polarity(int value, String label) { this.value = value; this.label = label; } public int asInt() { return value; } @Override public String toString() { return label; } public static Polarity valueOf(int value) { for (Polarity polarity : Polarity.values()) { if (polarity.asInt() == value) { return polarity; } } throw new IllegalArgumentException("Polarity not foud for value: " + value); } public Label[] labels() { return Polarity.values(); } }
import java.io.IOException; import java.util.Scanner; import financialdata.*; import handwritingrecognition.*; public class Terminal { private static final String helpText = "You can try the following commands: \n equity<GO> opens an applet to search for S&P 500 component stocks \n handwriting recognition<GO> launches the handwriting applet to verify neural network performance \n GUI<GO> launches the WIP GUI"; public static void main(String[] args){ System.out.println("Welcome to the neural network price stock prediction system. Type help<GO> for more information. Type exit<GO> to quit or exit current mode."); boolean run = true; while (run == true){ Scanner terminalInput = new Scanner(System.in); String input = terminalInput.nextLine(); if (input.equals("exit")) run = false; if (input.equals("help")) System.out.println(helpText); if (input.equals("equity")) { // String ticker; System.out.println(); System.out.println("You are now in equity mode.\n list stocks<GO> to see the list of tickers you can inquire about\n neural network<GO> brings up the stock price predictor \n exit<GO> will exit this mode."); terminalInput = new Scanner(System.in); input = terminalInput.nextLine(); Datafeed.loadStocks(); boolean runApplet = true; boolean fund = false; while (runApplet == true) { if (input.equals("exit")) runApplet = false; else if (input.equals("list stocks")) { System.out.println(Datafeed.getTickerList()); terminalInput = new Scanner(System.in); input = terminalInput.nextLine(); } else if (input.equals("neural network")) { System.out.println(); System.out.println("(WARNING: network make take multiple hours to run)"); System.out.println("The network has to be trained before predictions can be made."); System.out.println("Input network width"); terminalInput = new Scanner(System.in); int width = Integer.parseInt(terminalInput.nextLine()); System.out.println("Input network depth"); terminalInput = new Scanner(System.in); int depth = Integer.parseInt(terminalInput.nextLine()); System.out.println("Input number of iterations"); terminalInput = new Scanner(System.in); int iters = Integer.parseInt(terminalInput.nextLine()); System.out.println("Initializing network..."); DriverV2 network = new DriverV2(width,depth,iters); network.writeMasterData(); network.feedAll(); System.out.println("Training complete."); boolean runNetwork = true; while (runNetwork) { System.out.println("Ask the network which direction it thinks the price would move towards by providing it with a ticker. Else exit."); terminalInput = new Scanner(System.in); String askTicker = terminalInput.nextLine(); if (askTicker.equals("exit")) { runNetwork = false; terminalInput = new Scanner(System.in); input = terminalInput.nextLine(); } else System.out.println(network.giveRecommendation(askTicker)); } } else{ // Scanner tickerInput = new Scanner(System.in); // ticker = tickerInput.nextLine(); if (fund) { System.out.println(); System.out.println("Enter another ticker"); } if (!fund) { System.out.println(); System.out.println(Datafeed.nameFromTicker(input)); System.out.println(Datafeed.sectorFromTicker(input)); System.out.println("The newest price is $" + Datafeed.getNewestPrice(input)); System.out.println(); System.out.println("Type fundementals to get more information or enter another ticker"); } terminalInput = new Scanner(System.in); String input2 = terminalInput.nextLine(); if (input2.equals("exit")) runApplet = false; else if (input2.equals("fundementals")) { fund = true; System.out.println(); Datafeed.printFundementals(input); } else input = input2; } } } if (input.equals("handwriting recognition")) { String[] arguments = new String[1]; HandwritingNeuralNetwork.main(arguments); terminalInput = new Scanner(System.in); input = terminalInput.nextLine(); } if (input.equals("GUI")) { System.out.println("GUI is under construction."); GUI theGUI = new GUI(); } } // if(ticker.equals("train")){ // DriverV2 network = new DriverV2(60,1,100); // network.writeMasterData(); // System.out.println("got it"); // System.out.println(Datafeed.getNewestPrice(Datafeed.getTickerList().get(0))/1000); // System.out.println(network.createInputs(Datafeed.getTickerList().get(0)).length); // for (double i : network.createInputs(Datafeed.getTickerList().get(0))){ // System.out.println(i); // } // network.feedAll(); } }
package com.gaoshin.points.server.service; import com.gaoshin.points.server.bean.User; import com.gaoshin.points.server.bean.UserBalanceList; public interface UserService { User signup(User user); User login(User user); User getUserById(String userId); UserBalanceList listBalance(String userId); }
package de.mq; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import de.mq.phone.domain.person.support.JUnitSuiteDomain; import de.mq.phone.web.person.JUnitSuiteWeb; import de.mq.vaadin.util.JUnitSuiteUtil; @RunWith(Suite.class) @SuiteClasses({JUnitSuiteWeb.class, JUnitSuiteUtil.class, JUnitSuiteDomain.class}) public class AllTests { }
package de.cuuky.varo.listener.saveable; import org.bukkit.GameMode; import org.bukkit.block.Block; import org.bukkit.block.Chest; import org.bukkit.block.Furnace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerInteractEvent; import de.cuuky.varo.Main; import de.cuuky.varo.config.messages.ConfigMessages; import de.cuuky.varo.player.VaroPlayer; import de.cuuky.varo.player.stats.stat.inventory.VaroSaveable; import de.cuuky.varo.player.stats.stat.inventory.VaroSaveable.SaveableType; public class PlayerInteractListener implements Listener { @EventHandler public void onPlayerInteract(PlayerInteractEvent e) { if(!Main.getGame().isStarted()) return; if(!Main.getGame().isStarted() && e.getPlayer().getGameMode() != GameMode.CREATIVE) { e.setCancelled(true); return; } if(e.getAction() != Action.RIGHT_CLICK_BLOCK) return; Player player = e.getPlayer(); Block block = e.getClickedBlock(); if(!(block.getState() instanceof Chest) && !(block.getState() instanceof Furnace)) return; VaroPlayer varoPlayer = VaroPlayer.getPlayer(player); VaroSaveable saveable = VaroSaveable.getByLocation(block.getLocation()); if(saveable == null || saveable.canModify(varoPlayer) || saveable.holderDead()) return; if(!player.hasPermission("varo.ignoreSaveable")) { player.sendMessage(Main.getPrefix() + (saveable.getType() == SaveableType.CHEST ? ConfigMessages.NOT_TEAM_CHEST.getValue().replaceAll("%player%", saveable.getPlayer().getName()) : ConfigMessages.NOT_TEAM_FURNACE.getValue().replaceAll("%player%", saveable.getPlayer().getName()))); e.setCancelled(true); } else player.sendMessage(Main.getPrefix() + "§7Diese Kiste gehört " + Main.getColorCode() + saveable.getPlayer().getName() + "§7, doch durch deine Rechte konntest du sie trotzdem öffnen!"); } }
package org.example.opnesource; import lombok.extern.slf4j.Slf4j; import org.example.utility.UT; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @Slf4j public class SneakyThrowTest { public static void main(String[] args) throws IOException { System.out.println("[" + Thread.currentThread().getName() + "] pool start..."); // UT.schedule.poolPerSec(new RunnableTask(), 1, 1); UT.schedule.poolPerSec(new IoExceptionRunnableTask(), 1, 1); ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(new RunnableTask()); executorService.shutdown(); System.out.println("[" + Thread.currentThread().getName() + "] pool end..."); } } @Slf4j class RunnableTask implements Runnable { // @SneakyThrows @Override public void run() { throw new RuntimeException(); } } @Slf4j class IoExceptionRunnableTask implements Runnable { @Override public void run() { // TODO: 2020-10-26 Thread 내 IOException 을 던지려면? /** * 1. IOException 을 RuntimeException 으로 감싸서 던지는 방법, 일종의 꼼수 **/ try { throw new IOException("IOException Test"); } catch (IOException e) { throw new RuntimeException(e); } /** * **/ // throw new IOException("IOException Test"); } }